From bec76393bb3309335c77b2df5834c281ca4f65e8 Mon Sep 17 00:00:00 2001 From: devops Date: Fri, 16 Oct 2026 19:48:37 +0000 Subject: [PATCH 01/49] fix(shop): render products from server data --- frontend/application/app/shop/page.tsx | 4 ++++ frontend/application/components/ArchivePage.tsx | 17 +++++++++++++---- .../components/__tests__/ArchivePage.test.tsx | 8 ++++++++ 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/frontend/application/app/shop/page.tsx b/frontend/application/app/shop/page.tsx index 9d7b1264..ac11b984 100644 --- a/frontend/application/app/shop/page.tsx +++ b/frontend/application/app/shop/page.tsx @@ -1,6 +1,8 @@ import type { Metadata } from "next"; import ArchivePage from "../../components/ArchivePage"; import { getPageMetadata } from "../../lib/seo"; +import { productService } from "../../lib/services/productService"; +import type { PetType } from "../../lib/data/products"; export async function generateMetadata({ searchParams, @@ -41,6 +43,7 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [ const symptomsParam = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : ""; const symptomSingle = typeof resolvedParams.symptom === 'string' ? resolvedParams.symptom : ""; const symptoms = symptomsParam || (symptomSingle ? symptomSingle : ""); + const { data: initialProducts } = await productService.getProducts({ category, petType: petType as PetType | "all", query: search, symptom: symptomSingle, limit: 999 }); return ( ); } diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index 374af28e..92a4ba77 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -449,12 +449,14 @@ export default function ArchivePage({ initialCategory = "all", initialSearch = "", initialPetType = "all", - initialSymptoms = "" + initialSymptoms = "", + initialProducts = [] }: { initialCategory?: string, initialSearch?: string, initialPetType?: string, - initialSymptoms?: string + initialSymptoms?: string, + initialProducts?: Product[] }) { const router = useRouter(); const getText = useSettingsStore(state => state.getText); @@ -463,7 +465,7 @@ export default function ArchivePage({ const [activeSymptoms, setActiveSymptoms] = useState(initialSymptoms ? initialSymptoms.split(',') : []); const [searchQuery, setSearchQuery] = useState(initialSearch); const [isUpdating, setIsUpdating] = useState(false); - const [filteredProducts, setFilteredProducts] = useState([]); + const [filteredProducts, setFilteredProducts] = useState(() => orderProductsByAvailability(initialProducts)); const [sortBy, setSortBy] = useState("createdAt"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [viewMode, setViewMode] = useState<"list" | "grid">("list"); @@ -560,6 +562,9 @@ export default function ArchivePage({ } }, [selectedCategory, selectedPet, searchQuery, activeSymptoms, router]); + const hasInitialProducts = Boolean(initialProducts && initialProducts.length > 0); + const didSkipInitialFetch = React.useRef(false); + const fetchProducts = useCallback(async () => { setIsUpdating(true); try { @@ -588,8 +593,12 @@ export default function ArchivePage({ }, [selectedCategory, selectedPet, searchQuery, sortBy, sortOrder, activeSymptoms]); useEffect(() => { + if (hasInitialProducts && !didSkipInitialFetch.current) { + didSkipInitialFetch.current = true; + return; + } Promise.resolve().then(() => fetchProducts()); - }, [fetchProducts]); + }, [fetchProducts, hasInitialProducts]); const toggleSymptom = (s: string) => { setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]); diff --git a/frontend/application/components/__tests__/ArchivePage.test.tsx b/frontend/application/components/__tests__/ArchivePage.test.tsx index bd3e2da2..41755351 100644 --- a/frontend/application/components/__tests__/ArchivePage.test.tsx +++ b/frontend/application/components/__tests__/ArchivePage.test.tsx @@ -144,6 +144,14 @@ const mockProducts = [ }); describe("ArchivePage Component", () => { + it("renders server-provided initial products without waiting for a client fetch", () => { + render(); + + expect(screen.getAllByText("گلوکوزامین مفاصل").length).toBeGreaterThan(0); + expect(productService.getProducts).not.toHaveBeenCalled(); + }); + + beforeEach(() => { vi.clearAllMocks(); From 9a9ab149ede62e5bd045308fa842002c24a973e1 Mon Sep 17 00:00:00 2001 From: devops Date: Fri, 16 Oct 2026 20:22:41 +0000 Subject: [PATCH 02/49] feat(ux): restore login and cart routes --- docs/audit/UX-MODERNIZATION-TASK-REGISTER.md | 44 ++++++++++++++++++++ frontend/application/app/cart/page.test.tsx | 23 ++++++++++ frontend/application/app/cart/page.tsx | 18 ++++++++ frontend/application/app/login/page.test.tsx | 16 +++++++ frontend/application/app/login/page.tsx | 13 ++++++ 5 files changed, 114 insertions(+) create mode 100644 docs/audit/UX-MODERNIZATION-TASK-REGISTER.md create mode 100644 frontend/application/app/cart/page.test.tsx create mode 100644 frontend/application/app/cart/page.tsx create mode 100644 frontend/application/app/login/page.test.tsx create mode 100644 frontend/application/app/login/page.tsx diff --git a/docs/audit/UX-MODERNIZATION-TASK-REGISTER.md b/docs/audit/UX-MODERNIZATION-TASK-REGISTER.md new file mode 100644 index 00000000..529e0931 --- /dev/null +++ b/docs/audit/UX-MODERNIZATION-TASK-REGISTER.md @@ -0,0 +1,44 @@ +# Canina UX Modernization — Task Register + +Source: live Chromium audits, source audit at `bec76393b`, and QA/SEO/content reviews. +Status model: TODO -> IN_PROGRESS -> TEST -> DONE. Estimates are engineering hours, not elapsed calendar time. + +| ID | Owner departments | Pri | Estimate | Dependencies | Acceptance summary | Status | +|---|---|---:|---:|---|---|---| +| UX-PMO-001 | PMO | P0 | 4h | audits | Register, owners, dependencies, release gates and evidence contract are versioned | DONE | +| UX-DEV-001 | Dev + QA | P0 | 12h | none | `/login` and `/cart` are real routes, no 404, mobile/desktop smoke tests pass | IN_PROGRESS | +| UX-CAT-001 | Dev + UX + QA | P0 | 24h | UX-DEV-001 | Shop has deterministic SSR/client data states: success/loading/empty/error/retry | TODO | +| UX-CAT-002 | Dev + Product + QA | P0 | 24h | UX-CAT-001 | Catalog uses typed pagination/query URL state; no limit-999 hydration | TODO | +| UX-DATA-001 | Dev + DevOps | P0 | 20h | UX-CAT-001 | API errors are typed/actionable; cache tags and invalidation are verified | TODO | +| UX-A11Y-001 | UX + Dev + QA | P0 | 16h | UX-DEV-001 | Forms/buttons/overlays have names, labels, focus return and keyboard operation | TODO | +| UX-RESP-001 | UX + Dev + QA | P1 | 20h | UX-CAT-001 | 360/390/768/1024/1440 layouts have no unintended overflow and 44px targets | TODO | +| UX-PDP-001 | Product + UX + Dev + QA | P1 | 20h | UX-CAT-001 | PDP has one H1 and above-fold image/name/price/stock/CTA at all viewports | TODO | +| UX-CHECKOUT-001 | Payments + Dev + QA | P1 | 20h | UX-A11Y-001 | Checkout fields have labels/autocomplete/inputmode and announced errors | TODO | +| UX-NAV-001 | UX + Product + Dev | P1 | 16h | UX-RESP-001 | Mobile/desktop navigation is canonical, active state and cart state are consistent | TODO | +| UX-SEARCH-001 | Product + UX + SEO + Dev | P1 | 16h | UX-CAT-002 | Search landmark, Persian normalization, result count and actionable no-results state | TODO | +| UX-CONTENT-001 | Content + UX | P1 | 12h | UX-NAV-001 | Persian CTA/glossary unified across shop, wiki, auth, cart and footer | TODO | +| UX-CONTACT-001 | Support + Dev + Product | P1 | 4h | settings readback | No empty `tel:`/`mailto:` targets; official values verified live | TODO | +| UX-SEO-001 | SEO + Dev + QA | P1 | 16h | UX-CAT-002 | Category URLs, canonical/H1/meta and sitemap parity are tested | TODO | +| UX-SEO-002 | SEO + Dev + Content | P1 | 12h | UX-SEO-001 | Product 404 is real 404; Product/Offer/Breadcrumb JSON-LD matches facts | TODO | +| UX-MEDIA-001 | Content + SEO + Dev | P2 | 12h | UX-PDP-001 | Product/blog/feed images are valid, same-item, HTTPS and have useful alt text | TODO | +| UX-PERF-001 | Dev + DevOps + QA | P0 | 24h | UX-CAT-002, UX-RESP-001 | Mobile LCP/CLS/INP budgets, reduced-motion and image dimensions are verified | TODO | +| UX-ARCH-001 | Dev + UX | P1 | 24h | UX-CAT-001 | ArchivePage/global shell split into typed, independently testable feature modules | TODO | +| UX-STATE-001 | Dev + Commerce + QA | P0 | 24h | UX-DATA-001 | Cart price/stock/order state is backend-authoritative and persisted safely | TODO | +| UX-TEST-001 | Dev + QA | P0 | 16h | UX-DEV-001 | npm test/typecheck/lint scripts and coverage gates execute in clean checkout | TODO | +| UX-E2E-001 | QA + DevOps | P1 | 20h | UX-TEST-001, UX-RESP-001 | Chromium desktop/mobile smoke covers shop/PDP/cart/login/checkout/errors | TODO | +| UX-CI-001 | DevOps + Dev + QA | P0 | 20h | UX-TEST-001, UX-E2E-001 | CI gates lint/type/unit/build/E2E/perf and publishes evidence | TODO | +| UX-DEPLOY-001 | DevOps + QA | P1 | 24h | UX-CI-001 | Immutable SHA deployment, health checks, smoke gate and rollback are documented/tested | TODO | +| UX-CLAIMS-001 | R&D + Content + Compliance + human vet review | P1 | 32h | legal/vet access | 35 product/media medical claims have evidence/status and no unsupported claims publish | BLOCKED_EXTERNAL_REVIEW | +| UX-VERIFY-001 | PMO + QA + Analytics | P2 | 16h | all release tasks | Live release checklist, CWV/error/catalog/checkout telemetry and go/no-go evidence | TODO | + +**Current program estimate:** 396 engineering/review hours; critical path is lower with parallel teams. External legal/human-veterinarian review, recruited user panel, GSC/GA4 access and payment sandbox are explicit blockers where applicable. + +## Immediate execution order + +1. UX-DEV-001 — restore login/cart routes (current) +2. UX-TEST-001 — make frontend test/typecheck gates executable +3. UX-A11Y-001 + UX-RESP-001 — fix shared interaction and responsive foundations +4. UX-CAT-001/002 + UX-DATA-001 — reliable catalog flow +5. UX-PDP-001 + UX-CHECKOUT-001 + UX-STATE-001 — conversion journey +6. SEO/content/media/performance/CI/deployment gates +7. Live verification and release decision diff --git a/frontend/application/app/cart/page.test.tsx b/frontend/application/app/cart/page.test.tsx new file mode 100644 index 00000000..ac129ae2 --- /dev/null +++ b/frontend/application/app/cart/page.test.tsx @@ -0,0 +1,23 @@ +import React from "react"; +import { describe, expect, it, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; +import CartPage from "./page"; + +vi.mock("../../components/CartDrawer", () => ({ + default: ({ isOpen, onCheckout, onShopNavigate }: { isOpen: boolean; onCheckout: () => void; onShopNavigate: () => void }) => isOpen ? ( +
+ + +
+ ) : null, +})); +vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); + +describe("/cart route", () => { + it("renders the cart experience and provides journey actions", () => { + render(); + expect(screen.getByRole("region", { name: "سبد خرید" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "تکمیل سفارش" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "مشاهده محصولات" })).toBeInTheDocument(); + }); +}); diff --git a/frontend/application/app/cart/page.tsx b/frontend/application/app/cart/page.tsx new file mode 100644 index 00000000..493fc230 --- /dev/null +++ b/frontend/application/app/cart/page.tsx @@ -0,0 +1,18 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import CartDrawer from "../../components/CartDrawer"; + +export default function CartPage() { + const router = useRouter(); + return ( +
+ router.push("/")} + onCheckout={() => router.push("/checkout")} + onShopNavigate={() => router.push("/shop")} + /> +
+ ); +} diff --git a/frontend/application/app/login/page.test.tsx b/frontend/application/app/login/page.test.tsx new file mode 100644 index 00000000..6a024d35 --- /dev/null +++ b/frontend/application/app/login/page.test.tsx @@ -0,0 +1,16 @@ +import React from "react"; +import { describe, expect, it, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; +import LoginPage from "./page"; + +vi.mock("../../components/AuthModal", () => ({ + default: ({ isOpen }: { isOpen: boolean }) => isOpen ?
ورود به حساب
: null, +})); +vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); + +describe("/login route", () => { + it("renders the authentication experience instead of a missing-page route", () => { + render(); + expect(screen.getByRole("dialog")).toBeInTheDocument(); + }); +}); diff --git a/frontend/application/app/login/page.tsx b/frontend/application/app/login/page.tsx new file mode 100644 index 00000000..6c08a58d --- /dev/null +++ b/frontend/application/app/login/page.tsx @@ -0,0 +1,13 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import AuthModal from "../../components/AuthModal"; + +export default function LoginPage() { + const router = useRouter(); + return ( +
+ router.push("/")} /> +
+ ); +} From 5380bb66bb76a435d7535c5592ea00a5afed3027 Mon Sep 17 00:00:00 2001 From: devops Date: Fri, 16 Oct 2026 20:31:32 +0000 Subject: [PATCH 03/49] test(ux): add frontend quality gates --- frontend/application/app/cart/page.test.tsx | 6 +++--- frontend/application/app/login/page.test.tsx | 2 +- frontend/application/package.json | 6 +++++- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/frontend/application/app/cart/page.test.tsx b/frontend/application/app/cart/page.test.tsx index ac129ae2..ee6de826 100644 --- a/frontend/application/app/cart/page.test.tsx +++ b/frontend/application/app/cart/page.test.tsx @@ -16,8 +16,8 @@ vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); describe("/cart route", () => { it("renders the cart experience and provides journey actions", () => { render(); - expect(screen.getByRole("region", { name: "سبد خرید" })).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "تکمیل سفارش" })).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "مشاهده محصولات" })).toBeInTheDocument(); + expect(screen.getByRole("region", { name: "سبد خرید" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "تکمیل سفارش" })).toBeTruthy(); + expect(screen.getByRole("button", { name: "مشاهده محصولات" })).toBeTruthy(); }); }); diff --git a/frontend/application/app/login/page.test.tsx b/frontend/application/app/login/page.test.tsx index 6a024d35..bb743a48 100644 --- a/frontend/application/app/login/page.test.tsx +++ b/frontend/application/app/login/page.test.tsx @@ -11,6 +11,6 @@ vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); describe("/login route", () => { it("renders the authentication experience instead of a missing-page route", () => { render(); - expect(screen.getByRole("dialog")).toBeInTheDocument(); + expect(screen.getByRole("dialog")).toBeTruthy(); }); }); diff --git a/frontend/application/package.json b/frontend/application/package.json index 0bd79619..6ab6053e 100644 --- a/frontend/application/package.json +++ b/frontend/application/package.json @@ -6,7 +6,11 @@ "dev": "next dev -p 3300", "build": "next build", "start": "next start", - "lint": "eslint" + "lint": "eslint", + "test": "vitest run --maxWorkers=2", + "test:watch": "vitest", + "test:coverage": "vitest run --coverage --maxWorkers=2", + "typecheck": "tsc --noEmit" }, "dependencies": { "@types/dompurify": "^3.0.5", From 4393de5d8fb3bc42af045308d14d274adcd605ee Mon Sep 17 00:00:00 2001 From: devops Date: Fri, 16 Oct 2026 20:35:53 +0000 Subject: [PATCH 04/49] fix(a11y): label global search controls --- frontend/application/components/Header.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/application/components/Header.tsx b/frontend/application/components/Header.tsx index d54a2f65..f7701c0a 100644 --- a/frontend/application/components/Header.tsx +++ b/frontend/application/components/Header.tsx @@ -230,6 +230,8 @@ export default function Header({
setSearchQuery(e.target.value)} @@ -537,6 +539,8 @@ export default function Header({ setSearchQuery(e.target.value)} From 1aad48193002c1223290e024de818075f6609546 Mon Sep 17 00:00:00 2001 From: devops Date: Fri, 16 Oct 2026 20:41:53 +0000 Subject: [PATCH 05/49] fix(a11y): label catalog search controls --- frontend/application/components/ArchivePage.tsx | 4 ++++ .../application/components/__tests__/ArchivePage.test.tsx | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index 92a4ba77..80201001 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -705,6 +705,7 @@ export default function ArchivePage({
setSymptomSearch(e.target.value)} @@ -786,6 +787,7 @@ export default function ArchivePage({ setSearchQuery(e.target.value)} @@ -815,6 +817,7 @@ export default function ArchivePage({ setSearchQuery(e.target.value)} @@ -1003,6 +1006,7 @@ export default function ArchivePage({ setSymptomSearch(e.target.value)} diff --git a/frontend/application/components/__tests__/ArchivePage.test.tsx b/frontend/application/components/__tests__/ArchivePage.test.tsx index 41755351..4e4023af 100644 --- a/frontend/application/components/__tests__/ArchivePage.test.tsx +++ b/frontend/application/components/__tests__/ArchivePage.test.tsx @@ -151,6 +151,13 @@ describe("ArchivePage Component", () => { expect(productService.getProducts).not.toHaveBeenCalled(); }); + it("gives catalog search controls accessible names", () => { + render(); + + expect(screen.getAllByLabelText("جستجوی محصول").length).toBe(2); + expect(screen.getAllByLabelText("جستجوی علائم").length).toBeGreaterThan(0); + }); + beforeEach(() => { vi.clearAllMocks(); From 6dbee69601145e10bb05ec35a747e8f3dbfc6daf Mon Sep 17 00:00:00 2001 From: devops Date: Fri, 16 Oct 2026 20:47:00 +0000 Subject: [PATCH 06/49] fix(a11y): label catalog sort control --- frontend/application/components/ArchivePage.tsx | 1 + .../application/components/__tests__/ArchivePage.test.tsx | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index 80201001..93228b52 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -766,6 +766,7 @@ export default function ArchivePage({
مرتب‌سازی: + + +
@@ -73,12 +107,12 @@ export default function SearchResultsPage({ query }: { query: string }) { className="bg-white rounded-[2.5rem] p-8 border border-medical-gray-200 group hover:shadow-2xl hover:shadow-canina-blue/10 transition-all flex flex-col relative h-full block" >
- {product.nameFa {product.specialBadge && ( @@ -88,7 +122,7 @@ export default function SearchResultsPage({ query }: { query: string }) { )} {compatibility && (
{compatibility.type === 'alert' ? : compatibility.type === 'success' ? : } @@ -96,7 +130,7 @@ export default function SearchResultsPage({ query }: { query: string }) {
)}
- +
{product.category}

{product.nameFa || product.name}

From 2ab23187322e41dc2e7feaf207155ae02b602f71 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 10:29:51 +0000 Subject: [PATCH 23/49] fix(ux): render mobile solution and symptom modals via React Portal to prevent CSS mask clipping --- .../application/components/ArchivePage.tsx | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index 577cde51..053320ec 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -1,5 +1,6 @@ "use client"; import React, { useState, useMemo, useEffect, useCallback } from "react"; +import { createPortal } from "react-dom"; import { toPersian, isProductOutOfStock } from "../lib/utils"; import { Product, PetType } from "../lib/data/products"; import { usePetStore } from "../lib/store/usePetStore"; @@ -470,6 +471,11 @@ export default function ArchivePage({ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [viewMode, setViewMode] = useState<"list" | "grid">("list"); const [visibleCount, setVisibleCount] = useState(12); + const [isMounted, setIsMounted] = useState(false); + + useEffect(() => { + setIsMounted(true); + }, []); const [isMobileSolutionsOpen, setIsMobileSolutionsOpen] = useState(false); const [isMobileSymptomsOpen, setIsMobileSymptomsOpen] = useState(false); @@ -919,8 +925,8 @@ export default function ArchivePage({ - {isMobileSolutionsOpen && ( -
setIsMobileSolutionsOpen(false)}> + {isMobileSolutionsOpen && isMounted && createPortal( +
setIsMobileSolutionsOpen(false)}>
e.stopPropagation()} @@ -931,7 +937,7 @@ export default function ArchivePage({ @@ -945,7 +951,7 @@ export default function ArchivePage({ setSelectedCategory(cat.id); setIsMobileSolutionsOpen(false); }} - className={`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold text-right transition-colors border ${selectedCategory === cat.id ? "bg-canina-blue border-canina-blue text-white" : "bg-white border-medical-gray-100 hover:bg-medical-gray-50 text-medical-gray-700"}`} + className={`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold text-right transition-colors border cursor-pointer ${selectedCategory === cat.id ? "bg-canina-blue border-canina-blue text-white" : "bg-white border-medical-gray-100 hover:bg-medical-gray-50 text-medical-gray-700"}`} > {cat.icon} {cat.label} @@ -953,7 +959,8 @@ export default function ArchivePage({ ))}
-
+
, + document.body )} @@ -971,8 +978,8 @@ export default function ArchivePage({ - {isMobileSymptomsOpen && ( -
setIsMobileSymptomsOpen(false)}> + {isMobileSymptomsOpen && isMounted && createPortal( +
setIsMobileSymptomsOpen(false)}>
e.stopPropagation()} @@ -988,7 +995,7 @@ export default function ArchivePage({ @@ -996,7 +1003,7 @@ export default function ArchivePage({ @@ -1026,7 +1033,7 @@ export default function ArchivePage({ key={s} type="button" onClick={() => toggleSymptom(s)} - className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border whitespace-nowrap ${activeSymptoms.includes(s) + className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border whitespace-nowrap cursor-pointer ${activeSymptoms.includes(s) ? "bg-canina-blue border-canina-blue text-white shadow-2xs" : "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40 hover:text-canina-blue" }`} @@ -1041,13 +1048,14 @@ export default function ArchivePage({
-
+ , + document.body )} From 3d45b618ab3d5584fdbcab02b60c5f9458556107 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 10:42:55 +0000 Subject: [PATCH 24/49] feat(search): redesign search page for mobile-first layout with multi-content tabs (products, blogs, wiki, videos) --- .../components/SearchResultsPage.tsx | 690 ++++++++++++++---- 1 file changed, 548 insertions(+), 142 deletions(-) diff --git a/frontend/application/components/SearchResultsPage.tsx b/frontend/application/components/SearchResultsPage.tsx index 1bf69ef8..6d56a762 100644 --- a/frontend/application/components/SearchResultsPage.tsx +++ b/frontend/application/components/SearchResultsPage.tsx @@ -1,182 +1,588 @@ "use client"; -import React, { useState, useEffect } from "react"; -import { Search, ChevronLeft, ArrowRight, Sparkles, Heart, AlertCircle } from "lucide-react"; + +import React, { useState, useEffect, useMemo } from "react"; +import { + Search, + ChevronLeft, + ArrowRight, + Sparkles, + Heart, + AlertCircle, + ShoppingBag, + FileText, + BookOpen, + Video, + Check, + ExternalLink, + Pill, + Clock, + PlayCircle +} from "lucide-react"; import { usePetStore } from "../lib/store/usePetStore"; -import { motion } from "motion/react"; +import { motion, AnimatePresence } from "motion/react"; import { Product } from "../lib/data/products"; import { productService } from "../lib/services/productService"; - 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"; + +type SearchTab = "all" | "products" | "blogs" | "wiki" | "videos"; + +interface BlogItem { + id: string; + title: string; + slug: string; + excerpt?: string; + category?: string | { name?: string }; + imageUrl?: string; + readingTime?: number; +} + +interface WikiItem { + id: string; + name?: string; + nameFa?: string; + scientificName?: string; + slug?: string; + description?: string; + category?: string; +} + +interface VideoItem { + id: string; + title: string; + doctor?: string; + duration?: string; + thumbnail?: string; + description?: string; +} export default function SearchResultsPage({ query }: { query: string }) { const router = useRouter(); const { getActivePet } = usePetStore(); const activePet = getActivePet(); - const [products, setProducts] = useState([]); + const [activeTab, setActiveTab] = useState("all"); + const [searchInput, setSearchInput] = useState(query); + + const [products, setProducts] = useState([]); + const [blogs, setBlogs] = useState([]); + const [wikiItems, setWikiItems] = useState([]); + const [videos, setVideos] = useState([]); + const [isLoading, setIsLoading] = useState(true); + + // Sync input when prop changes useEffect(() => { - productService.getProducts({ limit: 999 }) - .then(res => setProducts(res.data)) - .catch(err => console.error("Error fetching products in SearchResultsPage:", err)); + setSearchInput(query); + }, [query]); + + // Fetch all searchable datasets in parallel + useEffect(() => { + let isMounted = true; + setIsLoading(true); + + 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); + } + }; + + loadAll(); + return () => { isMounted = false; }; }, []); - const results = products.filter(p => - p.name.toLowerCase().includes(query.toLowerCase()) || - p.description.toLowerCase().includes(query.toLowerCase()) || - p.main_ingredients.some(ing => ing.toLowerCase().includes(query.toLowerCase())) || - p.symptoms.some(sym => sym.toLowerCase().includes(query.toLowerCase())) - ); + const cleanQuery = (query || "").trim().toLowerCase(); + // 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) + ); + }, [products, cleanQuery]); + + // 2. Filtered Blogs + const filteredBlogs = useMemo(() => { + if (!cleanQuery) return blogs; + return blogs.filter(b => + (b.title || '').toLowerCase().includes(cleanQuery) || + (b.excerpt || '').toLowerCase().includes(cleanQuery) + ); + }, [blogs, cleanQuery]); + + // 3. Filtered Wiki Items + 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) + ); + }, [wikiItems, cleanQuery]); + + // 4. Filtered Videos + 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) + ); + }, [videos, cleanQuery]); + + const totalResults = filteredProducts.length + filteredBlogs.length + filteredWiki.length + filteredVideos.length; const bestSellers = products.slice(0, 3); + const handleSearchSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (searchInput.trim()) { + router.push(`/search?q=${encodeURIComponent(searchInput.trim())}`); + } else { + router.push('/search'); + } + }; + return ( -
+
- -
-
-

- {query ? ( - <>نتایج جستجو برای: "{query}" - ) : ( - "جستجوی هوشمند در محصولات و مکمل‌های کنینا" - )} -

-

- {query - ? `${results.length} محصول با معیارهای شما مطابقت دارد.` - : "نام دارو، ترکیب مؤثره، علامت بیماری یا مشکل پت خود را جستجو کنید."} -

- - {/* Direct Interactive Search Box */} -
{ - e.preventDefault(); - const form = e.currentTarget; - const input = form.elements.namedItem("q") as HTMLInputElement; - if (input && input.value.trim()) { - router.push(`/search?q=${encodeURIComponent(input.value.trim())}`); - } - }} - className="relative max-w-xl" + {/* Mobile-First Header Bar: Back Button & Compact Title */} +
+
+ - + + بازگشت + + جستجوی جامع کنینا
+ + {cleanQuery && ( + + {toPersian(totalResults)} نتیجه + + )}
- {results.length > 0 ? ( -
- {results.map((product) => { - const compatibility = (() => { - if (!activePet) return null; - const sameSpecies = product.suitableFor === activePet.type || product.suitableFor === "هر دو"; - const helpsSymptom = activePet.medicalConditions.some(c => product.symptoms.includes(c)); - if (!sameSpecies) return { type: 'alert', text: `مخصوص ${product.suitableFor}` }; - if (helpsSymptom) return { type: 'success', text: `توصیه شده برای ${activePet.name}` }; - return { type: 'neutral', text: `مناسب برای ${activePet.name}` }; - })(); + {/* Compact Search Header & Input */} +
+

+ {cleanQuery ? ( + <>نتایج جستجو برای: "{query}" + ) : ( + "جستجوی هوشمند در تمامی بخش‌های کنینا" + )} +

+

+ جستجوی هم‌زمان در داروها، مکمل‌ها، مقالات وبلاگ، دانشنامه ترکیبات و ویدیوهای بالینی +

- return ( - - -
- {product.nameFa - {product.specialBadge && ( -
- {product.specialBadge} -
- )} - {compatibility && ( -
- {compatibility.type === 'alert' ? : compatibility.type === 'success' ? : } - {compatibility.text} -
- )} -
+ {/* Search Box Input */} +
+ setSearchInput(e.target.value)} + placeholder="جستجوی دارو، مقاله، ترکیب علمی، ویدیو..." + className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 sm:py-3 pr-10 pl-20 text-xs sm:text-sm font-bold focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-xs text-medical-gray-900" + /> + + + +
-
- {product.category} -

{product.nameFa || product.name}

-

{product.benefits}

-
+ {/* Multi-Content Filter Tabs */} +
+ {[ + { id: "all", label: "همه نتایج", count: totalResults, icon: }, + { id: "products", label: "محصولات و داروها", count: filteredProducts.length, icon: }, + { id: "blogs", label: "مقالات وبلاگ", count: filteredBlogs.length, icon: }, + { id: "wiki", label: "دانشنامه ترکیبات", count: filteredWiki.length, icon: }, + { id: "videos", label: "ویدیوهای بالینی", count: filteredVideos.length, icon:
-
-
- {product.price} + {/* RESULTS AREA */} + {cleanQuery && totalResults === 0 && !isLoading ? ( + /* Empty State - Mobile-Optimized with direct suggestion cards */ +
+
+
+ +
+

نتیجه‌ای یافت نشد

+

+ متأسفیم، هیچ موردی با عبارت جستجو شده تطبیق نداشت. محصولات پرطرفدار زیر را بررسی کنید: +

+ +
+ + {bestSellers.length > 0 && ( +
+

محصولات پیشنهادی (پرفروش)

+
+ {bestSellers.map(p => ( + +
+ {p.name}
-
- +
+

{p.nameFa || p.name}

+
{p.price}
-
- - - ) - })} + + ))} +
+
+ )}
) : ( -
-
-
- -
-

نتیجه‌ای یافت نشد

-

- متاسفیم، هیچ محصولی با عبارت مورد نظر شما مطابقت نداشت. شاید محصولات پرفروش ما برای شما مفید باشند؟ -

-
+
-
-

محصولات پیشنهادی (پرفروش)

-
- {bestSellers.map(p => ( - -
- {p.name} -
-

{p.name}

- - ))} + {/* 1. PRODUCTS SECTION */} + {(activeTab === "all" || activeTab === "products") && filteredProducts.length > 0 && ( +
+
+
+ +

محصولات و مکمل‌ها ({toPersian(filteredProducts.length)})

+
+ {activeTab === "all" && filteredProducts.length > 6 && ( + + )}
-
+ +
+ {(activeTab === "all" ? filteredProducts.slice(0, 6) : filteredProducts).map((product) => { + const compatibility = (() => { + if (!activePet) return null; + const sameSpecies = product.suitableFor === activePet.type || product.suitableFor === "هر دو"; + const helpsSymptom = Array.isArray(activePet.medicalConditions) && Array.isArray(product.symptoms) && activePet.medicalConditions.some(c => product.symptoms.includes(c)); + if (!sameSpecies) return { type: 'alert', text: `مخصوص ${product.suitableFor}` }; + if (helpsSymptom) return { type: 'success', text: `توصیه شده برای ${activePet.name}` }; + return { type: 'neutral', text: `مناسب برای ${activePet.name}` }; + })(); + + return ( + +
+
+ {product.nameFa +
+ +
+
+ + {product.category} + + {compatibility && ( + + {compatibility.text} + + )} +
+

+ {product.nameFa || product.name} +

+

+ {product.benefits || product.description} +

+
+
+ +
+ {product.price} + + مشاهده و خرید + + +
+ + ); + })} +
+ + )} + + {/* 2. BLOGS SECTION */} + {(activeTab === "all" || activeTab === "blogs") && filteredBlogs.length > 0 && ( +
+
+
+ +

مقالات مجله سلامت ({toPersian(filteredBlogs.length)})

+
+ {activeTab === "all" && filteredBlogs.length > 4 && ( + + )} +
+ +
+ {(activeTab === "all" ? filteredBlogs.slice(0, 4) : filteredBlogs).map((blog) => ( + + {blog.imageUrl ? ( +
+ {blog.title} +
+ ) : ( +
+ +
+ )} + +
+ + {typeof blog.category === 'object' ? blog.category?.name : blog.category || 'مقاله علمی'} + +

+ {blog.title} +

+

+ {blog.excerpt} +

+
+ + ))} +
+
+ )} + + {/* 3. WIKI SECTION */} + {(activeTab === "all" || activeTab === "wiki") && filteredWiki.length > 0 && ( +
+
+
+ +

دانشنامه ترکیبات علمی ({toPersian(filteredWiki.length)})

+
+ {activeTab === "all" && filteredWiki.length > 4 && ( + + )} +
+ +
+ {(activeTab === "all" ? filteredWiki.slice(0, 4) : filteredWiki).map((wiki) => ( + +
+ +
+
+

+ {wiki.nameFa || wiki.name} +

+ {wiki.scientificName && ( +
+ {wiki.scientificName} +
+ )} +

+ {wiki.description} +

+
+ + + ))} +
+
+ )} + + {/* 4. VIDEOS SECTION */} + {(activeTab === "all" || activeTab === "videos") && filteredVideos.length > 0 && ( +
+
+
+
+ {activeTab === "all" && filteredVideos.length > 3 && ( + + )} +
+ +
+ {(activeTab === "all" ? filteredVideos.slice(0, 3) : filteredVideos).map((vid) => ( + +
+ {vid.thumbnail ? ( + {vid.title} + ) : null} +
+ +
+ {vid.duration && ( + + {vid.duration} + + )} +
+
+
+

+ {vid.title} +

+ {vid.doctor && ( + + {vid.doctor} + + )} +
+
+ + ))} +
+
+ )} +
)} +
); From 092933860a2a3e5109dd5fb3f0ad9fb0a40b228c Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 10:59:21 +0000 Subject: [PATCH 25/49] feat(ux): complete 5-task suite (category filter, real total count, mobile wiki, blog mobile UX, chatbot typewriter) --- .../application/components/ArchivePage.tsx | 11 +- frontend/application/components/BlogPage.tsx | 172 +++++++++++++----- .../application/components/IngredientWiki.tsx | 48 ++--- .../application/components/SupportChat.tsx | 30 ++- 4 files changed, 182 insertions(+), 79 deletions(-) diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index 053320ec..bd2db4cc 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -921,7 +921,7 @@ export default function ArchivePage({ }} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-xl border text-[11px] font-black shadow-2xs transition-all whitespace-nowrap ${selectedCategory !== "all" ? "bg-canina-blue text-white border-canina-blue" : "bg-white border-medical-gray-200 text-medical-gray-700"}`} > - {selectedCategory !== "all" ? (CATEGORY_LABELS[selectedCategory] || "راهکار درمانی") : "راهکار درمانی"} + {selectedCategory !== "all" ? (CATEGORY_LABELS[selectedCategory] || "دسته‌بندی") : "دسته‌بندی و راهکار"} @@ -933,7 +933,7 @@ export default function ArchivePage({ >
-

انتخاب راهکار درمانی

+

فیلتر دسته‌بندی و راهکار درمانی

)}
+ {/* Sort Dropdown */} +
+
+
+ + مرتب‌سازی: +
+ +
+
+ {selectedTag && ( -
- تگ انتخاب شده: #{selectedTag} +
+ تگ: #{selectedTag} @@ -189,54 +230,61 @@ export default function BlogPage({ )}
- {/* Category Filter Pills */} -
- - {categories.map((c) => ( + {/* Category Filter Pills with smooth edge mask */} +
+
- ))} + {categories.map((c) => ( + + ))} +
{/* Quick Tag Cloud */} {allTags.length > 0 && (
- + - محبوب‌ترین تگ‌ها: + تگ‌های محبوب: - {allTags.slice(0, 10).map((tag) => ( + {allTags.slice(0, 8).map((tag) => (
)} - {/* Regular Posts Grid */} - {regularPosts.length > 0 ? ( -
- {regularPosts.map((post, idx) => ( + {/* Regular Posts Grid - Mobile-Optimized */} + {slicedRegularPosts.length > 0 ? ( + <> +
+

همه مقالات تخصصی

+ + {toPersian(regularPosts.length)} مقاله + +
+ +
+ {slicedRegularPosts.map((post, idx) => ( router.push(`/blog/${encodeURIComponent(post.slug || post.id)}`)} >
@@ -348,7 +404,7 @@ export default function BlogPage({ {(post.viewCount ?? 0).toLocaleString('fa-IR')}
-
+
@@ -374,7 +430,7 @@ export default function BlogPage({
-
+
{post.author} @@ -387,6 +443,22 @@ export default function BlogPage({ ))}
+ + {hasMore && ( +
+ +
+ )} + ) : (

diff --git a/frontend/application/components/IngredientWiki.tsx b/frontend/application/components/IngredientWiki.tsx index 8f9e488d..91d9503d 100644 --- a/frontend/application/components/IngredientWiki.tsx +++ b/frontend/application/components/IngredientWiki.tsx @@ -166,36 +166,36 @@ export default function IngredientWiki() {

-
-
- - علم در خدمت کیفیت +
+
+ + علم در خدمت کیفیت
-

+

دانشنامه مواد نایاب و ارگانیک کنینا

-

+

تمامی ترکیبات فعال و مکمل‌های به کار رفته در محصولات دارویی و مراقبتی Canina Pharma آلمان، دارای بالاترین گرید بیولوژیک و فارماکوپه اروپا می‌باشند.

-
- +
+ setSearchQuery(e.target.value)} - className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-full py-3 pr-11 pl-4 text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20" + className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 sm:py-3 pr-10 pl-4 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-xs" />
{/* Sugar-Free & Gluten-Free Medical Standards Banner */} -
-
- +
+
+ ۱۰۰٪ فاقد قند افزوده (Sugar-Free)
-
- +
+ مطابق استانداردهای دارویی و بالینی آلمان
@@ -219,7 +219,7 @@ export default function IngredientWiki() { } return ( -
+
{filtered.map((ing, idx) => { const hasIngredient = getProductsForIngredient(ing.id, ing.name); const isTargeted = termParam === ing.id; @@ -228,7 +228,7 @@ export default function IngredientWiki() {
{/* Content */}
@@ -238,23 +238,23 @@ export default function IngredientWiki() { viewport={{ once: true }} transition={{ duration: 0.6 }} > -
-
+
+
-

{ing.name}

+

{ing.name}

کد ماده مؤثره: {ing.id}
-

+

{ing.description}

-
+
{ing.benefits.map((benefit, bIdx) => ( -
+
{benefit}
@@ -269,10 +269,10 @@ export default function IngredientWiki() { initial={{ opacity: 0, scale: 0.95 }} whileInView={{ opacity: 1, scale: 1 }} viewport={{ once: true }} - className="bg-medical-gray-50/80 rounded-[3rem] p-6 sm:p-8 border border-medical-gray-200/60 relative overflow-hidden flex-1 flex flex-col justify-between" + className="bg-medical-gray-50/80 rounded-xl sm:rounded-3xl p-3.5 sm:p-6 border border-medical-gray-200/60 relative overflow-hidden flex-1 flex flex-col justify-between" >
-
+

موجود در محصولات کاتالوگ

diff --git a/frontend/application/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx index 4ac4ba33..cbd2d577 100644 --- a/frontend/application/components/SupportChat.tsx +++ b/frontend/application/components/SupportChat.tsx @@ -160,9 +160,35 @@ export default function SupportChat() { // safe fallback kept } if (!controller.signal.aborted && token() === current) { - setRows((r) => { const next = [...r]; const i = next.length - 1; if (i >= 0 && next[i].question === question && next[i].answer === 'در حال بررسی…') next[i] = { question, answer }; return next; }); + // Typewriting animation for smooth AI assistant response streaming feel + const fullAnswer = answer; + const stepSize = Math.max(2, Math.floor(fullAnswer.length / 40)); + let currentIdx = 0; + + const typeInterval = setInterval(() => { + currentIdx += stepSize; + if (currentIdx >= fullAnswer.length || controller.signal.aborted) { + clearInterval(typeInterval); + setRows((r) => { + const next = [...r]; + const i = next.length - 1; + if (i >= 0 && next[i].question === question) next[i] = { question, answer: fullAnswer }; + return next; + }); + if (pending.current === controller) setBusy(false); + } else { + const partial = fullAnswer.slice(0, currentIdx) + " ▍"; + setRows((r) => { + const next = [...r]; + const i = next.length - 1; + if (i >= 0 && next[i].question === question) next[i] = { question, answer: partial }; + return next; + }); + } + }, 18); + } else { + if (pending.current === controller) setBusy(false); } - if (pending.current === controller) setBusy(false); } if (!config?.enabled) return configError ? تنظیمات پشتیبان هوشمند در دسترس نیست. : null; From 80d9dc2f454a685efb478fc9033295a005cd0c0b Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 11:18:52 +0000 Subject: [PATCH 26/49] fix(wiki): compact mobile cards and add pagination --- .../application/components/IngredientWiki.tsx | 95 +++++++++++++------ .../__tests__/IngredientWiki.test.tsx | 77 ++++++++++++++- 2 files changed, 141 insertions(+), 31 deletions(-) diff --git a/frontend/application/components/IngredientWiki.tsx b/frontend/application/components/IngredientWiki.tsx index 91d9503d..ec4d50d3 100644 --- a/frontend/application/components/IngredientWiki.tsx +++ b/frontend/application/components/IngredientWiki.tsx @@ -51,12 +51,12 @@ function formatIngredientDisplayName(item: { nameFa?: string; scientificName?: s const rawName = item.nameFa || item.name || ''; const cleanFa = rawName.replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim(); const sub = (item.scientificName || item.nameEn || '').replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim(); - + if (!cleanFa) return sub || rawName || item.slug || ''; if (!sub || cleanFa.toLowerCase() === sub.toLowerCase() || /[\u0600-\u06FF]/.test(sub)) { return cleanFa; } - + return `${cleanFa} (${sub})`; } @@ -67,6 +67,7 @@ export default function IngredientWiki() { const [ingredientsWiki, setIngredientsWiki] = useState([]); const [products, setProducts] = useState([]); const [searchQuery, setSearchQuery] = useState(""); + const [visibleCount, setVisibleCount] = useState(8); useEffect(() => { productService.getProducts({ limit: 999 }) @@ -110,7 +111,15 @@ export default function IngredientWiki() { }, 200); } } - }, [termParam, ingredientsWiki]); + }, [termParam, ingredientsWiki, visibleCount]); + + useEffect(() => { + if (!termParam || ingredientsWiki.length === 0) return; + const targetIndex = ingredientsWiki.findIndex(ing => ing.id === termParam); + if (targetIndex >= visibleCount) { + setVisibleCount(Math.ceil((targetIndex + 1) / 8) * 8); + } + }, [termParam, ingredientsWiki, visibleCount]); // Product matcher for each ingredient const getProductsForIngredient = useMemo(() => { @@ -146,11 +155,11 @@ export default function IngredientWiki() { }, [products]); return ( -
+
- + {/* Standard Breadcrumb Navigation & Integrated Back Button */} -
+
router.push('/')}>خانه @@ -183,7 +192,10 @@ export default function IngredientWiki() { type="text" placeholder="جستجوی ماده مؤثره (مثلاً: صدف لب‌سبز، آغوز، بیوتین)..." value={searchQuery} - onChange={(e) => setSearchQuery(e.target.value)} + onChange={(e) => { + setSearchQuery(e.target.value); + setVisibleCount(8); + }} className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 sm:py-3 pr-10 pl-4 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-xs" />
@@ -218,15 +230,20 @@ export default function IngredientWiki() { ); } + const visibleIngredients = filtered.slice(0, visibleCount); + const remainingCount = Math.max(filtered.length - visibleCount, 0); + const nextCount = Math.min(8, remainingCount); + return ( -
- {filtered.map((ing, idx) => { + <> +
+ {visibleIngredients.map((ing, idx) => { const hasIngredient = getProductsForIngredient(ing.id, ing.name); const isTargeted = termParam === ing.id; return ( -
@@ -247,7 +264,7 @@ export default function IngredientWiki() { کد ماده مؤثره: {ing.id}
- +

{ing.description}

@@ -265,7 +282,7 @@ export default function IngredientWiki() { {/* Products Linking */}
-
- -
+ +
{hasIngredient.length > 0 ? hasIngredient.slice(0, 4).map(p => ( - -
- {p.name} + {p.name} { e.currentTarget.src = '/assets/images/canina-product-placeholder.png'; }} />
-

{p.name}

+

{p.name}

)) : (
@@ -321,7 +341,7 @@ export default function IngredientWiki() { {hasIngredient.length > 4 && (
- @@ -330,7 +350,7 @@ export default function IngredientWiki() {
)} - + {/* Decorative backdrop */}
@@ -338,7 +358,24 @@ export default function IngredientWiki() {
); })} -
+
+ + {remainingCount > 0 && ( +
+ + + نمایش {Math.min(visibleCount, filtered.length).toLocaleString('fa-IR')} از {filtered.length.toLocaleString('fa-IR')} ماده + +
+ )} + ); })()}
diff --git a/frontend/application/components/__tests__/IngredientWiki.test.tsx b/frontend/application/components/__tests__/IngredientWiki.test.tsx index 99ede074..3f75c227 100644 --- a/frontend/application/components/__tests__/IngredientWiki.test.tsx +++ b/frontend/application/components/__tests__/IngredientWiki.test.tsx @@ -32,8 +32,8 @@ vi.mock('next/image', () => ({ // Mock next/link vi.mock('next/link', () => ({ - default: ({ children, href, className }: any) => ( - + default: ({ children, href, className, ...props }: any) => ( + {children} ), @@ -217,4 +217,77 @@ describe('IngredientWiki Component', () => { expect(screen.getByText(/آغوز گاو/)).toBeInTheDocument(); }); }); + + it('shows only the first 8 ingredients and loads the next page on demand', async () => { + (productService.getProducts as any).mockResolvedValueOnce({ data: [] }); + const ingredients = Array.from({ length: 18 }, (_, index) => ({ + id: `ingredient-${index + 1}`, + slug: `ingredient-${index + 1}`, + nameFa: `ماده شماره ${index + 1}`, + description: `توضیح ماده ${index + 1}`, + benefits: [], + })); + (api.get as any).mockResolvedValueOnce({ data: ingredients }); + + render(); + + await waitFor(() => expect(screen.getByText('ماده شماره 1')).toBeInTheDocument()); + expect(screen.getByText('ماده شماره 8')).toBeInTheDocument(); + expect(screen.queryByText('ماده شماره 9')).not.toBeInTheDocument(); + expect(screen.getByText(/نمایش ۸ از ۱۸ ماده/)).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: /مشاهده ۸ ماده بیشتر/ })); + + expect(screen.getByText('ماده شماره 16')).toBeInTheDocument(); + expect(screen.queryByText('ماده شماره 17')).not.toBeInTheDocument(); + expect(screen.getByText(/نمایش ۱۶ از ۱۸ ماده/)).toBeInTheDocument(); + }); + + it('resets ingredient pagination when the search query changes', async () => { + (productService.getProducts as any).mockResolvedValueOnce({ data: [] }); + const ingredients = Array.from({ length: 12 }, (_, index) => ({ + id: `item-${index + 1}`, + slug: `item-${index + 1}`, + nameFa: index < 10 ? `مشترک ${index + 1}` : `دیگر ${index + 1}`, + description: 'توضیح مشترک', + benefits: [], + })); + (api.get as any).mockResolvedValueOnce({ data: ingredients }); + + render(); + await waitFor(() => expect(screen.getByText('مشترک 1')).toBeInTheDocument()); + fireEvent.click(screen.getByRole('button', { name: /مشاهده ۴ ماده بیشتر/ })); + expect(screen.getByText('دیگر 12')).toBeInTheDocument(); + + fireEvent.change(screen.getByPlaceholderText(/جستجوی ماده مؤثره/), { target: { value: 'مشترک' } }); + expect(screen.getByText('مشترک 8')).toBeInTheDocument(); + expect(screen.queryByText('مشترک 9')).not.toBeInTheDocument(); + }); + + it('uses compact two-column related-product cards on mobile', async () => { + (api.get as any).mockResolvedValueOnce({ data: [{ + id: 'biotin', slug: 'biotin', nameFa: 'بیوتین', description: 'توضیح', benefits: [], + }] }); + (productService.getProducts as any).mockResolvedValueOnce({ data: [{ + id: 'p-1', slug: 'biotin-tabs', name: 'محصول بیوتین', main_ingredients: ['بیوتین'], image: '/biotin.png', + }] }); + + render(); + await waitFor(() => expect(screen.getByText('محصول بیوتین')).toBeInTheDocument()); + + expect(screen.getByTestId('wiki-related-products-grid')).toHaveClass('grid-cols-2'); + expect(screen.getByTestId('wiki-related-product-card')).toHaveClass('p-2'); + expect(screen.getByTestId('wiki-related-product-image')).toHaveClass('h-20'); + }); + + + it('keeps the mobile breadcrumb close to the top edge', () => { + (productService.getProducts as any).mockResolvedValueOnce({ data: [] }); + (api.get as any).mockResolvedValueOnce({ data: [] }); + + const { container } = render(); + expect(container.firstElementChild).toHaveClass('pt-3', 'pb-8', 'sm:py-12'); + expect(container.firstElementChild).not.toHaveClass('py-12'); + }); + }); From 5573bb3568d0e42a1d9941c39721520cf5c72bfb Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 11:24:36 +0000 Subject: [PATCH 27/49] fix(wiki): contain long ingredient codes on mobile --- .../application/components/IngredientWiki.tsx | 2 +- .../components/__tests__/IngredientWiki.test.tsx | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/frontend/application/components/IngredientWiki.tsx b/frontend/application/components/IngredientWiki.tsx index ec4d50d3..64b6427d 100644 --- a/frontend/application/components/IngredientWiki.tsx +++ b/frontend/application/components/IngredientWiki.tsx @@ -261,7 +261,7 @@ export default function IngredientWiki() {

{ing.name}

- کد ماده مؤثره: {ing.id} + کد ماده مؤثره: {ing.id}
diff --git a/frontend/application/components/__tests__/IngredientWiki.test.tsx b/frontend/application/components/__tests__/IngredientWiki.test.tsx index 3f75c227..68322ba3 100644 --- a/frontend/application/components/__tests__/IngredientWiki.test.tsx +++ b/frontend/application/components/__tests__/IngredientWiki.test.tsx @@ -290,4 +290,20 @@ describe('IngredientWiki Component', () => { expect(container.firstElementChild).not.toHaveClass('py-12'); }); + + it('wraps long ingredient codes inside the mobile card', async () => { + (productService.getProducts as any).mockResolvedValueOnce({ data: [] }); + (api.get as any).mockResolvedValueOnce({ data: [{ + id: 'beef-broth-279-spray-dried', + slug: 'beef-broth-279-spray-dried', + nameFa: 'آب گوشت گاو', + description: 'توضیح', + benefits: [], + }] }); + + render(); + await waitFor(() => expect(screen.getByText('آب گوشت گاو')).toBeInTheDocument()); + expect(screen.getByTestId('wiki-ingredient-code')).toHaveClass('max-w-full', 'break-all'); + }); + }); From 297aaadbe618408821075269a9e141b76127a8ae Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 11:45:34 +0000 Subject: [PATCH 28/49] fix(blog): preserve sanitized content through hydration --- frontend/application/app/blog/[slug]/page.tsx | 3 ++ frontend/application/components/BlogPage.tsx | 12 +++---- .../application/components/BlogPostClient.tsx | 13 ++------ .../components/__tests__/BlogPage.test.tsx | 2 +- .../__tests__/BlogPostClient.test.tsx | 27 ++++++++++++++++ frontend/application/lib/sanitizeBlogHtml.ts | 32 +++++++++++++++++++ 6 files changed, 72 insertions(+), 17 deletions(-) create mode 100644 frontend/application/lib/sanitizeBlogHtml.ts diff --git a/frontend/application/app/blog/[slug]/page.tsx b/frontend/application/app/blog/[slug]/page.tsx index 33fa4ff0..03ca3731 100644 --- a/frontend/application/app/blog/[slug]/page.tsx +++ b/frontend/application/app/blog/[slug]/page.tsx @@ -4,6 +4,7 @@ import type { Metadata } from 'next'; import BlogPostClient from "../../../components/BlogPostClient"; import { getSeoConfig, formatPageTitle } from "../../../lib/seo"; import { safeJsonLd } from "../../../lib/schema"; +import { sanitizeBlogHtml } from "../../../lib/sanitizeBlogHtml"; function safeIso(val: any, fallback?: string): string | undefined { if (!val) return fallback; @@ -182,6 +183,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug: const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString(); const modifiedIso = safeIso(blog.updatedAt) || publishedIso; + const sanitizedContent = sanitizeBlogHtml(blog.content); const schemaType = blog.schemaType || 'BlogPosting'; const authorSchema = blog.author && (blog.author.firstName || blog.author.lastName) @@ -279,6 +281,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug: blog={blog} publishedDate={publishedDate} authorName={authorName} + sanitizedContent={sanitizedContent} /> ); diff --git a/frontend/application/components/BlogPage.tsx b/frontend/application/components/BlogPage.tsx index e787f465..18c3cfe6 100644 --- a/frontend/application/components/BlogPage.tsx +++ b/frontend/application/components/BlogPage.tsx @@ -297,11 +297,11 @@ export default function BlogPage({ {/* Featured Post Banner */} {featuredPost && (
- router.push(`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`)} >
- +
)} @@ -375,14 +375,14 @@ export default function BlogPage({
{slicedRegularPosts.map((post, idx) => ( - router.push(`/blog/${encodeURIComponent(post.slug || post.id)}`)} >
@@ -440,7 +440,7 @@ export default function BlogPage({
-
+ ))}
diff --git a/frontend/application/components/BlogPostClient.tsx b/frontend/application/components/BlogPostClient.tsx index 5d6e5696..03e68985 100644 --- a/frontend/application/components/BlogPostClient.tsx +++ b/frontend/application/components/BlogPostClient.tsx @@ -1,6 +1,5 @@ "use client"; import React, { useState, useEffect } from "react"; -import DOMPurify from 'dompurify'; import { ChevronRight, Calendar, @@ -24,9 +23,10 @@ interface BlogPostClientProps { blog: any; publishedDate: string; authorName: string; + sanitizedContent: string; } -export default function BlogPostClient({ blog, publishedDate, authorName }: BlogPostClientProps) { +export default function BlogPostClient({ blog, publishedDate, authorName, sanitizedContent }: BlogPostClientProps) { const [copied, setCopied] = useState(false); const [viewCount, setViewCount] = useState(blog.viewCount || 0); const [commentName, setCommentName] = useState(""); @@ -176,14 +176,7 @@ export default function BlogPostClient({ blog, publishedDate, authorName }: Blog {/* Main Rich Content HTML Renderer */}
{/* Tags Chip Footer */} diff --git a/frontend/application/components/__tests__/BlogPage.test.tsx b/frontend/application/components/__tests__/BlogPage.test.tsx index 5333bcc0..8c1dd055 100644 --- a/frontend/application/components/__tests__/BlogPage.test.tsx +++ b/frontend/application/components/__tests__/BlogPage.test.tsx @@ -20,7 +20,7 @@ const blogs=[{id:'1',slug:'joint',title:'Joint article',excerpt:'Mobility guide' const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Skin',slug:'skin'}]; beforeEach(()=>vi.clearAllMocks()); describe('BlogPage',()=>{ - it('prioritizes featured post and navigates',()=>{render();expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');fireEvent.click(screen.getByText('Skin article'));expect(h.push).toHaveBeenCalledWith('/blog/skin');}); + it('renders featured and regular posts as semantic links',()=>{render();expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');expect(screen.getByRole('link',{name:/Skin article/})).toHaveAttribute('href','/blog/skin');expect(screen.getByRole('link',{name:/Joint article/})).toHaveAttribute('href','/blog/joint');}); it('combines category, excerpt search and tags then resets empty intersection',()=>{render();fireEvent.click(screen.getByRole('button',{name:'Joints'}));expect(h.replace).toHaveBeenCalledWith('/blog?categoryId=joints',{scroll:false});expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماری‌ها، ویتامین‌ها...'),{target:{value:'MOBILITY'}});expect(screen.getByText('Joint article')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#coat'}));expect(screen.getByText('هیچ مقاله‌ای با معیارهای جستجوی شما یافت نشد.')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'پاکسازی همه فیلترها'}));expect(screen.getByText('Skin article')).toBeInTheDocument();expect(screen.getByText('Joint article')).toBeInTheDocument();}); it('syncs category with route props',()=>{const view=render();expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender();expect(screen.queryByText('Joint article')).not.toBeInTheDocument();}); it('clears search and toggles tags off',()=>{render();fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.getByText('Skin article')).toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماری‌ها، ویتامین‌ها...'),{target:{value:'missing'}});fireEvent.click(screen.getByRole('button',{name:'پاک کردن'}));expect(screen.getByText('Skin article')).toBeInTheDocument();}); diff --git a/frontend/application/components/__tests__/BlogPostClient.test.tsx b/frontend/application/components/__tests__/BlogPostClient.test.tsx index eeb3e52c..f4b6f412 100644 --- a/frontend/application/components/__tests__/BlogPostClient.test.tsx +++ b/frontend/application/components/__tests__/BlogPostClient.test.tsx @@ -80,6 +80,7 @@ describe("BlogPostClient Component", () => { render( @@ -113,6 +114,7 @@ describe("BlogPostClient Component", () => { render( @@ -133,6 +135,7 @@ describe("BlogPostClient Component", () => { render( @@ -170,6 +173,7 @@ describe("BlogPostClient Component", () => { render( @@ -215,6 +219,7 @@ describe("BlogPostClient Component", () => { render( @@ -241,6 +246,7 @@ describe("BlogPostClient Component", () => { render( @@ -254,4 +260,25 @@ describe("BlogPostClient Component", () => { expect(screen.getByText("لینک کپی شد!")).toBeInTheDocument(); }); }); + + it("renders the server-sanitized article HTML instead of recomputing content in the browser", () => { + const rawContent = "

متن خام متفاوت

"; + const sanitizedContent = "

اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید

راهنمای تغذیه

"; + + const { container } = render( + + ); + + const article = container.querySelector('.article-html-content'); + expect(article?.innerHTML).toBe(sanitizedContent); + expect(article).toHaveTextContent('اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید'); + expect(article?.innerHTML).not.toContain('metaTitle'); + expect(article?.innerHTML).not.toContain(' Date: Sat, 17 Oct 2026 12:33:00 +0000 Subject: [PATCH 29/49] 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();}); From 2c3e4bb752732e927e3d9639795231735ed1fb0e Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 12:52:00 +0000 Subject: [PATCH 30/49] fix(search): connect tabs to results panel --- frontend/application/components/SearchResultsPage.tsx | 9 +++++++-- .../components/__tests__/SearchResultsPage.test.tsx | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/frontend/application/components/SearchResultsPage.tsx b/frontend/application/components/SearchResultsPage.tsx index a9b4a7d2..6461cfb7 100644 --- a/frontend/application/components/SearchResultsPage.tsx +++ b/frontend/application/components/SearchResultsPage.tsx @@ -267,7 +267,7 @@ export default function SearchResultsPage({ query }: { query: string }) { role="tab" id={`search-tab-${tab.id}`} aria-selected={activeTab === tab.id} - aria-controls={`search-panel-${tab.id}`} + aria-controls="search-results-panel" onClick={() => setActiveTab(tab.id as SearchTab)} className={`flex items-center gap-1.5 px-3 py-1.5 sm:px-4 sm:py-2 rounded-xl text-xs font-black transition-all shrink-0 cursor-pointer border ${ activeTab === tab.id @@ -344,7 +344,12 @@ export default function SearchResultsPage({ query }: { query: string }) { )}
) : ( -
+
{/* 1. PRODUCTS SECTION */} {(activeTab === "all" || activeTab === "products") && filteredProducts.length > 0 && ( diff --git a/frontend/application/components/__tests__/SearchResultsPage.test.tsx b/frontend/application/components/__tests__/SearchResultsPage.test.tsx index 6b04c07d..ba1c3254 100644 --- a/frontend/application/components/__tests__/SearchResultsPage.test.tsx +++ b/frontend/application/components/__tests__/SearchResultsPage.test.tsx @@ -51,6 +51,10 @@ describe('SearchResultsPage',()=>{ const wikiTab=screen.getByRole('tab',{name:/دانشنامه ترکیبات.*۱/}); const videoTab=screen.getByRole('tab',{name:/ویدیوهای بالینی.*۱/}); expect(allTab).toHaveAttribute('aria-selected','true'); + expect(allTab).toHaveAttribute('aria-controls','search-results-panel'); + expect(productTab).toHaveAttribute('aria-controls','search-results-panel'); + expect(screen.getByRole('tabpanel')).toHaveAttribute('id','search-results-panel'); + expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-labelledby','search-tab-all'); fireEvent.click(blogTab); expect(blogTab).toHaveAttribute('aria-selected','true'); expect(screen.getByRole('link',{name:/Care article/})).toBeInTheDocument(); From 5b20bab38174fa812dd2d9e5780a8eede52013d0 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 14:01:23 +0000 Subject: [PATCH 31/49] feat(wiki): add accessible accordion disclosures for ingredients --- .../application/components/IngredientWiki.tsx | 60 +++++++++++--- .../__tests__/IngredientWiki.test.tsx | 82 +++++++++++++++++++ 2 files changed, 130 insertions(+), 12 deletions(-) diff --git a/frontend/application/components/IngredientWiki.tsx b/frontend/application/components/IngredientWiki.tsx index 64b6427d..d6353f7f 100644 --- a/frontend/application/components/IngredientWiki.tsx +++ b/frontend/application/components/IngredientWiki.tsx @@ -2,7 +2,7 @@ import { useState, useEffect, useMemo } from "react"; import { Product, IngredientInfo } from "../lib/data/products"; import { motion } from "motion/react"; -import { FlaskConical, CheckCircle2, ChevronRight, ChevronLeft, Beaker, Search } from "lucide-react"; +import { FlaskConical, CheckCircle2, ChevronLeft, ChevronDown, Beaker, Search } from "lucide-react"; import { productService } from "../lib/services/productService"; import Link from "next/link"; @@ -68,6 +68,7 @@ export default function IngredientWiki() { const [products, setProducts] = useState([]); const [searchQuery, setSearchQuery] = useState(""); const [visibleCount, setVisibleCount] = useState(8); + const [expandedIngredients, setExpandedIngredients] = useState>(new Set()); useEffect(() => { productService.getProducts({ limit: 999 }) @@ -115,6 +116,12 @@ export default function IngredientWiki() { useEffect(() => { if (!termParam || ingredientsWiki.length === 0) return; + setExpandedIngredients(current => { + if (current.has(termParam)) return current; + const next = new Set(current); + next.add(termParam); + return next; + }); const targetIndex = ingredientsWiki.findIndex(ing => ing.id === termParam); if (targetIndex >= visibleCount) { setVisibleCount(Math.ceil((targetIndex + 1) / 8) * 8); @@ -240,13 +247,51 @@ export default function IngredientWiki() { {visibleIngredients.map((ing, idx) => { const hasIngredient = getProductsForIngredient(ing.id, ing.name); const isTargeted = termParam === ing.id; + const isExpanded = expandedIngredients.has(ing.id); + const safeId = ing.id.replace(/[^a-zA-Z0-9_-]/g, '-'); + const triggerId = `wiki-trigger-${safeId}`; + const panelId = `wiki-panel-${safeId}`; return (
+

+ +

+ + ); })} diff --git a/frontend/application/components/__tests__/IngredientWiki.test.tsx b/frontend/application/components/__tests__/IngredientWiki.test.tsx index 68322ba3..64ecc07f 100644 --- a/frontend/application/components/__tests__/IngredientWiki.test.tsx +++ b/frontend/application/components/__tests__/IngredientWiki.test.tsx @@ -281,6 +281,88 @@ describe('IngredientWiki Component', () => { }); + it('renders accessible disclosures and preserves complete content while toggling', async () => { + (api.get as any).mockResolvedValueOnce({ data: [{ + id: 'biotin', slug: 'biotin', nameFa: 'بیوتین', description: 'توضیح کامل بیوتین', + benefits: ['فایده اول', 'فایده دوم'], + }] }); + (productService.getProducts as any).mockResolvedValueOnce({ data: [{ + id: 'p-1', slug: 'biotin-tabs', name: 'محصول بیوتین', main_ingredients: ['بیوتین'], image: '/biotin.png', + }] }); + + const { container } = render(); + await waitFor(() => expect(screen.getByRole('button', { name: /بیوتین.*نمایش جزئیات/ })).toBeInTheDocument()); + + const trigger = screen.getByRole('button', { name: /بیوتین.*نمایش جزئیات/ }); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + const panelId = trigger.getAttribute('aria-controls'); + expect(panelId).toBeTruthy(); + const panel = container.querySelector(`#${panelId}`); + expect(panel).toHaveAttribute('role', 'region'); + expect(panel).toHaveAttribute('aria-labelledby', trigger.id); + expect(panel).not.toBeVisible(); + expect(screen.getByText('توضیح کامل بیوتین')).toBeInTheDocument(); + expect(screen.getByText('فایده اول')).toBeInTheDocument(); + expect(screen.getByText('فایده دوم')).toBeInTheDocument(); + expect(screen.getByText('محصول بیوتین')).toBeInTheDocument(); + + fireEvent.click(trigger); + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + expect(panel).toBeVisible(); + expect(screen.getByText('توضیح کامل بیوتین')).toBeInTheDocument(); + expect(screen.getByText('محصول بیوتین')).toBeInTheDocument(); + + fireEvent.click(trigger); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + expect(panel).not.toBeVisible(); + expect(screen.getByText('توضیح کامل بیوتین')).toBeInTheDocument(); + expect(screen.getByText('محصول بیوتین')).toBeInTheDocument(); + }); + + it('auto-expands a deep-linked ingredient beyond the first page', async () => { + mockSearchParamsGet.mockImplementation((param: string) => param === 'term' ? 'ingredient-13' : null); + (productService.getProducts as any).mockResolvedValueOnce({ data: [] }); + const ingredients = Array.from({ length: 18 }, (_, index) => ({ + id: `ingredient-${index + 1}`, + slug: `ingredient-${index + 1}`, + nameFa: `ماده شماره ${index + 1}`, + description: `توضیح ماده ${index + 1}`, + benefits: [], + })); + (api.get as any).mockResolvedValueOnce({ data: ingredients }); + + render(); + + const targetTrigger = await screen.findByRole('button', { name: /ماده شماره 13.*بستن جزئیات/ }); + expect(targetTrigger).toHaveAttribute('aria-expanded', 'true'); + expect(document.getElementById(targetTrigger.getAttribute('aria-controls')!)).toBeVisible(); + expect(screen.getByText(/نمایش ۱۶ از ۱۸ ماده/)).toBeInTheDocument(); + expect(document.getElementById('wiki-trigger-ingredient-1')).toHaveAttribute('aria-expanded', 'false'); + }); + + it('keeps an expanded ingredient open after loading another page', async () => { + (productService.getProducts as any).mockResolvedValueOnce({ data: [] }); + const ingredients = Array.from({ length: 18 }, (_, index) => ({ + id: `ingredient-${index + 1}`, + slug: `ingredient-${index + 1}`, + nameFa: `ماده شماره ${index + 1}`, + description: `توضیح ماده ${index + 1}`, + benefits: [], + })); + (api.get as any).mockResolvedValueOnce({ data: ingredients }); + + render(); + const firstTrigger = await screen.findByRole('button', { name: /ماده شماره 1.*نمایش جزئیات/ }); + fireEvent.click(firstTrigger); + expect(firstTrigger).toHaveAttribute('aria-expanded', 'true'); + + fireEvent.click(screen.getByRole('button', { name: /مشاهده ۸ ماده بیشتر/ })); + expect(firstTrigger).toHaveAttribute('aria-expanded', 'true'); + expect(screen.getByRole('button', { name: /ماده شماره 9.*نمایش جزئیات/ })).toHaveAttribute('aria-expanded', 'false'); + expect(screen.getByText(/نمایش ۱۶ از ۱۸ ماده/)).toBeInTheDocument(); + }); + + it('keeps the mobile breadcrumb close to the top edge', () => { (productService.getProducts as any).mockResolvedValueOnce({ data: [] }); (api.get as any).mockResolvedValueOnce({ data: [] }); From f9d70bc1964e5c13c5fef1ddea422b578f2f85c8 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 14:42:44 +0000 Subject: [PATCH 32/49] fix(shop): prevent duplicate product card rendering across breakpoints in list viewMode --- .../application/components/ArchivePage.tsx | 9 +------ .../components/__tests__/ArchivePage.test.tsx | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index bd2db4cc..25dc2a4f 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -1162,14 +1162,7 @@ export default function ArchivePage({ {section.products.map((p: Product) => ( {viewMode === "list" ? ( - <> -
- -
-
- -
- + ) : ( )} diff --git a/frontend/application/components/__tests__/ArchivePage.test.tsx b/frontend/application/components/__tests__/ArchivePage.test.tsx index 740f7edc..5243e288 100644 --- a/frontend/application/components/__tests__/ArchivePage.test.tsx +++ b/frontend/application/components/__tests__/ArchivePage.test.tsx @@ -321,4 +321,29 @@ describe("ArchivePage Component", () => { expect(mockPush).toHaveBeenCalledWith("/shop"); }); + + it("renders exactly one card instance per product in list viewMode to avoid DOM duplication across breakpoints", async () => { + const singleProduct = { + id: "prod-single-1", + slug: "canina-prod-single", + name: "محصول آزمایشی یکتا", + nameFa: "محصول آزمایشی یکتا", + priceValue: 120000, + stock: 10, + categorySlug: "joints", + images: ["/test.png"], + symptoms: [], + main_ingredients: [], + }; + + render(); + + await waitFor(() => { + expect(screen.getAllByText("محصول آزمایشی یکتا").length).toBeGreaterThan(0); + }); + + const productLinks = screen.getAllByRole("link", { name: /محصول آزمایشی یکتا/i }); + expect(productLinks).toHaveLength(1); + }); + }); From b4fdd7abb86e10fe8fb90c23c2a4c6d4c3e05a2a Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 15:27:07 +0000 Subject: [PATCH 33/49] fix(contact): add standard autocomplete, inputmode and attributes for contact inputs --- .../application/components/ContactFormClient.tsx | 7 ++++++- .../components/__tests__/ContactFormClient.test.tsx | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/frontend/application/components/ContactFormClient.tsx b/frontend/application/components/ContactFormClient.tsx index 43d83cd6..0cfbe5b3 100644 --- a/frontend/application/components/ContactFormClient.tsx +++ b/frontend/application/components/ContactFormClient.tsx @@ -150,7 +150,9 @@ export default function ContactFormClient() { setName(e.target.value)} className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl p-4 text-sm font-bold focus:outline-none focus:ring-2 focus:ring-canina-blue/20" @@ -162,7 +164,10 @@ export default function ContactFormClient() { setPhone(e.target.value)} className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl p-4 text-sm font-bold text-left focus:outline-none focus:ring-2 focus:ring-canina-blue/20" diff --git a/frontend/application/components/__tests__/ContactFormClient.test.tsx b/frontend/application/components/__tests__/ContactFormClient.test.tsx index 81c379e2..4d6c7403 100644 --- a/frontend/application/components/__tests__/ContactFormClient.test.tsx +++ b/frontend/application/components/__tests__/ContactFormClient.test.tsx @@ -131,4 +131,17 @@ describe("ContactFormClient Component", () => { expect(screen.getByText("خطا در سرور، لطفاً بعداً تلاش کنید.")).toBeInTheDocument(); }); }); + + it("provides standard autocomplete and inputmode attributes on contact inputs", () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: [] }); + render(); + + const nameInput = document.getElementById("contact-name"); + const phoneInput = document.getElementById("contact-phone"); + + expect(nameInput).toHaveAttribute("autocomplete", "name"); + expect(phoneInput).toHaveAttribute("autocomplete", "tel"); + expect(phoneInput).toHaveAttribute("inputmode", "tel"); + }); + }); From ea4d33b6bb9fffaf1751785992bef5876d2f1905 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 15:44:19 +0000 Subject: [PATCH 34/49] fix(mobile): ensure touch targets exceed 44x44px across bottom navigation --- .../application/components/MobileBottomNav.tsx | 8 ++++---- .../components/__tests__/MobileBottomNav.test.tsx | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/frontend/application/components/MobileBottomNav.tsx b/frontend/application/components/MobileBottomNav.tsx index 2025d21c..96d89a8d 100644 --- a/frontend/application/components/MobileBottomNav.tsx +++ b/frontend/application/components/MobileBottomNav.tsx @@ -513,7 +513,7 @@ export default function MobileBottomNav({ {/* Tab 1: Home */} @@ -528,7 +528,7 @@ export default function MobileBottomNav({ if (activeSheet === "menu") closeSheet(); else openSheet("menu"); }} - className={`flex flex-col items-center justify-center flex-1 py-1 transition-all ${ + className={`flex flex-col items-center justify-center flex-1 min-h-[48px] py-1 transition-all ${ activeSheet === "menu" ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700" }`} > @@ -543,7 +543,7 @@ export default function MobileBottomNav({ if (activeSheet === "shop") closeSheet(); else openSheet("shop"); }} - className={`flex flex-col items-center justify-center flex-1 py-1 transition-all ${ + className={`flex flex-col items-center justify-center flex-1 min-h-[48px] py-1 transition-all ${ isShopActive ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700" }`} > @@ -576,7 +576,7 @@ export default function MobileBottomNav({ , + }, +})); + +vi.mock('../SafeImage', () => ({ + default: ({ alt, className }: { alt: string; className?: string }) => ( + {alt} + ), +})); + +vi.mock('sonner', () => ({ + toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() }, +})); + +vi.mock('next/navigation', () => ({ + useRouter: () => ({ back: vi.fn(), push: vi.fn() }), + useSearchParams: () => new URLSearchParams(), +})); + +vi.mock('../../lib/store/settingsStore', () => ({ + useSettingsStore: Object.assign( + (fn: (s: any) => any) => + fn({ + getText: () => '', + getBoolean: () => true, + }), + { + getState: () => ({ + getText: () => '', + getBoolean: () => true, + }), + } + ), +})); + +vi.mock('../../lib/services/productService', () => ({ + productService: { getProducts: vi.fn().mockResolvedValue([]) }, +})); + +vi.mock('../../lib/services/api', () => ({ + default: { get: vi.fn(), post: vi.fn() }, + BASE_DOMAIN: 'https://canina.ir', +})); + +describe('UX-24 Semantic H1 Single-Instance Tests', () => { + it('PetProfile renders exactly one semantic H1 across all view states', () => { + const { rerender, container } = render(); + let h1Elements = container.querySelectorAll('h1'); + expect(h1Elements.length).toBe(1); + expect(h1Elements[0].textContent).toContain('همدم‌های من'); + + rerender(); + h1Elements = container.querySelectorAll('h1'); + expect(h1Elements.length).toBe(1); + + rerender(); + h1Elements = container.querySelectorAll('h1'); + expect(h1Elements.length).toBe(1); + }); + + it('FlipbookCatalog renders exactly one H1 across toolbar and visible spreads', () => { + const { container: flipbookContainer } = render( + + ); + const flipbookH1s = flipbookContainer.querySelectorAll('h1'); + expect(flipbookH1s.length).toBe(1); + expect(flipbookH1s[0].textContent).toContain('کاتالوگ دیجیتال Canina Pharma'); + }); +}); diff --git a/frontend/application/components/catalog/CatalogPageSpread.tsx b/frontend/application/components/catalog/CatalogPageSpread.tsx index 5b2fd053..2922f082 100644 --- a/frontend/application/components/catalog/CatalogPageSpread.tsx +++ b/frontend/application/components/catalog/CatalogPageSpread.tsx @@ -140,9 +140,9 @@ export default function CatalogPageSpread({
-

+

کاتالوگ تخصصی و راهنمای بالینی مکمل‌های دارویی کنینا -

+

مرجع رسمی مکمل‌های درمانی حیوانات خانگی با استانداردهای داروسازی آلمان (GMP) و تاییدیه‌های ارتوپدی و پوست

From 92065cc7f20f5445b0a1ff245b680c1b69ef54d7 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 18:05:35 +0000 Subject: [PATCH 37/49] fix(ux-25): add persistent error state with retry and recovery to shop archive --- .../application/components/ArchivePage.tsx | 23 +++++++++++- .../components/__tests__/ArchivePage.test.tsx | 37 +++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index ec0233c5..ba31ea18 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -466,6 +466,7 @@ export default function ArchivePage({ const [activeSymptoms, setActiveSymptoms] = useState(initialSymptoms ? initialSymptoms.split(',') : []); const [searchQuery, setSearchQuery] = useState(initialSearch); const [isUpdating, setIsUpdating] = useState(false); + const [fetchError, setFetchError] = useState(null); const [filteredProducts, setFilteredProducts] = useState(() => orderProductsByAvailability(initialProducts)); const [sortBy, setSortBy] = useState("createdAt"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); @@ -574,6 +575,7 @@ export default function ArchivePage({ const didSkipInitialFetch = React.useRef(false); const fetchProducts = useCallback(async () => { + setFetchError(null); setIsUpdating(true); try { const res = await productService.getProducts({ @@ -595,7 +597,8 @@ export default function ArchivePage({ setVisibleCount(12); } catch (error) { console.error("Failed to fetch products:", error); - toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید."); + toast.error("خطا در دریافت لیست محصولات از سرور."); + setFetchError("خطا در برقراری ارتباط با سرور یا دریافت اطلاعات محصولات."); } finally { setIsUpdating(false); } @@ -1094,7 +1097,23 @@ export default function ArchivePage({ )} - {isUpdating ? ( + {fetchError ? ( +
+
+ +
+

خطا در دریافت اطلاعات محصولات

+

{fetchError}

+ +
+ ) : isUpdating ? ( viewMode === "list" ? (
{Array.from({ length: 8 }).map((_, i) => ( diff --git a/frontend/application/components/__tests__/ArchivePage.test.tsx b/frontend/application/components/__tests__/ArchivePage.test.tsx index 5243e288..cb779abc 100644 --- a/frontend/application/components/__tests__/ArchivePage.test.tsx +++ b/frontend/application/components/__tests__/ArchivePage.test.tsx @@ -346,4 +346,41 @@ describe("ArchivePage Component", () => { expect(productLinks).toHaveLength(1); }); + + it("renders error state when productService fails and recovers on retry", async () => { + vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error("Network Error")); + + render(); + + await waitFor(() => { + expect(screen.getByTestId("shop-fetch-error")).toBeInTheDocument(); + expect(screen.getByText("خطا در دریافت اطلاعات محصولات")).toBeInTheDocument(); + expect(screen.getByText("خطا در برقراری ارتباط با سرور یا دریافت اطلاعات محصولات.")).toBeInTheDocument(); + }); + + // Mock recovery on retry + vi.mocked(productService.getProducts).mockResolvedValueOnce({ + data: [ + { + id: "prod-recovered", + name: "محصول بازیابی شده", + nameFa: "محصول بازیابی شده", + priceValue: 150000, + stock: 5, + categorySlug: "joints", + images: ["/test.png"], + symptoms: [], + main_ingredients: [], + } as any, + ], + } as any); + + const retryButton = screen.getByRole("button", { name: /تلاش مجدد/i }); + fireEvent.click(retryButton); + + await waitFor(() => { + expect(screen.queryByTestId("shop-fetch-error")).not.toBeInTheDocument(); + expect(screen.getByText("محصول بازیابی شده")).toBeInTheDocument(); + }); + }); }); From 21f7768ccefd57b16e0914eef9786abe40e25cb6 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 18:15:42 +0000 Subject: [PATCH 38/49] feat(ux-26): implement real shop pagination with deep-link page support and regression test --- frontend/application/app/shop/page.tsx | 3 + .../application/components/ArchivePage.tsx | 92 ++++++++++++++----- .../components/__tests__/ArchivePage.test.tsx | 42 ++++++++- 3 files changed, 115 insertions(+), 22 deletions(-) diff --git a/frontend/application/app/shop/page.tsx b/frontend/application/app/shop/page.tsx index ac11b984..154b8ce5 100644 --- a/frontend/application/app/shop/page.tsx +++ b/frontend/application/app/shop/page.tsx @@ -43,6 +43,8 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [ const symptomsParam = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : ""; const symptomSingle = typeof resolvedParams.symptom === 'string' ? resolvedParams.symptom : ""; const symptoms = symptomsParam || (symptomSingle ? symptomSingle : ""); + const pageParam = typeof resolvedParams.page === "string" ? parseInt(resolvedParams.page, 10) : 1; + const initialPage = isNaN(pageParam) || pageParam < 1 ? 1 : pageParam; const { data: initialProducts } = await productService.getProducts({ category, petType: petType as PetType | "all", query: search, symptom: symptomSingle, limit: 999 }); return ( @@ -52,6 +54,7 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [ initialPetType={petType} initialSymptoms={symptoms} initialProducts={initialProducts} + initialPage={initialPage} /> ); } diff --git a/frontend/application/components/ArchivePage.tsx b/frontend/application/components/ArchivePage.tsx index ba31ea18..04e11913 100644 --- a/frontend/application/components/ArchivePage.tsx +++ b/frontend/application/components/ArchivePage.tsx @@ -451,13 +451,17 @@ export default function ArchivePage({ initialSearch = "", initialPetType = "all", initialSymptoms = "", - initialProducts = [] + initialProducts = [], + initialPage = 1, + initialLimit = 12 }: { initialCategory?: string, initialSearch?: string, initialPetType?: string, initialSymptoms?: string, - initialProducts?: Product[] + initialProducts?: Product[], + initialPage?: number, + initialLimit?: number }) { const router = useRouter(); const getText = useSettingsStore(state => state.getText); @@ -471,7 +475,8 @@ export default function ArchivePage({ const [sortBy, setSortBy] = useState("createdAt"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [viewMode, setViewMode] = useState<"list" | "grid">("list"); - const [visibleCount, setVisibleCount] = useState(12); + const [currentPage, setCurrentPage] = useState(() => Math.max(1, initialPage)); + const pageSize = Math.max(1, initialLimit); const [isMounted, setIsMounted] = useState(false); useEffect(() => { @@ -534,6 +539,7 @@ export default function ArchivePage({ } lastInitialPropsRef.current = { initialCategory, initialSearch, initialPetType, initialSymptoms }; + setCurrentPage(initialPage || 1); // Normalize Input const normSearch = (initialSearch || "").trim().toLowerCase(); @@ -553,7 +559,7 @@ export default function ArchivePage({ setSelectedPet((initialPetType as PetType) || "all"); setActiveSymptoms(initialSymptoms ? initialSymptoms.split(',').filter(Boolean) : []); } - setVisibleCount(12); + setCurrentPage(1); }, [initialCategory, initialSearch, initialPetType, initialSymptoms]); // Update URL Query Parameters @@ -563,13 +569,14 @@ export default function ArchivePage({ if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet); if (searchQuery) params.set('search', searchQuery); if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(',')); + if (currentPage > 1) params.set('page', String(currentPage)); const queryString = params.toString(); const newUrl = `/shop${queryString ? `?${queryString}` : ''}`; if (typeof window !== 'undefined' && window.location.pathname + window.location.search !== newUrl) { router.replace(newUrl, { scroll: false }); } - }, [selectedCategory, selectedPet, searchQuery, activeSymptoms, router]); + }, [selectedCategory, selectedPet, searchQuery, activeSymptoms, currentPage, router]); const hasInitialProducts = Boolean(initialProducts && initialProducts.length > 0); const didSkipInitialFetch = React.useRef(false); @@ -594,7 +601,7 @@ export default function ArchivePage({ } setFilteredProducts(orderProductsByAvailability(result)); - setVisibleCount(12); + setCurrentPage(1); } catch (error) { console.error("Failed to fetch products:", error); toast.error("خطا در دریافت لیست محصولات از سرور."); @@ -1131,8 +1138,11 @@ export default function ArchivePage({ <> {/* Progressive slice of products for optimal DOM density and mobile UX */} {(() => { - const slicedProducts = filteredProducts.slice(0, visibleCount); - const hasMore = visibleCount < filteredProducts.length; + const totalPages = Math.max(1, Math.ceil(filteredProducts.length / pageSize)); + const safeCurrentPage = Math.min(currentPage, totalPages); + const startIndex = (safeCurrentPage - 1) * pageSize; + const slicedProducts = filteredProducts.slice(startIndex, startIndex + pageSize); + const totalInStock = filteredProducts.filter(product => !isProductOutOfStock(product)).length; const totalOutOfStock = filteredProducts.filter(product => isProductOutOfStock(product)).length; @@ -1184,19 +1194,59 @@ export default function ArchivePage({ ))} - {hasMore && ( -
- -
+ {/* Pagination Controls */} + {totalPages > 1 && ( + )} ); diff --git a/frontend/application/components/__tests__/ArchivePage.test.tsx b/frontend/application/components/__tests__/ArchivePage.test.tsx index cb779abc..228d3f59 100644 --- a/frontend/application/components/__tests__/ArchivePage.test.tsx +++ b/frontend/application/components/__tests__/ArchivePage.test.tsx @@ -1,7 +1,7 @@ "use client"; import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; -import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react"; import ArchivePage, { orderProductsByAvailability } from "../ArchivePage"; import { productService } from "../../lib/services/productService"; import { useCartStore } from "../../lib/store/cartStore"; @@ -383,4 +383,44 @@ describe("ArchivePage Component", () => { expect(screen.getByText("محصول بازیابی شده")).toBeInTheDocument(); }); }); + + it("supports real pagination, page switching, deep-link initialPage, and resets to page 1 on filter change", async () => { + const mockProducts = Array.from({ length: 25 }, (_, i) => ({ + id: "prod-" + (i + 1), + name: "محصول تست " + (i + 1), + nameFa: "محصول تست " + (i + 1), + priceValue: 100000 + i * 1000, + stock: 10, + categorySlug: i % 2 === 0 ? "joints" : "immune", + images: ["/test.png"], + symptoms: [], + main_ingredients: [], + })); + + // Initial render at page 1 with pageSize 12 -> shows items 1 to 12 + const { rerender } = render(); + + expect(screen.getByTestId("shop-pagination")).toBeInTheDocument(); + expect(screen.getByText("محصول تست 1")).toBeInTheDocument(); + expect(screen.getByText("محصول تست 12")).toBeInTheDocument(); + expect(screen.queryByText("محصول تست 13")).not.toBeInTheDocument(); + + // Click next page button + const nextBtn = screen.getByRole("button", { name: "صفحه بعد" }); + fireEvent.click(nextBtn); + + // Now page 2 -> shows items 13 to 24 + expect(screen.getByText("محصول تست 13")).toBeInTheDocument(); + expect(screen.getByText("محصول تست 24")).toBeInTheDocument(); + expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument(); + + // Deep-link initialPage test: render directly at page 2 + cleanup(); + render(); + + await waitFor(() => { + expect(screen.getByText("محصول تست 13")).toBeInTheDocument(); + expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument(); + }); + }); }); From 23724df4e4cb3af732dccd2f5db6f402f5f7942c Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 18:27:21 +0000 Subject: [PATCH 39/49] feat(ux-27): normalize persian text, add persistent error/retry state and accessible aria empty-state to search --- .../components/SearchResultsPage.tsx | 152 ++++++++++-------- .../__tests__/SearchResultsPage.test.tsx | 25 +++ frontend/application/lib/utils.ts | 20 +++ 3 files changed, 132 insertions(+), 65 deletions(-) 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(); +} From c4d95762f89b91ac81f42d32ff0d5d25c27f77cc Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 18:33:29 +0000 Subject: [PATCH 40/49] test(ux-28): add integration test verifying singleton authmodal and cartdrawer in shell layout --- .../application/app/ClientLayout.test.tsx | 194 ++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 frontend/application/app/ClientLayout.test.tsx diff --git a/frontend/application/app/ClientLayout.test.tsx b/frontend/application/app/ClientLayout.test.tsx new file mode 100644 index 00000000..7c550eea --- /dev/null +++ b/frontend/application/app/ClientLayout.test.tsx @@ -0,0 +1,194 @@ +import React from "react"; +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { render, screen, cleanup } from "@testing-library/react"; + +// Mock next/navigation +let currentPathname = "/"; +const mockRouter = { + push: vi.fn(), + replace: vi.fn(), + back: vi.fn(), + prefetch: vi.fn(), +}; + +vi.mock("next/navigation", () => ({ + usePathname: () => currentPathname, + useRouter: () => mockRouter, + useSearchParams: () => new URLSearchParams(), +})); + +// Mock dynamic components to render test identifiers +vi.mock("next/dynamic", () => ({ + default: (loader: any) => { + const str = loader.toString(); + const isCart = str.includes("CartDrawer"); + const isAuth = str.includes("AuthModal"); + const isLogin = str.includes("LoginModal"); + return function MockDynamic(props: any) { + if (props.isOpen === false) return null; + if (isCart) return
; + if (isAuth) return
; + if (isLogin) return
; + return
; + }; + }, +})); + +vi.mock("../components/Header", () => ({ + default: () =>
Header
, +})); + +vi.mock("../components/Footer", () => ({ + default: () =>
Footer
, +})); + +vi.mock("../components/NetworkBanner", () => ({ + NetworkBanner: () => null, +})); + +vi.mock("../components/NavigationProgressBar", () => ({ + default: () => null, +})); + +vi.mock("../components/MobileBottomNav", () => ({ + default: () => null, +})); + +vi.mock("../components/PrescriptionUploadModal", () => ({ + default: () => null, +})); + +vi.mock("sonner", () => ({ + Toaster: () => null, + toast: { success: vi.fn(), error: vi.fn() }, +})); + +// Mock real components used inside page routes +vi.mock("../components/AuthModal", () => ({ + default: (props: any) => ( +
+ ), +})); + +vi.mock("../components/CartDrawer", () => ({ + default: (props: any) => ( +
+ ), +})); + +// Mock stores +const mockUserStoreState: any = { + isAuthModalOpen: false, + setAuthModalOpen: vi.fn(), + fetchProfile: vi.fn().mockResolvedValue({}), + user: null, +}; + +vi.mock("../lib/store/userStore", () => { + const store = (selector?: any) => (typeof selector === "function" ? selector(mockUserStoreState) : mockUserStoreState); + store.getState = () => mockUserStoreState; + return { useUserStore: store }; +}); + +const mockSettingsStoreState: any = { + fetchSettings: vi.fn().mockResolvedValue({}), + getText: vi.fn().mockReturnValue(""), + getBoolean: vi.fn().mockReturnValue(false), +}; + +vi.mock("../lib/store/settingsStore", () => { + const store = (selector?: any) => (typeof selector === "function" ? selector(mockSettingsStoreState) : mockSettingsStoreState); + store.getState = () => mockSettingsStoreState; + return { useSettingsStore: store }; +}); + +const mockUIStoreState: any = { + isCartOpen: false, + isLoginModalOpen: false, + isB2BPortalOpen: false, + advisorData: null, + setCartOpen: vi.fn(), + setLoginModalOpen: vi.fn(), + setB2BPortalOpen: vi.fn(), + clearAdvisorData: vi.fn(), +}; + +vi.mock("../lib/store/uiStore", () => { + const store = (selector?: any) => (typeof selector === "function" ? selector(mockUIStoreState) : mockUIStoreState); + store.getState = () => mockUIStoreState; + return { useUIStore: store }; +}); + +import ClientLayout from "../app/ClientLayout"; +import LoginPage from "../app/login/page"; +import CartPage from "../app/cart/page"; + +describe("ClientLayout Shell & Singleton Modals Integration (UX-28)", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockUserStoreState.isAuthModalOpen = false; + mockUIStoreState.isCartOpen = false; + currentPathname = "/"; + }); + + afterEach(() => { + cleanup(); + }); + + it("renders singleton CartDrawer and AuthModal in ClientLayout on normal routes when opened", () => { + mockUIStoreState.isCartOpen = true; + mockUserStoreState.isAuthModalOpen = true; + + render( + +
Content
+
+ ); + + // On normal route, Header, Footer, and active drawers are rendered + expect(screen.getByTestId("shell-header")).toBeTruthy(); + expect(screen.getByTestId("shell-footer")).toBeTruthy(); + expect(screen.getByTestId("shell-cart-drawer")).toBeTruthy(); + expect(screen.getByTestId("shell-auth-modal")).toBeTruthy(); + }); + + it("ensures no duplicate CartDrawer exists when user visits /cart utility route", () => { + currentPathname = "/cart"; + mockUIStoreState.isCartOpen = true; // Even if UI store flag was left open + + const { container } = render( + + + + ); + + // Footer and shell-level CartDrawer must be suppressed on /cart + expect(screen.queryByTestId("shell-footer")).toBeNull(); + + // Page level cart drawer is present + expect(screen.getByTestId("page-cart-drawer")).toBeTruthy(); + + // Shell level dynamic cart drawer is NOT rendered because isUtilityRoute is true + expect(screen.queryByTestId("shell-cart-drawer")).toBeNull(); + }); + + it("ensures no duplicate AuthModal exists when user visits /login utility route", () => { + currentPathname = "/login"; + mockUserStoreState.isAuthModalOpen = true; // Even if userStore auth flag was left open + + const { container } = render( + + + + ); + + // Footer and shell-level AuthModal must be suppressed on /login + expect(screen.queryByTestId("shell-footer")).toBeNull(); + + // Page level auth modal is present + expect(screen.getByTestId("page-auth-modal")).toBeTruthy(); + + // Shell level dynamic auth modal is NOT rendered because isUtilityRoute is true + expect(screen.queryByTestId("shell-auth-modal")).toBeNull(); + }); +}); From 6d0dea07f8bb6f600bc862a0534620e11996bc59 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 18:37:26 +0000 Subject: [PATCH 41/49] test(ux-29): add responsive and semantic tests for login, cart, profile, videos and smart-advisor routes --- .../app/responsive-routes.test.tsx | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 frontend/application/app/responsive-routes.test.tsx diff --git a/frontend/application/app/responsive-routes.test.tsx b/frontend/application/app/responsive-routes.test.tsx new file mode 100644 index 00000000..feccd153 --- /dev/null +++ b/frontend/application/app/responsive-routes.test.tsx @@ -0,0 +1,95 @@ +import React from "react"; +import { describe, it, expect, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; + +// Mock next/navigation +vi.mock("next/navigation", () => ({ + usePathname: () => "/login", + useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }), + useSearchParams: () => new URLSearchParams(), +})); + +vi.mock("next/link", () => ({ + default: ({ children, href, ...props }: any) => {children}, +})); + +vi.mock("next/image", () => ({ + default: (props: any) => , +})); + +// Mock sub-components with exact path matching +vi.mock("../components/AuthModal", () => ({ + default: ({ isOpen, onClose }: any) => ( +
+ +
+ ), +})); + +vi.mock("../components/CartDrawer", () => ({ + default: ({ isOpen, onCheckout, onShopNavigate }: any) => ( +
+ + +
+ ), +})); + +vi.mock("../components/PetProfile", () => ({ + default: () =>
Pet Profile
, +})); + +vi.mock("../components/VideosPage", () => ({ + default: ({ initialVideos }: any) => ( +
Videos: {initialVideos?.length || 0}
+ ), +})); + +vi.mock("../components/SmartAdvisor", () => ({ + default: () =>
Smart Advisor
, +})); + +import LoginPage from "./login/page"; +import CartPage from "./cart/page"; +import ProfilePage from "./profile/page"; +import VideosPage from "./videos/page"; +import SmartAdvisorPage from "./smart-advisor/page"; + +describe("Lightweight Utility Routes and Responsive Layouts (UX-29)", () => { + it("renders LoginPage with minimal semantic wrapper and single accessible h1", () => { + const { container } = render(); + const h1 = screen.getByRole("heading", { level: 1 }); + expect(h1.textContent).toContain("ورود یا ثبت‌نام"); + expect(screen.getByTestId("auth-modal")).toBeTruthy(); + const main = container.querySelector("main"); + expect(main).not.toBeNull(); + expect(main?.getAttribute("dir")).toBe("rtl"); + }); + + it("renders CartPage with semantic main wrapper and single accessible h1", () => { + const { container } = render(); + const h1 = screen.getByRole("heading", { level: 1 }); + expect(h1.textContent).toContain("سبد خرید"); + expect(screen.getByTestId("cart-drawer")).toBeTruthy(); + const main = container.querySelector("main"); + expect(main).not.toBeNull(); + }); + + it("renders ProfilePage cleanly delegating to PetProfile component", () => { + render(); + expect(screen.getByTestId("pet-profile-component")).toBeTruthy(); + }); + + it("renders VideosPage cleanly passing initial videos dataset", async () => { + const component = await VideosPage(); + render(component); + expect(screen.getByTestId("videos-page-component")).toBeTruthy(); + }); + + it("renders SmartAdvisorPage with semantic breadcrumbs, h1 and advisor container", () => { + render(); + const h1 = screen.getByRole("heading", { level: 1 }); + expect(h1.textContent).toMatch(/مشاوره تخصصی و راهنمای/); + expect(screen.getByTestId("smart-advisor-component")).toBeTruthy(); + }); +}); From f5c970f82e7dc558312c669b0c2e2aa520d3c827 Mon Sep 17 00:00:00 2001 From: devops Date: Sat, 17 Oct 2026 18:43:34 +0000 Subject: [PATCH 42/49] feat(ux-30): ensure touch targets exceed 44px across CartDrawer, Wiki, Contact, Footer and MobileBottomNav with regression tests --- .../application/components/CartDrawer.tsx | 8 +- .../components/ContactFormClient.tsx | 2 +- frontend/application/components/Footer.tsx | 16 +- .../application/components/IngredientWiki.tsx | 4 +- .../components/MobileBottomNav.tsx | 2 +- .../__tests__/touch-targets.test.tsx | 141 ++++++++++++++++++ 6 files changed, 157 insertions(+), 16 deletions(-) create mode 100644 frontend/application/components/__tests__/touch-targets.test.tsx diff --git a/frontend/application/components/CartDrawer.tsx b/frontend/application/components/CartDrawer.tsx index 985236aa..715b2d8a 100644 --- a/frontend/application/components/CartDrawer.tsx +++ b/frontend/application/components/CartDrawer.tsx @@ -112,7 +112,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate

سبد خرید

-
@@ -152,7 +152,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate type="button" aria-label={`کاهش تعداد ${item.product.nameFa || item.product.name}`} onClick={() => updateQuantity(item.product.id, item.quantity - 1)} - className="p-1 hover:text-canina-blue transition-colors" + className="min-w-[44px] min-h-[44px] flex items-center justify-center p-1 hover:text-canina-blue transition-colors cursor-pointer" data-testid="minus-btn" > @@ -162,7 +162,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate type="button" aria-label={`افزایش تعداد ${item.product.nameFa || item.product.name}`} onClick={() => updateQuantity(item.product.id, item.quantity + 1)} - className="p-1 hover:text-canina-blue transition-colors" + className="min-w-[44px] min-h-[44px] flex items-center justify-center p-1 hover:text-canina-blue transition-colors cursor-pointer" data-testid="plus-btn" > @@ -173,7 +173,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate aria-label={`حذف ${item.product.nameFa || item.product.name} از سبد خرید`} data-testid="cart-item-delete-btn" onClick={() => setDeleteConfirmId(item.product.id)} - className="text-medical-gray-300 hover:text-red-500 transition-colors" + className="min-w-[44px] min-h-[44px] flex items-center justify-center text-medical-gray-300 hover:text-red-500 transition-colors cursor-pointer" > diff --git a/frontend/application/components/ContactFormClient.tsx b/frontend/application/components/ContactFormClient.tsx index 0cfbe5b3..ed17fff9 100644 --- a/frontend/application/components/ContactFormClient.tsx +++ b/frontend/application/components/ContactFormClient.tsx @@ -130,7 +130,7 @@ export default function ContactFormClient() {

diff --git a/frontend/application/components/Footer.tsx b/frontend/application/components/Footer.tsx index ae48514b..ec0b9dfb 100644 --- a/frontend/application/components/Footer.tsx +++ b/frontend/application/components/Footer.tsx @@ -74,12 +74,12 @@ export default function Footer({
{getText('contact_instagram', '') && ( - + )} {getText('contact_telegram', '') && ( - + )} @@ -121,12 +121,12 @@ export default function Footer({
{getText('contact_instagram', '') && ( - + )} {getText('contact_telegram', '') && ( - + )} @@ -209,7 +209,7 @@ export default function Footer({
-
+
@@ -218,7 +218,7 @@ export default function Footer({
-
+
@@ -229,7 +229,7 @@ export default function Footer({
-
+
@@ -242,7 +242,7 @@ export default function Footer({ {/* Trust and Verification Banner */}
-
+
diff --git a/frontend/application/components/IngredientWiki.tsx b/frontend/application/components/IngredientWiki.tsx index d6353f7f..c8afe3e9 100644 --- a/frontend/application/components/IngredientWiki.tsx +++ b/frontend/application/components/IngredientWiki.tsx @@ -175,7 +175,7 @@ export default function IngredientWiki() {