diff --git a/frontend/application/components/SearchResultsPage.tsx b/frontend/application/components/SearchResultsPage.tsx index 6461cfb7..652cfc53 100644 --- a/frontend/application/components/SearchResultsPage.tsx +++ b/frontend/application/components/SearchResultsPage.tsx @@ -26,7 +26,7 @@ import Link from "next/link"; import Image from "next/image"; import { useRouter } from 'next/navigation'; import api from "../lib/services/api"; -import { toPersian } from "../lib/utils"; +import { toPersian, normalizePersianText } from "../lib/utils"; type SearchTab = "all" | "products" | "blogs" | "wiki" | "videos"; @@ -72,79 +72,82 @@ export default function SearchResultsPage({ query }: { query: string }) { const [wikiItems, setWikiItems] = useState([]); const [videos, setVideos] = useState([]); const [isLoading, setIsLoading] = useState(true); + const [searchError, setSearchError] = useState(null); // Sync input when prop changes useEffect(() => { setSearchInput(query); }, [query]); - // Fetch all searchable datasets in parallel - useEffect(() => { - let isMounted = true; + const loadAll = async () => { setIsLoading(true); + setSearchError(null); + try { + const [prodRes, blogRes, wikiRes, videoRes] = await Promise.allSettled([ + productService.getProducts({ limit: 999 }), + api.get("/blogs?limit=50"), + api.get("/ingredients?limit=100"), + api.get("/videos?limit=50") + ]); - const loadAll = async () => { - try { - const [prodRes, blogRes, wikiRes, videoRes] = await Promise.allSettled([ - productService.getProducts({ limit: 999 }), - api.get("/blogs?limit=50"), - api.get("/ingredients?limit=100"), - api.get("/videos?limit=50") - ]); - - if (!isMounted) return; - - if (prodRes.status === "fulfilled" && prodRes.value?.data) { - setProducts(prodRes.value.data); - } else if (prodRes.status === "rejected") { - console.error("Error fetching products in SearchResultsPage:", prodRes.reason); - } - - if (blogRes.status === "fulfilled" && blogRes.value?.data) { - const list = Array.isArray(blogRes.value.data.data) - ? blogRes.value.data.data - : Array.isArray(blogRes.value.data) - ? blogRes.value.data - : []; - setBlogs(list); - } - - if (wikiRes.status === "fulfilled" && wikiRes.value?.data) { - const list = Array.isArray(wikiRes.value.data.data) - ? wikiRes.value.data.data - : Array.isArray(wikiRes.value.data) - ? wikiRes.value.data - : []; - setWikiItems(list); - } - - if (videoRes.status === "fulfilled" && videoRes.value?.data) { - const vList = videoRes.value.data.videos || videoRes.value.data.data || videoRes.value.data; - setVideos(Array.isArray(vList) ? vList : []); - } - } catch (err) { - console.error("Error loading search datasets:", err); - } finally { - if (isMounted) setIsLoading(false); + // If products or all datasets fail critically + if (prodRes.status === "rejected") { + setSearchError("خطا در برقراری ارتباط با سرور. لطفاً اتصال اینترنت خود را بررسی کنید."); + console.error("Critical failure fetching search datasets:", prodRes.reason); + return; } - }; + if (prodRes.status === "fulfilled" && prodRes.value?.data) { + setProducts(prodRes.value.data); + } + + if (blogRes.status === "fulfilled" && blogRes.value?.data) { + const list = Array.isArray(blogRes.value.data.data) + ? blogRes.value.data.data + : Array.isArray(blogRes.value.data) + ? blogRes.value.data + : []; + setBlogs(list); + } + + if (wikiRes.status === "fulfilled" && wikiRes.value?.data) { + const list = Array.isArray(wikiRes.value.data.data) + ? wikiRes.value.data.data + : Array.isArray(wikiRes.value.data) + ? wikiRes.value.data + : []; + setWikiItems(list); + } + + if (videoRes.status === "fulfilled" && videoRes.value?.data) { + const vList = videoRes.value.data.videos || videoRes.value.data.data || videoRes.value.data; + setVideos(Array.isArray(vList) ? vList : []); + } + } catch (err) { + console.error("Error loading search datasets:", err); + setSearchError("بارگذاری اطلاعات با مشکل مواجه شد."); + } finally { + setIsLoading(false); + } + }; + + useEffect(() => { loadAll(); - return () => { isMounted = false; }; }, []); const cleanQuery = (query || "").trim().toLowerCase(); + const normalizedQuery = normalizePersianText(query || ""); // 1. Filtered Products const filteredProducts = useMemo(() => { if (!cleanQuery) return products; return products.filter(p => - (p.name || '').toLowerCase().includes(cleanQuery) || - (p.description || '').toLowerCase().includes(cleanQuery) || - (Array.isArray(p.main_ingredients) && p.main_ingredients.some(ing => ing.toLowerCase().includes(cleanQuery))) || - (Array.isArray(p.symptoms) && p.symptoms.some(sym => sym.toLowerCase().includes(cleanQuery))) || - (p.nameFa || '').toLowerCase().includes(cleanQuery) || - (p.nameEn || '').toLowerCase().includes(cleanQuery) + normalizePersianText(p.name || '').includes(normalizedQuery) || + normalizePersianText(p.description || '').includes(normalizedQuery) || + (Array.isArray(p.main_ingredients) && p.main_ingredients.some(ing => normalizePersianText(ing || '').includes(normalizedQuery))) || + (Array.isArray(p.symptoms) && p.symptoms.some(sym => normalizePersianText(sym || '').includes(normalizedQuery))) || + normalizePersianText(p.nameFa || '').includes(normalizedQuery) || + normalizePersianText(p.nameEn || '').includes(normalizedQuery) ); }, [products, cleanQuery]); @@ -152,8 +155,8 @@ export default function SearchResultsPage({ query }: { query: string }) { const filteredBlogs = useMemo(() => { if (!cleanQuery) return blogs; return blogs.filter(b => - (b.title || '').toLowerCase().includes(cleanQuery) || - (b.excerpt || '').toLowerCase().includes(cleanQuery) + normalizePersianText(b.title || '').includes(normalizedQuery) || + normalizePersianText(b.excerpt || '').includes(normalizedQuery) ); }, [blogs, cleanQuery]); @@ -161,10 +164,10 @@ export default function SearchResultsPage({ query }: { query: string }) { const filteredWiki = useMemo(() => { if (!cleanQuery) return wikiItems; return wikiItems.filter(w => - (w.name || '').toLowerCase().includes(cleanQuery) || - (w.nameFa || '').toLowerCase().includes(cleanQuery) || - (w.scientificName || '').toLowerCase().includes(cleanQuery) || - (w.description || '').toLowerCase().includes(cleanQuery) + normalizePersianText(w.name || '').includes(normalizedQuery) || + normalizePersianText(w.nameFa || '').includes(normalizedQuery) || + normalizePersianText(w.scientificName || '').includes(normalizedQuery) || + normalizePersianText(w.description || '').includes(normalizedQuery) ); }, [wikiItems, cleanQuery]); @@ -172,9 +175,9 @@ export default function SearchResultsPage({ query }: { query: string }) { const filteredVideos = useMemo(() => { if (!cleanQuery) return videos; return videos.filter(v => - (v.title || '').toLowerCase().includes(cleanQuery) || - (v.doctor || '').toLowerCase().includes(cleanQuery) || - (v.description || '').toLowerCase().includes(cleanQuery) + normalizePersianText(v.title || '').includes(normalizedQuery) || + normalizePersianText(v.doctor || '').includes(normalizedQuery) || + normalizePersianText(v.description || '').includes(normalizedQuery) ); }, [videos, cleanQuery]); @@ -296,9 +299,28 @@ export default function SearchResultsPage({ query }: { query: string }) { + ) : searchError ? ( +
+
+ +
+

خطا در بارگذاری نتایج جستجو

+

{searchError}

+ +
) : cleanQuery && totalResults === 0 ? ( /* Empty State - Mobile-Optimized with direct suggestion cards */ -
+
diff --git a/frontend/application/components/__tests__/SearchResultsPage.test.tsx b/frontend/application/components/__tests__/SearchResultsPage.test.tsx index ba1c3254..e98ad87c 100644 --- a/frontend/application/components/__tests__/SearchResultsPage.test.tsx +++ b/frontend/application/components/__tests__/SearchResultsPage.test.tsx @@ -70,4 +70,29 @@ describe('SearchResultsPage',()=>{ 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();}); it('shows recommendation, species mismatch and neutral compatibility',async()=>{pet.active={type:'سگ',name:'Rex',medicalConditions:['pain']};render();await screen.findByText('Joint Alpha');expect(screen.getByText('توصیه شده برای Rex')).toBeInTheDocument();expect(screen.getByText('مخصوص گربه')).toBeInTheDocument();expect(screen.getAllByText('مناسب برای Rex')).toHaveLength(2);}); + + it('matches Persian queries with arabic letters, half-space, and different diacritics via normalization', async () => { + render(); + expect(await screen.findByRole('link', { name: /ماده مراقبت/ })).toBeInTheDocument(); + }); + + it('displays error state and recovers upon clicking retry', async () => { + vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error('Network error')); + vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error')); + + render(); + + const alertBox = await screen.findByRole('alert'); + expect(alertBox).toHaveTextContent('خطا در بارگذاری نتایج جستجو'); + + vi.mocked(productService.getProducts).mockResolvedValueOnce({ data: products } as any); + vi.mocked(api.get).mockResolvedValueOnce({ data: { data: [] } } as any); + + const retryBtn = screen.getByTestId('search-retry-button'); + fireEvent.click(retryBtn); + + await waitFor(() => { + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + }); }); diff --git a/frontend/application/lib/utils.ts b/frontend/application/lib/utils.ts index 5c6b95a7..86fd667a 100644 --- a/frontend/application/lib/utils.ts +++ b/frontend/application/lib/utils.ts @@ -25,3 +25,23 @@ export function isProductOutOfStock(product?: { if (product.packageSize !== undefined && product.packageSize !== null && Number(product.packageSize) <= 0) return true; return false; } + +export function normalizePersianText(input: string | undefined | null): string { + if (!input) return ""; + return input + .toString() + .toLowerCase() + .replace(/[\u200B-\u200D\uFEFF]/g, "") + .replace(/[\u200C]/g, " ") + .replace(/[يیى]/g, "ی") + .replace(/[ك]/g, "ک") + .replace(/[ة]/g, "ه") + .replace(/[أإآ]/g, "ا") + .replace(/[ؤ]/g, "و") + .replace(/[ء]/g, "") + .replace(/[\u064B-\u065F]/g, "") + .replace(/[۰-۹]/g, d => "0123456789"["۰۱۲۳۴۵۶۷۸۹".indexOf(d)]) + .replace(/[٠-٩]/g, d => "0123456789"["٠١٢٣٤٥٦٧٨٩".indexOf(d)]) + .replace(/\s+/g, " ") + .trim(); +}