test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -1,42 +1,42 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString, IsEnum } from 'class-validator';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsOptional, IsString, IsEnum } from "class-validator";
|
||||
import { PaginationDto } from "../../common/dto/pagination.dto";
|
||||
|
||||
export class GetProductsDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: 'فیلتر بر اساس اسلاگ دستهبندی' })
|
||||
@ApiPropertyOptional({ description: "فیلتر بر اساس اسلاگ دستهبندی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
category?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر بر اساس آیدی دستهبندی' })
|
||||
@ApiPropertyOptional({ description: "فیلتر بر اساس آیدی دستهبندی" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
categoryId?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'فیلتر بر اساس نوع حیوان',
|
||||
enum: ['سگ', 'گربه', 'سگ و گربه', 'هر دو', 'all'],
|
||||
description: "فیلتر بر اساس نوع حیوان",
|
||||
enum: ["سگ", "گربه", "سگ و گربه", "هر دو", "all"],
|
||||
})
|
||||
@IsOptional()
|
||||
@IsEnum(['سگ', 'گربه', 'سگ و گربه', 'هر دو', 'all'])
|
||||
@IsEnum(["سگ", "گربه", "سگ و گربه", "هر دو", "all"])
|
||||
petType?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر بر اساس یک علامت درمانی خاص' })
|
||||
@ApiPropertyOptional({ description: "فیلتر بر اساس یک علامت درمانی خاص" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
symptom?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر داروی نیازمند نسخه (true/false)' })
|
||||
@ApiPropertyOptional({ description: "فیلتر داروی نیازمند نسخه (true/false)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
requiresRx?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'حداقل قیمت (تومان)' })
|
||||
@ApiPropertyOptional({ description: "حداقل قیمت (تومان)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
minPrice?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'حداکثر قیمت (تومان)' })
|
||||
@ApiPropertyOptional({ description: "حداکثر قیمت (تومان)" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
maxPrice?: string;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ProductsController } from './products.controller';
|
||||
import { ProductsService } from './products.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { ProductsController } from "./products.controller";
|
||||
import { ProductsService } from "./products.service";
|
||||
import { NotFoundException } from "@nestjs/common";
|
||||
|
||||
describe('ProductsController', () => {
|
||||
describe("ProductsController", () => {
|
||||
let controller: ProductsController;
|
||||
let service: ProductsService;
|
||||
|
||||
const mockProductsService = {
|
||||
findAll: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ id: 'prod-id', name: 'Product 1' }]),
|
||||
.mockResolvedValue([{ id: "prod-id", name: "Product 1" }]),
|
||||
findOne: jest.fn(),
|
||||
};
|
||||
|
||||
@@ -28,30 +28,30 @@ describe('ProductsController', () => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
it("should be defined", () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should list products', async () => {
|
||||
const query = { category: 'joints' };
|
||||
it("should list products", async () => {
|
||||
const query = { category: "joints" };
|
||||
const result = await controller.findAll(query);
|
||||
expect(service.findAll).toHaveBeenCalledWith(query);
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should throw NotFoundException if product not found', async () => {
|
||||
describe("findOne", () => {
|
||||
it("should throw NotFoundException if product not found", async () => {
|
||||
mockProductsService.findOne.mockResolvedValue(null);
|
||||
await expect(controller.findOne('invalid-id')).rejects.toThrow(
|
||||
await expect(controller.findOne("invalid-id")).rejects.toThrow(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return product details if found', async () => {
|
||||
const prod = { id: 'prod-id', name: 'Product 1' };
|
||||
it("should return product details if found", async () => {
|
||||
const prod = { id: "prod-id", name: "Product 1" };
|
||||
mockProductsService.findOne.mockResolvedValue(prod);
|
||||
const result = await controller.findOne('prod-id');
|
||||
expect(service.findOne).toHaveBeenCalledWith('prod-id');
|
||||
const result = await controller.findOne("prod-id");
|
||||
expect(service.findOne).toHaveBeenCalledWith("prod-id");
|
||||
expect(result).toEqual(prod);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,71 +8,71 @@ import {
|
||||
NotFoundException,
|
||||
HttpStatus,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { ProductsService } from './products.service';
|
||||
import { GetProductsDto } from './dto/get-products.dto';
|
||||
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { ProductsService } from "./products.service";
|
||||
import { GetProductsDto } from "./dto/get-products.dto";
|
||||
import { ApiTags, ApiOperation, ApiResponse } from "@nestjs/swagger";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
|
||||
import { RolesGuard } from "../common/guards/roles.guard";
|
||||
import { Roles } from "../common/decorators/roles.decorator";
|
||||
|
||||
@ApiTags('Products - مدیریت محصولات دارویی')
|
||||
@Controller('products')
|
||||
@ApiTags("Products - مدیریت محصولات دارویی")
|
||||
@Controller("products")
|
||||
@ApiResponse({
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
description: 'خطای داخلی سرور',
|
||||
description: "خطای داخلی سرور",
|
||||
})
|
||||
export class ProductsController {
|
||||
constructor(private readonly productsService: ProductsService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'لیست و فیلتر محصولات' })
|
||||
@ApiOperation({ summary: "لیست و فیلتر محصولات" })
|
||||
findAll(@Query() query: GetProductsDto) {
|
||||
return this.productsService.findAll(query);
|
||||
}
|
||||
|
||||
@Get('filters')
|
||||
@Get("filters")
|
||||
@ApiOperation({
|
||||
summary: 'دریافت فیلترهای فعال محصولات (دسته، علائم، نوع پت)',
|
||||
summary: "دریافت فیلترهای فعال محصولات (دسته، علائم، نوع پت)",
|
||||
})
|
||||
getActiveFilters() {
|
||||
return this.productsService.getActiveFilters();
|
||||
}
|
||||
|
||||
@Get('navigation-filters')
|
||||
@Get("navigation-filters")
|
||||
@ApiOperation({
|
||||
summary: 'دریافت فیلترها و راهکارهای ناوبری (دسته با علائم مربوطه)',
|
||||
summary: "دریافت فیلترها و راهکارهای ناوبری (دسته با علائم مربوطه)",
|
||||
})
|
||||
getNavigationFilters() {
|
||||
return this.productsService.getNavigationFilters();
|
||||
}
|
||||
|
||||
@Get(':id/dosage-config')
|
||||
@ApiOperation({ summary: 'دریافت پیکربندی دوز مصرف محصول' })
|
||||
getDosageConfig(@Param('id') id: string) {
|
||||
@Get(":id/dosage-config")
|
||||
@ApiOperation({ summary: "دریافت پیکربندی دوز مصرف محصول" })
|
||||
getDosageConfig(@Param("id") id: string) {
|
||||
return this.productsService.getDosageConfig(id);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Patch(':id/dosage-config')
|
||||
@Roles("Admin")
|
||||
@Patch(":id/dosage-config")
|
||||
@ApiOperation({
|
||||
summary: 'ویرایش پیکربندی دوز مصرف محصول (نیازمند دسترسی ادمین)',
|
||||
summary: "ویرایش پیکربندی دوز مصرف محصول (نیازمند دسترسی ادمین)",
|
||||
})
|
||||
updateDosageConfig(
|
||||
@Param('id') id: string,
|
||||
@Param("id") id: string,
|
||||
@Body() body: Prisma.InputJsonValue,
|
||||
) {
|
||||
return this.productsService.updateDosageConfig(id, body);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'دریافت اطلاعات محصول با شناسه یکتا (ID)' })
|
||||
async findOne(@Param('id') id: string) {
|
||||
@Get(":id")
|
||||
@ApiOperation({ summary: "دریافت اطلاعات محصول با شناسه یکتا (ID)" })
|
||||
async findOne(@Param("id") id: string) {
|
||||
const product = await this.productsService.findOne(id);
|
||||
if (!product) {
|
||||
throw new NotFoundException('محصول یافت نشد');
|
||||
throw new NotFoundException("محصول یافت نشد");
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ProductsService } from './products.service';
|
||||
import { ProductsController } from './products.controller';
|
||||
import { TorobController } from './torob.controller';
|
||||
import { Module } from "@nestjs/common";
|
||||
import { ProductsService } from "./products.service";
|
||||
import { ProductsController } from "./products.controller";
|
||||
import { TorobController } from "./torob.controller";
|
||||
|
||||
@Module({
|
||||
controllers: [ProductsController, TorobController],
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ProductsService } from './products.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RevalidationService } from '../common/revalidation/revalidation.service';
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { ProductsService } from "./products.service";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
|
||||
describe('ProductsService', () => {
|
||||
describe("ProductsService", () => {
|
||||
let service: ProductsService;
|
||||
let prisma: PrismaService;
|
||||
|
||||
@@ -38,26 +38,26 @@ describe('ProductsService', () => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('findAll', () => {
|
||||
it('should query products with correct filters', async () => {
|
||||
mockPrisma.product.findMany.mockResolvedValue([{ id: 'prod-1' }]);
|
||||
describe("findAll", () => {
|
||||
it("should query products with correct filters", async () => {
|
||||
mockPrisma.product.findMany.mockResolvedValue([{ id: "prod-1" }]);
|
||||
mockPrisma.product.count.mockResolvedValue(1);
|
||||
const filters = { category: 'joints', petType: 'سگ', query: 'can' };
|
||||
const filters = { category: "joints", petType: "سگ", query: "can" };
|
||||
const result = await service.findAll(filters);
|
||||
|
||||
expect(result.data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should find product by id', async () => {
|
||||
const prod = { id: 'prod-1' };
|
||||
describe("findOne", () => {
|
||||
it("should find product by id", async () => {
|
||||
const prod = { id: "prod-1" };
|
||||
mockPrisma.product.findFirst.mockResolvedValue(prod);
|
||||
const result = await service.findOne('prod-1');
|
||||
const result = await service.findOne("prod-1");
|
||||
expect(result).toEqual(prod);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { GetProductsDto } from './dto/get-products.dto';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { RevalidationService } from '../common/revalidation/revalidation.service';
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { GetProductsDto } from "./dto/get-products.dto";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { RevalidationService } from "../common/revalidation/revalidation.service";
|
||||
|
||||
@Injectable()
|
||||
export class ProductsService {
|
||||
@@ -22,15 +22,15 @@ export class ProductsService {
|
||||
maxPrice,
|
||||
page = 1,
|
||||
limit = 50,
|
||||
sortBy = 'createdAt',
|
||||
sortOrder = 'desc',
|
||||
sortBy = "createdAt",
|
||||
sortOrder = "desc",
|
||||
} = filters;
|
||||
|
||||
const andConditions: Prisma.ProductWhereInput[] = [];
|
||||
|
||||
if (requiresRx !== undefined && requiresRx !== null && requiresRx !== '') {
|
||||
if (requiresRx !== undefined && requiresRx !== null && requiresRx !== "") {
|
||||
andConditions.push({
|
||||
requiresRx: requiresRx === 'true' || requiresRx === '1',
|
||||
requiresRx: requiresRx === "true" || requiresRx === "1",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,9 +38,9 @@ export class ProductsService {
|
||||
andConditions.push({ categorySlug: category });
|
||||
}
|
||||
|
||||
if (petType && petType !== 'all') {
|
||||
if (petType && petType !== "all") {
|
||||
andConditions.push({
|
||||
suitableFor: { in: [petType, 'سگ و گربه', 'هر دو'] },
|
||||
suitableFor: { in: [petType, "سگ و گربه", "هر دو"] },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ export class ProductsService {
|
||||
andConditions.push({
|
||||
symptoms: {
|
||||
some: {
|
||||
symptom: { contains: symptom, mode: 'insensitive' },
|
||||
symptom: { contains: symptom, mode: "insensitive" },
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -65,16 +65,16 @@ export class ProductsService {
|
||||
if (search) {
|
||||
andConditions.push({
|
||||
OR: [
|
||||
{ artNo: { contains: search, mode: 'insensitive' } },
|
||||
{ barcode: { contains: search, mode: 'insensitive' } },
|
||||
{ nameFa: { contains: search, mode: 'insensitive' } },
|
||||
{ nameEn: { contains: search, mode: 'insensitive' } },
|
||||
{ description: { contains: search, mode: 'insensitive' } },
|
||||
{ shortDescription: { contains: search, mode: 'insensitive' } },
|
||||
{ artNo: { contains: search, mode: "insensitive" } },
|
||||
{ barcode: { contains: search, mode: "insensitive" } },
|
||||
{ nameFa: { contains: search, mode: "insensitive" } },
|
||||
{ nameEn: { contains: search, mode: "insensitive" } },
|
||||
{ description: { contains: search, mode: "insensitive" } },
|
||||
{ shortDescription: { contains: search, mode: "insensitive" } },
|
||||
{
|
||||
symptoms: {
|
||||
some: {
|
||||
symptom: { contains: search, mode: 'insensitive' },
|
||||
symptom: { contains: search, mode: "insensitive" },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -97,7 +97,7 @@ export class ProductsService {
|
||||
ingredientList: true,
|
||||
symptoms: true,
|
||||
orderItems: {
|
||||
where: { order: { status: { not: 'CANCELLED' } } },
|
||||
where: { order: { status: { not: "CANCELLED" } } },
|
||||
select: { quantity: true },
|
||||
},
|
||||
},
|
||||
@@ -106,11 +106,11 @@ export class ProductsService {
|
||||
]);
|
||||
|
||||
const isWholesaleOrAdmin =
|
||||
userRole === 'User_Wholesale' ||
|
||||
userRole === 'User_Partner' ||
|
||||
userRole === 'ADMIN' ||
|
||||
userRole === 'SuperAdmin';
|
||||
const isAdmin = userRole === 'ADMIN' || userRole === 'SuperAdmin';
|
||||
userRole === "User_Wholesale" ||
|
||||
userRole === "User_Partner" ||
|
||||
userRole === "ADMIN" ||
|
||||
userRole === "SuperAdmin";
|
||||
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
||||
|
||||
const data = rawProducts.map((p) => {
|
||||
const totalSold =
|
||||
@@ -168,8 +168,8 @@ export class ProductsService {
|
||||
ingredientList: true,
|
||||
symptoms: true,
|
||||
reviews: {
|
||||
where: { status: 'APPROVED' },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
where: { status: "APPROVED" },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
userName: true,
|
||||
@@ -184,11 +184,11 @@ export class ProductsService {
|
||||
|
||||
if (!product) return null;
|
||||
const isWholesaleOrAdmin =
|
||||
userRole === 'User_Wholesale' ||
|
||||
userRole === 'User_Partner' ||
|
||||
userRole === 'ADMIN' ||
|
||||
userRole === 'SuperAdmin';
|
||||
const isAdmin = userRole === 'ADMIN' || userRole === 'SuperAdmin';
|
||||
userRole === "User_Wholesale" ||
|
||||
userRole === "User_Partner" ||
|
||||
userRole === "ADMIN" ||
|
||||
userRole === "SuperAdmin";
|
||||
const isAdmin = userRole === "ADMIN" || userRole === "SuperAdmin";
|
||||
|
||||
const { buyPrice, wholesalePrice, ...publicProduct } = product;
|
||||
void buyPrice;
|
||||
@@ -216,13 +216,13 @@ export class ProductsService {
|
||||
},
|
||||
}),
|
||||
this.prisma.productSymptom.findMany({
|
||||
distinct: ['symptom'],
|
||||
distinct: ["symptom"],
|
||||
select: {
|
||||
symptom: true,
|
||||
},
|
||||
}),
|
||||
this.prisma.product.findMany({
|
||||
distinct: ['suitableFor'],
|
||||
distinct: ["suitableFor"],
|
||||
select: {
|
||||
suitableFor: true,
|
||||
},
|
||||
@@ -236,7 +236,7 @@ export class ProductsService {
|
||||
new Set(
|
||||
petTypesDb
|
||||
.map((p) =>
|
||||
p.suitableFor === 'هر دو' ? 'سگ و گربه' : p.suitableFor,
|
||||
p.suitableFor === "هر دو" ? "سگ و گربه" : p.suitableFor,
|
||||
)
|
||||
.filter(Boolean),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { TorobController } from "./torob.controller";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
describe("TorobController", () => {
|
||||
let controller: TorobController;
|
||||
|
||||
const mockPrismaService = {
|
||||
product: {
|
||||
count: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const originalEnv = process.env;
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env = { ...originalEnv, FRONTEND_URL: "https://canina.ir" };
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [TorobController],
|
||||
providers: [
|
||||
{
|
||||
provide: PrismaService,
|
||||
useValue: mockPrismaService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<TorobController>(TorobController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
process.env = originalEnv;
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
describe("getTorobProducts", () => {
|
||||
it("should return formatted torob products with default pagination", async () => {
|
||||
const mockProducts = [
|
||||
{
|
||||
id: "prod-1",
|
||||
artNo: "1001",
|
||||
slug: "canina-gag-oil",
|
||||
nameFa: "روغن کانینا جی ای جی",
|
||||
nameEn: "Canina GAG Oil",
|
||||
packageSize: 250,
|
||||
unit: "میلیلیتر",
|
||||
suitableFor: "سگ و گربه",
|
||||
stockStatus: "IN_STOCK",
|
||||
stock: 15,
|
||||
priceValue: 750000,
|
||||
imageUrl: "https://api.canina.ir/uploads/products/gag.jpg",
|
||||
category: { name: "مفاصل و استخوان" },
|
||||
categorySlug: "joints",
|
||||
noIndex: false,
|
||||
},
|
||||
];
|
||||
|
||||
mockPrismaService.product.count.mockResolvedValue(1);
|
||||
mockPrismaService.product.findMany.mockResolvedValue(mockProducts);
|
||||
|
||||
const result = await controller.getTorobProducts();
|
||||
|
||||
expect(mockPrismaService.product.count).toHaveBeenCalledWith({
|
||||
where: {
|
||||
noIndex: false,
|
||||
stockStatus: { not: "DISCONTINUED" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockPrismaService.product.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
noIndex: false,
|
||||
stockStatus: { not: "DISCONTINUED" },
|
||||
},
|
||||
skip: 0,
|
||||
take: 100,
|
||||
include: {
|
||||
category: { select: { name: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
expect(result.count).toBe(1);
|
||||
expect(result.max_pages).toBe(1);
|
||||
expect(result.results).toHaveLength(1);
|
||||
|
||||
const item = result.results[0];
|
||||
expect(item.product_id).toBe("1001");
|
||||
expect(item.page_unique_code).toBe("1001");
|
||||
expect(item.page_url).toBe("https://canina.ir/shop/canina-gag-oil");
|
||||
expect(item.price).toBe(750000);
|
||||
expect(item.old_price).toBe(750000);
|
||||
expect(item.availability).toBe("instock");
|
||||
expect(item.category_name).toBe("مفاصل و استخوان");
|
||||
expect(item.image_link).toBe(
|
||||
"https://canina.ir/api/uploads/products/gag.jpg",
|
||||
);
|
||||
expect(item.spec["گونه هدف"]).toBe("سگ و گربه");
|
||||
expect(item.spec["کد محصول (Art.No)"]).toBe("1001");
|
||||
expect(item.spec["دسته دارویی و درمانی"]).toBe("مفاصل و استخوان");
|
||||
expect(item.spec["حجم / وزن / تعداد"]).toBe("250 میلیلیتر");
|
||||
});
|
||||
|
||||
it("should handle custom page and page_size within clamped bounds", async () => {
|
||||
mockPrismaService.product.count.mockResolvedValue(150);
|
||||
mockPrismaService.product.findMany.mockResolvedValue([]);
|
||||
|
||||
const result = await controller.getTorobProducts("2", "50");
|
||||
|
||||
expect(mockPrismaService.product.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
skip: 50,
|
||||
take: 50,
|
||||
}),
|
||||
);
|
||||
expect(result.count).toBe(150);
|
||||
expect(result.max_pages).toBe(3);
|
||||
});
|
||||
|
||||
it("should clamp invalid pagination inputs safely", async () => {
|
||||
mockPrismaService.product.count.mockResolvedValue(0);
|
||||
mockPrismaService.product.findMany.mockResolvedValue([]);
|
||||
|
||||
const result = await controller.getTorobProducts("-5", "999");
|
||||
|
||||
// page Math.max(1, -5) -> 1
|
||||
// pageSize Math.min(100, Math.max(10, 999)) -> 100
|
||||
expect(mockPrismaService.product.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
skip: 0,
|
||||
take: 100,
|
||||
}),
|
||||
);
|
||||
expect(result.max_pages).toBe(1);
|
||||
});
|
||||
|
||||
it("should correctly mark out-of-stock products", async () => {
|
||||
const mockOutOfStock = [
|
||||
{
|
||||
id: "prod-2",
|
||||
artNo: "1002",
|
||||
slug: "out-stock-item",
|
||||
nameFa: "محصول ناموجود",
|
||||
nameEn: "Out of Stock Item",
|
||||
packageSize: 0,
|
||||
unit: null,
|
||||
suitableFor: null,
|
||||
stockStatus: "OUT_OF_STOCK",
|
||||
stock: 0,
|
||||
priceValue: 0,
|
||||
imageUrl: null,
|
||||
ogImage: null,
|
||||
category: null,
|
||||
categorySlug: null,
|
||||
noIndex: false,
|
||||
},
|
||||
];
|
||||
|
||||
mockPrismaService.product.count.mockResolvedValue(1);
|
||||
mockPrismaService.product.findMany.mockResolvedValue(mockOutOfStock);
|
||||
|
||||
const result = await controller.getTorobProducts();
|
||||
expect(result.results[0].availability).toBe("outofstock");
|
||||
expect(result.results[0].image_link).toBe("");
|
||||
expect(result.results[0].category_name).toBe("مکمل حیوانات خانگی");
|
||||
});
|
||||
|
||||
it("should handle full URL in images and normalize relative paths", async () => {
|
||||
const mockProductWithExternalImage = [
|
||||
{
|
||||
id: "prod-3",
|
||||
artNo: null,
|
||||
slug: "external-img-item",
|
||||
nameFa: "محصول با عکس خارجی",
|
||||
nameEn: null,
|
||||
stockStatus: "in_stock",
|
||||
stock: 5,
|
||||
priceValue: "300000",
|
||||
ogImage: "https://external-cdn.com/images/prod.png",
|
||||
imageUrl: null,
|
||||
category: null,
|
||||
categorySlug: "vitamins",
|
||||
},
|
||||
];
|
||||
|
||||
mockPrismaService.product.count.mockResolvedValue(1);
|
||||
mockPrismaService.product.findMany.mockResolvedValue(
|
||||
mockProductWithExternalImage,
|
||||
);
|
||||
|
||||
const result = await controller.getTorobProducts();
|
||||
expect(result.results[0].image_link).toBe(
|
||||
"https://external-cdn.com/images/prod.png",
|
||||
);
|
||||
expect(result.results[0].product_id).toBe("prod-3");
|
||||
expect(result.results[0].category_name).toBe("vitamins");
|
||||
});
|
||||
|
||||
it("should format pet specifications correctly for 'هر دو' and specific pets", async () => {
|
||||
const mockProducts = [
|
||||
{
|
||||
id: "p1",
|
||||
artNo: "111",
|
||||
slug: "p1",
|
||||
nameFa: "مکمل هر دو",
|
||||
nameEn: "Both Pet",
|
||||
suitableFor: "هر دو",
|
||||
stockStatus: "INSTOCK",
|
||||
stock: 10,
|
||||
},
|
||||
{
|
||||
id: "p2",
|
||||
artNo: "222",
|
||||
slug: "p2",
|
||||
nameFa: "مکمل سگ",
|
||||
nameEn: "Dog Only",
|
||||
suitableFor: "سگ",
|
||||
stockStatus: "INSTOCK",
|
||||
stock: 10,
|
||||
},
|
||||
];
|
||||
|
||||
mockPrismaService.product.count.mockResolvedValue(2);
|
||||
mockPrismaService.product.findMany.mockResolvedValue(mockProducts);
|
||||
|
||||
const result = await controller.getTorobProducts();
|
||||
expect(result.results[0].spec["گونه هدف"]).toBe("سگ و گربه");
|
||||
expect(result.results[1].spec["گونه هدف"]).toBe("سگ");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { Controller, Get, Query } from "@nestjs/common";
|
||||
import { ApiTags, ApiOperation } from "@nestjs/swagger";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
|
||||
function buildTorobProductTitle(product: {
|
||||
nameFa?: string | null;
|
||||
@@ -9,28 +9,28 @@ function buildTorobProductTitle(product: {
|
||||
unit?: string | null;
|
||||
suitableFor?: string | null;
|
||||
}): string {
|
||||
const nameFa = (product.nameFa || '').trim();
|
||||
let nameEn = (product.nameEn || '').trim();
|
||||
const nameFa = (product.nameFa || "").trim();
|
||||
let nameEn = (product.nameEn || "").trim();
|
||||
|
||||
// Clean brand duplicate if nameEn already starts with Canina
|
||||
if (/^Canina\b/i.test(nameEn)) {
|
||||
nameEn = nameEn.replace(/^Canina\s*[-–:]*\s*/i, '').trim();
|
||||
nameEn = nameEn.replace(/^Canina\s*[-–:]*\s*/i, "").trim();
|
||||
}
|
||||
|
||||
// Package size & unit
|
||||
let sizePart = '';
|
||||
let sizePart = "";
|
||||
const numSize = Number(product.packageSize);
|
||||
const unit = (product.unit || '').trim();
|
||||
const unit = (product.unit || "").trim();
|
||||
if (numSize && numSize > 0) {
|
||||
sizePart = unit ? `${numSize} ${unit}` : `${numSize}`;
|
||||
}
|
||||
|
||||
// Suitable for pet
|
||||
let petPart = '';
|
||||
let petPart = "";
|
||||
if (product.suitableFor) {
|
||||
const pet = product.suitableFor.trim();
|
||||
if (pet === 'هر دو' || pet === 'سگ و گربه' || pet === 'سگ، گربه') {
|
||||
petPart = 'مناسب سگ و گربه';
|
||||
if (pet === "هر دو" || pet === "سگ و گربه" || pet === "سگ، گربه") {
|
||||
petPart = "مناسب سگ و گربه";
|
||||
} else if (pet) {
|
||||
petPart = `مناسب ${pet}`;
|
||||
}
|
||||
@@ -40,10 +40,10 @@ function buildTorobProductTitle(product: {
|
||||
if (nameFa) parts.push(nameFa);
|
||||
|
||||
// Brand part
|
||||
if (!nameFa.includes('کنینا') && !nameFa.includes('Canina')) {
|
||||
parts.push('برند کنینا Canina');
|
||||
} else if (!nameFa.includes('Canina')) {
|
||||
parts.push('Canina');
|
||||
if (!nameFa.includes("کنینا") && !nameFa.includes("Canina")) {
|
||||
parts.push("برند کنینا Canina");
|
||||
} else if (!nameFa.includes("Canina")) {
|
||||
parts.push("Canina");
|
||||
}
|
||||
|
||||
if (nameEn && nameEn.toLowerCase() !== nameFa.toLowerCase()) {
|
||||
@@ -58,7 +58,7 @@ function buildTorobProductTitle(product: {
|
||||
parts.push(petPart);
|
||||
}
|
||||
|
||||
return parts.join(' ').replace(/\s+/g, ' ').trim();
|
||||
return parts.join(" ").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function buildTorobProductSpec(product: {
|
||||
@@ -69,59 +69,59 @@ function buildTorobProductSpec(product: {
|
||||
category?: { name?: string } | null;
|
||||
}): Record<string, string> {
|
||||
const spec: Record<string, string> = {
|
||||
برند: 'کنینا (Canina Pharma Germany)',
|
||||
'کشور سازنده': 'آلمان',
|
||||
ضمانت: 'اصالت ۱۰۰٪ کالای آلمانی و سلامت فیزیکی',
|
||||
برند: "کنینا (Canina Pharma Germany)",
|
||||
"کشور سازنده": "آلمان",
|
||||
ضمانت: "اصالت ۱۰۰٪ کالای آلمانی و سلامت فیزیکی",
|
||||
};
|
||||
|
||||
if (product.suitableFor) {
|
||||
spec['گونه هدف'] =
|
||||
product.suitableFor === 'هر دو' ? 'سگ و گربه' : product.suitableFor;
|
||||
spec["گونه هدف"] =
|
||||
product.suitableFor === "هر دو" ? "سگ و گربه" : product.suitableFor;
|
||||
}
|
||||
|
||||
const numSize = Number(product.packageSize);
|
||||
const unit = (product.unit || '').trim();
|
||||
const unit = (product.unit || "").trim();
|
||||
if (numSize && numSize > 0) {
|
||||
spec['حجم / وزن / تعداد'] = unit ? `${numSize} ${unit}` : `${numSize}`;
|
||||
spec["حجم / وزن / تعداد"] = unit ? `${numSize} ${unit}` : `${numSize}`;
|
||||
}
|
||||
|
||||
if (product.artNo) {
|
||||
spec['کد محصول (Art.No)'] = product.artNo;
|
||||
spec["کد محصول (Art.No)"] = product.artNo;
|
||||
}
|
||||
|
||||
if (product.category?.name) {
|
||||
spec['دسته دارویی و درمانی'] = product.category.name;
|
||||
spec["دسته دارویی و درمانی"] = product.category.name;
|
||||
}
|
||||
|
||||
return spec;
|
||||
}
|
||||
|
||||
@ApiTags('Torob Integration - وبسرویس اتصال به ترب')
|
||||
@Controller('torob')
|
||||
@ApiTags("Torob Integration - وبسرویس اتصال به ترب")
|
||||
@Controller("torob")
|
||||
export class TorobController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
@Get('products')
|
||||
@Get("products")
|
||||
@ApiOperation({
|
||||
summary: 'دریافت محصولات جهت وبسرویس خودکار ترب (Torob API)',
|
||||
summary: "دریافت محصولات جهت وبسرویس خودکار ترب (Torob API)",
|
||||
})
|
||||
async getTorobProducts(
|
||||
@Query('page') pageQuery?: string,
|
||||
@Query('page_size') pageSizeQuery?: string,
|
||||
@Query("page") pageQuery?: string,
|
||||
@Query("page_size") pageSizeQuery?: string,
|
||||
) {
|
||||
const page = Math.max(1, parseInt(pageQuery || '1', 10));
|
||||
const page = Math.max(1, parseInt(pageQuery || "1", 10));
|
||||
const pageSize = Math.min(
|
||||
100,
|
||||
Math.max(10, parseInt(pageSizeQuery || '100', 10)),
|
||||
Math.max(10, parseInt(pageSizeQuery || "100", 10)),
|
||||
);
|
||||
const baseUrl = (process.env.FRONTEND_URL || 'https://canina.ir').replace(
|
||||
const baseUrl = (process.env.FRONTEND_URL || "https://canina.ir").replace(
|
||||
/\/$/,
|
||||
'',
|
||||
"",
|
||||
);
|
||||
|
||||
const whereCondition = {
|
||||
noIndex: false,
|
||||
stockStatus: { not: 'DISCONTINUED' as const },
|
||||
stockStatus: { not: "DISCONTINUED" as const },
|
||||
};
|
||||
|
||||
const [totalCount, products] = await Promise.all([
|
||||
@@ -133,7 +133,7 @@ export class TorobController {
|
||||
include: {
|
||||
category: { select: { name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -148,49 +148,49 @@ export class TorobController {
|
||||
const spec = buildTorobProductSpec(product);
|
||||
|
||||
// Construct pure English subtitle
|
||||
const rawEn = (product.nameEn || '').trim();
|
||||
const rawEn = (product.nameEn || "").trim();
|
||||
const numSize = Number(product.packageSize);
|
||||
const unit = (product.unit || '').trim();
|
||||
const unit = (product.unit || "").trim();
|
||||
const sizeStr =
|
||||
numSize && numSize > 0
|
||||
? unit
|
||||
? `${numSize} ${unit}`
|
||||
: `${numSize}`
|
||||
: '';
|
||||
let subtitle = rawEn.startsWith('Canina')
|
||||
: "";
|
||||
let subtitle = rawEn.startsWith("Canina")
|
||||
? rawEn
|
||||
: `Canina ${rawEn}`.trim();
|
||||
if (sizeStr && !subtitle.includes(sizeStr)) {
|
||||
subtitle = `${subtitle} - ${sizeStr}`;
|
||||
}
|
||||
|
||||
const rawImage = product.ogImage || product.imageUrl || '';
|
||||
let imageLink = '';
|
||||
const rawImage = product.ogImage || product.imageUrl || "";
|
||||
let imageLink = "";
|
||||
if (rawImage) {
|
||||
const cleanImage = rawImage
|
||||
.trim()
|
||||
.replace(/^https?:\/\/api\.canina\.ir/i, '')
|
||||
.replace(/^https?:\/\/localhost:\d+/i, '')
|
||||
.replace(/^https?:\/\/127\.0\.0\.1:\d+/i, '');
|
||||
.replace(/^https?:\/\/api\.canina\.ir/i, "")
|
||||
.replace(/^https?:\/\/localhost:\d+/i, "")
|
||||
.replace(/^https?:\/\/127\.0\.0\.1:\d+/i, "");
|
||||
|
||||
if (
|
||||
cleanImage.startsWith('http://') ||
|
||||
cleanImage.startsWith('https://')
|
||||
cleanImage.startsWith("http://") ||
|
||||
cleanImage.startsWith("https://")
|
||||
) {
|
||||
imageLink = cleanImage;
|
||||
} else {
|
||||
const cleanPath = cleanImage.replace(/^\/?(api\/)?(uploads\/)?/, '');
|
||||
const cleanPath = cleanImage.replace(/^\/?(api\/)?(uploads\/)?/, "");
|
||||
imageLink = `${baseUrl}/api/uploads/${cleanPath}`;
|
||||
}
|
||||
}
|
||||
|
||||
const isInStock =
|
||||
product.stockStatus !== 'DISCONTINUED' &&
|
||||
product.stockStatus !== 'OUT_OF_STOCK' &&
|
||||
product.stockStatus !== "DISCONTINUED" &&
|
||||
product.stockStatus !== "OUT_OF_STOCK" &&
|
||||
(product.stock === undefined || product.stock > 0) &&
|
||||
String(product.stockStatus || '')
|
||||
String(product.stockStatus || "")
|
||||
.toLowerCase()
|
||||
.includes('in');
|
||||
.includes("in");
|
||||
const price = Number(product.priceValue || 0);
|
||||
const oldPrice = Number(product.priceValue || 0);
|
||||
|
||||
@@ -202,13 +202,13 @@ export class TorobController {
|
||||
page_url: pageUrl,
|
||||
price,
|
||||
old_price: oldPrice,
|
||||
availability: isInStock ? 'instock' : 'outofstock',
|
||||
availability: isInStock ? "instock" : "outofstock",
|
||||
image_link: imageLink,
|
||||
guarantee: 'ضمانت اصالت ۱۰۰٪ کمپانی Canina آلمان و اصالت کالا',
|
||||
guarantee: "ضمانت اصالت ۱۰۰٪ کمپانی Canina آلمان و اصالت کالا",
|
||||
category_name:
|
||||
product.category?.name ||
|
||||
product.categorySlug ||
|
||||
'مکمل حیوانات خانگی',
|
||||
"مکمل حیوانات خانگی",
|
||||
spec,
|
||||
};
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user