From 2fca778930940281f79df25d3b01f1dc7f19254b Mon Sep 17 00:00:00 2001 From: parsa aghaei Date: Mon, 17 Aug 2026 09:01:33 +0330 Subject: [PATCH] feat: complete payment retry, reviews system, catalog mode enforcement, and UI text defaults --- backend/prisma/schema.prisma | 24 + backend/src/app.module.ts | 2 + backend/src/orders/orders.controller.ts | 13 + backend/src/orders/orders.service.ts | 131 ++++- backend/src/prisma/prisma.service.ts | 20 +- backend/src/reviews/dto/create-review.dto.ts | 25 + backend/src/reviews/dto/update-review.dto.ts | 15 + backend/src/reviews/reviews.controller.ts | 107 ++++ backend/src/reviews/reviews.module.ts | 12 + backend/src/reviews/reviews.service.ts | 228 ++++++++ backend/src/settings/default-ui-texts.ts | 134 +++++ backend/src/settings/settings.service.ts | 35 +- .../admin-panel/src/components/Sidebar.tsx | 1 + frontend/admin-panel/src/pages/Orders.tsx | 28 +- frontend/admin-panel/src/pages/Reviews.tsx | 493 ++++++++++++++++ frontend/admin-panel/src/pages/UITexts.tsx | 15 +- .../admin-panel/src/routes/adminRoutes.tsx | 2 + .../application/components/CheckoutPage.tsx | 42 +- frontend/application/components/Header.tsx | 29 +- .../components/MaintenancePage.tsx | 36 +- .../components/OrderDetailsModal.tsx | 545 ++++++++++++++---- .../application/components/ProductPage.tsx | 204 ++++--- .../application/components/ProductReviews.tsx | 382 ++++++++++++ .../application/components/UserDashboard.tsx | 16 +- 24 files changed, 2297 insertions(+), 242 deletions(-) create mode 100644 backend/src/reviews/dto/create-review.dto.ts create mode 100644 backend/src/reviews/dto/update-review.dto.ts create mode 100644 backend/src/reviews/reviews.controller.ts create mode 100644 backend/src/reviews/reviews.module.ts create mode 100644 backend/src/reviews/reviews.service.ts create mode 100644 backend/src/settings/default-ui-texts.ts create mode 100644 frontend/admin-panel/src/pages/Reviews.tsx create mode 100644 frontend/application/components/ProductReviews.tsx diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 4395fa9e..aa417cc9 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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") +} + diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index 5c4e1595..6030b759 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -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, diff --git a/backend/src/orders/orders.controller.ts b/backend/src/orders/orders.controller.ts index 561a07db..3e0dd82a 100644 --- a/backend/src/orders/orders.controller.ts +++ b/backend/src/orders/orders.controller.ts @@ -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); } diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index 5bb2d886..2ea7e345 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -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, + }; + } } diff --git a/backend/src/prisma/prisma.service.ts b/backend/src/prisma/prisma.service.ts index 8f1c6ff4..690d1df1 100644 --- a/backend/src/prisma/prisma.service.ts +++ b/backend/src/prisma/prisma.service.ts @@ -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) { diff --git a/backend/src/reviews/dto/create-review.dto.ts b/backend/src/reviews/dto/create-review.dto.ts new file mode 100644 index 00000000..58ce5871 --- /dev/null +++ b/backend/src/reviews/dto/create-review.dto.ts @@ -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; +} diff --git a/backend/src/reviews/dto/update-review.dto.ts b/backend/src/reviews/dto/update-review.dto.ts new file mode 100644 index 00000000..059b167f --- /dev/null +++ b/backend/src/reviews/dto/update-review.dto.ts @@ -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; +} diff --git a/backend/src/reviews/reviews.controller.ts b/backend/src/reviews/reviews.controller.ts new file mode 100644 index 00000000..20fe9dca --- /dev/null +++ b/backend/src/reviews/reviews.controller.ts @@ -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); + } +} diff --git a/backend/src/reviews/reviews.module.ts b/backend/src/reviews/reviews.module.ts new file mode 100644 index 00000000..300444bc --- /dev/null +++ b/backend/src/reviews/reviews.module.ts @@ -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 {} diff --git a/backend/src/reviews/reviews.service.ts b/backend/src/reviews/reviews.service.ts new file mode 100644 index 00000000..ab42e0e6 --- /dev/null +++ b/backend/src/reviews/reviews.service.ts @@ -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: 'دیدگاه با موفقیت حذف شد', + }; + } +} diff --git a/backend/src/settings/default-ui-texts.ts b/backend/src/settings/default-ui-texts.ts new file mode 100644 index 00000000..9cbb77e7 --- /dev/null +++ b/backend/src/settings/default-ui-texts.ts @@ -0,0 +1,134 @@ +export const DEFAULT_UI_TEXTS: Record = { + // === 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": "حریم خصوصی و قوانین", +}; diff --git a/backend/src/settings/settings.service.ts b/backend/src/settings/settings.service.ts index 66e3bc2e..25738fba 100644 --- a/backend/src/settings/settings.service.ts +++ b/backend/src/settings/settings.service.ts @@ -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(), diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index 7dc4a19d..31389477 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -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' }, diff --git a/frontend/admin-panel/src/pages/Orders.tsx b/frontend/admin-panel/src/pages/Orders.tsx index eb30c491..ca8c91d5 100644 --- a/frontend/admin-panel/src/pages/Orders.tsx +++ b/frontend/admin-panel/src/pages/Orders.tsx @@ -468,30 +468,30 @@ export default function Orders() { const charityAmt = Number(order.charityDonation || 0); return ( - - -
{toPersianDigits(displayCode)}
-
- - - {payInfo.label} + + +
{toPersianDigits(displayCode)}
+
+ + + {payInfo.label} {order.isRefill && ( - + تمدید ۵٪- )} {charityAmt > 0 && ( - - - مهربانی: {toPersianDigits(charityAmt.toLocaleString())} ت + + + مهربانی: {toPersianDigits(charityAmt.toLocaleString())} ت )}
- -
{customerName}
-
{toPersianDigits(order.user?.phone || order.user?.mobile || '')}
+ +
{customerName}
+
{toPersianDigits(order.user?.phone || order.user?.mobile || '')}
{toPersianDigits(totalAmt.toLocaleString())} تومان diff --git a/frontend/admin-panel/src/pages/Reviews.tsx b/frontend/admin-panel/src/pages/Reviews.tsx new file mode 100644 index 00000000..e2f7e08d --- /dev/null +++ b/frontend/admin-panel/src/pages/Reviews.tsx @@ -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([]); + 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(null); + + // Reply Modal State + const [replyingReview, setReplyingReview] = useState(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 ( +
+ {/* Header */} +
+
+

