diff --git a/frontend/application/components/ArticleContentRenderer.tsx b/frontend/application/components/ArticleContentRenderer.tsx new file mode 100644 index 00000000..b4630a12 --- /dev/null +++ b/frontend/application/components/ArticleContentRenderer.tsx @@ -0,0 +1,120 @@ +"use client"; +import React, { useMemo } from "react"; +import ArticleProductCard from "./ArticleProductCard"; + +interface ArticleContentRendererProps { + contentHtml: string; + relatedProducts?: any[]; +} + +export function parseContentWithProducts( + html: string, + relatedProducts: any[] = [] +): Array<{ type: "html" | "product"; content?: string; product?: any }> { + if (!html) return []; + + // Match tags like [product slug_or_id], [محصول slug_or_id] + // or HTML elements like
+ // or + const markerRegex = /(?:]*>\s*)?(?:\[(?:product|محصول)\s+([a-zA-Z0-9_-]+)\]|<(?:div|span)[^>]*data-product=["']([a-zA-Z0-9_-]+)["'][^>]*>(?:<\/(?:div|span)>)?)(?:\s*<\/p>)?/gi; + + const parts: Array<{ type: "html" | "product"; content?: string; product?: any }> = []; + let lastIndex = 0; + let match: RegExpExecArray | null; + + // Build product lookup map (by slug, id) + const productMap = new Map(); + for (const prod of relatedProducts) { + if (prod.slug) productMap.set(String(prod.slug).toLowerCase(), prod); + if (prod.id) productMap.set(String(prod.id).toLowerCase(), prod); + } + + while ((match = markerRegex.exec(html)) !== null) { + const matchedText = match[0]; + const identifier = (match[1] || match[2] || "").trim(); + const startIndex = match.index; + + // Push preceding HTML + if (startIndex > lastIndex) { + const htmlSlice = html.slice(lastIndex, startIndex); + if (htmlSlice.trim()) { + parts.push({ type: "html", content: htmlSlice }); + } + } + + const matchedProduct = productMap.get(identifier.toLowerCase()); + if (matchedProduct) { + parts.push({ type: "product", product: matchedProduct }); + } else { + // If product not found in map, attempt fallback with slug info + parts.push({ + type: "product", + product: { + id: identifier, + slug: identifier, + nameFa: `محصول ${identifier}`, + category: "مکمل دارویی کنینا", + }, + }); + } + + lastIndex = startIndex + matchedText.length; + } + + // Push remaining HTML + if (lastIndex < html.length) { + const trailingHtml = html.slice(lastIndex); + if (trailingHtml.trim()) { + parts.push({ type: "html", content: trailingHtml }); + } + } + + if (parts.length === 0 && html) { + parts.push({ type: "html", content: html }); + } + + return parts; +} + +export default function ArticleContentRenderer({ + contentHtml, + relatedProducts = [], +}: ArticleContentRendererProps) { + const sections = useMemo( + () => parseContentWithProducts(contentHtml, relatedProducts), + [contentHtml, relatedProducts] + ); + + // If there are no product cards inserted, preserve the exact original markup structure + const hasProducts = sections.some((s) => s.type === "product"); + if (!hasProducts) { + return ( +
+ ); + } + + return ( +
+ {sections.map((section, idx) => { + if (section.type === "product" && section.product) { + return ( + + ); + } + return ( +
+ ); + })} +
+ ); +} diff --git a/frontend/application/components/ArticleProductCard.tsx b/frontend/application/components/ArticleProductCard.tsx new file mode 100644 index 00000000..d6cde1e3 --- /dev/null +++ b/frontend/application/components/ArticleProductCard.tsx @@ -0,0 +1,202 @@ +"use client"; +import React, { useState } from "react"; +import Link from "next/link"; +import { ShoppingCart, Check, ExternalLink, ShieldCheck } from "lucide-react"; +import SafeImage from "./SafeImage"; +import { useCartStore } from "../lib/store/cartStore"; + +export interface ArticleProductCardProps { + product: { + id: string; + slug?: string; + nameFa: string; + nameEn?: string; + description?: string; + category?: { name: string; slug?: string } | string; + categorySlug?: string; + imageUrl?: string; + images?: string[]; + priceValue?: number; + priceDisplay?: string; + prices?: { price: number; volume?: string }[]; + stock?: number; + stockStatus?: string; + isOriginal?: boolean; + madeInGermany?: boolean; + rating?: number; + }; + compact?: boolean; +} + +export default function ArticleProductCard({ product, compact = false }: ArticleProductCardProps) { + const [isAdded, setIsAdded] = useState(false); + const addItem = useCartStore((state) => state.addItem); + + if (!product || !product.nameFa) return null; + + const productUrl = `/shop/${encodeURIComponent(product.slug || product.id)}`; + const imageSrc = + product.imageUrl || + (Array.isArray(product.images) && product.images[0]) || + "/assets/images/canina-product-placeholder.png"; + + const categoryName = + typeof product.category === "string" + ? product.category + : product.category?.name || product.categorySlug || "مکمل تخصصی کنینا"; + + // Price calculation + const rawPrice = + product.priceValue || + (Array.isArray(product.prices) && product.prices[0]?.price) || + 0; + + const formattedPrice = + product.priceDisplay || + (rawPrice > 0 ? `${Number(rawPrice).toLocaleString("fa-IR")} تومان` : "تماس بگیرید"); + + const isOutOfStock = + product.stockStatus === "OUT_OF_STOCK" || + product.stockStatus === "DISCONTINUED" || + (typeof product.stock === "number" && product.stock <= 0); + + const handleAddToCart = (e: React.MouseEvent) => { + e.preventDefault(); + e.stopPropagation(); + if (isOutOfStock) return; + + // Adapt to CartStore Product shape + const storeProduct: any = { + id: product.id, + slug: product.slug || product.id, + nameFa: product.nameFa, + nameEn: product.nameEn || "", + category: typeof product.category === "string" ? { name: product.category, slug: "" } : product.category, + priceValue: rawPrice, + images: [imageSrc], + stock: product.stock ?? 99, + stockStatus: product.stockStatus || "IN_STOCK", + }; + + addItem(storeProduct, 1); + setIsAdded(true); + setTimeout(() => { + setIsAdded(false); + }, 2500); + }; + + const buttonAriaLabel = isOutOfStock + ? "ناموجود" + : isAdded + ? "به سبد اضافه شد" + : "افزودن به سبد خرید"; + + return ( +
+
+ {/* Product Image Thumbnail */} + + + {/* Made In Germany Floating Pill on Image */} +
+ + اصل آلمان +
+ + + {/* Product Details */} +
+
+
+ + {categoryName} + +
+ + ضمانت ۱۰۰٪ اصالت آلمان +
+
+ + +

+ {product.nameFa} +

+ {product.nameEn && ( + + {product.nameEn} + + )} + + + {product.description && ( +

+ {product.description} +

+ )} +
+ + {/* Price & Action Button Row */} +
+
+ قیمت مصرف‌کننده: + + {formattedPrice} + +
+ +
+ + مشاهده مشخصات + + + + +
+
+
+
+
+ ); +} diff --git a/frontend/application/components/BlogPostClient.tsx b/frontend/application/components/BlogPostClient.tsx index 03e68985..9d16fa84 100644 --- a/frontend/application/components/BlogPostClient.tsx +++ b/frontend/application/components/BlogPostClient.tsx @@ -18,6 +18,8 @@ import { import Link from 'next/link'; import SafeImage from "./SafeImage"; import api from "../lib/services/api"; +import ArticleContentRenderer from "./ArticleContentRenderer"; + interface BlogPostClientProps { blog: any; @@ -173,10 +175,10 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
)} - {/* Main Rich Content HTML Renderer */} -
{/* Tags Chip Footer */} diff --git a/frontend/application/components/__tests__/ArticleContentRenderer.test.tsx b/frontend/application/components/__tests__/ArticleContentRenderer.test.tsx new file mode 100644 index 00000000..c7d70f20 --- /dev/null +++ b/frontend/application/components/__tests__/ArticleContentRenderer.test.tsx @@ -0,0 +1,84 @@ +import React from "react"; +import { describe, it, expect, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; +import ArticleContentRenderer, { parseContentWithProducts } from "../ArticleContentRenderer"; + +// Mock SafeImage +vi.mock("../SafeImage", () => ({ + default: ({ src, alt, className }: { src: string; alt: string; className?: string }) => ( + {alt} + ), +})); + +// Mock useCartStore +vi.mock("../../lib/store/cartStore", () => ({ + useCartStore: (selector?: any) => { + const state = { items: [], addItem: vi.fn() }; + return typeof selector === "function" ? selector(state) : state; + }, +})); + +const mockProducts = [ + { + id: "prod-1", + slug: "canhydrox-gag", + nameFa: "قرص کانی‌هیدروکس GAG", + category: { name: "مفاصل" }, + priceValue: 2450000, + }, + { + id: "prod-2", + slug: "petvital-derm-caps", + nameFa: "کپسول درم پت‌ویتال", + category: { name: "پوست و مو" }, + priceValue: 1200000, + }, +]; + +describe("ArticleContentRenderer and parseContentWithProducts", () => { + it("parses [product slug] markers in content into rich product items", () => { + const html = ` +

درمان مشکلات حرکتی در نژادهای بزرگ:

+

[product canhydrox-gag]

+

همچنین برای درخشش مو:

+

[محصول petvital-derm-caps]

+ `; + + const parsed = parseContentWithProducts(html, mockProducts); + expect(parsed.length).toBe(4); + expect(parsed[0].type).toBe("html"); + expect(parsed[1].type).toBe("product"); + expect(parsed[1].product?.nameFa).toBe("قرص کانی‌هیدروکس GAG"); + expect(parsed[2].type).toBe("html"); + expect(parsed[3].type).toBe("product"); + expect(parsed[3].product?.nameFa).toBe("کپسول درم پت‌ویتال"); + }); + + it("renders in-article product cards inside rendered HTML body", () => { + const html = ` +

اگر سگ شما دچار درد مفاصل است، این مکمل را تهیه نمایید:

+

[product canhydrox-gag]

+

پس از ۲ هفته بهبود قابل مشاهده خواهد بود.

+ `; + + render(); + + expect(screen.getByText(/اگر سگ شما دچار درد مفاصل است/)).toBeInTheDocument(); + expect(screen.getByTestId("article-product-card")).toBeInTheDocument(); + expect(screen.getByText("قرص کانی‌هیدروکس GAG")).toBeInTheDocument(); + expect(screen.getByText(/۲٬۴۵۰٬۰۰۰ تومان/)).toBeInTheDocument(); + expect(screen.getByText(/پس از ۲ هفته بهبود قابل مشاهده خواهد بود/)).toBeInTheDocument(); + }); + + it("handles data-product attribute markup as well", () => { + const html = ` +

توصیه ویژه:

+
+ `; + + render(); + + expect(screen.getByTestId("article-product-card")).toBeInTheDocument(); + expect(screen.getByText("قرص کانی‌هیدروکس GAG")).toBeInTheDocument(); + }); +}); diff --git a/frontend/application/components/__tests__/ArticleProductCard.test.tsx b/frontend/application/components/__tests__/ArticleProductCard.test.tsx new file mode 100644 index 00000000..0207c3ed --- /dev/null +++ b/frontend/application/components/__tests__/ArticleProductCard.test.tsx @@ -0,0 +1,101 @@ +import React from "react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { render, screen, fireEvent } from "@testing-library/react"; +import ArticleProductCard from "../ArticleProductCard"; +import { useCartStore } from "../../lib/store/cartStore"; + +// Mock SafeImage +vi.mock("../SafeImage", () => ({ + default: ({ src, alt, className }: { src: string; alt: string; className?: string }) => ( + {alt} + ), +})); + +// Mock useCartStore +const addItemMock = vi.fn(); +vi.mock("../../lib/store/cartStore", () => { + const mockStore = (selector?: any) => { + const state = { + items: [], + addItem: addItemMock, + }; + return typeof selector === "function" ? selector(state) : state; + }; + (mockStore as any).getState = () => ({ + items: [], + addItem: addItemMock, + }); + return { + useCartStore: mockStore, + }; +}); + +const mockProduct = { + id: "prod-canhydrox-1", + slug: "canhydrox-gag", + nameFa: "قرص کانی‌هیدروکس GAG کنینا", + nameEn: "Canhydrox GAG Tablets", + description: "ترمیم‌کننده قوی مفاصل، استخوان‌ها و رباط‌های سگ با صدف لب‌سبز اصل آلمان.", + category: { name: "مفاصل و استخوان" }, + imageUrl: "/assets/images/canhydrox.png", + priceValue: 2450000, + stock: 15, + stockStatus: "IN_STOCK", +}; + +describe("ArticleProductCard Component (CAT-P2-10)", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("renders product title, price, category, German origin badge, and thumbnail", () => { + render(); + + expect(screen.getByText("قرص کانی‌هیدروکس GAG کنینا")).toBeInTheDocument(); + expect(screen.getByText("Canhydrox GAG Tablets")).toBeInTheDocument(); + expect(screen.getByText("مفاصل و استخوان")).toBeInTheDocument(); + expect(screen.getByText("اصل آلمان")).toBeInTheDocument(); + expect(screen.getByText("ضمانت ۱۰۰٪ اصالت آلمان")).toBeInTheDocument(); + expect(screen.getByText(/۲٬۴۵۰٬۰۰۰ تومان/)).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "مشاهده مشخصات" })).toHaveAttribute( + "href", + "/shop/canhydrox-gag" + ); + }); + + it("triggers direct add to cart when buying button is clicked", () => { + render(); + + const buyBtn = screen.getByRole("button", { name: /افزودن به سبد خرید|خرید مستقیم/ }); + expect(buyBtn).toBeInTheDocument(); + + fireEvent.click(buyBtn); + + expect(addItemMock).toHaveBeenCalledWith( + expect.objectContaining({ + id: "prod-canhydrox-1", + slug: "canhydrox-gag", + nameFa: "قرص کانی‌هیدروکس GAG کنینا", + priceValue: 2450000, + }), + 1 + ); + + // Feedback state + expect(screen.getByText("به سبد اضافه شد")).toBeInTheDocument(); + }); + + it("disables add to cart button when product is out of stock", () => { + const outOfStockProduct = { + ...mockProduct, + stock: 0, + stockStatus: "OUT_OF_STOCK", + }; + + render(); + + const btn = screen.getByRole("button", { name: /ناموجود/ }); + expect(btn).toBeDisabled(); + expect(screen.getByText("ناموجود")).toBeInTheDocument(); + }); +}); diff --git a/frontend/application/components/__tests__/BlogPostClient.test.tsx b/frontend/application/components/__tests__/BlogPostClient.test.tsx index f4b6f412..8d30729c 100644 --- a/frontend/application/components/__tests__/BlogPostClient.test.tsx +++ b/frontend/application/components/__tests__/BlogPostClient.test.tsx @@ -143,7 +143,7 @@ describe("BlogPostClient Component", () => { // Related Products expect(screen.getByText("مکمل‌های مرتبط این مقاله")).toBeInTheDocument(); - expect(screen.getByText("قرص کانی‌هیدروکس GAG")).toBeInTheDocument(); + expect(screen.getAllByText("قرص کانی‌هیدروکس GAG").length).toBeGreaterThan(0); expect(screen.getByText(/۱٬۸۵۰٬۰۰۰ تومان/)).toBeInTheDocument(); // Related Blogs @@ -281,4 +281,22 @@ describe("BlogPostClient Component", () => { expect(article?.innerHTML).not.toContain(' { + const contentWithMarker = `

توضیحات مهم درباره آرتروز سگ‌ها:

[product canhydrox-gag-tablets]

توضیحات تکمیلی

`; + + render( + + ); + + expect(screen.getByTestId("article-product-card")).toBeInTheDocument(); + expect(screen.getAllByText("قرص کانی‌هیدروکس GAG").length).toBeGreaterThan(0); + expect(screen.getByText("ضمانت ۱۰۰٪ اصالت آلمان")).toBeInTheDocument(); + }); + });