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

@@ -1,25 +1,25 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsString, IsOptional } from "class-validator";
export class CreateHealthLogDto {
@ApiProperty({ description: 'وضعیت اشتها', example: 'عالی' })
@ApiProperty({ description: "وضعیت اشتها", example: "عالی" })
@IsNotEmpty()
@IsString()
appetite: string;
@ApiProperty({ description: 'وضعیت انرژی', example: 'نرمال' })
@ApiProperty({ description: "وضعیت انرژی", example: "نرمال" })
@IsNotEmpty()
@IsString()
energy: string;
@ApiProperty({ description: 'وضعیت گوارش', example: 'نرمال' })
@ApiProperty({ description: "وضعیت گوارش", example: "نرمال" })
@IsNotEmpty()
@IsString()
digestion: string;
@ApiPropertyOptional({
description: 'یادداشت یا توضیح اضافی',
example: 'امروز فعالیت خوبی داشت.',
description: "یادداشت یا توضیح اضافی",
example: "امروز فعالیت خوبی داشت.",
})
@IsOptional()
@IsString()
+9 -9
View File
@@ -1,44 +1,44 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsNotEmpty,
IsString,
IsOptional,
IsNumber,
IsArray,
} from 'class-validator';
} from "class-validator";
export class CreatePetDto {
@ApiProperty({ description: 'نام حیوان خانگی', example: 'بادی' })
@ApiProperty({ description: "نام حیوان خانگی", example: "بادی" })
@IsNotEmpty()
@IsString()
name: string;
@ApiProperty({ description: 'نوع (سگ/گربه)', example: 'سگ' })
@ApiProperty({ description: "نوع (سگ/گربه)", example: "سگ" })
@IsNotEmpty()
@IsString()
type: string;
@ApiPropertyOptional({ description: 'نژاد', example: 'ژرمن شپرد' })
@ApiPropertyOptional({ description: "نژاد", example: "ژرمن شپرد" })
@IsOptional()
@IsString()
breed?: string;
@ApiPropertyOptional({ description: 'وزن (کیلوگرم)', example: 25.5 })
@ApiPropertyOptional({ description: "وزن (کیلوگرم)", example: 25.5 })
@IsOptional()
@IsNumber()
weight?: number;
@ApiPropertyOptional({ description: 'سن (سال)', example: 3 })
@ApiPropertyOptional({ description: "سن (سال)", example: 3 })
@IsOptional()
@IsNumber()
age?: number;
@ApiPropertyOptional({ description: 'سطح فعالیت', example: 'متوسط' })
@ApiPropertyOptional({ description: "سطح فعالیت", example: "متوسط" })
@IsOptional()
@IsString()
activityLevel?: string;
@ApiPropertyOptional({ description: 'سوابق پزشکی', type: [String] })
@ApiPropertyOptional({ description: "سوابق پزشکی", type: [String] })
@IsOptional()
@IsArray()
@IsString({ each: true })
+8 -8
View File
@@ -1,28 +1,28 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsString, IsOptional } from "class-validator";
export class CreateReminderDto {
@ApiProperty({ description: 'عنوان یادآور', example: 'قرص کلسیم' })
@ApiProperty({ description: "عنوان یادآور", example: "قرص کلسیم" })
@IsNotEmpty()
@IsString()
title: string;
@ApiProperty({ description: 'زمان یادآور (مثال: 08:30)', example: '08:30' })
@ApiProperty({ description: "زمان یادآور (مثال: 08:30)", example: "08:30" })
@IsNotEmpty()
@IsString()
time: string;
@ApiProperty({
description: 'دوره زمانی (روزانه / هفتگی)',
example: 'روزانه',
description: "دوره زمانی (روزانه / هفتگی)",
example: "روزانه",
})
@IsNotEmpty()
@IsString()
frequency: string;
@ApiPropertyOptional({
description: 'شناسه محصول مربوطه',
example: 'a1b2c3d4-1234-5678-abcd-ef1234567890',
description: "شناسه محصول مربوطه",
example: "a1b2c3d4-1234-5678-abcd-ef1234567890",
})
@IsOptional()
@IsString()
+2 -2
View File
@@ -1,4 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreatePetDto } from './create-pet.dto';
import { PartialType } from "@nestjs/swagger";
import { CreatePetDto } from "./create-pet.dto";
export class UpdatePetDto extends PartialType(CreatePetDto) {}
+32 -32
View File
@@ -1,18 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PetsController } from './pets.controller';
import { PetsService } from './pets.service';
import { Test, TestingModule } from "@nestjs/testing";
import { PetsController } from "./pets.controller";
import { PetsService } from "./pets.service";
describe('PetsController', () => {
describe("PetsController", () => {
let controller: PetsController;
let service: PetsService;
const mockPetsService = {
create: jest.fn().mockResolvedValue({ id: 'pet-id', name: 'Buddy' }),
create: jest.fn().mockResolvedValue({ id: "pet-id", name: "Buddy" }),
findAllByUser: jest
.fn()
.mockResolvedValue({ data: [{ id: 'pet-id', name: 'Buddy' }] }),
findOne: jest.fn().mockResolvedValue({ id: 'pet-id', name: 'Buddy' }),
update: jest.fn().mockResolvedValue({ id: 'pet-id', name: 'Buddy New' }),
.mockResolvedValue({ data: [{ id: "pet-id", name: "Buddy" }] }),
findOne: jest.fn().mockResolvedValue({ id: "pet-id", name: "Buddy" }),
update: jest.fn().mockResolvedValue({ id: "pet-id", name: "Buddy New" }),
remove: jest.fn().mockResolvedValue({ success: true }),
};
@@ -30,44 +30,44 @@ describe('PetsController', () => {
jest.clearAllMocks();
});
it('should be defined', () => {
it("should be defined", () => {
expect(controller).toBeDefined();
});
it('should create pet', async () => {
const req = { user: { id: 'user-id' } };
const dto = { name: 'Buddy', type: 'Dog' };
it("should create pet", async () => {
const req = { user: { id: "user-id" } };
const dto = { name: "Buddy", type: "Dog" };
const result = await controller.create(req, dto);
expect(service.create).toHaveBeenCalledWith('user-id', dto);
expect(result.id).toBe('pet-id');
expect(service.create).toHaveBeenCalledWith("user-id", dto);
expect(result.id).toBe("pet-id");
});
it('should findAll pets', async () => {
const req = { user: { id: 'user-id' } };
it("should findAll pets", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.findAll(req, {});
expect(service.findAllByUser).toHaveBeenCalledWith('user-id', {});
expect(service.findAllByUser).toHaveBeenCalledWith("user-id", {});
expect(result.data).toHaveLength(1);
});
it('should findOne pet', async () => {
const req = { user: { id: 'user-id' } };
const result = await controller.findOne(req, 'pet-id');
expect(service.findOne).toHaveBeenCalledWith('pet-id', 'user-id');
expect(result.id).toBe('pet-id');
it("should findOne pet", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.findOne(req, "pet-id");
expect(service.findOne).toHaveBeenCalledWith("pet-id", "user-id");
expect(result.id).toBe("pet-id");
});
it('should update pet', async () => {
const req = { user: { id: 'user-id' } };
const dto = { name: 'Buddy New' };
const result = await controller.update(req, 'pet-id', dto);
expect(service.update).toHaveBeenCalledWith('pet-id', 'user-id', dto);
expect(result.name).toBe('Buddy New');
it("should update pet", async () => {
const req = { user: { id: "user-id" } };
const dto = { name: "Buddy New" };
const result = await controller.update(req, "pet-id", dto);
expect(service.update).toHaveBeenCalledWith("pet-id", "user-id", dto);
expect(result.name).toBe("Buddy New");
});
it('should remove pet', async () => {
const req = { user: { id: 'user-id' } };
const result = await controller.remove(req, 'pet-id');
expect(service.remove).toHaveBeenCalledWith('pet-id', 'user-id');
it("should remove pet", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.remove(req, "pet-id");
expect(service.remove).toHaveBeenCalledWith("pet-id", "user-id");
expect(result).toBeDefined();
});
});
+101 -96
View File
@@ -13,17 +13,17 @@ import {
UseInterceptors,
UploadedFile,
BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import * as fs from 'fs';
import { PetsService } from './pets.service';
import { CreatePetDto } from './dto/create-pet.dto';
import { UpdatePetDto } from './dto/update-pet.dto';
import { CreateReminderDto } from './dto/create-reminder.dto';
import { CreateHealthLogDto } from './dto/create-health-log.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { diskStorage } from "multer";
import { extname, join } from "path";
import * as fs from "fs";
import { PetsService } from "./pets.service";
import { CreatePetDto } from "./dto/create-pet.dto";
import { UpdatePetDto } from "./dto/update-pet.dto";
import { CreateReminderDto } from "./dto/create-reminder.dto";
import { CreateHealthLogDto } from "./dto/create-health-log.dto";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import {
ApiTags,
ApiBearerAuth,
@@ -33,21 +33,21 @@ import {
ApiCreatedResponse,
ApiBadRequestResponse,
ApiNotFoundResponse,
} from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
} from "@nestjs/swagger";
import { PaginationDto } from "../common/dto/pagination.dto";
@ApiTags('Pets - مدیریت حیوانات خانگی')
@ApiTags("Pets - مدیریت حیوانات خانگی")
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('pets')
@Controller("pets")
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: 'عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است',
description: "عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است",
schema: {
example: {
success: false,
message: 'Unauthorized',
code: 'UNAUTHORIZED',
message: "Unauthorized",
code: "UNAUTHORIZED",
details: {},
},
},
@@ -55,12 +55,12 @@ import { PaginationDto } from '../common/dto/pagination.dto';
export class PetsController {
constructor(private readonly petsService: PetsService) {}
@Post('upload-image')
@Post("upload-image")
@UseInterceptors(
FileInterceptor('file', {
FileInterceptor("file", {
storage: diskStorage({
destination: (req, file, cb) => {
const dir = join(process.cwd(), 'uploads', 'pets');
const dir = join(process.cwd(), "uploads", "pets");
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
@@ -70,17 +70,22 @@ export class PetsController {
const randomName = Array(32)
.fill(null)
.map(() => Math.round(Math.random() * 16).toString(16))
.join('');
.join("");
cb(null, `${randomName}${extname(file.originalname)}`);
},
}),
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
fileFilter: (_req, file, callback) => {
const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
const allowedMimeTypes = [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
];
if (!allowedMimeTypes.includes(file.mimetype)) {
return callback(
new BadRequestException(
'فرمت فایل مجاز نیست. لطفاً یکی از فرمت‌های JPG, PNG, WEBP را انتخاب کنید',
"فرمت فایل مجاز نیست. لطفاً یکی از فرمت‌های JPG, PNG, WEBP را انتخاب کنید",
),
false,
);
@@ -89,41 +94,41 @@ export class PetsController {
},
}),
)
@ApiOperation({ summary: 'آپلود تصویر حیوان خانگی' })
@ApiOperation({ summary: "آپلود تصویر حیوان خانگی" })
uploadPetImage(@UploadedFile() file: Express.Multer.File) {
if (!file) {
throw new BadRequestException('فایلی ارسال نشده است');
throw new BadRequestException("فایلی ارسال نشده است");
}
const url = `/uploads/pets/${file.filename}`;
return { url, filename: file.filename };
}
@Post()
@ApiOperation({ summary: 'ثبت حیوان خانگی جدید' })
@ApiOperation({ summary: "ثبت حیوان خانگی جدید" })
@ApiCreatedResponse({
description: 'حیوان خانگی جدید با موفقیت ثبت شد',
description: "حیوان خانگی جدید با موفقیت ثبت شد",
schema: {
example: {
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
id: "c7b8d9e0-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
name: "بادی",
type: "سگ",
breed: "ژرمن شپرد",
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
weight: "25.50",
activityLevel: "متوسط",
imageUrl: null,
createdAt: '2026-05-26T18:10:00.000Z',
createdAt: "2026-05-26T18:10:00.000Z",
},
},
})
@ApiBadRequestResponse({
description: 'خطا در صحت‌سنجی فیلدهای ورودی',
description: "خطا در صحت‌سنجی فیلدهای ورودی",
schema: {
example: {
success: false,
message: 'نوع حیوان خانگی اجباری است',
code: 'BAD_REQUEST',
message: "نوع حیوان خانگی اجباری است",
code: "BAD_REQUEST",
details: {},
},
},
@@ -136,23 +141,23 @@ export class PetsController {
}
@Get()
@ApiOperation({ summary: 'لیست حیوانات خانگی کاربر فعلی' })
@ApiOperation({ summary: "لیست حیوانات خانگی کاربر فعلی" })
@ApiOkResponse({
description: 'آرایه‌ای از حیوانات خانگی ثبت شده کاربر (صفحه‌بندی شده)',
description: "آرایه‌ای از حیوانات خانگی ثبت شده کاربر (صفحه‌بندی شده)",
schema: {
example: {
data: [
{
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
id: "c7b8d9e0-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
name: "بادی",
type: "سگ",
breed: "ژرمن شپرد",
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
weight: "25.50",
activityLevel: "متوسط",
imageUrl: null,
createdAt: '2026-05-26T18:10:00.000Z',
createdAt: "2026-05-26T18:10:00.000Z",
},
],
meta: {
@@ -168,121 +173,121 @@ export class PetsController {
return this.petsService.findAllByUser(req.user.id, query);
}
@Get(':id')
@ApiOperation({ summary: 'دریافت جزئیات کامل یک حیوان خانگی' })
@Get(":id")
@ApiOperation({ summary: "دریافت جزئیات کامل یک حیوان خانگی" })
@ApiOkResponse({
description: 'اطلاعات کامل حیوان خانگی مشخص شده با ID',
description: "اطلاعات کامل حیوان خانگی مشخص شده با ID",
schema: {
example: {
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
id: "c7b8d9e0-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
name: "بادی",
type: "سگ",
breed: "ژرمن شپرد",
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
weight: "25.50",
activityLevel: "متوسط",
imageUrl: null,
medicalConditions: [],
reminders: [],
healthLogs: [],
createdAt: '2026-05-26T18:10:00.000Z',
createdAt: "2026-05-26T18:10:00.000Z",
},
},
})
@ApiNotFoundResponse({
description: 'حیوان خانگی پیدا نشد یا متعلق به کاربر جاری نیست',
description: "حیوان خانگی پیدا نشد یا متعلق به کاربر جاری نیست",
schema: {
example: {
success: false,
message: 'Pet not found or unauthorized',
code: 'NOT_FOUND',
message: "Pet not found or unauthorized",
code: "NOT_FOUND",
details: {},
},
},
})
findOne(@Req() req: { user: { id: string } }, @Param('id') id: string) {
findOne(@Req() req: { user: { id: string } }, @Param("id") id: string) {
return this.petsService.findOne(id, req.user.id);
}
@Patch(':id')
@ApiOperation({ summary: 'بروزرسانی اطلاعات حیوان خانگی' })
@Patch(":id")
@ApiOperation({ summary: "بروزرسانی اطلاعات حیوان خانگی" })
@ApiOkResponse({
description: 'اطلاعات حیوان خانگی با موفقیت به‌روزرسانی شد',
description: "اطلاعات حیوان خانگی با موفقیت به‌روزرسانی شد",
schema: {
example: {
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
name: 'بادی قهرمان',
type: 'سگ',
breed: 'ژرمن شپرد',
id: "c7b8d9e0-1234-5678-abcd-ef1234567890",
name: "بادی قهرمان",
type: "سگ",
breed: "ژرمن شپرد",
age: 4,
weight: '26.00',
activityLevel: 'زیاد',
weight: "26.00",
activityLevel: "زیاد",
},
},
})
@ApiNotFoundResponse({
description: 'حیوان خانگی یافت نشد',
description: "حیوان خانگی یافت نشد",
schema: {
example: {
success: false,
message: 'Pet not found',
code: 'NOT_FOUND',
message: "Pet not found",
code: "NOT_FOUND",
details: {},
},
},
})
update(
@Req() req: { user: { id: string } },
@Param('id') id: string,
@Param("id") id: string,
@Body() updatePetDto: UpdatePetDto,
) {
return this.petsService.update(id, req.user.id, updatePetDto);
}
@Delete(':id')
@ApiOperation({ summary: 'حذف حیوان خانگی' })
@Delete(":id")
@ApiOperation({ summary: "حذف حیوان خانگی" })
@ApiOkResponse({
description: 'حیوان خانگی با موفقیت حذف شد',
description: "حیوان خانگی با موفقیت حذف شد",
schema: {
example: {
success: true,
message: 'حیوان خانگی با موفقیت حذف شد',
message: "حیوان خانگی با موفقیت حذف شد",
},
},
})
@ApiNotFoundResponse({
description: 'حیوان خانگی یافت نشد',
description: "حیوان خانگی یافت نشد",
schema: {
example: {
success: false,
message: 'Pet not found',
code: 'NOT_FOUND',
message: "Pet not found",
code: "NOT_FOUND",
details: {},
},
},
})
remove(@Req() req: { user: { id: string } }, @Param('id') id: string) {
remove(@Req() req: { user: { id: string } }, @Param("id") id: string) {
return this.petsService.remove(id, req.user.id);
}
@Post(':petId/reminders')
@ApiOperation({ summary: 'ثبت یادآور جدید برای پت' })
@Post(":petId/reminders")
@ApiOperation({ summary: "ثبت یادآور جدید برای پت" })
addReminder(
@Req() req: { user: { id: string } },
@Param('petId') petId: string,
@Param("petId") petId: string,
@Body() createReminderDto: CreateReminderDto,
) {
return this.petsService.addReminder(req.user.id, petId, createReminderDto);
}
@Post(':petId/reminders/:reminderId/toggle')
@ApiOperation({ summary: 'تغییر وضعیت انجام یادآور در یک تاریخ خاص' })
@Post(":petId/reminders/:reminderId/toggle")
@ApiOperation({ summary: "تغییر وضعیت انجام یادآور در یک تاریخ خاص" })
toggleReminder(
@Req() req: { user: { id: string } },
@Param('petId') petId: string,
@Param('reminderId') reminderId: string,
@Body('date') date: string,
@Param("petId") petId: string,
@Param("reminderId") reminderId: string,
@Body("date") date: string,
) {
return this.petsService.toggleReminder(
req.user.id,
@@ -292,11 +297,11 @@ export class PetsController {
);
}
@Post(':petId/health-logs')
@ApiOperation({ summary: 'ثبت لاگ سلامت جدید برای پت' })
@Post(":petId/health-logs")
@ApiOperation({ summary: "ثبت لاگ سلامت جدید برای پت" })
addHealthLog(
@Req() req: { user: { id: string } },
@Param('petId') petId: string,
@Param("petId") petId: string,
@Body() createHealthLogDto: CreateHealthLogDto,
) {
return this.petsService.addHealthLog(
+3 -3
View File
@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { PetsService } from './pets.service';
import { PetsController } from './pets.controller';
import { Module } from "@nestjs/common";
import { PetsService } from "./pets.service";
import { PetsController } from "./pets.controller";
@Module({
controllers: [PetsController],
+29 -29
View File
@@ -1,9 +1,9 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PetsService } from './pets.service';
import { PrismaService } from '../prisma/prisma.service';
import { NotFoundException } from '@nestjs/common';
import { Test, TestingModule } from "@nestjs/testing";
import { PetsService } from "./pets.service";
import { PrismaService } from "../prisma/prisma.service";
import { NotFoundException } from "@nestjs/common";
describe('PetsService', () => {
describe("PetsService", () => {
let service: PetsService;
let prisma: PrismaService;
@@ -34,61 +34,61 @@ describe('PetsService', () => {
jest.clearAllMocks();
});
it('should be defined', () => {
it("should be defined", () => {
expect(service).toBeDefined();
});
it('should create pet', async () => {
const dto = { name: 'Buddy', type: 'Dog', weight: 12.5 };
mockPrisma.pet.create.mockResolvedValue({ id: 'pet-id', ...dto });
it("should create pet", async () => {
const dto = { name: "Buddy", type: "Dog", weight: 12.5 };
mockPrisma.pet.create.mockResolvedValue({ id: "pet-id", ...dto });
const result = await service.create('user-id', dto);
const result = await service.create("user-id", dto);
expect(prisma.pet.create).toHaveBeenCalled();
expect(result.name).toBe('Buddy');
expect(result.name).toBe("Buddy");
});
it('should find all pets by user', async () => {
mockPrisma.pet.findMany.mockResolvedValue([{ id: 'pet-1' }]);
it("should find all pets by user", async () => {
mockPrisma.pet.findMany.mockResolvedValue([{ id: "pet-1" }]);
mockPrisma.pet.count.mockResolvedValue(1);
const result = await service.findAllByUser('user-id', {});
const result = await service.findAllByUser("user-id", {});
expect(prisma.pet.findMany).toHaveBeenCalled();
expect(result.data).toHaveLength(1);
});
describe('findOne', () => {
it('should throw NotFoundException if pet not found', async () => {
describe("findOne", () => {
it("should throw NotFoundException if pet not found", async () => {
mockPrisma.pet.findFirst.mockResolvedValue(null);
await expect(service.findOne('pet-id', 'user-id')).rejects.toThrow(
await expect(service.findOne("pet-id", "user-id")).rejects.toThrow(
NotFoundException,
);
});
it('should return pet if found', async () => {
const pet = { id: 'pet-id', userId: 'user-id' };
it("should return pet if found", async () => {
const pet = { id: "pet-id", userId: "user-id" };
mockPrisma.pet.findFirst.mockResolvedValue(pet);
const result = await service.findOne('pet-id', 'user-id');
const result = await service.findOne("pet-id", "user-id");
expect(result).toEqual(pet);
});
});
it('should update pet', async () => {
const pet = { id: 'pet-id', userId: 'user-id' };
it("should update pet", async () => {
const pet = { id: "pet-id", userId: "user-id" };
mockPrisma.pet.findFirst.mockResolvedValue(pet);
const dto = { name: 'Buddy New', type: 'Dog' };
const dto = { name: "Buddy New", type: "Dog" };
mockPrisma.pet.update.mockResolvedValue({ ...pet, ...dto });
const result = await service.update('pet-id', 'user-id', dto);
const result = await service.update("pet-id", "user-id", dto);
expect(prisma.pet.update).toHaveBeenCalled();
expect(result.name).toBe('Buddy New');
expect(result.name).toBe("Buddy New");
});
it('should remove pet', async () => {
const pet = { id: 'pet-id', userId: 'user-id' };
it("should remove pet", async () => {
const pet = { id: "pet-id", userId: "user-id" };
mockPrisma.pet.findFirst.mockResolvedValue(pet);
mockPrisma.pet.delete.mockResolvedValue(pet);
const result = await service.remove('pet-id', 'user-id');
const result = await service.remove("pet-id", "user-id");
expect(prisma.pet.delete).toHaveBeenCalled();
expect(result.id).toBe('pet-id');
expect(result.id).toBe("pet-id");
});
});
+22 -22
View File
@@ -1,9 +1,9 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { CreatePetDto } from './dto/create-pet.dto';
import { UpdatePetDto } from './dto/update-pet.dto';
import { Injectable, NotFoundException } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { PrismaService } from "../prisma/prisma.service";
import { PaginationDto } from "../common/dto/pagination.dto";
import { CreatePetDto } from "./dto/create-pet.dto";
import { UpdatePetDto } from "./dto/update-pet.dto";
export interface ReminderInput {
productId?: string | null;
@@ -31,8 +31,8 @@ export class PetsService {
data: {
name,
type,
breed: breed || '',
activityLevel: activityLevel || 'متوسط',
breed: breed || "",
activityLevel: activityLevel || "متوسط",
age: age || 1,
weight: weight || 0,
userId,
@@ -51,17 +51,17 @@ export class PetsService {
search,
page = 1,
limit = 10,
sortBy = 'createdAt',
sortOrder = 'desc',
sortBy = "createdAt",
sortOrder = "desc",
} = filters;
const whereClause: Prisma.PetWhereInput = {};
if (search) {
whereClause.OR = [
{ name: { contains: search, mode: 'insensitive' } },
{ breed: { contains: search, mode: 'insensitive' } },
{ user: { firstName: { contains: search, mode: 'insensitive' } } },
{ user: { lastName: { contains: search, mode: 'insensitive' } } },
{ name: { contains: search, mode: "insensitive" } },
{ breed: { contains: search, mode: "insensitive" } },
{ user: { firstName: { contains: search, mode: "insensitive" } } },
{ user: { lastName: { contains: search, mode: "insensitive" } } },
{ user: { mobile: { contains: search } } },
];
}
@@ -87,7 +87,7 @@ export class PetsService {
medicalConditions: true,
reminders: true,
healthLogs: {
orderBy: { loggedDate: 'desc' },
orderBy: { loggedDate: "desc" },
take: 10,
},
},
@@ -111,15 +111,15 @@ export class PetsService {
search,
page = 1,
limit = 10,
sortBy = 'createdAt',
sortOrder = 'desc',
sortBy = "createdAt",
sortOrder = "desc",
} = filters;
const whereClause: Prisma.PetWhereInput = { userId };
if (search) {
whereClause.OR = [
{ name: { contains: search, mode: 'insensitive' } },
{ breed: { contains: search, mode: 'insensitive' } },
{ name: { contains: search, mode: "insensitive" } },
{ breed: { contains: search, mode: "insensitive" } },
];
}
@@ -153,7 +153,7 @@ export class PetsService {
include: { medicalConditions: true, reminders: true, healthLogs: true },
});
if (!pet) {
throw new NotFoundException('حیوان خانگی یافت نشد');
throw new NotFoundException("حیوان خانگی یافت نشد");
}
return pet;
}
@@ -220,10 +220,10 @@ export class PetsService {
where: { id: reminderId },
});
if (!reminder || reminder.petId !== petId) {
throw new NotFoundException('یادآور یافت نشد');
throw new NotFoundException("یادآور یافت نشد");
}
const dateParts = dateStr.split('-');
const dateParts = dateStr.split("-");
const completedDate = new Date(
Date.UTC(
Number(dateParts[0]),