+ + مدیریت نظرات و دیدگاه‌ها +

+

+ بررسی امتیازات، تایید یا رد نظرات خریداران و پاسخ‌دهی کارشناسان به دیدگاه‌ها +

+
+ + {/* Search */} +
+ + { + setSearch(e.target.value); + setPage(1); + }} + /> +
+
+ + {/* Filter Tabs */} +
+ {[ + { 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 ( + + ); + })} +
+ + {/* Reviews Table */} +
+
+ + + + + + + + + + + + + + {isLoading ? ( + + + + ) : reviews.length === 0 ? ( + + + + ) : ( + reviews.map((review) => { + const isProcessing = processingId === review.id; + const date = new Date(review.createdAt); + + return ( + + {/* Product */} + + + {/* Author */} + + + {/* Rating */} + + + {/* Comment & Admin Reply */} + + + {/* Date */} + + + {/* Status */} + + + {/* Actions */} + + + ); + }) + )} + +
محصولنویسنده دیدگاهامتیازمتن نظر و پاسختاریخوضعیتعملیات
+ +

در حال بارگذاری نظرات...

+
+ هیچ دیدگاهی در این بخش یافت نشد. +
+
+ {review.product?.imageUrl ? ( + + ) : ( +
+ +
+ )} +
+
+ {review.product?.nameFa || 'محصول کنینا'} +
+
+ {review.product?.nameEn} +
+
+
+
+
+ + {review.userName} +
+ {review.userPhone && ( +
+ {toPersianDigits(review.userPhone)} +
+ )} +
+
+ {Array.from({ length: 5 }).map((_, i) => ( + + ))} + + {toPersianDigits(review.rating)} از ۵ + +
+
+
+ {review.comment} +
+ {review.adminReply && ( +
+ + + پاسخ کنینا: + +

{review.adminReply}

+
+ )} +
+
{toPersianDigits(date.toLocaleDateString('fa-IR'))}
+
+ {toPersianDigits(date.toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' }))} +
+
+ {review.status === 'PENDING' && ( + + + در انتظار بررسی + + )} + {review.status === 'APPROVED' && ( + + + تایید شده + + )} + {review.status === 'REJECTED' && ( + + + رد شده + + )} + +
+ {review.status !== 'APPROVED' && ( + + )} + {review.status !== 'REJECTED' && ( + + )} + + +
+
+
+ + {/* Pagination */} + {totalPages > 1 && ( +
+ + صفحه {toPersianDigits(page)} از {toPersianDigits(totalPages)} + +
+ + +
+
+ )} +
+ + {/* Reply Modal */} + {replyingReview && ( +
+
+
+

+ + پاسخ به دیدگاه {replyingReview.userName} +

+ +
+ +
+ متن دیدگاه خریدار: +

{replyingReview.comment}

+
+ +
+ +