diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 3b3d2804..207988c8 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -178,7 +178,7 @@ model Blog { slug String @unique @db.VarChar(200) content String @db.Text excerpt String? @db.Text - authorId String @map("author_id") @db.Uuid + authorId String? @map("author_id") @db.Uuid categoryId String? @map("category_id") @db.Uuid imageUrl String? @map("image_url") @db.Text imageAlt String? @map("image_alt") @db.VarChar(255) @@ -209,7 +209,7 @@ model Blog { createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() - author User @relation(fields: [authorId], references: [id]) + author User? @relation(fields: [authorId], references: [id]) category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull) tags BlogTag[] comments BlogComment[] diff --git a/backend/src/blogs/blogs.service.spec.ts b/backend/src/blogs/blogs.service.spec.ts index d617785e..df3628a8 100644 --- a/backend/src/blogs/blogs.service.spec.ts +++ b/backend/src/blogs/blogs.service.spec.ts @@ -40,7 +40,7 @@ describe("BlogsService", () => { describe("findAll", () => { it("should query published blogs with pagination", async () => { const blogs = [ - { id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" }, + { id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED", author: null }, ]; mockPrisma.blog.findMany.mockResolvedValue(blogs); mockPrisma.blog.count.mockResolvedValue(1); @@ -49,6 +49,8 @@ describe("BlogsService", () => { expect(mockPrisma.blog.findMany).toHaveBeenCalled(); expect(result.data).toEqual(blogs); expect(result.meta.total).toBe(1); + const query = mockPrisma.blog.findMany.mock.calls[0][0]; + expect(query.include.author).toBeUndefined(); }); it("should filter by categorySlug and search term", async () => { diff --git a/backend/src/blogs/blogs.service.ts b/backend/src/blogs/blogs.service.ts index 370c9758..edcbf302 100644 --- a/backend/src/blogs/blogs.service.ts +++ b/backend/src/blogs/blogs.service.ts @@ -68,9 +68,6 @@ export class BlogsService { [sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder, }, include: { - author: { - select: { firstName: true, lastName: true }, - }, category: { select: { id: true, name: true, slug: true }, }, @@ -110,7 +107,6 @@ export class BlogsService { take: 4, orderBy: { publishedAt: "desc" }, include: { - author: { select: { firstName: true, lastName: true } }, category: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } }, _count: { select: { comments: { where: { status: "APPROVED" } } } }, @@ -127,7 +123,6 @@ export class BlogsService { take: 4, orderBy: { publishedAt: "desc" }, include: { - author: { select: { firstName: true, lastName: true } }, category: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } }, _count: { select: { comments: { where: { status: "APPROVED" } } } }, @@ -163,9 +158,6 @@ export class BlogsService { ], }, include: { - author: { - select: { firstName: true, lastName: true }, - }, category: { select: { id: true, name: true, slug: true }, }, 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/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(); + }); +}); diff --git a/frontend/application/app/ClientLayout.tsx b/frontend/application/app/ClientLayout.tsx index fae81a50..5d8fa079 100644 --- a/frontend/application/app/ClientLayout.tsx +++ b/frontend/application/app/ClientLayout.tsx @@ -39,9 +39,10 @@ export default function ClientLayout({ children }: { children: React.ReactNode } const setB2BPortalOpen = useUIStore((state) => state.setB2BPortalOpen); const clearAdvisorData = useUIStore((state) => state.clearAdvisorData); const [isPrescriptionModalOpen, setIsPrescriptionModalOpen] = useState(false); - + const pathname = usePathname(); const router = useRouter(); + const isUtilityRoute = pathname === "/login" || pathname === "/cart"; const fetchProfile = useUserStore((state) => state.fetchProfile); const role = useUserStore((state) => state.role); @@ -166,9 +167,9 @@ export default function ClientLayout({ children }: { children: React.ReactNode } <> -
setCartOpen(true)} onSearch={handleSearch} @@ -177,23 +178,23 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
{children}
-
- {/* Search & Category Filter Section */} -
-
+ {/* Search & Category Filter Section - Styled like /shop filters */} +
+
{/* Search Input */}
- + setSearchQuery(e.target.value)} - className="w-full pl-4 pr-11 py-3 rounded-2xl bg-medical-gray-50 border border-medical-gray-200 focus:border-canina-blue focus:bg-white text-xs sm:text-sm font-bold outline-none transition-all" + onChange={(e) => { + setSearchQuery(e.target.value); + setVisibleCount(6); + }} + className="w-full pl-4 pr-10 py-2.5 rounded-xl sm:rounded-2xl bg-medical-gray-50 border border-medical-gray-200 focus:border-canina-blue focus:bg-white text-xs sm:text-sm font-bold outline-none transition-all" /> {searchQuery && ( )}
+ {/* 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) => ( - 0 ? ( + <> +
+

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

+ + {toPersian(regularPosts.length)} مقاله + +
+ +
+ {slicedRegularPosts.map((post, idx) => ( + router.push(`/blog/${encodeURIComponent(post.slug || post.id)}`)} + className="bg-white rounded-2xl sm:rounded-[2.5rem] overflow-hidden border border-medical-gray-200 shadow-xs sm:shadow-lg group hover:shadow-xl hover:border-canina-blue/30 transition-all cursor-pointer flex flex-col justify-between" >
@@ -348,7 +404,7 @@ export default function BlogPage({ {(post.viewCount ?? 0).toLocaleString('fa-IR')}
-
+
@@ -374,7 +430,7 @@ export default function BlogPage({
-
+
{post.author} @@ -384,9 +440,25 @@ export default function BlogPage({
- + ))}
+ + {hasMore && ( +
+ +
+ )} + ) : (

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/BlogPreviewSection.tsx b/frontend/application/components/BlogPreviewSection.tsx index a2a72b2a..b45e3346 100644 --- a/frontend/application/components/BlogPreviewSection.tsx +++ b/frontend/application/components/BlogPreviewSection.tsx @@ -56,10 +56,10 @@ export default function BlogPreviewSection() { } return ( -
+
{/* Section Header */} -
+
diff --git a/frontend/application/components/CartDrawer.tsx b/frontend/application/components/CartDrawer.tsx index 137d8d79..715b2d8a 100644 --- a/frontend/application/components/CartDrawer.tsx +++ b/frontend/application/components/CartDrawer.tsx @@ -94,6 +94,9 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate className="fixed inset-0 bg-medical-gray-900/40 backdrop-blur-sm z-[100]" />
-

سبد خرید

+

سبد خرید

-
@@ -146,25 +149,31 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
{toPersian(item.quantity)}
diff --git a/frontend/application/components/CheckoutPage.tsx b/frontend/application/components/CheckoutPage.tsx index 81f79bb3..0ab25df5 100644 --- a/frontend/application/components/CheckoutPage.tsx +++ b/frontend/application/components/CheckoutPage.tsx @@ -369,7 +369,7 @@ export default function CheckoutPage() { / router.push('/shop')}>سبد خرید / - تسویه‌حساب و پرداخت +

تسویه‌حساب و پرداخت

diff --git a/frontend/application/components/ContactFormClient.tsx b/frontend/application/components/ContactFormClient.tsx index 43d83cd6..ed17fff9 100644 --- a/frontend/application/components/ContactFormClient.tsx +++ b/frontend/application/components/ContactFormClient.tsx @@ -130,7 +130,7 @@ export default function ContactFormClient() {

@@ -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/FeaturedProducts.tsx b/frontend/application/components/FeaturedProducts.tsx index e3ab0e28..4d2bdb7b 100644 --- a/frontend/application/components/FeaturedProducts.tsx +++ b/frontend/application/components/FeaturedProducts.tsx @@ -186,9 +186,9 @@ export default function FeaturedProducts() { }, []); return ( -
+
-
+
{getText("featured_badge", "بیشترین انتخاب توسط دامپزشکان")} diff --git a/frontend/application/components/Footer.tsx b/frontend/application/components/Footer.tsx index f591504d..ec0b9dfb 100644 --- a/frontend/application/components/Footer.tsx +++ b/frontend/application/components/Footer.tsx @@ -57,7 +57,7 @@ export default function Footer({ {showScroll && (
-
-
- - علم در خدمت کیفیت +
+
+ + علم در خدمت کیفیت
-

+

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

-

+ +

تمامی ترکیبات فعال و مکمل‌های به کار رفته در محصولات دارویی و مراقبتی 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" + 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" />
{/* Sugar-Free & Gluten-Free Medical Standards Banner */} -
-
- +
+
+ ۱۰۰٪ فاقد قند افزوده (Sugar-Free)
-
- +
+ مطابق استانداردهای دارویی و بالینی آلمان
@@ -218,18 +237,61 @@ 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; + 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 ( -
+

+ +

+ +
+ )} + + {/* 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} + + )} +
+
+ + ))} +
+
+ )} +
)} +
); diff --git a/frontend/application/components/SmartAdvisor.tsx b/frontend/application/components/SmartAdvisor.tsx index 5b3b0ea6..2a0e7d04 100644 --- a/frontend/application/components/SmartAdvisor.tsx +++ b/frontend/application/components/SmartAdvisor.tsx @@ -207,10 +207,10 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro }; return ( -
+
{/* Header Title */} -
+
-
+
@@ -256,13 +256,13 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro {getText('advisor_card1_desc', 'مکمل‌های دارویی کنینا غلیظ و تخصصی هستند؛ الگوریتم هوشمند ما بر اساس سن، وزن و جثه پت شما، دوز دقیق مصرفی روزانه را محاسبه می‌کند.')}

-
+
{getText('advisor_card1_footer', 'تضمین ایمنی و عدم اوردوز')}
-
+
@@ -276,13 +276,13 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro {getText('advisor_card2_desc', 'با انتخاب علائمی مثل لنگیدن یا ریزش مو، دقیق‌ترین راهکار مکمل آلمانی به همراه دلایل علمی به شما پیشنهاد می‌شود.')}

-
+
{getText('advisor_card2_footer', 'پیشنهاد هدفمند و تخصصی')}
-
+
@@ -296,7 +296,7 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro {getText('advisor_card3_desc', 'زمان‌های مصرف مکمل‌ها تنظیم شده و سیستم قبل از اتمام دوره درمانی، هشدار شارژ مجدد ارسال خواهد کرد.')}

-
+
{getText('advisor_card3_footer', 'تکمیل منظم دوره درمان')}
diff --git a/frontend/application/components/SupportChat.test.tsx b/frontend/application/components/SupportChat.test.tsx index 6e65b327..fec37395 100644 --- a/frontend/application/components/SupportChat.test.tsx +++ b/frontend/application/components/SupportChat.test.tsx @@ -6,24 +6,30 @@ import SupportChat from './SupportChat'; afterEach(() => { cleanup(); vi.restoreAllMocks(); localStorage.clear(); }); describe('support widget', () => { it('submits only message without scope tabs, renders text safely', async () => { - const fetcher=vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:''})} as Response); - render(); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); + const fetcher=vi.spyOn(globalThis,'fetch') + .mockResolvedValueOnce({ok:true,json:async()=>({enabled:true,label:'گفتگو با پشتیبان',icon:'chat'})} as Response) + .mockResolvedValueOnce({ok:true,json:async()=>({answer:''})} as Response); + render(); await waitFor(() => expect(screen.getByRole('button',{name:/گفتگو با پشتیبان/})).toBeTruthy()); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'مکمل سگ'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); await waitFor(()=>expect(screen.getByText('')).toBeTruthy()); - expect(JSON.parse(fetcher.mock.calls[0][1]!.body as string)).toEqual({message:'مکمل سگ'}); + expect(JSON.parse(fetcher.mock.calls[1][1]!.body as string)).toEqual({message:'مکمل سگ', entryPath:'/'}); expect(document.querySelector('script')).toBeNull(); for (const label of ['محصولات و عمومی','سفارش‌های من','کیف پول']) expect(screen.queryByRole('button',{name:label})).toBeNull(); }); it('does not expose upstream errors', async()=> { - vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:false,status:503,json:async()=>({message:'secret-provider'})} as Response); - render(); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); + vi.spyOn(globalThis,'fetch') + .mockResolvedValueOnce({ok:true,json:async()=>({enabled:true,label:'گفتگو با پشتیبان',icon:'chat'})} as Response) + .mockResolvedValueOnce({ok:false,status:503,json:async()=>({message:'secret-provider'})} as Response); + render(); await waitFor(() => expect(screen.getByRole('button',{name:/گفتگو با پشتیبان/})).toBeTruthy()); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'سلام'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); await waitFor(()=>expect(screen.getByText(/فعلاً در دسترس نیست/)).toBeTruthy()); expect(screen.queryByText('secret-provider')).toBeNull(); }); it('clears transcript on account transition', async()=> { localStorage.setItem('accessToken','alice'); - vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:'private Alice'})} as Response); - render(); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'کیف پول'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); + vi.spyOn(globalThis,'fetch') + .mockResolvedValueOnce({ok:true,json:async()=>({enabled:true,label:'گفتگو با پشتیبان',icon:'chat'})} as Response) + .mockResolvedValueOnce({ok:true,json:async()=>({answer:'private Alice'})} as Response); + render(); await waitFor(() => expect(screen.getByRole('button',{name:/گفتگو با پشتیبان/})).toBeTruthy()); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'کیف پول'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); await waitFor(()=>expect(screen.getByText('private Alice')).toBeTruthy()); localStorage.setItem('accessToken','bob'); fireEvent.focus(window); await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull()); diff --git a/frontend/application/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx index 4ac4ba33..1c272d9a 100644 --- a/frontend/application/components/SupportChat.tsx +++ b/frontend/application/components/SupportChat.tsx @@ -160,15 +160,41 @@ 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; const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon]; return ( -
diff --git a/frontend/application/components/__tests__/ArchivePage.test.tsx b/frontend/application/components/__tests__/ArchivePage.test.tsx index bd3e2da2..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"; @@ -144,6 +144,35 @@ 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(); + }); + + it("gives catalog search controls accessible names", () => { + render(); + + expect(screen.getAllByLabelText("جستجوی محصول").length).toBe(2); + expect(screen.getAllByLabelText("جستجوی علائم").length).toBeGreaterThan(0); + }); + + it("gives the catalog sort control an accessible name", () => { + render(); + + expect(screen.getByLabelText("مرتب‌سازی محصولات")).toBeTruthy(); + }); + + it("exposes a scroll affordance for the mobile filter row", () => { + render(); + + const filterRow = screen.getByTestId("mobile-catalog-filters"); + expect(filterRow).toHaveAttribute("aria-label", "فیلترهای محصولات"); + expect(screen.getByTestId("mobile-catalog-filters-edge")).toBeInTheDocument(); + }); + + beforeEach(() => { vi.clearAllMocks(); @@ -183,6 +212,19 @@ describe("ArchivePage Component", () => { }); }); + it("refreshes products from the mobile catalog search control", async () => { + render(); + + const mobileSearch = screen.getByTestId("shop-search-input-mobile"); + fireEvent.change(mobileSearch, { target: { value: "گلوکوزامین" } }); + + await waitFor(() => { + expect(productService.getProducts).toHaveBeenCalledWith( + expect.objectContaining({ query: "گلوکوزامین" }) + ); + }); + }); + it("filters products by search query input", async () => { render(); @@ -279,4 +321,106 @@ 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); + }); + + + 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(); + }); + }); + + 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(); + }); + }); }); 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(' { 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"); + }); + }); diff --git a/frontend/application/components/__tests__/Footer.test.tsx b/frontend/application/components/__tests__/Footer.test.tsx index 417c6daa..db334152 100644 --- a/frontend/application/components/__tests__/Footer.test.tsx +++ b/frontend/application/components/__tests__/Footer.test.tsx @@ -10,7 +10,7 @@ describe('Footer', () => { expect(screen.getByText('Canina')).toBeInTheDocument(); expect(screen.getByText('ایران')).toBeInTheDocument(); - expect(screen.getByText('تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹')).toBeInTheDocument(); + expect(screen.queryByText('تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹')).not.toBeInTheDocument(); }); it('renders navigation links properly', () => { @@ -25,4 +25,15 @@ describe('Footer', () => { const trustLink = screen.getByText('نمادهای اعتماد و مجوزهای رسمی').closest('a'); expect(trustLink).toHaveAttribute('href', '/trust-seals'); }); + it('keeps the mobile back-to-top control above the support launcher and bottom nav', () => { + render(
-

+

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

+

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

diff --git a/frontend/application/lib/sanitizeBlogHtml.ts b/frontend/application/lib/sanitizeBlogHtml.ts new file mode 100644 index 00000000..f808e359 --- /dev/null +++ b/frontend/application/lib/sanitizeBlogHtml.ts @@ -0,0 +1,32 @@ +import sanitizeHtml from "sanitize-html"; + +const allowedTags = Array.from(new Set([ + ...sanitizeHtml.defaults.allowedTags, + "img", "iframe", "figure", "figcaption", "table", "thead", "tbody", "tfoot", + "tr", "th", "td", "video", "source", "details", "summary", +])); + +export function sanitizeBlogHtml(content: unknown): string { + if (typeof content !== "string" || !content) return ""; + + return sanitizeHtml(content, { + allowedTags, + allowedAttributes: { + ...sanitizeHtml.defaults.allowedAttributes, + "*": ["class", "id", "dir", "lang", "title"], + a: ["href", "name", "target", "rel", "class", "title"], + img: ["src", "alt", "title", "width", "height", "loading", "class"], + iframe: ["src", "title", "width", "height", "allow", "allowfullscreen", "frameborder", "scrolling", "loading", "class"], + video: ["src", "poster", "controls", "preload", "width", "height", "class"], + source: ["src", "type"], + td: ["colspan", "rowspan", "class"], + th: ["colspan", "rowspan", "scope", "class"], + }, + allowedSchemes: ["http", "https", "mailto", "tel"], + allowedSchemesByTag: { img: ["http", "https", "data"] }, + allowedIframeHostnames: ["www.youtube.com", "youtube.com", "www.aparat.com", "aparat.com"], + transformTags: { + a: sanitizeHtml.simpleTransform("a", { rel: "noopener noreferrer" }, true), + }, + }); +} 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(); +} 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",