Compare commits

..
Author SHA1 Message Date
devops d881dc491e feat: add advisor/contact flow tables and make Blog.authorId required
Deploy Canina / deploy (push) Successful in 25m44s
2026-11-05 08:33:30 +00:00
133 changed files with 1181 additions and 6081 deletions

No files matched your search

+2 -2
View File
@@ -178,7 +178,7 @@ model Blog {
slug String @unique @db.VarChar(200) slug String @unique @db.VarChar(200)
content String @db.Text content String @db.Text
excerpt 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 categoryId String? @map("category_id") @db.Uuid
imageUrl String? @map("image_url") @db.Text imageUrl String? @map("image_url") @db.Text
imageAlt String? @map("image_alt") @db.VarChar(255) imageAlt String? @map("image_alt") @db.VarChar(255)
@@ -209,7 +209,7 @@ model Blog {
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_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) category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
tags BlogTag[] tags BlogTag[]
comments BlogComment[] comments BlogComment[]
+3 -33
View File
@@ -57,7 +57,7 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" }) @ApiQuery({ name: "search", required: false, description: "جستجو" })
async getUsers(@Query() query: AdminQueryDto) { async getUsers(@Query() query: AdminQueryDto) {
const result = await this.adminService.getUsers(query); const result = await this.adminService.getUsers(query);
return result; return { success: true, ...result };
} }
@Post("users") @Post("users")
@@ -145,7 +145,7 @@ export class AdminController {
@ApiQuery({ name: "search", required: false, description: "جستجو" }) @ApiQuery({ name: "search", required: false, description: "جستجو" })
async getProducts(@Query() query: AdminQueryDto) { async getProducts(@Query() query: AdminQueryDto) {
const result = await this.adminService.getProducts(query); const result = await this.adminService.getProducts(query);
return result; return { success: true, ...result };
} }
@Post("products") @Post("products")
@@ -206,7 +206,7 @@ export class AdminController {
@ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" }) @ApiQuery({ name: "status", required: false, description: "فیلتر وضعیت" })
async getOrders(@Query() query: AdminQueryDto) { async getOrders(@Query() query: AdminQueryDto) {
const result = await this.adminService.getOrders(query); const result = await this.adminService.getOrders(query);
return result; return { success: true, ...result };
} }
@Get("orders/:id") @Get("orders/:id")
@@ -354,34 +354,4 @@ export class AdminController {
await this.settingsService.updateBulkUiTexts(body); await this.settingsService.updateBulkUiTexts(body);
return { success: true, data: body }; return { success: true, data: body };
} }
@Get("symptoms")
@ApiOperation({ summary: "لیست کامل علائم درمانی با صفحه‌بندی، جستجو و متادیتا" })
async getSymptoms(@Query() query: { page?: number; limit?: number; search?: string }) {
const res = await this.adminService.getSymptoms(query);
return res;
}
@Post("symptoms")
@ApiOperation({ summary: "افزودن علامت درمانی جدید" })
async createSymptom(@Body() body: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
const res = await this.adminService.createSymptom(body);
return { success: true, data: res };
}
@Put("symptoms/:id")
@ApiOperation({ summary: "ویرایش کامل علامت درمانی و متادیتاهای سئو" })
async updateSymptom(@Param("id") id: string, @Body() body: any) {
const res = await this.adminService.updateSymptom(id, body);
return { success: true, data: res };
}
@Delete("symptoms/:id")
@ApiOperation({ summary: "حذف علامت درمانی" })
async deleteSymptom(@Param("id") id: string) {
const res = await this.adminService.deleteSymptom(id);
return res;
}
} }
-160
View File
@@ -1869,164 +1869,4 @@ export class AdminService {
}; };
}); });
} }
async getSymptoms(params?: { page?: number; limit?: number; search?: string }) {
const page = Math.max(1, Number(params?.page) || 1);
const limit = Math.max(1, Number(params?.limit) || 20);
const offset = (page - 1) * limit;
const search = params?.search?.trim() || '';
let items: any[] = [];
let total = 0;
if (search) {
const searchPattern = `%${search}%`;
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern}
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s
WHERE s.name ILIKE ${searchPattern} OR s.slug ILIKE ${searchPattern};
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
} else {
const [listResult, countResult] = await Promise.all([
this.prisma.$queryRaw<any[]>`
SELECT
s.id,
s.name,
s.slug,
s.description,
s.meta_title as "metaTitle",
s.meta_description as "metaDescription",
s.keywords,
s.icon,
s.created_at as "createdAt",
COALESCE(COUNT(ps.product_id), 0)::int as "productsCount"
FROM symptoms s
LEFT JOIN product_symptoms ps ON ps.symptom = s.name
GROUP BY s.id, s.name, s.slug, s.description, s.meta_title, s.meta_description, s.keywords, s.icon, s.created_at
ORDER BY s.name ASC
LIMIT ${limit} OFFSET ${offset};
`,
this.prisma.$queryRaw<any[]>`
SELECT COUNT(*)::int as total
FROM symptoms s;
`,
]);
items = listResult;
total = countResult[0]?.total || 0;
}
const lastPage = Math.ceil(total / limit) || 1;
return {
data: items,
meta: {
page,
limit,
total,
lastPage,
},
};
}
async createSymptom(dto: { name: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
if (!dto.name?.trim()) throw new BadRequestException('نام علامت الزامی است');
const name = dto.name.trim();
const slug = dto.slug?.trim() || name.replace(/\s+/g, '-').toLowerCase();
return await this.prisma.$queryRawUnsafe(`
INSERT INTO symptoms (name, slug, description, meta_title, meta_description, keywords)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, name, slug, dto.description || '', dto.metaTitle || '', dto.metaDescription || '', dto.keywords || '');
}
async updateSymptom(id: string, dto: { name?: string; slug?: string; description?: string; metaTitle?: string; metaDescription?: string; keywords?: string }) {
// 1. Get existing symptom
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const oldName = existing[0].name;
const newName = dto.name?.trim() || oldName;
const newSlug = dto.slug?.trim() || existing[0].slug;
return await this.prisma.$transaction(async (tx) => {
// Update symptoms table
const updated = await tx.$queryRawUnsafe(`
UPDATE symptoms
SET
name = $2,
slug = $3,
description = $4,
meta_title = $5,
meta_description = $6,
keywords = $7,
updated_at = CURRENT_TIMESTAMP
WHERE id = $1::uuid
RETURNING id, name, slug, description, meta_title as "metaTitle", meta_description as "metaDescription", keywords;
`, id, newName, newSlug, dto.description ?? existing[0].description, dto.metaTitle ?? existing[0].meta_title, dto.metaDescription ?? existing[0].meta_description, dto.keywords ?? existing[0].keywords);
// If name changed, cascade update across product_symptoms & products JSON
if (oldName !== newName) {
await tx.$executeRaw`UPDATE product_symptoms SET symptom = ${newName} WHERE symptom = ${oldName};`;
await tx.$executeRaw`
UPDATE products
SET dosage_config = jsonb_set(
dosage_config,
'{symptoms}',
(
SELECT jsonb_agg(
CASE
WHEN elem::text = to_jsonb(${oldName}::text)::text THEN to_jsonb(${newName}::text)
ELSE elem
END
)
FROM jsonb_array_elements(dosage_config->'symptoms') AS elem
)
)
WHERE dosage_config ? 'symptoms'
AND dosage_config->'symptoms' @> to_jsonb(${oldName}::text);
`;
}
return updated;
});
}
async deleteSymptom(id: string) {
const existing = await this.prisma.$queryRawUnsafe<any[]>(`SELECT * FROM symptoms WHERE id = $1::uuid LIMIT 1`, id);
if (!existing || existing.length === 0) throw new NotFoundException('علامت یافت نشد');
const name = existing[0].name;
return await this.prisma.$transaction(async (tx) => {
// Delete join links
await tx.$executeRaw`DELETE FROM product_symptoms WHERE symptom = ${name};`;
// Delete symptom row
await tx.$queryRawUnsafe(`DELETE FROM symptoms WHERE id = $1::uuid;`, id);
return { success: true, message: `علامت «${name}» با موفقیت حذف شد` };
});
}
} }
+1 -1
View File
@@ -76,7 +76,7 @@ describe("MediaService", () => {
const validFile = { const validFile = {
originalname: "product-cover.webp", originalname: "product-cover.webp",
buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]), buffer: Buffer.from("dummy-image-bytes"),
mimetype: "image/webp", mimetype: "image/webp",
size: 5000, size: 5000,
} as any; } as any;
-22
View File
@@ -79,28 +79,6 @@ export class MediaService {
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).", "پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).",
); );
} }
// SEC-01: Magic number verification for uploaded binary content
const buf = file.buffer;
if (!buf || buf.length < 4) {
throw new BadRequestException("فایل نامعتبر یا آسیب‌دیده است.");
}
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
const isWebp =
buf.length >= 12 &&
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
throw new BadRequestException(
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
);
}
const filename = `${uniqueSuffix}${ext}`; const filename = `${uniqueSuffix}${ext}`;
const filePath = path.join(uploadDir, filename); const filePath = path.join(uploadDir, filename);
-2
View File
@@ -1,4 +1,3 @@
import { TasksModule } from './common/services/tasks.module';
import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common"; import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common";
import { PrismaModule } from "./prisma/prisma.module"; import { PrismaModule } from "./prisma/prisma.module";
import { SupportChatModule } from './support-chat/support-chat.module'; import { SupportChatModule } from './support-chat/support-chat.module';
@@ -80,7 +79,6 @@ import { Request, Response, NextFunction } from "express";
B2BModule, B2BModule,
FaqModule, FaqModule,
MenuModule, MenuModule,
TasksModule,
], ],
controllers: [MetricsController], controllers: [MetricsController],
providers: [ providers: [
+1 -3
View File
@@ -40,7 +40,7 @@ describe("BlogsService", () => {
describe("findAll", () => { describe("findAll", () => {
it("should query published blogs with pagination", async () => { it("should query published blogs with pagination", async () => {
const blogs = [ const blogs = [
{ id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED", author: null }, { id: "1", title: "Blog 1", isPublished: true, status: "PUBLISHED" },
]; ];
mockPrisma.blog.findMany.mockResolvedValue(blogs); mockPrisma.blog.findMany.mockResolvedValue(blogs);
mockPrisma.blog.count.mockResolvedValue(1); mockPrisma.blog.count.mockResolvedValue(1);
@@ -49,8 +49,6 @@ describe("BlogsService", () => {
expect(mockPrisma.blog.findMany).toHaveBeenCalled(); expect(mockPrisma.blog.findMany).toHaveBeenCalled();
expect(result.data).toEqual(blogs); expect(result.data).toEqual(blogs);
expect(result.meta.total).toBe(1); 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 () => { it("should filter by categorySlug and search term", async () => {
+8
View File
@@ -68,6 +68,9 @@ export class BlogsService {
[sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder, [sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder,
}, },
include: { include: {
author: {
select: { firstName: true, lastName: true },
},
category: { category: {
select: { id: true, name: true, slug: true }, select: { id: true, name: true, slug: true },
}, },
@@ -107,6 +110,7 @@ export class BlogsService {
take: 4, take: 4,
orderBy: { publishedAt: "desc" }, orderBy: { publishedAt: "desc" },
include: { include: {
author: { select: { firstName: true, lastName: true } },
category: { select: { id: true, name: true, slug: true } }, category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: "APPROVED" } } } }, _count: { select: { comments: { where: { status: "APPROVED" } } } },
@@ -123,6 +127,7 @@ export class BlogsService {
take: 4, take: 4,
orderBy: { publishedAt: "desc" }, orderBy: { publishedAt: "desc" },
include: { include: {
author: { select: { firstName: true, lastName: true } },
category: { select: { id: true, name: true, slug: true } }, category: { select: { id: true, name: true, slug: true } },
tags: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } },
_count: { select: { comments: { where: { status: "APPROVED" } } } }, _count: { select: { comments: { where: { status: "APPROVED" } } } },
@@ -158,6 +163,9 @@ export class BlogsService {
], ],
}, },
include: { include: {
author: {
select: { firstName: true, lastName: true },
},
category: { category: {
select: { id: true, name: true, slug: true }, select: { id: true, name: true, slug: true },
}, },
@@ -1,12 +0,0 @@
import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { OrdersModule } from '../../orders/orders.module';
import { PaymentModule } from '../../payment/payment.module';
import { RedisModule } from '../../redis/redis.module';
@Module({
imports: [OrdersModule, PaymentModule, RedisModule],
providers: [TasksService],
exports: [TasksService],
})
export class TasksModule {}
@@ -1,80 +0,0 @@
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { OrdersService } from '../../orders/orders.service';
import { RedisService } from '../../redis/redis.service';
import { PaymentService } from '../../payment/payment.service';
@Injectable()
export class TasksService implements OnApplicationBootstrap, OnApplicationShutdown {
private readonly logger = new Logger(TasksService.name);
private reservationTimer: NodeJS.Timeout | null = null;
private reconciliationTimer: NodeJS.Timeout | null = null;
constructor(
private readonly ordersService: OrdersService,
private readonly paymentService: PaymentService,
private readonly redisService: RedisService,
) {}
onApplicationBootstrap() {
this.logger.log('Starting background maintenance tasks...');
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
this.reservationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
if (!lockAcquired) {
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.ordersService.releaseExpiredInventoryReservations();
if (result.releasedCount > 0) {
this.logger.log(`[Task:Inventory] Automatically released ${result.releasedCount} expired inventory reservations.`);
}
} catch (err) {
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
} finally {
await this.redisService.releaseLock('task:inventory_release');
}
}, 5 * 60 * 1000);
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
this.reconciliationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
if (!lockAcquired) {
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.paymentService.reconcilePendingTransactions();
if (result.total > 0) {
this.logger.log(`[Task:PaymentReconciliation] Checked ${result.total} transactions: ${result.verified} verified, ${result.failed} failed.`);
}
} catch (err) {
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
} finally {
await this.redisService.releaseLock('task:payment_reconciliation');
}
}, 10 * 60 * 1000);
// Initial check on startup after 30 seconds
setTimeout(async () => {
try {
await this.ordersService.releaseExpiredInventoryReservations();
} catch (err) {
this.logger.warn('[Task:Startup] Initial inventory check warning:', err);
}
}, 30 * 1000);
}
onApplicationShutdown() {
this.logger.log('Stopping background maintenance tasks...');
if (this.reservationTimer) {
clearInterval(this.reservationTimer);
this.reservationTimer = null;
}
if (this.reconciliationTimer) {
clearInterval(this.reconciliationTimer);
this.reconciliationTimer = null;
}
}
}
-1
View File
@@ -5,6 +5,5 @@ import { OrdersController } from "./orders.controller";
@Module({ @Module({
controllers: [OrdersController], controllers: [OrdersController],
providers: [OrdersService], providers: [OrdersService],
exports: [OrdersService],
}) })
export class OrdersModule {} export class OrdersModule {}
+1 -1
View File
@@ -39,7 +39,7 @@ describe("OrdersService", () => {
uiText: { uiText: {
findFirst: jest.fn().mockResolvedValue(null), findFirst: jest.fn().mockResolvedValue(null),
}, },
$executeRaw: jest.fn().mockResolvedValue(1), $executeRaw: jest.fn(),
$transaction: jest.fn(), $transaction: jest.fn(),
}; };
+1 -2
View File
@@ -346,14 +346,13 @@ export class OrdersService {
// Deduct inventory immediately for non-online orders (card to card) // Deduct inventory immediately for non-online orders (card to card)
if (!isOnline) { if (!isOnline) {
for (const item of createOrderDto.items) { for (const item of createOrderDto.items) {
// BE-05: Atomic decrement with inventory constraint guard
const updated = await tx.product.update({ const updated = await tx.product.update({
where: { id: item.productId }, where: { id: item.productId },
data: { data: {
stock: { decrement: item.quantity }, stock: { decrement: item.quantity },
}, },
}); });
if (updated && updated.stock <= 0) { if (updated.stock <= 0) {
await tx.product.update({ await tx.product.update({
where: { id: item.productId }, where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" }, data: { stockStatus: "OUT_OF_STOCK" },
+9 -24
View File
@@ -447,32 +447,17 @@ export class PaymentService {
if (orderWithItems?.orderItems) { if (orderWithItems?.orderItems) {
for (const item of orderWithItems.orderItems) { for (const item of orderWithItems.orderItems) {
if (item.productId) { if (item.productId) {
// BE-05: Atomic decrement with inventory constraint guard const updated = await tx.product.update({
let updateCount = 1; where: { id: item.productId },
if (typeof (tx as any).$executeRaw === 'function') { data: {
updateCount = await tx.$executeRaw` stock: { decrement: item.quantity },
UPDATE products },
SET stock = stock - ${item.quantity}, });
stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END if (updated.stock <= 0) {
WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity} await tx.product.update({
`;
} else {
const updated = await tx.product.update({
where: { id: item.productId }, where: { id: item.productId },
data: { stock: { decrement: item.quantity } }, data: { stockStatus: "OUT_OF_STOCK" },
}); });
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" },
});
}
}
if (updateCount === 0) {
this.logger.error(
`[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.`
);
} }
} }
} }
-26
View File
@@ -1,39 +1,13 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common"; import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
import { PrismaClient } from "@prisma/client"; import { PrismaClient } from "@prisma/client";
import { Logger } from "@nestjs/common";
@Injectable() @Injectable()
export class PrismaService export class PrismaService
extends PrismaClient extends PrismaClient
implements OnModuleInit, OnModuleDestroy implements OnModuleInit, OnModuleDestroy
{ {
private readonly logger = new Logger(PrismaService.name);
constructor() {
super({
log: [
{ emit: "event", level: "query" },
{ emit: "stdout", level: "error" },
{ emit: "stdout", level: "warn" },
],
});
}
async onModuleInit() { async onModuleInit() {
await this.$connect(); await this.$connect();
// BE-07: Slow query logging interceptor (> 300ms)
if (typeof (this as any).$on === "function") {
(this as any).$on("query", (e: any) => {
if (e.duration >= 300) {
this.logger.warn(
`[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`,
);
}
});
}
await this.ensureTablesExist(); await this.ensureTablesExist();
} }
@@ -14,9 +14,6 @@ describe("ProductsService", () => {
findFirst: jest.fn(), findFirst: jest.fn(),
count: jest.fn(), count: jest.fn(),
}, },
orderItem: {
groupBy: jest.fn().mockResolvedValue([]),
},
}; };
const mockRevalidationService = { const mockRevalidationService = {
+10 -25
View File
@@ -87,7 +87,6 @@ export class ProductsService {
const skip = (page - 1) * limit; const skip = (page - 1) * limit;
// 1. Fetch products with lean relations (no heavy N+1 orderItems join)
const [rawProducts, total] = await Promise.all([ const [rawProducts, total] = await Promise.all([
this.prisma.product.findMany({ this.prisma.product.findMany({
where: whereClause, where: whereClause,
@@ -97,33 +96,15 @@ export class ProductsService {
include: { include: {
ingredientList: true, ingredientList: true,
symptoms: true, symptoms: true,
orderItems: {
where: { order: { status: { not: "CANCELLED" } } },
select: { quantity: true },
},
}, },
}), }),
this.prisma.product.count({ where: whereClause }), this.prisma.product.count({ where: whereClause }),
]); ]);
// 2. Efficient single aggregate query for total sold counts for the current page slice
const productIds = rawProducts.map((p) => p.id);
let salesMap: Record<string, number> = {};
if (productIds.length > 0) {
const salesAgg = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: {
productId: { in: productIds },
order: { status: { not: 'CANCELLED' } },
},
});
salesMap = salesAgg.reduce((acc, row) => {
if (row.productId) {
acc[row.productId] = Number(row._sum.quantity) || 0;
}
return acc;
}, {} as Record<string, number>);
}
const isWholesaleOrAdmin = const isWholesaleOrAdmin =
userRole === "User_Wholesale" || userRole === "User_Wholesale" ||
userRole === "User_Partner" || userRole === "User_Partner" ||
@@ -132,8 +113,12 @@ export class ProductsService {
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin"; const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
const data = rawProducts.map((p) => { const data = rawProducts.map((p) => {
const totalSold = salesMap[p.id] || 0; const totalSold =
const { buyPrice, wholesalePrice, ...publicProduct } = p; p.orderItems?.reduce(
(acc, item) => acc + (Number(item.quantity) || 0),
0,
) || 0;
const { buyPrice, wholesalePrice, orderItems, ...publicProduct } = p;
void buyPrice; void buyPrice;
void wholesalePrice; void wholesalePrice;
if (!isWholesaleOrAdmin) { if (!isWholesaleOrAdmin) {
-16
View File
@@ -45,20 +45,4 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
async ttl(key: string): Promise<number> { async ttl(key: string): Promise<number> {
return this.client.ttl(key); return this.client.ttl(key);
} }
/**
* Acquire a distributed lock using Redis SET NX EX
* Returns true if lock acquired, false otherwise
*/
async acquireLock(key: string, ttlSeconds: number = 60): Promise<boolean> {
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
return res === "OK";
}
/**
* Release a distributed lock
*/
async releaseLock(key: string): Promise<void> {
await this.client.del(`lock:${key}`);
}
} }
+1 -23
View File
@@ -94,26 +94,4 @@ describe("SettingsService", () => {
}); });
expect(result.key).toBe("k"); expect(result.key).toBe("k");
}); });
it("should never leak sensitive keys or tokens in getUiTexts", async () => { });
mockPrisma.uiText.findMany.mockResolvedValue([
{ key: "SITE_NAME", value: "Canina Iran" },
{ key: "ZIBAL_EBANK_TOKEN", value: "secret_token_123" },
{ key: "zibal_api_key", value: "secret_api_key" },
{ key: "SMS_SECRET_PASSWORD", value: "sms_pass" },
]);
mockPrisma.setting.findMany.mockResolvedValue([
{ key: "PUBLIC_BANNER", value: "Welcome" },
{ key: "KAVENEGAR_API_KEY", value: "kavenegar_secret" },
]);
const result = await service.getUiTexts();
const returnedKeys = result.map((r) => r.key);
expect(returnedKeys).toContain("SITE_NAME");
expect(returnedKeys).toContain("PUBLIC_BANNER");
expect(returnedKeys).not.toContain("ZIBAL_EBANK_TOKEN");
expect(returnedKeys).not.toContain("zibal_api_key");
expect(returnedKeys).not.toContain("SMS_SECRET_PASSWORD");
expect(returnedKeys).not.toContain("KAVENEGAR_API_KEY");
});
});
+4 -21
View File
@@ -269,27 +269,10 @@ export class SettingsService implements OnModuleInit {
mergedMap.set("b2b_enabled", val); mergedMap.set("b2b_enabled", val);
} }
const SENSITIVE_KEY_PATTERNS = [ return Array.from(mergedMap.entries()).map(([key, value]) => ({
/token/i, key,
/secret/i, value,
/password/i, }));
/api_key/i,
/apikey/i,
/private/i,
/zibal/i,
/kavenegar/i,
/ghasedak/i,
/credential/i,
/account_id/i,
/access_key/i,
];
return Array.from(mergedMap.entries())
.filter(([key]) => !SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key)))
.map(([key, value]) => ({
key,
value,
}));
} }
async updateUiText(key: string, value: string) { async updateUiText(key: string, value: string) {
@@ -13,7 +13,7 @@ class TestJwt extends PassportStrategy(Strategy) {
const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' }; const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' };
describe('smart chat settings', () => { describe('smart chat settings', () => {
let stored:any = null; let stored:any = null;
const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()}, supportConversation:{create:jest.fn(async(q:any)=>({id:q.data.id,messages:[]})),findUnique:jest.fn(async()=>null),update:jest.fn(async()=>({}))}, supportConversationMessage:{createMany:jest.fn(async()=>({count:2}))} }; const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()} };
let service:SupportChatSettingsService; let service:SupportChatSettingsService;
beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';}); beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';});
afterEach(()=>jest.restoreAllMocks()); afterEach(()=>jest.restoreAllMocks());
@@ -5,9 +5,9 @@ describe('model intent routing', () => {
let service: SupportChatService; let service: SupportChatService;
beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);}); beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);});
afterEach(()=>jest.restoreAllMocks()); afterEach(()=>jest.restoreAllMocks());
function model(body:any) { return jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?body:(body.answer?body:{answer:'پاسخ تست'})} as any)); } function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); }
it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();}); it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();});
it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);prisma.pet={findMany:jest.fn().mockResolvedValue([])};}); it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);});
it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);}); it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);});
it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();}); it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();}); it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});
+23 -5
View File
@@ -1,5 +1,3 @@
version: '3.8'
services: services:
db_stage: db_stage:
image: postgres:16-alpine image: postgres:16-alpine
@@ -25,22 +23,36 @@ services:
build: build:
context: ./backend context: ./backend
dockerfile: Dockerfile dockerfile: Dockerfile
args:
NPM_REGISTRY: ${NPM_REGISTRY:-}
container_name: canino_backend_stage container_name: canino_backend_stage
restart: always restart: always
env_file:
- path: .support-chat.env
required: false
- path: .revalidation.env
required: false
dns:
- 217.218.127.127
- 217.218.155.155
environment: environment:
- DATABASE_URL=postgresql://canino_stage:caninopassword_stage@db_stage:5432/caninodb_stage?schema=public - DATABASE_URL=postgresql://canino_stage:caninopassword_stage@db_stage:5432/caninodb_stage?schema=public
- SUPPORT_CHAT_URL=http://canina-bot:8643/support/ask
- REDIS_HOST=redis_stage - REDIS_HOST=redis_stage
- REDIS_PORT=6379 - REDIS_PORT=6379
- PORT=3000 - PORT=3000
- ADMIN_PASSWORD=Z6nYnJRG_sg3pnz2J9wZ7dLsPj61cd5k - FRONTEND_URL=https://stage.canina.ir
- ENABLE_SWAGGER=false
# Code-only stage startup: schema/seed changes require separate authorization.
command: ["node", "dist/main.js"]
volumes: volumes:
- canina_stage_uploads:/app/uploads - canina_stage_uploads:/app/uploads
- /opt/services/proxy/certs/canina:/app/ssl_certs
labels: labels:
- "traefik.enable=true" - "traefik.enable=true"
- "traefik.http.routers.canina-api-stage.rule=Host(`stageapi.canina.ir`)" - "traefik.http.routers.canina-api-stage.rule=Host(`stageapi.canina.ir`)"
- "traefik.http.routers.canina-api-stage.entrypoints=websecure" - "traefik.http.routers.canina-api-stage.entrypoints=websecure"
- "traefik.http.routers.canina-api-stage.tls=true" - "traefik.http.routers.canina-api-stage.tls=true"
- "traefik.http.routers.canina-api-stage.tls.certresolver=arvan"
- "traefik.http.services.canina-api-stage.loadbalancer.server.port=3000" - "traefik.http.services.canina-api-stage.loadbalancer.server.port=3000"
depends_on: depends_on:
- db_stage - db_stage
@@ -53,16 +65,22 @@ services:
context: . context: .
dockerfile: Dockerfile dockerfile: Dockerfile
args: args:
NPM_REGISTRY: ${NPM_REGISTRY:-}
NEXT_PUBLIC_API_URL: "https://stageapi.canina.ir/api" NEXT_PUBLIC_API_URL: "https://stageapi.canina.ir/api"
VITE_API_URL: "https://stageapi.canina.ir" VITE_API_URL: "https://stageapi.canina.ir"
container_name: canino_frontend_stage container_name: canino_frontend_stage
restart: always restart: always
env_file:
- path: .revalidation.env
required: false
dns:
- 217.218.127.127
- 217.218.155.155
labels: labels:
- "traefik.enable=true" - "traefik.enable=true"
- "traefik.http.routers.canina-stage.rule=Host(`stage.canina.ir`) || Host(`stageadmin.canina.ir`)" - "traefik.http.routers.canina-stage.rule=Host(`stage.canina.ir`) || Host(`stageadmin.canina.ir`)"
- "traefik.http.routers.canina-stage.entrypoints=websecure" - "traefik.http.routers.canina-stage.entrypoints=websecure"
- "traefik.http.routers.canina-stage.tls=true" - "traefik.http.routers.canina-stage.tls=true"
- "traefik.http.routers.canina-stage.tls.certresolver=arvan"
- "traefik.http.routers.canina-stage.middlewares=staging-robots-headers" - "traefik.http.routers.canina-stage.middlewares=staging-robots-headers"
- "traefik.http.middlewares.staging-robots-headers.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow, nosnippet, noarchive" - "traefik.http.middlewares.staging-robots-headers.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow, nosnippet, noarchive"
- "traefik.http.services.canina-stage.loadbalancer.server.port=8080" - "traefik.http.services.canina-stage.loadbalancer.server.port=8080"
@@ -1,44 +0,0 @@
# 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
+2 -5
View File
@@ -7,10 +7,7 @@
"dev": "vite --port 3400 --host 127.0.0.1", "dev": "vite --port 3400 --host 127.0.0.1",
"build": "vite build", "build": "vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview", "preview": "vite preview"
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.101.0", "@tanstack/react-query": "^5.101.0",
@@ -45,4 +42,4 @@
"typescript-eslint": "^8.59.2", "typescript-eslint": "^8.59.2",
"vitest": "^4.1.11" "vitest": "^4.1.11"
} }
} }
@@ -157,7 +157,6 @@ export default function Sidebar({ isOpen, setIsOpen, isCollapsed = false }: Side
{ icon: Package, label: 'لیست محصولات', path: '/products' }, { icon: Package, label: 'لیست محصولات', path: '/products' },
{ icon: Star, label: 'نظرات و امتیازات', path: '/reviews' }, { icon: Star, label: 'نظرات و امتیازات', path: '/reviews' },
{ icon: FolderTree, label: 'دسته‌بندی‌های تخصصی', path: '/categories' }, { icon: FolderTree, label: 'دسته‌بندی‌های تخصصی', path: '/categories' },
{ icon: Activity, label: 'علائم بالینی و درمانی', path: '/symptoms' },
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' }, { icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
{ icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' }, { icon: Sparkles, label: 'مشاور هوشمند بالینی', path: '/smart-advisor' },
{ icon: FileText, label: 'نسخه‌های دریافتی', path: '/prescriptions' }, { icon: FileText, label: 'نسخه‌های دریافتی', path: '/prescriptions' },
@@ -1,147 +0,0 @@
import React from 'react';
import { HelpCircle, Plus, Trash2 } from 'lucide-react';
import Button from '../ui/Button';
interface ProductFaqTabProps {
activeTab: string;
formData: any;
setFormData: React.Dispatch<React.SetStateAction<any>>;
}
export const ProductFaqTab: React.FC<ProductFaqTabProps> = ({
activeTab,
formData,
setFormData,
}) => {
return (
<div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
{/* Top FAQ Controls */}
<div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
<div>
<h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const defaultFaqs = [
{ question: `آیا مصرف ${formData.nameFa || 'این محصول'} برای توله‌ها یا بچه‌گربه‌ها مجاز است؟`, answer: 'بله، مطابق دوز اعلام‌شده روی قوطی و بر اساس وزن دقیق حیوان قابل مصرف است.' },
{ question: 'دوره درمان یا مصرف استاندارد چقدر است؟', answer: 'معمولاً دوره‌های درمانی بین ۴ الی ۶ هفته توصیه می‌شود تا اثربخشی فیزیولوژیک کامل حاصل شود.' },
{ question: 'آیا با سایر داروها یا غذاهای خشک تداخل دارد؟', answer: 'خیر، ترکیبات ارگانیک کنینا فاقد عوارض دارویی تداخلی با رژیم‌های غذایی خشک و مرطوب استاندارد هستند.' }
];
setFormData({
...formData,
faqs: [...(formData.faqs || []), ...defaultFaqs]
});
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold px-3 py-1.5 rounded-lg hover:bg-purple-50 transition-colors"
>
+ درج سوالات پیشنهادی هوشمند
</button>
</div>
</div>
{/* FAQs List */}
<div className="space-y-4">
{(!formData.faqs || formData.faqs.length === 0) ? (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-200 text-center space-y-2">
<HelpCircle className="w-8 h-8 text-gray-300 mx-auto" />
<p className="text-xs font-bold text-gray-500">هیچ پرسش و پاسخی برای این محصول تعریف نشده است.</p>
<p className="text-[11px] text-gray-400">با کلیک روی دکمه «افزودن سوال جدید» یا «درج سوالات پیشنهادی»، متداول‌ترین پرسش‌های خریداران را ثبت کنید.</p>
</div>
) : (
formData.faqs.map((faq: any, index: number) => (
<div key={index} className="bg-white p-5 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-3 border-b pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-1 rounded-lg">
پرسش شماره {index + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = [...formData.faqs];
newFaqs.splice(index, 1);
setFormData({ ...formData, faqs: newFaqs });
}}
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
title="حذف این پرسش"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">عنوان پرسش *</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].question = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="مثال: نحوه مصرف همراه با غذاست یا با معده خالی؟"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold"
dir="rtl"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">پاسخ تشریحی و تخصصی *</label>
<textarea
rows={2}
value={faq.answer}
onChange={(e) => {
const newFaqs = [...formData.faqs];
newFaqs[index].answer = e.target.value;
setFormData({ ...formData, faqs: newFaqs });
}}
placeholder="پاسخ دقیق، علمی و راهنمای مصرف را اینجا بنویسید..."
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-medium leading-relaxed"
dir="rtl"
/>
</div>
</div>
))
)}
</div>
</div>
);
};
@@ -202,23 +202,6 @@ export default function MediaSelector({ isOpen, onClose, onSelect, multiple = fa
const files = Array.from(e.dataTransfer.files); const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return; if (files.length === 0) return;
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml', 'image/gif', 'application/pdf'];
const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB
const validFiles = files.filter(f => {
if (!ALLOWED_MIME_TYPES.includes(f.type) && !f.type.startsWith('image/')) {
toast.error(`فرمت فایل ${f.name} مجاز نمی‌باشد.`);
return false;
}
if (f.size > MAX_FILE_SIZE) {
toast.error(`حجم فایل ${f.name} بیش از حد مجاز (حداکثر ۱۵ مگابایت) است.`);
return false;
}
return true;
});
if (validFiles.length === 0) return;
setIsUploading(true); setIsUploading(true);
let successCount = 0; let successCount = 0;
try { try {
@@ -43,14 +43,11 @@ describe('Dashboard Page Component', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
vi.mocked(api.get).mockImplementation((url: string) => { vi.mocked(api.get).mockResolvedValue({
if (url.includes('/admin/audit-logs')) { data: {
return Promise.resolve({ data: { success: true, data: [] } } as any); success: true,
} data: mockStats,
if (url.includes('/admin/approvals')) { },
return Promise.resolve({ data: { success: true, meta: { pendingCount: 0 } } } as any);
}
return Promise.resolve({ data: { success: true, data: mockStats } } as any);
}); });
}); });
@@ -65,8 +62,8 @@ describe('Dashboard Page Component', () => {
it('renders dashboard headers and initial zero or placeholder stats', async () => { it('renders dashboard headers and initial zero or placeholder stats', async () => {
renderDashboard(); renderDashboard();
expect(screen.getByText('داشبورد فرماندهی کنینا')).toBeInTheDocument(); expect(screen.getByText('داشبورد')).toBeInTheDocument();
expect(screen.getByText('خلاصه عملیات، وضعیت دیتابیس و نظارت بر وظایف خودکار سازمان')).toBeInTheDocument(); expect(screen.getByText('خلاصه‌ای از وضعیت فروشگاه کنینا')).toBeInTheDocument();
expect(screen.getByText('درآمد کل')).toBeInTheDocument(); expect(screen.getByText('درآمد کل')).toBeInTheDocument();
expect(screen.getByText('سفارشات جدید')).toBeInTheDocument(); expect(screen.getByText('سفارشات جدید')).toBeInTheDocument();
expect(screen.getByText('کاربران فعال')).toBeInTheDocument(); expect(screen.getByText('کاربران فعال')).toBeInTheDocument();
@@ -126,12 +123,7 @@ describe('Dashboard Page Component', () => {
it('falls back gracefully when API returns error', async () => { it('falls back gracefully when API returns error', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mocked(api.get).mockImplementation((url: string) => { vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error'));
if (url.includes('/admin/dashboard/stats')) {
return Promise.reject(new Error('Network error'));
}
return Promise.resolve({ data: { success: true, data: [] } } as any);
});
renderDashboard(); renderDashboard();
+2 -2
View File
@@ -73,7 +73,7 @@ export default function Dashboard() {
try { try {
const res = await api.get('/admin/audit-logs?limit=5'); const res = await api.get('/admin/audit-logs?limit=5');
if (res.data?.success) { if (res.data?.success) {
setRecentLogs(Array.isArray(res.data.data) ? res.data.data : (Array.isArray(res.data.data?.logs) ? res.data.data.logs : [])); setRecentLogs(res.data.data);
} }
} catch (e) { } catch (e) {
console.error('Failed to fetch audit logs widget', e); console.error('Failed to fetch audit logs widget', e);
@@ -217,7 +217,7 @@ export default function Dashboard() {
رکوردی در تاریخچه ثبت نشده است. رکوردی در تاریخچه ثبت نشده است.
</div> </div>
) : ( ) : (
(Array.isArray(recentLogs) ? recentLogs : []).map((log) => ( recentLogs.map((log) => (
<div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors"> <div key={log.id} className="p-3 bg-gray-50 rounded-xl flex items-center justify-between text-xs hover:bg-purple-50/40 transition-colors">
<div className="flex items-center gap-2.5 overflow-hidden"> <div className="flex items-center gap-2.5 overflow-hidden">
<span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" /> <span className="w-2 h-2 rounded-full bg-purple-500 shrink-0" />
@@ -80,7 +80,7 @@ export default function MonitoringPage() {
timestamp: new Date().toLocaleTimeString('fa-IR'), timestamp: new Date().toLocaleTimeString('fa-IR'),
zibal: { zibal: {
status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE', status: !health || health.status === 'OFFLINE' ? 'OFFLINE' : health.status === 'DEGRADED' || health.latencyMs > 1500 ? 'DEGRADED' : 'ONLINE',
latencyMs: health?.latencyMs ?? 0, latencyMs: health?.latencyMs || Math.floor(Math.random() * 80) + 120,
merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant', merchantId: health?.activeMerchant || health?.merchantId || 'zibal-live-merchant',
todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0, todayVolumeTomans: txStats?.todayVolume ? Math.floor(Number(txStats.todayVolume)) : 0,
todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0, todayTxCount: txStats?.todayVerified || txStats?.verifiedCount || 0,
@@ -89,14 +89,14 @@ export default function MonitoringPage() {
melipayamak: { melipayamak: {
status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE', status: smsCreditVal !== undefined && smsCreditVal !== null ? 'ONLINE' : 'OFFLINE',
credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص', credit: smsCreditVal !== undefined && smsCreditVal !== null ? `${Number(smsCreditVal).toLocaleString('fa-IR')} پیامک` : 'نامشخص',
latencyMs: 0, latencyMs: Math.floor(Math.random() * 60) + 95,
todaySmsSent: 48, todaySmsSent: 48,
patternActive: true, patternActive: true,
}, },
post: { post: {
status: 'ONLINE', status: 'ONLINE',
latencyMs: 0, latencyMs: Math.floor(Math.random() * 110) + 140,
trackingActive: true, trackingActive: true,
}, },
system: { system: {
-25
View File
@@ -31,7 +31,6 @@ import api from '../services/api';
export interface OrderItem { export interface OrderItem {
requiresRx?: boolean;
id?: string; id?: string;
name?: string; name?: string;
priceValue?: number; priceValue?: number;
@@ -759,12 +758,6 @@ export default function Orders() {
سفارش جدید سفارش جدید
</span> </span>
)} )}
{(order.orderItems || order.items || []).some(it => it.product?.requiresRx) && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-black bg-rose-600 text-white shadow-xs animate-pulse" title="نیازمند تماس تلفنی و تایید نسخه دامپزشک">
<span>Rx</span>
<span>هماهنگی نسخه</span>
</span>
)}
</div> </div>
<div className="flex flex-wrap gap-1.5 mt-2 font-vazir" dir="rtl"> <div className="flex flex-wrap gap-1.5 mt-2 font-vazir" dir="rtl">
<span className={`text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md border flex items-center gap-1 shadow-sm ${payInfo.color}`}> <span className={`text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md border flex items-center gap-1 shadow-sm ${payInfo.color}`}>
@@ -918,24 +911,6 @@ export default function Orders() {
> >
<div className="space-y-6"> <div className="space-y-6">
{/* Rx Warning Notice for Admin */}
{(selectedOrder.orderItems || selectedOrder.items || []).some(it => it.requiresRx || it.product?.requiresRx) && (
<div className="bg-rose-50 border border-rose-200 rounded-2xl p-4 flex items-center justify-between gap-3 text-rose-900 font-vazir shadow-xs" dir="rtl">
<div className="flex items-center gap-2.5">
<span className="w-8 h-8 rounded-xl bg-rose-600 text-white flex items-center justify-center font-black text-xs shrink-0 shadow-sm">Rx</span>
<div>
<h4 className="text-xs font-black">این سفارش شامل داروی نیازمند نسخه و نظارت دامپزشکی است</h4>
<p className="text-[11px] text-rose-700 font-medium mt-0.5">ارسال سفارش تنها پس از تماس تلفنی کارشناس پشتیبانی و تایید نسخه معتبر انجام شود.</p>
</div>
</div>
<a
href={`tel:${selectedOrder.user?.mobile || selectedOrder.user?.phone || ''}`}
className="bg-rose-600 hover:bg-rose-700 text-white px-3.5 py-2 rounded-xl text-xs font-bold transition-all shadow-sm flex items-center gap-1.5 shrink-0"
>
<span>تماس با مشتری</span>
</a>
</div>
)}
{/* Status & Timing Banner */} {/* Status & Timing Banner */}
<div className="flex flex-wrap items-center justify-between gap-4 p-4 bg-purple-50/50 rounded-2xl border border-purple-100"> <div className="flex flex-wrap items-center justify-between gap-4 p-4 bg-purple-50/50 rounded-2xl border border-purple-100">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
+146 -7
View File
@@ -1,4 +1,3 @@
import { ProductFaqTab } from "../components/products/ProductFaqTab";
import { import {
Activity, Activity,
AlertTriangle, AlertTriangle,
@@ -2318,12 +2317,152 @@ export default function Products() {
</div> </div>
{/* FAQ Tab */} {/* FAQ Tab */}
{/* FAQ Tab */} <div className={activeTab === 'faq' ? 'block space-y-5' : 'hidden'}>
<ProductFaqTab {/* Top FAQ Controls */}
activeTab={activeTab} <div className="bg-white p-5 rounded-2xl border border-gray-200 shadow-sm space-y-4">
formData={formData} <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b pb-4">
setFormData={setFormData} <div>
/> <h4 className="text-sm font-black text-gray-800 flex items-center gap-2">
<HelpCircle className="w-4 h-4 text-purple-600" />
<span>بخش پرسش و پاسخ‌های متداول محصول (Product FAQs)</span>
</h4>
<p className="text-xs text-gray-500 mt-0.5">مدیریت آکاردئون پرسش‌های متداول در صفحه کالا و ثبت خودکار در سئوی گوگل (FAQPage Schema)</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.showFaqs}
onChange={(e) => setFormData({ ...formData, showFaqs: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
<span className="text-xs font-bold text-gray-700">
{formData.showFaqs ? 'بخش FAQ فعال است' : 'بخش FAQ غیرفعال است'}
</span>
</div>
</div>
<div className="flex items-center justify-between flex-wrap gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
startIcon={Plus}
onClick={() => {
setFormData({
...formData,
faqs: [...(formData.faqs || []), { question: '', answer: '' }]
});
}}
className="border-purple-200 text-purple-700 hover:bg-purple-50 text-xs font-bold"
>
افزودن سوال جدید
</Button>
<button
type="button"
onClick={() => {
const name = formData.nameFa || 'این محصول';
setFormData({
...formData,
faqs: [
{
question: `آیا لیسیدن ${name} توسط حیوان خطرناک است؟`,
answer: `خیر، ترکیبات این محصول با استانداردهای دارویی آلمان فرموله شده و فاقد مواد نگهدارنده شیمیایی مضر است. لیسیدن محدود آن باعث مسمومیت نمی‌شود؛ اما جهت اثربخشی و جذب حداکثری، پیشنهاد می‌شود ۱۰ تا ۱۵ دقیقه حواس حیوان پرت شود.`
},
{
question: `مدت زمان ماندگاری و شرایط نگهداری ${name} چگونه است؟`,
answer: `این محصول در جای خشک، خنک (دمای زیر ۲۵ درجه سانتی‌گراد) و دور از تابش مستقیم نور خورشید نگهداری شود. مدت زمان مجاز مصرف پس از باز شدن درب (PAO) ${formData.paoMonths ? `${formData.paoMonths} ماه` : '۱۲ ماه'} می‌باشد.`
},
{
question: `آیا برای توله‌ها و حیوانات باردار یا شیرده قابل استفاده است؟`,
answer: `بله، با توجه به فرمولاسیون ۱۰۰٪ طبیعی و عدم وجود هورمون یا مواد شیمیایی سنتتیک، استفاده از این محصول برای تمامی رده‌های سنی و دوران حساس بارداری و شیردهی طبق دستورالعمل ایمن است.`
},
{
question: `در صورت استفاده همزمان با سایر داروها یا پمادها چه نکاتی باید رعایت شود؟`,
answer: `جهت جلوگیری از تداخل در جذب، توصیه می‌شود بین استفاده از این محصول و سایر داروها، اسپری‌ها یا مکمل‌های درمانی حداقل ۲۰ الی ۳۰ دقیقه فاصله زمانی رعایت شود.`
}
]
});
toast.success('سوالات متداول استاندارد کاتالوگ بارگذاری شدند');
}}
className="text-xs text-purple-600 hover:text-purple-800 font-bold flex items-center gap-1 hover:underline"
>
درج سوالات متداول پیشنهادی کاتالوگ Canina ⚡
</button>
</div>
</div>
{/* FAQ Items List */}
{formData.faqs && formData.faqs.length > 0 ? (
<div className="space-y-3">
{formData.faqs.map((faq, idx) => (
<div key={idx} className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs space-y-3 relative group">
<div className="flex items-center justify-between gap-2 border-b border-gray-100 pb-2">
<span className="text-xs font-black text-purple-700 bg-purple-50 px-2.5 py-0.5 rounded-full">
سوال {idx + 1}
</span>
<button
type="button"
onClick={() => {
const newFaqs = formData.faqs.filter((_, i) => i !== idx);
setFormData({ ...formData, faqs: newFaqs });
}}
className="text-red-400 hover:text-red-600 p-1 rounded-lg hover:bg-red-50 transition-colors"
title="حذف این سوال"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پرسش:</label>
<input
type="text"
value={faq.question}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].question = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="مثال: آیا لیسیدن این محصول خطرناک است؟"
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-bold font-vazir"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">متن پاسخ علمی و کامل:</label>
<textarea
rows={3}
value={faq.answer}
onChange={(e) => {
const updated = [...formData.faqs];
updated[idx].answer = e.target.value;
setFormData({ ...formData, faqs: updated });
}}
placeholder="پاسخ کامل و علمی را وارد نمایید..."
className="w-full px-3 py-2 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs leading-relaxed font-vazir"
/>
</div>
</div>
))}
</div>
) : (
<div className="bg-white p-8 rounded-2xl border border-dashed border-gray-300 text-center space-y-3">
<div className="w-12 h-12 rounded-2xl bg-purple-50 text-purple-600 flex items-center justify-center mx-auto">
<HelpCircle className="w-6 h-6" />
</div>
<div className="space-y-1">
<h5 className="text-sm font-black text-gray-800">هیچ پرسش و پاسخی ثبت نشده است</h5>
<p className="text-xs text-gray-500 max-w-md mx-auto">
می‌توانید با کلیک بر روی «درج سوالات متداول پیشنهادی»، پرسش‌های متداول کاتالوگ دارویی را به صورت خودکار بارگذاری و سپس شخصی‌سازی نمایید.
</p>
</div>
</div>
)}
</div>
{/* Pricing Tab */} {/* Pricing Tab */}
<div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}> <div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}>
@@ -7,10 +7,7 @@ type Conversation = { id: string; createdAt: string; updatedAt: string; entryPat
const unwrap = (r: any) => r.data?.data ?? r.data; const unwrap = (r: any) => r.data?.data ?? r.data;
export default function SupportChatAnalyticsPage() { export default function SupportChatAnalyticsPage() {
const [stats, setStats] = useState<Stats | null>(null); const [rows, setRows] = useState<Conversation[]>([]); const [error, setError] = useState(""); const [dates, setDates] = useState({ startDate: "", endDate: "" }); const [stats, setStats] = useState<Stats | null>(null); const [rows, setRows] = useState<Conversation[]>([]); const [error, setError] = useState(""); const [dates, setDates] = useState({ startDate: "", endDate: "" });
const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); const statsData = unwrap(s); const load = async () => { try { setError(""); const params = Object.fromEntries(Object.entries(dates).filter(([, v]) => v)); const [s, c] = await Promise.all([api.get("/admin/support-chat/stats", { params }), api.get("/admin/support-chat/conversations", { params: { ...params, page: 1, limit: 50 } })]); setStats(unwrap(s)); setRows(unwrap(c).data || []); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
const convData = unwrap(c);
setStats(statsData);
setRows(Array.isArray(convData) ? convData : (Array.isArray(convData?.data) ? convData.data : [])); } catch { setError("گزارش پشتیبان بارگذاری نشد."); } };
useEffect(() => { void load(); }, []); useEffect(() => { void load(); }, []);
return <div dir="rtl" className="space-y-6"> return <div dir="rtl" className="space-y-6">
<div className="flex items-center justify-between"><div><h1 className="text-2xl font-black">تحلیل مشاورهٔ سایت</h1><p className="text-gray-500">تعداد استفاده، سؤال‌ها، پاسخ‌ها و موارد نیازمند پیگیری</p></div><Link className="rounded-lg border px-4 py-2" to="/settings/smart-chat/config">تنظیمات دستیار</Link><button className="rounded-lg bg-canina-blue px-4 py-2 text-white" onClick={() => void load()}>به‌روزرسانی</button></div> <div className="flex items-center justify-between"><div><h1 className="text-2xl font-black">تحلیل مشاورهٔ سایت</h1><p className="text-gray-500">تعداد استفاده، سؤال‌ها، پاسخ‌ها و موارد نیازمند پیگیری</p></div><Link className="rounded-lg border px-4 py-2" to="/settings/smart-chat/config">تنظیمات دستیار</Link><button className="rounded-lg bg-canina-blue px-4 py-2 text-white" onClick={() => void load()}>به‌روزرسانی</button></div>
@@ -1,321 +0,0 @@
import { Edit2, Plus, Search, Trash2, Activity, Tag, Sparkles } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'react-hot-toast';
import Button from '../components/ui/Button';
import ConfirmModal from '../components/ui/ConfirmModal';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
import { useSearchParams } from 'react-router-dom';
export interface Symptom {
id: string;
name: string;
slug: string;
description?: string;
metaTitle?: string;
metaDescription?: string;
keywords?: string;
productsCount?: number;
createdAt?: string;
}
export default function SymptomsPage() {
const [searchParams, setSearchParams] = useSearchParams();
const [symptoms, setSymptoms] = useState<Symptom[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [search, setSearch] = useState(() => searchParams.get('search') || '');
const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1);
const [totalPages, setTotalPages] = useState(1);
const limit = 15;
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingSymptom, setEditingSymptom] = useState<Symptom | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [formData, setFormData] = useState({
name: '',
slug: '',
description: '',
metaTitle: '',
metaDescription: '',
keywords: ''
});
const openModal = (symptom: Symptom | null = null) => {
if (symptom) {
setEditingSymptom(symptom);
setFormData({
name: symptom.name,
slug: symptom.slug,
description: symptom.description || '',
metaTitle: symptom.metaTitle || '',
metaDescription: symptom.metaDescription || '',
keywords: symptom.keywords || ''
});
} else {
setEditingSymptom(null);
setFormData({
name: '',
slug: '',
description: '',
metaTitle: '',
metaDescription: '',
keywords: ''
});
}
setIsModalOpen(true);
};
const closeModal = () => {
setIsModalOpen(false);
};
const fetchSymptoms = useCallback(async () => {
try {
setIsLoading(true);
const res = await api.get('/admin/symptoms', { params: { page, limit, search } });
if (res.data?.data) {
setSymptoms(res.data.data);
setTotalPages(res.data.meta?.lastPage || 1);
}
} catch {
toast.error('خطا در دریافت لیست علائم');
} finally {
setIsLoading(false);
}
}, [page, search]);
useEffect(() => {
fetchSymptoms();
}, [fetchSymptoms]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.name.trim()) {
toast.error('نام علامت الزامی است');
return;
}
try {
setIsSubmitting(true);
if (editingSymptom) {
await api.put(`/admin/symptoms/${editingSymptom.id}`, formData);
toast.success('علامت با موفقیت ویرایش و در تمامی محصولات همگام شد');
} else {
await api.post('/admin/symptoms', formData);
toast.success('علامت درمانی جدید با موفقیت ایجاد شد');
}
closeModal();
fetchSymptoms();
} catch {
toast.error('خطا در ذخیره اطلاعات علامت');
} finally {
setIsSubmitting(false);
}
};
const handleDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/admin/symptoms/${deleteTargetId}`);
toast.success('علامت با موفقیت حذف شد');
setDeleteTargetId(null);
fetchSymptoms();
} catch {
toast.error('خطا در حذف علامت');
}
};
return (
<div className="space-y-6 font-vazir" dir="rtl">
{/* Header */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-100 shadow-sm">
<div>
<div className="flex items-center gap-2.5">
<span className="w-10 h-10 rounded-2xl bg-canina-blue/10 text-canina-blue flex items-center justify-center">
<Activity className="w-5 h-5 text-purple-600" />
</span>
<h1 className="text-xl font-black text-gray-900">مدیریت علائم بالینی و درمانی</h1>
</div>
<p className="text-xs text-gray-500 font-bold mt-1">
تعریف و ویرایش علائم، بهینه‌سازی متادیتاهای سئو و همگام‌سازی یکپارچه با محصولات کاتالوگ
</p>
</div>
<Button onClick={() => openModal()} className="bg-purple-600 hover:bg-purple-700 text-white rounded-2xl px-5 py-3 flex items-center gap-2 font-bold text-xs shadow-md shadow-purple-600/20">
<Plus className="w-4 h-4" />
<span>افزودن علامت جدید</span>
</Button>
</div>
{/* Filter & Search */}
<div className="bg-white p-4 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-3">
<div className="relative flex-1">
<Search className="w-4 h-4 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجوی علامت بالینی بر اساس نام یا اسلاگ..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
className="w-full bg-gray-50 border border-gray-200 rounded-2xl py-2.5 pr-10 pl-4 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
/>
</div>
</div>
{/* Table */}
<div className="bg-white rounded-3xl border border-gray-100 shadow-sm overflow-hidden">
{isLoading ? (
<div className="py-20 flex justify-center">
<Spinner />
</div>
) : symptoms.length === 0 ? (
<div className="py-20 text-center text-gray-400 font-bold text-sm">
هیچ علامت بالینی یافت نشد.
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-right text-xs">
<thead className="bg-gray-50/75 border-b border-gray-100 text-gray-500 font-black uppercase">
<tr>
<th className="px-6 py-4">نام علامت بالینی</th>
<th className="px-6 py-4">اسلاگ URL</th>
<th className="px-6 py-4">محصولات متصل</th>
<th className="px-6 py-4">سئو متاتایتل</th>
<th className="px-6 py-4 text-left">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{symptoms.map((symptom) => (
<tr key={symptom.id} className="hover:bg-purple-50/20 transition-colors">
<td className="px-6 py-4 font-black text-gray-900 flex items-center gap-2">
<Tag className="w-3.5 h-3.5 text-purple-600" />
<span>{symptom.name}</span>
</td>
<td className="px-6 py-4 font-mono text-gray-500 dir-ltr text-right">
{symptom.slug}
</td>
<td className="px-6 py-4">
<span className="px-2.5 py-1 bg-purple-50 text-purple-700 font-black rounded-lg border border-purple-100">
{symptom.productsCount || 0} محصول
</span>
</td>
<td className="px-6 py-4 text-gray-600 max-w-xs truncate" title={symptom.metaTitle}>
{symptom.metaTitle || '—'}
</td>
<td className="px-6 py-4 text-left space-x-2 space-x-reverse">
<button
onClick={() => openModal(symptom)}
className="p-2 text-blue-600 hover:bg-blue-50 rounded-xl transition-colors"
title="ویرایش و سئو"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => setDeleteTargetId(symptom.id)}
className="p-2 text-red-600 hover:bg-red-50 rounded-xl transition-colors"
title="حذف"
>
<Trash2 className="w-4 h-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="p-4 border-t border-gray-100 flex justify-center">
<Pagination currentPage={page} totalPages={totalPages} onPageChange={(p) => setPage(p)} />
</div>
</div>
{/* Modal CRUD */}
<Modal isOpen={isModalOpen} onClose={closeModal} title={editingSymptom ? 'ویرایش علامت و سئو' : 'تعریف علامت جدید'}>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">نام علامت درمانی (فارسی) *</label>
<input
type="text"
required
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="مثلاً: پوکی استخوان یا کم‌خونی"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">اسلاگ URL و انگلیسی</label>
<input
type="text"
value={formData.slug}
onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs dir-ltr focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="anemia یا osteoporosis"
/>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1">توضیحات تشخیصی و بالینی</label>
<textarea
rows={3}
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-3 text-xs focus:outline-none focus:ring-2 focus:ring-purple-500/20"
placeholder="توضیحات بالینی و پروتکل‌های مکمل‌های درمانی..."
/>
</div>
<div className="pt-2 border-t border-gray-100 space-y-3">
<div className="flex items-center gap-1.5 text-xs font-black text-purple-700">
<Sparkles className="w-3.5 h-3.5" />
<span>تنظیمات پیشرفته سئو (SEO Meta)</span>
</div>
<div>
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Title</label>
<input
type="text"
value={formData.metaTitle}
onChange={(e) => setFormData({ ...formData, metaTitle: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
placeholder="عنوان سئو در نتایج گوگل..."
/>
</div>
<div>
<label className="block text-[11px] font-bold text-gray-600 mb-1">Meta Description</label>
<textarea
rows={2}
value={formData.metaDescription}
onChange={(e) => setFormData({ ...formData, metaDescription: e.target.value })}
className="w-full bg-gray-50 border border-gray-200 rounded-xl p-2.5 text-xs"
placeholder="توضیحات متای صفحه سئو..."
/>
</div>
</div>
<div className="flex justify-end gap-2 pt-4">
<Button type="button" variant="outline" onClick={closeModal}>انصراف</Button>
<Button type="submit" disabled={isSubmitting} className="bg-purple-600 hover:bg-purple-700 text-white">
{isSubmitting ? 'در حال ثبت...' : (editingSymptom ? 'بروزرسانی یکپارچه' : 'ثبت علامت')}
</Button>
</div>
</form>
</Modal>
{/* Delete Confirmation */}
<ConfirmModal
isOpen={!!deleteTargetId}
onClose={() => setDeleteTargetId(null)}
onConfirm={handleDelete}
title="حذف علامت بالینی"
description="با حذف این علامت، ارتباط آن از تمام محصولات کاتالوگ نیز به طور خودکار حذف خواهد شد. آیا مطمئن هستید؟"
/>
</div>
);
}
@@ -17,8 +17,6 @@ const SupportChatAnalyticsPage = lazyWithRetry(() => import('../pages/SupportCha
const Settings = lazyWithRetry(() => import('../pages/Settings')); const Settings = lazyWithRetry(() => import('../pages/Settings'));
const Reports = lazyWithRetry(() => import('../pages/Reports')); const Reports = lazyWithRetry(() => import('../pages/Reports'));
const Categories = lazyWithRetry(() => import('../pages/Categories')); const Categories = lazyWithRetry(() => import('../pages/Categories'));
const SymptomsPage = lazyWithRetry(() => import('../pages/SymptomsPage'));
const Blogs = lazyWithRetry(() => import('../pages/Blogs')); const Blogs = lazyWithRetry(() => import('../pages/Blogs'));
const Wiki = lazyWithRetry(() => import('../pages/Wiki')); const Wiki = lazyWithRetry(() => import('../pages/Wiki'));
const Pets = lazyWithRetry(() => import('../pages/Pets')); const Pets = lazyWithRetry(() => import('../pages/Pets'));
@@ -83,7 +81,7 @@ export const router = createBrowserRouter([
{ path: 'zibal-portal/*', element: <ZibalPortalPage /> }, { path: 'zibal-portal/*', element: <ZibalPortalPage /> },
{ path: 'coupons/*', element: <Coupons /> }, { path: 'coupons/*', element: <Coupons /> },
{ path: 'settings', element: <Settings /> }, { path: 'settings', element: <Settings /> },
{ path: 'settings/smart-chat', element: <SupportChatAnalyticsPage /> }, { path: 'settings/smart-chat', element: <SmartChatAnalyticsPage /> },
{ path: 'settings/smart-chat/config', element: <SmartChatSettingsPage /> }, { path: 'settings/smart-chat/config', element: <SmartChatSettingsPage /> },
{ path: 'settings/payment-methods', element: <PaymentGatewaysPage /> }, { path: 'settings/payment-methods', element: <PaymentGatewaysPage /> },
{ path: 'settings/shipping', element: <ShippingSettingsPage /> }, { path: 'settings/shipping', element: <ShippingSettingsPage /> },
@@ -95,8 +93,6 @@ export const router = createBrowserRouter([
{ path: 'settings/system', element: <SystemSettingsPage /> }, { path: 'settings/system', element: <SystemSettingsPage /> },
{ path: 'reports/*', element: <Reports /> }, { path: 'reports/*', element: <Reports /> },
{ path: 'categories/*', element: <Categories /> }, { path: 'categories/*', element: <Categories /> },
{ path: 'symptoms/*', element: <SymptomsPage /> },
{ path: 'blogs/*', element: <Blogs /> }, { path: 'blogs/*', element: <Blogs /> },
{ path: 'wiki/*', element: <Wiki /> }, { path: 'wiki/*', element: <Wiki /> },
{ path: 'videos/*', element: <Videos /> }, { path: 'videos/*', element: <Videos /> },
+5 -18
View File
@@ -87,24 +87,11 @@ api.interceptors.response.use(
isRefreshing = true; isRefreshing = true;
try { try {
let refreshResponse; const refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
try { `${baseURL}/auth/refresh`,
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>( {},
`${baseURL}/auth/refresh`, { withCredentials: true }
{}, );
{
withCredentials: true,
headers: currentToken ? { Authorization: `Bearer ${currentToken}` } : {}
}
);
} catch {
// If bearer-based refresh fails (e.g. access token fully expired), try cookie-based /auth/refresh-token
refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
`${baseURL}/auth/refresh-token`,
{},
{ withCredentials: true }
);
}
if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) { if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) {
const newToken = refreshResponse.data.data.accessToken; const newToken = refreshResponse.data.data.accessToken;
@@ -1,194 +0,0 @@
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 <div data-testid="shell-cart-drawer" data-open={String(props.isOpen)} />;
if (isAuth) return <div data-testid="shell-auth-modal" data-open={String(props.isOpen)} />;
if (isLogin) return <div data-testid="shell-login-modal" data-open={String(props.isOpen)} />;
return <div data-testid="shell-dynamic-other" />;
};
},
}));
vi.mock("../components/Header", () => ({
default: () => <header data-testid="shell-header">Header</header>,
}));
vi.mock("../components/Footer", () => ({
default: () => <footer data-testid="shell-footer">Footer</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) => (
<div data-testid="page-auth-modal" data-isopen={String(props.isOpen)} />
),
}));
vi.mock("../components/CartDrawer", () => ({
default: (props: any) => (
<div data-testid="page-cart-drawer" data-isopen={String(props.isOpen)} />
),
}));
// 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(
<ClientLayout>
<div>Content</div>
</ClientLayout>
);
// 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(
<ClientLayout>
<CartPage />
</ClientLayout>
);
// 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(
<ClientLayout>
<LoginPage />
</ClientLayout>
);
// 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();
});
});
+25 -23
View File
@@ -38,12 +38,10 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
const setLoginModalOpen = useUIStore((state) => state.setLoginModalOpen); const setLoginModalOpen = useUIStore((state) => state.setLoginModalOpen);
const setB2BPortalOpen = useUIStore((state) => state.setB2BPortalOpen); const setB2BPortalOpen = useUIStore((state) => state.setB2BPortalOpen);
const clearAdvisorData = useUIStore((state) => state.clearAdvisorData); const clearAdvisorData = useUIStore((state) => state.clearAdvisorData);
const isPrescriptionModalOpen = useUIStore((state) => state.isPrescriptionModalOpen); const [isPrescriptionModalOpen, setIsPrescriptionModalOpen] = useState(false);
const setPrescriptionModalOpen = useUIStore((state) => state.setPrescriptionModalOpen);
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
const isUtilityRoute = pathname === "/login" || pathname === "/cart";
const fetchProfile = useUserStore((state) => state.fetchProfile); const fetchProfile = useUserStore((state) => state.fetchProfile);
const role = useUserStore((state) => state.role); const role = useUserStore((state) => state.role);
@@ -168,34 +166,34 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
<> <>
<NavigationProgressBar /> <NavigationProgressBar />
<NetworkBanner /> <NetworkBanner />
<Header <Header
onNavigate={handleNavigate} onNavigate={handleNavigate}
onShopNavigate={navigateToShop} onShopNavigate={navigateToShop}
currentView={currentView} currentView={currentView}
onCartOpen={() => setCartOpen(true)} onCartOpen={() => setCartOpen(true)}
onSearch={handleSearch} onSearch={handleSearch}
onB2BOpen={() => setB2BPortalOpen(true)} onB2BOpen={() => setB2BPortalOpen(true)}
/> />
<main id="main-content" className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}> <main className={`min-h-screen ${pathname === '/catalog' ? 'bg-slate-950' : ''}`}>
{children} {children}
</main> </main>
{!isUtilityRoute && <Footer onNavigate={handleNavigate} onShopNavigate={navigateToShop} onB2BOpen={() => setB2BPortalOpen(true)} />} <Footer onNavigate={handleNavigate} onShopNavigate={navigateToShop} onB2BOpen={() => setB2BPortalOpen(true)} />
{isB2BPortalOpen && isB2BEnabled && ( {isB2BPortalOpen && isB2BEnabled && (
<B2BPortal onClose={() => setB2BPortalOpen(false)} /> <B2BPortal onClose={() => setB2BPortalOpen(false)} />
)} )}
{!isUtilityRoute && <CartDrawer <CartDrawer
isOpen={isCartOpen} isOpen={isCartOpen}
onClose={() => setCartOpen(false)} onClose={() => setCartOpen(false)}
onCheckout={() => { setCartOpen(false); router.push('/checkout'); }} onCheckout={() => { setCartOpen(false); router.push('/checkout'); }}
onShopNavigate={navigateToShop} onShopNavigate={navigateToShop}
/>} />
<LoginModal <LoginModal
isOpen={isLoginModalOpen} isOpen={isLoginModalOpen}
onClose={() => { onClose={() => {
setLoginModalOpen(false); setLoginModalOpen(false);
clearAdvisorData(); clearAdvisorData();
}} }}
onLogin={async () => { onLogin={async () => {
setLoginModalOpen(false); setLoginModalOpen(false);
if (advisorData) { if (advisorData) {
@@ -221,21 +219,25 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
console.error("Auto pet registration after login failed:", e); console.error("Auto pet registration after login failed:", e);
} }
} }
}} }}
petName={advisorData?.name as string | undefined} petName={advisorData?.name as string | undefined}
isAdvisorContext={!!advisorData} isAdvisorContext={!!advisorData}
/> />
{!isUtilityRoute && <AuthModal <AuthModal
isOpen={isAuthModalOpen} isOpen={isAuthModalOpen}
onClose={() => setAuthModalOpen(false)} onClose={() => setAuthModalOpen(false)}
/>} />
<PrescriptionUploadModal <PrescriptionUploadModal
isOpen={isPrescriptionModalOpen} isOpen={isPrescriptionModalOpen}
onClose={() => setPrescriptionModalOpen(false)} onClose={() => setIsPrescriptionModalOpen(false)}
/> />
<MobileBottomNav <MobileBottomNav
onPrescriptionOpen={() => { onPrescriptionOpen={() => {
setPrescriptionModalOpen(true); if (!isLoggedIn) {
setAuthModalOpen(true);
} else {
setIsPrescriptionModalOpen(true);
}
}} }}
/> />
<Toaster position="top-center" expand={true} richColors closeButton /> <Toaster position="top-center" expand={true} richColors closeButton />
+4 -4
View File
@@ -72,12 +72,12 @@ export default function HomeClient({ initialData }: HomeClientProps) {
{/* Navigation to Sections */} {/* Navigation to Sections */}
<section className="py-5 sm:py-14 bg-medical-gray-50 border-y border-medical-gray-100 font-sans"> <section className="py-8 sm:py-14 bg-medical-gray-50 border-y border-medical-gray-100 font-sans">
<div className="max-w-7xl mx-auto px-4 grid md:grid-cols-2 gap-5 sm:gap-8"> <div className="max-w-7xl mx-auto px-4 grid md:grid-cols-2 gap-5 sm:gap-8">
{/* Specialty Shop Card */} {/* Specialty Shop Card */}
<Link <Link
href="/shop" href="/shop"
className="group relative overflow-hidden rounded-2xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-blue-50/50 to-canina-blue/10 p-4 sm:p-10 border border-blue-200/70 shadow-xs sm:shadow-md hover:shadow-2xl hover:border-canina-blue/50 hover:-translate-y-1 transition-all duration-500 block" className="group relative overflow-hidden rounded-3xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-blue-50/50 to-canina-blue/10 p-6 sm:p-10 border border-blue-200/70 shadow-md hover:shadow-2xl hover:border-canina-blue/50 hover:-translate-y-1 transition-all duration-500 block"
> >
{/* Ambient Glows */} {/* Ambient Glows */}
<div className="absolute -top-16 -left-16 w-44 h-44 bg-canina-blue/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" /> <div className="absolute -top-16 -left-16 w-44 h-44 bg-canina-blue/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" />
@@ -112,7 +112,7 @@ export default function HomeClient({ initialData }: HomeClientProps) {
{/* Scientific Wiki Card */} {/* Scientific Wiki Card */}
<Link <Link
href="/wiki" href="/wiki"
className="group relative overflow-hidden rounded-2xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-emerald-50/50 to-teal-500/10 p-4 sm:p-10 border border-emerald-200/70 shadow-xs sm:shadow-md hover:shadow-2xl hover:border-emerald-500/50 hover:-translate-y-1 transition-all duration-500 block" className="group relative overflow-hidden rounded-3xl sm:rounded-[2.5rem] bg-gradient-to-br from-white via-emerald-50/50 to-teal-500/10 p-6 sm:p-10 border border-emerald-200/70 shadow-md hover:shadow-2xl hover:border-emerald-500/50 hover:-translate-y-1 transition-all duration-500 block"
> >
{/* Ambient Glows */} {/* Ambient Glows */}
<div className="absolute -top-16 -left-16 w-44 h-44 bg-emerald-500/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" /> <div className="absolute -top-16 -left-16 w-44 h-44 bg-emerald-500/15 rounded-full blur-3xl group-hover:scale-150 transition-transform duration-700 pointer-events-none" />
@@ -147,7 +147,7 @@ export default function HomeClient({ initialData }: HomeClientProps) {
</section> </section>
{/* About Section Teaser */} {/* About Section Teaser */}
<section className="py-5 sm:py-16 bg-white overflow-hidden font-sans"> <section className="py-8 sm:py-16 bg-white overflow-hidden font-sans">
<div className="max-w-7xl mx-auto px-4 grid lg:grid-cols-2 gap-8 lg:gap-24 items-center"> <div className="max-w-7xl mx-auto px-4 grid lg:grid-cols-2 gap-8 lg:gap-24 items-center">
<div className="relative overflow-hidden rounded-2xl sm:rounded-[3rem]"> <div className="relative overflow-hidden rounded-2xl sm:rounded-[3rem]">
<div className="absolute -top-10 -right-10 w-40 h-40 bg-canina-blue/5 rounded-full blur-3xl" /> <div className="absolute -top-10 -right-10 w-40 h-40 bg-canina-blue/5 rounded-full blur-3xl" />
@@ -1,33 +0,0 @@
import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
export async function GET() {
const commitSha =
process.env.NEXT_PUBLIC_GIT_COMMIT ||
process.env.GIT_COMMIT_SHA ||
process.env.COMMIT_SHA ||
'local-build';
const buildTime =
process.env.BUILD_TIMESTAMP ||
process.env.NEXT_PUBLIC_BUILD_TIME ||
new Date().toISOString();
const environment = process.env.NODE_ENV || 'production';
const service = 'frontend';
return NextResponse.json({
status: 'ok',
service,
commitSha,
buildTime,
environment,
}, {
status: 200,
headers: {
'Cache-Control': 'no-store, no-cache, must-revalidate',
'X-Commit-Sha': commitSha,
},
});
}
@@ -1,19 +0,0 @@
import { describe, it, expect } from 'vitest';
import { GET } from './route';
describe('Deployment Metadata Endpoint Gate (UX-37)', () => {
it('returns valid deployment signature, status and commit header', async () => {
const response = await GET();
expect(response.status).toBe(200);
const data = await response.json();
expect(data.status).toBe('ok');
expect(data.service).toBe('frontend');
expect(data).toHaveProperty('commitSha');
expect(data).toHaveProperty('buildTime');
expect(data).toHaveProperty('environment');
expect(response.headers.get('Cache-Control')).toBe('no-store, no-cache, must-revalidate');
expect(response.headers.get('X-Commit-Sha')).toBeDefined();
});
});
@@ -1,104 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import BlogPostPage from './page';
vi.mock('../../../lib/seo', () => ({
getSeoConfig: vi.fn().mockResolvedValue({
brandNameFa: 'کنینا ایران',
canonicalBaseUrl: 'https://canina.ir',
ogImageUrl: '/assets/og.jpg',
defaultMetaDescription: 'توضیحات پیش‌فرض',
titleSeparator: '|',
titlePosition: 'suffix',
}),
formatPageTitle: vi.fn((title) => `${title} | کنینا ایران`),
}));
vi.mock('../../../components/BlogPostClient', () => ({
default: () => <div data-testid="blog-post-client" />,
}));
describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
beforeEach(() => {
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
it('injects FAQPage JSON-LD schema when article contains questions and answers', async () => {
const blogData = {
slug: 'joint-health',
title: 'سلامت مفاصل سگ',
content: `
<article>
<p>مقدمه‌ای درباره مفاصل سگ.</p>
<details>
<summary>آیا این مکمل برای سگ مسن مناسب است؟</summary>
<p>بله، بسیار توصیه می‌شود و روند تخریب مفصل را کند می‌کند.</p>
</details>
</article>
`,
createdAt: '2026-01-01',
publishedAt: '2026-01-01',
};
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => blogData,
})
);
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'joint-health' }) });
expect(jsx).toBeDefined();
// Verify scripts in JSX tree
const scripts = React.Children.toArray(jsx.props.children).filter(
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
);
// There should be 3 schemas: Article, Breadcrumb, and FAQPage
expect(scripts.length).toBe(3);
const faqScript: any = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
expect(faqScript).toBeDefined();
const faqJson = JSON.parse(faqScript.props.dangerouslySetInnerHTML.__html);
expect(faqJson['@type']).toBe('FAQPage');
expect(faqJson.mainEntity).toHaveLength(1);
expect(faqJson.mainEntity[0].name).toBe('آیا این مکمل برای سگ مسن مناسب است؟');
});
it('does not inject FAQPage schema when article does not have FAQs', async () => {
const blogData = {
slug: 'nutrition',
title: 'تغذیه سگ',
content: '<p>یک مقاله ساده بدون سوال و جواب یا آکاردئون.</p>',
createdAt: '2026-01-01',
publishedAt: '2026-01-01',
};
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => blogData,
})
);
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'nutrition' }) });
const scripts = React.Children.toArray(jsx.props.children).filter(
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
);
// Only Article and Breadcrumb schemas
expect(scripts.length).toBe(2);
const faqScript = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
expect(faqScript).toBeUndefined();
});
});
+1 -16
View File
@@ -4,8 +4,6 @@ import type { Metadata } from 'next';
import BlogPostClient from "../../../components/BlogPostClient"; import BlogPostClient from "../../../components/BlogPostClient";
import { getSeoConfig, formatPageTitle } from "../../../lib/seo"; import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
import { safeJsonLd } from "../../../lib/schema"; import { safeJsonLd } from "../../../lib/schema";
import { sanitizeBlogHtml } from "../../../lib/sanitizeBlogHtml";
import { extractFaqsFromHtml, generateFAQPageSchema } from "../../../lib/extractFaqs";
function safeIso(val: any, fallback?: string): string | undefined { function safeIso(val: any, fallback?: string): string | undefined {
if (!val) return fallback; if (!val) return fallback;
@@ -83,7 +81,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str
const ogTitle = blog.ogTitle || title; const ogTitle = blog.ogTitle || title;
const ogDesc = blog.ogDescription || description; const ogDesc = blog.ogDescription || description;
const isStaging = const isStaging =
process.env.NEXT_PUBLIC_APP_ENV === 'staging' || process.env.NEXT_PUBLIC_APP_ENV === 'staging' ||
process.env.NODE_ENV !== 'production' || process.env.NODE_ENV !== 'production' ||
siteUrl.includes('stage') || siteUrl.includes('stage') ||
@@ -184,7 +182,6 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString(); const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
const modifiedIso = safeIso(blog.updatedAt) || publishedIso; const modifiedIso = safeIso(blog.updatedAt) || publishedIso;
const sanitizedContent = sanitizeBlogHtml(blog.content);
const schemaType = blog.schemaType || 'BlogPosting'; const schemaType = blog.schemaType || 'BlogPosting';
const authorSchema = blog.author && (blog.author.firstName || blog.author.lastName) const authorSchema = blog.author && (blog.author.firstName || blog.author.lastName)
@@ -268,10 +265,6 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
], ],
}; };
// SEO-P1-07: Auto-detect and inject FAQPage Schema when article content contains Q&As or accordion structures
const extractedFaqs = extractFaqsFromHtml(blog.content || '');
const faqPageSchema = generateFAQPageSchema(extractedFaqs);
return ( return (
<> <>
<script <script
@@ -282,18 +275,10 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
type="application/ld+json" type="application/ld+json"
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbJsonLd) }} dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbJsonLd) }}
/> />
{faqPageSchema && (
<script
type="application/ld+json"
data-testid="faq-schema"
dangerouslySetInnerHTML={{ __html: safeJsonLd(faqPageSchema) }}
/>
)}
<BlogPostClient <BlogPostClient
blog={blog} blog={blog}
publishedDate={publishedDate} publishedDate={publishedDate}
authorName={authorName} authorName={authorName}
sanitizedContent={sanitizedContent}
/> />
</> </>
); );
@@ -1,24 +0,0 @@
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 ? (
<div role="region" aria-label="سبد خرید">
<button onClick={onCheckout}>تکمیل سفارش</button>
<button onClick={onShopNavigate}>مشاهده محصولات</button>
</div>
) : null,
}));
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
describe("/cart route", () => {
it("renders the cart experience and provides journey actions", () => {
render(<CartPage />);
expect(screen.getByRole("heading", { name: "سبد خرید" })).toBeTruthy();
expect(screen.getAllByRole("region", { name: "سبد خرید" })).toHaveLength(1);
expect(screen.getByRole("button", { name: "تکمیل سفارش" })).toBeTruthy();
expect(screen.getByRole("button", { name: "مشاهده محصولات" })).toBeTruthy();
});
});
-19
View File
@@ -1,19 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import CartDrawer from "../../components/CartDrawer";
export default function CartPage() {
const router = useRouter();
return (
<main className="min-h-screen bg-medical-gray-50" dir="rtl">
<h1 className="sr-only">سبد خرید</h1>
<CartDrawer
isOpen
onClose={() => router.push("/")}
onCheckout={() => router.push("/checkout")}
onShopNavigate={() => router.push("/shop")}
/>
</main>
);
}
+1 -1
View File
@@ -42,7 +42,7 @@ export default async function ContactPage() {
type="application/ld+json" type="application/ld+json"
dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbs) }} dangerouslySetInnerHTML={{ __html: safeJsonLd(breadcrumbs) }}
/> />
<div className="bg-medical-gray-50 pt-10 pb-28 sm:py-16 px-4 sm:px-6 lg:px-8 font-vazir" dir="rtl"> <div className="bg-medical-gray-50 py-16 px-4 sm:px-6 lg:px-8 font-vazir" dir="rtl">
<div className="max-w-6xl mx-auto space-y-16"> <div className="max-w-6xl mx-auto space-y-16">
{/* Title */} {/* Title */}
+1 -3
View File
@@ -10,9 +10,7 @@ export default function ErrorBoundary({
reset: () => void; reset: () => void;
}) { }) {
useEffect(() => { useEffect(() => {
if (process.env.NODE_ENV === "development") { console.error("Global Application Error:", error);
console.error("Global Application Error:", error?.message || "Unknown error");
}
}, [error]); }, [error]);
return <ServerErrorPage onRetry={reset} />; return <ServerErrorPage onRetry={reset} />;
+1 -7
View File
@@ -41,7 +41,7 @@
html, body { html, body {
font-family: var(--font-vazir), "Vazirmatn", sans-serif !important; font-family: var(--font-vazir), "Vazirmatn", sans-serif !important;
@apply bg-medical-gray-50 text-medical-gray-900 antialiased w-full max-w-full overflow-x-clip; @apply bg-medical-gray-50 text-medical-gray-900 antialiased max-w-[100vw] overflow-x-hidden;
font-feature-settings: "ss01", "ss02", "cv01", "cv11"; font-feature-settings: "ss01", "ss02", "cv01", "cv11";
} }
@@ -140,12 +140,6 @@
background: var(--color-canina-blue); background: var(--color-canina-blue);
} }
/* Mobile catalog filter edge affordances (clean mask-based fade) */
.mobile-filter-mask {
-webkit-mask-image: linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent 100%);
mask-image: linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent 100%);
}
/* Micro horizontal scrollbar for dark backgrounds (catalog etc.) */ /* Micro horizontal scrollbar for dark backgrounds (catalog etc.) */
.micro-hscroll-dark { .micro-hscroll-dark {
scrollbar-width: thin; scrollbar-width: thin;
@@ -1,82 +0,0 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
// Mock child components to verify presence without side-effects
vi.mock("../components/Hero", () => ({
default: () => <section data-testid="hero-section">Hero</section>,
}));
vi.mock("../components/SmartAdvisor", () => ({
default: () => <section data-testid="smart-advisor-section">SmartAdvisor</section>,
}));
vi.mock("../components/BannerPlacement", () => ({
default: ({ position }: { position: string }) => (
<section data-testid={`banner-placement-${position}`}>BannerPlacement {position}</section>
),
}));
vi.mock("../components/FeaturedProducts", () => ({
default: () => <section data-testid="featured-products-section">FeaturedProducts</section>,
}));
vi.mock("../components/VetGallery", () => ({
default: () => <section data-testid="vet-gallery-section">VetGallery</section>,
}));
vi.mock("../components/TestimonialsSection", () => ({
default: () => <section data-testid="testimonials-section">TestimonialsSection</section>,
}));
vi.mock("../components/BlogPreviewSection", () => ({
default: () => <section data-testid="blog-preview-section">BlogPreviewSection</section>,
}));
vi.mock("../components/FAQSection", () => ({
default: () => <section data-testid="faq-section">FAQSection</section>,
}));
vi.mock("next/link", () => ({
default: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
}));
vi.mock("next/image", () => ({
default: ({ src, alt, ...props }: any) => <img src={src} alt={alt} {...props} />,
}));
vi.mock("../lib/services/api", () => ({
default: {
get: vi.fn().mockReturnValue(new Promise(() => {})), // Avoid triggering state updates during test
},
}));
vi.mock("../lib/store/settingsStore", () => ({
useSettingsStore: (selector?: any) => {
const s = { getText: (k: string, d: string) => d };
return typeof selector === "function" ? selector(s) : s;
},
}));
import HomeClient from "./HomeClient";
describe("Home Sections Mobile Retention Gate (UX-35)", () => {
it("strictly retains 100% of all core Home sections and feature cards without mobile exclusion or deletion", () => {
const { container } = render(<HomeClient initialData={null} />);
// Verify presence of all major sections
expect(screen.getByTestId("hero-section")).toBeTruthy();
expect(screen.getByTestId("smart-advisor-section")).toBeTruthy();
expect(screen.getByTestId("banner-placement-home_middle")).toBeTruthy();
expect(screen.getByTestId("featured-products-section")).toBeTruthy();
expect(screen.getByTestId("vet-gallery-section")).toBeTruthy();
expect(screen.getByTestId("testimonials-section")).toBeTruthy();
expect(screen.getByTestId("blog-preview-section")).toBeTruthy();
expect(screen.getByTestId("faq-section")).toBeTruthy();
// Verify navigation specialty cards
expect(screen.getByText("داروخانه تخصصی مکمل‌ها")).toBeTruthy();
expect(screen.getByText("دانشنامه علمی و مقالات")).toBeTruthy();
// Ensure none of the sections have `hidden` alone as a display class on mobile
const sections = container.querySelectorAll("section");
expect(sections.length).toBeGreaterThanOrEqual(10);
sections.forEach((sec) => {
const classList = sec.className.split(/\s+/);
expect(classList).not.toContain("hidden");
});
});
});
+1 -16
View File
@@ -71,10 +71,6 @@ export async function generateMetadata(): Promise<Metadata> {
}, },
alternates: { alternates: {
canonical: '/', canonical: '/',
languages: {
'fa-IR': `${siteUrl}/`,
'x-default': `${siteUrl}/`,
},
}, },
formatDetection: { formatDetection: {
email: false, email: false,
@@ -152,12 +148,7 @@ export default async function RootLayout({
}, },
}; };
const rootSchemaGraph = { const safeJsonLd = JSON.stringify([orgSchema, webSiteSchema]).replace(/</g, '\\u003c');
'@context': 'https://schema.org',
'@graph': [orgSchema, webSiteSchema],
};
const safeJsonLd = JSON.stringify(rootSchemaGraph).replace(/</g, '\\u003c');
const gaId = config.googleAnalyticsId?.trim(); const gaId = config.googleAnalyticsId?.trim();
const isGaEnabled = Boolean(gaId && config.enableGoogleAnalytics !== false); const isGaEnabled = Boolean(gaId && config.enableGoogleAnalytics !== false);
@@ -178,12 +169,6 @@ export default async function RootLayout({
<link rel="dns-prefetch" href="https://scripts.clarity.ms" /> <link rel="dns-prefetch" href="https://scripts.clarity.ms" />
</head> </head>
<body className="min-h-screen bg-medical-gray-50 font-sans" suppressHydrationWarning> <body className="min-h-screen bg-medical-gray-50 font-sans" suppressHydrationWarning>
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:right-4 focus:z-[999999] focus:px-4 focus:py-2.5 focus:bg-canina-blue focus:text-white focus:font-black focus:rounded-xl focus:shadow-2xl focus:outline-none focus:ring-2 focus:ring-white font-vazir text-sm transition-all"
>
پرش به محتوای اصلی
</a>
{/* Google Tag Manager (noscript fallback) */} {/* Google Tag Manager (noscript fallback) */}
{isGtmEnabled && ( {isGtmEnabled && (
<noscript> <noscript>
@@ -1,17 +0,0 @@
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 ? <div role="dialog">ورود به حساب</div> : null,
}));
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
describe("/login route", () => {
it("renders the authentication experience instead of a missing-page route", () => {
render(<LoginPage />);
expect(screen.getByRole("heading", { name: "ورود یا ثبت‌نام" })).toBeTruthy();
expect(screen.getAllByRole("dialog")).toHaveLength(1);
});
});
-14
View File
@@ -1,14 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import AuthModal from "../../components/AuthModal";
export default function LoginPage() {
const router = useRouter();
return (
<main className="min-h-screen bg-medical-gray-50 px-4 py-12" dir="rtl">
<h1 className="sr-only">ورود یا ثبت‌نام</h1>
<AuthModal isOpen onClose={() => router.push("/")} />
</main>
);
}
@@ -1,284 +0,0 @@
"use client";
import React, { useState } from "react";
import {
Stethoscope,
Upload,
CheckCircle2,
ShieldCheck,
FileText,
Clock,
Send,
Phone,
Sparkles,
AlertCircle
} from "lucide-react";
import { toast } from "sonner";
import api from "../../lib/services/api";
export default function PrescriptionPageClient() {
const [file, setFile] = useState<File | null>(null);
const [phone, setPhone] = useState("");
const [petName, setPetName] = useState("");
const [petType, setPetType] = useState<"سگ" | "گربه">("سگ");
const [notes, setNotes] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
setFile(e.target.files[0]);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!file) {
toast.error("لطفاً تصویر یا فایل PDF نسخه پزشکی را بارگذاری کنید.");
return;
}
const cleanPhone = phone.trim();
if (!/^09\d{9}$/.test(cleanPhone)) {
toast.error("لطفاً یک شماره همراه معتبر ۱۱ رقمی وارد نمایید (مثال: ۰۹۱۲۳۴۵۶۷۸۹).");
return;
}
setIsSubmitting(true);
try {
// 1. Submit to public B2B inquiry endpoint with prescription classification
await api.post("/b2b/inquire", {
companyName: `نسخه پزشکی دامپزشک (${petType} به نام ${petName || 'بدون نام'})`,
contactName: petName ? `سرپرست: ${petName}` : "مراجعه‌کننده آنلاین",
email: `rx-${Date.now()}@canina.ir`,
phone: cleanPhone,
businessType: `ثبت نسخه دارویی (${petType})`,
estimatedVolume: "نسخه تک‌موردی بیمار",
message: `نام پت: ${petName || 'قید نشده'} | گونه: ${petType} | فایل: ${file.name} | توضیحات نسخه: ${notes || 'توضیحی ثبت نشده'}`,
});
setIsSubmitting(false);
setIsSuccess(true);
toast.success("نسخه پزشکی شما با موفقیت ثبت شد. دامپزشک کشیک کنینا به زودی با شما تماس خواهد گرفت.");
} catch {
setIsSubmitting(false);
toast.error("خطایی در ثبت اطلاعات نسخه رخ داد. لطفاً مجدداً تلاش کنید.");
}
};
return (
<div className="bg-medical-gray-50 min-h-screen font-vazir py-12 px-4 sm:px-6 lg:px-8" dir="rtl">
<div className="max-w-4xl mx-auto space-y-8">
{/* Header */}
<div className="text-center space-y-4">
<div className="inline-flex items-center gap-2 px-4 py-2 bg-emerald-50 text-emerald-800 border border-emerald-200 rounded-full text-xs font-bold shadow-xs">
<Stethoscope className="w-4 h-4 text-emerald-600" />
سامانه رسمی ارزیابی و تطبیق نسخه دارویی پت
</div>
<h1 className="text-3xl sm:text-4xl font-black text-medical-gray-900 tracking-tight">
ثبت آنلاین نسخه دامپزشک و تطبیق مکمل‌های <span className="text-canina-blue">کنینا آلمان</span>
</h1>
<p className="text-sm sm:text-base text-medical-gray-600 max-w-2xl mx-auto leading-relaxed">
نسخه تجویزی پزشک معالج همدم خود را بارگذاری نمایید تا کادر دامپزشکان متخصص کنینا ایران مکمل‌های دارویی اصل و سازگار با دوز تجویزی را ارزیابی و به شما معرفی کنند.
</p>
</div>
{/* Benefits bar */}
<div className="grid sm:grid-cols-3 gap-4">
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
<ShieldCheck className="w-5 h-5" />
</div>
<div>
<h4 className="text-xs font-black text-medical-gray-900">تطبیق دقیق دارویی</h4>
<p className="text-[11px] text-medical-gray-500">معادل‌سازی برندهای آلمانی و دوز</p>
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-blue-50 text-canina-blue flex items-center justify-center shrink-0">
<Clock className="w-5 h-5" />
</div>
<div>
<h4 className="text-xs font-black text-medical-gray-900">پاسخگویی سریع</h4>
<p className="text-[11px] text-medical-gray-500">بررسی توسط دامپزشک زیر ۲ ساعت</p>
</div>
</div>
<div className="bg-white p-4 rounded-2xl border border-medical-gray-200 shadow-xs flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
<Sparkles className="w-5 h-5" />
</div>
<div>
<h4 className="text-xs font-black text-medical-gray-900">مشاوره تغذیه رایگان</h4>
<p className="text-[11px] text-medical-gray-500">همراه با راهنمای رژیم و دوز مصرف</p>
</div>
</div>
</div>
{/* Form Card */}
<div className="bg-white rounded-3xl border border-medical-gray-200 shadow-xl overflow-hidden p-6 sm:p-10">
{isSuccess ? (
<div className="text-center py-12 space-y-4">
<div className="w-20 h-20 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto shadow-lg shadow-emerald-500/20">
<CheckCircle2 className="w-10 h-10" />
</div>
<h3 className="text-2xl font-black text-medical-gray-900">نسخه پزشکی با موفقیت ثبت شد</h3>
<p className="text-sm text-medical-gray-600 max-w-md mx-auto leading-relaxed">
اطلاعات نسخه برای کادر دامپزشکی کنینا ارسال شد. همکاران ما پس از بررسی دقیق فرمولاسیون و انطباق دوز دارویی، از طریق شماره تماس واردشده با شما ارتباط خواهند گرفت.
</p>
<button
type="button"
onClick={() => {
setFile(null);
setNotes("");
setPetName("");
setIsSuccess(false);
}}
className="inline-flex items-center gap-2 bg-canina-blue text-white px-6 py-3 rounded-xl font-bold text-xs shadow-md hover:bg-canina-blue/90 transition-all cursor-pointer"
>
ثبت نسخه جدید دیگر
</button>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-6">
{/* Pet Info */}
<div className="grid sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-bold text-medical-gray-700 mb-2">
گونه حیوان خانگی <span className="text-red-500">*</span>
</label>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => setPetType("سگ")}
className={`p-3 rounded-2xl border text-xs font-black flex items-center justify-center gap-2 transition-all cursor-pointer ${
petType === "سگ"
? "border-canina-blue bg-blue-50/50 text-canina-blue ring-2 ring-canina-blue/20"
: "border-medical-gray-200 text-medical-gray-600 hover:bg-medical-gray-50"
}`}
>
🐶 سگ
</button>
<button
type="button"
onClick={() => setPetType("گربه")}
className={`p-3 rounded-2xl border text-xs font-black flex items-center justify-center gap-2 transition-all cursor-pointer ${
petType === "گربه"
? "border-canina-blue bg-blue-50/50 text-canina-blue ring-2 ring-canina-blue/20"
: "border-medical-gray-200 text-medical-gray-600 hover:bg-medical-gray-50"
}`}
>
🐱 گربه
</button>
</div>
</div>
<div>
<label htmlFor="rx-petName" className="block text-xs font-bold text-medical-gray-700 mb-2">
نام همدم (پت)
</label>
<input
id="rx-petName"
type="text"
placeholder="مثال: لئو، ببری، جسی..."
value={petName}
onChange={(e) => setPetName(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all"
/>
</div>
</div>
{/* Phone */}
<div>
<label htmlFor="rx-phone" className="block text-xs font-bold text-medical-gray-700 mb-2">
شماره تماس همراه (جهت دریافت نتیجه ارزیابی) <span className="text-red-500">*</span>
</label>
<div className="relative">
<input
id="rx-phone"
type="tel"
required
placeholder="۰۹۱۲۳۴۵۶۷۸۹"
value={phone}
onChange={(e) => setPhone(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 pl-10 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all dir-ltr text-right"
/>
<Phone className="w-4 h-4 text-medical-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
</div>
</div>
{/* File Upload Zone */}
<div>
<label className="block text-xs font-bold text-medical-gray-700 mb-2">
بارگذاری تصویر یا فایل PDF نسخه <span className="text-red-500">*</span>
</label>
<div className="relative border-2 border-dashed border-medical-gray-300 hover:border-canina-blue rounded-3xl p-6 sm:p-8 text-center transition-all bg-medical-gray-50/50 hover:bg-blue-50/20">
<input
id="rx-file-input"
type="file"
accept="image/jpeg,image/png,image/webp,application/pdf"
required
onChange={handleFileChange}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
/>
<div className="space-y-3 pointer-events-none">
<div className="w-14 h-14 rounded-2xl bg-canina-blue/10 text-canina-blue flex items-center justify-center mx-auto">
<Upload className="w-7 h-7" />
</div>
{file ? (
<div className="space-y-1">
<p className="text-sm font-black text-medical-gray-900">{file.name}</p>
<p className="text-xs text-emerald-600 font-bold">فایل با موفقیت انتخاب شد (برای تغییر کلیک کنید)</p>
</div>
) : (
<div className="space-y-1">
<p className="text-sm font-black text-medical-gray-900">
برای انتخاب فایل یا عکس نسخه، اینجا کلیک کنید یا فایل را بکشید
</p>
<p className="text-xs text-medical-gray-400">
فرمت‌های مجاز: JPG, PNG, WEBP یا PDF (حداکثر ۱۰ مگابایت)
</p>
</div>
)}
</div>
</div>
</div>
{/* Notes */}
<div>
<label htmlFor="rx-notes" className="block text-xs font-bold text-medical-gray-700 mb-2">
توضیحات تکمیلی یا علائم حیوان (اختیاری)
</label>
<textarea
id="rx-notes"
rows={3}
placeholder="اگر حیوان به ماده غذایی خاصی حساسیت دارد یا داروی همزمانی مصرف می‌کند در اینجا ذکر فرمایید..."
value={notes}
onChange={(e) => setNotes(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl px-4 py-3 text-sm text-medical-gray-900 focus:bg-white focus:border-canina-blue focus:ring-4 focus:ring-canina-blue/10 outline-none transition-all"
/>
</div>
{/* Submit Button */}
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-canina-blue hover:bg-canina-blue/90 text-white font-black text-base py-4 rounded-2xl shadow-xl shadow-canina-blue/20 transition-all flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
>
{isSubmitting ? (
<span>در حال ارسال نسخه و ثبت درخواست...</span>
) : (
<>
<Send className="w-5 h-5" />
<span>ارسال و ثبت نسخه جهت ارزیابی دامپزشک</span>
</>
)}
</button>
</form>
)}
</div>
</div>
</div>
);
}
@@ -1,16 +0,0 @@
import React from "react";
import type { Metadata } from "next";
import PrescriptionPageClient from "./PrescriptionPageClient";
import { getPageMetadata } from "../../lib/seo";
export async function generateMetadata(): Promise<Metadata> {
return getPageMetadata('prescriptions', {
canonicalPath: '/prescriptions',
fallbackTitle: 'ثبت و ارزیابی نسخه دامپزشک | مشاوره تخصصی دارویی کنینا ایران',
fallbackDesc: 'سامانه آنلاین آپلود و تحلیل نسخه دامپزشک جهت تطبیق با مکمل‌های دارویی اصل Canina Pharma آلمان با نظارت کادر مجرب دامپزشکان.',
});
}
export default function PrescriptionPage() {
return <PrescriptionPageClient />;
}
@@ -1,61 +0,0 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render, fireEvent, waitFor } from "@testing-library/react";
const mockPost = vi.fn().mockResolvedValue({ data: { success: true } });
vi.mock("axios", () => {
const mAxios = {
post: vi.fn(() => Promise.resolve({ data: { success: true } })),
get: vi.fn(() => Promise.resolve({ data: { success: true } })),
interceptors: {
request: { use: vi.fn(), eject: vi.fn() },
response: { use: vi.fn(), eject: vi.fn() },
},
create: () => mAxios,
};
return { default: mAxios };
});
vi.mock("sonner", () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
import api from "../../lib/services/api";
import PrescriptionPageClient from "./PrescriptionPageClient";
describe("PrescriptionPageClient Suite (B2B-03)", () => {
it("renders online prescription portal and submits without requiring login", async () => {
const { container } = render(<PrescriptionPageClient />);
const phoneInput = container.querySelector("#rx-phone") as HTMLInputElement;
const petNameInput = container.querySelector("#rx-petName") as HTMLInputElement;
const fileInput = container.querySelector("#rx-file-input") as HTMLInputElement;
const form = container.querySelector("form") as HTMLFormElement;
expect(phoneInput).not.toBeNull();
expect(fileInput).not.toBeNull();
expect(form).not.toBeNull();
// Create fake file
const fakeFile = new File(["dummy content"], "prescription.jpg", { type: "image/jpeg" });
fireEvent.change(phoneInput, { target: { value: "09121114455" } });
fireEvent.change(petNameInput, { target: { value: "لئو" } });
fireEvent.change(fileInput, { target: { files: [fakeFile] } });
fireEvent.submit(form);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith(
"/b2b/inquire",
expect.objectContaining({
phone: "09121114455",
companyName: expect.stringContaining("لئو"),
})
);
});
});
});
@@ -1,95 +0,0 @@
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) => <a href={href} {...props}>{children}</a>,
}));
vi.mock("next/image", () => ({
default: (props: any) => <img {...props} />,
}));
// Mock sub-components with exact path matching
vi.mock("../components/AuthModal", () => ({
default: ({ isOpen, onClose }: any) => (
<div data-testid="auth-modal" data-isopen={String(isOpen)}>
<button onClick={onClose}>بستن</button>
</div>
),
}));
vi.mock("../components/CartDrawer", () => ({
default: ({ isOpen, onCheckout, onShopNavigate }: any) => (
<div data-testid="cart-drawer" data-isopen={String(isOpen)}>
<button onClick={onCheckout}>تکمیل سفارش</button>
<button onClick={onShopNavigate}>فروشگاه</button>
</div>
),
}));
vi.mock("../components/PetProfile", () => ({
default: () => <div data-testid="pet-profile-component">Pet Profile</div>,
}));
vi.mock("../components/VideosPage", () => ({
default: ({ initialVideos }: any) => (
<div data-testid="videos-page-component">Videos: {initialVideos?.length || 0}</div>
),
}));
vi.mock("../components/SmartAdvisor", () => ({
default: () => <div data-testid="smart-advisor-component">Smart Advisor</div>,
}));
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(<LoginPage />);
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(<CartPage />);
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(<ProfilePage />);
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(<SmartAdvisorPage />);
const h1 = screen.getByRole("heading", { level: 1 });
expect(h1.textContent).toMatch(/مشاوره تخصصی و راهنمای/);
expect(screen.getByTestId("smart-advisor-component")).toBeTruthy();
});
});
-2
View File
@@ -37,8 +37,6 @@ export default function robots(): MetadataRoute.Robots {
`${baseUrl}/sitemap.xml`, `${baseUrl}/sitemap.xml`,
`${baseUrl}/sitemap-products.xml`, `${baseUrl}/sitemap-products.xml`,
`${baseUrl}/sitemap-categories.xml`, `${baseUrl}/sitemap-categories.xml`,
`${baseUrl}/sitemap-blog.xml`,
`${baseUrl}/sitemap-wiki.xml`,
], ],
}; };
} }
-1
View File
@@ -7,7 +7,6 @@ export async function generateMetadata(): Promise<Metadata> {
canonicalPath: '/search', canonicalPath: '/search',
fallbackTitle: 'جستجوی هوشمند مکمل‌ها و دانشنامه سلامت', fallbackTitle: 'جستجوی هوشمند مکمل‌ها و دانشنامه سلامت',
fallbackDesc: 'جستجوی سریع در کاتالوگ محصولات، بیماری‌ها، علائم بالینی و مقالات سلامت کنینا ایران.', fallbackDesc: 'جستجوی سریع در کاتالوگ محصولات، بیماری‌ها، علائم بالینی و مقالات سلامت کنینا ایران.',
noIndex: true,
}); });
} }
@@ -1,4 +1,3 @@
import { notFound } from 'next/navigation';
import ProductPage from "../../../components/ProductPage"; import ProductPage from "../../../components/ProductPage";
import { productService } from "../../../lib/services/productService"; import { productService } from "../../../lib/services/productService";
import type { Metadata } from 'next'; import type { Metadata } from 'next';
@@ -134,7 +133,7 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl
const product = await productService.getProductBySlug(resolvedParams.slug); const product = await productService.getProductBySlug(resolvedParams.slug);
if (!product) { if (!product) {
notFound(); return <ProductPage productSlug={resolvedParams.slug} />;
} }
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir'; const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
@@ -350,7 +349,7 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl
</div> </div>
</div> </div>
}> }>
<ProductPage productSlug={resolvedParams.slug} initialProduct={product} /> <ProductPage productSlug={resolvedParams.slug} />
</Suspense> </Suspense>
</> </>
); );
-7
View File
@@ -1,8 +1,6 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import ArchivePage from "../../components/ArchivePage"; import ArchivePage from "../../components/ArchivePage";
import { getPageMetadata } from "../../lib/seo"; import { getPageMetadata } from "../../lib/seo";
import { productService } from "../../lib/services/productService";
import type { PetType } from "../../lib/data/products";
export async function generateMetadata({ export async function generateMetadata({
searchParams, searchParams,
@@ -43,9 +41,6 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [
const symptomsParam = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : ""; const symptomsParam = typeof resolvedParams.symptoms === 'string' ? resolvedParams.symptoms : "";
const symptomSingle = typeof resolvedParams.symptom === 'string' ? resolvedParams.symptom : ""; const symptomSingle = typeof resolvedParams.symptom === 'string' ? resolvedParams.symptom : "";
const symptoms = symptomsParam || (symptomSingle ? symptomSingle : ""); 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 ( return (
<ArchivePage <ArchivePage
@@ -53,8 +48,6 @@ export default async function Shop({ searchParams }: { searchParams: Promise<{ [
initialSearch={search} initialSearch={search}
initialPetType={petType} initialPetType={petType}
initialSymptoms={symptoms} initialSymptoms={symptoms}
initialProducts={initialProducts}
initialPage={initialPage}
/> />
); );
} }
@@ -1,78 +0,0 @@
import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
export const revalidate = 3600; // Revalidate every hour
type SitemapBlog = {
slug: string;
noIndex?: boolean;
status: string;
updatedAt?: string;
createdAt?: string;
featured?: boolean;
title?: string;
imageUrl?: string;
ogImage?: string;
};
export async function GET() {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
const apiUrl =
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
const blogRoutes: SitemapBlog[] = [];
try {
let page = 1;
let lastPage = 1;
do {
const res = await fetch(`${apiBase}/blogs?page=${page}&limit=20`, { cache: 'no-store' });
if (!res.ok) throw new Error(`Blog sitemap request failed: ${res.status}`);
const data = await res.json();
const blogsList: SitemapBlog[] = data.data || [];
if (!blogsList.length) break;
const validBlogs = blogsList.filter((b) => !b.noIndex && b.status === 'PUBLISHED');
blogRoutes.push(...validBlogs);
lastPage = Number(data.meta?.lastPage) || 1;
page += 1;
} while (page <= lastPage);
} catch (err) {
console.error('Failed to fetch blogs for sitemap-blog.xml:', err);
}
const urlsXml = blogRoutes
.map((blog) => {
const loc = `${baseUrl}/blog/${encodeURIComponent(blog.slug)}`;
const lastmod = blog.updatedAt
? new Date(blog.updatedAt).toISOString()
: blog.createdAt
? new Date(blog.createdAt).toISOString()
: new Date().toISOString();
const priority = blog.featured ? '0.9' : '0.7';
const primaryImg = blog.ogImage || blog.imageUrl;
const title = blog.title || 'مقاله وبلاگ تخصصی کنینا';
const imageTag = primaryImg
? `\n <image:image>\n <image:loc>${
primaryImg.startsWith('http') ? primaryImg : `${baseUrl}${primaryImg.startsWith('/') ? '' : '/'}${primaryImg}`
}</image:loc>\n <image:title><![CDATA[${title}]]></image:title>\n </image:image>`
: '';
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>${priority}</priority>${imageTag}\n </url>`;
})
.join('\n');
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"\n xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n${urlsXml}\n</urlset>`;
return new NextResponse(xmlContent, {
status: 200,
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
},
});
}
@@ -1,64 +0,0 @@
import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
export const revalidate = 86400; // Revalidate daily
type SitemapWikiTerm = {
key: string;
term: string;
definition?: string;
updatedAt?: string;
createdAt?: string;
};
export async function GET() {
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
const apiUrl =
process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api';
const normalizedApiUrl = apiUrl.replace(/\/$/, '');
const apiBase = normalizedApiUrl.endsWith('/api') ? normalizedApiUrl : `${normalizedApiUrl}/api`;
const wikiRoutes: SitemapWikiTerm[] = [];
try {
let page = 1;
let lastPage = 1;
do {
const res = await fetch(`${apiBase}/wiki?page=${page}&limit=50`, { cache: 'no-store' });
if (!res.ok) throw new Error(`Wiki sitemap request failed: ${res.status}`);
const data = await res.json();
const wikiList: SitemapWikiTerm[] = data.data || [];
if (!wikiList.length) break;
wikiRoutes.push(...wikiList);
lastPage = Number(data.meta?.lastPage) || 1;
page += 1;
} while (page <= lastPage);
} catch (err) {
console.error('Failed to fetch wiki terms for sitemap-wiki.xml:', err);
}
const urlsXml = wikiRoutes
.map((item) => {
const loc = `${baseUrl}/wiki/${encodeURIComponent(item.key)}`;
const lastmod = item.updatedAt
? new Date(item.updatedAt).toISOString()
: item.createdAt
? new Date(item.createdAt).toISOString()
: new Date().toISOString();
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n <changefreq>weekly</changefreq>\n <priority>0.8</priority>\n </url>`;
})
.join('\n');
const xmlContent = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urlsXml}\n</urlset>`;
return new NextResponse(xmlContent, {
status: 200,
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Cache-Control': 'public, max-age=86400, s-maxage=86400, stale-while-revalidate=604800',
},
});
}
+6 -1
View File
@@ -30,7 +30,12 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
changeFrequency: 'weekly', changeFrequency: 'weekly',
priority: 0.8, priority: 0.8,
}, },
{
url: `${baseUrl}/search`,
lastModified: new Date(),
changeFrequency: 'weekly',
priority: 0.5,
},
{ {
url: `${baseUrl}/about`, url: `${baseUrl}/about`,
lastModified: new Date(), lastModified: new Date(),
-91
View File
@@ -1,91 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import robots from './robots';
import { GET as getBlogSitemap } from './sitemap-blog.xml/route';
import { GET as getWikiSitemap } from './sitemap-wiki.xml/route';
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
describe('Sub-sitemaps and robots.ts integration (SEO-P1-10)', () => {
it('registers sitemap-blog.xml and sitemap-wiki.xml in robots.ts', () => {
vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'production');
vi.stubEnv('NODE_ENV', 'production');
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
const config = robots();
const sitemaps = Array.isArray(config.sitemap) ? config.sitemap : [config.sitemap];
expect(sitemaps).toContain('https://canina.ir/sitemap.xml');
expect(sitemaps).toContain('https://canina.ir/sitemap-products.xml');
expect(sitemaps).toContain('https://canina.ir/sitemap-categories.xml');
expect(sitemaps).toContain('https://canina.ir/sitemap-blog.xml');
expect(sitemaps).toContain('https://canina.ir/sitemap-wiki.xml');
});
it('generates sitemap-blog.xml correctly with published blogs and image tags', async () => {
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
data: [
{
slug: 'puppy-nutrition',
title: 'تغذیه توله سگ',
status: 'PUBLISHED',
updatedAt: '2026-10-10T12:00:00.000Z',
featured: true,
imageUrl: '/uploads/puppy.jpg',
},
{
slug: 'hidden-blog',
title: 'مقاله پیش‌نویس',
status: 'DRAFT',
},
],
meta: { lastPage: 1 },
}),
});
vi.stubGlobal('fetch', fetchMock);
const res = await getBlogSitemap();
expect(res.status).toBe(200);
const xml = await res.text();
expect(xml).toContain('<loc>https://canina.ir/blog/puppy-nutrition</loc>');
expect(xml).toContain('<priority>0.9</priority>');
expect(xml).toContain('<image:loc>https://canina.ir/uploads/puppy.jpg</image:loc>');
expect(xml).toContain('تغذیه توله سگ');
expect(xml).not.toContain('hidden-blog');
});
it('generates sitemap-wiki.xml correctly with scientific terms', async () => {
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
data: [
{
key: 'omega-3',
term: 'امگا ۳',
updatedAt: '2026-09-01T10:00:00.000Z',
},
],
meta: { lastPage: 1 },
}),
});
vi.stubGlobal('fetch', fetchMock);
const res = await getWikiSitemap();
expect(res.status).toBe(200);
const xml = await res.text();
expect(xml).toContain('<loc>https://canina.ir/wiki/omega-3</loc>');
expect(xml).toContain('<priority>0.8</priority>');
});
});
+13 -29
View File
@@ -1,4 +1,3 @@
import { notFound } from 'next/navigation';
import Link from 'next/link'; import Link from 'next/link';
import { ChevronRight, Sparkles, Package, ArrowLeft, ShieldCheck } from 'lucide-react'; import { ChevronRight, Sparkles, Package, ArrowLeft, ShieldCheck } from 'lucide-react';
import type { Metadata } from 'next'; import type { Metadata } from 'next';
@@ -12,38 +11,15 @@ const apiBase = API_URL.endsWith('/api') ? API_URL : `${API_URL.replace(/\/$/, '
async function getWikiTerm(key: string) { async function getWikiTerm(key: string) {
try { try {
// 1. Try scientific terms endpoint
const res = await fetch(`${apiBase}/wiki/${encodeURIComponent(key)}`, { const res = await fetch(`${apiBase}/wiki/${encodeURIComponent(key)}`, {
next: { revalidate: 3600, tags: ['wiki', `wiki-${key}`] } next: { revalidate: 3600, tags: ['wiki', `wiki-${key}`] }
}); });
if (res.ok) { if (!res.ok) return null;
return await res.json(); return await res.json();
}
} catch (error) { } catch (error) {
console.warn('[Wiki] /wiki/:key failed, trying /ingredients fallback:', error); console.error('[Wiki] Error fetching term:', error);
return null;
} }
try {
// 2. Fallback to ingredients endpoint if slug is an ingredient slug
const ingRes = await fetch(`${apiBase}/ingredients/${encodeURIComponent(key)}`, {
next: { revalidate: 3600, tags: ['ingredients', `ing-${key}`] }
});
if (ingRes.ok) {
const ing = await ingRes.json();
return {
key: ing.slug,
term: ing.nameFa || ing.nameEn || ing.slug,
definition: ing.description || `بررسی تخصصی ترکیب دارویی و خواص ${ing.nameFa || ing.nameEn} در کاتالوگ مکمل‌های کنینا آلمان.`,
metaTitle: `خواص دارویی ${ing.nameFa || ing.nameEn} | دانشنامه کنینا ایران`,
metaDescription: (ing.description || '').slice(0, 155),
wikiId: ing.slug,
};
}
} catch (error) {
console.error('[Wiki] Error fetching ingredient fallback:', error);
}
return null;
} }
async function getRelatedProducts(termName: string) { async function getRelatedProducts(termName: string) {
@@ -105,7 +81,15 @@ export default async function WikiTermPage({ params }: { params: Promise<{ slug:
const term = await getWikiTerm(slug); const term = await getWikiTerm(slug);
if (!term) { if (!term) {
notFound(); return (
<div className="min-h-[50vh] flex flex-col items-center justify-center font-vazir text-center px-4" dir="rtl">
<h1 className="text-3xl font-black text-medical-gray-900 mb-4">ترکیب علمی یافت نشد</h1>
<Link href="/wiki" className="text-canina-blue font-bold flex items-center gap-2">
<ChevronRight className="w-4 h-4" />
بازگشت به دانشنامه
</Link>
</div>
);
} }
const relatedProducts = await getRelatedProducts(term.term); const relatedProducts = await getRelatedProducts(term.term);
+112 -229
View File
@@ -1,7 +1,5 @@
"use client"; "use client";
import { useUserStore } from "../lib/store/userStore";
import React, { useState, useMemo, useEffect, useCallback } from "react"; import React, { useState, useMemo, useEffect, useCallback } from "react";
import { createPortal } from "react-dom";
import { toPersian, isProductOutOfStock } from "../lib/utils"; import { toPersian, isProductOutOfStock } from "../lib/utils";
import { Product, PetType } from "../lib/data/products"; import { Product, PetType } from "../lib/data/products";
import { usePetStore } from "../lib/store/usePetStore"; import { usePetStore } from "../lib/store/usePetStore";
@@ -88,8 +86,7 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
const { addItem } = useCartStore(); const { addItem } = useCartStore();
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id)); const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
const [isAdding, setIsAdding] = useState(false); const [isAdding, setIsAdding] = useState(false);
const isLoggedIn = useUserStore(s => s.isLoggedIn); const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null);
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : null));
const { showPrices, allowCart, showPreorderBtn } = useCatalogMode(); const { showPrices, allowCart, showPreorderBtn } = useCatalogMode();
const productUrl = `/shop/${product.slug || product.id}`; const productUrl = `/shop/${product.slug || product.id}`;
@@ -131,11 +128,15 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
href={productUrl} href={productUrl}
className="group bg-white rounded-[2.5rem] border border-medical-gray-200 overflow-hidden hover:shadow-2xl transition-all flex flex-col h-full relative" className="group bg-white rounded-[2.5rem] border border-medical-gray-200 overflow-hidden hover:shadow-2xl transition-all flex flex-col h-full relative"
> >
{/* SpecialBadge moved below image to avoid covering product photo */} {product.specialBadge && (
<div className="absolute top-4 right-4 z-10 bg-canina-blue text-white text-2xs font-black uppercase tracking-widest px-3 py-1 rounded-full shadow-lg">
{product.specialBadge}
</div>
)}
{compatibility && ( {compatibility && (
<div className={`absolute top-4 right-4 z-10 text-3xs font-black uppercase tracking-widest px-2.5 py-1 rounded-full shadow-md flex items-center gap-1 backdrop-blur-xs ${compatibility.type === 'alert' ? 'bg-amber-500/90 text-white' : <div className={`absolute top-14 right-4 z-10 text-3xs font-black uppercase tracking-widest px-3 py-1 rounded-full shadow-md flex items-center gap-1 ${compatibility.type === 'alert' ? 'bg-amber-100 text-amber-700' :
compatibility.type === 'success' ? 'bg-emerald-600/90 text-white' : 'bg-canina-blue/90 text-white' compatibility.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-medical-gray-100 text-medical-gray-600'
}`}> }`}>
{compatibility.type === 'alert' ? ( {compatibility.type === 'alert' ? (
forBoth ? ( forBoth ? (
@@ -182,13 +183,6 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
</div> </div>
<div className="p-6 flex flex-col flex-1"> <div className="p-6 flex flex-col flex-1">
{product.specialBadge && (
<div className="mb-2">
<span className="inline-block bg-canina-blue/10 text-canina-blue border border-canina-blue/20 text-[10px] font-black px-2.5 py-1 rounded-lg line-clamp-1 font-vazir" title={product.specialBadge}>
{product.specialBadge}
</span>
</div>
)}
<div className="text-2xs font-bold text-canina-blue uppercase tracking-widest mb-2">{product.category}</div> <div className="text-2xs font-bold text-canina-blue uppercase tracking-widest mb-2">{product.category}</div>
<div className="flex flex-col gap-1 mb-3"> <div className="flex flex-col gap-1 mb-3">
<h3 dir="rtl" className="text-base font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors leading-tight text-right font-vazir"> <h3 dir="rtl" className="text-base font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors leading-tight text-right font-vazir">
@@ -223,8 +217,8 @@ export const ArchiveProductCard: React.FC<{ product: Product }> = ({ product })
</span> </span>
) : allowCart ? ( ) : allowCart ? (
cartItem && cartItem.quantity > 0 ? ( cartItem && cartItem.quantity > 0 ? (
<div <div
onClick={(e) => { e.preventDefault(); e.stopPropagation(); }} onClick={(e) => { e.preventDefault(); e.stopPropagation(); }}
className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-xl p-1 shrink-0" className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-xl p-1 shrink-0"
> >
<button <button
@@ -278,8 +272,7 @@ const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) =>
const { addItem } = useCartStore(); const { addItem } = useCartStore();
const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id)); const cartItem = useCartStore((s) => s.items.find(i => i.product.id === product.id));
const [isAdding, setIsAdding] = useState(false); const [isAdding, setIsAdding] = useState(false);
const isLoggedIn = useUserStore(s => s.isLoggedIn); const activePet = usePetStore(state => state.pets.find(p => p.id === state.activePetId) || null);
const activePet = usePetStore(state => (isLoggedIn ? (state.pets.find(p => p.id === state.activePetId) || null) : null));
const productUrl = `/shop/${product.slug || product.id}`; const productUrl = `/shop/${product.slug || product.id}`;
const handleAddToCart = (e: React.MouseEvent) => { const handleAddToCart = (e: React.MouseEvent) => {
@@ -331,7 +324,11 @@ const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) =>
className="w-full h-full group-hover:scale-105 transition-transform duration-500" className="w-full h-full group-hover:scale-105 transition-transform duration-500"
imgClassName="w-full h-full object-contain" imgClassName="w-full h-full object-contain"
/> />
{/* List specialBadge moved below */} {product.specialBadge && (
<div className="absolute top-1 right-1 z-10 bg-canina-blue text-white text-[9px] font-black uppercase px-1.5 py-0.5 rounded-md shadow-xs">
{product.specialBadge}
</div>
)}
<div className="absolute bottom-1 left-1 flex gap-1"> <div className="absolute bottom-1 left-1 flex gap-1">
{forDog && ( {forDog && (
<div className="w-5 h-5 bg-white/90 backdrop-blur-xs rounded-md flex items-center justify-center text-medical-gray-500 border border-medical-gray-100 shadow-2xs" title="مناسب برای سگ"> <div className="w-5 h-5 bg-white/90 backdrop-blur-xs rounded-md flex items-center justify-center text-medical-gray-500 border border-medical-gray-100 shadow-2xs" title="مناسب برای سگ">
@@ -395,8 +392,8 @@ const ArchiveProductListItem: React.FC<{ product: Product }> = ({ product }) =>
</span> </span>
) : allowCart ? ( ) : allowCart ? (
cartItem && cartItem.quantity > 0 ? ( cartItem && cartItem.quantity > 0 ? (
<div <div
onClick={(e) => { e.preventDefault(); e.stopPropagation(); }} onClick={(e) => { e.preventDefault(); e.stopPropagation(); }}
className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-lg p-0.5 shrink-0" className="flex items-center gap-1 bg-canina-blue/10 border border-canina-blue/20 rounded-lg p-0.5 shrink-0"
> >
<button <button
@@ -452,18 +449,12 @@ export default function ArchivePage({
initialCategory = "all", initialCategory = "all",
initialSearch = "", initialSearch = "",
initialPetType = "all", initialPetType = "all",
initialSymptoms = "", initialSymptoms = ""
initialProducts = [],
initialPage = 1,
initialLimit = 12
}: { }: {
initialCategory?: string, initialCategory?: string,
initialSearch?: string, initialSearch?: string,
initialPetType?: string, initialPetType?: string,
initialSymptoms?: string, initialSymptoms?: string
initialProducts?: Product[],
initialPage?: number,
initialLimit?: number
}) { }) {
const router = useRouter(); const router = useRouter();
const getText = useSettingsStore(state => state.getText); const getText = useSettingsStore(state => state.getText);
@@ -472,18 +463,10 @@ export default function ArchivePage({
const [activeSymptoms, setActiveSymptoms] = useState<string[]>(initialSymptoms ? initialSymptoms.split(',') : []); const [activeSymptoms, setActiveSymptoms] = useState<string[]>(initialSymptoms ? initialSymptoms.split(',') : []);
const [searchQuery, setSearchQuery] = useState(initialSearch); const [searchQuery, setSearchQuery] = useState(initialSearch);
const [isUpdating, setIsUpdating] = useState(false); const [isUpdating, setIsUpdating] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null); const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);
const [filteredProducts, setFilteredProducts] = useState<Product[]>(() => orderProductsByAvailability(initialProducts));
const [sortBy, setSortBy] = useState<string>("createdAt"); const [sortBy, setSortBy] = useState<string>("createdAt");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [viewMode, setViewMode] = useState<"list" | "grid">("list"); const [viewMode, setViewMode] = useState<"list" | "grid">("list");
const [currentPage, setCurrentPage] = useState<number>(() => Math.max(1, initialPage));
const pageSize = Math.max(1, initialLimit);
const [isMounted, setIsMounted] = useState<boolean>(false);
useEffect(() => {
setIsMounted(true);
}, []);
const [isMobileSolutionsOpen, setIsMobileSolutionsOpen] = useState(false); const [isMobileSolutionsOpen, setIsMobileSolutionsOpen] = useState(false);
const [isMobileSymptomsOpen, setIsMobileSymptomsOpen] = useState(false); const [isMobileSymptomsOpen, setIsMobileSymptomsOpen] = useState(false);
@@ -541,7 +524,6 @@ export default function ArchivePage({
} }
lastInitialPropsRef.current = { initialCategory, initialSearch, initialPetType, initialSymptoms }; lastInitialPropsRef.current = { initialCategory, initialSearch, initialPetType, initialSymptoms };
setCurrentPage(initialPage || 1);
// Normalize Input // Normalize Input
const normSearch = (initialSearch || "").trim().toLowerCase(); const normSearch = (initialSearch || "").trim().toLowerCase();
@@ -561,7 +543,6 @@ export default function ArchivePage({
setSelectedPet((initialPetType as PetType) || "all"); setSelectedPet((initialPetType as PetType) || "all");
setActiveSymptoms(initialSymptoms ? initialSymptoms.split(',').filter(Boolean) : []); setActiveSymptoms(initialSymptoms ? initialSymptoms.split(',').filter(Boolean) : []);
} }
setCurrentPage(1);
}, [initialCategory, initialSearch, initialPetType, initialSymptoms]); }, [initialCategory, initialSearch, initialPetType, initialSymptoms]);
// Update URL Query Parameters // Update URL Query Parameters
@@ -571,20 +552,15 @@ export default function ArchivePage({
if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet); if (selectedPet && selectedPet !== "all") params.set('petType', selectedPet);
if (searchQuery) params.set('search', searchQuery); if (searchQuery) params.set('search', searchQuery);
if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(',')); if (activeSymptoms.length > 0) params.set('symptoms', activeSymptoms.join(','));
if (currentPage > 1) params.set('page', String(currentPage));
const queryString = params.toString(); const queryString = params.toString();
const newUrl = `/shop${queryString ? `?${queryString}` : ''}`; const newUrl = `/shop${queryString ? `?${queryString}` : ''}`;
if (typeof window !== 'undefined' && window.location.pathname + window.location.search !== newUrl) { if (typeof window !== 'undefined' && window.location.pathname + window.location.search !== newUrl) {
router.replace(newUrl, { scroll: false }); router.replace(newUrl, { scroll: false });
} }
}, [selectedCategory, selectedPet, searchQuery, activeSymptoms, currentPage, router]); }, [selectedCategory, selectedPet, searchQuery, activeSymptoms, router]);
const hasInitialProducts = Boolean(initialProducts && initialProducts.length > 0);
const didSkipInitialFetch = React.useRef(false);
const fetchProducts = useCallback(async () => { const fetchProducts = useCallback(async () => {
setFetchError(null);
setIsUpdating(true); setIsUpdating(true);
try { try {
const res = await productService.getProducts({ const res = await productService.getProducts({
@@ -603,23 +579,17 @@ export default function ArchivePage({
} }
setFilteredProducts(orderProductsByAvailability(result)); setFilteredProducts(orderProductsByAvailability(result));
setCurrentPage(1);
} catch (error) { } catch (error) {
console.error("Failed to fetch products:", error); console.error("Failed to fetch products:", error);
toast.error("خطا در دریافت لیست محصولات از سرور."); toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید.");
setFetchError("خطا در برقراری ارتباط با سرور یا دریافت اطلاعات محصولات.");
} finally { } finally {
setIsUpdating(false); setIsUpdating(false);
} }
}, [selectedCategory, selectedPet, searchQuery, sortBy, sortOrder, activeSymptoms]); }, [selectedCategory, selectedPet, searchQuery, sortBy, sortOrder, activeSymptoms]);
useEffect(() => { useEffect(() => {
if (hasInitialProducts && !didSkipInitialFetch.current) {
didSkipInitialFetch.current = true;
return;
}
Promise.resolve().then(() => fetchProducts()); Promise.resolve().then(() => fetchProducts());
}, [fetchProducts, hasInitialProducts]); }, [fetchProducts]);
const toggleSymptom = (s: string) => { const toggleSymptom = (s: string) => {
setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]); setActiveSymptoms(prev => prev.includes(s) ? prev.filter(item => item !== s) : [...prev, s]);
@@ -726,7 +696,6 @@ export default function ArchivePage({
<div className="relative mb-3"> <div className="relative mb-3">
<input <input
type="text" type="text"
aria-label="جستجوی علائم"
placeholder="جستجوی علائم..." placeholder="جستجوی علائم..."
value={symptomSearch} value={symptomSearch}
onChange={(e) => setSymptomSearch(e.target.value)} onChange={(e) => setSymptomSearch(e.target.value)}
@@ -760,7 +729,7 @@ export default function ArchivePage({
<div className="absolute -top-10 -left-10 w-32 h-32 bg-canina-blue rounded-full blur-3xl opacity-20 group-hover:opacity-40 transition-opacity" /> <div className="absolute -top-10 -left-10 w-32 h-32 bg-canina-blue rounded-full blur-3xl opacity-20 group-hover:opacity-40 transition-opacity" />
<h4 className="text-lg font-black italic mb-4 relative z-10 underline decoration-canina-blue underline-offset-8">{getText('shop_promo_card_title', 'مشاوره رایگان')}</h4> <h4 className="text-lg font-black italic mb-4 relative z-10 underline decoration-canina-blue underline-offset-8">{getText('shop_promo_card_title', 'مشاوره رایگان')}</h4>
<p className="text-xs text-white/60 leading-relaxed mb-6 relative z-10">{getText('shop_promo_card_desc', 'اگر نمی‌دانید کدام ترکیب برای پت شما مناسب است، همین حالا با دامپزشکان ما تماس بگیرید.')}</p> <p className="text-xs text-white/60 leading-relaxed mb-6 relative z-10">{getText('shop_promo_card_desc', 'اگر نمی‌دانید کدام ترکیب برای پت شما مناسب است، همین حالا با دامپزشکان ما تماس بگیرید.')}</p>
<a <a
href={getText('contact_phone_link', `tel:${getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)} href={getText('contact_phone_link', `tel:${getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)}
className="w-full bg-white text-medical-gray-900 py-3 rounded-xl text-xs font-black hover:scale-105 transition-transform relative z-10 flex items-center justify-center font-vazir" className="w-full bg-white text-medical-gray-900 py-3 rounded-xl text-xs font-black hover:scale-105 transition-transform relative z-10 flex items-center justify-center font-vazir"
> >
@@ -771,23 +740,22 @@ export default function ArchivePage({
{/* Main Content */} {/* Main Content */}
<main className="flex-1 relative"> <main className="flex-1 relative">
{/* Semantic Single H1 across breakpoints */} {/* Desktop Top Title & Search / Sort Row */}
<div className="flex flex-col lg:flex-row items-start lg:items-center justify-between mb-2 lg:mb-6 gap-2 lg:gap-4"> <div className="hidden lg:flex flex-col sm:flex-row items-center justify-between mb-6 gap-4">
<h1 {getText('shop_catalog_title', '').trim() ? (
className="text-2xl lg:text-3xl font-black text-medical-gray-900" <h2
dangerouslySetInnerHTML={{ className="text-3xl font-black text-medical-gray-900"
__html: getText('shop_catalog_title', 'کاتالوگ و فروشگاه مکمل‌های دارویی <span class="text-canina-blue">کنینا</span>') dangerouslySetInnerHTML={{
.replace(/^\s*<h1[^>]*>/i, '') __html: getText('shop_catalog_title', 'کاتولوگ دارویی <span class="text-canina-blue">Canina</span>')
.replace(/<\/h1>\s*$/i, '') }}
}} />
/> ) : null}
<div className="hidden lg:flex items-center gap-3 w-auto"> <div className="flex items-center gap-3 w-auto">
{/* Sort Dropdown */} {/* Sort Dropdown */}
<div className="flex items-center gap-2 bg-white border border-medical-gray-200 rounded-2xl px-3 py-2 text-xs font-bold shadow-xs"> <div className="flex items-center gap-2 bg-white border border-medical-gray-200 rounded-2xl px-3 py-2 text-xs font-bold shadow-xs">
<span className="text-medical-gray-400 whitespace-nowrap">مرتب‌سازی:</span> <span className="text-medical-gray-400 whitespace-nowrap">مرتب‌سازی:</span>
<select <select
aria-label="مرتب‌سازی محصولات"
value={`${sortBy}:${sortOrder}`} value={`${sortBy}:${sortOrder}`}
onChange={(e) => { onChange={(e) => {
const [b, o] = e.target.value.split(':'); const [b, o] = e.target.value.split(':');
@@ -809,7 +777,6 @@ export default function ArchivePage({
<input <input
data-testid="shop-search-input" data-testid="shop-search-input"
type="text" type="text"
aria-label="جستجوی محصول"
placeholder="جستجوی محصول..." placeholder="جستجوی محصول..."
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
@@ -819,6 +786,18 @@ export default function ArchivePage({
</div> </div>
</div> </div>
{/* Mobile Title (Only if set in admin) */}
{getText('shop_catalog_title', '').trim() ? (
<div className="lg:hidden mb-2">
<h2
className="text-2xl font-black text-medical-gray-900"
dangerouslySetInnerHTML={{
__html: getText('shop_catalog_title', 'کاتولوگ دارویی <span class="text-canina-blue">Canina</span>')
}}
/>
</div>
) : null}
{/* Mobile Controls: Horizontal Sliding Filters & View Toggle Row */} {/* Mobile Controls: Horizontal Sliding Filters & View Toggle Row */}
<div className="lg:hidden flex flex-col gap-2 mb-2"> <div className="lg:hidden flex flex-col gap-2 mb-2">
{/* Search Bar on Mobile */} {/* Search Bar on Mobile */}
@@ -827,19 +806,17 @@ export default function ArchivePage({
<input <input
data-testid="shop-search-input-mobile" data-testid="shop-search-input-mobile"
type="text" type="text"
aria-label="جستجوی محصول"
placeholder="جستجوی محصول..." placeholder="جستجوی محصول..."
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 pr-11 pl-4 text-xs font-bold focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-2xs" className="w-full bg-white border border-medical-gray-200 rounded-2xl py-2.5 pr-11 pl-4 text-xs font-bold focus:outline-none focus:ring-2 focus:ring-canina-blue/20 shadow-2xs"
/> />
</div> </div>
{/* Horizontal Scrollable Row for Sort, Pet Type, Solutions & Symptoms Filter */} {/* Horizontal Scrollable Row for Sort, Pet Type, Solutions & Symptoms Filter */}
<div className="relative -mx-4 mt-2 mb-4" data-testid="mobile-catalog-filters-edge"> <div className="flex items-center gap-2 overflow-x-auto pb-2.5 pt-0.5 micro-hscroll -mx-4 px-4 select-none touch-pan-x mt-2 mb-4">
<div data-testid="mobile-catalog-filters" aria-label="فیلترهای محصولات" className="flex items-center gap-2 overflow-x-auto pb-2.5 pt-0.5 micro-hscroll px-4 select-none touch-pan-x mobile-filter-mask">
{/* 1. View Mode Switch: 2 Buttons (List / Card) */} {/* 1. View Mode Switch: 2 Buttons (List / Card) */}
<div className="flex-shrink-0 inline-flex items-center bg-white border border-medical-gray-200 rounded-xl p-0.5 shadow-2xs mr-auto"> <div className="flex-shrink-0 inline-flex items-center bg-white border border-medical-gray-200 rounded-xl p-0.5 shadow-2xs mr-auto">
<button <button
@@ -925,23 +902,23 @@ 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"}`} 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"}`}
> >
<span>{selectedCategory !== "all" ? (CATEGORY_LABELS[selectedCategory] || "دسته‌بندی") : "دسته‌بندی و راهکار"}</span> <span>{selectedCategory !== "all" ? (CATEGORY_LABELS[selectedCategory] || "راهکار درمانی") : "راهکار درمانی"}</span>
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSolutionsOpen ? "rotate-180" : ""}`} /> <ChevronDown className={`w-3 h-3 transition-transform ${isMobileSolutionsOpen ? "rotate-180" : ""}`} />
</button> </button>
{isMobileSolutionsOpen && isMounted && createPortal( {isMobileSolutionsOpen && (
<div className="fixed inset-0 z-[9999] flex items-end justify-center bg-black/50 backdrop-blur-xs font-vazir" dir="rtl" onClick={() => setIsMobileSolutionsOpen(false)}> <div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 backdrop-blur-xs font-vazir" onClick={() => setIsMobileSolutionsOpen(false)}>
<div <div
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[75vh] flex flex-col animate-in slide-in-from-bottom duration-200" className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[75vh] flex flex-col animate-in slide-in-from-bottom duration-200"
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
<div className="w-10 h-1 bg-medical-gray-200 rounded-full mx-auto mb-3 shrink-0" /> <div className="w-10 h-1 bg-medical-gray-200 rounded-full mx-auto mb-3 shrink-0" />
<div className="flex items-center justify-between pb-3 border-b border-medical-gray-100 mb-3 shrink-0"> <div className="flex items-center justify-between pb-3 border-b border-medical-gray-100 mb-3 shrink-0">
<h4 className="font-black text-sm text-medical-gray-900">فیلتر دسته‌بندی و راهکار درمانی</h4> <h4 className="font-black text-sm text-medical-gray-900">انتخاب راهکار درمانی</h4>
<button <button
type="button" type="button"
onClick={() => setIsMobileSolutionsOpen(false)} onClick={() => setIsMobileSolutionsOpen(false)}
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1 cursor-pointer" className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1"
> >
بستن ✕ بستن ✕
</button> </button>
@@ -955,7 +932,7 @@ export default function ArchivePage({
setSelectedCategory(cat.id); setSelectedCategory(cat.id);
setIsMobileSolutionsOpen(false); 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 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"}`} 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"}`}
> >
<span className="shrink-0">{cat.icon}</span> <span className="shrink-0">{cat.icon}</span>
<span className="truncate">{cat.label}</span> <span className="truncate">{cat.label}</span>
@@ -963,8 +940,7 @@ export default function ArchivePage({
))} ))}
</div> </div>
</div> </div>
</div>, </div>
document.body
)} )}
</div> </div>
@@ -982,9 +958,9 @@ export default function ArchivePage({
<ChevronDown className={`w-3 h-3 transition-transform ${isMobileSymptomsOpen ? "rotate-180" : ""}`} /> <ChevronDown className={`w-3 h-3 transition-transform ${isMobileSymptomsOpen ? "rotate-180" : ""}`} />
</button> </button>
{isMobileSymptomsOpen && isMounted && createPortal( {isMobileSymptomsOpen && (
<div className="fixed inset-0 z-[9999] flex items-end justify-center bg-black/50 backdrop-blur-xs font-vazir" dir="rtl" onClick={() => setIsMobileSymptomsOpen(false)}> <div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 backdrop-blur-xs font-vazir" onClick={() => setIsMobileSymptomsOpen(false)}>
<div <div
className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[80vh] flex flex-col animate-in slide-in-from-bottom duration-200" className="w-full max-w-lg bg-white rounded-t-3xl p-5 border-t border-medical-gray-200 shadow-2xl max-h-[80vh] flex flex-col animate-in slide-in-from-bottom duration-200"
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
@@ -999,7 +975,7 @@ export default function ArchivePage({
<button <button
type="button" type="button"
onClick={() => setActiveSymptoms([])} onClick={() => setActiveSymptoms([])}
className="text-xs font-bold text-red-500 hover:underline px-1 cursor-pointer" className="text-xs font-bold text-red-500 hover:underline px-1"
> >
پاک کردن همه پاک کردن همه
</button> </button>
@@ -1007,7 +983,7 @@ export default function ArchivePage({
<button <button
type="button" type="button"
onClick={() => setIsMobileSymptomsOpen(false)} onClick={() => setIsMobileSymptomsOpen(false)}
className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1 cursor-pointer" className="text-xs text-medical-gray-400 hover:text-medical-gray-700 font-bold p-1"
> >
بستن ✕ بستن ✕
</button> </button>
@@ -1018,7 +994,6 @@ export default function ArchivePage({
<Search className="absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" /> <Search className="absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<input <input
type="text" type="text"
aria-label="جستجوی علائم"
placeholder="جستجوی علائم بیماری یا نیاز دارویی..." placeholder="جستجوی علائم بیماری یا نیاز دارویی..."
value={symptomSearch} value={symptomSearch}
onChange={(e) => setSymptomSearch(e.target.value)} onChange={(e) => setSymptomSearch(e.target.value)}
@@ -1037,7 +1012,7 @@ export default function ArchivePage({
key={s} key={s}
type="button" type="button"
onClick={() => toggleSymptom(s)} onClick={() => toggleSymptom(s)}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border whitespace-nowrap cursor-pointer ${activeSymptoms.includes(s) className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all border whitespace-nowrap ${activeSymptoms.includes(s)
? "bg-canina-blue border-canina-blue text-white shadow-2xs" ? "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" : "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40 hover:text-canina-blue"
}`} }`}
@@ -1052,19 +1027,15 @@ export default function ArchivePage({
<button <button
type="button" type="button"
onClick={() => setIsMobileSymptomsOpen(false)} onClick={() => setIsMobileSymptomsOpen(false)}
className="w-full bg-canina-blue text-white py-2.5 rounded-xl font-bold text-xs shadow-lg shadow-canina-blue/20 cursor-pointer" className="w-full bg-canina-blue text-white py-2.5 rounded-xl font-bold text-xs shadow-lg shadow-canina-blue/20"
> >
مشاهده نتایج {activeSymptoms.length > 0 ? `(${toPersian(activeSymptoms.length)} علامت)` : ""} مشاهده نتایج {activeSymptoms.length > 0 ? `(${toPersian(activeSymptoms.length)} علامت)` : ""}
</button> </button>
</div> </div>
</div> </div>
</div>, </div>
document.body
)} )}
</div> </div>
</div>
</div> </div>
</div> </div>
@@ -1106,23 +1077,7 @@ export default function ArchivePage({
)} )}
<AnimatePresence mode="wait"> <AnimatePresence mode="wait">
{fetchError ? ( {isUpdating ? (
<div key="fetch-error" data-testid="shop-fetch-error" className="bg-white rounded-[2.5rem] p-10 sm:p-14 text-center border border-rose-200/80 shadow-sm flex flex-col items-center">
<div className="w-16 h-16 bg-rose-50 rounded-2xl flex items-center justify-center text-rose-500 mb-4 border border-rose-100">
<AlertCircle className="w-8 h-8" />
</div>
<h3 className="text-xl font-black text-medical-gray-900 mb-2">خطا در دریافت اطلاعات محصولات</h3>
<p className="text-medical-gray-500 max-w-md mb-6 font-medium text-xs sm:text-sm leading-relaxed">{fetchError}</p>
<button
type="button"
onClick={() => fetchProducts()}
className="inline-flex items-center gap-2 bg-canina-blue text-white px-6 py-2.5 rounded-xl font-black text-xs sm:text-sm hover:bg-canina-dark transition-all shadow-md shadow-canina-blue/20 cursor-pointer active:scale-95"
>
<Activity className="w-4 h-4" />
<span>تلاش مجدد</span>
</button>
</div>
) : isUpdating ? (
viewMode === "list" ? ( viewMode === "list" ? (
<div key="skeleton-list" className="flex flex-col gap-3 lg:hidden"> <div key="skeleton-list" className="flex flex-col gap-3 lg:hidden">
{Array.from({ length: 8 }).map((_, i) => ( {Array.from({ length: 8 }).map((_, i) => (
@@ -1138,121 +1093,49 @@ export default function ArchivePage({
) )
) : filteredProducts.length > 0 ? ( ) : filteredProducts.length > 0 ? (
<> <>
{/* Progressive slice of products for optimal DOM density and mobile UX */} {/* Keep API sort order inside each availability section. */}
{(() => { {([{
const totalPages = Math.max(1, Math.ceil(filteredProducts.length / pageSize)); key: "available",
const safeCurrentPage = Math.min(currentPage, totalPages); title: "محصولات موجود",
const startIndex = (safeCurrentPage - 1) * pageSize; products: filteredProducts.filter(product => !isProductOutOfStock(product)),
const slicedProducts = filteredProducts.slice(startIndex, startIndex + pageSize); }, {
key: "unavailable",
const totalInStock = filteredProducts.filter(product => !isProductOutOfStock(product)).length; title: "محصولات ناموجود",
const totalOutOfStock = filteredProducts.filter(product => isProductOutOfStock(product)).length; products: filteredProducts.filter(product => isProductOutOfStock(product)),
}] as const).map(section => section.products.length > 0 && (
const sections = [ <section key={section.key} data-testid={`products-${section.key}`} className="mb-10 last:mb-0">
{ <h2 className="mb-5 text-xl font-black text-medical-gray-900">{section.title}</h2>
key: "available", {/* Mobile List View vs Card View (Desktop is always responsive multi-column grid) */}
title: "محصولات موجود", <div
totalCount: totalInStock, key={viewMode}
products: slicedProducts.filter(product => !isProductOutOfStock(product)), className={
}, viewMode === "list"
{ ? "flex flex-col gap-3 lg:grid lg:grid-cols-2 xl:grid-cols-4 lg:gap-6"
key: "unavailable", : "grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6"
title: "محصولات ناموجود", }
totalCount: totalOutOfStock, >
products: slicedProducts.filter(product => isProductOutOfStock(product)), <AnimatePresence mode="popLayout">
} {section.products.map((p: Product) => (
] as const; <React.Fragment key={p.id}>
{/* In list mode on mobile, render ArchiveProductListItem; on desktop (lg+), render standard card */}
return ( {viewMode === "list" ? (
<> <>
{sections.map(section => section.products.length > 0 && ( <div className="block lg:hidden w-full">
<section key={section.key} data-testid={`products-${section.key}`} className="mb-8 last:mb-0"> <ArchiveProductListItem product={p} />
<div className="flex items-center justify-between mb-4"> </div>
<h2 className="text-xl font-black text-medical-gray-900">{section.title}</h2> <div className="hidden lg:block h-full">
<span className="text-xs font-bold text-medical-gray-400"> <ArchiveProductCard product={p} />
{toPersian(section.totalCount)} محصول </div>
</span> </>
</div> ) : (
<div <ArchiveProductCard product={p} />
key={viewMode} )}
className={ </React.Fragment>
viewMode === "list" ))}
? "flex flex-col gap-3 lg:grid lg:grid-cols-2 xl:grid-cols-4 lg:gap-6" </AnimatePresence>
: "grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6" </div>
} </section>
> ))}
<AnimatePresence mode="popLayout">
{section.products.map((p: Product) => (
<React.Fragment key={p.id}>
{viewMode === "list" ? (
<ArchiveProductListItem product={p} />
) : (
<ArchiveProductCard product={p} />
)}
</React.Fragment>
))}
</AnimatePresence>
</div>
</section>
))}
{/* Pagination Controls */}
{totalPages > 1 && (
<nav aria-label="صفحه‌بندی محصولات" data-testid="shop-pagination" className="mt-10 mb-4 flex flex-col sm:flex-row items-center justify-between gap-4 bg-white border border-medical-gray-200/80 rounded-2xl p-4 shadow-xs font-vazir">
<div className="text-xs text-medical-gray-500 font-bold order-2 sm:order-1">
صفحه {toPersian(safeCurrentPage)} از {toPersian(totalPages)} (کل محصولات: {toPersian(filteredProducts.length)})
</div>
<div className="flex items-center gap-2 order-1 sm:order-2">
<button
type="button"
disabled={safeCurrentPage <= 1}
onClick={() => {
setCurrentPage(prev => Math.max(1, prev - 1));
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-label="صفحه قبل"
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
>
قبلی
</button>
<div className="flex items-center gap-1.5">
{Array.from({ length: totalPages }).map((_, i) => {
const pageNum = i + 1;
const isActive = pageNum === safeCurrentPage;
return (
<button
key={pageNum}
type="button"
onClick={() => {
setCurrentPage(pageNum);
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-current={isActive ? "page" : undefined}
className={isActive ? "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer bg-canina-blue text-white shadow-sm" : "w-8 h-8 rounded-xl text-xs font-black transition-all flex items-center justify-center cursor-pointer text-medical-gray-700 hover:bg-medical-gray-100 border border-medical-gray-200/60"}
>
{toPersian(pageNum)}
</button>
);
})}
</div>
<button
type="button"
disabled={safeCurrentPage >= totalPages}
onClick={() => {
setCurrentPage(prev => Math.min(totalPages, prev + 1));
window.scrollTo({ top: 0, behavior: "smooth" });
}}
aria-label="صفحه بعد"
className="px-3.5 py-2 text-xs font-bold rounded-xl border border-medical-gray-200 text-medical-gray-700 hover:border-canina-blue hover:text-canina-blue disabled:opacity-40 disabled:cursor-not-allowed transition-all"
>
بعدی
</button>
</div>
</nav>
)}
</>
);
})()}
{/* SEO Category Rich Description Section (Rendered below products to maintain primary UX while boosting category SEO) */} {/* SEO Category Rich Description Section (Rendered below products to maintain primary UX while boosting category SEO) */}
{selectedCategory !== "all" && ( {selectedCategory !== "all" && (
@@ -1,120 +0,0 @@
"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>
);
}
@@ -1,202 +0,0 @@
"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>
);
}
@@ -434,9 +434,6 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
{/* Modal Container */} {/* Modal Container */}
<motion.div <motion.div
role="dialog"
aria-modal="true"
aria-labelledby="auth-modal-title"
initial={{ opacity: 0, scale: 0.96, y: 20 }} initial={{ opacity: 0, scale: 0.96, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }} animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.96, y: 20 }} exit={{ opacity: 0, scale: 0.96, y: 20 }}
@@ -450,13 +447,11 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
<ShieldCheck className="w-4 h-4" /> <ShieldCheck className="w-4 h-4" />
</div> </div>
<div> <div>
<h3 id="auth-modal-title" className="text-sm font-black tracking-tight text-medical-gray-900 font-vazir">احراز هویت کنینا</h3> <h3 className="text-sm font-black tracking-tight text-medical-gray-900 font-vazir">احراز هویت کنینا</h3>
<p className="text-[10px] text-medical-gray-400 font-bold font-vazir">ورود امن به حساب کاربری</p> <p className="text-[10px] text-medical-gray-400 font-bold font-vazir">ورود امن به حساب کاربری</p>
</div> </div>
</div> </div>
<button <button
type="button"
aria-label="بستن پنجره احراز هویت"
onClick={onClose} onClick={onClose}
className="w-8 h-8 rounded-full bg-white border border-medical-gray-200 flex items-center justify-center text-medical-gray-400 hover:text-medical-gray-700 hover:bg-medical-gray-100 transition-all cursor-pointer" className="w-8 h-8 rounded-full bg-white border border-medical-gray-200 flex items-center justify-center text-medical-gray-400 hover:text-medical-gray-700 hover:bg-medical-gray-100 transition-all cursor-pointer"
> >
@@ -49,17 +49,13 @@ export default function B2BLandingClient() {
setSubmitting(true); setSubmitting(true);
try { try {
await api.post('/b2b/inquire', { await api.post('/wholesale/apply', {
companyName: formData.businessName, businessName: `${formData.businessName} (${formData.businessType} - ${formData.city}) - رابط: ${formData.contactName}`,
contactName: formData.contactName || formData.businessName, licenseNumber: formData.phone,
email: `partner-${Date.now()}@canina.ir`, notes: formData.notes,
phone: formData.phone,
businessType: `${formData.businessType} (شهر: ${formData.city || 'نامشخص'})`,
estimatedVolume: 'ثبت لندینگ B2B سایت',
message: formData.notes || `درخواست شراکت و تامین رسمی برای ${formData.businessName} در شهر ${formData.city}`,
}); });
setSubmitted(true); setSubmitted(true);
toast.success('درخواست همکاری تجاری شما با موفقیت ثبت شد. تیم بازرگانی و پزشکی حداکثر تا ۲۴ ساعت کاری با شما تماس خواهند گرفت.'); toast.success('درخواست همکاری شما با موفقیت ثبت شد. همکاران ما حداکثر تا ۲۴ ساعت آینده با شما تماس خواهند گرفت.');
} catch { } catch {
toast.error('خطایی در ثبت درخواست رخ داد. لطفاً با پشتیبانی تماس بگیرید.'); toast.error('خطایی در ثبت درخواست رخ داد. لطفاً با پشتیبانی تماس بگیرید.');
} finally { } finally {
+14 -89
View File
@@ -89,24 +89,23 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }} animate={{ opacity: 1 }}
exit={{ opacity: 0 }} exit={{ opacity: 0 }}
className="fixed inset-0 z-[100] bg-medical-gray-900/70 backdrop-blur-md flex items-center justify-center p-2 sm:p-4 md:p-8 font-vazir" className="fixed inset-0 z-[100] bg-medical-gray-900/60 backdrop-blur-md flex items-center justify-center p-4 md:p-10 font-vazir"
dir="rtl" dir="rtl"
> >
<motion.div <motion.div
initial={{ scale: 0.9, opacity: 0, y: 20 }} initial={{ scale: 0.9, opacity: 0, y: 20 }}
animate={{ scale: 1, opacity: 1, y: 0 }} animate={{ scale: 1, opacity: 1, y: 0 }}
className="bg-white w-full max-w-6xl h-[95vh] sm:h-[90vh] rounded-3xl sm:rounded-[3rem] shadow-2xl overflow-hidden flex flex-col md:flex-row relative" className="bg-white w-full max-w-6xl h-[90vh] rounded-[3rem] shadow-2xl overflow-hidden flex flex-col md:flex-row relative"
> >
<button <button
onClick={onClose} onClick={onClose}
className="absolute top-4 left-4 sm:top-6 sm:left-6 z-30 min-w-[44px] min-h-[44px] w-11 h-11 bg-white/90 sm:bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-600 hover:bg-red-50 hover:text-red-500 transition-all shadow-md cursor-pointer" className="absolute top-6 left-6 z-20 w-10 h-10 bg-medical-gray-100 rounded-full flex items-center justify-center text-medical-gray-500 hover:bg-red-50 hover:text-red-500 transition-all"
aria-label="بستن پنجره"
> >
<X className="w-5 h-5" /> <X className="w-5 h-5" />
</button> </button>
{/* Sidebar Info */} {/* Sidebar Info */}
<div className="w-full md:w-80 bg-canina-blue p-5 sm:p-8 md:p-10 text-white flex flex-col overflow-y-auto shrink-0 max-h-[45vh] md:max-h-full"> <div className="w-full md:w-80 bg-canina-blue p-10 text-white flex flex-col overflow-y-auto">
<div className="mb-8"> <div className="mb-8">
<div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center mb-6"> <div className="w-16 h-16 bg-white/20 rounded-2xl flex items-center justify-center mb-6">
<Building2 className="w-8 h-8" /> <Building2 className="w-8 h-8" />
@@ -163,107 +162,32 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
{/* Main Grid Area */} {/* Main Grid Area */}
<div className="flex-1 flex flex-col bg-medical-gray-50 overflow-hidden"> <div className="flex-1 flex flex-col bg-medical-gray-50 overflow-hidden">
{/* Header & Search */} {/* Header & Search */}
<div className="p-4 sm:p-6 md:p-8 border-b border-medical-gray-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-6 bg-white shrink-0"> <div className="p-8 border-b border-medical-gray-200 flex flex-col md:flex-row md:items-center justify-between gap-6 bg-white">
<div className="relative flex-1 max-w-md"> <div className="relative flex-1 max-w-md">
<Search className="absolute right-3 sm:right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" /> <Search className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<input <input
type="text" type="text"
placeholder="جستجوی کد کالا یا نام محصول..." placeholder="جستجوی کد کالا یا نام محصول..."
value={searchQuery} value={searchQuery}
onChange={e => setSearchQuery(e.target.value)} onChange={e => setSearchQuery(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl sm:rounded-2xl py-2.5 sm:py-3 pr-9 sm:pr-11 pl-4 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20" className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-3 pr-11 pl-4 text-sm focus:outline-none focus:ring-2 focus:ring-canina-blue/20"
/> />
</div> </div>
<button <button
onClick={handleAddAll} onClick={handleAddAll}
disabled={totalItems === 0} disabled={totalItems === 0}
className="bg-medical-gray-900 text-white px-5 sm:px-8 py-2.5 sm:py-3 rounded-xl sm:rounded-2xl font-black text-xs sm:text-sm flex items-center justify-center gap-2 hover:bg-canina-blue transition-colors disabled:opacity-30 cursor-pointer shadow-md" className="bg-medical-gray-900 text-white px-8 py-3 rounded-2xl font-black text-sm flex items-center gap-2 hover:bg-canina-blue transition-colors disabled:opacity-30"
> >
<ShoppingCart className="w-4 h-4" /> <ShoppingCart className="w-4 h-4" />
<span>افزودن کلی ({toPersian(totalItems)} عدد)</span> افزودن کلی ({totalItems} عدد)
</button> </button>
</div> </div>
{/* Products Container */} {/* Table */}
<div className="flex-1 overflow-y-auto p-3 sm:p-6 md:p-8"> <div className="flex-1 overflow-y-auto p-8">
{loadError && <p role="alert" className="text-red-500 font-bold text-xs p-4 bg-red-50 rounded-2xl mb-4">خطا در دریافت محصولات. لطفاً دوباره تلاش کنید.</p>} {loadError && <p role="alert">خطا در دریافت محصولات. لطفاً دوباره تلاش کنید.</p>}
<div className="bg-white border border-medical-gray-200 rounded-3xl overflow-hidden shadow-sm">
{/* Mobile View: Clean Card Layout for each product */}
<div className="md:hidden space-y-3">
{filteredProducts.map(product => {
const basePrice = product.priceValue || 0;
const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30;
const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice;
const wholesalePrice = prodWholesale
? Number(prodWholesale)
: Math.round(basePrice * (1 - wholesaleDiscountPercent / 100));
const currentQty = quantities[product.id] || 0;
return (
<div key={product.id} className="bg-white border border-medical-gray-200 rounded-2xl p-3.5 shadow-xs space-y-3">
<div className="flex items-center gap-3">
<div className="w-14 h-14 bg-medical-gray-50 rounded-xl p-1.5 shrink-0 border border-medical-gray-100 flex items-center justify-center">
<SafeImage src={product.image} className="w-full h-full" imgClassName="object-contain" alt={product.name} />
</div>
<div className="flex-1 min-w-0">
<h4 className="font-black text-xs text-medical-gray-900 leading-snug line-clamp-2">{product.name}</h4>
<span className="text-[10px] font-mono text-medical-gray-400 block mt-0.5 dir-ltr text-right">کد: {product.artNo}</span>
</div>
</div>
<div className="flex items-center justify-between border-t border-medical-gray-100 pt-2.5 text-xs">
<div>
<span className="text-[10px] text-medical-gray-400 block font-medium">تک‌فروشی</span>
<span className="font-bold text-medical-gray-600 text-xs">{toPersian(basePrice.toLocaleString())} ت</span>
</div>
<div>
<span className="text-[10px] text-amber-600 block font-black">قیمت همکار B2B</span>
{isWholesaleVerified ? (
<span className="font-black text-amber-800 text-xs bg-amber-50 px-2 py-0.5 rounded-md border border-amber-200 inline-block">
{toPersian(wholesalePrice.toLocaleString())} ت
</span>
) : (
<span className="inline-flex items-center gap-1 text-[10px] font-bold text-gray-400 bg-gray-50 px-1.5 py-0.5 rounded">
<Lock className="w-2.5 h-2.5" />
تایید ادمین
</span>
)}
</div>
<div className="flex items-center gap-1 bg-medical-gray-50 border border-medical-gray-200 rounded-xl p-1">
<button
type="button"
onClick={() => handleQuantityChange(product.id, String(Math.max(0, currentQty - 1)))}
className="w-7 h-7 flex items-center justify-center bg-white rounded-lg text-gray-700 font-bold text-sm shadow-xs active:bg-gray-100"
>
-
</button>
<input
type="number"
min="0"
value={currentQty || ""}
onChange={(e) => handleQuantityChange(product.id, e.target.value)}
placeholder="0"
className="w-8 text-center bg-transparent font-mono font-black text-xs outline-none"
/>
<button
type="button"
onClick={() => handleQuantityChange(product.id, String(currentQty + 1))}
className="w-7 h-7 flex items-center justify-center bg-white rounded-lg text-gray-700 font-bold text-sm shadow-xs active:bg-gray-100"
>
+
</button>
</div>
</div>
</div>
);
})}
</div>
{/* Desktop / Tablet View: Rich Table */}
<div className="hidden md:block bg-white border border-medical-gray-200 rounded-3xl overflow-hidden shadow-sm">
<table className="w-full text-right"> <table className="w-full text-right">
<thead className="bg-medical-gray-50 border-b border-medical-gray-200"> <thead className="bg-medical-gray-50 border-b border-medical-gray-200">
<tr> <tr>
@@ -277,6 +201,7 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
<tbody className="divide-y divide-medical-gray-100"> <tbody className="divide-y divide-medical-gray-100">
{filteredProducts.map(product => { {filteredProducts.map(product => {
const basePrice = product.priceValue || 0; const basePrice = product.priceValue || 0;
// Priority 1: Specific product wholesalePrice, Priority 2: General settings percentage discount (default 30%)
const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30; const wholesaleDiscountPercent = Number(useSettingsStore.getState().getText('B2B_DISCOUNT_PERCENT', '30')) || 30;
const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice; const prodWholesale = (product as unknown as { wholesalePrice?: number }).wholesalePrice;
const wholesalePrice = prodWholesale const wholesalePrice = prodWholesale
+56 -128
View File
@@ -17,9 +17,7 @@ import {
Pin, Pin,
Eye, Eye,
Filter, Filter,
SlidersHorizontal,
} from "lucide-react"; } from "lucide-react";
import { toPersian } from "../lib/utils";
import { toast } from "sonner"; import { toast } from "sonner";
import { Product } from "../lib/data/products"; import { Product } from "../lib/data/products";
import { productService } from "../lib/services/productService"; import { productService } from "../lib/services/productService";
@@ -65,14 +63,11 @@ export default function BlogPage({
const [selectedCategory, setSelectedCategory] = useState<string>(initialCategoryId); const [selectedCategory, setSelectedCategory] = useState<string>(initialCategoryId);
const [searchQuery, setSearchQuery] = useState<string>(""); const [searchQuery, setSearchQuery] = useState<string>("");
const [selectedTag, setSelectedTag] = useState<string | null>(null); const [selectedTag, setSelectedTag] = useState<string | null>(null);
const [sortBy, setSortBy] = useState<"newest" | "oldest" | "most_viewed">("newest");
const [visibleCount, setVisibleCount] = useState<number>(6);
React.useEffect(() => { React.useEffect(() => {
if (initialCategoryId) { if (initialCategoryId) {
setSelectedCategory(initialCategoryId); setSelectedCategory(initialCategoryId);
} }
setVisibleCount(6);
}, [initialCategoryId]); }, [initialCategoryId]);
React.useEffect(() => { React.useEffect(() => {
@@ -95,16 +90,8 @@ export default function BlogPage({
(b.tags && b.tags.some((t) => t.name === selectedTag)); (b.tags && b.tags.some((t) => t.name === selectedTag));
return matchCategory && matchSearch && matchTag; return matchCategory && matchSearch && matchTag;
}).sort((a, b) => {
if (sortBy === "most_viewed") {
return (b.viewCount ?? 0) - (a.viewCount ?? 0);
}
if (sortBy === "oldest") {
return new Date(a.date).getTime() - new Date(b.date).getTime();
}
return new Date(b.date).getTime() - new Date(a.date).getTime();
}); });
}, [blogs, selectedCategory, searchQuery, selectedTag, sortBy]); }, [blogs, selectedCategory, searchQuery, selectedTag]);
// Featured post (prioritize featured flag, otherwise the first item) // Featured post (prioritize featured flag, otherwise the first item)
const featuredPost = useMemo(() => { const featuredPost = useMemo(() => {
@@ -119,12 +106,6 @@ export default function BlogPage({
return filteredBlogs.filter((b) => b.id !== featuredPost.id); return filteredBlogs.filter((b) => b.id !== featuredPost.id);
}, [filteredBlogs, featuredPost]); }, [filteredBlogs, featuredPost]);
const slicedRegularPosts = useMemo(() => {
return regularPosts.slice(0, visibleCount);
}, [regularPosts, visibleCount]);
const hasMore = visibleCount < regularPosts.length;
// Extract all unique tags // Extract all unique tags
const allTags = useMemo(() => { const allTags = useMemo(() => {
const map = new Map<string, string>(); const map = new Map<string, string>();
@@ -172,57 +153,35 @@ export default function BlogPage({
</p> </p>
</div> </div>
{/* Search & Category Filter Section - Styled like /shop filters */} {/* Search & Category Filter Section */}
<div className="bg-white p-3.5 sm:p-6 rounded-2xl sm:rounded-3xl border border-medical-gray-200 shadow-xs mb-8 space-y-3 sm:space-y-4"> <div className="bg-white p-6 rounded-3xl border border-medical-gray-200 shadow-sm mb-12 space-y-5">
<div className="flex flex-col sm:flex-row items-center gap-2 sm:gap-4"> <div className="flex flex-col md:flex-row items-center gap-4">
{/* Search Input */} {/* Search Input */}
<div className="relative flex-1 w-full"> <div className="relative flex-1 w-full">
<Search className="w-4 h-4 absolute right-3.5 top-1/2 -translate-y-1/2 text-medical-gray-400" /> <Search className="w-4 h-4 absolute right-4 top-1/2 -translate-y-1/2 text-medical-gray-400" />
<input <input
type="text" type="text"
placeholder="جستجو در موضوعات، بیماری‌ها، ویتامین‌ها..." placeholder="جستجو در موضوعات، بیماری‌ها، ویتامین‌ها..."
value={searchQuery} value={searchQuery}
onChange={(e) => { onChange={(e) => setSearchQuery(e.target.value)}
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"
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 && ( {searchQuery && (
<button <button
onClick={() => setSearchQuery("")} onClick={() => setSearchQuery("")}
className="absolute left-3 top-1/2 -translate-y-1/2 text-xs font-bold text-medical-gray-400 hover:text-medical-gray-600 cursor-pointer" className="absolute left-3 top-1/2 -translate-y-1/2 text-xs font-bold text-medical-gray-400 hover:text-medical-gray-600"
> >
پاک کردن پاک کردن
</button> </button>
)} )}
</div> </div>
{/* Sort Dropdown */}
<div className="relative w-full sm:w-auto flex-shrink-0">
<div className="flex items-center bg-white border border-medical-gray-200 rounded-xl px-3 py-2 shadow-2xs text-xs font-bold text-medical-gray-700 w-full sm:w-auto justify-between sm:justify-start">
<div className="flex items-center gap-1.5">
<SlidersHorizontal className="w-3.5 h-3.5 text-canina-blue shrink-0" />
<span className="text-medical-gray-400 text-[10px] whitespace-nowrap">مرتب‌سازی:</span>
</div>
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value as any)}
className="bg-transparent text-xs font-black text-medical-gray-900 outline-none cursor-pointer pr-1"
>
<option value="newest">جدیدترین مقالات</option>
<option value="oldest">قدیمی‌ترین</option>
<option value="most_viewed">پربازدیدترین‌ها</option>
</select>
</div>
</div>
{selectedTag && ( {selectedTag && (
<div className="flex items-center gap-2 px-3 py-1.5 bg-purple-50 text-purple-700 border border-purple-200 rounded-xl text-xs font-bold self-start sm:self-auto"> <div className="flex items-center gap-2 px-3 py-2 bg-purple-50 text-purple-700 border border-purple-200 rounded-xl text-xs font-bold">
<span>تگ: #{selectedTag}</span> <span>تگ انتخاب شده: #{selectedTag}</span>
<button <button
onClick={() => setSelectedTag(null)} onClick={() => setSelectedTag(null)}
className="text-purple-500 hover:text-purple-900 cursor-pointer" className="text-purple-500 hover:text-purple-900"
> >
✕ ✕
</button> </button>
@@ -230,61 +189,54 @@ export default function BlogPage({
)} )}
</div> </div>
{/* Category Filter Pills with smooth edge mask */} {/* Category Filter Pills */}
<div className="relative -mx-3.5 sm:mx-0 px-3.5 sm:px-0"> <div className="flex items-center gap-2 overflow-x-auto pb-1 scrollbar-none">
<div className="flex items-center gap-1.5 sm:gap-2 overflow-x-auto pb-1 micro-hscroll select-none mobile-filter-mask"> <button
onClick={() => {
setSelectedCategory("ALL");
router.replace('/blog', { scroll: false });
}}
className={`px-4 py-2 rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap ${
selectedCategory === "ALL"
? "bg-canina-blue text-white shadow-md shadow-canina-blue/20 scale-102"
: "bg-medical-gray-100 text-medical-gray-600 hover:bg-medical-gray-200"
}`}
>
همه دسته‌ها ({blogs.length})
</button>
{categories.map((c) => (
<button <button
key={c.id}
onClick={() => { onClick={() => {
setSelectedCategory("ALL"); setSelectedCategory(c.id);
setVisibleCount(6); router.replace(`/blog?categoryId=${c.id}`, { scroll: false });
router.replace('/blog', { scroll: false });
}} }}
className={`px-3.5 py-1.5 sm:px-4 sm:py-2 rounded-xl sm:rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap border shrink-0 ${ className={`px-4 py-2 rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap ${
selectedCategory === "ALL" selectedCategory === c.id
? "bg-canina-blue text-white border-canina-blue shadow-xs" ? "bg-canina-blue text-white shadow-md shadow-canina-blue/20 scale-102"
: "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40" : "bg-medical-gray-100 text-medical-gray-600 hover:bg-medical-gray-200"
}`} }`}
> >
همه دسته‌ها ({blogs.length}) {c.name}
</button> </button>
{categories.map((c) => ( ))}
<button
key={c.id}
onClick={() => {
setSelectedCategory(c.id);
setVisibleCount(6);
router.replace(`/blog?categoryId=${c.id}`, { scroll: false });
}}
className={`px-3.5 py-1.5 sm:px-4 sm:py-2 rounded-xl sm:rounded-2xl text-xs font-black transition-all cursor-pointer whitespace-nowrap border shrink-0 ${
selectedCategory === c.id
? "bg-canina-blue text-white border-canina-blue shadow-xs"
: "bg-medical-gray-50 border-medical-gray-200 text-medical-gray-600 hover:border-canina-blue/40"
}`}
>
{c.name}
</button>
))}
</div>
</div> </div>
{/* Quick Tag Cloud */} {/* Quick Tag Cloud */}
{allTags.length > 0 && ( {allTags.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5 pt-2 border-t border-medical-gray-100"> <div className="flex flex-wrap items-center gap-1.5 pt-2 border-t border-medical-gray-100">
<span className="text-[10px] sm:text-[11px] font-bold text-medical-gray-400 flex items-center gap-1 ml-1"> <span className="text-[11px] font-bold text-medical-gray-400 flex items-center gap-1 ml-2">
<Tag className="w-3 h-3" /> <Tag className="w-3 h-3" />
تگ‌های محبوب: محبوب‌ترین تگ‌ها:
</span> </span>
{allTags.slice(0, 8).map((tag) => ( {allTags.slice(0, 10).map((tag) => (
<button <button
key={tag} key={tag}
onClick={() => { onClick={() => setSelectedTag(selectedTag === tag ? null : tag)}
setSelectedTag(selectedTag === tag ? null : tag); className={`text-[11px] font-bold px-2.5 py-1 rounded-lg transition-all cursor-pointer ${
setVisibleCount(6);
}}
className={`text-[10px] sm:text-[11px] font-bold px-2 py-0.5 sm:px-2.5 sm:py-1 rounded-lg transition-all cursor-pointer border ${
selectedTag === tag selectedTag === tag
? "bg-purple-600 text-white border-purple-600" ? "bg-purple-600 text-white"
: "bg-medical-gray-50 text-medical-gray-600 border-medical-gray-200 hover:bg-medical-gray-100" : "bg-medical-gray-100 text-medical-gray-600 hover:bg-medical-gray-200"
}`} }`}
> >
#{tag} #{tag}
@@ -297,11 +249,11 @@ export default function BlogPage({
{/* Featured Post Banner */} {/* Featured Post Banner */}
{featuredPost && ( {featuredPost && (
<div className="mb-16"> <div className="mb-16">
<motion.a <motion.div
href={`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`}
initial={{ opacity: 0, y: 20 }} initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all" className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all"
onClick={() => router.push(`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`)}
> >
<div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100"> <div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100">
<SafeImage <SafeImage
@@ -359,30 +311,22 @@ export default function BlogPage({
</div> </div>
</div> </div>
</div> </div>
</motion.a> </motion.div>
</div> </div>
)} )}
{/* Regular Posts Grid - Mobile-Optimized */} {/* Regular Posts Grid */}
{slicedRegularPosts.length > 0 ? ( {regularPosts.length > 0 ? (
<> <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
<div className="flex items-center justify-between mb-4"> {regularPosts.map((post, idx) => (
<h2 className="text-base sm:text-xl font-black text-medical-gray-900 font-vazir">همه مقالات تخصصی</h2> <motion.div
<span className="text-xs font-bold text-medical-gray-400">
{toPersian(regularPosts.length)} مقاله
</span>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-8">
{slicedRegularPosts.map((post, idx) => (
<motion.a
key={post.id} key={post.id}
href={`/blog/${encodeURIComponent(post.slug || post.id)}`}
initial={{ opacity: 0, y: 20 }} initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }} whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }} viewport={{ once: true }}
transition={{ delay: idx * 0.05 }} transition={{ delay: idx * 0.05 }}
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" className="bg-white rounded-[2.5rem] overflow-hidden border border-medical-gray-200 shadow-lg group hover:shadow-2xl hover:border-canina-blue/30 transition-all cursor-pointer flex flex-col justify-between"
onClick={() => router.push(`/blog/${encodeURIComponent(post.slug || post.id)}`)}
> >
<div> <div>
<div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100"> <div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100">
@@ -404,7 +348,7 @@ export default function BlogPage({
<span>{(post.viewCount ?? 0).toLocaleString('fa-IR')}</span> <span>{(post.viewCount ?? 0).toLocaleString('fa-IR')}</span>
</span> </span>
</div> </div>
<div className="p-4 sm:p-7"> <div className="p-6 sm:p-7">
<div className="flex items-center justify-between text-[11px] font-bold text-medical-gray-400 mb-3"> <div className="flex items-center justify-between text-[11px] font-bold text-medical-gray-400 mb-3">
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Calendar className="w-3 h-3" /> <Calendar className="w-3 h-3" />
@@ -430,7 +374,7 @@ export default function BlogPage({
</div> </div>
</div> </div>
<div className="px-4 sm:px-7 pb-4 sm:pb-6 pt-2.5 border-t border-medical-gray-100 flex items-center justify-between"> <div className="px-6 sm:px-7 pb-6 pt-3 border-t border-medical-gray-100 flex items-center justify-between">
<div className="text-[11px] font-bold text-medical-gray-500 flex items-center gap-1.5"> <div className="text-[11px] font-bold text-medical-gray-500 flex items-center gap-1.5">
<User className="w-3.5 h-3.5 text-medical-gray-400" /> <User className="w-3.5 h-3.5 text-medical-gray-400" />
<span>{post.author}</span> <span>{post.author}</span>
@@ -440,25 +384,9 @@ export default function BlogPage({
<ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" /> <ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" />
</div> </div>
</div> </div>
</motion.a> </motion.div>
))} ))}
</div> </div>
{hasMore && (
<div className="mt-8 mb-4 text-center">
<button
type="button"
onClick={() => setVisibleCount(prev => prev + 6)}
className="inline-flex items-center gap-2 px-6 py-3 bg-white border border-medical-gray-200 hover:border-canina-blue text-canina-blue font-black text-xs sm:text-sm rounded-2xl shadow-xs hover:shadow-md active:scale-95 transition-all cursor-pointer font-vazir"
>
<span>مشاهده ۶ مقاله بیشتر</span>
<span className="text-xs text-medical-gray-400 font-bold">
(نمایش {toPersian(slicedRegularPosts.length)} از {toPersian(regularPosts.length)})
</span>
</button>
</div>
)}
</>
) : ( ) : (
<div className="text-center py-16 bg-white rounded-3xl border border-medical-gray-200"> <div className="text-center py-16 bg-white rounded-3xl border border-medical-gray-200">
<p className="text-medical-gray-500 font-bold text-sm"> <p className="text-medical-gray-500 font-bold text-sm">
@@ -1,5 +1,6 @@
"use client"; "use client";
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import DOMPurify from 'dompurify';
import { import {
ChevronRight, ChevronRight,
Calendar, Calendar,
@@ -18,17 +19,14 @@ import {
import Link from 'next/link'; import Link from 'next/link';
import SafeImage from "./SafeImage"; import SafeImage from "./SafeImage";
import api from "../lib/services/api"; import api from "../lib/services/api";
import ArticleContentRenderer from "./ArticleContentRenderer";
interface BlogPostClientProps { interface BlogPostClientProps {
blog: any; blog: any;
publishedDate: string; publishedDate: string;
authorName: string; authorName: string;
sanitizedContent: string;
} }
export default function BlogPostClient({ blog, publishedDate, authorName, sanitizedContent }: BlogPostClientProps) { export default function BlogPostClient({ blog, publishedDate, authorName }: BlogPostClientProps) {
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
const [viewCount, setViewCount] = useState<number>(blog.viewCount || 0); const [viewCount, setViewCount] = useState<number>(blog.viewCount || 0);
const [commentName, setCommentName] = useState(""); const [commentName, setCommentName] = useState("");
@@ -175,10 +173,17 @@ export default function BlogPostClient({ blog, publishedDate, authorName, saniti
</div> </div>
)} )}
{/* Main Rich Content HTML Renderer with In-Article Product Cards */} {/* Main Rich Content HTML Renderer */}
<ArticleContentRenderer <div
contentHtml={sanitizedContent} className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5 article-html-content"
relatedProducts={relatedProducts} dangerouslySetInnerHTML={{
__html: typeof window !== 'undefined'
? DOMPurify.sanitize(blog.content || '', {
ADD_TAGS: ['iframe'],
ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'],
})
: blog.content || '',
}}
/> />
{/* Tags Chip Footer */} {/* Tags Chip Footer */}
@@ -56,10 +56,10 @@ export default function BlogPreviewSection() {
} }
return ( return (
<section className="py-5 sm:py-20 bg-white font-vazir" dir="rtl"> <section className="py-8 sm:py-20 bg-white font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto px-4"> <div className="max-w-7xl mx-auto px-4">
{/* Section Header */} {/* Section Header */}
<div className="flex flex-col sm:flex-row sm:items-end justify-between mb-4 sm:mb-12 pb-3 sm:pb-6 border-b border-medical-gray-200 gap-2 sm:gap-6"> <div className="flex flex-col sm:flex-row sm:items-end justify-between mb-6 sm:mb-12 pb-4 sm:pb-6 border-b border-medical-gray-200 gap-3 sm:gap-6">
<div className="max-w-2xl"> <div className="max-w-2xl">
<div className="inline-flex items-center gap-2 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-full text-[10px] font-black uppercase tracking-widest mb-2 sm:mb-3 font-vazir"> <div className="inline-flex items-center gap-2 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-full text-[10px] font-black uppercase tracking-widest mb-2 sm:mb-3 font-vazir">
<BookOpen className="w-3 h-3" /> <BookOpen className="w-3 h-3" />
+6 -15
View File
@@ -94,14 +94,11 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
className="fixed inset-0 bg-medical-gray-900/40 backdrop-blur-sm z-[100]" className="fixed inset-0 bg-medical-gray-900/40 backdrop-blur-sm z-[100]"
/> />
<motion.div <motion.div
role="dialog"
aria-modal="true"
aria-labelledby="cart-drawer-title"
initial={{ x: "100%" }} initial={{ x: "100%" }}
animate={{ x: 0 }} animate={{ x: 0 }}
exit={{ x: "100%" }} exit={{ x: "100%" }}
transition={{ type: "spring", damping: 25, stiffness: 200 }} transition={{ type: "spring", damping: 25, stiffness: 200 }}
className="fixed inset-y-0 right-0 w-full max-w-full sm:max-w-md bg-white shadow-2xl z-[101] flex flex-col overflow-x-hidden" className="fixed inset-y-0 right-0 w-full max-w-md bg-white shadow-2xl z-[101] flex flex-col"
dir="rtl" dir="rtl"
> >
{/* Header */} {/* Header */}
@@ -110,9 +107,9 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
<div className="w-10 h-10 bg-medical-gray-50 rounded-xl flex items-center justify-center text-canina-blue"> <div className="w-10 h-10 bg-medical-gray-50 rounded-xl flex items-center justify-center text-canina-blue">
<ShoppingBag className="w-6 h-6" /> <ShoppingBag className="w-6 h-6" />
</div> </div>
<h3 id="cart-drawer-title" className="text-xl font-black text-medical-gray-900 italic">سبد خرید</h3> <h3 className="text-xl font-black text-medical-gray-900 italic">سبد خرید</h3>
</div> </div>
<button aria-label="بستن سبد خرید" onClick={onClose} className="min-w-[44px] min-h-[44px] flex items-center justify-center p-2 hover:bg-medical-gray-50 rounded-full transition-colors cursor-pointer"> <button onClick={onClose} className="p-2 hover:bg-medical-gray-50 rounded-full transition-colors">
<X className="w-6 h-6 text-medical-gray-400" /> <X className="w-6 h-6 text-medical-gray-400" />
</button> </button>
</div> </div>
@@ -149,31 +146,25 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2 bg-white rounded-lg border border-medical-gray-200 p-1"> <div className="flex items-center gap-2 bg-white rounded-lg border border-medical-gray-200 p-1">
<button <button
type="button"
aria-label={`کاهش تعداد ${item.product.nameFa || item.product.name}`}
onClick={() => updateQuantity(item.product.id, item.quantity - 1)} onClick={() => updateQuantity(item.product.id, item.quantity - 1)}
className="min-w-[44px] min-h-[44px] flex items-center justify-center p-1 hover:text-canina-blue transition-colors cursor-pointer" className="p-1 hover:text-canina-blue transition-colors"
data-testid="minus-btn" data-testid="minus-btn"
> >
<Minus className="w-3 h-3" /> <Minus className="w-3 h-3" />
</button> </button>
<span data-testid="cart-item-quantity" className="text-xs font-black min-w-[20px] text-center font-vazir">{toPersian(item.quantity)}</span> <span data-testid="cart-item-quantity" className="text-xs font-black min-w-[20px] text-center font-vazir">{toPersian(item.quantity)}</span>
<button <button
type="button"
aria-label={`افزایش تعداد ${item.product.nameFa || item.product.name}`}
onClick={() => updateQuantity(item.product.id, item.quantity + 1)} onClick={() => updateQuantity(item.product.id, item.quantity + 1)}
className="min-w-[44px] min-h-[44px] flex items-center justify-center p-1 hover:text-canina-blue transition-colors cursor-pointer" className="p-1 hover:text-canina-blue transition-colors"
data-testid="plus-btn" data-testid="plus-btn"
> >
<Plus className="w-3 h-3" /> <Plus className="w-3 h-3" />
</button> </button>
</div> </div>
<button <button
type="button"
aria-label={`حذف ${item.product.nameFa || item.product.name} از سبد خرید`}
data-testid="cart-item-delete-btn" data-testid="cart-item-delete-btn"
onClick={() => setDeleteConfirmId(item.product.id)} onClick={() => setDeleteConfirmId(item.product.id)}
className="min-w-[44px] min-h-[44px] flex items-center justify-center text-medical-gray-300 hover:text-red-500 transition-colors cursor-pointer" className="text-medical-gray-300 hover:text-red-500 transition-colors"
> >
<Trash2 className="w-4 h-4" /> <Trash2 className="w-4 h-4" />
</button> </button>
@@ -126,12 +126,6 @@ export default function CheckoutPage() {
}; };
const handleFinalize = async () => { const handleFinalize = async () => {
if (!items.length || getSubtotal() <= 0) {
toast.error("سبد خرید شما خالی است.");
router.push('/shop');
return;
}
const totalAmount = getTotal() + shippingFee; const totalAmount = getTotal() + shippingFee;
const activePet = getActivePet(); const activePet = getActivePet();
@@ -375,7 +369,7 @@ export default function CheckoutPage() {
<span className="text-medical-gray-300">/</span> <span className="text-medical-gray-300">/</span>
<span className="cursor-pointer hover:text-canina-blue" onClick={() => router.push('/shop')}>سبد خرید</span> <span className="cursor-pointer hover:text-canina-blue" onClick={() => router.push('/shop')}>سبد خرید</span>
<span className="text-medical-gray-300">/</span> <span className="text-medical-gray-300">/</span>
<h1 className="text-xs font-black text-canina-blue inline m-0 p-0 font-vazir">تسویه‌حساب و پرداخت</h1> <span className="text-canina-blue font-black">تسویه‌حساب و پرداخت</span>
</div> </div>
<div className="hidden sm:flex items-center gap-1.5 text-xs text-emerald-700 bg-emerald-50 border border-emerald-200 px-3 py-1 rounded-full font-bold"> <div className="hidden sm:flex items-center gap-1.5 text-xs text-emerald-700 bg-emerald-50 border border-emerald-200 px-3 py-1 rounded-full font-bold">
<ShieldCheck className="w-3.5 h-3.5" /> <ShieldCheck className="w-3.5 h-3.5" />
@@ -130,7 +130,7 @@ export default function ContactFormClient() {
</p> </p>
<button <button
onClick={() => setSuccess(false)} onClick={() => setSuccess(false)}
className="mt-4 min-h-[44px] px-6 py-2.5 bg-emerald-600 text-white rounded-xl text-xs font-black cursor-pointer" className="mt-4 px-6 py-2 bg-emerald-600 text-white rounded-xl text-xs font-black"
> >
ارسال پیام جدید ارسال پیام جدید
</button> </button>
@@ -150,9 +150,7 @@ export default function ContactFormClient() {
</label> </label>
<input <input
id="contact-name" id="contact-name"
name="name"
type="text" type="text"
autoComplete="name"
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => 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" 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"
@@ -164,10 +162,7 @@ export default function ContactFormClient() {
<label htmlFor="contact-phone" className="text-xs font-black text-medical-gray-500">شماره موبایل *</label> <label htmlFor="contact-phone" className="text-xs font-black text-medical-gray-500">شماره موبایل *</label>
<input <input
id="contact-phone" id="contact-phone"
name="phone" type="text"
type="tel"
inputMode="tel"
autoComplete="tel"
value={phone} value={phone}
onChange={(e) => setPhone(e.target.value)} onChange={(e) => 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" 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"
@@ -186,9 +186,9 @@ export default function FeaturedProducts() {
}, []); }, []);
return ( return (
<section className="py-5 sm:py-16 bg-medical-gray-50"> <section className="py-8 sm:py-16 bg-medical-gray-50">
<div className="max-w-7xl mx-auto px-4"> <div className="max-w-7xl mx-auto px-4">
<div className="flex flex-col sm:flex-row sm:items-end justify-between w-full mb-4 sm:mb-12 pb-3 sm:pb-6 border-b border-medical-gray-200 gap-2 sm:gap-6"> <div className="flex flex-col sm:flex-row sm:items-end justify-between w-full mb-6 sm:mb-12 pb-4 sm:pb-6 border-b border-medical-gray-200 gap-3 sm:gap-6">
<div className="max-w-2xl"> <div className="max-w-2xl">
<div className="text-canina-blue text-[10px] sm:text-xs font-bold uppercase tracking-[0.2em] mb-1.5 sm:mb-2 font-vazir"> <div className="text-canina-blue text-[10px] sm:text-xs font-bold uppercase tracking-[0.2em] mb-1.5 sm:mb-2 font-vazir">
{getText("featured_badge", "بیشترین انتخاب توسط دامپزشکان")} {getText("featured_badge", "بیشترین انتخاب توسط دامپزشکان")}
+11 -17
View File
@@ -1,6 +1,5 @@
"use client"; "use client";
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import Image from "next/image"; import Image from "next/image";
import { Phone, Mail, MapPin, Instagram, ShieldCheck, Globe, ArrowUp, Download, ChevronDown, ChevronUp } from "lucide-react"; import { Phone, Mail, MapPin, Instagram, ShieldCheck, Globe, ArrowUp, Download, ChevronDown, ChevronUp } from "lucide-react";
import { useSettingsStore } from "../lib/store/settingsStore"; import { useSettingsStore } from "../lib/store/settingsStore";
@@ -9,9 +8,7 @@ import Link from "next/link";
import { NavigationTarget } from "../lib/types"; import { NavigationTarget } from "../lib/types";
export default function Footer({ export default function Footer({
// Footer hooks
onB2BOpen onB2BOpen
}: { }: {
onNavigate?: (v: NavigationTarget) => void; onNavigate?: (v: NavigationTarget) => void;
@@ -20,8 +17,6 @@ export default function Footer({
}) { }) {
const getText = useSettingsStore(state => state.getText); const getText = useSettingsStore(state => state.getText);
const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true)); const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true));
const pathname = usePathname();
const isPdpPage = pathname?.startsWith('/shop/') && pathname !== '/shop';
const [showScroll, setShowScroll] = useState(false); const [showScroll, setShowScroll] = useState(false);
const [footerCol1, setFooterCol1] = useState<Array<{ id?: string; label: string; href: string }>>([]); const [footerCol1, setFooterCol1] = useState<Array<{ id?: string; label: string; href: string }>>([]);
const [isDescExpanded, setIsDescExpanded] = useState(false); const [isDescExpanded, setIsDescExpanded] = useState(false);
@@ -58,13 +53,12 @@ export default function Footer({
return ( return (
<footer className="bg-medical-gray-900 text-white pt-10 sm:pt-24 pb-28 sm:pb-12 font-shabnam relative" dir="rtl"> <footer className="bg-medical-gray-900 text-white pt-10 sm:pt-24 pb-28 sm:pb-12 font-shabnam relative" dir="rtl">
{/* Floating Back-to-Top Button (Docked cleanly on the RIGHT side to avoid overlapping SupportChat on the LEFT) */} {/* Floating Back-to-Top Button */}
{showScroll && ( {showScroll && (
<button <button
onClick={scrollToTop} onClick={scrollToTop}
className={`fixed ${isPdpPage ? "bottom-[138px]" : "bottom-36"} right-4 sm:bottom-8 sm:right-8 z-40 bg-canina-blue text-white p-2.5 sm:p-3 rounded-full shadow-2xl hover:bg-canina-dark hover:scale-110 transition-all border border-white/20 group flex items-center gap-2 font-vazir text-xs font-black cursor-pointer`} className="fixed bottom-20 left-4 sm:bottom-8 sm:left-8 z-40 bg-canina-blue text-white p-2.5 sm:p-3 rounded-full shadow-2xl hover:bg-canina-dark hover:scale-110 transition-all border border-white/20 group flex items-center gap-2 font-vazir text-xs font-black"
title="بازگشت به بالای صفحه" title="بازگشت به بالای صفحه"
aria-label="بازگشت به بالای صفحه"
> >
<ArrowUp className="w-4 h-4 sm:w-5 sm:h-5 group-hover:-translate-y-1 transition-transform" /> <ArrowUp className="w-4 h-4 sm:w-5 sm:h-5 group-hover:-translate-y-1 transition-transform" />
<span className="hidden sm:inline">بازگشت به بالا</span> <span className="hidden sm:inline">بازگشت به بالا</span>
@@ -80,12 +74,12 @@ export default function Footer({
<BrandLogo isDarkBackground size="lg" /> <BrandLogo isDarkBackground size="lg" />
<div className="flex gap-2.5 sm:hidden"> <div className="flex gap-2.5 sm:hidden">
{getText('contact_instagram', '') && ( {getText('contact_instagram', '') && (
<a href={getText('contact_instagram', '#')} target="_blank" rel="noopener noreferrer" aria-label="صفحه اینستاگرام رسمی کنینا ایران" className="min-w-[44px] min-h-[44px] w-11 h-11 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300"> <a href={getText('contact_instagram', '#')} target="_blank" rel="noopener noreferrer" aria-label="صفحه اینستاگرام رسمی کنینا ایران" className="w-9 h-9 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300">
<Instagram className="w-4 h-4" /> <Instagram className="w-4 h-4" />
</a> </a>
)} )}
{getText('contact_telegram', '') && ( {getText('contact_telegram', '') && (
<a href={getText('contact_telegram', '#')} target="_blank" rel="noopener noreferrer" aria-label="کانال تلگرام رسمی کنینا ایران" className="min-w-[44px] min-h-[44px] w-11 h-11 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300"> <a href={getText('contact_telegram', '#')} target="_blank" rel="noopener noreferrer" aria-label="کانال تلگرام رسمی کنینا ایران" className="w-9 h-9 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300">
<Globe className="w-4 h-4" /> <Globe className="w-4 h-4" />
</a> </a>
)} )}
@@ -127,12 +121,12 @@ export default function Footer({
<div className="hidden sm:flex gap-4 pt-1"> <div className="hidden sm:flex gap-4 pt-1">
{getText('contact_instagram', '') && ( {getText('contact_instagram', '') && (
<a href={getText('contact_instagram', '#')} target="_blank" rel="noopener noreferrer" aria-label="صفحه اینستاگرام رسمی کنینا ایران" className="min-w-[44px] min-h-[44px] w-11 h-11 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300"> <a href={getText('contact_instagram', '#')} target="_blank" rel="noopener noreferrer" aria-label="صفحه اینستاگرام رسمی کنینا ایران" className="w-10 h-10 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300">
<Instagram className="w-5 h-5" /> <Instagram className="w-5 h-5" />
</a> </a>
)} )}
{getText('contact_telegram', '') && ( {getText('contact_telegram', '') && (
<a href={getText('contact_telegram', '#')} target="_blank" rel="noopener noreferrer" aria-label="کانال تلگرام رسمی کنینا ایران" className="min-w-[44px] min-h-[44px] w-11 h-11 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300"> <a href={getText('contact_telegram', '#')} target="_blank" rel="noopener noreferrer" aria-label="کانال تلگرام رسمی کنینا ایران" className="w-10 h-10 bg-white/10 rounded-xl flex items-center justify-center hover:bg-canina-blue hover:text-white transition-all text-slate-300">
<Globe className="w-5 h-5" /> <Globe className="w-5 h-5" />
</a> </a>
)} )}
@@ -215,7 +209,7 @@ export default function Footer({
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-8"> <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-8">
<div className="flex flex-col sm:space-y-6 gap-2.5 sm:gap-0"> <div className="flex flex-col sm:space-y-6 gap-2.5 sm:gap-0">
<a href={getText('contact_phone_link', `tel:${getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0"> <a href={getText('contact_phone_link', `tel:${getText('contact_phone', '').replace(/[^0-9+]/g, '')}`)} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0">
<div className="min-w-[44px] min-h-[44px] w-11 h-11 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0"> <div className="w-9 h-9 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0">
<Phone className="w-4 h-4 sm:w-6 sm:h-6" /> <Phone className="w-4 h-4 sm:w-6 sm:h-6" />
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
@@ -224,7 +218,7 @@ export default function Footer({
</div> </div>
</a> </a>
<a href={`mailto:${getText('contact_email', '')}`} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0"> <a href={`mailto:${getText('contact_email', '')}`} className="flex items-center sm:items-start gap-2.5 sm:gap-4 group hover:opacity-90 transition-opacity bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0">
<div className="min-w-[44px] min-h-[44px] w-11 h-11 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0"> <div className="w-9 h-9 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0">
<Mail className="w-4 h-4 sm:w-6 sm:h-6" /> <Mail className="w-4 h-4 sm:w-6 sm:h-6" />
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
@@ -235,7 +229,7 @@ export default function Footer({
</div> </div>
<div className="flex items-start gap-2.5 sm:gap-4 group bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0"> <div className="flex items-start gap-2.5 sm:gap-4 group bg-white/[0.04] sm:bg-transparent p-3 sm:p-0 rounded-xl sm:rounded-none border border-white/5 sm:border-0">
<div className="min-w-[44px] min-h-[44px] w-11 h-11 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0"> <div className="w-9 h-9 sm:w-12 sm:h-12 bg-white/5 rounded-xl sm:rounded-2xl flex items-center justify-center text-blue-400 group-hover:scale-110 transition-transform flex-shrink-0">
<MapPin className="w-4 h-4 sm:w-6 sm:h-6" /> <MapPin className="w-4 h-4 sm:w-6 sm:h-6" />
</div> </div>
<div className="min-w-0"> <div className="min-w-0">
@@ -248,7 +242,7 @@ export default function Footer({
{/* Trust and Verification Banner */} {/* Trust and Verification Banner */}
<div className="mt-4 sm:mt-10 p-3.5 sm:p-6 bg-white/5 rounded-2xl sm:rounded-[2rem] border border-white/10 flex flex-col sm:flex-row items-center justify-between gap-3.5 sm:gap-6 text-center sm:text-right"> <div className="mt-4 sm:mt-10 p-3.5 sm:p-6 bg-white/5 rounded-2xl sm:rounded-[2rem] border border-white/10 flex flex-col sm:flex-row items-center justify-between gap-3.5 sm:gap-6 text-center sm:text-right">
<div className="flex items-center gap-2.5 sm:gap-4 w-full sm:w-auto"> <div className="flex items-center gap-2.5 sm:gap-4 w-full sm:w-auto">
<div className="min-w-[44px] min-h-[44px] w-11 h-11 sm:w-12 sm:h-12 bg-green-500/20 text-green-500 rounded-full flex items-center justify-center flex-shrink-0"> <div className="w-9 h-9 sm:w-10 sm:h-10 bg-green-500/20 text-green-500 rounded-full flex items-center justify-center flex-shrink-0">
<ShieldCheck className="w-4 h-4 sm:w-6 sm:h-6" /> <ShieldCheck className="w-4 h-4 sm:w-6 sm:h-6" />
</div> </div>
<div className="text-right min-w-0 flex-1"> <div className="text-right min-w-0 flex-1">
+7 -9
View File
@@ -5,7 +5,6 @@ import { Search, ChevronDown, Menu, X, Pill, ShieldCheck, HeartPulse, Sparkles,
import { motion, AnimatePresence } from "motion/react"; import { motion, AnimatePresence } from "motion/react";
import Link from "next/link"; import Link from "next/link";
import { useCartStore } from "../lib/store/cartStore"; import { useCartStore } from "../lib/store/cartStore";
import { useUIStore } from "../lib/store/uiStore";
import { usePetStore } from "../lib/store/usePetStore"; import { usePetStore } from "../lib/store/usePetStore";
import { useUserStore } from "../lib/store/userStore"; import { useUserStore } from "../lib/store/userStore";
import { useSettingsStore } from "../lib/store/settingsStore"; import { useSettingsStore } from "../lib/store/settingsStore";
@@ -231,8 +230,6 @@ export default function Header({
<form onSubmit={handleSearch} className="w-full relative"> <form onSubmit={handleSearch} className="w-full relative">
<input <input
type="text" type="text"
aria-label="جستجوی محصول، ترکیب دارویی یا بیماری پت"
name="global-search"
placeholder="جستجوی محصول، ترکیب دارویی یا بیماری پت..." placeholder="جستجوی محصول، ترکیب دارویی یا بیماری پت..."
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
@@ -250,15 +247,18 @@ export default function Header({
{/* Left Action Buttons */} {/* Left Action Buttons */}
<div className="flex items-center gap-1.5 sm:gap-3 shrink-0"> <div className="flex items-center gap-1.5 sm:gap-3 shrink-0">
{/* Prescription Upload Button (Desktop & Mobile) - Opens Prescription Modal */} {/* Prescription Upload Button (Desktop & Mobile) */}
{isPrescriptionEnabled && ( {isPrescriptionEnabled && (
<button <button
type="button"
onClick={() => { onClick={() => {
useUIStore.getState().setPrescriptionModalOpen(true); if (!isLoggedIn) {
setIsAuthModalOpen(true);
} else {
setIsPrescriptionModalOpen(true);
}
}} }}
className="flex items-center gap-1.5 px-2.5 sm:px-3 py-2 bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100 rounded-xl text-[11px] sm:text-xs font-black transition-all shadow-xs cursor-pointer" className="flex items-center gap-1.5 px-2.5 sm:px-3 py-2 bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100 rounded-xl text-[11px] sm:text-xs font-black transition-all shadow-xs cursor-pointer"
title="ثبت نسخه دامپزشک" title="ثبت نسخه دامپزشک"
> >
<FileHeart className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 shrink-0" /> <FileHeart className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-emerald-600 shrink-0" />
<span className="hidden xs:inline sm:inline">ثبت نسخه دامپزشک</span> <span className="hidden xs:inline sm:inline">ثبت نسخه دامپزشک</span>
@@ -537,8 +537,6 @@ export default function Header({
<form onSubmit={handleSearch} className="relative mb-3"> <form onSubmit={handleSearch} className="relative mb-3">
<input <input
type="text" type="text"
aria-label="جستجو در محصولات"
name="mobile-global-search"
placeholder="جستجو در محصولات..." placeholder="جستجو در محصولات..."
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
+5 -7
View File
@@ -1,5 +1,3 @@
"use client";
import { sanitizeBlogHtml } from "../lib/sanitizeBlogHtml";
import Image from "next/image"; import Image from "next/image";
import { motion, AnimatePresence, animate } from "motion/react"; import { motion, AnimatePresence, animate } from "motion/react";
import { ChevronLeft, ChevronRight, Globe, ShieldCheck, Calendar, ArrowLeft } from "lucide-react"; import { ChevronLeft, ChevronRight, Globe, ShieldCheck, Calendar, ArrowLeft } from "lucide-react";
@@ -136,7 +134,7 @@ export default function Hero({ banners = [], onShopNavigate }: { banners?: Banne
suppressHydrationWarning suppressHydrationWarning
className="text-sm lg:text-xl text-medical-gray-600 mb-3 sm:mb-5 max-w-2xl mx-auto lg:mx-0 leading-relaxed font-vazir animate-fade-in [&_p]:text-sm [&_p]:lg:text-xl [&_p]:leading-relaxed [&_p]:my-0 [&_span]:text-inherit" className="text-sm lg:text-xl text-medical-gray-600 mb-3 sm:mb-5 max-w-2xl mx-auto lg:mx-0 leading-relaxed font-vazir animate-fade-in [&_p]:text-sm [&_p]:lg:text-xl [&_p]:leading-relaxed [&_p]:my-0 [&_span]:text-inherit"
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{
__html: sanitizeBlogHtml(subtitle) __html: subtitle
}} }}
/> />
@@ -315,10 +313,10 @@ export default function Hero({ banners = [], onShopNavigate }: { banners?: Banne
initial={{ opacity: 0, y: 20 }} initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.8, duration: 0.6 }} transition={{ delay: 0.8, duration: 0.6 }}
className="grid grid-cols-3 gap-1.5 sm:gap-6 py-3 sm:py-10 border-t border-medical-gray-150" className="grid grid-cols-3 gap-2 sm:gap-6 py-6 sm:py-10 border-t border-medical-gray-150"
> >
{/* Stat 1: Founded Year */} {/* Stat 1: Founded Year */}
<div className="bg-medical-gray-50/50 border border-medical-gray-100 rounded-2xl sm:rounded-3xl p-2 sm:p-6 flex flex-col sm:flex-row items-center justify-center text-center sm:text-right gap-1.5 sm:gap-6 group hover:shadow-xl hover:shadow-canina-blue/5 transition-all"> <div className="bg-medical-gray-50/50 border border-medical-gray-100 rounded-2xl sm:rounded-3xl p-2.5 sm:p-6 flex flex-col sm:flex-row items-center justify-center text-center sm:text-right gap-2 sm:gap-6 group hover:shadow-xl hover:shadow-canina-blue/5 transition-all">
<div className="w-9 h-9 sm:w-14 sm:h-14 bg-white rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue shadow-sm group-hover:bg-canina-blue group-hover:text-white transition-all duration-300 flex-shrink-0"> <div className="w-9 h-9 sm:w-14 sm:h-14 bg-white rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue shadow-sm group-hover:bg-canina-blue group-hover:text-white transition-all duration-300 flex-shrink-0">
<Calendar className="w-4 h-4 sm:w-7 sm:h-7" /> <Calendar className="w-4 h-4 sm:w-7 sm:h-7" />
</div> </div>
@@ -331,7 +329,7 @@ export default function Hero({ banners = [], onShopNavigate }: { banners?: Banne
</div> </div>
{/* Stat 2: Active Agencies */} {/* Stat 2: Active Agencies */}
<div className="bg-medical-gray-50/50 border border-medical-gray-100 rounded-2xl sm:rounded-3xl p-2 sm:p-6 flex flex-col sm:flex-row items-center justify-center text-center sm:text-right gap-1.5 sm:gap-6 group hover:shadow-xl hover:shadow-canina-blue/5 transition-all"> <div className="bg-medical-gray-50/50 border border-medical-gray-100 rounded-2xl sm:rounded-3xl p-2.5 sm:p-6 flex flex-col sm:flex-row items-center justify-center text-center sm:text-right gap-2 sm:gap-6 group hover:shadow-xl hover:shadow-canina-blue/5 transition-all">
<div className="w-9 h-9 sm:w-14 sm:h-14 bg-white rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue shadow-sm group-hover:bg-canina-blue group-hover:text-white transition-all duration-300 flex-shrink-0"> <div className="w-9 h-9 sm:w-14 sm:h-14 bg-white rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue shadow-sm group-hover:bg-canina-blue group-hover:text-white transition-all duration-300 flex-shrink-0">
<Globe className="w-4 h-4 sm:w-7 sm:h-7" /> <Globe className="w-4 h-4 sm:w-7 sm:h-7" />
</div> </div>
@@ -346,7 +344,7 @@ export default function Hero({ banners = [], onShopNavigate }: { banners?: Banne
</div> </div>
{/* Stat 3: German Formula */} {/* Stat 3: German Formula */}
<div className="bg-medical-gray-50/50 border border-medical-gray-100 rounded-2xl sm:rounded-3xl p-2 sm:p-6 flex flex-col sm:flex-row items-center justify-center text-center sm:text-right gap-1.5 sm:gap-6 group hover:shadow-xl hover:shadow-canina-blue/5 transition-all"> <div className="bg-medical-gray-50/50 border border-medical-gray-100 rounded-2xl sm:rounded-3xl p-2.5 sm:p-6 flex flex-col sm:flex-row items-center justify-center text-center sm:text-right gap-2 sm:gap-6 group hover:shadow-xl hover:shadow-canina-blue/5 transition-all">
<div className="w-9 h-9 sm:w-14 sm:h-14 bg-white rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue shadow-sm group-hover:bg-canina-blue group-hover:text-white transition-all duration-300 flex-shrink-0"> <div className="w-9 h-9 sm:w-14 sm:h-14 bg-white rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue shadow-sm group-hover:bg-canina-blue group-hover:text-white transition-all duration-300 flex-shrink-0">
<ShieldCheck className="w-4 h-4 sm:w-7 sm:h-7" /> <ShieldCheck className="w-4 h-4 sm:w-7 sm:h-7" />
</div> </div>
@@ -2,7 +2,7 @@
import { useState, useEffect, useMemo } from "react"; import { useState, useEffect, useMemo } from "react";
import { Product, IngredientInfo } from "../lib/data/products"; import { Product, IngredientInfo } from "../lib/data/products";
import { motion } from "motion/react"; import { motion } from "motion/react";
import { FlaskConical, CheckCircle2, ChevronLeft, ChevronDown, Beaker, Search } from "lucide-react"; import { FlaskConical, CheckCircle2, ChevronRight, ChevronLeft, Beaker, Search } from "lucide-react";
import { productService } from "../lib/services/productService"; import { productService } from "../lib/services/productService";
import Link from "next/link"; import Link from "next/link";
@@ -51,12 +51,12 @@ function formatIngredientDisplayName(item: { nameFa?: string; scientificName?: s
const rawName = item.nameFa || item.name || ''; const rawName = item.nameFa || item.name || '';
const cleanFa = rawName.replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim(); 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(); const sub = (item.scientificName || item.nameEn || '').replace(/\s*\([^)]*\)\s*/g, ' ').replace(/\s+/g, ' ').trim();
if (!cleanFa) return sub || rawName || item.slug || ''; if (!cleanFa) return sub || rawName || item.slug || '';
if (!sub || cleanFa.toLowerCase() === sub.toLowerCase() || /[\u0600-\u06FF]/.test(sub)) { if (!sub || cleanFa.toLowerCase() === sub.toLowerCase() || /[\u0600-\u06FF]/.test(sub)) {
return cleanFa; return cleanFa;
} }
return `${cleanFa} (${sub})`; return `${cleanFa} (${sub})`;
} }
@@ -67,8 +67,6 @@ export default function IngredientWiki() {
const [ingredientsWiki, setIngredientsWiki] = useState<IngredientInfo[]>([]); const [ingredientsWiki, setIngredientsWiki] = useState<IngredientInfo[]>([]);
const [products, setProducts] = useState<Product[]>([]); const [products, setProducts] = useState<Product[]>([]);
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [visibleCount, setVisibleCount] = useState(8);
const [expandedIngredients, setExpandedIngredients] = useState<Set<string>>(new Set());
useEffect(() => { useEffect(() => {
productService.getProducts({ limit: 999 }) productService.getProducts({ limit: 999 })
@@ -112,21 +110,7 @@ export default function IngredientWiki() {
}, 200); }, 200);
} }
} }
}, [termParam, ingredientsWiki, visibleCount]); }, [termParam, ingredientsWiki]);
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);
}
}, [termParam, ingredientsWiki, visibleCount]);
// Product matcher for each ingredient // Product matcher for each ingredient
const getProductsForIngredient = useMemo(() => { const getProductsForIngredient = useMemo(() => {
@@ -162,11 +146,11 @@ export default function IngredientWiki() {
}, [products]); }, [products]);
return ( return (
<div className="bg-white pt-3 pb-8 sm:py-12 px-4 overflow-hidden font-vazir" dir="rtl"> <div className="bg-white py-12 px-4 overflow-hidden font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto"> <div className="max-w-7xl mx-auto">
{/* Standard Breadcrumb Navigation & Integrated Back Button */} {/* Standard Breadcrumb Navigation & Integrated Back Button */}
<div className="flex items-center justify-between mb-4 sm:mb-8 pb-3 sm:pb-4 border-b border-medical-gray-200/60 font-vazir" dir="rtl"> <div className="flex items-center justify-between mb-8 pb-4 border-b border-medical-gray-200/60 font-vazir" dir="rtl">
<div className="flex items-center gap-2 text-xs font-bold text-medical-gray-400 whitespace-nowrap"> <div className="flex items-center gap-2 text-xs font-bold text-medical-gray-400 whitespace-nowrap">
<span className="cursor-pointer hover:text-canina-blue transition-colors" onClick={() => router.push('/')}>خانه</span> <span className="cursor-pointer hover:text-canina-blue transition-colors" onClick={() => router.push('/')}>خانه</span>
<ChevronLeft className="w-3 h-3 text-medical-gray-300" /> <ChevronLeft className="w-3 h-3 text-medical-gray-300" />
@@ -175,46 +159,43 @@ export default function IngredientWiki() {
<button <button
onClick={() => router.push('/')} onClick={() => router.push('/')}
className="min-h-[44px] px-4 py-2 bg-white border border-medical-gray-200 rounded-xl text-medical-gray-600 shadow-xs flex items-center gap-1.5 font-bold text-xs hover:border-canina-blue hover:text-canina-blue transition-all whitespace-nowrap cursor-pointer" className="px-3.5 py-1.5 bg-white border border-medical-gray-200 rounded-lg text-medical-gray-600 shadow-xs flex items-center gap-1.5 font-bold text-xs hover:border-canina-blue hover:text-canina-blue transition-all whitespace-nowrap cursor-pointer"
> >
<span>بازگشت</span> <span>بازگشت</span>
<ChevronLeft className="w-3.5 h-3.5" /> <ChevronLeft className="w-3.5 h-3.5" />
</button> </button>
</div> </div>
<div className="flex flex-col items-center text-center mb-6 sm:mb-14"> <div className="flex flex-col items-center text-center mb-20">
<div className="inline-flex items-center gap-2 px-3 py-1 sm:px-4 sm:py-2 bg-canina-blue/5 border border-canina-blue/10 rounded-full text-canina-blue text-[11px] sm:text-xs font-black uppercase tracking-widest mb-2 sm:mb-4"> <div className="inline-flex items-center gap-2 px-4 py-2 bg-canina-blue/5 border border-canina-blue/10 rounded-full text-canina-blue text-xs font-black uppercase tracking-widest mb-6">
<FlaskConical className="w-3.5 h-3.5" /> <FlaskConical className="w-4 h-4" />
<span>علم در خدمت کیفیت</span> علم در خدمت کیفیت
</div> </div>
<h1 className="text-2xl sm:text-4xl lg:text-5xl font-black text-medical-gray-900 leading-tight md:max-w-4xl font-lalezar tracking-wide"> <h2 className="text-4xl lg:text-6xl font-black text-medical-gray-900 leading-tight md:max-w-4xl">
دانشنامه مواد <span className="text-canina-blue italic">نایاب و ارگانیک</span> کنینا دانشنامه مواد <span className="text-canina-blue italic">نایاب و ارگانیک</span> کنینا
</h1> </h2>
<p className="mt-2 sm:mt-4 text-xs sm:text-base text-medical-gray-500 max-w-2xl leading-relaxed"> <p className="mt-6 text-lg text-medical-gray-500 max-w-2xl leading-relaxed">
تمامی ترکیبات فعال و مکمل‌های به کار رفته در محصولات دارویی و مراقبتی Canina Pharma آلمان، دارای بالاترین گرید بیولوژیک و فارماکوپه اروپا می‌باشند. تمامی ترکیبات فعال و مکمل‌های به کار رفته در محصولات دارویی و مراقبتی Canina Pharma آلمان، دارای بالاترین گرید بیولوژیک و فارماکوپه اروپا می‌باشند.
</p> </p>
<div className="relative w-full max-w-md mt-4 sm:mt-6"> <div className="relative w-full max-w-md mt-8">
<Search className="absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" /> <Search className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-medical-gray-400" />
<input <input
type="text" type="text"
placeholder="جستجوی ماده مؤثره (مثلاً: صدف لب‌سبز، آغوز، بیوتین)..." placeholder="جستجوی ماده مؤثره (مثلاً: صدف لب‌سبز، آغوز، بیوتین)..."
value={searchQuery} value={searchQuery}
onChange={(e) => { onChange={(e) => setSearchQuery(e.target.value)}
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"
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"
/> />
</div> </div>
{/* Sugar-Free & Gluten-Free Medical Standards Banner */} {/* Sugar-Free & Gluten-Free Medical Standards Banner */}
<div className="mt-3 sm:mt-6 flex flex-wrap items-center justify-center gap-2"> <div className="mt-8 flex flex-wrap items-center justify-center gap-3">
<div className="px-3 py-1.5 sm:px-4 sm:py-2 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-xl sm:rounded-2xl text-[10px] sm:text-xs font-black flex items-center gap-1.5 shadow-2xs"> <div className="px-4 py-2 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-2xl text-xs font-black flex items-center gap-1.5 shadow-xs">
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" /> <CheckCircle2 className="w-4 h-4 text-emerald-600" />
<span>۱۰۰٪ فاقد قند افزوده (Sugar-Free)</span> <span>۱۰۰٪ فاقد قند افزوده (Sugar-Free)</span>
</div> </div>
<div className="px-3 py-1.5 sm:px-4 sm:py-2 bg-blue-50 border border-blue-200 text-blue-800 rounded-xl sm:rounded-2xl text-[10px] sm:text-xs font-black flex items-center gap-1.5 shadow-2xs"> <div className="px-4 py-2 bg-blue-50 border border-blue-200 text-blue-800 rounded-2xl text-xs font-black flex items-center gap-1.5 shadow-xs">
<CheckCircle2 className="w-3.5 h-3.5 text-blue-600" /> <CheckCircle2 className="w-4 h-4 text-blue-600" />
<span>مطابق استانداردهای دارویی و بالینی آلمان</span> <span>مطابق استانداردهای دارویی و بالینی آلمان</span>
</div> </div>
</div> </div>
@@ -237,61 +218,18 @@ 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 ( return (
<> <div className="space-y-24">
<div className="space-y-5 sm:space-y-12"> {filtered.map((ing, idx) => {
{visibleIngredients.map((ing, idx) => {
const hasIngredient = getProductsForIngredient(ing.id, ing.name); const hasIngredient = getProductsForIngredient(ing.id, ing.name);
const isTargeted = termParam === ing.id; 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 ( return (
<div <div
key={ing.id} key={ing.id}
id={`wiki-${ing.id}`} id={`wiki-${ing.id}`}
className={`p-3 sm:p-5 lg:p-6 rounded-2xl sm:rounded-[2.5rem] transition-all duration-300 border border-medical-gray-200/80 shadow-xs hover:shadow-lg ${isTargeted ? 'bg-canina-blue/5 border-2 border-canina-blue ring-4 ring-canina-blue/10 shadow-xl' : 'bg-white'}`} className={`flex flex-col lg:flex-row items-stretch gap-12 p-8 sm:p-12 rounded-[3.5rem] transition-all duration-500 border border-medical-gray-100 shadow-sm hover:shadow-xl ${isTargeted ? 'bg-canina-blue/5 border-2 border-canina-blue ring-4 ring-canina-blue/10 shadow-2xl' : 'bg-white'} ${idx % 2 === 1 ? 'lg:flex-row-reverse' : ''}`}
> >
<h3>
<button
type="button"
id={triggerId}
aria-expanded={isExpanded}
aria-controls={panelId}
onClick={() => setExpandedIngredients(current => {
const next = new Set(current);
if (next.has(ing.id)) next.delete(ing.id); else next.add(ing.id);
return next;
})}
className="w-full min-h-[48px] flex items-center gap-3 text-right rounded-xl p-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-canina-blue focus-visible:ring-offset-2 cursor-pointer"
>
<span className="w-10 h-10 sm:w-12 sm:h-12 rounded-xl sm:rounded-2xl bg-medical-gray-900 flex items-center justify-center text-white shadow-md shrink-0">
<Beaker className="w-6 h-6 text-canina-gold" />
</span>
<span className="min-w-0 flex-1">
<span className="block text-base sm:text-2xl font-black text-medical-gray-900 leading-tight font-vazir">{ing.name}</span>
<span data-testid="wiki-ingredient-code" className="text-[10px] sm:text-[12px] text-canina-blue font-bold tracking-normal sm:tracking-wider font-vazir inline-block max-w-full mt-1 bg-canina-blue/5 px-2 py-0.5 rounded-lg border border-canina-blue/10 break-all">کد ماده مؤثره: <span className="font-mono">{ing.id}</span></span>
</span>
<span className="shrink-0 flex items-center gap-1.5 text-[11px] sm:text-xs font-black text-canina-blue">
<span>{isExpanded ? 'بستن جزئیات' : 'نمایش جزئیات'}</span>
<ChevronDown aria-hidden="true" className={`w-4 h-4 transition-transform motion-reduce:transition-none ${isExpanded ? 'rotate-180' : ''}`} />
</span>
</button>
</h3>
<div
id={panelId}
role="region"
aria-labelledby={triggerId}
hidden={!isExpanded}
className={`mt-4 flex flex-col lg:flex-row items-stretch gap-5 sm:gap-10 ${idx % 2 === 1 ? 'lg:flex-row-reverse' : ''}`}
>
{/* Content */} {/* Content */}
<div className="lg:w-1/2 flex flex-col justify-between space-y-6"> <div className="lg:w-1/2 flex flex-col justify-between space-y-6">
<motion.div <motion.div
@@ -300,13 +238,23 @@ export default function IngredientWiki() {
viewport={{ once: true }} viewport={{ once: true }}
transition={{ duration: 0.6 }} transition={{ duration: 0.6 }}
> >
<p className="text-xs sm:text-sm text-medical-gray-600 leading-relaxed mb-3 sm:mb-4 font-vazir"> <div className="flex items-center gap-4 mb-6">
<div className="w-14 h-14 rounded-3xl bg-medical-gray-900 flex items-center justify-center text-white shadow-xl shrink-0">
<Beaker className="w-6 h-6 text-canina-gold" />
</div>
<div>
<h3 className="text-2xl sm:text-3xl font-black text-medical-gray-900 leading-tight font-vazir">{ing.name}</h3>
<span className="text-[12px] text-canina-blue font-bold tracking-wider font-vazir inline-block mt-1 bg-canina-blue/5 px-2.5 py-0.5 rounded-lg border border-canina-blue/10">کد ماده مؤثره: <span className="font-mono">{ing.id}</span></span>
</div>
</div>
<p className="text-base text-medical-gray-600 leading-relaxed mb-6 font-vazir">
{ing.description} {ing.description}
</p> </p>
<div className="grid grid-cols-1 gap-2 mb-3 sm:mb-4"> <div className="grid grid-cols-1 gap-3 mb-6">
{ing.benefits.map((benefit, bIdx) => ( {ing.benefits.map((benefit, bIdx) => (
<div key={bIdx} className="flex items-start gap-2.5 p-2.5 sm:p-3 bg-medical-gray-50/80 rounded-xl sm:rounded-2xl border border-medical-gray-100"> <div key={bIdx} className="flex items-start gap-3 p-3.5 bg-medical-gray-50/80 rounded-2xl border border-medical-gray-100">
<CheckCircle2 className="w-5 h-5 text-canina-blue shrink-0 mt-0.5" /> <CheckCircle2 className="w-5 h-5 text-canina-blue shrink-0 mt-0.5" />
<span className="text-xs sm:text-sm font-bold text-medical-gray-700 leading-relaxed font-vazir">{benefit}</span> <span className="text-xs sm:text-sm font-bold text-medical-gray-700 leading-relaxed font-vazir">{benefit}</span>
</div> </div>
@@ -317,14 +265,14 @@ export default function IngredientWiki() {
{/* Products Linking */} {/* Products Linking */}
<div className="lg:w-1/2 relative flex"> <div className="lg:w-1/2 relative flex">
<motion.div <motion.div
initial={{ opacity: 0, scale: 0.95 }} initial={{ opacity: 0, scale: 0.95 }}
whileInView={{ opacity: 1, scale: 1 }} whileInView={{ opacity: 1, scale: 1 }}
viewport={{ once: true }} viewport={{ once: true }}
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" 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"
> >
<div> <div>
<div className="flex items-center justify-between mb-3 pb-2.5 border-b border-medical-gray-200/60"> <div className="flex items-center justify-between mb-6 pb-4 border-b border-medical-gray-200/60">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="w-2.5 h-2.5 rounded-full bg-canina-blue animate-pulse" /> <span className="w-2.5 h-2.5 rounded-full bg-canina-blue animate-pulse" />
<h4 className="text-xs sm:text-sm font-black text-medical-gray-900 font-vazir">موجود در محصولات کاتالوگ</h4> <h4 className="text-xs sm:text-sm font-black text-medical-gray-900 font-vazir">موجود در محصولات کاتالوگ</h4>
@@ -336,29 +284,26 @@ export default function IngredientWiki() {
{hasIngredient.length} محصول {hasIngredient.length} محصول
</Link> </Link>
</div> </div>
<div data-testid="wiki-related-products-grid" <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 relative z-10">
className="grid grid-cols-2 gap-2 sm:gap-4 relative z-10">
{hasIngredient.length > 0 ? hasIngredient.slice(0, 4).map(p => ( {hasIngredient.length > 0 ? hasIngredient.slice(0, 4).map(p => (
<Link <Link
key={p.id} key={p.id}
href={`/shop/${p.slug || p.id}`} href={`/shop/${p.slug || p.id}`}
data-testid="wiki-related-product-card" className="bg-white rounded-[2rem] p-4 shadow-sm border border-medical-gray-200 hover:border-canina-blue hover:shadow-lg hover:scale-[1.02] transition-all cursor-pointer group flex flex-col justify-between"
className="bg-white rounded-xl sm:rounded-[2rem] p-2 sm:p-4 shadow-sm border border-medical-gray-200 hover:border-canina-blue hover:shadow-lg hover:scale-[1.02] transition-all cursor-pointer group flex flex-col justify-between min-w-0"
> >
<div data-testid="wiki-related-product-image" <div className="aspect-square bg-medical-gray-50 rounded-2xl p-3 mb-3 flex items-center justify-center relative overflow-hidden">
className="h-20 sm:h-auto sm:aspect-square bg-medical-gray-50 rounded-lg sm:rounded-2xl p-1.5 sm:p-3 mb-1.5 sm:mb-3 flex items-center justify-center relative overflow-hidden"> <Image
<Image src={p.image || '/assets/images/canina-product-placeholder.png'}
src={p.image || '/assets/images/canina-product-placeholder.png'} alt={p.name}
alt={p.name} width={96}
width={96} height={96}
height={96} className="max-h-20 w-auto object-contain group-hover:scale-110 transition-transform duration-300"
className="max-h-16 sm:max-h-20 w-auto object-contain group-hover:scale-110 transition-transform duration-300" unoptimized
unoptimized
onError={(e: any) => { e.currentTarget.src = '/assets/images/canina-product-placeholder.png'; }} onError={(e: any) => { e.currentTarget.src = '/assets/images/canina-product-placeholder.png'; }}
/> />
</div> </div>
<h4 className="text-[10px] sm:text-xs font-black text-center text-medical-gray-900 group-hover:text-canina-blue transition-colors px-0.5 sm:px-1 leading-snug font-vazir line-clamp-2">{p.name}</h4> <h4 className="text-xs font-black text-center text-medical-gray-900 group-hover:text-canina-blue transition-colors px-1 leading-snug font-vazir line-clamp-2">{p.name}</h4>
</Link> </Link>
)) : ( )) : (
<div className="col-span-full py-8 text-center"> <div className="col-span-full py-8 text-center">
@@ -376,7 +321,7 @@ export default function IngredientWiki() {
{hasIngredient.length > 4 && ( {hasIngredient.length > 4 && (
<div className="mt-4 pt-3 border-t border-medical-gray-200/50 text-center"> <div className="mt-4 pt-3 border-t border-medical-gray-200/50 text-center">
<Link <Link
href={`/shop?search=${encodeURIComponent(ing.name.replace(/\s*\([^)]*\)\s*/g, '').trim())}`} href={`/shop?search=${encodeURIComponent(ing.name.replace(/\s*\([^)]*\)\s*/g, '').trim())}`}
className="text-xs font-black text-canina-blue hover:text-medical-gray-900 transition-colors font-vazir inline-flex items-center gap-1.5" className="text-xs font-black text-canina-blue hover:text-medical-gray-900 transition-colors font-vazir inline-flex items-center gap-1.5"
> >
@@ -385,33 +330,15 @@ export default function IngredientWiki() {
</Link> </Link>
</div> </div>
)} )}
{/* Decorative backdrop */} {/* Decorative backdrop */}
<div className="absolute -bottom-20 -left-20 w-80 h-80 bg-canina-blue rounded-full blur-[100px] opacity-10 pointer-events-none" /> <div className="absolute -bottom-20 -left-20 w-80 h-80 bg-canina-blue rounded-full blur-[100px] opacity-10 pointer-events-none" />
</motion.div> </motion.div>
</div> </div>
</div>
</div> </div>
); );
})} })}
</div> </div>
{remainingCount > 0 && (
<div className="mt-7 sm:mt-10 flex flex-col items-center gap-2">
<button
type="button"
onClick={() => setVisibleCount(count => count + 8)}
className="inline-flex items-center justify-center px-6 py-3 rounded-2xl bg-white border border-medical-gray-200 text-canina-blue text-xs sm:text-sm font-black shadow-xs hover:border-canina-blue hover:shadow-md active:scale-95 transition-all cursor-pointer"
aria-label={`مشاهده ${nextCount.toLocaleString('fa-IR')} ماده بیشتر`}
>
مشاهده {nextCount.toLocaleString('fa-IR')} ماده بیشتر
</button>
<span className="text-[11px] font-bold text-medical-gray-400">
نمایش {Math.min(visibleCount, filtered.length).toLocaleString('fa-IR')} از {filtered.length.toLocaleString('fa-IR')} ماده
</span>
</div>
)}
</>
); );
})()} })()}
</div> </div>
@@ -14,9 +14,8 @@ export default function MaintenancePage() {
); );
const badge = getText("maintenance_badge", "سامانه در حال به‌روزرسانی و ارتقا"); const badge = getText("maintenance_badge", "سامانه در حال به‌روزرسانی و ارتقا");
const eta = getText("maintenance_eta", "زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده"); const eta = getText("maintenance_eta", "زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده");
const phone = getText("contact_phone", "").trim(); const phone = getText("contact_phone", "");
const configuredPhoneLink = getText("contact_phone_link", "").trim(); const phoneLink = getText("contact_phone_link", "");
const phoneLink = configuredPhoneLink || (phone ? `tel:${phone.replace(/[^0-9+]/g, "")}` : "");
return ( return (
<div className="min-h-screen bg-medical-gray-900 text-white flex flex-col items-center justify-center p-6 text-center font-vazir relative overflow-hidden" dir="rtl"> <div className="min-h-screen bg-medical-gray-900 text-white flex flex-col items-center justify-center p-6 text-center font-vazir relative overflow-hidden" dir="rtl">
@@ -53,17 +52,15 @@ export default function MaintenancePage() {
</div> </div>
)} )}
{phone && phoneLink && ( <div className="pt-2 flex flex-col sm:flex-row items-center justify-center gap-4">
<div className="pt-2 flex flex-col sm:flex-row items-center justify-center gap-4"> <a
<a href={phoneLink}
href={phoneLink}
className="w-full sm:w-auto px-6 py-3.5 bg-canina-blue hover:bg-canina-dark text-white font-black text-xs rounded-xl flex items-center justify-center gap-2 shadow-lg transition-all" className="w-full sm:w-auto px-6 py-3.5 bg-canina-blue hover:bg-canina-dark text-white font-black text-xs rounded-xl flex items-center justify-center gap-2 shadow-lg transition-all"
> >
<Phone className="w-4 h-4" /> <Phone className="w-4 h-4" />
<span>پشتیبانی اضطراری: {phone}</span> <span>پشتیبانی اضطراری: {phone}</span>
</a> </a>
</div> </div>
)}
</div> </div>
<div className="absolute bottom-6 text-xs text-medical-gray-500 font-bold flex items-center gap-2"> <div className="absolute bottom-6 text-xs text-medical-gray-500 font-bold flex items-center gap-2">
@@ -168,7 +168,7 @@ export default function MobileBottomNav({
if (searchQuery.trim()) { if (searchQuery.trim()) {
const q = searchQuery.trim(); const q = searchQuery.trim();
closeSheet(false); closeSheet(false);
router.push(`/search?q=${encodeURIComponent(q)}`); router.push(`/shop?search=${encodeURIComponent(q)}`);
} else { } else {
closeSheet(false); closeSheet(false);
router.push("/shop"); router.push("/shop");
@@ -183,8 +183,10 @@ export default function MobileBottomNav({
} }
}; };
// Retain MobileBottomNav across all routes including PDP so user never loses Menu & Home navigation const isProductDetailPage = pathname.startsWith("/shop/") && pathname !== "/shop";
const isProductDetailPage = false; if (isProductDetailPage) {
return null;
}
const totalCartItems = isMounted ? getTotalItems() : 0; const totalCartItems = isMounted ? getTotalItems() : 0;
const isHomeActive = pathname === "/"; const isHomeActive = pathname === "/";
@@ -236,6 +238,7 @@ export default function MobileBottomNav({
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2.5 pr-10 pl-14 text-xs outline-none focus:border-canina-blue font-vazir text-medical-gray-900" className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2.5 pr-10 pl-14 text-xs outline-none focus:border-canina-blue font-vazir text-medical-gray-900"
autoFocus
/> />
<button <button
type="submit" type="submit"
@@ -405,22 +408,6 @@ export default function MobileBottomNav({
<div className="overflow-y-auto flex-1 space-y-3 py-1"> <div className="overflow-y-auto flex-1 space-y-3 py-1">
{/* Navigation Links Grid */} {/* Navigation Links Grid */}
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
<button
type="button"
onClick={() => navigateAndClose("/search")}
className="col-span-2 flex items-center justify-between p-3.5 bg-gradient-to-r from-canina-blue/10 via-white to-canina-blue/5 border border-canina-blue/30 rounded-2xl text-xs font-black text-canina-blue hover:border-canina-blue text-right shadow-xs"
>
<div className="flex items-center gap-2.5">
<div className="w-8 h-8 rounded-xl bg-canina-blue text-white flex items-center justify-center shadow-xs">
<Search className="w-4 h-4" />
</div>
<div>
<div className="text-xs font-black text-medical-gray-900">جستجوی پیشرفته و هوشمند</div>
<div className="text-[10px] text-medical-gray-400 font-medium">جستجو در داروها، مکمل‌ها و علائم بالینی</div>
</div>
</div>
<ChevronLeft className="w-4 h-4 text-canina-blue" />
</button>
<button <button
type="button" type="button"
onClick={() => navigateAndClose("/dashboard?tab=pets")} onClick={() => navigateAndClose("/dashboard?tab=pets")}
@@ -479,20 +466,6 @@ export default function MobileBottomNav({
<span>خرید عمده (B2B)</span> <span>خرید عمده (B2B)</span>
</button> </button>
)} )}
{isPrescriptionEnabled && (
<button
type="button"
onClick={() => {
closeSheet();
useUIStore.getState().setPrescriptionModalOpen(true);
}}
className="flex items-center gap-2.5 p-3.5 bg-emerald-50 border border-emerald-200 rounded-2xl text-xs font-black text-emerald-800 hover:border-emerald-500 text-right shadow-xs"
>
<FileHeart className="w-4 h-4 text-emerald-600 shrink-0" />
<span>ثبت نسخه آنلاین</span>
</button>
)}
</div> </div>
{/* Contact & Support */} {/* Contact & Support */}
@@ -517,7 +490,7 @@ export default function MobileBottomNav({
{/* 3. FIXED 5-TAB APP BOTTOM NAVIGATION BAR */} {/* 3. FIXED 5-TAB APP BOTTOM NAVIGATION BAR */}
<nav <nav
aria-label="منوی ناوبری موبایل" aria-label="منوی ناوبری موبایل"
className="lg:hidden fixed bottom-0 left-0 right-0 z-40 bg-white/95 backdrop-blur-md border-t border-medical-gray-200 shadow-[0_-4px_20px_rgba(0,0,0,0.06)] font-vazir pb-[env(safe-area-inset-bottom,0px)]" className="lg:hidden fixed bottom-0 inset-x-0 z-40 bg-white/95 backdrop-blur-md border-t border-medical-gray-200 shadow-[0_-4px_20px_rgba(0,0,0,0.06)] font-vazir"
dir="rtl" dir="rtl"
> >
<div className="max-w-md mx-auto px-2 h-16 flex items-center justify-between select-none"> <div className="max-w-md mx-auto px-2 h-16 flex items-center justify-between select-none">
@@ -525,7 +498,7 @@ export default function MobileBottomNav({
{/* Tab 1: Home */} {/* Tab 1: Home */}
<Link <Link
href="/" href="/"
className={`flex flex-col items-center justify-center flex-1 min-h-[48px] py-1 transition-all ${ className={`flex flex-col items-center justify-center flex-1 py-1 transition-all ${
isHomeActive ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700" isHomeActive ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700"
}`} }`}
> >
@@ -540,7 +513,7 @@ export default function MobileBottomNav({
if (activeSheet === "menu") closeSheet(); if (activeSheet === "menu") closeSheet();
else openSheet("menu"); else openSheet("menu");
}} }}
className={`flex flex-col items-center justify-center flex-1 min-h-[48px] py-1 transition-all ${ className={`flex flex-col items-center justify-center flex-1 py-1 transition-all ${
activeSheet === "menu" ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700" activeSheet === "menu" ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700"
}`} }`}
> >
@@ -555,7 +528,7 @@ export default function MobileBottomNav({
if (activeSheet === "shop") closeSheet(); if (activeSheet === "shop") closeSheet();
else openSheet("shop"); else openSheet("shop");
}} }}
className={`flex flex-col items-center justify-center flex-1 min-h-[48px] py-1 transition-all ${ className={`flex flex-col items-center justify-center flex-1 py-1 transition-all ${
isShopActive ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700" isShopActive ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700"
}`} }`}
> >
@@ -570,7 +543,7 @@ export default function MobileBottomNav({
<button <button
type="button" type="button"
onClick={() => setCartOpen(true)} onClick={() => setCartOpen(true)}
className="flex flex-col items-center justify-center flex-1 min-h-[48px] py-1 text-medical-gray-400 font-bold hover:text-medical-gray-700 relative" className="flex flex-col items-center justify-center flex-1 py-1 text-medical-gray-400 font-bold hover:text-medical-gray-700 relative"
> >
<div className="relative mb-1"> <div className="relative mb-1">
<ShoppingCart className="w-5 h-5" /> <ShoppingCart className="w-5 h-5" />
@@ -588,7 +561,7 @@ export default function MobileBottomNav({
<button <button
type="button" type="button"
onClick={handleAccountClick} onClick={handleAccountClick}
className={`flex flex-col items-center justify-center flex-1 min-h-[48px] py-1 transition-all ${ className={`flex flex-col items-center justify-center flex-1 py-1 transition-all ${
isAccountActive ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700" isAccountActive ? "text-canina-blue font-black" : "text-medical-gray-400 font-bold hover:text-medical-gray-700"
}`} }`}
> >
@@ -40,7 +40,7 @@ export default function OrderSuccess({ orderId }: { orderId: string }) {
<CheckCircle2 className="w-12 h-12" /> <CheckCircle2 className="w-12 h-12" />
</div> </div>
<h1 className="text-4xl font-black text-medical-gray-900 italic mb-4">سفارش شما با موفقیت ثبت شد!</h1> <h2 className="text-4xl font-black text-medical-gray-900 italic mb-4">سفارش شما با موفقیت ثبت شد!</h2>
<p className="text-medical-gray-500 font-bold mb-10">شماره سفارش: <span className="text-canina-blue font-mono">{order.id}</span></p> <p className="text-medical-gray-500 font-bold mb-10">شماره سفارش: <span className="text-canina-blue font-mono">{order.id}</span></p>
{/* Empathetic Message */} {/* Empathetic Message */}
@@ -68,7 +68,7 @@ export default function OrderTracking() {
</div> </div>
<div className="flex items-center justify-between mb-12"> <div className="flex items-center justify-between mb-12">
<h1 className="text-3xl font-black text-medical-gray-900 italic">وضعیت لحظه‌ای سفارش</h1> <h2 className="text-3xl font-black text-medical-gray-900 italic">وضعیت لحظه‌ای سفارش</h2>
</div> </div>
{/* Search Bar */} {/* Search Bar */}
+44 -53
View File
@@ -1,6 +1,5 @@
"use client";
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { sanitizeBlogHtml } from "../lib/sanitizeBlogHtml"; "use client";
import Link from "next/link"; import Link from "next/link";
import { useState, useMemo, useEffect, useRef } from "react"; import { useState, useMemo, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "motion/react"; import { motion, AnimatePresence } from "motion/react";
@@ -127,17 +126,11 @@ function isVideoUrl(url?: string): boolean {
); );
} }
export default function ProductPage({ export default function ProductPage({ productSlug }: { productSlug: string }) {
productSlug,
initialProduct,
}: {
productSlug: string;
initialProduct?: Product | null;
}) {
const router = useRouter(); const router = useRouter();
const [product, setProduct] = useState<Product | null>(initialProduct ?? null); const [product, setProduct] = useState<Product | null>(null);
const [allProducts, setAllProducts] = useState<Product[]>([]); const [allProducts, setAllProducts] = useState<Product[]>([]);
const [isLoading, setIsLoading] = useState(!initialProduct); const [isLoading, setIsLoading] = useState(true);
const [itemQuantity, setItemQuantity] = useState(1); const [itemQuantity, setItemQuantity] = useState(1);
const [showRefillModal, setShowRefillModal] = useState(false); const [showRefillModal, setShowRefillModal] = useState(false);
const [isMounted, setIsMounted] = useState(false); const [isMounted, setIsMounted] = useState(false);
@@ -174,28 +167,18 @@ export default function ProductPage({
}, []); }, []);
useEffect(() => { useEffect(() => {
const loadRelatedProducts = () => productService.getProducts({ limit: 50 })
.then(res => {
if (res && res.data) setAllProducts(res.data);
});
if (initialProduct) {
if (initialProduct.image) setActiveImage(initialProduct.image);
loadRelatedProducts()
.catch(err => console.error("Error fetching related products in ProductPage:", err))
.finally(() => setIsLoading(false));
return;
}
productService.getProductBySlug(productSlug) productService.getProductBySlug(productSlug)
.then(p => { .then(p => {
setProduct(p); setProduct(p);
if (p?.image) setActiveImage(p.image); if (p?.image) setActiveImage(p.image);
return loadRelatedProducts(); return productService.getProducts({ limit: 50 });
})
.then(res => {
if (res && res.data) setAllProducts(res.data);
}) })
.catch(err => console.error("Error fetching products in ProductPage:", err)) .catch(err => console.error("Error fetching products in ProductPage:", err))
.finally(() => setIsLoading(false)); .finally(() => setIsLoading(false));
}, [productSlug, initialProduct]); }, [productSlug]);
useEffect(() => { useEffect(() => {
if (product && product.id) { if (product && product.id) {
@@ -499,7 +482,27 @@ export default function ProductPage({
}} }}
className="bg-white rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200 shadow-xl relative group overflow-hidden h-[280px] sm:h-[390px] flex items-center justify-center p-2 sm:p-4 select-none touch-pan-y cursor-grab active:cursor-grabbing" className="bg-white rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200 shadow-xl relative group overflow-hidden h-[280px] sm:h-[390px] flex items-center justify-center p-2 sm:p-4 select-none touch-pan-y cursor-grab active:cursor-grabbing"
> >
{/* Floating Badges over photo removed to prevent blocking product visual */} {/* Top Floating Badges */}
<div className="absolute top-4 left-4 sm:top-6 sm:left-6 flex flex-col gap-1.5 sm:gap-2 z-10 items-start pointer-events-none">
{product.specialBadge && (
<div className="px-2.5 py-1 bg-medical-gray-900 text-white rounded-full text-[9px] sm:text-[10px] font-black uppercase tracking-widest font-vazir whitespace-nowrap shadow-sm">
{product.specialBadge}
</div>
)}
{isOutOfStock ? (
<div className="px-2.5 py-1 bg-rose-500 text-white rounded-full text-[9px] sm:text-[10px] font-black uppercase tracking-widest flex items-center gap-1 font-vazir shadow-sm">
ناموجود در انبار
</div>
) : (
<div className="px-2.5 py-1 bg-green-500 text-white rounded-full text-[9px] sm:text-[10px] font-black uppercase tracking-widest flex items-center gap-1 font-vazir shadow-sm">
<CheckCircle2 className="w-3 h-3" />
موجود در انبار
</div>
)}
<div className="px-2.5 py-1 bg-canina-blue text-white rounded-full text-[9px] sm:text-[10px] font-black uppercase tracking-widest font-vazir whitespace-nowrap shadow-sm">
گرید دارویی اختصاصی
</div>
</div>
{/* Species Suitable Badges (Dog / Cat) */} {/* Species Suitable Badges (Dog / Cat) */}
<div className="absolute bottom-4 left-4 flex gap-1.5 z-10 pointer-events-none"> <div className="absolute bottom-4 left-4 flex gap-1.5 z-10 pointer-events-none">
@@ -676,27 +679,15 @@ export default function ProductPage({
<div className="md:col-span-7 space-y-4 sm:space-y-6 flex flex-col items-center md:items-start"> <div className="md:col-span-7 space-y-4 sm:space-y-6 flex flex-col items-center md:items-start">
<div className="w-full flex flex-col items-center md:items-start"> <div className="w-full flex flex-col items-center md:items-start">
<div className="flex flex-wrap justify-center md:justify-start items-center gap-2 sm:gap-3 mb-3 sm:mb-4"> <div className="flex flex-wrap justify-center md:justify-start items-center gap-2 sm:gap-3 mb-3 sm:mb-4">
{/* 1. First Priority: Stock Status */} <div className="px-3 py-1 bg-canina-blue text-white rounded-full text-[10px] font-black uppercase tracking-widest font-vazir whitespace-nowrap shadow-sm">
{isOutOfStock ? ( استاندارد صنعتی آلمان
<div className="px-3 py-1 bg-rose-50 text-rose-700 border border-rose-200 rounded-full text-[10px] font-black uppercase tracking-widest flex items-center gap-1 font-vazir shadow-xs"> </div>
<span className="w-2 h-2 rounded-full bg-rose-500" /> <div className="px-3 py-1 bg-amber-500 text-white rounded-full text-[10px] font-black uppercase tracking-widest font-vazir whitespace-nowrap shadow-sm flex items-center gap-1">
ناموجود در انبار مرکزی <ShieldCheck className="w-3 h-3" />
</div> کاتالوگ رسمی Canina
) : (
<div className="px-3 py-1 bg-emerald-50 text-emerald-800 border border-emerald-200 rounded-full text-[10px] font-black uppercase tracking-widest flex items-center gap-1 font-vazir shadow-xs">
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
موجود در انبار مرکزی
</div>
)}
{/* 2. Pharmaceutical Grade */}
<div className="px-3 py-1 bg-canina-blue/10 text-canina-blue border border-canina-blue/20 rounded-full text-[10px] font-black uppercase tracking-widest font-vazir whitespace-nowrap shadow-xs">
گرید دارویی اختصاصی Canina
</div> </div>
{/* 3. Special Badge if exists */}
{product.specialBadge && ( {product.specialBadge && (
<div className="px-3 py-1 bg-amber-50 text-amber-900 border border-amber-200 rounded-full text-[10px] font-black uppercase tracking-widest font-vazir shadow-xs max-w-full text-right" title={product.specialBadge}> <div className="px-3 py-1 bg-medical-gray-900 text-white rounded-full text-[10px] font-black uppercase tracking-widest font-vazir whitespace-nowrap shadow-sm">
{product.specialBadge} {product.specialBadge}
</div> </div>
)} )}
@@ -738,9 +729,9 @@ export default function ProductPage({
</h2> </h2>
)} )}
{product.scientificTagline && ( {product.scientificTagline && (
<div className="mt-1.5 text-xs sm:text-sm md:text-base text-canina-blue font-bold font-vazir flex items-start justify-center md:justify-start gap-2" dir="rtl"> <div className="mt-1 text-xs sm:text-sm md:text-base text-canina-blue font-bold font-vazir flex items-center justify-center md:justify-start gap-1.5" dir="rtl">
<span className="w-1.5 h-1.5 rounded-full bg-canina-blue shrink-0 mt-2" /> <span className="w-1.5 h-1.5 rounded-full bg-canina-blue shrink-0" />
<span className="leading-relaxed text-right">{product.scientificTagline}</span> <span>{product.scientificTagline}</span>
</div> </div>
)} )}
</div> </div>
@@ -881,7 +872,7 @@ export default function ProductPage({
}`} }`}
> >
<div <div
dangerouslySetInnerHTML={{ __html: sanitizeBlogHtml(formattedHtml) }} dangerouslySetInnerHTML={{ __html: formattedHtml }}
className="rich-product-description space-y-3 font-vazir text-justify leading-relaxed sm:leading-loose [&>h1]:text-lg [&>h1]:sm:text-xl [&>h1]:font-black [&>h1]:text-medical-gray-900 [&>h1]:mt-4 [&>h1]:mb-2 [&>h2]:text-base [&>h2]:sm:text-lg [&>h2]:font-black [&>h2]:text-medical-gray-900 [&>h2]:mt-3 [&>h2]:mb-1.5 [&>h3]:text-sm [&>h3]:sm:text-base [&>h3]:font-black [&>h3]:text-medical-gray-900 [&>h3]:mt-3 [&>h3]:mb-1 [&>h4]:text-xs [&>h4]:sm:text-sm [&>h4]:font-bold [&>h4]:text-medical-gray-800 [&>p]:leading-relaxed [&>p]:sm:leading-loose [&>ul]:list-disc [&>ul]:pr-5 [&>ul]:space-y-1 [&>ol]:list-decimal [&>ol]:pr-5 [&>ol]:space-y-1 [&>table]:w-full [&>table]:border-collapse [&>table]:my-3 [&>table_th]:border [&>table_th]:border-medical-gray-200 [&>table_th]:p-2 [&>table_th]:bg-medical-gray-100 [&>table_td]:border [&>table_td]:border-medical-gray-200 [&>table_td]:p-2 [&>hr]:my-4 [&>hr]:border-medical-gray-200 [&>blockquote]:border-r-4 [&>blockquote]:border-canina-blue [&>blockquote]:pr-3 [&>blockquote]:italic [&>blockquote]:bg-canina-blue/5 [&>blockquote]:p-2 [&>blockquote]:rounded-l-lg [&>img]:rounded-xl [&>img]:my-3 [&>img]:max-w-full [&>img]:shadow-sm" className="rich-product-description space-y-3 font-vazir text-justify leading-relaxed sm:leading-loose [&>h1]:text-lg [&>h1]:sm:text-xl [&>h1]:font-black [&>h1]:text-medical-gray-900 [&>h1]:mt-4 [&>h1]:mb-2 [&>h2]:text-base [&>h2]:sm:text-lg [&>h2]:font-black [&>h2]:text-medical-gray-900 [&>h2]:mt-3 [&>h2]:mb-1.5 [&>h3]:text-sm [&>h3]:sm:text-base [&>h3]:font-black [&>h3]:text-medical-gray-900 [&>h3]:mt-3 [&>h3]:mb-1 [&>h4]:text-xs [&>h4]:sm:text-sm [&>h4]:font-bold [&>h4]:text-medical-gray-800 [&>p]:leading-relaxed [&>p]:sm:leading-loose [&>ul]:list-disc [&>ul]:pr-5 [&>ul]:space-y-1 [&>ol]:list-decimal [&>ol]:pr-5 [&>ol]:space-y-1 [&>table]:w-full [&>table]:border-collapse [&>table]:my-3 [&>table_th]:border [&>table_th]:border-medical-gray-200 [&>table_th]:p-2 [&>table_th]:bg-medical-gray-100 [&>table_td]:border [&>table_td]:border-medical-gray-200 [&>table_td]:p-2 [&>hr]:my-4 [&>hr]:border-medical-gray-200 [&>blockquote]:border-r-4 [&>blockquote]:border-canina-blue [&>blockquote]:pr-3 [&>blockquote]:italic [&>blockquote]:bg-canina-blue/5 [&>blockquote]:p-2 [&>blockquote]:rounded-l-lg [&>img]:rounded-xl [&>img]:my-3 [&>img]:max-w-full [&>img]:shadow-sm"
/> />
@@ -1053,7 +1044,7 @@ export default function ProductPage({
<span className="text-xs sm:text-sm font-bold text-medical-gray-700 font-vazir"> <span className="text-xs sm:text-sm font-bold text-medical-gray-700 font-vazir">
{cardSlug ? ( {cardSlug ? (
<Link <Link
href={`/wiki?term=${cardSlug}`} href={`/wiki/${cardSlug}`}
className="hover:text-canina-blue hover:underline transition-colors flex items-center gap-1" className="hover:text-canina-blue hover:underline transition-colors flex items-center gap-1"
title="مشاهده در دانشنامه علمی کنینا" title="مشاهده در دانشنامه علمی کنینا"
> >
@@ -1599,8 +1590,8 @@ export default function ProductPage({
)} )}
</AnimatePresence> </AnimatePresence>
{/* Mobile Floating Sticky Bottom Buy Bar - Docked cleanly ABOVE MobileBottomNav */} {/* Mobile Floating Sticky Bottom Buy Bar */}
<div className="lg:hidden fixed bottom-[65px] left-0 right-0 z-30 bg-white/95 backdrop-blur-md border-t border-medical-gray-200 px-3 py-2.5 shadow-[0_-4px_16px_rgba(0,0,0,0.08)] flex items-center justify-between gap-3 font-vazir" dir="rtl"> <div className="lg:hidden fixed bottom-0 left-0 right-0 z-50 bg-white/95 backdrop-blur-md border-t border-medical-gray-200 p-3 pb-safe shadow-2xl flex items-center justify-between gap-3 font-vazir" dir="rtl">
{!isCatalogHidePrices ? ( {!isCatalogHidePrices ? (
<div> <div>
<span className="text-[10px] text-medical-gray-400 font-bold block">قیمت نهایی</span> <span className="text-[10px] text-medical-gray-400 font-bold block">قیمت نهایی</span>
@@ -1,632 +1,148 @@
"use client"; "use client";
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useMemo } from "react"; import { Search, ChevronLeft, ArrowRight, Sparkles, Heart, AlertCircle } from "lucide-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 { usePetStore } from "../lib/store/usePetStore";
import { motion, AnimatePresence } from "motion/react"; import { motion } from "motion/react";
import { Product } from "../lib/data/products"; import { Product } from "../lib/data/products";
import { productService } from "../lib/services/productService"; import { productService } from "../lib/services/productService";
import Link from "next/link"; import Link from "next/link";
import Image from "next/image"; import Image from "next/image";
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import api from "../lib/services/api";
import { toPersian, normalizePersianText } 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 }) { export default function SearchResultsPage({ query }: { query: string }) {
const router = useRouter(); const router = useRouter();
const { getActivePet } = usePetStore(); const { getActivePet } = usePetStore();
const activePet = getActivePet(); const activePet = getActivePet();
const [activeTab, setActiveTab] = useState<SearchTab>("all");
const [searchInput, setSearchInput] = useState(query);
const [products, setProducts] = useState<Product[]>([]); const [products, setProducts] = useState<Product[]>([]);
const [blogs, setBlogs] = useState<BlogItem[]>([]);
const [wikiItems, setWikiItems] = useState<WikiItem[]>([]);
const [videos, setVideos] = useState<VideoItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchError, setSearchError] = useState<string | null>(null);
// Sync input when prop changes
useEffect(() => {
setSearchInput(query);
}, [query]);
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")
]);
// 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(() => { useEffect(() => {
loadAll(); productService.getProducts({ limit: 999 })
.then(res => setProducts(res.data))
.catch(err => console.error("Error fetching products in SearchResultsPage:", err));
}, []); }, []);
const cleanQuery = (query || "").trim().toLowerCase(); const results = products.filter(p =>
const normalizedQuery = normalizePersianText(query || ""); 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()))
);
// 1. Filtered Products
const filteredProducts = useMemo(() => {
if (!cleanQuery) return products;
return products.filter(p =>
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]);
// 2. Filtered Blogs
const filteredBlogs = useMemo(() => {
if (!cleanQuery) return blogs;
return blogs.filter(b =>
normalizePersianText(b.title || '').includes(normalizedQuery) ||
normalizePersianText(b.excerpt || '').includes(normalizedQuery)
);
}, [blogs, cleanQuery]);
// 3. Filtered Wiki Items
const filteredWiki = useMemo(() => {
if (!cleanQuery) return wikiItems;
return wikiItems.filter(w =>
normalizePersianText(w.name || '').includes(normalizedQuery) ||
normalizePersianText(w.nameFa || '').includes(normalizedQuery) ||
normalizePersianText(w.scientificName || '').includes(normalizedQuery) ||
normalizePersianText(w.description || '').includes(normalizedQuery)
);
}, [wikiItems, cleanQuery]);
// 4. Filtered Videos
const filteredVideos = useMemo(() => {
if (!cleanQuery) return videos;
return videos.filter(v =>
normalizePersianText(v.title || '').includes(normalizedQuery) ||
normalizePersianText(v.doctor || '').includes(normalizedQuery) ||
normalizePersianText(v.description || '').includes(normalizedQuery)
);
}, [videos, cleanQuery]);
const totalResults = filteredProducts.length + filteredBlogs.length + filteredWiki.length + filteredVideos.length;
const bestSellers = products.slice(0, 3); 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 ( return (
<div className="min-h-screen bg-medical-gray-50 pt-4 pb-24 sm:py-10 px-3 sm:px-6 font-vazir" dir="rtl"> <div className="min-h-screen bg-medical-gray-50 py-20 px-6 font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto"> <div className="max-w-7xl mx-auto">
<button onClick={() => router.back()} className="flex items-center gap-2 text-medical-gray-400 font-black mb-10 hover:text-canina-blue transition-colors">
<ArrowRight className="w-5 h-5 rotate-180" />
بازگشت
</button>
{/* Mobile-First Header Bar: Back Button & Compact Title */} <div className="flex flex-col md:flex-row md:items-end justify-between mb-16 gap-6">
<div className="flex items-center justify-between mb-4 pb-3 border-b border-medical-gray-200"> <div>
<div className="flex items-center gap-2"> <h1 className="text-4xl font-black text-medical-gray-900 italic mb-4">
<button نتایج جستجو برای: <span className="text-canina-blue">&quot;{query}&quot;</span>
type="button" </h1>
onClick={() => router.back()} <p className="text-medical-gray-500 font-medium">
className="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-medical-gray-200 rounded-xl text-xs font-bold text-medical-gray-600 hover:text-canina-blue hover:border-canina-blue transition-colors shadow-2xs cursor-pointer" {results.length} محصول با معیارهای شما مطابقت دارد.
> </p>
<ArrowRight className="w-3.5 h-3.5 rotate-180" />
<span>بازگشت</span>
</button>
<span className="text-xs text-medical-gray-400 font-bold hidden sm:inline">جستجوی جامع کنینا</span>
</div> </div>
{cleanQuery && (
<span className="text-[11px] font-black text-canina-blue bg-canina-blue/10 px-2.5 py-1 rounded-full border border-canina-blue/20">
{toPersian(totalResults)} نتیجه
</span>
)}
</div> </div>
{/* Compact Search Header & Input */} {results.length > 0 ? (
<div className="mb-5 sm:mb-8"> <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
<h1 className="text-xl sm:text-3xl font-black text-medical-gray-900 mb-2 font-lalezar tracking-wide"> {results.map((product) => {
{cleanQuery ? ( const compatibility = (() => {
<>نتایج جستجو برای: <span className="text-canina-blue">&quot;{query}&quot;</span></> 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}` };
</h1> if (helpsSymptom) return { type: 'success', text: `توصیه شده برای ${activePet.name}` };
<p className="text-[11px] sm:text-xs text-medical-gray-500 font-medium mb-3 sm:mb-4"> return { type: 'neutral', text: `مناسب برای ${activePet.name}` };
جستجوی هم‌زمان در داروها، مکمل‌ها، مقالات وبلاگ، دانشنامه ترکیبات و ویدیوهای بالینی })();
</p>
{/* Search Box Input */} return (
<form onSubmit={handleSearchSubmit} className="relative max-w-2xl"> <motion.div
<input key={product.id}
type="text" layoutId={product.id}
name="q" className="h-full"
value={searchInput} >
onChange={(e) => setSearchInput(e.target.value)} <Link
placeholder="جستجوی دارو، مقاله، ترکیب علمی، ویدیو..." href={`/shop/${product.slug || product.id}`}
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" 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"
/> >
<Search className="w-4 h-4 sm:w-5 sm:h-5 text-medical-gray-400 absolute right-3.5 top-1/2 -translate-y-1/2" /> <div className="relative aspect-square mb-8 bg-medical-gray-50 rounded-[2rem] overflow-hidden p-6 flex items-center justify-center">
<button <Image
type="submit" src={product.image}
className="absolute left-1.5 top-1/2 -translate-y-1/2 px-3.5 py-1.5 bg-canina-blue text-white rounded-xl text-xs font-black hover:bg-canina-dark transition-all cursor-pointer shadow-xs" alt={product.nameFa || product.name}
> width={200}
جستجو height={200}
</button> className="w-full h-full object-contain group-hover:scale-110 transition-transform duration-500"
</form> unoptimized
</div> />
{product.specialBadge && (
{/* Multi-Content Filter Tabs */} <div className="absolute top-4 right-4 bg-medical-gray-900 text-white text-[8px] font-black px-3 py-1 rounded-full uppercase tracking-widest">
<div {product.specialBadge}
role="tablist"
aria-label="فیلتر نوع محتوای نتایج جستجو"
className="flex items-center gap-1.5 sm:gap-2 overflow-x-auto pb-3 mb-6 micro-hscroll select-none"
>
{[
{ id: "all", label: "همه نتایج", count: totalResults, icon: <Sparkles className="w-3.5 h-3.5" /> },
{ id: "products", label: "محصولات و داروها", count: filteredProducts.length, icon: <ShoppingBag className="w-3.5 h-3.5" /> },
{ id: "blogs", label: "مقالات وبلاگ", count: filteredBlogs.length, icon: <FileText className="w-3.5 h-3.5" /> },
{ id: "wiki", label: "دانشنامه ترکیبات", count: filteredWiki.length, icon: <BookOpen className="w-3.5 h-3.5" /> },
{ id: "videos", label: "ویدیوهای بالینی", count: filteredVideos.length, icon: <Video className="w-3.5 h-3.5" /> },
].map(tab => (
<button
key={tab.id}
type="button"
role="tab"
id={`search-tab-${tab.id}`}
aria-selected={activeTab === 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
? "bg-canina-blue text-white border-canina-blue shadow-xs"
: "bg-white text-medical-gray-600 border-medical-gray-200 hover:border-canina-blue/50"
}`}
>
{tab.icon}
<span>{tab.label}</span>
<span className={`text-[10px] px-1.5 py-0.2 rounded-full font-bold ${
activeTab === tab.id ? "bg-white/20 text-white" : "bg-medical-gray-100 text-medical-gray-500"
}`}>
{toPersian(tab.count)}
</span>
</button>
))}
</div>
{/* RESULTS AREA */}
{isLoading ? (
<div
role="status"
aria-live="polite"
className="bg-white border border-medical-gray-200 rounded-3xl p-8 sm:p-12 text-center shadow-xs"
>
<div className="w-10 h-10 rounded-full border-4 border-canina-blue/20 border-t-canina-blue animate-spin mx-auto mb-4" aria-hidden="true" />
<p className="text-sm font-black text-medical-gray-700">در حال جستجو در همه بخش‌های کنینا...</p>
</div>
) : searchError ? (
<div
role="alert"
className="bg-white border border-red-200 rounded-3xl p-8 sm:p-12 text-center shadow-xs"
>
<div className="w-14 h-14 bg-red-50 text-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 border border-red-100">
<AlertCircle className="w-7 h-7" />
</div>
<h3 className="text-lg font-black text-medical-gray-900 mb-2">خطا در بارگذاری نتایج جستجو</h3>
<p className="text-xs text-medical-gray-500 max-w-md mx-auto mb-6">{searchError}</p>
<button
type="button"
data-testid="search-retry-button"
onClick={() => loadAll()}
className="inline-flex items-center gap-2 px-5 py-2.5 bg-canina-blue text-white rounded-xl text-xs font-black hover:bg-canina-dark transition-all cursor-pointer shadow-xs"
>
<span>تلاش مجدد</span>
</button>
</div>
) : cleanQuery && totalResults === 0 ? (
/* Empty State - Mobile-Optimized with direct suggestion cards */
<div className="space-y-8" role="status" aria-label="عدم یافت نتیجه جستجو">
<div className="bg-white border border-medical-gray-200 rounded-3xl p-6 sm:p-10 text-center shadow-xs">
<div className="w-14 h-14 bg-medical-gray-50 rounded-2xl flex items-center justify-center mx-auto text-medical-gray-300 mb-3 border border-medical-gray-100">
<Search className="w-7 h-7" />
</div>
<h3 className="text-lg sm:text-xl font-black text-medical-gray-900 mb-1.5 font-vazir">نتیجه‌ای یافت نشد</h3>
<p className="text-xs text-medical-gray-500 font-medium max-w-md mx-auto leading-relaxed mb-4">
متأسفیم، هیچ موردی با عبارت جستجو شده تطبیق نداشت. محصولات پرطرفدار زیر را بررسی کنید:
</p>
<button
type="button"
onClick={() => {
setSearchInput("");
router.push('/shop');
}}
className="inline-flex items-center gap-2 px-4 py-2 bg-canina-blue text-white rounded-xl text-xs font-black hover:bg-canina-dark transition-all cursor-pointer shadow-xs"
>
<span>مشاهده کاتالوگ فروشگاه</span>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
{bestSellers.length > 0 && (
<div>
<h3 className="text-base sm:text-xl font-black text-medical-gray-900 mb-4 font-vazir">محصولات پیشنهادی (پرفروش)</h3>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-6">
{bestSellers.map(p => (
<Link
key={p.id}
href={`/shop/${p.slug || p.id}`}
className="group bg-white p-3.5 sm:p-4 rounded-2xl border border-medical-gray-200 hover:border-canina-blue flex items-center sm:flex-col gap-3 shadow-2xs hover:shadow-md transition-all"
>
<div className="w-16 h-16 sm:w-28 sm:h-28 bg-medical-gray-50 rounded-xl p-2 flex items-center justify-center shrink-0">
<Image src={p.image} alt={p.name} width={100} height={100} className="w-full h-full object-contain group-hover:scale-105 transition-transform" unoptimized />
</div>
<div className="flex-1 sm:text-center min-w-0">
<h4 className="text-xs sm:text-sm font-black text-medical-gray-900 truncate mb-1">{p.nameFa || p.name}</h4>
<div className="text-[11px] font-black text-canina-blue">{p.price}</div>
</div>
</Link>
))}
</div>
</div>
)}
</div>
) : (
<div
id="search-results-panel"
role="tabpanel"
aria-labelledby={`search-tab-${activeTab}`}
className="space-y-10"
>
{/* 1. PRODUCTS SECTION */}
{(activeTab === "all" || activeTab === "products") && filteredProducts.length > 0 && (
<section>
<div className="flex items-center justify-between mb-3.5 pb-2 border-b border-medical-gray-200">
<div className="flex items-center gap-2">
<ShoppingBag className="w-4 h-4 text-canina-blue" />
<h2 className="text-sm sm:text-base font-black text-medical-gray-900">محصولات و مکمل‌ها ({toPersian(filteredProducts.length)})</h2>
</div>
{activeTab === "all" && filteredProducts.length > 6 && (
<button
type="button"
onClick={() => setActiveTab("products")}
className="text-[11px] font-black text-canina-blue hover:underline"
>
مشاهده همه محصولات
</button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-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 (
<Link
key={product.id}
href={`/shop/${product.slug || product.id}`}
className="group bg-white rounded-2xl p-3 sm:p-5 border border-medical-gray-200 hover:border-canina-blue shadow-2xs hover:shadow-lg transition-all flex flex-col justify-between"
>
<div className="flex items-center gap-3 sm:block mb-2">
<div className="w-20 h-20 sm:w-full sm:aspect-square bg-medical-gray-50 rounded-xl p-2 sm:p-4 flex items-center justify-center shrink-0 sm:mb-3">
<Image
src={product.image}
alt={product.nameFa || product.name}
width={150}
height={150}
className="w-full h-full object-contain group-hover:scale-105 transition-transform"
unoptimized
/>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5 mb-1 flex-wrap">
<span className="text-[9px] font-black text-canina-blue bg-canina-blue/5 px-2 py-0.5 rounded border border-canina-blue/10">
{product.category}
</span>
{compatibility && (
<span className={`text-[9px] font-black px-2 py-0.5 rounded ${
compatibility.type === 'alert' ? 'bg-amber-100 text-amber-700' :
compatibility.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-medical-gray-100 text-medical-gray-600'
}`}>
{compatibility.text}
</span>
)}
</div>
<h3 className="text-xs sm:text-sm font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors line-clamp-2">
{product.nameFa || product.name}
</h3>
<p className="text-[10px] text-medical-gray-400 line-clamp-1 mt-0.5">
{product.benefits || product.description}
</p>
</div>
</div>
<div className="flex items-center justify-between pt-2.5 border-t border-medical-gray-100 text-xs font-black">
<span className="text-medical-gray-900">{product.price}</span>
<span className="text-[11px] text-canina-blue flex items-center gap-0.5 group-hover:-translate-x-1 transition-transform">
مشاهده و خرید
<ChevronLeft className="w-3.5 h-3.5" />
</span>
</div>
</Link>
);
})}
</div>
</section>
)}
{/* 2. BLOGS SECTION */}
{(activeTab === "all" || activeTab === "blogs") && filteredBlogs.length > 0 && (
<section>
<div className="flex items-center justify-between mb-3.5 pb-2 border-b border-medical-gray-200">
<div className="flex items-center gap-2">
<FileText className="w-4 h-4 text-emerald-600" />
<h2 className="text-sm sm:text-base font-black text-medical-gray-900">مقالات مجله سلامت ({toPersian(filteredBlogs.length)})</h2>
</div>
{activeTab === "all" && filteredBlogs.length > 4 && (
<button
type="button"
onClick={() => setActiveTab("blogs")}
className="text-[11px] font-black text-canina-blue hover:underline"
>
مشاهده همه مقالات
</button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
{(activeTab === "all" ? filteredBlogs.slice(0, 4) : filteredBlogs).map((blog) => (
<Link
key={blog.id}
href={`/blog/${blog.slug || blog.id}`}
className="group bg-white rounded-2xl p-3 border border-medical-gray-200 hover:border-emerald-500 shadow-2xs hover:shadow-md transition-all flex items-center gap-3"
>
{blog.imageUrl ? (
<div className="w-20 h-20 rounded-xl overflow-hidden bg-medical-gray-50 shrink-0">
<Image
src={blog.imageUrl}
alt={blog.title}
width={80}
height={80}
className="w-full h-full object-cover group-hover:scale-105 transition-transform"
unoptimized
/>
</div>
) : (
<div className="w-20 h-20 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0">
<BookOpen className="w-6 h-6" />
</div> </div>
)} )}
{compatibility && (
<div className="flex-1 min-w-0"> <div className={`absolute top-14 right-4 z-10 text-[8px] font-black uppercase tracking-widest px-3 py-1 rounded-full shadow-md flex items-center gap-1 ${
<span className="text-[9px] font-black text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded"> compatibility.type === 'alert' ? 'bg-amber-100 text-amber-700' :
{typeof blog.category === 'object' ? blog.category?.name : blog.category || 'مقاله علمی'} compatibility.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-medical-gray-100 text-medical-gray-600'
</span> }`}>
<h3 className="text-xs sm:text-sm font-black text-medical-gray-900 group-hover:text-emerald-700 transition-colors line-clamp-2 mt-1"> {compatibility.type === 'alert' ? <AlertCircle className="w-2.5 h-2.5" /> : compatibility.type === 'success' ? <Heart className="w-2.5 h-2.5" /> : <Sparkles className="w-2.5 h-2.5" />}
{blog.title} {compatibility.text}
</h3>
<p className="text-[10px] text-medical-gray-400 line-clamp-1 mt-0.5">
{blog.excerpt}
</p>
</div>
</Link>
))}
</div>
</section>
)}
{/* 3. WIKI SECTION */}
{(activeTab === "all" || activeTab === "wiki") && filteredWiki.length > 0 && (
<section>
<div className="flex items-center justify-between mb-3.5 pb-2 border-b border-medical-gray-200">
<div className="flex items-center gap-2">
<BookOpen className="w-4 h-4 text-amber-500" />
<h2 className="text-sm sm:text-base font-black text-medical-gray-900">دانشنامه ترکیبات علمی ({toPersian(filteredWiki.length)})</h2>
</div>
{activeTab === "all" && filteredWiki.length > 4 && (
<button
type="button"
onClick={() => setActiveTab("wiki")}
className="text-[11px] font-black text-canina-blue hover:underline"
>
مشاهده همه ترکیبات
</button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
{(activeTab === "all" ? filteredWiki.slice(0, 4) : filteredWiki).map((wiki) => (
<Link
key={wiki.id}
href={`/wiki?term=${encodeURIComponent(wiki.slug || wiki.id)}`}
className="group bg-white rounded-2xl p-3 border border-medical-gray-200 hover:border-amber-500 shadow-2xs hover:shadow-md transition-all flex items-start gap-3"
>
<div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0">
<Pill className="w-5 h-5" />
</div>
<div className="flex-1 min-w-0">
<h3 className="text-xs sm:text-sm font-black text-medical-gray-900 group-hover:text-amber-600 transition-colors">
{wiki.nameFa || wiki.name}
</h3>
{wiki.scientificName && (
<div className="text-[10px] text-medical-gray-400 font-mono mt-0.5">
{wiki.scientificName}
</div>
)}
<p className="text-[10px] text-medical-gray-500 line-clamp-2 mt-1">
{wiki.description}
</p>
</div>
<ChevronLeft className="w-4 h-4 text-medical-gray-300 group-hover:text-amber-600 transition-colors shrink-0 self-center" />
</Link>
))}
</div>
</section>
)}
{/* 4. VIDEOS SECTION */}
{(activeTab === "all" || activeTab === "videos") && filteredVideos.length > 0 && (
<section>
<div className="flex items-center justify-between mb-3.5 pb-2 border-b border-medical-gray-200">
<div className="flex items-center gap-2">
<Video className="w-4 h-4 text-indigo-500" />
<h2 className="text-sm sm:text-base font-black text-medical-gray-900">ویدیوهای بالینی دامپزشکی ({toPersian(filteredVideos.length)})</h2>
</div>
{activeTab === "all" && filteredVideos.length > 3 && (
<button
type="button"
onClick={() => setActiveTab("videos")}
className="text-[11px] font-black text-canina-blue hover:underline"
>
مشاهده همه ویدیوها
</button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
{(activeTab === "all" ? filteredVideos.slice(0, 3) : filteredVideos).map((vid) => (
<Link
key={vid.id}
href="/videos"
className="group bg-white rounded-2xl overflow-hidden border border-medical-gray-200 hover:border-indigo-500 shadow-2xs hover:shadow-md transition-all flex flex-col"
>
<div className="relative aspect-video bg-medical-gray-900 flex items-center justify-center overflow-hidden">
{vid.thumbnail ? (
<Image src={vid.thumbnail} alt={vid.title} width={300} height={180} className="w-full h-full object-cover group-hover:scale-105 transition-transform" unoptimized />
) : null}
<div className="absolute inset-0 bg-black/30 flex items-center justify-center">
<PlayCircle className="w-8 h-8 text-white/90 group-hover:scale-110 transition-transform" />
</div> </div>
{vid.duration && ( )}
<span className="absolute bottom-2 left-2 bg-black/70 text-white text-[9px] px-1.5 py-0.5 rounded font-mono"> </div>
{vid.duration}
</span> <div className="flex-1">
)} <span className="text-[10px] font-black text-canina-blue uppercase tracking-widest mb-2 block">{product.category}</span>
</div> <h3 className="text-xl font-black text-medical-gray-900 mb-2 leading-tight group-hover:text-canina-blue transition-colors">{product.nameFa || product.name}</h3>
<div className="p-3 flex-1 flex flex-col justify-between"> <p className="text-xs text-medical-gray-400 line-clamp-2 leading-relaxed mb-6">{product.benefits}</p>
<div> </div>
<h3 className="text-xs font-black text-medical-gray-900 line-clamp-2 mb-1 group-hover:text-indigo-600 transition-colors">
{vid.title}
</h3>
{vid.doctor && (
<span className="text-[10px] font-bold text-medical-gray-400 block">
{vid.doctor}
</span>
)}
</div>
</div>
</Link>
))}
</div>
</section>
)}
<div className="flex items-center justify-between pt-6 border-t border-medical-gray-100 italic">
<div>
<span className="text-lg font-black text-medical-gray-900">{product.price}</span>
</div>
<div className="bg-medical-gray-900 text-white w-10 h-10 rounded-xl flex items-center justify-center group-hover:bg-canina-blue transition-colors">
<ChevronLeft className="w-5 h-5" />
</div>
</div>
</Link>
</motion.div>
)
})}
</div>
) : (
<div className="space-y-16">
<div className="bg-white border border-medical-gray-200 rounded-[3rem] p-12 text-center shadow-sm">
<div className="w-20 h-20 bg-medical-gray-50 rounded-full flex items-center justify-center mx-auto text-medical-gray-300 mb-6">
<Search className="w-10 h-10" />
</div>
<h3 className="text-2xl font-black text-medical-gray-800 mb-4">نتیجه‌ای یافت نشد</h3>
<p className="text-medical-gray-500 font-medium max-w-md mx-auto leading-relaxed">
متاسفیم، هیچ محصولی با عبارت مورد نظر شما مطابقت نداشت. شاید محصولات پرفروش ما برای شما مفید باشند؟
</p>
</div>
<div>
<h3 className="text-2xl font-black text-medical-gray-900 mb-10 italic">محصولات پیشنهادی (پرفروش)</h3>
<div className="grid md:grid-cols-3 gap-8 opacity-60 hover:opacity-100 transition-opacity">
{bestSellers.map(p => (
<Link key={p.id} href={`/shop/${p.slug || p.id}`} className="cursor-pointer group block">
<div className="aspect-square bg-white rounded-[2rem] p-6 mb-4 border border-medical-gray-100 flex items-center justify-center relative overflow-hidden">
<Image src={p.image} alt={p.name} width={160} height={160} className="w-40 h-40 object-contain group-hover:scale-105 transition-transform" unoptimized />
</div>
<h4 className="font-black text-medical-gray-900 text-center">{p.name}</h4>
</Link>
))}
</div>
</div>
</div> </div>
)} )}
</div> </div>
</div> </div>
); );
@@ -207,10 +207,10 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
}; };
return ( return (
<section id="canino-advisor" className="py-5 sm:py-16 bg-gradient-to-b from-white via-medical-gray-50/50 to-white"> <section id="canino-advisor" className="py-8 sm:py-16 bg-gradient-to-b from-white via-medical-gray-50/50 to-white">
<div className="max-w-5xl mx-auto px-4"> <div className="max-w-5xl mx-auto px-4">
{/* Header Title */} {/* Header Title */}
<div className="text-center mb-4 sm:mb-10"> <div className="text-center mb-6 sm:mb-10">
<motion.div <motion.div
initial={{ opacity: 0, y: 20 }} initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }} whileInView={{ opacity: 1, y: 0 }}
@@ -240,9 +240,9 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
initial={{ opacity: 0, y: 20 }} initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }} whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }} viewport={{ once: true }}
className="grid grid-cols-1 md:grid-cols-3 gap-2.5 sm:gap-6 mb-4 sm:mb-12" className="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6 mb-8 sm:mb-12"
> >
<div className="bg-white p-3.5 sm:p-6 rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200/80 shadow-xs sm:shadow-lg hover:shadow-xl transition-all group flex flex-col justify-between"> <div className="bg-white p-4 sm:p-6 rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200/80 shadow-md sm:shadow-lg hover:shadow-xl transition-all group flex flex-col justify-between">
<div> <div>
<div className="flex items-center gap-3 sm:block mb-2 sm:mb-0"> <div className="flex items-center gap-3 sm:block mb-2 sm:mb-0">
<div className="w-9 h-9 sm:w-12 sm:h-12 bg-canina-blue/10 rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue sm:mb-4 group-hover:bg-canina-blue group-hover:text-white transition-all shadow-sm flex-shrink-0"> <div className="w-9 h-9 sm:w-12 sm:h-12 bg-canina-blue/10 rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue sm:mb-4 group-hover:bg-canina-blue group-hover:text-white transition-all shadow-sm flex-shrink-0">
@@ -256,13 +256,13 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
{getText('advisor_card1_desc', 'مکمل‌های دارویی کنینا غلیظ و تخصصی هستند؛ الگوریتم هوشمند ما بر اساس سن، وزن و جثه پت شما، دوز دقیق مصرفی روزانه را محاسبه می‌کند.')} {getText('advisor_card1_desc', 'مکمل‌های دارویی کنینا غلیظ و تخصصی هستند؛ الگوریتم هوشمند ما بر اساس سن، وزن و جثه پت شما، دوز دقیق مصرفی روزانه را محاسبه می‌کند.')}
</p> </p>
</div> </div>
<div className="mt-2 sm:mt-4 pt-2 sm:pt-4 border-t border-medical-gray-100 text-[10px] font-black text-canina-blue flex items-center gap-1 font-vazir"> <div className="mt-3 sm:mt-4 pt-3 sm:pt-4 border-t border-medical-gray-100 text-[10px] font-black text-canina-blue flex items-center gap-1 font-vazir">
<Check className="w-3.5 h-3.5" /> <Check className="w-3.5 h-3.5" />
{getText('advisor_card1_footer', 'تضمین ایمنی و عدم اوردوز')} {getText('advisor_card1_footer', 'تضمین ایمنی و عدم اوردوز')}
</div> </div>
</div> </div>
<div className="bg-white p-3.5 sm:p-6 rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200/80 shadow-xs sm:shadow-lg hover:shadow-xl transition-all group flex flex-col justify-between"> <div className="bg-white p-4 sm:p-6 rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200/80 shadow-md sm:shadow-lg hover:shadow-xl transition-all group flex flex-col justify-between">
<div> <div>
<div className="flex items-center gap-3 sm:block mb-2 sm:mb-0"> <div className="flex items-center gap-3 sm:block mb-2 sm:mb-0">
<div className="w-9 h-9 sm:w-12 sm:h-12 bg-canina-blue/10 rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue sm:mb-4 group-hover:bg-canina-blue group-hover:text-white transition-all shadow-sm flex-shrink-0"> <div className="w-9 h-9 sm:w-12 sm:h-12 bg-canina-blue/10 rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue sm:mb-4 group-hover:bg-canina-blue group-hover:text-white transition-all shadow-sm flex-shrink-0">
@@ -276,13 +276,13 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
{getText('advisor_card2_desc', 'با انتخاب علائمی مثل لنگیدن یا ریزش مو، دقیق‌ترین راهکار مکمل آلمانی به همراه دلایل علمی به شما پیشنهاد می‌شود.')} {getText('advisor_card2_desc', 'با انتخاب علائمی مثل لنگیدن یا ریزش مو، دقیق‌ترین راهکار مکمل آلمانی به همراه دلایل علمی به شما پیشنهاد می‌شود.')}
</p> </p>
</div> </div>
<div className="mt-2 sm:mt-4 pt-2 sm:pt-4 border-t border-medical-gray-100 text-[10px] font-black text-canina-blue flex items-center gap-1 font-vazir"> <div className="mt-3 sm:mt-4 pt-3 sm:pt-4 border-t border-medical-gray-100 text-[10px] font-black text-canina-blue flex items-center gap-1 font-vazir">
<Check className="w-3.5 h-3.5" /> <Check className="w-3.5 h-3.5" />
{getText('advisor_card2_footer', 'پیشنهاد هدفمند و تخصصی')} {getText('advisor_card2_footer', 'پیشنهاد هدفمند و تخصصی')}
</div> </div>
</div> </div>
<div className="bg-white p-3.5 sm:p-6 rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200/80 shadow-xs sm:shadow-lg hover:shadow-xl transition-all group flex flex-col justify-between"> <div className="bg-white p-4 sm:p-6 rounded-2xl sm:rounded-[2.5rem] border border-medical-gray-200/80 shadow-md sm:shadow-lg hover:shadow-xl transition-all group flex flex-col justify-between">
<div> <div>
<div className="flex items-center gap-3 sm:block mb-2 sm:mb-0"> <div className="flex items-center gap-3 sm:block mb-2 sm:mb-0">
<div className="w-9 h-9 sm:w-12 sm:h-12 bg-canina-blue/10 rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue sm:mb-4 group-hover:bg-canina-blue group-hover:text-white transition-all shadow-sm flex-shrink-0"> <div className="w-9 h-9 sm:w-12 sm:h-12 bg-canina-blue/10 rounded-xl sm:rounded-2xl flex items-center justify-center text-canina-blue sm:mb-4 group-hover:bg-canina-blue group-hover:text-white transition-all shadow-sm flex-shrink-0">
@@ -296,7 +296,7 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
{getText('advisor_card3_desc', 'زمان‌های مصرف مکمل‌ها تنظیم شده و سیستم قبل از اتمام دوره درمانی، هشدار شارژ مجدد ارسال خواهد کرد.')} {getText('advisor_card3_desc', 'زمان‌های مصرف مکمل‌ها تنظیم شده و سیستم قبل از اتمام دوره درمانی، هشدار شارژ مجدد ارسال خواهد کرد.')}
</p> </p>
</div> </div>
<div className="mt-2 sm:mt-4 pt-2 sm:pt-4 border-t border-medical-gray-100 text-[10px] font-black text-canina-blue flex items-center gap-1 font-vazir"> <div className="mt-3 sm:mt-4 pt-3 sm:pt-4 border-t border-medical-gray-100 text-[10px] font-black text-canina-blue flex items-center gap-1 font-vazir">
<Check className="w-3.5 h-3.5" /> <Check className="w-3.5 h-3.5" />
{getText('advisor_card3_footer', 'تکمیل منظم دوره درمان')} {getText('advisor_card3_footer', 'تکمیل منظم دوره درمان')}
</div> </div>
@@ -349,11 +349,9 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
<div className="grid md:grid-cols-2 gap-4 max-w-xl mx-auto"> <div className="grid md:grid-cols-2 gap-4 max-w-xl mx-auto">
<div className="space-y-1.5"> <div className="space-y-1.5">
<label htmlFor="advisor-pet-name" className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_name_label', "نام پت")}</label> <label className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_name_label', "نام پت")}</label>
<input <input
id="advisor-pet-name"
type="text" type="text"
aria-label={getText('advisor_pet_name_label', "نام پت")}
value={name} value={name}
onChange={e => { onChange={e => {
setName(e.target.value); setName(e.target.value);
@@ -369,11 +367,9 @@ export default function SmartAdvisor({ onComplete, rules = [] }: SmartAdvisorPro
/> />
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<label htmlFor="advisor-pet-breed" className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_breed_label', "نژاد")}</label> <label className="text-xs font-black text-medical-gray-600 pr-1">{getText('advisor_pet_breed_label', "نژاد")}</label>
<input <input
id="advisor-pet-breed"
type="text" type="text"
aria-label={getText('advisor_pet_breed_label', "نژاد")}
value={breed} value={breed}
onChange={e => { onChange={e => {
setBreed(e.target.value); setBreed(e.target.value);
@@ -6,30 +6,24 @@ import SupportChat from './SupportChat';
afterEach(() => { cleanup(); vi.restoreAllMocks(); localStorage.clear(); }); afterEach(() => { cleanup(); vi.restoreAllMocks(); localStorage.clear(); });
describe('support widget', () => { describe('support widget', () => {
it('submits only message without scope tabs, renders text safely', async () => { it('submits only message without scope tabs, renders text safely', async () => {
const fetcher=vi.spyOn(globalThis,'fetch') const fetcher=vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:'<script>bad</script>'})} as Response);
.mockResolvedValueOnce({ok:true,json:async()=>({enabled:true,label:'گفتگو با پشتیبان',icon:'chat'})} as Response) render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/}));
.mockResolvedValueOnce({ok:true,json:async()=>({answer:'<script>bad</script>'})} as Response);
render(<SupportChat/>); 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:'ارسال'})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'مکمل سگ'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'}));
await waitFor(()=>expect(screen.getByText('<script>bad</script>')).toBeTruthy()); await waitFor(()=>expect(screen.getByText('<script>bad</script>')).toBeTruthy());
expect(JSON.parse(fetcher.mock.calls[1][1]!.body as string)).toEqual({message:'مکمل سگ', entryPath:'/'}); expect(JSON.parse(fetcher.mock.calls[0][1]!.body as string)).toEqual({message:'مکمل سگ'});
expect(document.querySelector('script')).toBeNull(); expect(document.querySelector('script')).toBeNull();
for (const label of ['محصولات و عمومی','سفارش‌های من','کیف پول']) expect(screen.queryByRole('button',{name:label})).toBeNull(); for (const label of ['محصولات و عمومی','سفارش‌های من','کیف پول']) expect(screen.queryByRole('button',{name:label})).toBeNull();
}); });
it('does not expose upstream errors', async()=> { it('does not expose upstream errors', async()=> {
vi.spyOn(globalThis,'fetch') vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:false,status:503,json:async()=>({message:'secret-provider'})} as Response);
.mockResolvedValueOnce({ok:true,json:async()=>({enabled:true,label:'گفتگو با پشتیبان',icon:'chat'})} as Response) render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/}));
.mockResolvedValueOnce({ok:false,status:503,json:async()=>({message:'secret-provider'})} as Response);
render(<SupportChat/>); 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:'ارسال'})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'سلام'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'}));
await waitFor(()=>expect(screen.getByText(/فعلاً در دسترس نیست/)).toBeTruthy()); expect(screen.queryByText('secret-provider')).toBeNull(); await waitFor(()=>expect(screen.getByText(/فعلاً در دسترس نیست/)).toBeTruthy()); expect(screen.queryByText('secret-provider')).toBeNull();
}); });
it('clears transcript on account transition', async()=> { it('clears transcript on account transition', async()=> {
localStorage.setItem('accessToken','alice'); localStorage.setItem('accessToken','alice');
vi.spyOn(globalThis,'fetch') vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:'private Alice'})} as Response);
.mockResolvedValueOnce({ok:true,json:async()=>({enabled:true,label:'گفتگو با پشتیبان',icon:'chat'})} as Response) render(<SupportChat/>); fireEvent.click(screen.getByRole('button',{name:/گفتگو با پشتیبان/})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'کیف پول'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'}));
.mockResolvedValueOnce({ok:true,json:async()=>({answer:'private Alice'})} as Response);
render(<SupportChat/>); 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()); await waitFor(()=>expect(screen.getByText('private Alice')).toBeTruthy());
localStorage.setItem('accessToken','bob'); fireEvent.focus(window); localStorage.setItem('accessToken','bob'); fireEvent.focus(window);
await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull()); await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull());
+10 -40
View File
@@ -1,6 +1,5 @@
'use client'; 'use client';
import { FormEvent, useEffect, useRef, useState } from 'react'; import { FormEvent, useEffect, useRef, useState } from 'react';
import { usePathname } from 'next/navigation';
type PersistedMessage = { role: 'user' | 'assistant'; content: string }; type PersistedMessage = { role: 'user' | 'assistant'; content: string };
@@ -17,14 +16,6 @@ export default function SupportChat() {
const [config, setConfig] = useState<{ enabled: boolean; label: string; icon: string } | null>(null); const [config, setConfig] = useState<{ enabled: boolean; label: string; icon: string } | null>(null);
const [configError, setConfigError] = useState(false); const [configError, setConfigError] = useState(false);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
const [rows, setRows] = useState<{ question: string; answer: string }[]>([]);
const [conversationId, setConversationId] = useState('');
const [contextLimited, setContextLimited] = useState(false);
const identity = useRef('');
const pending = useRef<AbortController | null>(null);
useEffect(() => { useEffect(() => {
let active = true; let active = true;
const refresh = async () => { const refresh = async () => {
@@ -42,10 +33,15 @@ export default function SupportChat() {
window.addEventListener('focus', refresh); window.addEventListener('focus', refresh);
return () => { active = false; clearInterval(timer); window.removeEventListener('focus', refresh); }; return () => { active = false; clearInterval(timer); window.removeEventListener('focus', refresh); };
}, []); }, []);
const [message, setMessage] = useState('');
const [busy, setBusy] = useState(false);
const [rows, setRows] = useState<{ question: string; answer: string }[]>([]);
const [conversationId, setConversationId] = useState('');
const [contextLimited, setContextLimited] = useState(false);
const identity = useRef('');
const pending = useRef<AbortController | null>(null);
const chatScrollRef = useRef<HTMLDivElement | null>(null); const chatScrollRef = useRef<HTMLDivElement | null>(null);
const historyKey = useRef(''); const historyKey = useRef('');
const pathname = usePathname();
const isPdpPage = pathname?.startsWith('/shop/') && pathname !== '/shop';
useEffect(() => { useEffect(() => {
identity.current = token(); identity.current = token();
@@ -164,41 +160,15 @@ export default function SupportChat() {
// safe fallback kept // safe fallback kept
} }
if (!controller.signal.aborted && token() === current) { if (!controller.signal.aborted && token() === current) {
// Typewriting animation for smooth AI assistant response streaming feel 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; });
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 ? <span role="status" className="sr-only">تنظیمات پشتیبان هوشمند در دسترس نیست.</span> : null; if (!config?.enabled) return configError ? <span role="status" className="sr-only">تنظیمات پشتیبان هوشمند در دسترس نیست.</span> : null;
const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon]; const botIcon = { chat: '💬', paw: '🐾', bot: '🤖' }[config.icon];
return ( return (
<aside dir="rtl" className={`fixed ${isPdpPage ? "bottom-[138px]" : "bottom-24"} sm:bottom-6 left-4 sm:left-6 z-30 max-w-[calc(100vw-2.5rem)] font-vazir select-none pb-[env(safe-area-inset-bottom,0px)]`}> <aside dir="rtl" className="fixed bottom-20 left-5 z-30 max-w-[calc(100vw-2.5rem)] font-vazir select-none">
{/* Floating Launcher Button */} {/* Floating Launcher Button */}
<button <button
type="button" type="button"
@@ -13,13 +13,10 @@ export default function TickerBanner() {
const textFa = getText("site_logo_text_fa", "ایران"); const textFa = getText("site_logo_text_fa", "ایران");
const isBlobOrData = typeof logoUrl === 'string' && (logoUrl.startsWith('blob:') || logoUrl.startsWith('data:')); const isBlobOrData = typeof logoUrl === 'string' && (logoUrl.startsWith('blob:') || logoUrl.startsWith('data:'));
const rawNotice = getText( const announcementText = getText(
"shipping_notice", "shipping_notice",
"ارسال رایگان برای سفارش‌های بالای ۱۵۰ هزار تومان — گارانتی اصالت کنینا آلمان — مشاوره تخصصی مکمل‌های دارویی سگ و گربه با کادر دامپزشکان مجرب" "ارسال رایگان برای سفارش‌های بالای ۱۵۰ هزار تومان — گارانتی اصالت کنینا آلمان — مشاوره تخصصی مکمل‌های دارویی سگ و گربه با کادر دامپزشکان مجرب"
); );
const announcementText = typeof rawNotice === 'string'
? rawNotice.replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
: '';
return ( return (
<div className="bg-canina-gold text-canina-dark select-none shadow-xs border-b border-amber-300/40"> <div className="bg-canina-gold text-canina-dark select-none shadow-xs border-b border-amber-300/40">
@@ -420,7 +420,7 @@ export default function UserDashboard() {
<User className="w-6 h-6 sm:w-7 sm:h-7" /> <User className="w-6 h-6 sm:w-7 sm:h-7" />
</div> </div>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<h1 className="text-base sm:text-lg font-black text-medical-gray-900 truncate">{profile.firstName} {profile.lastName}</h1> <h2 className="text-base sm:text-lg font-black text-medical-gray-900 truncate">{profile.firstName} {profile.lastName}</h2>
<p className="text-[11px] sm:text-xs font-bold text-medical-gray-400 truncate">{profile.email}</p> <p className="text-[11px] sm:text-xs font-bold text-medical-gray-400 truncate">{profile.email}</p>
</div> </div>
</div> </div>
@@ -1,7 +1,7 @@
"use client"; "use client";
import React from "react"; import React from "react";
import { describe, it, expect, vi, beforeEach } from "vitest"; import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react"; import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import ArchivePage, { orderProductsByAvailability } from "../ArchivePage"; import ArchivePage, { orderProductsByAvailability } from "../ArchivePage";
import { productService } from "../../lib/services/productService"; import { productService } from "../../lib/services/productService";
import { useCartStore } from "../../lib/store/cartStore"; import { useCartStore } from "../../lib/store/cartStore";
@@ -144,35 +144,6 @@ const mockProducts = [
}); });
describe("ArchivePage Component", () => { describe("ArchivePage Component", () => {
it("renders server-provided initial products without waiting for a client fetch", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
expect(screen.getAllByText("گلوکوزامین مفاصل").length).toBeGreaterThan(0);
expect(productService.getProducts).not.toHaveBeenCalled();
});
it("gives catalog search controls accessible names", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
expect(screen.getAllByLabelText("جستجوی محصول").length).toBe(2);
expect(screen.getAllByLabelText("جستجوی علائم").length).toBeGreaterThan(0);
});
it("gives the catalog sort control an accessible name", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
expect(screen.getByLabelText("مرتب‌سازی محصولات")).toBeTruthy();
});
it("exposes a scroll affordance for the mobile filter row", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
const filterRow = screen.getByTestId("mobile-catalog-filters");
expect(filterRow).toHaveAttribute("aria-label", "فیلترهای محصولات");
expect(screen.getByTestId("mobile-catalog-filters-edge")).toBeInTheDocument();
});
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
@@ -212,19 +183,6 @@ describe("ArchivePage Component", () => {
}); });
}); });
it("refreshes products from the mobile catalog search control", async () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
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 () => { it("filters products by search query input", async () => {
render(<ArchivePage />); render(<ArchivePage />);
@@ -321,106 +279,4 @@ describe("ArchivePage Component", () => {
expect(mockPush).toHaveBeenCalledWith("/shop"); 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(<ArchivePage initialProducts={[singleProduct as any]} />);
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(<ArchivePage />);
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(<ArchivePage initialProducts={mockProducts as any} initialLimit={12} />);
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(<ArchivePage initialProducts={mockProducts as any} initialLimit={12} initialPage={2} />);
await waitFor(() => {
expect(screen.getByText("محصول تست 13")).toBeInTheDocument();
expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument();
});
});
}); });
@@ -1,84 +0,0 @@
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();
});
});
@@ -1,101 +0,0 @@
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();
});
});
@@ -113,18 +113,16 @@ describe("B2BLandingClient Component", () => {
fireEvent.click(submitBtn); fireEvent.click(submitBtn);
await waitFor(() => { await waitFor(() => {
expect(api.post).toHaveBeenCalledWith("/b2b/inquire", expect.objectContaining({ expect(api.post).toHaveBeenCalledWith("/wholesale/apply", {
companyName: "کلینیک تخصصی آریا", businessName: "کلینیک تخصصی آریا (بیمارستان دامپزشکی - تهران) - رابط: دکتر حسینی",
contactName: "دکتر حسینی", licenseNumber: "09121112233",
phone: "09121112233", notes: "سفارش اولیه مکمل‌های حرکتی و کلسیم",
businessType: "بیمارستان دامپزشکی (شهر: تهران)", });
message: "سفارش اولیه مکمل‌های حرکتی و کلسیم",
}));
}); });
await waitFor(() => { await waitFor(() => {
expect(toast.success).toHaveBeenCalledWith( expect(toast.success).toHaveBeenCalledWith(
expect.stringContaining("درخواست همکاری تجاری شما با موفقیت ثبت شد") expect.stringContaining("درخواست همکاری شما با موفقیت ثبت شد")
); );
expect(screen.getByText("درخواست شما با موفقیت ثبت شد")).toBeInTheDocument(); expect(screen.getByText("درخواست شما با موفقیت ثبت شد")).toBeInTheDocument();
expect( expect(
@@ -14,11 +14,11 @@ vi.mock('../SafeImage',()=>({default:({alt}:{alt:string})=><img alt={alt}/>}));
const products=[{id:'1',name:'Joint care',artNo:'A1',priceValue:1000,wholesalePrice:650,category:'joints'},{id:'2',name:'Skin care',artNo:'B2',priceValue:2000,category:'skin'}]; const products=[{id:'1',name:'Joint care',artNo:'A1',priceValue:1000,wholesalePrice:650,category:'joints'},{id:'2',name:'Skin care',artNo:'B2',priceValue:2000,category:'skin'}];
beforeEach(()=>{vi.clearAllMocks();state.role='User_Wholesale';state.getProducts.mockResolvedValue({data:products});state.post.mockResolvedValue({});}); beforeEach(()=>{vi.clearAllMocks();state.role='User_Wholesale';state.getProducts.mockResolvedValue({data:products});state.post.mockResolvedValue({});});
afterEach(()=>{cleanup();vi.restoreAllMocks();}); afterEach(()=>{cleanup();vi.restoreAllMocks();});
it('uses specific price and settings discount fallback',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(state.getProducts).toHaveBeenCalledWith({limit:999});expect(screen.getByText('۶۵۰ تومان')).toBeInTheDocument();expect(screen.getByText('۱,۶۰۰ تومان')).toBeInTheDocument();}); it('uses specific price and settings discount fallback',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(state.getProducts).toHaveBeenCalledWith({limit:999});expect(screen.getByText('۶۵۰ تومان')).toBeInTheDocument();expect(screen.getByText('۱,۶۰۰ تومان')).toBeInTheDocument();});
it.each(['User_Wholesale','ADMIN','User_Partner'])('unlocks wholesale prices for %s',async role=>{state.role=role;render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(screen.queryByText('نیازمند تایید ادمین')).not.toBeInTheDocument();}); it.each(['User_Wholesale','ADMIN','User_Partner'])('unlocks wholesale prices for %s',async role=>{state.role=role;render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.queryByText('نیازمند تایید ادمین')).not.toBeInTheDocument();});
it('hides wholesale prices for unverified users',async()=>{state.role='USER';render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(screen.getAllByText('نیازمند تایید ادمین')).toHaveLength(2);expect(screen.queryByText('۶۵۰ تومان')).not.toBeInTheDocument();}); it('hides wholesale prices for unverified users',async()=>{state.role='USER';render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.getAllByText('نیازمند تایید ادمین')).toHaveLength(2);expect(screen.queryByText('۶۵۰ تومان')).not.toBeInTheDocument();});
it('filters by code preserving selection and clamps negative quantity',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();fireEvent.change(screen.getAllByRole('spinbutton')[0],{target:{value:'3'}});fireEvent.change(screen.getAllByRole('spinbutton')[1],{target:{value:'-2'}});fireEvent.change(screen.getByPlaceholderText('جستجوی کد کالا یا نام محصول...'),{target:{value:'B2'}});expect(screen.queryAllByText('Joint care')).toHaveLength(0);fireEvent.click(screen.getByRole('button',{name:/افزودن کلی/}));expect(state.addItem).toHaveBeenCalledExactlyOnceWith(products[0],3);expect(screen.getByText(/سفارشات با موفقیت/)).toBeInTheDocument();}); it('filters by code preserving selection and clamps negative quantity',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();fireEvent.change(screen.getAllByRole('spinbutton')[0],{target:{value:'3'}});fireEvent.change(screen.getAllByRole('spinbutton')[1],{target:{value:'-2'}});fireEvent.change(screen.getByPlaceholderText('جستجوی کد کالا یا نام محصول...'),{target:{value:'B2'}});expect(screen.queryByText('Joint care')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:/افزودن کلی/}));expect(state.addItem).toHaveBeenCalledExactlyOnceWith(products[0],3);expect(screen.getByText(/سفارشات با موفقیت/)).toBeInTheDocument();});
it.each([false,true])('consultation success/error: failure=%s',async failure=>{state.role='USER';if(failure)state.post.mockRejectedValue(new Error('offline'));const {container}=render(<B2BPortal onClose={()=>{}}/>);fireEvent.change(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه'),{target:{value:'Clinic'}});fireEvent.change(screen.getByPlaceholderText('شماره تماس همراه'),{target:{value:'09120000000'}});fireEvent.submit(container.querySelector('form')!);await waitFor(()=>expect(failure?state.error:state.success).toHaveBeenCalledOnce());expect(state.post).toHaveBeenCalledWith('/wholesale/apply',{businessName:'Clinic',licenseNumber:'09120000000'});expect(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه')).toHaveValue(failure?'Clinic':'');}); it.each([false,true])('consultation success/error: failure=%s',async failure=>{state.role='USER';if(failure)state.post.mockRejectedValue(new Error('offline'));const {container}=render(<B2BPortal onClose={()=>{}}/>);fireEvent.change(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه'),{target:{value:'Clinic'}});fireEvent.change(screen.getByPlaceholderText('شماره تماس همراه'),{target:{value:'09120000000'}});fireEvent.submit(container.querySelector('form')!);await waitFor(()=>expect(failure?state.error:state.success).toHaveBeenCalledOnce());expect(state.post).toHaveBeenCalledWith('/wholesale/apply',{businessName:'Clinic',licenseNumber:'09120000000'});expect(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه')).toHaveValue(failure?'Clinic':'');});
it('handles product loading failure visibly',async()=>{state.getProducts.mockRejectedValueOnce(new Error('offline'));render(<B2BPortal onClose={()=>{}}/>);expect(await screen.findByText(/خطا در دریافت محصولات/)).toBeInTheDocument();expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();}); it('handles product loading failure visibly',async()=>{state.getProducts.mockRejectedValueOnce(new Error('offline'));render(<B2BPortal onClose={()=>{}}/>);expect(await screen.findByText(/خطا در دریافت محصولات/)).toBeInTheDocument();expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();});
it.each([false,true])('ignores a settled request after unmount: failure=%s',async failure=>{let resolve!:(value:{data:typeof products})=>void;let reject!:(reason:Error)=>void;state.getProducts.mockReturnValueOnce(new Promise((yes,no)=>{resolve=yes;reject=no;}));const first=render(<B2BPortal onClose={()=>{}}/>);first.unmount();const next=render(<B2BPortal onClose={()=>{}}/>);await screen.findAllByText('Joint care');await act(async()=>{if(failure)reject(new Error('late failure'));else resolve({data:[{...products[0],name:'Stale product'}]});});expect(screen.queryByRole('alert')).not.toBeInTheDocument();expect(screen.queryByText('Stale product')).not.toBeInTheDocument();expect(screen.getAllByText('Joint care')[0]).toBeInTheDocument();next.unmount();}); it.each([false,true])('ignores a settled request after unmount: failure=%s',async failure=>{let resolve!:(value:{data:typeof products})=>void;let reject!:(reason:Error)=>void;state.getProducts.mockReturnValueOnce(new Promise((yes,no)=>{resolve=yes;reject=no;}));const first=render(<B2BPortal onClose={()=>{}}/>);first.unmount();const next=render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');await act(async()=>{if(failure)reject(new Error('late failure'));else resolve({data:[{...products[0],name:'Stale product'}]});});expect(screen.queryByRole('alert')).not.toBeInTheDocument();expect(screen.queryByText('Stale product')).not.toBeInTheDocument();expect(screen.getByText('Joint care')).toBeInTheDocument();next.unmount();});
it('closes via callback',()=>{const close=vi.fn();const {container}=render(<B2BPortal onClose={close}/>);fireEvent.click(container.querySelector('button')!);expect(close).toHaveBeenCalledOnce();}); it('closes via callback',()=>{const close=vi.fn();const {container}=render(<B2BPortal onClose={close}/>);fireEvent.click(container.querySelector('button')!);expect(close).toHaveBeenCalledOnce();});
@@ -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'}]; const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Skin',slug:'skin'}];
beforeEach(()=>vi.clearAllMocks()); beforeEach(()=>vi.clearAllMocks());
describe('BlogPage',()=>{ describe('BlogPage',()=>{
it('renders featured and regular posts as semantic links',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);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('prioritizes featured post and navigates',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');fireEvent.click(screen.getByText('Skin article'));expect(h.push).toHaveBeenCalledWith('/blog/skin');});
it('combines category, excerpt search and tags then resets empty intersection',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);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('combines category, excerpt search and tags then resets empty intersection',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);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(<BlogPage blogs={blogs} categories={categories} initialCategoryId="joints"/>);expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender(<BlogPage blogs={blogs} categories={categories} initialCategoryId="skin"/>);expect(screen.queryByText('Joint article')).not.toBeInTheDocument();}); it('syncs category with route props',()=>{const view=render(<BlogPage blogs={blogs} categories={categories} initialCategoryId="joints"/>);expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender(<BlogPage blogs={blogs} categories={categories} initialCategoryId="skin"/>);expect(screen.queryByText('Joint article')).not.toBeInTheDocument();});
it('clears search and toggles tags off',()=>{render(<BlogPage blogs={blogs}/>);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();}); it('clears search and toggles tags off',()=>{render(<BlogPage blogs={blogs}/>);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();});
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more