From 11dd549c7c63430fa0dbe0ff29663d3d719bc4ac Mon Sep 17 00:00:00 2001 From: devops Date: Mon, 12 Oct 2026 18:35:49 +0000 Subject: [PATCH 01/15] fix(security): add RolesGuard to doctors mutations and JwtAuthGuard to prescriptions upload --- backend/src/doctors/doctors.controller.ts | 11 ++++++++--- backend/src/prescriptions/prescriptions.controller.ts | 4 ++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/backend/src/doctors/doctors.controller.ts b/backend/src/doctors/doctors.controller.ts index 733e8f13..4c5778a6 100644 --- a/backend/src/doctors/doctors.controller.ts +++ b/backend/src/doctors/doctors.controller.ts @@ -13,6 +13,8 @@ import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger'; import { DoctorsService } from './doctors.service'; import { DoctorQueryDto } from './dto/doctor-query.dto'; import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { RolesGuard } from '../common/guards/roles.guard'; +import { Roles } from '../common/decorators/roles.decorator'; import { Prisma } from '@prisma/client'; @ApiTags('Doctors') @@ -33,7 +35,8 @@ export class DoctorsController { } @Post() - @UseGuards(JwtAuthGuard) + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('Admin', 'ADMIN') @ApiBearerAuth() @ApiOperation({ summary: 'Create new doctor' }) create(@Body() createDoctorDto: Prisma.DoctorCreateInput) { @@ -41,7 +44,8 @@ export class DoctorsController { } @Put(':id') - @UseGuards(JwtAuthGuard) + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('Admin', 'ADMIN') @ApiBearerAuth() @ApiOperation({ summary: 'Update doctor' }) update( @@ -52,7 +56,8 @@ export class DoctorsController { } @Delete(':id') - @UseGuards(JwtAuthGuard) + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('Admin', 'ADMIN') @ApiBearerAuth() @ApiOperation({ summary: 'Delete doctor' }) remove(@Param('id') id: string) { diff --git a/backend/src/prescriptions/prescriptions.controller.ts b/backend/src/prescriptions/prescriptions.controller.ts index 17eb4ac6..0ccf94ee 100644 --- a/backend/src/prescriptions/prescriptions.controller.ts +++ b/backend/src/prescriptions/prescriptions.controller.ts @@ -46,6 +46,8 @@ export class PrescriptionsController { private readonly mediaService: MediaService, ) {} + @UseGuards(JwtAuthGuard) + @ApiBearerAuth() @Post('upload') @ApiOperation({ summary: 'آپلود تصویر یا فایل نسخه دارویی توسط کاربر' }) @UseInterceptors( @@ -72,6 +74,8 @@ export class PrescriptionsController { return { success: true, data }; } + @UseGuards(JwtAuthGuard) + @ApiBearerAuth() @Post() @ApiOperation({ summary: 'بارگذاری نسخه جدید توسط کاربر' }) create( From cae22ff7c94fc156223dff130b5e7bf383793bab Mon Sep 17 00:00:00 2001 From: devops Date: Mon, 12 Oct 2026 18:42:47 +0000 Subject: [PATCH 02/15] fix(inventory): enforce out-of-stock validation in cartStore, ordersService, and JSON-LD availability --- backend/src/orders/orders.service.ts | 12 +++++++++++- frontend/application/app/shop/[slug]/page.tsx | 12 ++++++++---- frontend/application/lib/store/cartStore.ts | 8 ++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index 8b73efee..c14d644e 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -142,9 +142,19 @@ export class OrdersService { const productMap = new Map(products.map((p) => [p.id, p])); for (const productId of productIds) { - if (!productMap.has(productId)) { + const product = productMap.get(productId); + if (!product) { throw new NotFoundException(`محصول یافت نشد`); } + const isOutOfStock = + product.stockStatus === 'OUT_OF_STOCK' || + product.stockStatus === 'DISCONTINUED' || + (product.packageSize !== null && Number(product.packageSize) <= 0); + if (isOutOfStock) { + throw new BadRequestException( + `محصول «${product.nameFa || product.name}» در حال حاضر ناموجود است و امکان ثبت سفارش آن وجود ندارد`, + ); + } } let cartTotal = new Prisma.Decimal(0); diff --git a/frontend/application/app/shop/[slug]/page.tsx b/frontend/application/app/shop/[slug]/page.tsx index 62931fff..f9263e34 100644 --- a/frontend/application/app/shop/[slug]/page.tsx +++ b/frontend/application/app/shop/[slug]/page.tsx @@ -122,14 +122,18 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl const productUrl = `${siteUrl}/shop/${resolvedParams.slug}`; const priceInRial = product.priceValue * 10; - // Map stock status to Schema.org availability + // Map stock status and packageSize to Schema.org availability + const isOutOfStock = + product.stockStatus === 'OUT_OF_STOCK' || + (typeof product.packageSize === 'number' && product.packageSize <= 0); + let availabilityUrl = 'https://schema.org/InStock'; - if (product.stockStatus === 'OUT_OF_STOCK') { + if (product.stockStatus === 'DISCONTINUED') { + availabilityUrl = 'https://schema.org/Discontinued'; + } else if (isOutOfStock) { availabilityUrl = 'https://schema.org/OutOfStock'; } else if (product.stockStatus === 'PRE_ORDER') { availabilityUrl = 'https://schema.org/PreOrder'; - } else if (product.stockStatus === 'DISCONTINUED') { - availabilityUrl = 'https://schema.org/Discontinued'; } // Collect unique images diff --git a/frontend/application/lib/store/cartStore.ts b/frontend/application/lib/store/cartStore.ts index 68c2c591..62a0b293 100644 --- a/frontend/application/lib/store/cartStore.ts +++ b/frontend/application/lib/store/cartStore.ts @@ -60,6 +60,14 @@ export const useCartStore = create()( coupon: null, orders: [], addItem: (product, quantity, dose) => { + // Prevent adding out-of-stock products + const isOutOfStock = + product.stockStatus === 'OUT_OF_STOCK' || + product.stockStatus === 'DISCONTINUED' || + (typeof product.packageSize === 'number' && product.packageSize <= 0); + if (isOutOfStock || quantity <= 0) { + return; + } const items = get().items; const existing = items.find((i) => i.product.id === product.id); if (existing) { From deea1016ab44da671e6860d79acaa5332a0d7c80 Mon Sep 17 00:00:00 2001 From: devops Date: Mon, 12 Oct 2026 18:45:18 +0000 Subject: [PATCH 03/15] fix(admin): auto-sync stockStatus to OUT_OF_STOCK when packageSize is zero, preserve zero packageSize --- backend/src/admin/admin.service.ts | 2 +- frontend/admin-panel/src/pages/Products.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/admin/admin.service.ts b/backend/src/admin/admin.service.ts index 60fae8a4..ff62111d 100644 --- a/backend/src/admin/admin.service.ts +++ b/backend/src/admin/admin.service.ts @@ -552,7 +552,7 @@ export class AdminService { data.wholesalePrice !== undefined ? data.wholesalePrice : null, priceDisplay: data.priceDisplay || '', unit: data.unit || 'عدد', - packageSize: data.packageSize || 100, + packageSize: data.packageSize !== undefined ? data.packageSize : 100, dosageLogic: data.dosageLogic || '', dosageConfig: Object.keys(dosageConfigData).length > 0 diff --git a/frontend/admin-panel/src/pages/Products.tsx b/frontend/admin-panel/src/pages/Products.tsx index f3476dc2..ed066909 100644 --- a/frontend/admin-panel/src/pages/Products.tsx +++ b/frontend/admin-panel/src/pages/Products.tsx @@ -927,7 +927,7 @@ export default function Products() { metaDescription: (formData.metaDescription || '').trim() || formData.shortDescription || 'خرید آنلاین مکمل اصل کنینا آلمان با بالاترین کیفیت بالینی...', keywords: (formData.keywords || '').trim() || undefined, canonicalUrl: (formData.canonicalUrl || '').trim() || `/shop/${derivedSlug}`, - stockStatus: formData.stockStatus || 'IN_STOCK', + stockStatus: (Number(formData.packageSize) <= 0) ? 'OUT_OF_STOCK' : (formData.stockStatus || 'IN_STOCK'), noIndex: Boolean(formData.noIndex), noFollow: Boolean(formData.noFollow), ogImage: (formData.ogImage || '').trim() || undefined, From e4932a94e3362bd241e8855cccb89ad1bcfd1dc2 Mon Sep 17 00:00:00 2001 From: devops Date: Mon, 12 Oct 2026 18:46:34 +0000 Subject: [PATCH 04/15] =?UTF-8?q?fix(seed):=20standardize=20suitableFor=20?= =?UTF-8?q?to=20=C2=AB=D8=B3=DA=AF=20=D9=88=20=DA=AF=D8=B1=D8=A8=D9=87?= =?UTF-8?q?=C2=BB=20matching=20production=20database=20enum?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/prisma/seed-products.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/prisma/seed-products.ts b/backend/prisma/seed-products.ts index d8deeb30..8ee5fcfb 100644 --- a/backend/prisma/seed-products.ts +++ b/backend/prisma/seed-products.ts @@ -22,10 +22,10 @@ function determineSuitableFor(name: string, description: string): string { text.includes('hund') || text.includes('توله') || text.includes('dog'); - if (hasCat && hasDog) return 'هر دو'; + if (hasCat && hasDog) return 'سگ و گربه'; if (hasCat) return 'گربه'; if (hasDog) return 'سگ'; - return 'هر دو'; + return 'سگ و گربه'; } function parseSize(size: string): { unit: string; packageSize: number } { From 4d5159a1690aae832ae212573ba003e636847afa Mon Sep 17 00:00:00 2001 From: devops Date: Mon, 12 Oct 2026 18:49:48 +0000 Subject: [PATCH 05/15] fix(torob): correctly map packageSize 0 and OUT_OF_STOCK to outofstock in Torob API --- backend/src/products/torob.controller.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/src/products/torob.controller.ts b/backend/src/products/torob.controller.ts index 5292f1cd..ac0c420e 100644 --- a/backend/src/products/torob.controller.ts +++ b/backend/src/products/torob.controller.ts @@ -186,6 +186,8 @@ export class TorobController { const isInStock = product.stockStatus !== 'DISCONTINUED' && + product.stockStatus !== 'OUT_OF_STOCK' && + (product.packageSize === null || Number(product.packageSize) > 0) && String(product.stockStatus || '') .toLowerCase() .includes('in'); From e9582430e6966bd25d39026d4a4b2dce6df1bcfb Mon Sep 17 00:00:00 2001 From: devops Date: Mon, 12 Oct 2026 18:54:47 +0000 Subject: [PATCH 06/15] fix(security): add fileFilter mime check to pets upload and Throttling to tickets endpoints --- backend/src/pets/pets.controller.ts | 12 ++++++++++++ backend/src/tickets/tickets.controller.ts | 3 +++ 2 files changed, 15 insertions(+) diff --git a/backend/src/pets/pets.controller.ts b/backend/src/pets/pets.controller.ts index 1e190561..5aa7c534 100644 --- a/backend/src/pets/pets.controller.ts +++ b/backend/src/pets/pets.controller.ts @@ -75,6 +75,18 @@ export class PetsController { }, }), limits: { fileSize: 10 * 1024 * 1024 }, // 10MB + fileFilter: (_req, file, callback) => { + const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif']; + if (!allowedMimeTypes.includes(file.mimetype)) { + return callback( + new BadRequestException( + 'فرمت فایل مجاز نیست. لطفاً یکی از فرمت‌های JPG, PNG, WEBP را انتخاب کنید', + ), + false, + ); + } + callback(null, true); + }, }), ) @ApiOperation({ summary: 'آپلود تصویر حیوان خانگی' }) diff --git a/backend/src/tickets/tickets.controller.ts b/backend/src/tickets/tickets.controller.ts index 7994937d..84b3a124 100644 --- a/backend/src/tickets/tickets.controller.ts +++ b/backend/src/tickets/tickets.controller.ts @@ -1,3 +1,4 @@ +import { Throttle } from '@nestjs/throttler'; import { Controller, Get, @@ -33,6 +34,7 @@ import { export class TicketsController { constructor(private readonly ticketsService: TicketsService) {} + @Throttle({ default: { limit: 5, ttl: 60000 } }) @UseGuards(JwtAuthGuard) @ApiBearerAuth() @Post() @@ -66,6 +68,7 @@ export class TicketsController { return this.ticketsService.getTicketDetails(id, req.user.id, isAdmin); } + @Throttle({ default: { limit: 10, ttl: 60000 } }) @UseGuards(JwtAuthGuard) @ApiBearerAuth() @Post(':id/messages') From 741365f04cdacb09bf41d014367e53c165449dc2 Mon Sep 17 00:00:00 2001 From: devops Date: Mon, 12 Oct 2026 19:29:48 +0000 Subject: [PATCH 07/15] feat(inventory): implement numeric stock inventory across fullstack and improve prescription UX handoff --- backend/prisma/schema.prisma | 1 + backend/src/admin/admin.service.ts | 11 ++- backend/src/admin/dto/product.dto.ts | 5 ++ backend/src/orders/orders.service.ts | 89 ++++++++++++++----- backend/src/payment/payment.service.ts | 26 +++++- backend/src/products/torob.controller.ts | 2 +- frontend/admin-panel/src/pages/Products.tsx | 43 +++++++-- frontend/application/app/ClientLayout.tsx | 8 +- frontend/application/app/shop/[slug]/page.tsx | 4 +- frontend/application/components/Header.tsx | 14 ++- .../components/PrescriptionUploadModal.tsx | 6 +- frontend/application/lib/data/products.ts | 1 + frontend/application/lib/store/cartStore.ts | 14 ++- 13 files changed, 177 insertions(+), 47 deletions(-) diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index cd006589..a9ff9c22 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -230,6 +230,7 @@ model Product { metaDescription String? @map("meta_description") @db.Text canonicalUrl String? @map("canonical_url") @db.Text keywords String? @db.Text + stock Int @default(100) @map("stock") stockStatus StockStatus @default(IN_STOCK) @map("stock_status") noIndex Boolean @default(false) @map("no_index") noFollow Boolean @default(false) @map("no_follow") diff --git a/backend/src/admin/admin.service.ts b/backend/src/admin/admin.service.ts index ff62111d..8f0bfac9 100644 --- a/backend/src/admin/admin.service.ts +++ b/backend/src/admin/admin.service.ts @@ -581,7 +581,8 @@ export class AdminService { metaDescription: data.metaDescription || '', keywords: data.keywords || '', canonicalUrl: data.canonicalUrl || '', - stockStatus: data.stockStatus || 'IN_STOCK', + stock: data.stock !== undefined ? Number(data.stock) : (data.stockStatus === 'OUT_OF_STOCK' ? 0 : 100), + stockStatus: data.stockStatus || (data.stock !== undefined && Number(data.stock) <= 0 ? 'OUT_OF_STOCK' : 'IN_STOCK'), noIndex: data.noIndex ?? false, noFollow: data.noFollow ?? false, ogImage: data.ogImage || null, @@ -761,8 +762,14 @@ export class AdminService { metaDescription: data.metaDescription, keywords: data.keywords, canonicalUrl: data.canonicalUrl, + stock: + data.stock !== undefined ? Number(data.stock) : undefined, stockStatus: - data.stockStatus !== undefined ? data.stockStatus : undefined, + data.stockStatus !== undefined + ? data.stockStatus + : (data.stock !== undefined + ? (Number(data.stock) <= 0 ? 'OUT_OF_STOCK' : 'IN_STOCK') + : undefined), noIndex: data.noIndex !== undefined ? data.noIndex : undefined, noFollow: data.noFollow !== undefined ? data.noFollow : undefined, ogImage: data.ogImage !== undefined ? data.ogImage : undefined, diff --git a/backend/src/admin/dto/product.dto.ts b/backend/src/admin/dto/product.dto.ts index c44b0832..ffcdefd0 100644 --- a/backend/src/admin/dto/product.dto.ts +++ b/backend/src/admin/dto/product.dto.ts @@ -241,6 +241,11 @@ export class ProductDto { @IsString() stockStatus?: 'IN_STOCK' | 'OUT_OF_STOCK' | 'PRE_ORDER' | 'DISCONTINUED'; + @ApiPropertyOptional({ description: 'تعداد موجودی در انبار' }) + @IsOptional() + @IsNumber() + stock?: number; + @ApiPropertyOptional({ description: 'عدم ایندکس توسط موتورهای جستجو' }) @IsOptional() @IsBoolean() diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index c14d644e..567ac2f1 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -141,18 +141,23 @@ export class OrdersService { const productMap = new Map(products.map((p) => [p.id, p])); - for (const productId of productIds) { - const product = productMap.get(productId); + for (const item of createOrderDto.items) { + const product = productMap.get(item.productId); if (!product) { throw new NotFoundException(`محصول یافت نشد`); } const isOutOfStock = product.stockStatus === 'OUT_OF_STOCK' || product.stockStatus === 'DISCONTINUED' || - (product.packageSize !== null && Number(product.packageSize) <= 0); + product.stock <= 0; if (isOutOfStock) { throw new BadRequestException( - `محصول «${product.nameFa || product.name}» در حال حاضر ناموجود است و امکان ثبت سفارش آن وجود ندارد`, + `محصول «${product.nameFa || (product as any).name}» در حال حاضر ناموجود است و امکان ثبت سفارش آن وجود ندارد`, + ); + } + if (item.quantity > product.stock) { + throw new BadRequestException( + `تعداد درخواستی برای محصول «${product.nameFa || (product as any).name}» (${item.quantity} عدد) بیشتر از موجودی انبار (${product.stock} عدد) است`, ); } } @@ -272,6 +277,22 @@ export class OrdersService { .catch(() => {}); } + // Deduct inventory atomically for wallet orders + for (const item of createOrderDto.items) { + const updated = await tx.product.update({ + where: { id: item.productId }, + data: { + stock: { decrement: item.quantity }, + }, + }); + if (updated.stock <= 0) { + await tx.product.update({ + where: { id: item.productId }, + data: { stockStatus: 'OUT_OF_STOCK' }, + }); + } + } + return newOrder; }); @@ -289,27 +310,49 @@ export class OrdersService { const isOnline = createOrderDto.paymentMethod === 'online'; const initialStatus = isOnline ? 'pending_payment' : 'processing'; - const createdOrder = await this.prisma.order.create({ - data: { - userId, - couponId, - totalAmount: Number(finalAmount), - charityDonation: Number(charityAmount), - isRefill: Boolean(createOrderDto.isRefill), - refillIntervalDays: createOrderDto.refillIntervalDays || 60, - trackingNumber, - status: initialStatus, - paymentMethod: createOrderDto.paymentMethod || 'card', - shippingAddress: createOrderDto.shippingAddress, - orderItems: { - create: orderItemsData, + const createdOrder = await this.prisma.$transaction(async (tx) => { + const order = await tx.order.create({ + data: { + userId, + couponId, + totalAmount: Number(finalAmount), + charityDonation: Number(charityAmount), + isRefill: Boolean(createOrderDto.isRefill), + refillIntervalDays: createOrderDto.refillIntervalDays || 60, + trackingNumber, + status: initialStatus, + paymentMethod: createOrderDto.paymentMethod || 'card', + shippingAddress: createOrderDto.shippingAddress, + orderItems: { + create: orderItemsData, + }, }, - }, - include: { - orderItems: { - include: { product: true }, + include: { + orderItems: { + include: { product: true }, + }, }, - }, + }); + + // Deduct inventory immediately for non-online orders (card to card) + if (!isOnline) { + for (const item of createOrderDto.items) { + const updated = await tx.product.update({ + where: { id: item.productId }, + data: { + stock: { decrement: item.quantity }, + }, + }); + if (updated.stock <= 0) { + await tx.product.update({ + where: { id: item.productId }, + data: { stockStatus: 'OUT_OF_STOCK' }, + }); + } + } + } + + return order; }); // Send Order Confirmation SMS (for card-to-card or non-online orders, online orders get SMS on verify) diff --git a/backend/src/payment/payment.service.ts b/backend/src/payment/payment.service.ts index c0b453df..d709df78 100644 --- a/backend/src/payment/payment.service.ts +++ b/backend/src/payment/payment.service.ts @@ -433,12 +433,36 @@ export class PaymentService { }, }); - // Mark inventory reservations as CONSUMED + // Mark inventory reservations as CONSUMED and decrement product stock await tx.inventoryReservation.updateMany({ where: { orderId: transaction.orderId, status: 'ACTIVE' }, data: { status: 'CONSUMED' }, }); + const orderWithItems = await tx.order.findUnique({ + where: { id: transaction.orderId }, + include: { orderItems: true }, + }); + + if (orderWithItems?.orderItems) { + for (const item of orderWithItems.orderItems) { + if (item.productId) { + const updated = await tx.product.update({ + where: { id: item.productId }, + data: { + stock: { decrement: item.quantity }, + }, + }); + if (updated.stock <= 0) { + await tx.product.update({ + where: { id: item.productId }, + data: { stockStatus: 'OUT_OF_STOCK' }, + }); + } + } + } + } + // If charity donation was made, update user's total charity if ( transaction.order && diff --git a/backend/src/products/torob.controller.ts b/backend/src/products/torob.controller.ts index ac0c420e..3359d89e 100644 --- a/backend/src/products/torob.controller.ts +++ b/backend/src/products/torob.controller.ts @@ -187,7 +187,7 @@ export class TorobController { const isInStock = product.stockStatus !== 'DISCONTINUED' && product.stockStatus !== 'OUT_OF_STOCK' && - (product.packageSize === null || Number(product.packageSize) > 0) && + (product.stock === undefined || product.stock > 0) && String(product.stockStatus || '') .toLowerCase() .includes('in'); diff --git a/frontend/admin-panel/src/pages/Products.tsx b/frontend/admin-panel/src/pages/Products.tsx index ed066909..f6330121 100644 --- a/frontend/admin-panel/src/pages/Products.tsx +++ b/frontend/admin-panel/src/pages/Products.tsx @@ -96,6 +96,7 @@ export interface Product { keywords?: string; canonicalUrl?: string; slug?: string; + stock?: number; stockStatus?: 'IN_STOCK' | 'OUT_OF_STOCK' | 'PRE_ORDER' | 'DISCONTINUED'; noIndex?: boolean; noFollow?: boolean; @@ -249,6 +250,7 @@ export default function Products() { priceDisplay: '', unit: '', packageSize: '' as number | string, + stock: '' as number | string, dosageLogic: '', suitableFor: 'سگ و گربه', imageUrl: '', @@ -518,6 +520,7 @@ export default function Products() { priceDisplay: product.priceDisplay || '', unit: product.unit || '', packageSize: product.packageSize !== undefined && product.packageSize !== null ? Number(product.packageSize) : '', + stock: product.stock !== undefined && product.stock !== null ? Number(product.stock) : (product.stockStatus === 'OUT_OF_STOCK' ? 0 : 100), dosageLogic: product.dosageLogic || '', feedingAdvice: dosageConfig.feedingAdvice || product.feedingAdvice || product.dosageLogic || '', showFaqs: dosageConfig.showFaqs !== undefined ? Boolean(dosageConfig.showFaqs) : (product.showFaqs !== undefined ? Boolean(product.showFaqs) : true), @@ -576,7 +579,7 @@ export default function Products() { wholesaleMarginPercent: pricingSettings.defaultWholesaleMarginPercent, roundingStep: '', roundingMode: '', - priceDisplay: '', unit: '', packageSize: '', dosageLogic: '', + priceDisplay: '', unit: '', packageSize: '', stock: '', dosageLogic: '', feedingAdvice: '', showFaqs: true, faqs: [], @@ -906,7 +909,8 @@ export default function Products() { roundingMode: formData.roundingMode || null, priceDisplay: formData.priceDisplay || `${Number(formData.priceValue || 0).toLocaleString('fa-IR')} تومان`, unit: (formData.unit || '').trim() || undefined, - packageSize: Number(formData.packageSize) || 0, + packageSize: formData.packageSize !== '' ? Number(formData.packageSize) : 100, + stock: formData.stock !== '' ? Number(formData.stock) : (formData.stockStatus === 'OUT_OF_STOCK' ? 0 : 100), dosageLogic: (formData.dosageLogic || '').trim() || undefined, suitableFor: formData.suitableFor || 'سگ و گربه', imageUrl: (formData.imageUrl || '').trim() || undefined, @@ -927,7 +931,7 @@ export default function Products() { metaDescription: (formData.metaDescription || '').trim() || formData.shortDescription || 'خرید آنلاین مکمل اصل کنینا آلمان با بالاترین کیفیت بالینی...', keywords: (formData.keywords || '').trim() || undefined, canonicalUrl: (formData.canonicalUrl || '').trim() || `/shop/${derivedSlug}`, - stockStatus: (Number(formData.packageSize) <= 0) ? 'OUT_OF_STOCK' : (formData.stockStatus || 'IN_STOCK'), + stockStatus: (formData.stock !== '' && Number(formData.stock) <= 0) ? 'OUT_OF_STOCK' : (formData.stockStatus || 'IN_STOCK'), noIndex: Boolean(formData.noIndex), noFollow: Boolean(formData.noFollow), ogImage: (formData.ogImage || '').trim() || undefined, @@ -1303,7 +1307,14 @@ export default function Products() {
{Number(product.priceValue).toLocaleString()} تومان - {product.packageSize} موجودی +
+ 0 ? 'text-emerald-600' : 'text-rose-600'}`}> + {product.stock !== undefined ? `${product.stock} عدد موجود` : (product.stockStatus === 'OUT_OF_STOCK' ? 'ناموجود' : 'موجود')} + + {product.packageSize && ( + ({product.packageSize} {product.unit || 'واحد'}) + )} +
@@ -2822,23 +2833,39 @@ export default function Products() { -
+
- + setFormData({ ...formData, stock: e.target.value === '' ? '' : Number(e.target.value) })} + className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-left font-mono font-bold" + dir="ltr" + /> + تعداد فیزیکی کالا برای خرید و کنترل سقف سفارش +
+
+ + setFormData({ ...formData, packageSize: e.target.value === '' ? '' : Number(e.target.value) })} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-left font-mono font-bold" dir="ltr" /> + جهت محاسبه روز مصرف و سئو
- setFormData({ ...formData, unit: e.target.value })} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm" /> + setFormData({ ...formData, unit: e.target.value })} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm" /> + واحد بسته (گرم، قرص، میلی‌لیتر)
diff --git a/frontend/application/app/ClientLayout.tsx b/frontend/application/app/ClientLayout.tsx index b1eed048..dadb3d00 100644 --- a/frontend/application/app/ClientLayout.tsx +++ b/frontend/application/app/ClientLayout.tsx @@ -231,7 +231,13 @@ export default function ClientLayout({ children }: { children: React.ReactNode } onClose={() => setIsPrescriptionModalOpen(false)} /> setIsPrescriptionModalOpen(true)} + onPrescriptionOpen={() => { + if (!isLoggedIn) { + setAuthModalOpen(true); + } else { + setIsPrescriptionModalOpen(true); + } + }} /> diff --git a/frontend/application/app/shop/[slug]/page.tsx b/frontend/application/app/shop/[slug]/page.tsx index f9263e34..3cf4d1f1 100644 --- a/frontend/application/app/shop/[slug]/page.tsx +++ b/frontend/application/app/shop/[slug]/page.tsx @@ -122,10 +122,10 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl const productUrl = `${siteUrl}/shop/${resolvedParams.slug}`; const priceInRial = product.priceValue * 10; - // Map stock status and packageSize to Schema.org availability + // Map stock status and stock quantity to Schema.org availability const isOutOfStock = product.stockStatus === 'OUT_OF_STOCK' || - (typeof product.packageSize === 'number' && product.packageSize <= 0); + (typeof product.stock === 'number' && product.stock <= 0); let availabilityUrl = 'https://schema.org/InStock'; if (product.stockStatus === 'DISCONTINUED') { diff --git a/frontend/application/components/Header.tsx b/frontend/application/components/Header.tsx index ad17a436..d54a2f65 100644 --- a/frontend/application/components/Header.tsx +++ b/frontend/application/components/Header.tsx @@ -250,7 +250,13 @@ export default function Header({ {/* Prescription Upload Button (Desktop & Mobile) */} {isPrescriptionEnabled && (
} /> + }> + Admin Dashboard Content} /> + + + + ); + }; + + it('renders protected child content immediately when already authenticated with ADMIN role', async () => { + useAdminAuthStore.getState().setAuth('valid-token', regularAdminUser); + + renderWithRouter(); + + expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument(); + }); + + it('renders protected child content immediately when authenticated with SUPER_ADMIN role', async () => { + useAdminAuthStore.getState().setAuth('valid-token', superAdminUser); + + renderWithRouter(); + + expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument(); + }); + + it('redirects to /login if user is authenticated but does not have ADMIN or SUPER_ADMIN role', async () => { + useAdminAuthStore.getState().setAuth('valid-token', customerUser); + + renderWithRouter(); + + expect(await screen.findByText('Login Page')).toBeInTheDocument(); + expect(screen.queryByText('Admin Dashboard Content')).not.toBeInTheDocument(); + }); + + it('redirects to /login when completely unauthenticated (no token, no user)', async () => { + renderWithRouter(); + + expect(await screen.findByText('Login Page')).toBeInTheDocument(); + expect(screen.queryByText('Admin Dashboard Content')).not.toBeInTheDocument(); + }); + + it('refreshes token successfully via /auth/refresh when accessToken exists but state is unauthenticated', async () => { + useAdminAuthStore.setState({ + accessToken: 'stale-token', + isAuthenticated: false, + adminUser: null, + }); + + vi.mocked(api.post).mockResolvedValueOnce({ + data: { + success: true, + data: { + accessToken: 'fresh-token', + user: regularAdminUser, + }, + }, + }); + + renderWithRouter(); + + expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument(); + expect(api.post).toHaveBeenCalledWith('/auth/refresh'); + expect(useAdminAuthStore.getState().accessToken).toBe('fresh-token'); + expect(useAdminAuthStore.getState().isAuthenticated).toBe(true); + }); + + it('falls back to /users/profile when /auth/refresh fails, and succeeds if profile is valid', async () => { + useAdminAuthStore.setState({ + accessToken: 'persisted-token', + isAuthenticated: false, + adminUser: null, + }); + + vi.mocked(api.post).mockRejectedValueOnce(new Error('Refresh failed')); + vi.mocked(api.get).mockResolvedValueOnce({ + data: { + success: true, + data: superAdminUser, + }, + }); + + renderWithRouter(); + + expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument(); + expect(api.get).toHaveBeenCalledWith('/users/profile'); + expect(useAdminAuthStore.getState().isAuthenticated).toBe(true); + }); + + it('clears auth and redirects to /login when both refresh and profile validation fail', async () => { + useAdminAuthStore.setState({ + accessToken: 'invalid-token', + isAuthenticated: false, + adminUser: null, + }); + + vi.mocked(api.post).mockRejectedValueOnce(new Error('Refresh failed')); + vi.mocked(api.get).mockRejectedValueOnce(new Error('Profile failed')); + + renderWithRouter(); + + expect(await screen.findByText('Login Page')).toBeInTheDocument(); + await waitFor(() => { + expect(useAdminAuthStore.getState().isAuthenticated).toBe(false); + expect(useAdminAuthStore.getState().accessToken).toBeNull(); + }); + }); +}); diff --git a/frontend/admin-panel/src/components/ProtectedRoute.tsx b/frontend/admin-panel/src/components/ProtectedRoute.tsx index 0e8378ab..a4a8d400 100644 --- a/frontend/admin-panel/src/components/ProtectedRoute.tsx +++ b/frontend/admin-panel/src/components/ProtectedRoute.tsx @@ -1,8 +1,8 @@ -import { useState, useEffect } from 'react'; -import { Navigate, Outlet } from 'react-router-dom'; +import { useEffect,useState } from 'react'; +import { Navigate,Outlet } from 'react-router-dom'; import api from '../services/api'; import { useAdminAuthStore } from '../store/adminAuthStore'; -import type { ApiResponse, AuthResponseData, AdminUser } from '../types/admin'; +import type { AdminUser,ApiResponse,AuthResponseData } from '../types/admin'; export default function ProtectedRoute() { const { isAuthenticated, accessToken, setAuth, clearAuth } = useAdminAuthStore(); diff --git a/frontend/admin-panel/src/components/RouteErrorBoundary.tsx b/frontend/admin-panel/src/components/RouteErrorBoundary.tsx index 35a4be59..d610d4a8 100644 --- a/frontend/admin-panel/src/components/RouteErrorBoundary.tsx +++ b/frontend/admin-panel/src/components/RouteErrorBoundary.tsx @@ -1,5 +1,5 @@ -import { Component, ReactNode, ErrorInfo } from 'react'; -import { AlertCircle, RefreshCw, Home } from 'lucide-react'; +import { AlertCircle,Home,RefreshCw } from 'lucide-react'; +import { Component,type ErrorInfo,type ReactNode } from 'react'; interface Props { children: ReactNode; diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index bb4f2e1c..46d1c1be 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -1,43 +1,43 @@ -import { useState, useEffect, useRef } from 'react'; -import { Link, useLocation } from 'react-router-dom'; import { - LayoutDashboard, - TrendingUp, - ShoppingCart, - Receipt, - Package, - FolderTree, - Tag, - Sparkles, - FileText, - Users, - Heart, - MessageSquare, - Building2, - PhoneCall, - Image, - FlaskConical, - MessageSquareQuote, - BookOpen, - Video, - Settings, - ShieldCheck, - Languages, - UserCheck, - DollarSign, - CreditCard, - Truck, - Sliders, - Globe, - ChevronDown, - Star, - Layers, - HelpCircle, - Menu, - RotateCcw, - Activity, - Key, +Activity, +BookOpen, +Building2, +ChevronDown, +CreditCard, +DollarSign, +FileText, +FlaskConical, +FolderTree, +Globe, +Heart, +HelpCircle, +Image, +Key, +Languages, +Layers, +LayoutDashboard, +Menu, +MessageSquare, +MessageSquareQuote, +Package, +PhoneCall, +Receipt, +RotateCcw, +Settings, +ShieldCheck, +ShoppingCart, +Sliders, +Sparkles, +Star, +Tag, +TrendingUp, +Truck, +UserCheck, +Users, +Video, } from 'lucide-react'; +import { useEffect,useRef,useState } from 'react'; +import { Link,useLocation } from 'react-router-dom'; import api from '../services/api'; interface SubMenuItem { diff --git a/frontend/admin-panel/src/components/Topbar.tsx b/frontend/admin-panel/src/components/Topbar.tsx index 3f1c317d..a6251fa9 100644 --- a/frontend/admin-panel/src/components/Topbar.tsx +++ b/frontend/admin-panel/src/components/Topbar.tsx @@ -1,7 +1,7 @@ -import { useState, useRef, useEffect } from 'react'; -import { useNavigate, Link } from 'react-router-dom'; -import { Search, UserCircle, Menu, Activity, ShieldCheck, MessageSquare, Calendar, Clock, RefreshCw, PanelRightClose, PanelRightOpen } from 'lucide-react'; +import { Activity,Clock,Menu,PanelRightClose,PanelRightOpen,Search,UserCircle } from 'lucide-react'; +import { useEffect,useRef,useState } from 'react'; import { toast } from 'react-hot-toast'; +import { Link,useNavigate } from 'react-router-dom'; import api from '../services/api'; import { useAdminAuthStore } from '../store/adminAuthStore'; diff --git a/frontend/admin-panel/src/components/TransactionReceiptModal.tsx b/frontend/admin-panel/src/components/TransactionReceiptModal.tsx index 12139261..09f9b9e6 100644 --- a/frontend/admin-panel/src/components/TransactionReceiptModal.tsx +++ b/frontend/admin-panel/src/components/TransactionReceiptModal.tsx @@ -1,5 +1,4 @@ -import React from 'react'; -import { Printer, X, CheckCircle2, ShieldCheck, Copy } from 'lucide-react'; +import { Copy,Printer,ShieldCheck,X } from 'lucide-react'; import { toast } from 'react-hot-toast'; import Button from './ui/Button'; diff --git a/frontend/admin-panel/src/components/ui/Button.test.tsx b/frontend/admin-panel/src/components/ui/Button.test.tsx new file mode 100644 index 00000000..b4514970 --- /dev/null +++ b/frontend/admin-panel/src/components/ui/Button.test.tsx @@ -0,0 +1,62 @@ +import { fireEvent,render,screen } from '@testing-library/react'; +import { describe,expect,it,vi } from 'vitest'; +import Button from './Button'; + +describe('Button Component', () => { + it('renders children correctly', () => { + render(); + expect(screen.getByRole('button', { name: 'کلیک کنید' })).toBeInTheDocument(); + }); + + it('renders with different variants and size styling classes', () => { + const { rerender } = render(); + let btn = screen.getByRole('button'); + expect(btn.className).toContain('bg-rose-600'); + expect(btn.className).toContain('px-3'); + + rerender(); + btn = screen.getByRole('button'); + expect(btn.className).toContain('bg-emerald-600'); + expect(btn.className).toContain('px-5'); + }); + + it('handles click events when enabled', () => { + const handleClick = vi.fn(); + render(); + + fireEvent.click(screen.getByRole('button')); + expect(handleClick).toHaveBeenCalledTimes(1); + }); + + it('shows spinner and disables button when isLoading is true', () => { + const handleClick = vi.fn(); + render(); + + const btn = screen.getByRole('button'); + expect(btn).toBeDisabled(); + expect(screen.queryByText('ارسال')).not.toBeInTheDocument(); + + fireEvent.click(btn); + expect(handleClick).not.toHaveBeenCalled(); + }); + + it('renders startIcon, endIcon, badge, and info tooltip correctly', () => { + const MockIcon = ({ className }: { className?: string }) => ; + + render( + + ); + + const icons = screen.getAllByTestId('mock-icon'); + expect(icons.length).toBe(2); + expect(screen.getByText('5')).toBeInTheDocument(); + expect(screen.getByTitle('اطلاعات کمکی')).toBeInTheDocument(); + }); +}); diff --git a/frontend/admin-panel/src/components/ui/Button.tsx b/frontend/admin-panel/src/components/ui/Button.tsx index bf7a1fd2..38995dd6 100644 --- a/frontend/admin-panel/src/components/ui/Button.tsx +++ b/frontend/admin-panel/src/components/ui/Button.tsx @@ -1,5 +1,5 @@ -import React from 'react'; import { Info } from 'lucide-react'; +import React from 'react'; import Spinner from './Spinner'; export type ButtonVariant = diff --git a/frontend/admin-panel/src/components/ui/ConfirmModal.test.tsx b/frontend/admin-panel/src/components/ui/ConfirmModal.test.tsx new file mode 100644 index 00000000..7652aa24 --- /dev/null +++ b/frontend/admin-panel/src/components/ui/ConfirmModal.test.tsx @@ -0,0 +1,97 @@ +import { fireEvent,render,screen } from '@testing-library/react'; +import { describe,expect,it,vi } from 'vitest'; +import ConfirmModal from './ConfirmModal'; + +describe('ConfirmModal Component', () => { + const defaultProps = { + isOpen: true, + title: 'حذف آیتم', + message: 'آیا از حذف این آیتم اطمینان دارید؟', + onConfirm: vi.fn(), + onCancel: vi.fn(), + }; + + it('does not render when isOpen is false', () => { + const { container } = render(); + expect(container.firstChild).toBeNull(); + }); + + it('renders title, message, and default button texts when isOpen is true', () => { + render(); + + expect(screen.getByText('حذف آیتم')).toBeInTheDocument(); + expect(screen.getByText('آیا از حذف این آیتم اطمینان دارید؟')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'تایید' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'لغو' })).toBeInTheDocument(); + }); + + it('calls onConfirm when confirm button is clicked', () => { + const onConfirmMock = vi.fn(); + render(); + + const confirmButton = screen.getByRole('button', { name: 'تایید' }); + fireEvent.click(confirmButton); + + expect(onConfirmMock).toHaveBeenCalledTimes(1); + }); + + it('calls onCancel when cancel button or close X is clicked', () => { + const onCancelMock = vi.fn(); + render(); + + const cancelButton = screen.getByRole('button', { name: 'لغو' }); + fireEvent.click(cancelButton); + expect(onCancelMock).toHaveBeenCalledTimes(1); + + const buttons = screen.getAllByRole('button'); + const closeIconButton = buttons[0]; + fireEvent.click(closeIconButton); + expect(onCancelMock).toHaveBeenCalledTimes(2); + }); + + it('renders custom confirm and cancel texts', () => { + render( + + ); + + expect(screen.getByRole('button', { name: 'بله، حذف کن' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'انصراف' })).toBeInTheDocument(); + }); + + it('disables buttons and shows loading text when isLoading is true', () => { + const onConfirmMock = vi.fn(); + const onCancelMock = vi.fn(); + + render( + + ); + + const confirmButton = screen.getByRole('button', { name: 'در حال پردازش...' }); + const cancelButton = screen.getByRole('button', { name: 'لغو' }); + + expect(confirmButton).toBeDisabled(); + expect(cancelButton).toBeDisabled(); + + fireEvent.click(confirmButton); + fireEvent.click(cancelButton); + + expect(onConfirmMock).not.toHaveBeenCalled(); + expect(onCancelMock).not.toHaveBeenCalled(); + }); + + it('applies non-destructive styling when isDestructive is false', () => { + render(); + + const confirmButton = screen.getByRole('button', { name: 'تایید' }); + expect(confirmButton.className).toContain('bg-purple-600'); + }); +}); diff --git a/frontend/admin-panel/src/components/ui/ConfirmModal.tsx b/frontend/admin-panel/src/components/ui/ConfirmModal.tsx index a32569a0..0d79f072 100644 --- a/frontend/admin-panel/src/components/ui/ConfirmModal.tsx +++ b/frontend/admin-panel/src/components/ui/ConfirmModal.tsx @@ -1,4 +1,4 @@ -import { X, AlertTriangle } from 'lucide-react'; +import { AlertTriangle,X } from 'lucide-react'; interface ConfirmModalProps { isOpen: boolean; diff --git a/frontend/admin-panel/src/components/ui/FormField.tsx b/frontend/admin-panel/src/components/ui/FormField.tsx index 61fc20f1..be22009b 100644 --- a/frontend/admin-panel/src/components/ui/FormField.tsx +++ b/frontend/admin-panel/src/components/ui/FormField.tsx @@ -1,5 +1,5 @@ -import React from 'react'; import { HelpCircle } from 'lucide-react'; +import React from 'react'; export interface FormFieldProps { label?: string; diff --git a/frontend/admin-panel/src/components/ui/IconPickerModal.tsx b/frontend/admin-panel/src/components/ui/IconPickerModal.tsx index b684cb87..b9b7b363 100644 --- a/frontend/admin-panel/src/components/ui/IconPickerModal.tsx +++ b/frontend/admin-panel/src/components/ui/IconPickerModal.tsx @@ -1,45 +1,45 @@ -import React, { useState, useMemo } from 'react'; import { - X, - Search, - Check, - Smile, - Pill, - ShieldCheck, - HeartPulse, - Sparkles, - ShoppingBag, - User, - Building2, - PhoneCall, - Activity, - Heart, - Dog, - BookOpen, - FileText, - Video, - Award, - Star, - Truck, - HelpCircle, - MessageSquare, - Globe, - Settings, - Flame, - CheckCircle2, - AlertCircle, - ThumbsUp, - Package, - Layers, - Compass, - MapPin, - Mail, - Send, - Zap, - Tag, - Gift, - Clock, +Activity, +AlertCircle, +Award, +BookOpen, +Building2, +Check, +CheckCircle2, +Clock, +Compass, +Dog, +FileText, +Flame, +Gift, +Globe, +Heart, +HeartPulse, +HelpCircle, +Layers, +Mail, +MapPin, +MessageSquare, +Package, +PhoneCall, +Pill, +Search, +Send, +Settings, +ShieldCheck, +ShoppingBag, +Smile, +Sparkles, +Star, +Tag, +ThumbsUp, +Truck, +User, +Video, +X, +Zap, } from 'lucide-react'; +import React,{ useMemo,useState } from 'react'; interface IconPickerModalProps { isOpen: boolean; diff --git a/frontend/admin-panel/src/components/ui/ImagePreviewModal.tsx b/frontend/admin-panel/src/components/ui/ImagePreviewModal.tsx index deb93dc3..1bc9cf2c 100644 --- a/frontend/admin-panel/src/components/ui/ImagePreviewModal.tsx +++ b/frontend/admin-panel/src/components/ui/ImagePreviewModal.tsx @@ -1,5 +1,5 @@ -import React, { useEffect } from 'react'; -import { X, ZoomIn, ZoomOut, Download, ExternalLink } from 'lucide-react'; +import { ExternalLink,X,ZoomIn,ZoomOut } from 'lucide-react'; +import React,{ useEffect } from 'react'; export interface ImagePreviewModalProps { isOpen: boolean; diff --git a/frontend/admin-panel/src/components/ui/Input.tsx b/frontend/admin-panel/src/components/ui/Input.tsx index 09f37d32..fa974bdc 100644 --- a/frontend/admin-panel/src/components/ui/Input.tsx +++ b/frontend/admin-panel/src/components/ui/Input.tsx @@ -1,4 +1,4 @@ -import React, { forwardRef } from 'react'; +import React,{ forwardRef } from 'react'; export interface InputProps extends React.InputHTMLAttributes { error?: string; diff --git a/frontend/admin-panel/src/components/ui/MaskableField.tsx b/frontend/admin-panel/src/components/ui/MaskableField.tsx index be4e48e7..e5f2104f 100644 --- a/frontend/admin-panel/src/components/ui/MaskableField.tsx +++ b/frontend/admin-panel/src/components/ui/MaskableField.tsx @@ -1,5 +1,5 @@ -import React, { useState } from 'react'; -import { Eye, EyeOff, Copy, Check } from 'lucide-react'; +import { Check,Copy,Eye,EyeOff } from 'lucide-react'; +import React,{ useState } from 'react'; import { toast } from 'react-hot-toast'; interface MaskableFieldProps { diff --git a/frontend/admin-panel/src/components/ui/MediaSelector.test.tsx b/frontend/admin-panel/src/components/ui/MediaSelector.test.tsx new file mode 100644 index 00000000..9cabfaf3 --- /dev/null +++ b/frontend/admin-panel/src/components/ui/MediaSelector.test.tsx @@ -0,0 +1,188 @@ +import { fireEvent,render,screen,waitFor } from '@testing-library/react'; +import { beforeEach,describe,expect,it,vi } from 'vitest'; +import api from '../../services/api'; +import MediaSelector from './MediaSelector'; + +vi.mock('../../services/api', () => ({ + default: { + get: vi.fn(), + post: vi.fn(), + delete: vi.fn(), + }, + BASE_DOMAIN: 'https://test.canina.ir', +})); + +describe('MediaSelector Modal Component', () => { + const mockMediaData = [ + { + id: 'media-1', + url: '/uploads/product-1.jpg', + filename: 'product-1.jpg', + createdAt: '2025-01-01T10:00:00Z', + mimetype: 'image/jpeg', + }, + { + id: 'media-2', + url: '/uploads/guide-video.mp4', + filename: 'guide-video.mp4', + createdAt: '2025-01-02T10:00:00Z', + mimetype: 'video/mp4', + }, + { + id: 'media-3', + url: '/uploads/catalog.pdf', + filename: 'catalog.pdf', + createdAt: '2025-01-03T10:00:00Z', + mimetype: 'application/pdf', + }, + ]; + + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(api.get).mockResolvedValue({ + data: { success: true, data: mockMediaData }, + }); + }); + + it('renders nothing when isOpen is false', () => { + const { container } = render( + + ); + expect(container.firstChild).toBeNull(); + }); + + it('fetches and displays media items when isOpen is true', async () => { + render( + + ); + + expect(await screen.findByText('گالری و مدیریت رسانه')).toBeInTheDocument(); + expect(await screen.findByText('product-1.jpg')).toBeInTheDocument(); + expect(screen.getByText('guide-video.mp4')).toBeInTheDocument(); + expect(screen.getByText('catalog.pdf')).toBeInTheDocument(); + expect(api.get).toHaveBeenCalledWith('/admin/media'); + }); + + it('filters media list by file type tabs', async () => { + render( + + ); + + expect(await screen.findByText('product-1.jpg')).toBeInTheDocument(); + + // Click 'ویدئوها' tab + const videoTab = screen.getByRole('button', { name: 'ویدئوها' }); + fireEvent.click(videoTab); + + // Only video should remain visible + expect(screen.getByText('guide-video.mp4')).toBeInTheDocument(); + expect(screen.queryByText('product-1.jpg')).not.toBeInTheDocument(); + expect(screen.queryByText('catalog.pdf')).not.toBeInTheDocument(); + + // Click 'اسناد PDF' tab + const pdfTab = screen.getByRole('button', { name: 'اسناد PDF' }); + fireEvent.click(pdfTab); + + expect(screen.getByText('catalog.pdf')).toBeInTheDocument(); + expect(screen.queryByText('guide-video.mp4')).not.toBeInTheDocument(); + }); + + it('selects an item on click and confirms selection with the footer button', async () => { + const onSelect = vi.fn(); + const onClose = vi.fn(); + + render( + + ); + + expect(await screen.findByText('product-1.jpg')).toBeInTheDocument(); + + const submitBtn = screen.getByRole('button', { name: /انتخاب و ثبت فایل/i }); + expect(submitBtn).toBeDisabled(); + + // Click on the product card + const cardText = screen.getByText('product-1.jpg'); + fireEvent.click(cardText); + + // Now submit button should be enabled + expect(submitBtn).not.toBeDisabled(); + expect(screen.getByText(/۱ فایل انتخاب شد/i)).toBeInTheDocument(); + + // Click submit + fireEvent.click(submitBtn); + + expect(onSelect).toHaveBeenCalledWith('https://test.canina.ir/uploads/product-1.jpg'); + expect(onClose).toHaveBeenCalled(); + }); + + it('immediately confirms and closes on card double-click', async () => { + const onSelect = vi.fn(); + const onClose = vi.fn(); + + render( + + ); + + const cardText = await screen.findByText('product-1.jpg'); + fireEvent.doubleClick(cardText); + + expect(onSelect).toHaveBeenCalledWith('https://test.canina.ir/uploads/product-1.jpg'); + expect(onClose).toHaveBeenCalled(); + }); + + it('opens preview modal when eye button is clicked', async () => { + render( + + ); + + expect(await screen.findByText('product-1.jpg')).toBeInTheDocument(); + + const eyeButtons = screen.getAllByTitle('مشاهده'); + expect(eyeButtons.length).toBeGreaterThan(0); + fireEvent.click(eyeButtons[0]); + + // Modal or preview image should be triggered + await waitFor(() => { + const previewImg = document.querySelector('img[src="https://test.canina.ir/uploads/product-1.jpg"]'); + expect(previewImg).toBeInTheDocument(); + }); + }); + + it('triggers delete confirm modal and executes delete on confirmation', async () => { + vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } }); + + render( + + ); + + expect(await screen.findByText('product-1.jpg')).toBeInTheDocument(); + + const deleteButtons = screen.getAllByTitle('حذف فایل'); + fireEvent.click(deleteButtons[0]); + + expect(await screen.findByText('حذف تصویر')).toBeInTheDocument(); + expect(screen.getByText(/آیا از حذف این تصویر مطمئن هستید؟/i)).toBeInTheDocument(); + + // Confirm deletion + const confirmBtn = screen.getByRole('button', { name: /تایید/i }); + fireEvent.click(confirmBtn); + + await waitFor(() => { + expect(api.delete).toHaveBeenCalledWith('/admin/media/media-1'); + expect(screen.queryByText('product-1.jpg')).not.toBeInTheDocument(); + }); + }); + + it('calls onClose when clicking close icon or cancel button', async () => { + const onClose = vi.fn(); + render( + + ); + + await screen.findByText('گالری و مدیریت رسانه'); + + const cancelBtn = screen.getByRole('button', { name: 'انصراف' }); + fireEvent.click(cancelBtn); + expect(onClose).toHaveBeenCalled(); + }); +}); diff --git a/frontend/admin-panel/src/components/ui/MediaSelector.tsx b/frontend/admin-panel/src/components/ui/MediaSelector.tsx index 69489678..2befb4dd 100644 --- a/frontend/admin-panel/src/components/ui/MediaSelector.tsx +++ b/frontend/admin-panel/src/components/ui/MediaSelector.tsx @@ -1,11 +1,11 @@ -import { useState, useEffect, useRef, useCallback } from 'react'; -import { X, Upload, Image as ImageIcon, Trash2, CheckCircle2, Clipboard, Eye, Video, FileText, Music, Play } from 'lucide-react'; +import { CheckCircle2,Clipboard,Eye,FileText,Image as ImageIcon,Music,Play,Trash2,Upload,X } from 'lucide-react'; +import { useCallback,useEffect,useRef,useState } from 'react'; import { toast } from 'react-hot-toast'; -import api, { BASE_DOMAIN } from '../../services/api'; -import Spinner from './Spinner'; -import Pagination from './Pagination'; +import api,{ BASE_DOMAIN } from '../../services/api'; import ConfirmModal from './ConfirmModal'; import ImagePreviewModal from './ImagePreviewModal'; +import Pagination from './Pagination'; +import Spinner from './Spinner'; interface Media { id: string; diff --git a/frontend/admin-panel/src/components/ui/Modal.tsx b/frontend/admin-panel/src/components/ui/Modal.tsx index 242b7bab..3e448822 100644 --- a/frontend/admin-panel/src/components/ui/Modal.tsx +++ b/frontend/admin-panel/src/components/ui/Modal.tsx @@ -1,5 +1,5 @@ -import React, { useEffect } from 'react'; import { X } from 'lucide-react'; +import React,{ useEffect } from 'react'; export interface ModalProps { isOpen: boolean; diff --git a/frontend/admin-panel/src/components/ui/Pagination.test.tsx b/frontend/admin-panel/src/components/ui/Pagination.test.tsx new file mode 100644 index 00000000..cb2faef9 --- /dev/null +++ b/frontend/admin-panel/src/components/ui/Pagination.test.tsx @@ -0,0 +1,111 @@ +import { fireEvent,render,screen } from '@testing-library/react'; +import { describe,expect,it,vi } from 'vitest'; +import Pagination from './Pagination'; + +describe('Pagination Component', () => { + it('renders nothing when totalPages is 1 or less', () => { + const { container: c1 } = render( + + ); + expect(c1.firstChild).toBeNull(); + + const { container: c0 } = render( + + ); + expect(c0.firstChild).toBeNull(); + }); + + it('renders navigation buttons and page numbers when totalPages > 1', () => { + render( + + ); + + expect(screen.getByTitle('صفحه اول')).toBeInTheDocument(); + expect(screen.getByTitle('صفحه قبلی')).toBeInTheDocument(); + expect(screen.getByTitle('صفحه بعدی')).toBeInTheDocument(); + expect(screen.getByTitle('صفحه آخر')).toBeInTheDocument(); + + // Check Persian digit representation of current page 2 ('۲') + const page2Button = screen.getByRole('button', { name: (2).toLocaleString('fa-IR') }); + expect(page2Button).toBeInTheDocument(); + expect(page2Button.className).toContain('bg-purple-600'); + }); + + it('disables first and previous buttons on the first page', () => { + render( + + ); + + const firstBtn = screen.getByTitle('صفحه اول'); + const prevBtn = screen.getByTitle('صفحه قبلی'); + const nextBtn = screen.getByTitle('صفحه بعدی'); + const lastBtn = screen.getByTitle('صفحه آخر'); + + expect(firstBtn).toBeDisabled(); + expect(prevBtn).toBeDisabled(); + expect(nextBtn).not.toBeDisabled(); + expect(lastBtn).not.toBeDisabled(); + }); + + it('disables next and last buttons on the last page', () => { + render( + + ); + + const firstBtn = screen.getByTitle('صفحه اول'); + const prevBtn = screen.getByTitle('صفحه قبلی'); + const nextBtn = screen.getByTitle('صفحه بعدی'); + const lastBtn = screen.getByTitle('صفحه آخر'); + + expect(firstBtn).not.toBeDisabled(); + expect(prevBtn).not.toBeDisabled(); + expect(nextBtn).toBeDisabled(); + expect(lastBtn).toBeDisabled(); + }); + + it('calls onPageChange with correct page numbers when navigation buttons are clicked', () => { + const handlePageChange = vi.fn(); + render( + + ); + + fireEvent.click(screen.getByTitle('صفحه اول')); + expect(handlePageChange).toHaveBeenCalledWith(1); + + fireEvent.click(screen.getByTitle('صفحه قبلی')); + expect(handlePageChange).toHaveBeenCalledWith(2); + + fireEvent.click(screen.getByTitle('صفحه بعدی')); + expect(handlePageChange).toHaveBeenCalledWith(4); + + fireEvent.click(screen.getByTitle('صفحه آخر')); + expect(handlePageChange).toHaveBeenCalledWith(10); + }); + + it('navigates directly via jump input form', () => { + const handlePageChange = vi.fn(); + render( + + ); + + const input = screen.getByPlaceholderText('2'); + const submitBtn = screen.getByRole('button', { name: /برو/ }); + + // Valid jump + fireEvent.change(input, { target: { value: '7' } }); + fireEvent.click(submitBtn); + expect(handlePageChange).toHaveBeenCalledWith(7); + + // Invalid jump (out of range > totalPages) + handlePageChange.mockClear(); + fireEvent.change(input, { target: { value: '15' } }); + fireEvent.click(submitBtn); + expect(handlePageChange).not.toHaveBeenCalled(); + + // Invalid jump (<= 0) + handlePageChange.mockClear(); + fireEvent.change(input, { target: { value: '0' } }); + fireEvent.click(submitBtn); + expect(handlePageChange).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/admin-panel/src/components/ui/Pagination.tsx b/frontend/admin-panel/src/components/ui/Pagination.tsx index d5451196..1607c8e4 100644 --- a/frontend/admin-panel/src/components/ui/Pagination.tsx +++ b/frontend/admin-panel/src/components/ui/Pagination.tsx @@ -1,4 +1,4 @@ -import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react'; +import { ChevronLeft,ChevronRight,ChevronsLeft,ChevronsRight } from 'lucide-react'; import { useState } from 'react'; interface PaginationProps { diff --git a/frontend/admin-panel/src/components/ui/PriceInput.tsx b/frontend/admin-panel/src/components/ui/PriceInput.tsx index 68585d4b..bb894844 100644 --- a/frontend/admin-panel/src/components/ui/PriceInput.tsx +++ b/frontend/admin-panel/src/components/ui/PriceInput.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect } from 'react'; +import React,{ useEffect,useState } from 'react'; interface PriceInputProps { value: number | string; @@ -38,7 +38,6 @@ export default function PriceInput({ suffix = 'تومان', disabled = false, required = false, - min, max, name, id, diff --git a/frontend/admin-panel/src/components/ui/RichTextEditor.tsx b/frontend/admin-panel/src/components/ui/RichTextEditor.tsx index 23e0cc62..ded61f93 100644 --- a/frontend/admin-panel/src/components/ui/RichTextEditor.tsx +++ b/frontend/admin-panel/src/components/ui/RichTextEditor.tsx @@ -1,33 +1,33 @@ -import React, { useRef, useEffect, useState, useCallback } from 'react'; import { - Bold, - Italic, - Underline, - Heading1, - Heading2, - Heading3, - Heading4, - List, - ListOrdered, - Link as LinkIcon, - AlignRight, - AlignCenter, - AlignLeft, - Palette, - PaintBucket, - Undo, - Redo, - Code, - RemoveFormatting, - Image as ImageIcon, - Video, - Music, - Table as TableIcon, - Quote, - Minus, - Maximize2, - Minimize2, +AlignCenter, +AlignLeft, +AlignRight, +Bold, +Code, +Heading1, +Heading2, +Heading3, +Heading4, +Image as ImageIcon, +Italic, +Link as LinkIcon, +List, +ListOrdered, +Maximize2, +Minimize2, +Minus, +Music, +PaintBucket, +Palette, +Quote, +Redo, +RemoveFormatting, +Table as TableIcon, +Underline, +Undo, +Video, } from 'lucide-react'; +import { useCallback,useEffect,useRef,useState } from 'react'; import MediaSelector from './MediaSelector'; interface RichTextEditorProps { diff --git a/frontend/admin-panel/src/components/ui/Select.tsx b/frontend/admin-panel/src/components/ui/Select.tsx index de90eaec..c6729ca4 100644 --- a/frontend/admin-panel/src/components/ui/Select.tsx +++ b/frontend/admin-panel/src/components/ui/Select.tsx @@ -1,5 +1,5 @@ -import React, { forwardRef } from 'react'; import { ChevronDown } from 'lucide-react'; +import React,{ forwardRef } from 'react'; export interface SelectOption { value: string | number; diff --git a/frontend/admin-panel/src/components/ui/Textarea.tsx b/frontend/admin-panel/src/components/ui/Textarea.tsx index 5ad99785..a5d673a3 100644 --- a/frontend/admin-panel/src/components/ui/Textarea.tsx +++ b/frontend/admin-panel/src/components/ui/Textarea.tsx @@ -1,4 +1,4 @@ -import React, { forwardRef } from 'react'; +import React,{ forwardRef } from 'react'; export interface TextareaProps extends React.TextareaHTMLAttributes { error?: string; diff --git a/frontend/admin-panel/src/components/ui/ThSort.tsx b/frontend/admin-panel/src/components/ui/ThSort.tsx index 094f6c3a..85c043a5 100644 --- a/frontend/admin-panel/src/components/ui/ThSort.tsx +++ b/frontend/admin-panel/src/components/ui/ThSort.tsx @@ -1,5 +1,5 @@ +import { ArrowDown,ArrowUp,ArrowUpDown } from 'lucide-react'; import React from 'react'; -import { ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react'; export interface ThSortProps { column: string; diff --git a/frontend/admin-panel/src/components/ui/ToggleSwitch.tsx b/frontend/admin-panel/src/components/ui/ToggleSwitch.tsx index 79779f51..6b007bd3 100644 --- a/frontend/admin-panel/src/components/ui/ToggleSwitch.tsx +++ b/frontend/admin-panel/src/components/ui/ToggleSwitch.tsx @@ -1,4 +1,3 @@ -import React from 'react'; export interface ToggleSwitchProps { checked: boolean; diff --git a/frontend/admin-panel/src/main.tsx b/frontend/admin-panel/src/main.tsx index 53470c25..58284dbe 100644 --- a/frontend/admin-panel/src/main.tsx +++ b/frontend/admin-panel/src/main.tsx @@ -1,7 +1,7 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import './index.css' -import App from './App.tsx' +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import App from './App.tsx'; +import './index.css'; // Handle Vite dynamic import chunk mismatch after fresh deployment window.addEventListener('vite:preloadError', (event) => { diff --git a/frontend/admin-panel/src/pages/ApiKeysPage.test.tsx b/frontend/admin-panel/src/pages/ApiKeysPage.test.tsx new file mode 100644 index 00000000..d76afa08 --- /dev/null +++ b/frontend/admin-panel/src/pages/ApiKeysPage.test.tsx @@ -0,0 +1,43 @@ +import { fireEvent,render,screen,waitFor } from '@testing-library/react'; +import { toast } from 'react-hot-toast'; +import { beforeEach,describe,expect,it,vi } from 'vitest'; +import api from '../services/api'; +import ApiKeysPage from './ApiKeysPage'; +vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), delete: vi.fn() } })); +vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); +const key = { id: 'k1', name: 'Warehouse', keyPrefix: 'test_prefix', scopes: ['orders:read'], status: 'ACTIVE', isExpired: false }; +beforeEach(() => { + vi.resetAllMocks(); vi.mocked(api.get).mockResolvedValue({ data: { success: true, data: [key] } }); + vi.mocked(api.post).mockResolvedValue({ data: { success: true, data: { rawKey: 'synthetic-test-key' } } }); + vi.mocked(api.patch).mockResolvedValue({ data: { success: true } }); vi.mocked(api.delete).mockResolvedValue({ data: { success: true } }); +}); +async function open() { render(); await screen.findByText('Warehouse'); fireEvent.click(screen.getByRole('button', { name: 'ساخت API Key جدید' })); } +function submit() { fireEvent.submit(document.querySelector('form')!); } +describe('ApiKeysPage', () => { + it('shows only the prefix, scopes and active status', async () => { render(); await screen.findByText('Warehouse'); expect(screen.getByText('test_prefix')).toBeInTheDocument(); expect(screen.getByText('orders:read')).toBeInTheDocument(); expect(screen.getByText('فعال')).toBeInTheDocument(); }); + it('rejects whitespace names without making a request', async () => { await open(); fireEvent.change(screen.getByPlaceholderText('مثلاً: ورک‌فلو n8n یا اتصال انبار'), { target: { value: ' ' } }); submit(); expect(toast.error).toHaveBeenCalledWith('لطفاً عنوان کلید را وارد کنید'); expect(api.post).not.toHaveBeenCalled(); }); + it('creates restricted expiring key and displays raw key only until dismissed', async () => { + await open(); fireEvent.change(screen.getByPlaceholderText('مثلاً: ورک‌فلو n8n یا اتصال انبار'), { target: { value: ' Automation ' } }); + fireEvent.change(screen.getByPlaceholderText('کاربرد این کلید در کجاست؟'), { target: { value: ' Orders ' } }); + fireEvent.click(screen.getByText('مشاهده سفارشات')); fireEvent.click(screen.getByRole('button', { name: '۳۰ روزه' })); + const before = Date.now(); submit(); await screen.findByDisplayValue('synthetic-test-key'); + const payload = vi.mocked(api.post).mock.calls[0][1] as { name: string; description: string; scopes: string[]; expiresAt: string }; + expect(payload).toEqual({ name: 'Automation', description: 'Orders', scopes: ['orders:read'], expiresAt: expect.any(String) }); + expect(new Date(payload.expiresAt).getTime() - before).toBeGreaterThan(29 * 86400000); + expect(new Date(payload.expiresAt).getTime() - before).toBeLessThan(31 * 86400000); + const copy = vi.fn().mockResolvedValue(undefined); Object.defineProperty(navigator, 'clipboard', { value: { writeText: copy }, configurable: true }); + fireEvent.click(screen.getByRole('button', { name: 'کپی کلید' })); expect(copy).toHaveBeenCalledWith('synthetic-test-key'); + fireEvent.click(screen.getByRole('button', { name: 'کلید را ذخیره کردم، بستن پنجره' })); expect(screen.queryByDisplayValue('synthetic-test-key')).not.toBeInTheDocument(); + }); + it('retains creation form on rejection', async () => { vi.mocked(api.post).mockRejectedValue(new Error('offline')); await open(); fireEvent.change(screen.getByPlaceholderText('مثلاً: ورک‌فلو n8n یا اتصال انبار'), { target: { value: 'Draft' } }); submit(); await waitFor(() => expect(api.post).toHaveBeenCalled()); expect(screen.getByDisplayValue('Draft')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); }); + it('toggles key status and reloads', async () => { render(); fireEvent.click(await screen.findByTitle('غیرفعال کردن کلید')); await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/admin/api-keys/k1/toggle')); await waitFor(() => expect(api.get).toHaveBeenCalledTimes(2)); }); + it('requires confirmation before deleting and removes the row after success', async () => { + const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false); render(); fireEvent.click(await screen.findByTitle('حذف دائمی کلید')); expect(api.delete).not.toHaveBeenCalled(); + confirm.mockReturnValue(true); fireEvent.click(screen.getByTitle('حذف دائمی کلید')); await waitFor(() => expect(api.delete).toHaveBeenCalledWith('/admin/api-keys/k1')); await screen.findByText('هیچ کلید دسترسی تعریف نشده است'); confirm.mockRestore(); + }); + it('retains key on rejected delete or status mutation', async () => { + vi.spyOn(window, 'confirm').mockReturnValue(true); vi.mocked(api.delete).mockRejectedValue(new Error('offline')); vi.mocked(api.patch).mockRejectedValue(new Error('offline')); + render(); fireEvent.click(await screen.findByTitle('حذف دائمی کلید')); fireEvent.click(screen.getByTitle('غیرفعال کردن کلید')); await waitFor(() => expect(api.patch).toHaveBeenCalled()); expect(screen.getByText('Warehouse')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled(); vi.mocked(window.confirm).mockRestore(); + }); + it('reports load failures and clears loading', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بارگذاری کلیدهای دسترسی')); expect(screen.getByText('هیچ کلید دسترسی تعریف نشده است')).toBeInTheDocument(); }); +}); diff --git a/frontend/admin-panel/src/pages/ApiKeysPage.tsx b/frontend/admin-panel/src/pages/ApiKeysPage.tsx index b371b4bc..823ce8fc 100644 --- a/frontend/admin-panel/src/pages/ApiKeysPage.tsx +++ b/frontend/admin-panel/src/pages/ApiKeysPage.tsx @@ -1,23 +1,22 @@ -import { useState, useEffect } from 'react'; import { - Key, - Plus, - Trash2, - Copy, - Check, - Shield, - Clock, - AlertTriangle, - RefreshCw, - Power, - ExternalLink, - Lock, +AlertTriangle, +Check, +Clock, +Copy, +ExternalLink, +Key, +Plus, +Power, +RefreshCw, +Shield, +Trash2 } from 'lucide-react'; +import { useEffect,useState } from 'react'; import { toast } from 'react-hot-toast'; -import api from '../services/api'; -import Spinner from '../components/ui/Spinner'; import Button from '../components/ui/Button'; -import type { ApiKeyItem, CreateApiKeyPayload } from '../types/admin'; +import Spinner from '../components/ui/Spinner'; +import api from '../services/api'; +import type { ApiKeyItem,CreateApiKeyPayload } from '../types/admin'; export default function ApiKeysPage() { const [keys, setKeys] = useState([]); diff --git a/frontend/admin-panel/src/pages/B2BManager.test.tsx b/frontend/admin-panel/src/pages/B2BManager.test.tsx new file mode 100644 index 00000000..b70ba437 --- /dev/null +++ b/frontend/admin-panel/src/pages/B2BManager.test.tsx @@ -0,0 +1,15 @@ +import { fireEvent,render,screen,waitFor } from '@testing-library/react'; +import { toast } from 'react-hot-toast'; +import { beforeEach,describe,expect,it,vi } from 'vitest'; +import api from '../services/api'; +import B2BManager from './B2BManager'; +vi.mock('../services/api', () => ({ default: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn() } })); +vi.mock('react-hot-toast', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) })); +describe('B2BManager',()=>{ +const inquiry = { id: 'i1', companyName: 'Clinic Alpha', contactName: 'Doctor A', phone: '09120000000', email: 'a@example.test', businessType: 'clinic', message: 'Bulk request', status: 'PENDING' }; +beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async url => ({ data: url === '/b2b/inquiries' ? [inquiry] : { data: [] } })); vi.mocked(api.patch).mockResolvedValue({ data: {} }); }); +it('filters inquiries by status without losing the loaded list', async () => { render(); await screen.findByText('Clinic Alpha'); fireEvent.click(screen.getByRole('button', { name: 'رد شده' })); expect(screen.queryByText('Clinic Alpha')).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'همه' })); expect(screen.getByText('Clinic Alpha')).toBeInTheDocument(); }); +it('reviews an inquiry with trimmed notes and refreshes the list', async () => { render(); fireEvent.click(await screen.findByRole('button', { name: 'تغییر وضعیت' })); fireEvent.change(document.querySelector('#inquiryForm select')!, { target: { value: 'APPROVED' } }); fireEvent.change(screen.getByRole('textbox'), { target: { value: ' approved after review ' } }); fireEvent.submit(document.querySelector('#inquiryForm')!); await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/b2b/inquiries/i1', { status: 'APPROVED', adminNotes: 'approved after review' })); await waitFor(() => expect(api.get).toHaveBeenCalledTimes(2)); }); +it('keeps failed review open and reports failure', async () => { vi.mocked(api.patch).mockRejectedValue(new Error('denied')); render(); fireEvent.click(await screen.findByRole('button', { name: 'تغییر وضعیت' })); fireEvent.submit(document.querySelector('#inquiryForm')!); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بروزرسانی وضعیت درخواست B2B')); expect(document.querySelector('#inquiryForm')).toBeInTheDocument(); }); +it('blocks whitespace-only partner identity before posting', async () => { render(); await screen.findByText('Clinic Alpha'); fireEvent.click(screen.getByTestId('b2b-partners-tab')); fireEvent.click(await screen.findByRole('button', { name: 'افزودن همکار B2B جدید' })); fireEvent.change(screen.getByPlaceholderText('uuid-string-of-user'), { target: { value: ' ' } }); fireEvent.submit(document.querySelector('#partnerForm')!); expect(api.post).not.toHaveBeenCalled(); expect(toast.error).toHaveBeenCalledWith('شناسه کاربر و نام شرکت اجباری هستند'); }); +}); diff --git a/frontend/admin-panel/src/pages/B2BManager.tsx b/frontend/admin-panel/src/pages/B2BManager.tsx index abb2f2e0..9074dd45 100644 --- a/frontend/admin-panel/src/pages/B2BManager.tsx +++ b/frontend/admin-panel/src/pages/B2BManager.tsx @@ -1,11 +1,11 @@ -import { useState, useEffect } from 'react'; -import { Building2, CheckCircle2, XCircle, Clock, PhoneCall, Filter, X, Plus, ShieldCheck } from 'lucide-react'; +import { Building2,CheckCircle2,Clock,Filter,PhoneCall,Plus,ShieldCheck,XCircle } from 'lucide-react'; +import { useEffect,useState } from 'react'; import { toast } from 'react-hot-toast'; -import api from '../services/api'; -import Spinner from '../components/ui/Spinner'; import Button from '../components/ui/Button'; import Modal from '../components/ui/Modal'; -import type { B2BInquiry, PartnerAccount } from '../types/admin'; +import Spinner from '../components/ui/Spinner'; +import api from '../services/api'; +import type { B2BInquiry,PartnerAccount } from '../types/admin'; diff --git a/frontend/admin-panel/src/pages/BannersManager.test.tsx b/frontend/admin-panel/src/pages/BannersManager.test.tsx new file mode 100644 index 00000000..eaaee112 --- /dev/null +++ b/frontend/admin-panel/src/pages/BannersManager.test.tsx @@ -0,0 +1,276 @@ +import { fireEvent,render,screen,waitFor } from "@testing-library/react"; +import { toast } from "react-hot-toast"; +import { beforeEach,describe,expect,it,vi } from "vitest"; +import api from "../services/api"; +import BannersManager from "./BannersManager"; + +vi.mock("../services/api", () => { + return { + default: { + get: vi.fn(), + post: vi.fn(), + patch: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + }, + BASE_DOMAIN: "https://canina.ir", + }; +}); + +vi.mock("react-hot-toast", () => ({ + toast: { + success: vi.fn(), + error: vi.fn(), + }, +})); + +// Mock MediaSelector +vi.mock("../components/ui/MediaSelector", () => ({ + default: ({ isOpen, onSelect, onClose }: any) => { + if (!isOpen) return null; + return ( +
+ + +
+ ); + }, +})); + +describe("BannersManager", () => { + const mockBanners = [ + { + id: "b-1", + title: "Banner 1", + subtitle: "Subtitle 1", + imageUrl: "/uploads/banner1.jpg", + linkUrl: "/products/promo1", + position: "home_hero", + isActive: true, + order: 0, + }, + { + id: "b-2", + title: "Banner 2", + subtitle: "Subtitle 2", + imageUrl: "https://external.com/banner2.png", + linkUrl: "/products/promo2", + position: "home_promo", + isActive: false, + order: 1, + }, + ]; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("renders banners list successfully", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + + render(); + + expect(screen.getByText("مدیریت بنرها و اسلایدرها")).toBeInTheDocument(); + + // Wait for banners to load + await waitFor(() => { + expect(screen.getByText("Banner 1")).toBeInTheDocument(); + expect(screen.getByText("Banner 2")).toBeInTheDocument(); + }); + + expect(screen.getByText("Subtitle 1")).toBeInTheDocument(); + expect(screen.getByText("اسلایدر اصلی")).toBeInTheDocument(); + expect(screen.getByText("بنر تبلیغاتی میانی")).toBeInTheDocument(); + expect(screen.getByText("/products/promo1")).toBeInTheDocument(); + expect(screen.getByText("فعال")).toBeInTheDocument(); + expect(screen.getByText("غیرفعال")).toBeInTheDocument(); + }); + + it("handles empty state when no banners found", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: [] }); + + render(); + + await waitFor(() => { + expect(screen.getByText("هیچ بنری یافت نشد")).toBeInTheDocument(); + }); + }); + + it("creates a new banner via modal", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } }); + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); // for refresh + + render(); + + await waitFor(() => { + expect(screen.getByText("Banner 1")).toBeInTheDocument(); + }); + + // Click Add New Banner button + const addButton = screen.getByRole("button", { name: /افزودن بنر جدید/i }); + fireEvent.click(addButton); + + // Modal should be open + expect(screen.getByText("افزودن بنر جدید", { selector: "h3" })).toBeInTheDocument(); + + // Fill in form fields + const titleInput = screen.getByPlaceholderText(/مثال: تخفیف ویژه مکمل‌های غذایی/i); + const subtitleInput = screen.getByPlaceholderText(/مثال: تا ۳۰٪ تخفیف برای مدت محدود/i); + const imageInput = screen.getByPlaceholderText(/آدرس تصویر یا انتخاب از رسانه‌ها\.\.\./i); + const linkInput = screen.getByPlaceholderText(/\/shop یا https:\/\/\.\.\./i); + + fireEvent.change(titleInput, { target: { value: "New Campaign Banner" } }); + fireEvent.change(subtitleInput, { target: { value: "Save 20%" } }); + fireEvent.change(imageInput, { target: { value: "/uploads/new-camp.jpg" } }); + fireEvent.change(linkInput, { target: { value: "/camp" } }); + + // Save banner + const saveButton = screen.getByRole("button", { name: /ذخیره تغییرات/i }); + fireEvent.click(saveButton); + + await waitFor(() => { + expect(api.post).toHaveBeenCalledWith("/banners", expect.objectContaining({ + title: "New Campaign Banner", + subtitle: "Save 20%", + imageUrl: "/uploads/new-camp.jpg", + linkUrl: "/camp", + position: "home_hero", + isActive: true, + })); + expect(toast.success).toHaveBeenCalledWith("بنر جدید با موفقیت ایجاد شد"); + }); + }); + + it("selects image from MediaSelector", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: [] }); + + render(); + + await waitFor(() => { + expect(screen.getByText("هیچ بنری یافت نشد")).toBeInTheDocument(); + }); + + fireEvent.click(screen.getByRole("button", { name: /افزودن بنر جدید/i })); + + // Open media selector + const chooseMediaButton = screen.getByRole("button", { name: /انتخاب تصویر/i }); + fireEvent.click(chooseMediaButton); + + expect(screen.getByTestId("media-selector-modal")).toBeInTheDocument(); + + // Select media + fireEvent.click(screen.getByText("Select Media Sample")); + + const imageInput = screen.getByPlaceholderText(/آدرس تصویر یا انتخاب از رسانه‌ها\.\.\./i) as HTMLInputElement; + expect(imageInput.value).toBe("/uploads/media-selected.png"); + }); + + it("edits an existing banner", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + vi.mocked(api.patch).mockResolvedValueOnce({ data: { success: true } }); + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + + render(); + + await waitFor(() => { + expect(screen.getByText("Banner 1")).toBeInTheDocument(); + }); + + const rows = screen.getAllByRole("row"); + const editButton = rows[1].querySelectorAll("button")[3]; + fireEvent.click(editButton); + + expect(screen.getByText("ویرایش بنر", { selector: "h3" })).toBeInTheDocument(); + + const titleInput = screen.getByPlaceholderText(/مثال: تخفیف ویژه مکمل‌های غذایی/i); + expect(titleInput).toHaveValue("Banner 1"); + + fireEvent.change(titleInput, { target: { value: "Updated Banner 1" } }); + + const saveButton = screen.getByRole("button", { name: /ذخیره تغییرات/i }); + fireEvent.click(saveButton); + + await waitFor(() => { + expect(api.patch).toHaveBeenCalledWith("/banners/b-1", expect.objectContaining({ + title: "Updated Banner 1", + })); + expect(toast.success).toHaveBeenCalledWith("بنر با موفقیت بروزرسانی شد"); + }); + }); + + it("toggles active state of a banner", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + vi.mocked(api.patch).mockResolvedValueOnce({ data: { success: true } }); + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + + render(); + + await waitFor(() => { + expect(screen.getByText("Banner 1")).toBeInTheDocument(); + }); + + const activeToggle = screen.getByText("فعال"); + fireEvent.click(activeToggle); + + await waitFor(() => { + expect(api.patch).toHaveBeenCalledWith("/banners/b-1", { isActive: false }); + expect(toast.success).toHaveBeenCalledWith("وضعیت بنر تغییر کرد"); + }); + }); + + it("deletes a banner via confirmation modal", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } }); + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + + render(); + + await waitFor(() => { + expect(screen.getByText("Banner 1")).toBeInTheDocument(); + }); + + const rows = screen.getAllByRole("row"); + const deleteButton = rows[1].querySelectorAll("button")[4]; + fireEvent.click(deleteButton); + + expect(screen.getByText(/آیا از حذف این بنر اطمینان دارید؟/i)).toBeInTheDocument(); + + const confirmButton = screen.getByRole("button", { name: /تایید/i }); + fireEvent.click(confirmButton); + + await waitFor(() => { + expect(api.delete).toHaveBeenCalledWith("/banners/b-1"); + expect(toast.success).toHaveBeenCalledWith("بنر با موفقیت حذف شد"); + }); + }); + + it("moves banner order down and calls reorder API", async () => { + vi.mocked(api.get).mockResolvedValueOnce({ data: mockBanners }); + vi.mocked(api.put).mockResolvedValueOnce({ data: { success: true } }); + + render(); + + await waitFor(() => { + expect(screen.getByText("Banner 1")).toBeInTheDocument(); + }); + + const rows = screen.getAllByRole("row"); + const moveDownButton = rows[1].querySelectorAll("button")[1]; + fireEvent.click(moveDownButton); + + await waitFor(() => { + expect(api.put).toHaveBeenCalledWith("/banners/reorder", [ + { id: "b-2", order: 0 }, + { id: "b-1", order: 1 }, + ]); + expect(toast.success).toHaveBeenCalledWith("ترتیب بنرها به روز شد"); + }); + }); +}); diff --git a/frontend/admin-panel/src/pages/BannersManager.tsx b/frontend/admin-panel/src/pages/BannersManager.tsx index 37b0022a..7b06b68b 100644 --- a/frontend/admin-panel/src/pages/BannersManager.tsx +++ b/frontend/admin-panel/src/pages/BannersManager.tsx @@ -1,12 +1,12 @@ -import { useState, useEffect } from 'react'; -import { Image as ImageIcon, Plus, Edit2, Trash2, X, MoveUp, MoveDown, CheckCircle2, XCircle } from 'lucide-react'; +import { CheckCircle2,Edit2,Image as ImageIcon,MoveDown,MoveUp,Plus,Trash2,XCircle } from 'lucide-react'; +import { useEffect,useState } from 'react'; import { toast } from 'react-hot-toast'; -import api, { BASE_DOMAIN } from '../services/api'; -import Spinner from '../components/ui/Spinner'; +import Button from '../components/ui/Button'; import ConfirmModal from '../components/ui/ConfirmModal'; import MediaSelector from '../components/ui/MediaSelector'; -import Button from '../components/ui/Button'; import Modal from '../components/ui/Modal'; +import Spinner from '../components/ui/Spinner'; +import api,{ BASE_DOMAIN } from '../services/api'; import type { Banner } from '../types/admin'; @@ -153,6 +153,17 @@ export default function BannersManager() { } }; + const handleToggleActive = async (banner: Banner) => { + try { + await api.patch('/banners/' + banner.id, { isActive: !banner.isActive }); + toast.success('وضعیت بنر تغییر کرد'); + fetchBanners(); + } catch (err) { + console.error('Failed to toggle banner status:', err); + toast.error('خطا در تغییر وضعیت بنر'); + } + }; + const getImageFullUrl = (url: string) => { if (!url) return ''; if (url.startsWith('http')) return url; @@ -211,14 +222,14 @@ export default function BannersManager() {
+ +
+ ); + }, +})); + +// Mock RichTextEditor +vi.mock("../components/ui/RichTextEditor", () => ({ + default: ({ value, onChange }: any) => ( +