feat: complete payment retry, reviews system, catalog mode enforcement, and UI text defaults
Deploy Canina / deploy (push) Successful in 1m48s

This commit is contained in:
parsa aghaei committed 2026-08-17 09:01:33 +03:30
1 parent e1b035d6dd
commit 2fca778930
24 files changed
+2297 -242

No files matched your search

+24
View File
@@ -30,6 +30,7 @@ model User {
partnerAccount PartnerAccount?
paymentTransactions PaymentTransaction[]
tickets Ticket[]
reviews ProductReview[]
@@map("users")
}
@@ -163,6 +164,7 @@ model Product {
orderItems OrderItem[]
advisorRules SmartAdvisorRule[]
inventoryReservations InventoryReservation[]
reviews ProductReview[]
@@index([categorySlug])
@@index([suitableFor])
@@ -671,4 +673,26 @@ model TicketMessage {
@@map("ticket_messages")
}
model ProductReview {
id String @id @default(uuid()) @db.Uuid
productId String @map("product_id") @db.Uuid
userId String? @map("user_id") @db.Uuid
userName String @map("user_name") @db.VarChar(100)
userPhone String? @map("user_phone") @db.VarChar(20)
rating Int @default(5)
comment String @db.Text
status String @default("PENDING") @db.VarChar(20) // PENDING, APPROVED, REJECTED
adminReply String? @map("admin_reply") @db.Text
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
@@index([productId])
@@index([status])
@@index([createdAt])
@@map("product_reviews")
}
+2
View File
@@ -29,6 +29,7 @@ import { PrescriptionsModule } from './prescriptions/prescriptions.module';
import { B2BModule } from './b2b/b2b.module';
import { PaymentModule } from './payment/payment.module';
import { TicketsModule } from './tickets/tickets.module';
import { ReviewsModule } from './reviews/reviews.module';
import { Request, Response, NextFunction } from 'express';
@@ -46,6 +47,7 @@ import { Request, Response, NextFunction } from 'express';
SettingsModule,
PaymentModule,
TicketsModule,
ReviewsModule,
ThrottlerModule.forRoot([
{
ttl: 60000,
+13
View File
@@ -186,6 +186,19 @@ export class OrdersController {
},
},
})
@Post(':id/retry-payment')
@ApiOperation({ summary: 'پرداخت مجدد و تکمیل سفارش با امکان انتخاب روش پرداخت' })
@ApiOkResponse({
description: 'درخواست پرداخت مجدد با موفقیت پردازش شد',
})
retryPayment(
@Req() req: { user: { id: string } },
@Param('id') id: string,
@Body() body: { paymentMethod?: string },
) {
return this.ordersService.retryPayment(req.user.id, id, body?.paymentMethod);
}
findOne(@Req() req: { user: { id: string } }, @Param('id') id: string) {
return this.ordersService.findOne(id, req.user.id);
}
+128 -3
View File
@@ -20,10 +20,8 @@ export class OrdersService {
) {}
private generateTrackingNumber(): string {
const date = new Date();
const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
const random = Math.floor(10000 + Math.random() * 90000);
return `CN-${dateStr}-${random}`;
return `CN-${random}`;
}
async validateCoupon(
@@ -101,6 +99,17 @@ export class OrdersService {
}
async create(userId: string, createOrderDto: CreateOrderDto) {
// Check catalog mode settings
const catalogSetting = await this.prisma.setting.findFirst({
where: { key: { in: ['catalog_mode', 'catalog_disable_checkout'] } },
});
const catalogUiText = await this.prisma.uiText.findFirst({
where: { key: { in: ['catalog_mode', 'catalog_disable_checkout'] }, value: 'true' },
});
if ((catalogSetting && String(catalogSetting.value) === 'true') || catalogUiText) {
throw new BadRequestException('امکان ثبت سفارش به دلیل فعال بودن حالت کاتالوگ در حال حاضر وجود ندارد.');
}
if (!createOrderDto.items || createOrderDto.items.length === 0) {
throw new BadRequestException('سبد خرید خالی است');
}
@@ -430,4 +439,120 @@ export class OrdersService {
executedAt: now,
};
}
/**
* Retry or complete payment for an existing pending order with selectable payment method
*/
async retryPayment(
userId: string,
orderId: string,
paymentMethod?: string,
) {
const order = await this.prisma.order.findFirst({
where: { id: orderId, userId },
include: { user: true },
});
if (!order) {
throw new NotFoundException('سفارش مورد نظر یافت نشد');
}
if (['shipped', 'delivered'].includes(order.status)) {
throw new BadRequestException('این سفارش قبلاً پرداخت و تکمیل شده است');
}
const selectedMethod = paymentMethod || order.paymentMethod || 'online';
const finalAmount = Number(order.totalAmount);
if (selectedMethod === 'wallet') {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) throw new NotFoundException('کاربر یافت نشد');
const userBalance = Number(user.walletBalance || 0);
if (userBalance < finalAmount) {
throw new BadRequestException(
`موجودی کیف پول شما (${userBalance.toLocaleString('fa-IR')} تومان) کمتر از مبلغ سفارش (${finalAmount.toLocaleString('fa-IR')} تومان) است.`,
);
}
await this.prisma.$transaction(async (tx) => {
await tx.user.update({
where: { id: userId },
data: { walletBalance: { decrement: finalAmount } },
});
await tx.walletTransaction.create({
data: {
userId,
amount: finalAmount,
type: 'withdrawal',
status: 'completed',
description: `پرداخت مجدد سفارش ${order.trackingNumber || order.id}`,
},
});
if (Number(order.charityDonation) > 0) {
await tx.user.update({
where: { id: userId },
data: { charityDonationTotal: { increment: Number(order.charityDonation) } },
});
}
await tx.order.update({
where: { id: order.id },
data: {
status: 'processing',
paymentMethod: 'wallet',
},
});
});
if (user.mobile) {
const customerName = user.firstName || 'مشتری';
await this.smsService
.sendOrderConfirmation(
user.mobile,
customerName,
order.trackingNumber || order.id.slice(0, 8),
finalAmount.toLocaleString('fa-IR'),
)
.catch(() => {});
}
return {
success: true,
message: 'پرداخت با موفقیت از طریق کیف پول انجام شد.',
paymentMethod: 'wallet',
orderId: order.id,
};
}
if (selectedMethod === 'card') {
await this.prisma.order.update({
where: { id: order.id },
data: { paymentMethod: 'card', status: 'pending_payment' },
});
return {
success: true,
message: 'روش پرداخت به کارت به کارت تغییر یافت. لطفاً پس از واریز فیش را ثبت فرمایید.',
paymentMethod: 'card',
orderId: order.id,
};
}
// Default: Online Gateway (Zibal)
await this.prisma.order.update({
where: { id: order.id },
data: { paymentMethod: 'online', status: 'pending_payment' },
});
return {
success: true,
message: 'سفارش آماده پرداخت آنلاین است.',
paymentMethod: 'online',
orderId: order.id,
paymentInitiateRequired: true,
};
}
}
+19 -1
View File
@@ -58,7 +58,25 @@ export class PrismaService
)`,
`CREATE INDEX IF NOT EXISTS "sms_logs_phone_idx" ON "sms_logs"("phone")`,
`CREATE INDEX IF NOT EXISTS "sms_logs_status_idx" ON "sms_logs"("status")`,
`CREATE INDEX IF NOT EXISTS "sms_logs_created_at_idx" ON "sms_logs"("created_at")`
`CREATE INDEX IF NOT EXISTS "sms_logs_created_at_idx" ON "sms_logs"("created_at")`,
// 4. Product Reviews Table
`CREATE TABLE IF NOT EXISTS "product_reviews" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"product_id" UUID NOT NULL REFERENCES "products"("id") ON DELETE CASCADE,
"user_id" UUID REFERENCES "users"("id") ON DELETE SET NULL,
"user_name" VARCHAR(100) NOT NULL,
"user_phone" VARCHAR(20),
"rating" INTEGER NOT NULL DEFAULT 5,
"comment" TEXT NOT NULL,
"status" VARCHAR(20) NOT NULL DEFAULT 'PENDING',
"admin_reply" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
)`,
`CREATE INDEX IF NOT EXISTS "product_reviews_product_id_idx" ON "product_reviews"("product_id")`,
`CREATE INDEX IF NOT EXISTS "product_reviews_status_idx" ON "product_reviews"("status")`,
`CREATE INDEX IF NOT EXISTS "product_reviews_created_at_idx" ON "product_reviews"("created_at")`
];
for (const sql of ddlStatements) {
@@ -0,0 +1,25 @@
import { IsString, IsNotEmpty, IsInt, Min, Max, IsOptional } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class CreateReviewDto {
@ApiProperty({ description: 'امتیاز محصول از ۱ تا ۵', example: 5 })
@IsInt()
@Min(1)
@Max(5)
rating: number;
@ApiProperty({ description: 'متن دیدگاه یا نظر کاربر', example: 'کیفیت عالی و اثربخشی فوق‌العاده' })
@IsString()
@IsNotEmpty({ message: 'متن نظر نمی‌تواند خالی باشد' })
comment: string;
@ApiProperty({ description: 'نام نمایشی کاربر', required: false, example: 'امیر رضایی' })
@IsString()
@IsOptional()
userName?: string;
@ApiProperty({ description: 'شماره تماس کاربر', required: false, example: '09123456789' })
@IsString()
@IsOptional()
userPhone?: string;
}
@@ -0,0 +1,15 @@
import { IsString, IsIn, IsOptional } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class UpdateReviewDto {
@ApiProperty({ description: 'وضعیت بررسی نظر', enum: ['PENDING', 'APPROVED', 'REJECTED'], required: false })
@IsString()
@IsIn(['PENDING', 'APPROVED', 'REJECTED'])
@IsOptional()
status?: string;
@ApiProperty({ description: 'پاسخ کارشناس یا ادمین به نظر', required: false })
@IsString()
@IsOptional()
adminReply?: string;
}
+107
View File
@@ -0,0 +1,107 @@
import {
Controller,
Get,
Post,
Patch,
Delete,
Body,
Param,
Query,
UseGuards,
Req,
} from '@nestjs/common';
import { ReviewsService } from './reviews.service';
import { CreateReviewDto } from './dto/create-review.dto';
import { UpdateReviewDto } from './dto/update-review.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
@ApiTags('Reviews - نظرات و امتیازدهی محصولات')
@Controller()
export class ReviewsController {
constructor(private readonly reviewsService: ReviewsService) {}
/**
* Public / User: Submit a review for a product
*/
@Post('products/:productId/reviews')
@ApiOperation({ summary: 'ثبت دیدگاه جدید برای یک محصول' })
async createReview(
@Param('productId') productId: string,
@Body() dto: CreateReviewDto,
@Req() req: any,
) {
const userId = req.user?.id || undefined;
return this.reviewsService.createReview(productId, dto, userId);
}
/**
* Public: Get approved reviews for a product with pagination
*/
@Get('products/:productId/reviews')
@ApiOperation({ summary: 'دریافت نظرات تایید شده یک محصول' })
async getProductReviews(
@Param('productId') productId: string,
@Query('page') page?: string,
@Query('limit') limit?: string,
) {
return this.reviewsService.getProductReviews(
productId,
page ? parseInt(page, 10) : 1,
limit ? parseInt(limit, 10) : 10,
);
}
/**
* Admin: Get all reviews with status filter, search, and pagination
*/
@Get('admin/reviews')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin_Super', 'Admin_Shop', 'Admin_Support', 'Admin_Pharmacy')
@ApiBearerAuth()
@ApiOperation({ summary: 'دریافت تمام نظرات برای مدیریت ادمین' })
async getAdminReviews(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('status') status?: string,
@Query('search') search?: string,
@Query('productId') productId?: string,
) {
return this.reviewsService.getAdminReviews({
page: page ? parseInt(page, 10) : 1,
limit: limit ? parseInt(limit, 10) : 20,
status,
search,
productId,
});
}
/**
* Admin: Approve / Reject / Reply to a review
*/
@Patch('admin/reviews/:id')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin_Super', 'Admin_Shop', 'Admin_Support', 'Admin_Pharmacy')
@ApiBearerAuth()
@ApiOperation({ summary: 'تغییر وضعیت یا پاسخ به دیدگاه' })
async updateReviewStatus(
@Param('id') id: string,
@Body() dto: UpdateReviewDto,
) {
return this.reviewsService.updateReviewStatus(id, dto);
}
/**
* Admin: Delete a review
*/
@Delete('admin/reviews/:id')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin_Super', 'Admin_Shop')
@ApiBearerAuth()
@ApiOperation({ summary: 'حذف یک دیدگاه' })
async deleteReview(@Param('id') id: string) {
return this.reviewsService.deleteReview(id);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { ReviewsService } from './reviews.service';
import { ReviewsController } from './reviews.controller';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [PrismaModule],
controllers: [ReviewsController],
providers: [ReviewsService],
exports: [ReviewsService],
})
export class ReviewsModule {}
+228
View File
@@ -0,0 +1,228 @@
import { Injectable, NotFoundException, BadRequestException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateReviewDto } from './dto/create-review.dto';
import { UpdateReviewDto } from './dto/update-review.dto';
@Injectable()
export class ReviewsService {
private readonly logger = new Logger(ReviewsService.name);
constructor(private readonly prisma: PrismaService) {}
/**
* 1. Submit a new review for a product (User/Guest)
*/
async createReview(productId: string, dto: CreateReviewDto, userId?: string) {
const product = await this.prisma.product.findUnique({
where: { id: productId },
select: { id: true, nameFa: true, nameEn: true },
});
if (!product) {
throw new NotFoundException('محصول مورد نظر یافت نشد');
}
let resolvedName = dto.userName?.trim();
let resolvedPhone = dto.userPhone?.trim();
if (userId) {
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: { firstName: true, lastName: true, mobile: true },
});
if (user) {
if (!resolvedName) {
resolvedName = `${user.firstName || ''} ${user.lastName || ''}`.trim() || 'کاربر کنینا';
}
if (!resolvedPhone) {
resolvedPhone = user.mobile;
}
}
}
if (!resolvedName) {
resolvedName = 'کاربر مهمان';
}
const review = await this.prisma.productReview.create({
data: {
productId,
userId: userId || null,
userName: resolvedName,
userPhone: resolvedPhone || null,
rating: Math.max(1, Math.min(5, Number(dto.rating) || 5)),
comment: dto.comment.trim(),
status: 'PENDING',
},
});
return {
success: true,
message: 'دیدگاه شما با موفقیت ثبت شد و پس از بررسی و تایید کارشناسان در سایت نمایش داده می‌شود.',
data: review,
};
}
/**
* 2. Get approved reviews for a single product with pagination and rating statistics
*/
async getProductReviews(productId: string, page: number = 1, limit: number = 10) {
const skip = (Math.max(1, page) - 1) * limit;
const [reviews, total, aggregateRating] = await Promise.all([
this.prisma.productReview.findMany({
where: { productId, status: 'APPROVED' },
orderBy: { createdAt: 'desc' },
skip,
take: limit,
select: {
id: true,
userName: true,
rating: true,
comment: true,
adminReply: true,
createdAt: true,
},
}),
this.prisma.productReview.count({
where: { productId, status: 'APPROVED' },
}),
this.prisma.productReview.aggregate({
where: { productId, status: 'APPROVED' },
_avg: { rating: true },
_count: { rating: true },
}),
]);
const averageRating = aggregateRating._avg.rating
? Number(aggregateRating._avg.rating.toFixed(1))
: 5;
const totalReviews = aggregateRating._count.rating || 0;
return {
success: true,
data: reviews,
pagination: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
stats: {
averageRating,
totalReviews,
},
};
}
/**
* 3. Admin: Get all reviews with filters, search, and pagination
*/
async getAdminReviews(query: {
page?: number;
limit?: number;
status?: string;
search?: string;
productId?: string;
}) {
const page = Math.max(1, Number(query.page) || 1);
const limit = Math.max(1, Math.min(100, Number(query.limit) || 20));
const skip = (page - 1) * limit;
const where: any = {};
if (query.status && query.status !== 'ALL') {
where.status = query.status.toUpperCase();
}
if (query.productId) {
where.productId = query.productId;
}
if (query.search) {
const q = query.search.trim();
where.OR = [
{ userName: { contains: q, mode: 'insensitive' } },
{ userPhone: { contains: q, mode: 'insensitive' } },
{ comment: { contains: q, mode: 'insensitive' } },
{ product: { nameFa: { contains: q, mode: 'insensitive' } } },
];
}
const [reviews, total] = await Promise.all([
this.prisma.productReview.findMany({
where,
orderBy: { createdAt: 'desc' },
skip,
take: limit,
include: {
product: {
select: { id: true, nameFa: true, nameEn: true, slug: true, imageUrl: true },
},
user: {
select: { id: true, firstName: true, lastName: true, mobile: true },
},
},
}),
this.prisma.productReview.count({ where }),
]);
return {
success: true,
data: reviews,
pagination: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
/**
* 4. Admin: Moderate review (Approve / Reject / Reply)
*/
async updateReviewStatus(id: string, dto: UpdateReviewDto) {
const review = await this.prisma.productReview.findUnique({
where: { id },
});
if (!review) {
throw new NotFoundException('دیدگاه مورد نظر یافت نشد');
}
const updated = await this.prisma.productReview.update({
where: { id },
data: {
status: dto.status || review.status,
adminReply: dto.adminReply !== undefined ? dto.adminReply : review.adminReply,
},
});
return {
success: true,
message: 'وضعیت دیدگاه با موفقیت بروزرسانی شد',
data: updated,
};
}
/**
* 5. Admin: Delete review
*/
async deleteReview(id: string) {
const review = await this.prisma.productReview.findUnique({
where: { id },
});
if (!review) {
throw new NotFoundException('دیدگاه مورد نظر یافت نشد');
}
await this.prisma.productReview.delete({ where: { id } });
return {
success: true,
message: 'دیدگاه با موفقیت حذف شد',
};
}
}
+134
View File
@@ -0,0 +1,134 @@
export const DEFAULT_UI_TEXTS: Record<string, string> = {
// === Catalog & Maintenance Mode ===
"maintenance_mode": "false",
"maintenance_title": "سامانه در حال به‌روزرسانی و ارتقای فنی است",
"maintenance_desc": "وب‌سایت رسمی کنینا ایران جهت ارتقای زیرساخت‌ها و بهبود عملکرد به صورت موقت در دست به‌روزرسانی است. از شکیبایی شما سپاسگزاریم.",
"maintenance_eta": "زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده",
"maintenance_contact_phone": "۰۲۱-۸۸۸۸۸۸۸۸",
"maintenance_badge": "سامانه در حال ارتقا",
"catalog_mode": "false",
"catalog_hide_prices": "false",
"catalog_disable_cart": "false",
"catalog_disable_checkout": "false",
// === Header / Navigation ===
"shipping_notice": "ارسال رایگان برای سفارش‌های بالای ۱۵۰ هزار تومان — گارانتی اصالت کنینا آلمان",
"brand_name_fa": "کنینا ایران",
"brand_subtitle": "نمایندگی رسمی مکمل‌های دارویی کنینا آلمان",
"nav_solutions": "راهکارهای درمانی",
"nav_products": "محصولات تخصصی",
"nav_wiki": "دانشنامه علمی",
"nav_blog": "مجله سلامت پت",
"nav_pet_profiles": "شناسنامه پت‌ها",
"nav_search_placeholder": "جستجوی محصولات، علائم بالینی، مقالات سلامت...",
"nav_search_button": "جستجو",
"nav_pet_switcher_title": "تغییر پت یا مدیریت پرونده سلامت",
"nav_register_pet": "ثبت همدم (Pet) جدید",
"nav_wallet_orders": "کیف پول و سفارشات",
"nav_logout": "خروج از حساب",
"nav_login": "ورود / ثبت‌نام",
"nav_cart": "سبد خرید",
// === Hero Section ===
"hero_badge": "از ۱۹۸۴ در خدمت سلامت حیوانات",
"hero_title": "تخصص آلمانی در خدمت سلامت پت‌های خانگی",
"hero_desc": "از سال ۱۹۸۴، شرکت Canina pharma GmbH در آلمان با بهره‌گیری از مواد اولیه ارگانیک و پیشرفته‌ترین فرمولاسیون دامپزشکی، استاندارد طلایی مکمل‌های بالینی را ارائه می‌دهد.",
"hero_btn_advisor": "دستیار هوشمند سلامت پت",
"hero_btn_products": "مشاهده محصولات",
"hero_image_badge": "سرآمد علمی در پزشکی پت‌ها",
"hero_image_title": "مکمل‌های تایید شده دامپزشکی با گواهی IFS",
"hero_quality_standard": "استاندارد کیفی آلمان (IFS & HACCP)",
"hero_image_url": "/assets/images/hero-section-image.png",
"hero_stat_founded": "۱۹۸۴ سال تأسیس",
"hero_stat_agencies": "نمایندگی‌های فعال جهانی",
"hero_stat_german_formula": "۱۰۰٪ فرمولاسیون آلمانی",
// === Smart Advisor ===
"advisor_badge": "تکنولوژی پایش هوشمند",
"advisor_title": "دستیار هوشمند سلامت کنینا",
"advisor_subtitle": "تنها با چند کلیک شناسنامه سلامت پت خود را تکمیل کرده و مشاوره تخصصی دریافت کنید",
"advisor_step1_title": "گام اول: مشخصات و هویت پت",
"advisor_step1_desc": "نام و نژاد همدم دوست‌داشتنی شما چیست؟",
"advisor_pet_name_label": "نام پت",
"advisor_pet_name_placeholder": "مثلاً لوسی، تدی، ببری...",
"advisor_pet_breed_label": "نژاد پت",
"advisor_pet_breed_placeholder": "مثلاً ژرمن شپرد، پرشین، هاسکی...",
"advisor_submit_btn": "ثبت و ادامه به مرحله بعد",
"advisor_validation_warning": "لطفاً ابتدا نام و نژاد پت را وارد نمایید.",
"advisor_step2_title": "گام دوم: پایش فیزیکی و سطح فعالیت",
"advisor_step2_desc": "اطلاعات فیزیکی به محاسبه دقیق دوز مصرفی کمک می‌کند",
"advisor_age_label": "سن (سال)",
"advisor_weight_label": "وزن تقریبی (کیلوگرم)",
"advisor_activity_label": "سطح فعالیت روزانه",
"advisor_back": "مرحله قبل",
"advisor_next_final": "ادامه به مرحله نهایی",
"advisor_step3_title": "گام آخر: سوابق پزشکی و نیازهای ویژه",
"advisor_step3_desc": "در صورت وجود هرگونه حساسیت یا نیاز درمانی آن را مشخص کنید",
"advisor_complete": "صدور شناسنامه و دریافت رژیم سلامتی",
// === Featured Products ===
"featured_badge": "انتخاب نخست دامپزشکان و کلینیک‌ها",
"featured_title_line1": "محصولات برگزیده و راهکارهای",
"featured_title_line2": "درمان تخصصی بالینی",
"featured_desc": "مکمل‌های تخصصی دارویی کنینا با بالاترین درجه خلوص مواد اولیه در آلمان فرآوری شده‌اند.",
"featured_view_all": "مشاهده کاتالوگ کامل محصولات",
"product_view_details": "مشاهده جزئیات و خرید",
"featured_no_products_title": "محصولی یافت نشد",
"featured_no_products_desc": "در حال حاضر محصولی در این دسته موجود نمی‌باشد.",
// === Videos & Media ===
"videos_badge": "ویدئوهای آموزشی دامپزشکی",
"videos_title": "توصیه‌های بالینی و ویدئویی",
"videos_title_highlight": "متخصصان و دامپزشکان",
"videos_desc": "مشاهده نحوه مصرف صحیح، عملکرد بیولوژیکی و پاسخ به پرسش‌های پرتکرار سرپرستان پت.",
"videos_view_all": "مشاهده تمامی ویدئوها",
// === Navigation Cards ===
"nav_card_shop_title": "داروخانه تخصصی مکمل‌ها",
"nav_card_shop_desc": "دسته‌بندی جامع بر اساس نیازهای مفاصل، پوست و مو، رشد، گوارش و ایمنی.",
"nav_card_shop_cta": "ورود به فروشگاه",
"nav_card_wiki_title": "دانشنامه علمی و مقالات",
"nav_card_wiki_desc": "جدیدترین مقالات تخصصی سلامت و تغذیه حیوانات خانگی با ترجمه متون علمی آلمان.",
"nav_card_wiki_cta": "مطالعه دانشنامه",
// === About Us ===
"about_label": "درباره برند کنینا",
"about_title": "چرا کنینا آلمان انتخاب اول متخصصان است؟",
"about_item1_title": "مواد اولیه ۱۰۰٪ طبیعی",
"about_item1_desc": "استفاده از عصاره صدف سبز نیوزیلند و املاح معدنی ارگانیک با جذب زیستی بالا.",
"about_item2_title": "فاقد افزودنی‌های مضر",
"about_item2_desc": "بدون رنگ‌های مصنوعی، نگهدارنده‌های شیمیایی و قندهای افزودنی.",
"about_item3_title": "استاندارد دارویی اروپا",
"about_item3_desc": "تولید مطابق استانداردهای سخت‌گیرانه داروسازی آلمان IFS و HACCP.",
// === CTA Section ===
"cta_title": "می‌خواهید بدانید کدام محصول برای پت شما مناسب‌تر است؟",
"cta_desc": "با استفاده از دستیار هوشمند سلامت یا مشاوره رایگان با دامپزشکان ما، بهترین برنامه مکمل را انتخاب کنید.",
"cta_btn_primary": "شروع ارزیابی هوشمند پت",
"cta_btn_secondary": "مشاوره با دامپزشک",
// === Footer ===
"footer_brand_title": "کنینا ایران (Canina Iran)",
"footer_brand_subtitle": "نمایندگی رسمی شرکت Canina pharma GmbH آلمان",
"footer_brand_desc": "تولیدکننده و توزیع‌کننده برتر مکمل‌های دارویی و بهداشتی با بیش از ۴۰ سال سابقه در آلمان و عرضه رسمی در ایران.",
"footer_links_title": "دسترسی سریع",
"footer_link_products": "کاتالوگ محصولات",
"footer_link_blog": "مجله سلامت و مقالات",
"footer_link_profiles": "شناسنامه و پرونده پت‌ها",
"footer_link_wiki": "دانشنامه دارویی",
"footer_link_b2b": "پرتال همکاری و دامپزشکان",
"footer_contact_title": "ارتباط با پشتیبانی",
"footer_phone_label": "تلفن تماس",
"footer_phone": "۰۲۱-۸۸۸۸۸۸۸۸",
"footer_email_label": "پست الکترونیک",
"footer_email": "info@canina.ir",
"footer_address_label": "نشانی مرکزی",
"footer_address": "تهران، خیابان ولیعصر، برج تجاری کنینا",
"footer_auth_title": "ضمانت اصالت کالا",
"footer_auth_desc": "کلیه محصولات دارای برچسب اصالت و مجوز واردات رسمی می‌باشند.",
"footer_auth_badge": "تضمین ۱۰۰٪ اصالت کالا",
"footer_copyright": "تمامی حقوق مادی و معنوی این وب‌سایت متعلق به شرکت کنینا ایران می‌باشد.",
"footer_about": "درباره ما",
"footer_contact": "تماس با ما",
"footer_privacy": "حریم خصوصی و قوانین",
};
+33 -2
View File
@@ -1,7 +1,8 @@
import { Injectable } from '@nestjs/common';
import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService, SmsLogQuery } from '../common/services/sms.service';
import { DEFAULT_UI_TEXTS } from './default-ui-texts';
export class ScientificTermData {
term?: string;
@@ -10,13 +11,43 @@ export class ScientificTermData {
}
@Injectable()
export class SettingsService {
export class SettingsService implements OnModuleInit {
private readonly logger = new Logger(SettingsService.name);
constructor(
private prisma: PrismaService,
private smsService: SmsService,
) {}
async onModuleInit() {
await this.seedDefaultUiTexts();
}
async seedDefaultUiTexts() {
try {
const existing = await this.prisma.uiText.findMany({ select: { key: true } });
const existingKeys = new Set(existing.map((e) => e.key));
const missingEntries = Object.entries(DEFAULT_UI_TEXTS).filter(
([key]) => !existingKeys.has(key),
);
if (missingEntries.length > 0) {
await this.prisma.uiText.createMany({
data: missingEntries.map(([key, value]) => ({ key, value })),
skipDuplicates: true,
});
this.logger.log(`[SettingsService] Auto-seeded ${missingEntries.length} default UI texts.`);
}
} catch (err: any) {
this.logger.warn(`[SettingsService] Failed to auto-seed UI texts: ${err?.message || err}`);
}
}
async getUiTexts() {
// Ensure default texts exist
await this.seedDefaultUiTexts();
const [uiTexts, settings] = await Promise.all([
this.prisma.uiText.findMany(),
this.prisma.setting.findMany(),
@@ -17,6 +17,7 @@ const menuGroups = [
{ icon: ShoppingCart, label: 'سفارشات', path: '/orders' },
{ icon: Receipt, label: 'تراکنش‌ها و لاگ پرداخت', path: '/transactions' },
{ icon: Package, label: 'محصولات', path: '/products' },
{ icon: MessageSquare, label: 'نظرات محصولات', path: '/reviews' },
{ icon: FolderTree, label: 'دسته‌بندی‌ها', path: '/categories' },
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
{ icon: Sparkles, label: 'مشاور هوشمند', path: '/smart-advisor' },
+14 -14
View File
@@ -468,30 +468,30 @@ export default function Orders() {
const charityAmt = Number(order.charityDonation || 0);
return (
<tr key={order.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6 font-bold text-purple-600 font-mono" dir="ltr">
<div>{toPersianDigits(displayCode)}</div>
<div className="flex flex-wrap gap-1 mt-1.5" dir="rtl">
<span className={`text-[9px] font-black px-2 py-0.5 rounded-md border flex items-center gap-1 ${payInfo.color}`}>
<CreditCard className="w-2.5 h-2.5" />
{payInfo.label}
<tr key={order.id} className="hover:bg-gray-50/50 transition-colors font-vazir">
<td className="py-4 px-6 font-vazir" dir="rtl">
<div className="font-black text-purple-700 text-sm tracking-wide font-vazir">{toPersianDigits(displayCode)}</div>
<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}`}>
<CreditCard className="w-3 h-3 shrink-0" />
<span className="font-vazir">{payInfo.label}</span>
</span>
{order.isRefill && (
<span className="text-[9px] font-black px-2 py-0.5 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200">
<span className="text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200 shadow-sm">
تمدید ۵٪-
</span>
)}
{charityAmt > 0 && (
<span className="text-[9px] font-black px-2 py-0.5 rounded-md bg-rose-50 text-rose-700 border border-rose-200 flex items-center gap-1">
<Heart className="w-2.5 h-2.5 fill-rose-500 text-rose-500" />
مهربانی: {toPersianDigits(charityAmt.toLocaleString())} ت
<span className="text-[10px] font-bold font-vazir px-2 py-0.5 rounded-md bg-rose-50 text-rose-700 border border-rose-200 shadow-sm flex items-center gap-1">
<Heart className="w-3 h-3 fill-rose-500 text-rose-500 shrink-0" />
<span className="font-vazir">مهربانی: {toPersianDigits(charityAmt.toLocaleString())} ت</span>
</span>
)}
</div>
</td>
<td className="py-4 px-6">
<div className="font-bold text-gray-900">{customerName}</div>
<div className="text-xs text-gray-400 font-medium" dir="ltr">{toPersianDigits(order.user?.phone || order.user?.mobile || '')}</div>
<td className="py-4 px-6 font-vazir">
<div className="font-bold text-gray-900 font-vazir">{customerName}</div>
<div className="text-xs text-gray-400 font-medium font-vazir" dir="ltr">{toPersianDigits(order.user?.phone || order.user?.mobile || '')}</div>
</td>
<td className="py-4 px-6 font-black text-gray-900">
{toPersianDigits(totalAmt.toLocaleString())} <span className="text-xs font-normal">تومان</span>
+493
View File
@@ -0,0 +1,493 @@
import { useState, useEffect, useCallback } from 'react';
import {
MessageSquare,
Search,
Star,
CheckCircle2,
XCircle,
Trash2,
Reply,
Loader2,
ExternalLink,
ChevronLeft,
ChevronRight,
Clock,
User,
Package,
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import api from '../services/api';
import Spinner from '../components/ui/Spinner';
interface ProductReview {
id: string;
productId: string;
userId?: string;
userName: string;
userPhone?: string;
rating: number;
comment: string;
status: 'PENDING' | 'APPROVED' | 'REJECTED';
adminReply?: string;
createdAt: string;
product?: {
id: string;
nameFa: string;
nameEn: string;
slug: string;
imageUrl: string;
};
user?: {
id: string;
firstName: string;
lastName: string;
mobile: string;
};
}
const toPersianDigits = (n: string | number): string => {
if (n === null || n === undefined) return '';
const farsiDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return n.toString().replace(/\d/g, (x) => farsiDigits[parseInt(x)]);
};
export default function Reviews() {
const [reviews, setReviews] = useState<ProductReview[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [page, setPage] = useState(1);
const [limit] = useState(15);
const [totalPages, setTotalPages] = useState(1);
const [totalCount, setTotalCount] = useState(0);
const [statusFilter, setStatusFilter] = useState('ALL');
const [search, setSearch] = useState('');
const [processingId, setProcessingId] = useState<string | null>(null);
// Reply Modal State
const [replyingReview, setReplyingReview] = useState<ProductReview | null>(null);
const [replyText, setReplyText] = useState('');
const [isSavingReply, setIsSavingReply] = useState(false);
const fetchReviews = useCallback(async () => {
try {
setIsLoading(true);
const params = new URLSearchParams();
params.append('page', page.toString());
params.append('limit', limit.toString());
if (statusFilter && statusFilter !== 'ALL') params.append('status', statusFilter);
if (search.trim()) params.append('search', search.trim());
const res = await api.get(`/admin/reviews?${params.toString()}`);
if (res.data?.success) {
setReviews(res.data.data || []);
setTotalPages(res.data.pagination?.totalPages || 1);
setTotalCount(res.data.pagination?.total || 0);
}
} catch (err: any) {
console.error('Failed to fetch reviews:', err);
} finally {
setIsLoading(false);
}
}, [page, limit, statusFilter, search]);
useEffect(() => {
fetchReviews();
}, [fetchReviews]);
const handleUpdateStatus = async (id: string, newStatus: 'APPROVED' | 'REJECTED') => {
try {
setProcessingId(id);
const res = await api.patch(`/admin/reviews/${id}`, { status: newStatus });
if (res.data?.success) {
toast.success(newStatus === 'APPROVED' ? 'دیدگاه تایید شد و در سایت نمایش می‌یابد.' : 'دیدگاه رد شد.');
setReviews((prev) =>
prev.map((r) => (r.id === id ? { ...r, status: newStatus } : r))
);
}
} catch (err: any) {
console.error('Error updating review status:', err);
} finally {
setProcessingId(null);
}
};
const handleOpenReplyModal = (review: ProductReview) => {
setReplyingReview(review);
setReplyText(review.adminReply || '');
};
const handleSaveReply = async () => {
if (!replyingReview) return;
try {
setIsSavingReply(true);
const res = await api.patch(`/admin/reviews/${replyingReview.id}`, {
adminReply: replyText.trim(),
status: 'APPROVED', // Auto-approve when replied
});
if (res.data?.success) {
toast.success('پاسخ با موفقیت ثبت شد.');
setReviews((prev) =>
prev.map((r) =>
r.id === replyingReview.id
? { ...r, adminReply: replyText.trim(), status: 'APPROVED' }
: r
)
);
setReplyingReview(null);
}
} catch (err: any) {
console.error('Error saving admin reply:', err);
} finally {
setIsSavingReply(false);
}
};
const handleDelete = async (id: string) => {
if (!window.confirm('آیا از حذف این دیدگاه اطمینان دارید؟')) return;
try {
setProcessingId(id);
const res = await api.delete(`/admin/reviews/${id}`);
if (res.data?.success) {
toast.success('دیدگاه با موفقیت حذف شد.');
setReviews((prev) => prev.filter((r) => r.id !== id));
setTotalCount((c) => Math.max(0, c - 1));
}
} catch (err: any) {
console.error('Error deleting review:', err);
} finally {
setProcessingId(null);
}
};
return (
<div className="space-y-6 font-vazir text-right" dir="rtl">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
<MessageSquare className="w-6 h-6 text-purple-600" />
مدیریت نظرات و دیدگاه‌ها
</h2>
<p className="text-gray-500 font-medium mt-1">
بررسی امتیازات، تایید یا رد نظرات خریداران و پاسخ‌دهی کارشناسان به دیدگاه‌ها
</p>
</div>
{/* Search */}
<div className="relative w-full sm:w-80">
<Search className="w-5 h-5 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
<input
type="text"
placeholder="جستجو (نام خریدار، متن نظر، نام محصول)..."
className="pl-4 pr-10 py-2.5 border border-gray-200 rounded-xl outline-none focus:ring-2 focus:ring-purple-500 w-full font-medium text-sm bg-white"
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
/>
</div>
</div>
{/* Filter Tabs */}
<div className="flex flex-wrap items-center gap-2 pt-1 border-b border-gray-200 pb-3">
{[
{ label: 'همه دیدگاه‌ها', value: 'ALL', count: totalCount },
{ label: 'در انتظار بررسی', value: 'PENDING', color: 'text-amber-700 bg-amber-50 border-amber-200' },
{ label: 'تایید شده', value: 'APPROVED', color: 'text-emerald-700 bg-emerald-50 border-emerald-200' },
{ label: 'رد شده', value: 'REJECTED', color: 'text-rose-700 bg-rose-50 border-rose-200' },
].map((tab) => {
const isSelected = statusFilter === tab.value;
return (
<button
key={tab.value}
onClick={() => {
setStatusFilter(tab.value);
setPage(1);
}}
className={`px-4 py-2 rounded-xl text-xs font-bold transition-all border ${
isSelected
? 'bg-purple-600 text-white border-purple-600 shadow-sm'
: 'bg-white text-gray-600 border-gray-200 hover:bg-gray-50'
}`}
>
{tab.label}
</button>
);
})}
</div>
{/* Reviews Table */}
<div className="bg-white border border-gray-200 rounded-2xl shadow-sm overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-right border-collapse">
<thead>
<tr className="bg-gray-50/80 border-b border-gray-200 text-xs font-black text-gray-500">
<th className="py-4 px-6">محصول</th>
<th className="py-4 px-6">نویسنده دیدگاه</th>
<th className="py-4 px-6">امتیاز</th>
<th className="py-4 px-6">متن نظر و پاسخ</th>
<th className="py-4 px-6">تاریخ</th>
<th className="py-4 px-6">وضعیت</th>
<th className="py-4 px-6 text-center">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100 text-sm">
{isLoading ? (
<tr>
<td colSpan={7} className="py-16 text-center">
<Spinner size="lg" />
<p className="text-gray-400 font-bold mt-2 text-xs">در حال بارگذاری نظرات...</p>
</td>
</tr>
) : reviews.length === 0 ? (
<tr>
<td colSpan={7} className="py-16 text-center text-gray-400 font-bold">
هیچ دیدگاهی در این بخش یافت نشد.
</td>
</tr>
) : (
reviews.map((review) => {
const isProcessing = processingId === review.id;
const date = new Date(review.createdAt);
return (
<tr key={review.id} className="hover:bg-gray-50/50 transition-colors">
{/* Product */}
<td className="py-4 px-6">
<div className="flex items-center gap-3">
{review.product?.imageUrl ? (
<img
src={review.product.imageUrl}
alt=""
className="w-11 h-11 object-contain rounded-lg border border-gray-100 p-1 bg-white shrink-0"
/>
) : (
<div className="w-11 h-11 bg-gray-100 rounded-lg flex items-center justify-center text-gray-400 shrink-0">
<Package className="w-5 h-5" />
</div>
)}
<div className="min-w-0">
<div className="font-bold text-gray-900 line-clamp-1 text-xs sm:text-sm">
{review.product?.nameFa || 'محصول کنینا'}
</div>
<div className="text-[11px] text-gray-400 font-medium line-clamp-1" dir="ltr">
{review.product?.nameEn}
</div>
</div>
</div>
</td>
{/* Author */}
<td className="py-4 px-6">
<div className="font-bold text-gray-900 flex items-center gap-1.5">
<User className="w-3.5 h-3.5 text-gray-400 shrink-0" />
<span>{review.userName}</span>
</div>
{review.userPhone && (
<div className="text-xs text-gray-400 font-mono mt-0.5" dir="ltr">
{toPersianDigits(review.userPhone)}
</div>
)}
</td>
{/* Rating */}
<td className="py-4 px-6">
<div className="flex items-center gap-1">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
className={`w-4 h-4 ${
i < review.rating
? 'fill-amber-400 text-amber-400'
: 'text-gray-200'
}`}
/>
))}
<span className="font-bold text-xs text-gray-700 mr-1.5 font-vazir">
{toPersianDigits(review.rating)} از ۵
</span>
</div>
</td>
{/* Comment & Admin Reply */}
<td className="py-4 px-6 max-w-xs md:max-w-md">
<div className="text-gray-800 text-xs sm:text-sm leading-relaxed whitespace-pre-wrap">
{review.comment}
</div>
{review.adminReply && (
<div className="mt-2 p-2.5 bg-purple-50/70 border-r-2 border-purple-500 rounded-lg text-xs text-purple-900 space-y-1">
<span className="font-bold block text-purple-700 flex items-center gap-1">
<Reply className="w-3 h-3 rotate-180" />
پاسخ کنینا:
</span>
<p className="leading-relaxed">{review.adminReply}</p>
</div>
)}
</td>
{/* Date */}
<td className="py-4 px-6 text-gray-500 text-xs font-bold">
<div>{toPersianDigits(date.toLocaleDateString('fa-IR'))}</div>
<div className="text-[10px] text-gray-400">
{toPersianDigits(date.toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' }))}
</div>
</td>
{/* Status */}
<td className="py-4 px-6">
{review.status === 'PENDING' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-amber-50 text-amber-700 border border-amber-200">
<Clock className="w-3 h-3" />
در انتظار بررسی
</span>
)}
{review.status === 'APPROVED' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-50 text-emerald-700 border border-emerald-200">
<CheckCircle2 className="w-3 h-3" />
تایید شده
</span>
)}
{review.status === 'REJECTED' && (
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-rose-50 text-rose-700 border border-rose-200">
<XCircle className="w-3 h-3" />
رد شده
</span>
)}
</td>
{/* Actions */}
<td className="py-4 px-6 text-center">
<div className="flex items-center justify-center gap-1.5">
{review.status !== 'APPROVED' && (
<button
disabled={isProcessing}
onClick={() => handleUpdateStatus(review.id, 'APPROVED')}
title="تایید دیدگاه"
className="p-1.5 text-emerald-600 hover:bg-emerald-50 rounded-lg transition-colors border border-emerald-200"
>
<CheckCircle2 className="w-4 h-4" />
</button>
)}
{review.status !== 'REJECTED' && (
<button
disabled={isProcessing}
onClick={() => handleUpdateStatus(review.id, 'REJECTED')}
title="رد دیدگاه"
className="p-1.5 text-rose-600 hover:bg-rose-50 rounded-lg transition-colors border border-rose-200"
>
<XCircle className="w-4 h-4" />
</button>
)}
<button
disabled={isProcessing}
onClick={() => handleOpenReplyModal(review)}
title="پاسخ به دیدگاه"
className="p-1.5 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors border border-purple-200"
>
<Reply className="w-4 h-4" />
</button>
<button
disabled={isProcessing}
onClick={() => handleDelete(review.id)}
title="حذف دیدگاه"
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="p-4 border-t border-gray-100 flex items-center justify-between">
<span className="text-xs text-gray-500 font-bold">
صفحه {toPersianDigits(page)} از {toPersianDigits(totalPages)}
</span>
<div className="flex items-center gap-2">
<button
disabled={page <= 1 || isLoading}
onClick={() => setPage((p) => Math.max(1, p - 1))}
className="p-2 border border-gray-200 rounded-xl hover:bg-gray-50 disabled:opacity-40 disabled:pointer-events-none transition-all text-xs font-bold flex items-center gap-1"
>
<ChevronRight className="w-4 h-4" />
<span>قبلی</span>
</button>
<button
disabled={page >= totalPages || isLoading}
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
className="p-2 border border-gray-200 rounded-xl hover:bg-gray-50 disabled:opacity-40 disabled:pointer-events-none transition-all text-xs font-bold flex items-center gap-1"
>
<span>بعدی</span>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</div>
)}
</div>
{/* Reply Modal */}
{replyingReview && (
<div className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4">
<div className="bg-white rounded-2xl p-6 w-full max-w-lg shadow-2xl space-y-4 font-vazir animate-in fade-in zoom-in-95 duration-150" dir="rtl">
<div className="flex items-center justify-between border-b border-gray-100 pb-3">
<h3 className="text-base font-black text-gray-900 flex items-center gap-2">
<Reply className="w-5 h-5 text-purple-600" />
پاسخ به دیدگاه {replyingReview.userName}
</h3>
<button
onClick={() => setReplyingReview(null)}
className="p-1 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
>
✕
</button>
</div>
<div className="p-3 bg-gray-50 rounded-xl border border-gray-100 text-xs text-gray-600 space-y-1">
<span className="font-bold text-gray-700 block">متن دیدگاه خریدار:</span>
<p className="leading-relaxed whitespace-pre-wrap">{replyingReview.comment}</p>
</div>
<div>
<label className="block text-xs font-bold text-gray-700 mb-1.5">
متن پاسخ کارشناس رسمی کنینا:
</label>
<textarea
rows={4}
value={replyText}
onChange={(e) => setReplyText(e.target.value)}
placeholder="پاسخ و توضیحات رسمی برای نمایش در زیر نظر..."
className="w-full p-3 border border-gray-200 rounded-xl text-sm font-medium outline-none focus:ring-2 focus:ring-purple-500 resize-none leading-relaxed"
/>
</div>
<div className="flex items-center justify-end gap-3 pt-2">
<button
type="button"
onClick={() => setReplyingReview(null)}
className="px-4 py-2.5 text-xs font-bold text-gray-600 hover:bg-gray-100 rounded-xl transition-all"
>
انصراف
</button>
<button
type="button"
disabled={isSavingReply}
onClick={handleSaveReply}
className="px-5 py-2.5 text-xs font-bold bg-purple-600 hover:bg-purple-700 text-white rounded-xl shadow-lg shadow-purple-600/20 transition-all flex items-center gap-1.5"
>
{isSavingReply && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
<span>ثبت و انتشار پاسخ</span>
</button>
</div>
</div>
</div>
)}
</div>
);
}
+12 -3
View File
@@ -15,7 +15,8 @@ const PAGE_TABS = [
const GROUPS: Record<string, string[]> = {
"تنظیمات کاتالوگ‌مود و حالت صیانت": [
"maintenance_mode", "catalog_mode", "catalog_hide_prices", "catalog_disable_cart", "catalog_disable_checkout",
"maintenance_mode", "maintenance_title", "maintenance_desc", "maintenance_eta", "maintenance_contact_phone", "maintenance_badge",
"catalog_mode", "catalog_hide_prices", "catalog_disable_cart", "catalog_disable_checkout",
],
"هدر و ناوبری": [
"shipping_notice", "brand_name_fa", "brand_subtitle",
@@ -94,8 +95,16 @@ const KEY_LABELS_FA: Record<string, string> = {
featured_title_line1: "عنوان بخش محصولات برگزیده",
cta_title: "عنوان کادر دعوت به اقدام (CTA)",
footer_copyright: "متن کپی‌رایت فوتر",
maintenance_mode: "حالت تعمیرات و صیانت سایت",
catalog_mode: "حالت کاتالوگ‌مود",
maintenance_mode: "حالت تعمیرات و صیانت سایت (غیرفعال‌سازی موقت دسترسی عموم)",
maintenance_title: "عنوان صفحه حالت تعمیرات",
maintenance_desc: "توضیحات و پیام اطلاع‌رسانی حالت تعمیرات",
maintenance_eta: "متن زمان تقریبی بازگشایی سامانه",
maintenance_contact_phone: "شماره تلفن تماس اضطراری در صفحه تعمیرات",
maintenance_badge: "بج بالای صفحه تعمیرات",
catalog_mode: "حالت کاتالوگ‌مود (غیرفعال‌سازی خرید مستقیم)",
catalog_hide_prices: "مخفی‌سازی قیمت محصولات در حالت کاتالوگ",
catalog_disable_cart: "غیرفعال‌سازی سبد خرید در حالت کاتالوگ",
catalog_disable_checkout: "غیرفعال‌سازی صفحه تسویه‌حساب در حالت کاتالوگ",
};
const GROUP_PAGE_MAP: Record<string, string> = {
@@ -37,6 +37,7 @@ const SmsSettingsPage = lazy(() => import('../pages/SmsSettingsPage'));
const SslSettingsPage = lazy(() => import('../pages/SslSettingsPage'));
const Transactions = lazy(() => import('../pages/Transactions'));
const Tickets = lazy(() => import('../pages/Tickets'));
const Reviews = lazy(() => import('../pages/Reviews'));
export interface AdminRouteConfig {
path: string;
@@ -86,6 +87,7 @@ export const router = createBrowserRouter([
{ path: 'wholesale/*', element: <WholesaleApplications /> },
{ path: 'contact/*', element: <ContactSubmissions /> },
{ path: 'tickets/*', element: <Tickets /> },
{ path: 'reviews/*', element: <Reviews /> },
],
},
],
@@ -12,7 +12,9 @@ import {
ArrowRight,
Heart,
PlusCircle,
Copy
Copy,
Phone,
AlertCircle
} from "lucide-react";
import { toPersian, cn } from "../lib/utils";
import { PRODUCTS } from "../lib/data/products";
@@ -195,6 +197,44 @@ export default function CheckoutPage() {
}
};
const getText = useSettingsStore(state => state.getText);
const isCatalogMode = getText('catalog_mode', 'false') === 'true';
const isCatalogDisableCheckout = getText('catalog_disable_checkout', 'false') === 'true';
const isCheckoutDisabled = isCatalogMode || isCatalogDisableCheckout;
if (isCheckoutDisabled) {
return (
<div className="min-h-[70vh] bg-medical-gray-50 flex items-center justify-center p-6 text-center font-vazir" dir="rtl">
<div className="max-w-md bg-white border border-medical-gray-200 rounded-3xl p-8 shadow-xl space-y-6">
<div className="w-16 h-16 bg-amber-50 text-amber-600 rounded-2xl flex items-center justify-center mx-auto">
<AlertCircle className="w-8 h-8" />
</div>
<h2 className="text-xl font-black text-medical-gray-900">
امکان ثبت سفارش آنلاین موقتاً غیرفعال است
</h2>
<p className="text-xs sm:text-sm text-medical-gray-600 font-bold leading-relaxed">
سامانه در حال حاضر در حالت کاتالوگ قرار دارد. جهت استعلام قیمت و دریافت مشاوره تخصصی می‌توانید با کارشناسان ما تماس بگیرید.
</p>
<div className="flex flex-col sm:flex-row gap-3 pt-2">
<a
href="tel:02188888888"
className="flex-1 px-4 py-3 bg-canina-blue hover:bg-canina-dark text-white rounded-xl text-xs font-black transition-all shadow-md flex items-center justify-center gap-2"
>
<Phone className="w-4 h-4" />
<span>تماس با پشتیبانی</span>
</a>
<button
onClick={() => router.push('/shop')}
className="flex-1 px-4 py-3 bg-medical-gray-100 hover:bg-medical-gray-200 text-medical-gray-700 rounded-xl text-xs font-bold transition-all"
>
مشاهده کاتالوگ
</button>
</div>
</div>
</div>
);
}
if (items.length === 0) {
return (
<div className="min-h-screen bg-medical-gray-50 flex items-center justify-center p-6" dir="rtl">
+17 -12
View File
@@ -86,6 +86,9 @@ export default function Header({
const { pets, activePetId, setActivePet } = usePetStore();
const { isLoggedIn, logout, profile } = useUserStore();
const getText = useSettingsStore(state => state.getText);
const isCatalogMode = getText('catalog_mode', 'false') === 'true';
const isCatalogDisableCart = getText('catalog_disable_cart', 'false') === 'true';
const isCartDisabled = isCatalogMode || isCatalogDisableCart;
useEffect(() => {
const loadNavFilters = async () => {
@@ -305,18 +308,20 @@ export default function Header({
)}
{/* Shopping Cart Button */}
<button
onClick={onCartOpen}
className="relative px-3.5 py-2 bg-canina-blue text-white rounded-xl text-xs font-black hover:bg-medical-gray-900 transition-all flex items-center gap-2 shadow-sm"
>
<ShoppingBag className="w-4 h-4" />
<span className="hidden sm:inline">سبد خرید</span>
{isMounted && getTotalItems() > 0 && (
<span className="w-5 h-5 bg-canina-gold text-canina-dark rounded-full text-[10px] font-black flex items-center justify-center">
{getTotalItems()}
</span>
)}
</button>
{!isCartDisabled && (
<button
onClick={onCartOpen}
className="relative px-3.5 py-2 bg-canina-blue text-white rounded-xl text-xs font-black hover:bg-medical-gray-900 transition-all flex items-center gap-2 shadow-sm"
>
<ShoppingBag className="w-4 h-4" />
<span className="hidden sm:inline">سبد خرید</span>
{isMounted && getTotalItems() > 0 && (
<span className="w-5 h-5 bg-canina-gold text-canina-dark rounded-full text-[10px] font-black flex items-center justify-center">
{getTotalItems()}
</span>
)}
</button>
)}
</div>
</div>
@@ -1,8 +1,21 @@
"use client";
import React from "react";
import { Wrench, Phone, ShieldCheck } from "lucide-react";
import { Wrench, Phone, ShieldCheck, Clock } from "lucide-react";
import { useSettingsStore } from "../lib/store/settingsStore";
export default function MaintenancePage() {
const getText = useSettingsStore((state) => state.getText);
const title = getText("maintenance_title", "سامانه در حال به‌روزرسانی و ارتقای فنی است");
const desc = getText(
"maintenance_desc",
"وب‌سایت رسمی کنینا ایران جهت ارتقای زیرساخت‌ها و بهبود عملکرد به صورت موقت در دست به‌روزرسانی است. از شکیبایی شما سپاسگزاریم."
);
const badge = getText("maintenance_badge", "سامانه در حال به‌روزرسانی و ارتقا");
const eta = getText("maintenance_eta", "زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده");
const phone = getText("maintenance_contact_phone", "۰۲۱-۸۸۸۸۸۸۸۸");
const rawPhone = phone.replace(/[^0-9]/g, "");
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">
{/* Glow Effects */}
@@ -15,24 +28,31 @@ export default function MaintenancePage() {
</div>
<span className="inline-block px-4 py-1.5 bg-canina-gold/20 text-canina-gold border border-canina-gold/30 rounded-full text-xs font-black tracking-widest uppercase">
سامانه در حال به‌روزرسانی و ارتقا
{badge}
</span>
<h1 className="text-3xl sm:text-5xl font-black tracking-tight leading-tight">
به‌زودی با خدمات کامل‌تر بازمی‌گردیم
<h1 className="text-2xl sm:text-4xl font-black tracking-tight leading-tight">
{title}
</h1>
<p className="text-sm sm:text-base text-medical-gray-300 leading-relaxed">
وب‌سایت کنینا ایران جهت ارتقای زیرساخت‌ها و ارائه خدمات بهتر به شما سرپرستان و دامپزشکان محترم به صورت موقت در دست به‌روزرسانی است. از شکیبایی شما سپاسگزاریم.
{desc}
</p>
<div className="pt-4 flex flex-col sm:flex-row items-center justify-center gap-4">
{eta && (
<div className="inline-flex items-center gap-2 px-4 py-2 bg-white/5 border border-white/10 rounded-xl text-xs text-medical-gray-300 font-bold">
<Clock className="w-4 h-4 text-canina-gold" />
<span>{eta}</span>
</div>
)}
<div className="pt-2 flex flex-col sm:flex-row items-center justify-center gap-4">
<a
href="tel:0218888"
href={`tel:${rawPhone || "02188888888"}`}
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" />
<span>پشتیبانی اضطراری: ۰۲۱-۸۸۸۸</span>
<span>پشتیبانی اضطراری: {phone}</span>
</a>
</div>
</div>
@@ -1,6 +1,6 @@
/* eslint-disable @next/next/no-img-element */
"use client";
import React from "react";
import React, { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
X,
@@ -14,29 +14,58 @@ import {
Truck,
PackageCheck,
XCircle,
AlertCircle
AlertCircle,
Wallet,
Building2,
Loader2,
ArrowRight,
Sparkles,
} from "lucide-react";
import { toPersian } from "../lib/utils";
import api from "../lib/services/api";
import { toast } from "sonner";
interface OrderDetailsModalProps {
isOpen: boolean;
onClose: () => void;
order: Record<string, unknown> | null;
onOrderUpdated?: (orderId: string, newStatus: string) => void;
}
export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetailsModalProps) {
export default function OrderDetailsModal({
isOpen,
onClose,
order,
onOrderUpdated,
}: OrderDetailsModalProps) {
const [retryModalOpen, setRetryModalOpen] = useState(false);
const [selectedMethod, setSelectedMethod] = useState<'online' | 'wallet' | 'card'>('online');
const [isProcessingPayment, setIsProcessingPayment] = useState(false);
if (!order) return null;
const getProductName = (p: Record<string, unknown> | undefined) => String(p?.nameFa || p?.name || p?.nameEn || 'محصول کنینا');
const getProductImage = (p: Record<string, unknown> | undefined) => String(p?.imageUrl || p?.image || '/products/product-placeholder.png');
const displayTrackingCode = String(order.trackingNumber || (typeof order.id === 'string' ? order.id.substring(0, 8) : '') || 'CN-0000');
const orderId = String(order.id || '');
const orderStatus = String(order.status || '');
const isPendingPayment = orderStatus === 'pending_payment';
const getProductName = (p: Record<string, unknown> | undefined) =>
String(p?.nameFa || p?.name || p?.nameEn || 'محصول کنینا');
const getProductImage = (p: Record<string, unknown> | undefined) =>
String(p?.imageUrl || p?.image || '/products/product-placeholder.png');
const displayTrackingCode = String(
order.trackingNumber || (typeof order.id === 'string' ? order.id.substring(0, 8) : '') || 'CN-0000'
);
const rawDate = order.date || order.createdAt;
const orderDate = rawDate ? new Date(String(rawDate)) : new Date();
const formattedDate = orderDate.toLocaleDateString("fa-IR");
const formattedTime = orderDate.toLocaleTimeString("fa-IR", { hour: '2-digit', minute: '2-digit' });
const items = Array.isArray(order.items) ? (order.items as Record<string, unknown>[]) : (Array.isArray(order.orderItems) ? (order.orderItems as Record<string, unknown>[]) : []);
const items = Array.isArray(order.items)
? (order.items as Record<string, unknown>[])
: Array.isArray(order.orderItems)
? (order.orderItems as Record<string, unknown>[])
: [];
const itemsSubtotal = items.reduce((sum: number, item: Record<string, unknown>) => {
const prod = item.product as Record<string, unknown> | undefined;
const price = Number(prod?.priceValue || item.priceValue || 0);
@@ -46,20 +75,26 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
const charityAmount = Number(order.charityDonation || 0);
const totalAmount = Number(order.total || order.totalAmount || itemsSubtotal + charityAmount);
const isRefill = Boolean(order.isRefill);
const refillDiscount = isRefill ? Math.round(itemsSubtotal * 0.05) : 0;
const paymentMethodText = order.paymentMethod === 'wallet' ? 'پرداخت از کیف پول الکترونیک' : 'پرداخت آنلاین از درگاه شتاب';
const getPaymentMethodTitle = (method?: unknown) => {
const m = String(method || '');
if (m === 'wallet') return 'کیف پول الکترونیک کنینا';
if (m === 'card' || m === 'card_to_card') return 'کارت به کارت مستقیم';
return 'درگاه پرداخت اینترنتی زیبال (شتاب)';
};
const handlePrint = () => {
const printWindow = window.open('', '_blank');
if (!printWindow) return;
const itemsHtml = items.map((item: Record<string, unknown>) => {
const prod = item.product as Record<string, unknown> | undefined;
const pName = getProductName(prod);
const pImg = getProductImage(prod);
const pPrice = Number(prod?.priceValue || item.priceValue || 0);
const rowTotal = pPrice * Number(item.quantity || 1);
return `
const itemsHtml = items
.map((item: Record<string, unknown>) => {
const prod = item.product as Record<string, unknown> | undefined;
const pName = getProductName(prod);
const pImg = getProductImage(prod);
const pPrice = Number(prod?.priceValue || item.priceValue || 0);
const rowTotal = pPrice * Number(item.quantity || 1);
return `
<tr>
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; vertical-align: middle;">
<div style="display: flex; align-items: center; gap: 12px;">
@@ -67,12 +102,19 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
<span style="font-weight: 700; color: #111827;">${pName}</span>
</div>
</td>
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: center; font-weight: 700;">${toPersian(Number(item.quantity || 1))}</td>
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: left; font-weight: 700;">${toPersian(pPrice.toLocaleString())} تومان</td>
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: left; font-weight: 900; color: #0055FF;">${toPersian(rowTotal.toLocaleString())} تومان</td>
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: center; font-weight: 700;">${toPersian(
Number(item.quantity || 1)
)}</td>
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: left; font-weight: 700;">${toPersian(
pPrice.toLocaleString()
)} تومان</td>
<td style="padding: 14px; border-bottom: 1px solid #e5e7eb; text-align: left; font-weight: 900; color: #0055FF;">${toPersian(
rowTotal.toLocaleString()
)} تومان</td>
</tr>
`;
}).join('');
})
.join('');
printWindow.document.write(`
<!DOCTYPE html>
@@ -98,8 +140,8 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
.summary-row.total { font-size: 20px; font-weight: 900; color: #fbbf24; border-top: 1px solid #334155; padding-top: 14px; margin-top: 14px; margin-bottom: 0; }
.footer { margin-top: 40px; text-align: center; font-size: 11px; color: #9ca3af; font-weight: 700; }
@media print {
body { padding: 0; }
.invoice-card { border: none; padding: 0; }
body { padding: 0; background: #fff; }
.invoice-card { border: none; padding: 0; max-width: 100%; }
}
</style>
</head>
@@ -107,33 +149,41 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
<div class="invoice-card">
<div class="header">
<div>
<div class="logo-text">CANINA | کنینا</div>
<div class="sub-logo">مکمل‌های تخصصی دامپزشکی آلمان</div>
<div class="logo-text">Canina Iran</div>
<div class="sub-logo">نماینده رسمی Canina pharma GmbH آلمان در ایران</div>
</div>
<div style="text-align: left;">
<div style="font-size: 14px; font-weight: 900; color: #111827;">کد پیگیری: ${toPersian(displayTrackingCode)}</div>
<div style="font-size: 12px; color: #6b7280; font-weight: 700;">تاریخ: ${toPersian(formattedDate)} - ساعت ${toPersian(formattedTime)}</div>
<h2 style="margin: 0; font-size: 22px; font-weight: 900; color: #111827;">صورتحساب فروش کالا و خدمات</h2>
<span style="font-size: 12px; font-weight: 700; color: #0055FF; margin-top: 4px; display: block;">شناسه فاکتور: ${toPersian(
displayTrackingCode
)}</span>
</div>
</div>
<div class="meta-grid">
<div>
<p style="margin: 0 0 6px 0;"><strong>گیرنده و آدرس:</strong> ${order.shippingAddress || "ثبت‌شده در حساب کاربری"}</p>
<p style="margin: 0;"><strong>روش پرداخت:</strong> ${paymentMethodText}</p>
<strong style="color: #4b5563;">اطلاعات سفارش:</strong>
<div style="margin-top: 6px;">تاریخ ثبت: ${toPersian(formattedDate)} - ساعت ${toPersian(
formattedTime
)}</div>
<div style="margin-top: 4px;">روش پرداخت: ${getPaymentMethodTitle(order.paymentMethod)}</div>
<div style="margin-top: 4px;">وضعیت: ${getStatusLabel(orderStatus)}</div>
</div>
<div style="text-align: left;">
<p style="margin: 0 0 6px 0;"><strong>وضعیت سفارش:</strong> ${order.status === 'delivered' ? 'تحویل شده' : 'در حال پردازش در انبار'}</p>
<p style="margin: 0;"><strong>نوع سفارش:</strong> ${isRefill ? 'تمدید خودکار (Refill)' : 'عادی'}</p>
<div>
<strong style="color: #4b5563;">نشانی تحویل گیرنده:</strong>
<div style="margin-top: 6px; line-height: 1.5;">${
String(order.shippingAddress || 'آدرس ثبتی کاربر در حساب کاربری')
}</div>
</div>
</div>
<table>
<thead>
<tr>
<th>شرح محصول</th>
<th>شرح کالا / مکمل دارویی</th>
<th style="text-align: center;">تعداد</th>
<th>قیمت واحد</th>
<th>مجموع</th>
<th style="text-align: left;">مبلغ واحد</th>
<th style="text-align: left;">مبلغ کل</th>
</tr>
</thead>
<tbody>
@@ -143,43 +193,37 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
<div class="summary-box">
<div class="summary-row">
<span>مجموع اولیه اقلام:</span>
<span>جمع اقلام:</span>
<span>${toPersian(itemsSubtotal.toLocaleString())} تومان</span>
</div>
${isRefill ? `
<div class="summary-row" style="color: #4ade80;">
<span>تخفیف تمدید خودکار (۵٪):</span>
<span>${toPersian(refillDiscount.toLocaleString())}- تومان</span>
</div>
` : ''}
${charityAmount > 0 ? `
<div class="summary-row" style="color: #f472b6;">
<span>کمک اهدایی (ردپای مهربانی):</span>
<span>${toPersian(charityAmount.toLocaleString())}+ تومان</span>
</div>
` : ''}
${
charityAmount > 0
? `
<div class="summary-row" style="color: #f472b6;">
<span>کمک به حیوانات بی‌سرپرست (ردپای مهربانی):</span>
<span>${toPersian(charityAmount.toLocaleString())}+ تومان</span>
</div>
`
: ''
}
<div class="summary-row">
<span>هزینه ارسال:</span>
<span style="color: #4ade80;">رایگان</span>
<span>هزینه بسته‌بندی و ارسال اکسپرس:</span>
<span style="color: #34d399;">رایگان (تحویل سراسری)</span>
</div>
<div class="summary-row total">
<span>مبلغ نهایی پرداخت شده:</span>
<span>مبلغ نهایی فاکتور:</span>
<span>${toPersian(totalAmount.toLocaleString())} تومان</span>
</div>
</div>
<div class="footer">
این فاکتور رسمی به صورت هوشمند و سیستمی صادر شده و فاقد نیاز به مهر و امضای فیزیکی است.<br/>
پشتیبانی کنینا آلمان: ۰۲۱-۸۸۸۸۸۸۸۸ | www.canina.ir
داروخانه تخصصی مکمل‌های کنینا ایران • تلفن پشتیبانی: ۰۲۱-۸۸۸۸۸۸۸۸ • وب‌سایت: www.canina.ir
</div>
</div>
<script>
window.onload = function() {
setTimeout(function() {
window.print();
}, 400);
};
setTimeout(function() { window.print(); }, 300);
}
</script>
</body>
</html>
@@ -187,35 +231,90 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
printWindow.document.close();
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'delivered': return <CheckCircle2 className="w-5 h-5 text-green-500" />;
case 'shipped': return <Truck className="w-5 h-5 text-blue-500" />;
case 'packaged':
case 'ready_to_ship': return <PackageCheck className="w-5 h-5 text-purple-600" />;
case 'cancelled': return <XCircle className="w-5 h-5 text-red-500" />;
case 'pending_payment': return <AlertCircle className="w-5 h-5 text-rose-500" />;
default: return <Clock className="w-5 h-5 text-amber-500" />;
const handleExecuteRetryPayment = async () => {
try {
setIsProcessingPayment(true);
const res = await api.post(`/orders/${orderId}/retry-payment`, {
paymentMethod: selectedMethod,
});
if (res.data?.success) {
if (selectedMethod === 'online') {
// Initiate Zibal Payment
const payRes = await api.post('/payment/zibal/initiate', {
orderId,
});
if (payRes.data?.paymentUrl) {
toast.success('در حال انتقال به درگاه پرداخت زیبال...');
window.location.href = payRes.data.paymentUrl;
return;
}
} else if (selectedMethod === 'wallet') {
toast.success('پرداخت سفارش با موفقیت از طریق کیف پول انجام شد.');
if (onOrderUpdated) {
onOrderUpdated(orderId, 'processing');
}
setRetryModalOpen(false);
onClose();
} else {
toast.success('روش پرداخت به کارت به کارت تغییر یافت.');
if (onOrderUpdated) {
onOrderUpdated(orderId, 'pending_payment');
}
setRetryModalOpen(false);
}
}
} catch (err: any) {
console.error('Retry payment error:', err);
} finally {
setIsProcessingPayment(false);
}
};
const getStatusLabel = (status: string) => {
switch (status) {
case 'delivered': return 'تحویل شده';
case 'shipped': return 'ارسال شده';
function getStatusIcon(st: string) {
switch (st) {
case 'processing':
return <Clock className="w-5 h-5 text-amber-500" />;
case 'packaged':
case 'ready_to_ship': return 'بسته‌بندی شده (آماده ارسال)';
case 'cancelled': return 'لغو شده';
case 'pending_payment': return 'در انتظار پرداخت / ناموفق';
case 'refunded': return 'مرجوع شده';
default: return 'در حال پردازش';
case 'ready_to_ship':
return <PackageCheck className="w-5 h-5 text-purple-500" />;
case 'shipped':
return <Truck className="w-5 h-5 text-blue-500" />;
case 'delivered':
return <CheckCircle2 className="w-5 h-5 text-green-500" />;
case 'pending_payment':
return <AlertCircle className="w-5 h-5 text-rose-500" />;
case 'cancelled':
return <XCircle className="w-5 h-5 text-red-500" />;
default:
return <Package className="w-5 h-5 text-medical-gray-400" />;
}
};
}
function getStatusLabel(st: string) {
switch (st) {
case 'processing':
return 'در حال پردازش در انبار';
case 'packaged':
case 'ready_to_ship':
return 'بسته‌بندی شده (آماده ارسال)';
case 'shipped':
return 'تحویل شرکت پست / پیک';
case 'delivered':
return 'تحویل موفق به مشتری';
case 'pending_payment':
return 'در انتظار پرداخت / ناموفق';
case 'cancelled':
return 'سفارش لغو شده';
default:
return 'ثبت اولیه';
}
}
return (
<AnimatePresence>
{isOpen && (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
@@ -223,61 +322,102 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
onClick={onClose}
className="absolute inset-0 bg-medical-gray-900/60 backdrop-blur-md"
/>
<motion.div
initial={{ opacity: 0, scale: 0.9, y: 20 }}
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
className="bg-white w-full max-w-2xl rounded-[3.5rem] relative z-10 shadow-2xl overflow-hidden font-vazir text-right"
exit={{ opacity: 0, scale: 0.95, y: 20 }}
className="bg-white w-full max-w-3xl rounded-[2.5rem] relative z-10 shadow-2xl overflow-hidden font-vazir text-right"
dir="rtl"
>
{/* Header */}
<div className="bg-medical-gray-50 px-8 sm:px-10 py-6 sm:py-8 flex items-center justify-between border-b border-medical-gray-100">
{/* Modal Header */}
<div className="p-6 sm:p-8 bg-medical-gray-50/80 border-b border-medical-gray-100 flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="w-12 h-12 sm:w-14 sm:h-14 bg-canina-blue rounded-2xl flex items-center justify-center text-white shadow-lg">
<Package className="w-6 h-6 sm:w-7 sm:h-7" />
<div className="w-12 h-12 bg-canina-blue/10 rounded-2xl flex items-center justify-center text-canina-blue">
<Package className="w-6 h-6" />
</div>
<div>
<h3 className="text-lg sm:text-xl font-black text-medical-gray-900 italic">سفارش {toPersian(displayTrackingCode)}</h3>
<p className="text-xs font-bold text-medical-gray-400">ثبت شده در {toPersian(formattedDate)} - ساعت {toPersian(formattedTime)}</p>
<h3 className="text-xl font-black text-medical-gray-900">
جزئیات کامل سفارش {toPersian(displayTrackingCode)}
</h3>
<p className="text-xs text-medical-gray-400 font-bold mt-0.5">
ثبت شده در تاریخ {toPersian(formattedDate)}
</p>
</div>
</div>
<button
onClick={onClose}
className="w-10 h-10 flex items-center justify-center rounded-xl bg-white border border-medical-gray-200 text-medical-gray-400 hover:text-red-500 transition-all"
className="w-10 h-10 rounded-xl bg-white border border-medical-gray-200 text-medical-gray-400 hover:text-medical-gray-700 flex items-center justify-center transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Pending Payment Notice Banner */}
{isPendingPayment && (
<div className="bg-rose-50 border-b border-rose-200 px-6 py-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-center gap-3">
<AlertCircle className="w-5 h-5 text-rose-600 shrink-0" />
<div>
<span className="text-xs font-black text-rose-900 block">
پرداخت این سفارش هنوز تکمیل نشده است.
</span>
<span className="text-[11px] text-rose-700 font-medium">
می‌توانید همین حالا روش پرداخت را تغییر داده یا مجدداً پرداخت را انجام دهید.
</span>
</div>
</div>
<button
onClick={() => setRetryModalOpen(true)}
className="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white rounded-xl text-xs font-black transition-all shadow-md shadow-rose-600/20 whitespace-nowrap shrink-0 flex items-center justify-center gap-1.5"
>
<CreditCard className="w-4 h-4" />
<span>پرداخت و تکمیل سفارش</span>
</button>
</div>
)}
{/* Content Scrollable */}
<div className="max-h-[70vh] overflow-y-auto px-8 sm:px-10 py-8 space-y-8 custom-scrollbar">
<div className="max-h-[60vh] overflow-y-auto px-6 sm:px-10 py-6 space-y-6 custom-scrollbar">
{/* Summary Stats */}
<div className="grid grid-cols-3 gap-3 sm:gap-4">
<div className="bg-medical-gray-50 p-4 rounded-2xl">
<div className="text-[9px] font-black text-medical-gray-400 uppercase tracking-widest mb-1">وضعیت تحویل</div>
<div className="text-[9px] font-black text-medical-gray-400 uppercase tracking-widest mb-1">
وضعیت سفارش
</div>
<div className="flex items-center gap-2">
{getStatusIcon(String(order.status || ''))}
<span className="text-xs sm:text-sm font-black text-medical-gray-900">{getStatusLabel(String(order.status || ''))}</span>
{getStatusIcon(orderStatus)}
<span className="text-xs sm:text-sm font-black text-medical-gray-900">
{getStatusLabel(orderStatus)}
</span>
</div>
</div>
<div className="bg-medical-gray-50 p-4 rounded-2xl">
<div className="text-[9px] font-black text-medical-gray-400 uppercase tracking-widest mb-1">کد پیگیری</div>
<div className="text-xs sm:text-sm font-mono font-bold text-canina-blue">{toPersian(displayTrackingCode)}</div>
<div className="text-[9px] font-black text-medical-gray-400 uppercase tracking-widest mb-1">
کد پیگیری
</div>
<div className="text-xs sm:text-sm font-bold text-canina-blue font-vazir">
{toPersian(displayTrackingCode)}
</div>
</div>
<div className="bg-medical-gray-50 p-4 rounded-2xl">
<div className="text-[9px] font-black text-medical-gray-400 uppercase tracking-widest mb-1">زمان دقیق</div>
<div className="text-[9px] font-black text-medical-gray-400 uppercase tracking-widest mb-1">
زمان دقیق
</div>
<div className="flex items-center gap-1.5">
<Clock className="w-4 h-4 text-medical-gray-400 flex-shrink-0" />
<span className="text-xs sm:text-sm font-black text-medical-gray-900">{toPersian(formattedTime)}</span>
<span className="text-xs sm:text-sm font-black text-medical-gray-900">
{toPersian(formattedTime)}
</span>
</div>
</div>
</div>
{/* Items List */}
<div>
<h4 className="text-sm font-black text-medical-gray-900 mb-4 flex items-center gap-2">
<h4 className="text-sm font-black text-medical-gray-900 mb-3 flex items-center gap-2">
<ShoppingBag className="w-4 h-4 text-canina-blue" />
سبد محصولات خریده شده
سبد اقلام سفارش
</h4>
<div className="space-y-3">
{items.map((item: Record<string, unknown>, idx: number) => {
@@ -287,7 +427,10 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
const pPrice = Number(prod?.priceValue || item.priceValue || 0);
const itemQty = Number(item.quantity || 1);
return (
<div key={String(prod?.id || idx)} className="flex items-center justify-between p-4 border border-medical-gray-100 rounded-2xl hover:border-canina-blue transition-all">
<div
key={String(prod?.id || idx)}
className="flex items-center justify-between p-4 border border-medical-gray-100 rounded-2xl hover:border-canina-blue transition-all"
>
<div className="flex items-center gap-4">
<div className="w-14 h-14 bg-medical-gray-50 rounded-xl p-1.5 flex items-center justify-center shrink-0 border border-medical-gray-200">
<img
@@ -297,11 +440,15 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
/>
</div>
<div>
<h5 className="font-black text-medical-gray-900 text-sm">{pName}</h5>
<p className="text-xs text-medical-gray-400">{toPersian(itemQty)} عدد × {toPersian(pPrice.toLocaleString())} تومان</p>
<h5 className="font-black text-medical-gray-900 text-xs sm:text-sm">
{pName}
</h5>
<p className="text-xs text-medical-gray-400 mt-0.5">
{toPersian(itemQty)} عدد × {toPersian(pPrice.toLocaleString())} تومان
</p>
</div>
</div>
<div className="text-left font-black text-canina-blue text-sm">
<div className="text-left font-black text-canina-blue text-xs sm:text-sm">
{toPersian((pPrice * itemQty).toLocaleString())} تومان
</div>
</div>
@@ -311,14 +458,14 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
</div>
{/* Shipping & Payment */}
<div className="grid md:grid-cols-2 gap-6 pt-6 border-t border-medical-gray-100">
<div className="grid md:grid-cols-2 gap-6 pt-4 border-t border-medical-gray-100">
<div>
<h4 className="text-sm font-black text-medical-gray-900 mb-3 flex items-center gap-2">
<MapPin className="w-4 h-4 text-canina-blue" />
اطلاعات ارسال
</h4>
<p className="text-xs font-bold text-medical-gray-600 leading-relaxed bg-medical-gray-50 p-4 rounded-2xl border border-medical-gray-100">
{String(order.shippingAddress || "آدرس ثبتی کاربر در حساب کاربری")}
{String(order.shippingAddress || 'آدرس ثبتی کاربر در حساب کاربری')}
</p>
</div>
<div>
@@ -329,18 +476,14 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
<div className="space-y-2 bg-medical-gray-50 p-4 rounded-2xl border border-medical-gray-100">
<div className="flex justify-between text-xs font-bold text-medical-gray-500">
<span>روش پرداخت:</span>
<span className="text-medical-gray-900 font-black">{paymentMethodText}</span>
<span className="text-medical-gray-900 font-black">
{getPaymentMethodTitle(order.paymentMethod)}
</span>
</div>
<div className="flex justify-between text-xs font-bold text-medical-gray-500">
<span>مجموع اولیه اقلام:</span>
<span>{toPersian(itemsSubtotal.toLocaleString())} تومان</span>
</div>
{isRefill && (
<div className="flex justify-between text-xs font-bold text-green-600 bg-green-50 p-2 rounded-xl border border-green-100">
<span>رزرو هوشمند تمدید (۵٪ پاداش خرید بعدی):</span>
<span>فعال ({toPersian(Math.round(itemsSubtotal * 0.05).toLocaleString())} تومان)</span>
</div>
)}
{charityAmount > 0 && (
<div className="flex justify-between text-xs font-bold text-pink-500">
<span>کمک اهدایی (ردپای مهربانی):</span>
@@ -351,9 +494,11 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
<span>هزینه ارسال:</span>
<span className="text-green-600 font-black">رایگان</span>
</div>
<div className="flex justify-between text-sm sm:text-base font-black text-medical-gray-900 pt-2 border-t border-medical-gray-200 italic">
<span>مبلغ نهایی پرداخت شده:</span>
<span className="text-canina-blue">{toPersian(totalAmount.toLocaleString())} تومان</span>
<div className="flex justify-between text-sm sm:text-base font-black text-medical-gray-900 pt-2 border-t border-medical-gray-200">
<span>مبلغ نهایی سفارش:</span>
<span className="text-canina-blue">
{toPersian(totalAmount.toLocaleString())} تومان
</span>
</div>
</div>
</div>
@@ -361,16 +506,182 @@ export default function OrderDetailsModal({ isOpen, onClose, order }: OrderDetai
</div>
{/* Footer Actions */}
<div className="p-6 sm:p-8 bg-medical-gray-50 border-t border-medical-gray-100 flex gap-4">
<div className="p-6 sm:p-8 bg-medical-gray-50 border-t border-medical-gray-100 flex flex-col sm:flex-row gap-3">
{isPendingPayment && (
<button
onClick={() => setRetryModalOpen(true)}
className="flex-1 py-3.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-2xl font-black text-xs sm:text-sm flex items-center justify-center gap-2 shadow-lg shadow-emerald-600/20 transition-all"
>
<CreditCard className="w-4 h-4" />
<span>پرداخت آنلاین و تکمیل سفارش</span>
</button>
)}
<button
onClick={handlePrint}
className="flex-1 py-4 bg-canina-blue text-white rounded-2xl font-black text-sm flex items-center justify-center gap-3 hover:bg-medical-gray-900 transition-all shadow-lg shadow-canina-blue/20"
className="flex-1 py-3.5 bg-canina-blue hover:bg-medical-gray-900 text-white rounded-2xl font-black text-xs sm:text-sm flex items-center justify-center gap-2 transition-all shadow-md"
>
<Download className="w-5 h-5" />
دانلود و چاپ فاکتور رسمی کنینا
<Download className="w-4 h-4" />
<span>دانلود و چاپ فاکتور رسمی</span>
</button>
</div>
</motion.div>
{/* Retry Payment Method Selector Modal */}
{retryModalOpen && (
<div className="fixed inset-0 z-60 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
<div className="bg-white rounded-3xl p-6 sm:p-8 w-full max-w-md shadow-2xl space-y-6 font-vazir animate-in fade-in zoom-in-95 duration-150" dir="rtl">
<div className="flex items-center justify-between border-b border-medical-gray-100 pb-4">
<div className="flex items-center gap-2">
<CreditCard className="w-5 h-5 text-canina-blue" />
<h3 className="text-base font-black text-medical-gray-900">
انتخاب روش پرداخت سفارش
</h3>
</div>
<button
onClick={() => setRetryModalOpen(false)}
className="p-1 text-medical-gray-400 hover:text-medical-gray-600 rounded-lg hover:bg-medical-gray-100"
>
✕
</button>
</div>
<div className="p-3.5 bg-canina-blue/5 border border-canina-blue/10 rounded-2xl flex justify-between items-center text-xs">
<span className="font-bold text-medical-gray-600">مبلغ قابل پرداخت:</span>
<span className="font-black text-canina-blue text-sm">
{toPersian(totalAmount.toLocaleString())} تومان
</span>
</div>
{/* Methods Options */}
<div className="space-y-3">
<label
onClick={() => setSelectedMethod('online')}
className={`flex items-center justify-between p-4 rounded-2xl border-2 cursor-pointer transition-all ${
selectedMethod === 'online'
? 'border-canina-blue bg-canina-blue/5'
: 'border-medical-gray-100 hover:border-medical-gray-200'
}`}
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center font-bold">
<CreditCard className="w-5 h-5" />
</div>
<div>
<div className="text-xs font-black text-medical-gray-900">
درگاه پرداخت آنلاین زیبال
</div>
<div className="text-[10px] text-medical-gray-400 font-bold mt-0.5">
پرداخت آنی با تمامی کارت‌های بانکی عضو شتاب
</div>
</div>
</div>
<div
className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
selectedMethod === 'online'
? 'border-canina-blue bg-canina-blue'
: 'border-medical-gray-300'
}`}
>
{selectedMethod === 'online' && (
<span className="w-2 h-2 rounded-full bg-white" />
)}
</div>
</label>
<label
onClick={() => setSelectedMethod('wallet')}
className={`flex items-center justify-between p-4 rounded-2xl border-2 cursor-pointer transition-all ${
selectedMethod === 'wallet'
? 'border-canina-blue bg-canina-blue/5'
: 'border-medical-gray-100 hover:border-medical-gray-200'
}`}
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-purple-50 text-purple-600 rounded-xl flex items-center justify-center font-bold">
<Wallet className="w-5 h-5" />
</div>
<div>
<div className="text-xs font-black text-medical-gray-900">
کیف پول الکترونیک کنینا
</div>
<div className="text-[10px] text-medical-gray-400 font-bold mt-0.5">
کسر خودکار از موجودی کیف پول
</div>
</div>
</div>
<div
className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
selectedMethod === 'wallet'
? 'border-canina-blue bg-canina-blue'
: 'border-medical-gray-300'
}`}
>
{selectedMethod === 'wallet' && (
<span className="w-2 h-2 rounded-full bg-white" />
)}
</div>
</label>
<label
onClick={() => setSelectedMethod('card')}
className={`flex items-center justify-between p-4 rounded-2xl border-2 cursor-pointer transition-all ${
selectedMethod === 'card'
? 'border-canina-blue bg-canina-blue/5'
: 'border-medical-gray-100 hover:border-medical-gray-200'
}`}
>
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center font-bold">
<Building2 className="w-5 h-5" />
</div>
<div>
<div className="text-xs font-black text-medical-gray-900">
کارت به کارت مستقیم
</div>
<div className="text-[10px] text-medical-gray-400 font-bold mt-0.5">
واریز به شماره کارت / شبا شرکت
</div>
</div>
</div>
<div
className={`w-5 h-5 rounded-full border-2 flex items-center justify-center ${
selectedMethod === 'card'
? 'border-canina-blue bg-canina-blue'
: 'border-medical-gray-300'
}`}
>
{selectedMethod === 'card' && (
<span className="w-2 h-2 rounded-full bg-white" />
)}
</div>
</label>
</div>
<div className="flex items-center justify-end gap-3 pt-2">
<button
type="button"
onClick={() => setRetryModalOpen(false)}
className="px-4 py-2.5 text-xs font-bold text-medical-gray-600 hover:bg-medical-gray-100 rounded-xl transition-all"
>
انصراف
</button>
<button
type="button"
disabled={isProcessingPayment}
onClick={handleExecuteRetryPayment}
className="px-6 py-2.5 text-xs font-black bg-canina-blue hover:bg-canina-dark text-white rounded-xl shadow-lg shadow-canina-blue/20 transition-all flex items-center gap-2"
>
{isProcessingPayment ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<CheckCircle2 className="w-4 h-4" />
)}
<span>تایید و ادامه پرداخت</span>
</button>
</div>
</div>
</div>
)}
</div>
)}
</AnimatePresence>
+124 -80
View File
@@ -26,7 +26,8 @@ import {
ShoppingBag,
Thermometer,
AlertTriangle,
Share2
Share2,
Phone
} from "lucide-react";
const ICON_MAP: Record<string, React.ComponentType<{ className?: string }>> = {
@@ -65,6 +66,7 @@ const useCalculatorStore = create<CalculatorState>((set) => ({
import Tooltip from "./Tooltip";
import SafeImage from "./SafeImage";
import ProductReviews from "./ProductReviews";
import { useRouter } from 'next/navigation';
@@ -111,6 +113,12 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
const activePet = getActivePet();
const { petType, weight, setPetType, setWeight } = useCalculatorStore();
const { addItem } = useCartStore();
const getText = useSettingsStore((state) => state.getText);
const isCatalogMode = getText('catalog_mode', 'false') === 'true';
const isCatalogHidePrices = getText('catalog_hide_prices', 'false') === 'true';
const isCatalogDisableCart = getText('catalog_disable_cart', 'false') === 'true';
const isCartDisabled = isCatalogMode || isCatalogDisableCart;
const scientificTerms = useSettingsStore(state => state.scientificTerms);
const termKeys = useMemo(() => {
return Array.from(new Set([
@@ -663,6 +671,13 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
</div>
</section>
)}
{/* Customer Reviews & Ratings Section */}
{product && (
<div className="pt-8">
<ProductReviews productId={product.id} productName={product.name} />
</div>
)}
</div>
{/* Sticky Sidebar (Clean Buy Box) - Hidden on mobile as mobile floating buy bar is active */}
@@ -671,63 +686,78 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
<div className="absolute top-0 right-0 w-24 h-24 bg-canina-blue/5 rounded-full -mr-12 -mt-12" />
<div className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest mb-1 font-vazir">قیمت نهایی محصول</div>
<div className="text-4xl font-black font-vazir text-medical-gray-900 tracking-tighter mb-8">
{toPersian(product.price)}
<div className="text-3xl sm:text-4xl font-black font-vazir text-medical-gray-900 tracking-tighter mb-8">
{isCatalogHidePrices ? "استعلام قیمت" : toPersian(product.price)}
</div>
<div className="flex gap-4 mb-6">
{/* Quantity Selector - 40% Width */}
<div className="flex items-center gap-4 bg-medical-gray-50 border border-medical-gray-100 rounded-2xl p-2 h-16 w-[40%]">
<button
onClick={() => setItemQuantity(Math.max(1, itemQuantity - 1))}
className="w-10 h-10 flex items-center justify-center rounded-xl bg-white text-medical-gray-900 border border-medical-gray-200 hover:bg-canina-blue hover:text-white hover:border-canina-blue transition-all shadow-sm"
{isCartDisabled ? (
<div className="space-y-3">
<a
href="tel:02188888888"
className="w-full flex items-center justify-center gap-2 px-4 bg-canina-blue text-white rounded-2xl h-16 font-black text-sm hover:bg-canina-dark transition-all shadow-xl shadow-canina-blue/20 font-vazir"
>
<Minus className="w-4 h-4" />
</button>
<span className="text-xl font-black text-medical-gray-900 flex-1 text-center font-vazir">
{toPersian(itemQuantity)}
</span>
<button
onClick={() => setItemQuantity(itemQuantity + 1)}
className="w-10 h-10 flex items-center justify-center rounded-xl bg-white text-medical-gray-900 border border-medical-gray-200 hover:bg-canina-blue hover:text-white hover:border-canina-blue transition-all shadow-sm"
>
<Plus className="w-4 h-4" />
</button>
<Phone className="w-5 h-5" />
<span>مشاوره و استعلام خرید</span>
</a>
<p className="text-[11px] text-medical-gray-400 font-bold text-center">
خرید آنلاین در حالت کاتالوگ موقتاً غیرفعال است
</p>
</div>
) : (
<div className="flex gap-4 mb-6">
{/* Quantity Selector - 40% Width */}
<div className="flex items-center gap-4 bg-medical-gray-50 border border-medical-gray-100 rounded-2xl p-2 h-16 w-[40%]">
<button
onClick={() => setItemQuantity(Math.max(1, itemQuantity - 1))}
className="w-10 h-10 flex items-center justify-center rounded-xl bg-white text-medical-gray-900 border border-medical-gray-200 hover:bg-canina-blue hover:text-white hover:border-canina-blue transition-all shadow-sm"
>
<Minus className="w-4 h-4" />
</button>
<span className="text-xl font-black text-medical-gray-900 flex-1 text-center font-vazir">
{toPersian(itemQuantity)}
</span>
<button
onClick={() => setItemQuantity(itemQuantity + 1)}
className="w-10 h-10 flex items-center justify-center rounded-xl bg-white text-medical-gray-900 border border-medical-gray-200 hover:bg-canina-blue hover:text-white hover:border-canina-blue transition-all shadow-sm"
>
<Plus className="w-4 h-4" />
</button>
</div>
{/* Add to Cart / Preorder / Stock Notify Button - 60% Width */}
{(product as unknown as { isPreorder?: boolean; preorderDeposit?: number }).isPreorder ? (
<button
onClick={() => {
addItem(product, itemQuantity, { quantity: calculation.dailyDose, unit: calculation.unit });
toast.success(`پیش‌خرید ${toPersian(itemQuantity)} عدد ${product.name} به سبد شما اضافه شد`);
}}
className="w-[60%] flex items-center justify-center gap-1.5 px-4 bg-purple-700 text-white rounded-2xl h-16 font-black text-sm hover:bg-purple-800 transition-all shadow-xl shadow-purple-900/20 font-vazir whitespace-nowrap"
>
<Sparkles className="w-5 h-5 mb-1 text-amber-300" />
{((product as unknown as { preorderDeposit?: number }).preorderDeposit || 0) > 0 ? `پیش‌خرید (بیعانه: ${((product as unknown as { preorderDeposit?: number }).preorderDeposit || 0).toLocaleString('fa-IR')} تومان)` : 'ثبت پیش‌خرید (رایگان)'}
</button>
) : (product.packageSize || 0) <= 0 ? (
<button
onClick={() => toast.info("درخواست اطلاع‌رسانی موجودی ثبت شد")}
className="w-[60%] flex items-center justify-center gap-1.5 px-4 bg-amber-500 text-white rounded-2xl h-16 font-black text-sm hover:bg-amber-600 transition-all shadow-xl shadow-amber-500/20 font-vazir whitespace-nowrap"
>
<Bell className="w-5 h-5 mb-1" />
موجود شد اطلاع بده
</button>
) : (
<button
onClick={() => {
addItem(product, itemQuantity, { quantity: calculation.dailyDose, unit: calculation.unit });
toast.success(`${toPersian(itemQuantity)} عدد ${product.name} به سبد خرید اضافه شد`);
}}
className="w-[60%] flex items-center justify-center gap-1.5 px-4 bg-medical-gray-900 text-white rounded-2xl h-16 font-black text-sm hover:bg-canina-blue transition-all shadow-xl shadow-black/10 font-vazir whitespace-nowrap"
>
<ShoppingBag className="w-5 h-5 mb-1" />
افزودن به سبد خرید
</button>
)}
</div>
{/* Add to Cart / Preorder / Stock Notify Button - 60% Width */}
{(product as unknown as { isPreorder?: boolean; preorderDeposit?: number }).isPreorder ? (
<button
onClick={() => {
addItem(product, itemQuantity, { quantity: calculation.dailyDose, unit: calculation.unit });
toast.success(`پیش‌خرید ${toPersian(itemQuantity)} عدد ${product.name} به سبد شما اضافه شد`);
}}
className="w-[60%] flex items-center justify-center gap-1.5 px-4 bg-purple-700 text-white rounded-2xl h-16 font-black text-sm hover:bg-purple-800 transition-all shadow-xl shadow-purple-900/20 font-vazir whitespace-nowrap"
>
<Sparkles className="w-5 h-5 mb-1 text-amber-300" />
{((product as unknown as { preorderDeposit?: number }).preorderDeposit || 0) > 0 ? `پیش‌خرید (بیعانه: ${((product as unknown as { preorderDeposit?: number }).preorderDeposit || 0).toLocaleString('fa-IR')} تومان)` : 'ثبت پیش‌خرید (رایگان)'}
</button>
) : (product.packageSize || 0) <= 0 ? (
<button
onClick={() => toast.info("درخواست اطلاع‌رسانی موجودی ثبت شد")}
className="w-[60%] flex items-center justify-center gap-1.5 px-4 bg-amber-500 text-white rounded-2xl h-16 font-black text-sm hover:bg-amber-600 transition-all shadow-xl shadow-amber-500/20 font-vazir whitespace-nowrap"
>
<Bell className="w-5 h-5 mb-1" />
موجود شد اطلاع بده
</button>
) : (
<button
onClick={() => {
addItem(product, itemQuantity, { quantity: calculation.dailyDose, unit: calculation.unit });
toast.success(`${toPersian(itemQuantity)} عدد ${product.name} به سبد خرید اضافه شد`);
}}
className="w-[60%] flex items-center justify-center gap-1.5 px-4 bg-medical-gray-900 text-white rounded-2xl h-16 font-black text-sm hover:bg-canina-blue transition-all shadow-xl shadow-black/10 font-vazir whitespace-nowrap"
>
<ShoppingBag className="w-5 h-5 mb-1" />
افزودن به سبد خرید
</button>
)}
</div>
)}
<div className="mt-6 flex flex-col gap-3 border-t border-medical-gray-50 pt-6">
<div className="flex items-center gap-2 text-xs font-bold text-medical-gray-500 font-vazir">
@@ -878,38 +908,52 @@ export default function ProductPage({ productSlug }: { productSlug: string }) {
<div className="lg:hidden fixed bottom-0 left-0 right-0 z-40 bg-white border-t border-medical-gray-200 p-3 shadow-2xl flex items-center justify-between gap-3 font-vazir" dir="rtl">
<div>
<span className="text-[10px] text-medical-gray-400 font-bold block">قیمت نهایی</span>
<span className="text-lg font-black text-medical-gray-900 font-vazir">{toPersian(product.price)}</span>
<span className="text-base sm:text-lg font-black text-medical-gray-900 font-vazir">
{isCatalogHidePrices ? "استعلام قیمت" : toPersian(product.price)}
</span>
</div>
<div className="flex items-center gap-2 flex-1 max-w-[240px]">
<div className="flex items-center gap-1 bg-medical-gray-50 border border-medical-gray-200 rounded-xl p-1 h-11">
<button
onClick={() => setItemQuantity(Math.max(1, itemQuantity - 1))}
className="w-7 h-7 flex items-center justify-center rounded-lg bg-white text-medical-gray-900 border border-medical-gray-200 font-bold text-xs"
{isCartDisabled ? (
<a
href="tel:02188888888"
className="flex-1 bg-canina-blue text-white py-2.5 px-3 rounded-xl font-black text-xs hover:bg-canina-dark transition-all flex items-center justify-center gap-1.5 shadow-md shadow-canina-blue/20 whitespace-nowrap"
>
-
</button>
<span className="w-5 text-center font-black text-medical-gray-900 text-xs font-vazir">
{toPersian(itemQuantity)}
</span>
<button
onClick={() => setItemQuantity(itemQuantity + 1)}
className="w-7 h-7 flex items-center justify-center rounded-lg bg-white text-medical-gray-900 border border-medical-gray-200 font-bold text-xs"
>
+
</button>
</div>
<Phone className="w-4 h-4" />
استعلام و مشاوره
</a>
) : (
<>
<div className="flex items-center gap-1 bg-medical-gray-50 border border-medical-gray-200 rounded-xl p-1 h-11">
<button
onClick={() => setItemQuantity(Math.max(1, itemQuantity - 1))}
className="w-7 h-7 flex items-center justify-center rounded-lg bg-white text-medical-gray-900 border border-medical-gray-200 font-bold text-xs"
>
-
</button>
<span className="w-5 text-center font-black text-medical-gray-900 text-xs font-vazir">
{toPersian(itemQuantity)}
</span>
<button
onClick={() => setItemQuantity(itemQuantity + 1)}
className="w-7 h-7 flex items-center justify-center rounded-lg bg-white text-medical-gray-900 border border-medical-gray-200 font-bold text-xs"
>
+
</button>
</div>
<button
onClick={() => {
addItem(product, itemQuantity, { quantity: calculation.dailyDose, unit: calculation.unit });
toast.success(`${toPersian(itemQuantity)} عدد به سبد خرید اضافه شد`);
}}
className="flex-1 bg-canina-blue text-white py-2.5 px-3 rounded-xl font-black text-xs hover:bg-canina-dark transition-all flex items-center justify-center gap-1.5 shadow-md shadow-canina-blue/20 whitespace-nowrap"
>
<ShoppingBag className="w-4 h-4" />
افزودن به سبد
</button>
<button
onClick={() => {
addItem(product, itemQuantity, { quantity: calculation.dailyDose, unit: calculation.unit });
toast.success(`${toPersian(itemQuantity)} عدد به سبد خرید اضافه شد`);
}}
className="flex-1 bg-canina-blue text-white py-2.5 px-3 rounded-xl font-black text-xs hover:bg-canina-dark transition-all flex items-center justify-center gap-1.5 shadow-md shadow-canina-blue/20 whitespace-nowrap"
>
<ShoppingBag className="w-4 h-4" />
افزودن به سبد
</button>
</>
)}
</div>
</div>
</div>
@@ -0,0 +1,382 @@
"use client";
import React, { useState, useEffect, useCallback } from "react";
import {
Star,
MessageSquare,
CheckCircle2,
Reply,
Loader2,
ChevronLeft,
ChevronRight,
Send,
User,
ShieldCheck,
} from "lucide-react";
import { toast } from "sonner";
import api from "../lib/services/api";
import { toPersian } from "../lib/utils";
interface ReviewItem {
id: string;
userName: string;
rating: number;
comment: string;
adminReply?: string;
createdAt: string;
}
interface ProductReviewsProps {
productId: string;
productName: string;
}
export default function ProductReviews({ productId, productName }: ProductReviewsProps) {
const [reviews, setReviews] = useState<ReviewItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [stats, setStats] = useState({ averageRating: 5, totalReviews: 0 });
// Submission Form State
const [isSubmitting, setIsSubmitting] = useState(false);
const [rating, setRating] = useState(5);
const [hoverRating, setHoverRating] = useState(0);
const [comment, setComment] = useState("");
const [userName, setUserName] = useState("");
const [userPhone, setUserPhone] = useState("");
const [formOpen, setFormOpen] = useState(false);
const fetchReviews = useCallback(async () => {
if (!productId) return;
try {
setIsLoading(true);
const res = await api.get(`/products/${productId}/reviews?page=${page}&limit=5`);
if (res.data?.success) {
setReviews(res.data.data || []);
setTotalPages(res.data.pagination?.totalPages || 1);
if (res.data.stats) {
setStats(res.data.stats);
}
}
} catch (err: any) {
console.error("Failed to fetch product reviews:", err);
} finally {
setIsLoading(false);
}
}, [productId, page]);
useEffect(() => {
fetchReviews();
}, [fetchReviews]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!comment.trim()) {
toast.error("لطفاً متن نظر خود را وارد نمایید.");
return;
}
try {
setIsSubmitting(true);
const res = await api.post(`/products/${productId}/reviews`, {
rating,
comment: comment.trim(),
userName: userName.trim() || undefined,
userPhone: userPhone.trim() || undefined,
});
if (res.data?.success) {
toast.success(
res.data.message || "دیدگاه شما با موفقیت ثبت شد و پس از تایید کارشناسان منتشر خواهد شد."
);
setComment("");
setFormOpen(false);
}
} catch (err: any) {
console.error("Failed to submit review:", err);
} finally {
setIsSubmitting(false);
}
};
return (
<section className="bg-white border border-medical-gray-200 rounded-[2.5rem] p-6 sm:p-10 shadow-md space-y-8 font-vazir text-right" dir="rtl">
{/* Header & Rating Summary */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6 pb-6 border-b border-medical-gray-100">
<div className="space-y-2">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-canina-gold/10 text-canina-gold rounded-2xl flex items-center justify-center shadow-xs">
<Star className="w-6 h-6 fill-canina-gold" />
</div>
<div>
<h3 className="text-xl sm:text-2xl font-black text-medical-gray-900">
نظرات و تجربیات خریداران
</h3>
<p className="text-xs text-medical-gray-400 font-bold mt-0.5">
دیدگاه‌های ثبت‌شده درباره اثرگذاری مکمل {productName}
</p>
</div>
</div>
</div>
{/* Rating Score Badge & Add Review Button */}
<div className="flex flex-wrap items-center gap-4">
<div className="flex items-center gap-3 px-5 py-3 bg-medical-gray-50 border border-medical-gray-100 rounded-2xl">
<div className="flex items-center gap-1">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
className={`w-4 h-4 ${
i < Math.round(stats.averageRating)
? "fill-amber-400 text-amber-400"
: "text-medical-gray-200"
}`}
/>
))}
</div>
<div className="text-sm font-black text-medical-gray-900">
{toPersian(stats.averageRating)} از ۵
</div>
<span className="text-xs text-medical-gray-400 font-bold border-r border-medical-gray-200 pr-2">
({toPersian(stats.totalReviews)} دیدگاه)
</span>
</div>
<button
onClick={() => setFormOpen(!formOpen)}
className="px-5 py-3 bg-canina-blue hover:bg-canina-dark text-white rounded-2xl text-xs font-black transition-all shadow-md shadow-canina-blue/20 flex items-center gap-2"
>
<MessageSquare className="w-4 h-4" />
<span>{formOpen ? "بستن فرم" : "ثبت دیدگاه جدید"}</span>
</button>
</div>
</div>
{/* Submission Form (Accordion / Collapsible) */}
{formOpen && (
<form
onSubmit={handleSubmit}
className="bg-medical-gray-50/80 border border-medical-gray-200 rounded-3xl p-6 sm:p-8 space-y-5 animate-in fade-in duration-200"
>
<div className="flex items-center justify-between border-b border-medical-gray-200 pb-3">
<h4 className="text-sm font-black text-medical-gray-900 flex items-center gap-2">
<Send className="w-4 h-4 text-canina-blue" />
ارسال نظر و امتیاز برای {productName}
</h4>
<span className="text-[11px] text-medical-gray-400 font-bold">
نظر شما پس از تایید مدیریت نمایش داده می‌شود
</span>
</div>
{/* Star Rating Selector */}
<div>
<label className="block text-xs font-black text-medical-gray-700 mb-2">
امتیاز شما به کیفیت و اثرگذاری محصول:
</label>
<div className="flex items-center gap-2">
{Array.from({ length: 5 }).map((_, i) => {
const starVal = i + 1;
const active = starVal <= (hoverRating || rating);
return (
<button
type="button"
key={i}
onMouseEnter={() => setHoverRating(starVal)}
onMouseLeave={() => setHoverRating(0)}
onClick={() => setRating(starVal)}
className="p-1 text-2xl transition-transform hover:scale-110"
>
<Star
className={`w-7 h-7 ${
active
? "fill-amber-400 text-amber-400"
: "text-medical-gray-300"
}`}
/>
</button>
);
})}
<span className="text-xs font-bold text-medical-gray-600 mr-2">
{toPersian(rating)} ستاره
</span>
</div>
</div>
{/* Name & Phone Inputs */}
<div className="grid sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-black text-medical-gray-700 mb-1.5">
نام و نام خانوادگی (اختیاری):
</label>
<input
type="text"
value={userName}
onChange={(e) => setUserName(e.target.value)}
placeholder="مثلاً علی محمدی"
className="w-full px-4 py-2.5 bg-white border border-medical-gray-200 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-canina-blue/20"
/>
</div>
<div>
<label className="block text-xs font-black text-medical-gray-700 mb-1.5">
شماره موبایل (اختیاری - محرمانه):
</label>
<input
type="tel"
value={userPhone}
onChange={(e) => setUserPhone(e.target.value)}
placeholder="0912..."
className="w-full px-4 py-2.5 bg-white border border-medical-gray-200 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-canina-blue/20 font-mono"
dir="ltr"
/>
</div>
</div>
{/* Comment Textarea */}
<div>
<label className="block text-xs font-black text-medical-gray-700 mb-1.5">
متن دیدگاه یا تجربه مصرف: <span className="text-rose-500">*</span>
</label>
<textarea
required
rows={4}
value={comment}
onChange={(e) => setComment(e.target.value)}
placeholder="تجربه خود را از نحوه مصرف، تغییرات بالینی پت و اثربخشی این مکمل بنویسید..."
className="w-full p-4 bg-white border border-medical-gray-200 rounded-2xl text-xs sm:text-sm font-medium outline-none focus:ring-2 focus:ring-canina-blue/20 resize-none leading-relaxed"
/>
</div>
<div className="flex justify-end gap-3 pt-2">
<button
type="button"
onClick={() => setFormOpen(false)}
className="px-5 py-2.5 bg-medical-gray-200 hover:bg-medical-gray-300 text-medical-gray-700 rounded-xl text-xs font-bold transition-all"
>
انصراف
</button>
<button
type="submit"
disabled={isSubmitting}
className="px-6 py-2.5 bg-canina-blue hover:bg-canina-dark text-white rounded-xl text-xs font-black transition-all shadow-md flex items-center gap-2"
>
{isSubmitting ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<CheckCircle2 className="w-4 h-4" />
)}
<span>ثبت و ارسال دیدگاه</span>
</button>
</div>
</form>
)}
{/* Reviews List */}
<div className="space-y-4">
{isLoading ? (
<div className="py-12 text-center text-medical-gray-400 font-bold text-xs flex flex-col items-center gap-2">
<Loader2 className="w-6 h-6 animate-spin text-canina-blue" />
<span>در حال دریافت نظرات خریداران...</span>
</div>
) : reviews.length === 0 ? (
<div className="py-12 text-center bg-medical-gray-50/50 border border-dashed border-medical-gray-200 rounded-3xl">
<p className="text-sm font-bold text-medical-gray-500">
هنوز دیدگاهی برای این محصول ثبت نشده است.
</p>
<p className="text-xs text-medical-gray-400 font-medium mt-1">
اولین نفری باشید که تجربه خود را درباره این محصول به اشتراک می‌گذارید.
</p>
</div>
) : (
reviews.map((rev) => {
const date = new Date(rev.createdAt);
return (
<div
key={rev.id}
className="bg-medical-gray-50/60 border border-medical-gray-100 rounded-3xl p-5 sm:p-6 space-y-3 hover:bg-medical-gray-50 transition-colors"
>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2.5">
<div className="w-9 h-9 bg-canina-blue/10 text-canina-blue rounded-xl flex items-center justify-center font-black text-xs">
<User className="w-4 h-4" />
</div>
<div>
<div className="text-xs sm:text-sm font-black text-medical-gray-900 flex items-center gap-2">
<span>{rev.userName}</span>
<span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-md border border-emerald-200">
<ShieldCheck className="w-3 h-3" />
خریدار تایید شده
</span>
</div>
<div className="text-[10px] text-medical-gray-400 font-bold mt-0.5">
{toPersian(date.toLocaleDateString("fa-IR"))}
</div>
</div>
</div>
{/* Stars */}
<div className="flex items-center gap-1">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
className={`w-3.5 h-3.5 ${
i < rev.rating
? "fill-amber-400 text-amber-400"
: "text-medical-gray-200"
}`}
/>
))}
</div>
</div>
{/* Review Text */}
<p className="text-xs sm:text-sm text-medical-gray-700 font-medium leading-relaxed whitespace-pre-wrap pt-1">
{rev.comment}
</p>
{/* Admin Reply */}
{rev.adminReply && (
<div className="mt-3 p-3.5 bg-white border-r-3 border-canina-blue rounded-2xl text-xs space-y-1 shadow-xs">
<span className="font-black text-canina-blue flex items-center gap-1">
<Reply className="w-3.5 h-3.5 rotate-180" />
پاسخ کارشناس کنینا ایران:
</span>
<p className="text-medical-gray-600 font-medium leading-relaxed">
{rev.adminReply}
</p>
</div>
)}
</div>
);
})
)}
{/* Pagination Controls */}
{totalPages > 1 && (
<div className="flex items-center justify-between pt-4 border-t border-medical-gray-100">
<span className="text-xs font-bold text-medical-gray-400">
صفحه {toPersian(page)} از {toPersian(totalPages)}
</span>
<div className="flex items-center gap-2">
<button
disabled={page <= 1 || isLoading}
onClick={() => setPage((p) => Math.max(1, p - 1))}
className="px-3 py-1.5 border border-medical-gray-200 rounded-xl text-xs font-bold hover:bg-medical-gray-50 disabled:opacity-40 transition-all flex items-center gap-1"
>
<ChevronRight className="w-4 h-4" />
<span>قبلی</span>
</button>
<button
disabled={page >= totalPages || isLoading}
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
className="px-3 py-1.5 border border-medical-gray-200 rounded-xl text-xs font-bold hover:bg-medical-gray-50 disabled:opacity-40 transition-all flex items-center gap-1"
>
<span>بعدی</span>
<ChevronLeft className="w-4 h-4" />
</button>
</div>
</div>
)}
</div>
</section>
);
}
@@ -21,7 +21,7 @@ import { useRouter, useSearchParams } from 'next/navigation';
export default function UserDashboard() {
const router = useRouter();
const searchParams = useSearchParams();
const { profile, isLoggedIn, logout, updateProfile, addAddress, updateAddress, deleteAddress, setDefaultAddress, topUpWallet } = useUserStore();
const { profile, isLoggedIn, logout, updateProfile, addAddress, updateAddress, deleteAddress, setDefaultAddress, topUpWallet, fetchProfile } = useUserStore();
const { pets, activePetId, setActivePet, removePet } = usePetStore();
const isWithdrawalEnabled = useSettingsStore((s) => s.getBoolean('wallet_withdrawal_enabled', false));
@@ -1430,6 +1430,20 @@ export default function UserDashboard() {
</div>
</div>
)}
{/* Order Details & Retry Payment Modal */}
<OrderDetailsModal
isOpen={!!selectedOrder}
onClose={() => setSelectedOrder(null)}
order={selectedOrder}
onOrderUpdated={async () => {
try {
await fetchProfile();
} catch (e) {
console.error(e);
}
}}
/>
</div>
);
}