feat(blog): implement interactive in-article product cards (CAT-P2-10)
Deploy Canina / deploy (push) Successful in 2m15s

This commit is contained in:
devops committed 2026-10-18 06:37:05 +00:00
1 parent 69094a8646
commit bb81f2c944
6 files changed
+532 -5

No files matched your search

@@ -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 <div data-product="slug_or_id"></div>
// or <span data-product="slug_or_id"></span>
const markerRegex = /(?:<p[^>]*>\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<string, any>();
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 (
<div
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5 article-html-content"
dangerouslySetInnerHTML={{ __html: contentHtml }}
/>
);
}
return (
<div className="article-html-content space-y-6">
{sections.map((section, idx) => {
if (section.type === "product" && section.product) {
return (
<ArticleProductCard
key={`article-prod-${section.product.id || idx}`}
product={section.product}
/>
);
}
return (
<div
key={`article-html-${idx}`}
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5"
dangerouslySetInnerHTML={{ __html: section.content || "" }}
/>
);
})}
</div>
);
}
@@ -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 (
<div
data-testid="article-product-card"
className="my-6 sm:my-8 rounded-3xl bg-gradient-to-br from-white via-medical-gray-50/60 to-canina-blue/5 border-2 border-canina-blue/20 hover:border-canina-blue/40 shadow-lg hover:shadow-xl transition-all duration-300 overflow-hidden font-vazir text-right group not-prose"
dir="rtl"
>
<div className="p-4 sm:p-6 flex flex-col sm:flex-row items-center gap-4 sm:gap-6">
{/* Product Image Thumbnail */}
<Link
href={productUrl}
className="relative w-28 h-28 sm:w-32 sm:h-32 shrink-0 bg-white rounded-2xl p-2 border border-medical-gray-200/80 shadow-inner flex items-center justify-center overflow-hidden group-hover:scale-105 transition-transform duration-300"
aria-label={product.nameFa}
>
<SafeImage
src={imageSrc}
alt={product.nameFa}
className="w-full h-full"
imgClassName="w-full h-full object-contain"
/>
{/* Made In Germany Floating Pill on Image */}
<div className="absolute top-1.5 right-1.5 bg-black/80 backdrop-blur-xs text-white text-[9px] font-black px-1.5 py-0.5 rounded-md flex items-center gap-0.5 shadow-xs border border-white/20">
<span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
<span>اصل آلمان</span>
</div>
</Link>
{/* Product Details */}
<div className="flex-1 min-w-0 w-full flex flex-col justify-between h-full space-y-2">
<div>
<div className="flex items-center justify-between gap-2 mb-1">
<span className="text-[11px] font-bold text-canina-blue bg-canina-blue/10 px-2.5 py-0.5 rounded-full">
{categoryName}
</span>
<div className="flex items-center gap-1 text-[11px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-md border border-emerald-200/60">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
<span>ضمانت ۱۰۰٪ اصالت آلمان</span>
</div>
</div>
<Link href={productUrl} className="block group-hover:text-canina-blue transition-colors">
<h4 className="text-base sm:text-lg font-black text-medical-gray-900 leading-snug truncate">
{product.nameFa}
</h4>
{product.nameEn && (
<span className="text-xs font-mono font-medium text-medical-gray-400 block truncate mt-0.5 dir-ltr text-right">
{product.nameEn}
</span>
)}
</Link>
{product.description && (
<p className="text-xs text-medical-gray-600 line-clamp-2 mt-1 leading-relaxed">
{product.description}
</p>
)}
</div>
{/* Price & Action Button Row */}
<div className="flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-medical-gray-200/60">
<div>
<span className="text-[10px] text-medical-gray-400 block font-bold">قیمت مصرف‌کننده:</span>
<span className="text-sm sm:text-base font-black text-canina-blue font-mono">
{formattedPrice}
</span>
</div>
<div className="flex items-center gap-2">
<Link
href={productUrl}
className="px-3.5 py-2 bg-white hover:bg-medical-gray-100 text-medical-gray-700 text-xs font-bold rounded-xl border border-medical-gray-200 transition-colors flex items-center gap-1.5 shadow-2xs"
>
<span>مشاهده مشخصات</span>
<ExternalLink className="w-3.5 h-3.5" />
</Link>
<button
type="button"
onClick={handleAddToCart}
disabled={isOutOfStock}
aria-label={buttonAriaLabel}
className={`px-4 py-2 text-xs font-black rounded-xl transition-all duration-300 flex items-center gap-1.5 shadow-md cursor-pointer ${
isOutOfStock
? "bg-medical-gray-200 text-medical-gray-400 cursor-not-allowed"
: isAdded
? "bg-emerald-600 text-white hover:bg-emerald-700"
: "bg-canina-blue hover:bg-canina-blue/90 text-white active:scale-95"
}`}
>
{isAdded ? (
<>
<Check className="w-4 h-4 animate-in zoom-in-50" />
<span>به سبد اضافه شد</span>
</>
) : isOutOfStock ? (
<span>ناموجود</span>
) : (
<>
<ShoppingCart className="w-4 h-4" />
<span>خرید مستقیم</span>
</>
)}
</button>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -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
</div>
)}
{/* Main Rich Content HTML Renderer */}
<div
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5 article-html-content"
dangerouslySetInnerHTML={{ __html: sanitizedContent }}
{/* Main Rich Content HTML Renderer with In-Article Product Cards */}
<ArticleContentRenderer
contentHtml={sanitizedContent}
relatedProducts={relatedProducts}
/>
{/* Tags Chip Footer */}
@@ -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 }) => (
<img src={src} alt={alt} className={className} data-testid="safe-image" />
),
}));
// 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 = `
<p>درمان مشکلات حرکتی در نژادهای بزرگ:</p>
<p>[product canhydrox-gag]</p>
<p>همچنین برای درخشش مو:</p>
<p>[محصول petvital-derm-caps]</p>
`;
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 = `
<p>اگر سگ شما دچار درد مفاصل است، این مکمل را تهیه نمایید:</p>
<p>[product canhydrox-gag]</p>
<p>پس از ۲ هفته بهبود قابل مشاهده خواهد بود.</p>
`;
render(<ArticleContentRenderer contentHtml={html} relatedProducts={mockProducts} />);
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 = `
<p>توصیه ویژه:</p>
<div data-product="canhydrox-gag"></div>
`;
render(<ArticleContentRenderer contentHtml={html} relatedProducts={mockProducts} />);
expect(screen.getByTestId("article-product-card")).toBeInTheDocument();
expect(screen.getByText("قرص کانی‌هیدروکس GAG")).toBeInTheDocument();
});
});
@@ -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 }) => (
<img src={src} alt={alt} className={className} data-testid="safe-image" />
),
}));
// 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(<ArticleProductCard product={mockProduct} />);
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(<ArticleProductCard product={mockProduct} />);
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(<ArticleProductCard product={outOfStockProduct} />);
const btn = screen.getByRole("button", { name: /ناموجود/ });
expect(btn).toBeDisabled();
expect(screen.getByText("ناموجود")).toBeInTheDocument();
});
});
@@ -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('<script');
});
it("renders in-article product cards when content has product markers", () => {
const contentWithMarker = `<p>توضیحات مهم درباره آرتروز سگ‌ها:</p><p>[product canhydrox-gag-tablets]</p><p>توضیحات تکمیلی</p>`;
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={contentWithMarker}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
expect(screen.getByTestId("article-product-card")).toBeInTheDocument();
expect(screen.getAllByText("قرص کانی‌هیدروکس GAG").length).toBeGreaterThan(0);
expect(screen.getByText("ضمانت ۱۰۰٪ اصالت آلمان")).toBeInTheDocument();
});
});