test: comprehensive test suites and quality gates pass across backend, storefront and admin
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s

- 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:
devops committed 2026-10-13 16:01:00 +00:00
1 parent 1e73715169
commit ddbf1ca026
439 files changed
+32911 -6107

No files matched your search

@@ -0,0 +1,230 @@
import { Test, TestingModule } from "@nestjs/testing";
import { BadRequestException } from "@nestjs/common";
import {
PrescriptionsController,
UserReqPayload,
} from "./prescriptions.controller";
import { PrescriptionsService } from "./prescriptions.service";
import { MediaService } from "../admin/media.service";
describe("PrescriptionsController", () => {
let controller: PrescriptionsController;
let prescriptionsService: PrescriptionsService;
let mediaService: MediaService;
const mockPrescriptionsService = {
create: jest.fn(),
findAll: jest.fn(),
findOne: jest.fn(),
review: jest.fn(),
};
const mockMediaService = {
uploadFile: jest.fn(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [PrescriptionsController],
providers: [
{
provide: PrescriptionsService,
useValue: mockPrescriptionsService,
},
{
provide: MediaService,
useValue: mockMediaService,
},
],
}).compile();
controller = module.get<PrescriptionsController>(PrescriptionsController);
prescriptionsService =
module.get<PrescriptionsService>(PrescriptionsService);
mediaService = module.get<MediaService>(MediaService);
});
afterEach(() => {
jest.clearAllMocks();
});
it("should be defined", () => {
expect(controller).toBeDefined();
expect(prescriptionsService).toBeDefined();
expect(mediaService).toBeDefined();
});
describe("uploadFile", () => {
it("should successfully upload a prescription file via mediaService", async () => {
const mockFile = {
fieldname: "file",
originalname: "prescription.jpg",
encoding: "7bit",
mimetype: "image/jpeg",
buffer: Buffer.from("fake-file-data"),
size: 1024,
} as Express.Multer.File;
const uploadResult = {
url: "https://canina.ir/uploads/prescriptions/prescription.jpg",
filename: "prescription.jpg",
};
mockMediaService.uploadFile.mockResolvedValue(uploadResult);
const result = await controller.uploadFile(mockFile);
expect(mediaService.uploadFile).toHaveBeenCalledWith(mockFile);
expect(result).toEqual({ success: true, data: uploadResult });
});
it("should throw BadRequestException if no file is provided", async () => {
await expect(controller.uploadFile(undefined as any)).rejects.toThrow(
BadRequestException,
);
});
});
describe("create", () => {
it("should create a prescription successfully with valid fileUrl", async () => {
const req: UserReqPayload = {
user: { id: "user-1", role: "Customer" },
};
const body = {
petName: "مکس",
phone: "09123456789",
fileUrl: "https://canina.ir/uploads/rx1.pdf",
notes: "دوز مصرف کانهیدروکس برای درمان لنگش پا",
};
const createdPrescription = {
id: "rx-1",
userId: "user-1",
fileUrl: body.fileUrl,
notes: body.notes,
status: "PENDING",
};
mockPrescriptionsService.create.mockResolvedValue(createdPrescription);
const result = await controller.create(req, body);
expect(prescriptionsService.create).toHaveBeenCalledWith("user-1", body);
expect(result).toEqual(createdPrescription);
});
it("should fallback to req.user.userId if req.user.id is undefined", async () => {
const req: UserReqPayload = {
user: { userId: "user-2", role: "Customer" },
};
const body = {
fileUrl: "https://canina.ir/uploads/rx2.jpg",
};
mockPrescriptionsService.create.mockResolvedValue({ id: "rx-2" });
await controller.create(req, body);
expect(prescriptionsService.create).toHaveBeenCalledWith("user-2", body);
});
it("should throw BadRequestException if fileUrl is missing or whitespace only", () => {
const req: UserReqPayload = {
user: { id: "user-1" },
};
expect(() => controller.create(req, { fileUrl: "" })).toThrow(
BadRequestException,
);
expect(() => controller.create(req, { fileUrl: " " })).toThrow(
BadRequestException,
);
expect(() => controller.create(req, {} as any)).toThrow(
BadRequestException,
);
});
});
describe("findAll", () => {
it("should pass isAdmin=false for regular customers", async () => {
const req: UserReqPayload = {
user: { id: "user-client-1", role: "Customer" },
};
const mockList = [{ id: "rx-1", userId: "user-client-1" }];
mockPrescriptionsService.findAll.mockResolvedValue(mockList);
const result = await controller.findAll(req);
expect(prescriptionsService.findAll).toHaveBeenCalledWith(
"user-client-1",
false,
);
expect(result).toEqual(mockList);
});
it("should pass isAdmin=true for Admin role", async () => {
const req: UserReqPayload = {
user: { id: "admin-1", role: "Admin" },
};
const mockList = [{ id: "rx-1" }, { id: "rx-2" }];
mockPrescriptionsService.findAll.mockResolvedValue(mockList);
const result = await controller.findAll(req);
expect(prescriptionsService.findAll).toHaveBeenCalledWith(
"admin-1",
true,
);
expect(result).toEqual(mockList);
});
});
describe("findOne", () => {
it("should query prescription by id, userId, and role", async () => {
const req: UserReqPayload = {
user: { id: "user-1", role: "Customer" },
};
const prescriptionId = "rx-100";
const mockRx = { id: prescriptionId, userId: "user-1" };
mockPrescriptionsService.findOne.mockResolvedValue(mockRx);
const result = await controller.findOne(req, prescriptionId);
expect(prescriptionsService.findOne).toHaveBeenCalledWith(
prescriptionId,
"user-1",
false,
);
expect(result).toEqual(mockRx);
});
});
describe("review", () => {
it("should review and update status and notes for a prescription", async () => {
const prescriptionId = "rx-100";
const reviewPayload = {
status: "APPROVED" as const,
adminNotes: "نسخه تایید شد. مصرف روزانه ۱ قرص کانهیدروکس بلامانع است.",
};
const updatedRx = {
id: prescriptionId,
status: "APPROVED",
adminNotes: reviewPayload.adminNotes,
};
mockPrescriptionsService.review.mockResolvedValue(updatedRx);
const result = await controller.review(prescriptionId, reviewPayload);
expect(prescriptionsService.review).toHaveBeenCalledWith(
prescriptionId,
reviewPayload,
);
expect(result).toEqual(updatedRx);
});
});
});
@@ -7,27 +7,27 @@ import {
Param,
UseGuards,
Req,
} from '@nestjs/common';
import { PrescriptionsService } from './prescriptions.service';
import { ApiTags, ApiOperation, ApiBearerAuth } 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 { PrescriptionsService } from "./prescriptions.service";
import { ApiTags, ApiOperation, ApiBearerAuth } from "@nestjs/swagger";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import {
UseInterceptors,
UploadedFile,
BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { MediaService } from '../admin/media.service';
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { MediaService } from "../admin/media.service";
const ALLOWED_PRESCRIPTION_MIME_TYPES = [
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
'application/pdf',
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"application/pdf",
];
export interface UserReqPayload {
@@ -38,8 +38,8 @@ export interface UserReqPayload {
};
}
@ApiTags('Prescriptions - نسخه و تاییدیه دارویی')
@Controller('prescriptions')
@ApiTags("Prescriptions - نسخه و تاییدیه دارویی")
@Controller("prescriptions")
export class PrescriptionsController {
constructor(
private readonly prescriptionsService: PrescriptionsService,
@@ -48,10 +48,10 @@ export class PrescriptionsController {
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Post('upload')
@ApiOperation({ summary: 'آپلود تصویر یا فایل نسخه دارویی توسط کاربر' })
@Post("upload")
@ApiOperation({ summary: "آپلود تصویر یا فایل نسخه دارویی توسط کاربر" })
@UseInterceptors(
FileInterceptor('file', {
FileInterceptor("file", {
limits: {
fileSize: 10 * 1024 * 1024, // 10MB limit
},
@@ -59,7 +59,7 @@ export class PrescriptionsController {
if (!ALLOWED_PRESCRIPTION_MIME_TYPES.includes(file.mimetype)) {
return callback(
new BadRequestException(
'فرمت فایل مجاز نیست. تنها فرمت‌های تصویری و PDF پشتیبانی می‌شوند.',
"فرمت فایل مجاز نیست. تنها فرمت‌های تصویری و PDF پشتیبانی می‌شوند.",
),
false,
);
@@ -69,7 +69,7 @@ export class PrescriptionsController {
}),
)
async uploadFile(@UploadedFile() file: Express.Multer.File) {
if (!file) throw new BadRequestException('فایل بارگذاری نشده است');
if (!file) throw new BadRequestException("فایل بارگذاری نشده است");
const data = await this.mediaService.uploadFile(file);
return { success: true, data };
}
@@ -77,7 +77,7 @@ export class PrescriptionsController {
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Post()
@ApiOperation({ summary: 'بارگذاری نسخه جدید توسط کاربر' })
@ApiOperation({ summary: "بارگذاری نسخه جدید توسط کاربر" })
create(
@Req() req: UserReqPayload,
@Body()
@@ -91,10 +91,10 @@ export class PrescriptionsController {
) {
if (
!body?.fileUrl ||
typeof body.fileUrl !== 'string' ||
typeof body.fileUrl !== "string" ||
!body.fileUrl.trim()
) {
throw new BadRequestException('آدرس فایل نسخه الزامی است.');
throw new BadRequestException("آدرس فایل نسخه الزامی است.");
}
const userId = req.user?.id || req.user?.userId || null;
return this.prescriptionsService.create(userId, body);
@@ -103,31 +103,31 @@ export class PrescriptionsController {
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Get()
@ApiOperation({ summary: 'دریافت لیست نسخه‌ها (کاربر یا ادمین)' })
@ApiOperation({ summary: "دریافت لیست نسخه‌ها (کاربر یا ادمین)" })
findAll(@Req() req: UserReqPayload) {
const userId = req.user.id || req.user.userId || '';
const isAdmin = req.user.role === 'Admin' || req.user.role === 'ADMIN';
const userId = req.user.id || req.user.userId || "";
const isAdmin = req.user.role === "Admin" || req.user.role === "ADMIN";
return this.prescriptionsService.findAll(userId, isAdmin);
}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Get(':id')
@ApiOperation({ summary: 'دریافت جزئیات یک نسخه' })
findOne(@Req() req: UserReqPayload, @Param('id') id: string) {
const userId = req.user.id || req.user.userId || '';
const isAdmin = req.user.role === 'Admin' || req.user.role === 'ADMIN';
@Get(":id")
@ApiOperation({ summary: "دریافت جزئیات یک نسخه" })
findOne(@Req() req: UserReqPayload, @Param("id") id: string) {
const userId = req.user.id || req.user.userId || "";
const isAdmin = req.user.role === "Admin" || req.user.role === "ADMIN";
return this.prescriptionsService.findOne(id, userId, isAdmin);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'ADMIN')
@Patch(':id/review')
@ApiOperation({ summary: 'بررسی و تایید/رد نسخه دارویی (نیازمند ادمین)' })
@Roles("Admin", "ADMIN")
@Patch(":id/review")
@ApiOperation({ summary: "بررسی و تایید/رد نسخه دارویی (نیازمند ادمین)" })
review(
@Param('id') id: string,
@Param("id") id: string,
@Body()
body: { status: 'APPROVED' | 'REJECTED' | 'PENDING'; adminNotes?: string },
body: { status: "APPROVED" | "REJECTED" | "PENDING"; adminNotes?: string },
) {
return this.prescriptionsService.review(id, body);
}
@@ -1,10 +1,10 @@
import { Module } from '@nestjs/common';
import { PrescriptionsController } from './prescriptions.controller';
import { PrescriptionsService } from './prescriptions.service';
import { PrismaModule } from '../prisma/prisma.module';
import { SmsService } from '../common/services/sms.service';
import { Module } from "@nestjs/common";
import { PrescriptionsController } from "./prescriptions.controller";
import { PrescriptionsService } from "./prescriptions.service";
import { PrismaModule } from "../prisma/prisma.module";
import { SmsService } from "../common/services/sms.service";
import { AdminModule } from '../admin/admin.module';
import { AdminModule } from "../admin/admin.module";
@Module({
imports: [PrismaModule, AdminModule],
@@ -0,0 +1,119 @@
import { Test, TestingModule } from "@nestjs/testing";
import { PrescriptionsService } from "./prescriptions.service";
import { PrismaService } from "../prisma/prisma.service";
import { SmsService } from "../common/services/sms.service";
import { ForbiddenException, NotFoundException } from "@nestjs/common";
describe("PrescriptionsService", () => {
let service: PrescriptionsService;
const mockPrisma = {
user: {
findFirst: jest.fn(),
create: jest.fn(),
},
pet: {
findFirst: jest.fn(),
create: jest.fn(),
},
prescription: {
create: jest.fn(),
findMany: jest.fn(),
findUnique: jest.fn(),
update: jest.fn(),
},
};
const mockSmsService = {
sendTemplateSms: jest.fn().mockResolvedValue(true),
sendSms: jest.fn().mockResolvedValue(true),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
PrescriptionsService,
{ provide: PrismaService, useValue: mockPrisma },
{ provide: SmsService, useValue: mockSmsService },
],
}).compile();
service = module.get<PrescriptionsService>(PrescriptionsService);
jest.clearAllMocks();
});
it("should be defined", () => {
expect(service).toBeDefined();
});
describe("create prescription", () => {
it("should auto-create user and pet when phone and petName provided for guest prescription", async () => {
mockPrisma.user.findFirst.mockResolvedValue(null);
mockPrisma.user.create.mockResolvedValue({
id: "u-new",
mobile: "09120000000",
});
mockPrisma.pet.findFirst.mockResolvedValue(null);
mockPrisma.pet.create.mockResolvedValue({ id: "p-new", name: "لئو" });
mockPrisma.prescription.create.mockResolvedValue({
id: "rx-1",
userId: "u-new",
petId: "p-new",
fileUrl: "https://canina.ir/rx.pdf",
status: "PENDING",
});
const res = await service.create(null, {
phone: "09120000000",
petName: "لئو",
petType: "سگ",
fileUrl: "https://canina.ir/rx.pdf",
notes: "بررسی کمبود کلسیم",
});
expect(mockPrisma.user.create).toHaveBeenCalledWith({
data: expect.objectContaining({
mobile: "09120000000",
role: "Customer",
}),
});
expect(mockPrisma.pet.create).toHaveBeenCalledWith({
data: expect.objectContaining({
userId: "u-new",
name: "لئو",
type: "سگ",
}),
});
expect(mockPrisma.prescription.create).toHaveBeenCalled();
expect(res.id).toBe("rx-1");
});
});
describe("findOne & authorization checks", () => {
it("should throw NotFoundException if prescription does not exist", async () => {
mockPrisma.prescription.findUnique.mockResolvedValue(null);
await expect(service.findOne("rx-999", "u-1", false)).rejects.toThrow(
NotFoundException,
);
});
it("should throw ForbiddenException if regular customer attempts to access someone else prescription", async () => {
mockPrisma.prescription.findUnique.mockResolvedValue({
id: "rx-1",
userId: "u-owner",
});
await expect(service.findOne("rx-1", "u-hacker", false)).rejects.toThrow(
ForbiddenException,
);
});
it("should grant access to admin even if prescription belongs to another user", async () => {
const rx = { id: "rx-1", userId: "u-owner", fileUrl: "https://..." };
mockPrisma.prescription.findUnique.mockResolvedValue(rx);
const res = await service.findOne("rx-1", "u-admin", true);
expect(res).toEqual(rx);
});
});
});
@@ -3,9 +3,9 @@ import {
NotFoundException,
ForbiddenException,
Logger,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService } from '../common/services/sms.service';
} from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { SmsService } from "../common/services/sms.service";
@Injectable()
export class PrescriptionsService {
@@ -44,9 +44,9 @@ export class PrescriptionsService {
user = await this.prisma.user.create({
data: {
mobile: cleanPhone,
role: 'Customer',
firstName: data.petName ? `سرپرست ${data.petName}` : 'کاربر',
lastName: 'کنینا',
role: "Customer",
firstName: data.petName ? `سرپرست ${data.petName}` : "کاربر",
lastName: "کنینا",
},
});
}
@@ -67,11 +67,11 @@ export class PrescriptionsService {
data: {
userId: user.id,
name: cleanPetName,
type: data.petType || 'سگ',
breed: data.petBreed || 'نامشخص',
type: data.petType || "سگ",
breed: data.petBreed || "نامشخص",
age: data.petAge !== undefined ? data.petAge : 0,
weight: data.petWeight !== undefined ? data.petWeight : 0,
activityLevel: 'متوسط',
activityLevel: "متوسط",
},
});
}
@@ -85,7 +85,7 @@ export class PrescriptionsService {
petId: finalPetId || undefined,
fileUrl: data.fileUrl,
notes: data.notes,
status: 'PENDING',
status: "PENDING",
},
include: { user: true, pet: true },
});
@@ -94,13 +94,13 @@ export class PrescriptionsService {
async findAll(userId: string, isAdmin: boolean) {
if (isAdmin) {
return this.prisma.prescription.findMany({
orderBy: { createdAt: 'desc' },
orderBy: { createdAt: "desc" },
include: { user: true, pet: true },
});
}
return this.prisma.prescription.findMany({
where: { userId },
orderBy: { createdAt: 'desc' },
orderBy: { createdAt: "desc" },
include: { pet: true },
});
}
@@ -116,7 +116,7 @@ export class PrescriptionsService {
}
if (!isAdmin && item.userId !== userId) {
throw new ForbiddenException('Access denied to this prescription');
throw new ForbiddenException("Access denied to this prescription");
}
return item;
@@ -125,7 +125,7 @@ export class PrescriptionsService {
async review(
id: string,
reviewData: {
status: 'APPROVED' | 'REJECTED' | 'PENDING';
status: "APPROVED" | "REJECTED" | "PENDING";
adminNotes?: string;
},
) {
@@ -147,8 +147,8 @@ export class PrescriptionsService {
});
// Send SMS notification if prescription was reviewed/approved and user has mobile
if (item.user?.mobile && reviewData.status === 'APPROVED') {
const petTitle = item.pet?.name ? ` برای «${item.pet.name}»` : '';
if (item.user?.mobile && reviewData.status === "APPROVED") {
const petTitle = item.pet?.name ? ` برای «${item.pet.name}»` : "";
const smsText = `کنینا: نسخه پزشکی شما${petTitle} توسط تیم تخصصی بررسی و تایید شد. جهت مشاهده تجویز پزشک و سفارش مکمل‌ها به پنل کاربری خود در canina.ir مراجعه کنید.`;
try {
await this.smsService.sendSms(item.user.mobile, smsText);