From 570f0acc6616aebeb7e6c647c6079802c38d31d6 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 12:33:00 +0000 Subject: [PATCH] feat(search): add segmented universal results --- .../components/MobileBottomNav.tsx | 2 +- .../components/SearchResultsPage.tsx | 23 +++++++++-- .../__tests__/MobileBottomNav.test.tsx | 14 +++++++ .../__tests__/SearchResultsPage.test.tsx | 38 ++++++++++++++++++- 4 files changed, 72 insertions(+), 5 deletions(-) diff --git a/frontend/application/components/MobileBottomNav.tsx b/frontend/application/components/MobileBottomNav.tsx index 20b1f54d..2025d21c 100644 --- a/frontend/application/components/MobileBottomNav.tsx +++ b/frontend/application/components/MobileBottomNav.tsx @@ -168,7 +168,7 @@ export default function MobileBottomNav({ if (searchQuery.trim()) { const q = searchQuery.trim(); closeSheet(false); - router.push(`/shop?search=${encodeURIComponent(q)}`); + router.push(`/search?q=${encodeURIComponent(q)}`); } else { closeSheet(false); router.push("/shop"); diff --git a/frontend/application/components/SearchResultsPage.tsx b/frontend/application/components/SearchResultsPage.tsx index 6d56a762..a9b4a7d2 100644 --- a/frontend/application/components/SearchResultsPage.tsx +++ b/frontend/application/components/SearchResultsPage.tsx @@ -249,7 +249,11 @@ export default function SearchResultsPage({ query }: { query: string }) { {/* Multi-Content Filter Tabs */} -
+
{[ { id: "all", label: "همه نتایج", count: totalResults, icon: }, { id: "products", label: "محصولات و داروها", count: filteredProducts.length, icon: }, @@ -260,6 +264,10 @@ export default function SearchResultsPage({ query }: { query: string }) {
{/* RESULTS AREA */} - {cleanQuery && totalResults === 0 && !isLoading ? ( + {isLoading ? ( +
+ + ) : cleanQuery && totalResults === 0 ? ( /* Empty State - Mobile-Optimized with direct suggestion cards */
@@ -497,7 +514,7 @@ export default function SearchResultsPage({ query }: { query: string }) { {(activeTab === "all" ? filteredWiki.slice(0, 4) : filteredWiki).map((wiki) => (
diff --git a/frontend/application/components/__tests__/MobileBottomNav.test.tsx b/frontend/application/components/__tests__/MobileBottomNav.test.tsx index d6c5d63f..06614204 100644 --- a/frontend/application/components/__tests__/MobileBottomNav.test.tsx +++ b/frontend/application/components/__tests__/MobileBottomNav.test.tsx @@ -8,6 +8,7 @@ import { useUserStore } from '../../lib/store/userStore'; import { useUIStore } from '../../lib/store/uiStore'; import { useSettingsStore } from '../../lib/store/settingsStore'; import { useCatalogMode } from '../../lib/useCatalogMode'; +import { productService } from '../../lib/services/productService'; vi.mock('next/navigation', () => ({ usePathname: vi.fn(), @@ -34,6 +35,10 @@ vi.mock('../../lib/useCatalogMode', () => ({ useCatalogMode: vi.fn(), })); +vi.mock('../../lib/services/productService', () => ({ + productService: { getProducts: vi.fn() }, +})); + describe('MobileBottomNav Component', () => { const mockRouterPush = vi.fn(); const mockSetAuthModalOpen = vi.fn(); @@ -80,6 +85,7 @@ describe('MobileBottomNav Component', () => { isCatalogOnly: false, allowCart: true, } as any); + vi.mocked(productService.getProducts).mockResolvedValue({ data: [] } as any); }); it('renders all default 5 navigation tabs', () => { @@ -182,6 +188,14 @@ describe('MobileBottomNav Component', () => { expect(screen.getByText('مشاهده کاتالوگ و همه محصولات')).toBeInTheDocument(); }); + it('routes mobile search submissions to universal search', () => { + render(); + fireEvent.click(screen.getByText('فروشگاه').closest('button')!); + fireEvent.change(screen.getByPlaceholderText(/جستجوی دارو، ترکیب یا علامت بالینی/i), { target: { value: 'joint care' } }); + fireEvent.submit(screen.getByPlaceholderText(/جستجوی دارو، ترکیب یا علامت بالینی/i).closest('form')!); + expect(mockRouterPush).toHaveBeenCalledWith('/search?q=joint%20care'); + }); + it('opens menu bottom sheet when menu tab is clicked', () => { render(); diff --git a/frontend/application/components/__tests__/SearchResultsPage.test.tsx b/frontend/application/components/__tests__/SearchResultsPage.test.tsx index 4f2d292f..6b04c07d 100644 --- a/frontend/application/components/__tests__/SearchResultsPage.test.tsx +++ b/frontend/application/components/__tests__/SearchResultsPage.test.tsx @@ -16,7 +16,9 @@ import { toast } from 'sonner'; afterEach(cleanup); import SearchResultsPage from '../SearchResultsPage'; import { productService } from '../../lib/services/productService'; +import api from '../../lib/services/api'; vi.mock('../../lib/services/productService',()=>({productService:{getProducts:vi.fn()}})); +vi.mock('../../lib/services/api',()=>({default:{get:vi.fn()}})); const pet=vi.hoisted(()=>({active:null as any})); vi.mock('../../lib/store/usePetStore',()=>({usePetStore:()=>({getActivePet:()=>pet.active})})); const products=[ @@ -24,8 +26,42 @@ const products=[ {id:'b',name:'Coat Beta',description:'Shiny fur',main_ingredients:['Biotin'],symptoms:['itch'],suitableFor:'گربه',image:'/b.png',price:'200',category:'skin',benefits:'coat'}, {id:'c',name:'Both Gamma',description:'Daily care',main_ingredients:[],symptoms:[],suitableFor:'هر دو',image:'/c.png',price:'300',category:'care',benefits:'health'}, {id:'d',name:'Fourth',description:'Daily',main_ingredients:[],symptoms:[],suitableFor:'سگ',image:'/d.png',price:'400',category:'care',benefits:'health'}]; -beforeEach(()=>{vi.clearAllMocks();pet.active=null;vi.mocked(productService.getProducts).mockResolvedValue({data:products} as any);}); +beforeEach(()=>{ + vi.clearAllMocks();pet.active=null; + vi.mocked(productService.getProducts).mockResolvedValue({data:products} as any); + vi.mocked(api.get).mockImplementation(async (url: string) => { + if (url.startsWith('/blogs')) return {data:{data:[{id:'blog-1',slug:'care-guide',title:'Care article',excerpt:'Daily care'}]}} as any; + if (url.startsWith('/ingredients')) return {data:[{id:'wiki-1',slug:'care',nameFa:'ماده مراقبت',description:'Daily care'}]} as any; + if (url.startsWith('/videos')) return {data:{videos:[{id:'video-1',title:'Care video',description:'Daily care'}]}} as any; + throw new Error(`Unexpected URL: ${url}`); + }); +}); describe('SearchResultsPage',()=>{ + it('announces loading before all search datasets settle',()=>{ + vi.mocked(productService.getProducts).mockReturnValue(new Promise(()=>{}) as any); + vi.mocked(api.get).mockReturnValue(new Promise(()=>{}) as any); + render(); + expect(screen.getByRole('status')).toHaveTextContent('در حال جستجو'); + }); + it('exposes accessible segmented tabs with live counts and filters each content type',async()=>{ + render(); + const allTab=await screen.findByRole('tab',{name:/همه نتایج.*۴/}); + const productTab=screen.getByRole('tab',{name:/محصولات و داروها.*۱/}); + const blogTab=screen.getByRole('tab',{name:/مقالات وبلاگ.*۱/}); + const wikiTab=screen.getByRole('tab',{name:/دانشنامه ترکیبات.*۱/}); + const videoTab=screen.getByRole('tab',{name:/ویدیوهای بالینی.*۱/}); + expect(allTab).toHaveAttribute('aria-selected','true'); + fireEvent.click(blogTab); + expect(blogTab).toHaveAttribute('aria-selected','true'); + expect(screen.getByRole('link',{name:/Care article/})).toBeInTheDocument(); + expect(screen.queryByRole('link',{name:/Both Gamma/})).not.toBeInTheDocument(); + fireEvent.click(wikiTab); + expect(screen.getByRole('link',{name:/ماده مراقبت/})).toBeInTheDocument(); + fireEvent.click(videoTab); + expect(screen.getByRole('link',{name:/Care video/})).toBeInTheDocument(); + fireEvent.click(productTab); + expect(screen.getByRole('link',{name:/Both Gamma/})).toBeInTheDocument(); + }); it.each(['JOINT','mobility','glucosamine','pain'])('searches field %s',async query=>{render();expect(await screen.findByRole('link',{name:/Joint Alpha/})).toHaveAttribute('href','/shop/alpha');expect(screen.getAllByRole('link')).toHaveLength(1);expect(productService.getProducts).toHaveBeenCalledWith({limit:999});}); it('recomputes query without fetching and limits fallback suggestions',async()=>{const view=render();await screen.findByText('Joint Alpha');view.rerender();expect(screen.getByText('نتیجه‌ای یافت نشد')).toBeInTheDocument();expect(screen.getAllByRole('link')).toHaveLength(3);expect(screen.queryByText('Fourth')).not.toBeInTheDocument();expect(productService.getProducts).toHaveBeenCalledTimes(1);fireEvent.click(screen.getByRole('button',{name:'بازگشت'}));expect(h.back).toHaveBeenCalled();}); it('handles service failure',async()=>{const err=vi.spyOn(console,'error').mockImplementation(()=>{});vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error('offline'));render();await waitFor(()=>expect(err).toHaveBeenCalled());expect(screen.queryAllByRole('link')).toHaveLength(0);err.mockRestore();});