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

+10 -10
View File
@@ -1,43 +1,43 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsString, IsNotEmpty, IsOptional, IsBoolean } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsString, IsNotEmpty, IsOptional, IsBoolean } from "class-validator";
export class AddressDto {
@ApiProperty({ description: 'عنوان آدرس (مثلا خانه، کار)' })
@ApiProperty({ description: "عنوان آدرس (مثلا خانه، کار)" })
@IsString()
@IsNotEmpty()
title: string;
@ApiProperty({ description: 'نام تحویل‌گیرنده' })
@ApiProperty({ description: "نام تحویل‌گیرنده" })
@IsString()
@IsNotEmpty()
receptorName: string;
@ApiProperty({ description: 'شماره تلفن گیرنده' })
@ApiProperty({ description: "شماره تلفن گیرنده" })
@IsString()
@IsNotEmpty()
phone: string;
@ApiProperty({ description: 'استان' })
@ApiProperty({ description: "استان" })
@IsString()
@IsNotEmpty()
province: string;
@ApiProperty({ description: 'شهر' })
@ApiProperty({ description: "شهر" })
@IsString()
@IsNotEmpty()
city: string;
@ApiProperty({ description: 'جزئیات آدرس پستی' })
@ApiProperty({ description: "جزئیات آدرس پستی" })
@IsString()
@IsNotEmpty()
detail: string;
@ApiProperty({ description: 'کد پستی' })
@ApiProperty({ description: "کد پستی" })
@IsString()
@IsNotEmpty()
zipCode: string;
@ApiPropertyOptional({ description: 'انتخاب به عنوان آدرس پیش‌فرض' })
@ApiPropertyOptional({ description: "انتخاب به عنوان آدرس پیش‌فرض" })
@IsOptional()
@IsBoolean()
isDefault?: boolean;
+10 -10
View File
@@ -1,34 +1,34 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString, IsEmail, MinLength } from 'class-validator';
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString, IsEmail, MinLength } from "class-validator";
export class UpdateProfileDto {
@ApiPropertyOptional({ description: 'نام کاربر' })
@ApiPropertyOptional({ description: "نام کاربر" })
@IsOptional()
@IsString()
firstName?: string;
@ApiPropertyOptional({ description: 'نام خانوادگی کاربر' })
@ApiPropertyOptional({ description: "نام خانوادگی کاربر" })
@IsOptional()
@IsString()
lastName?: string;
@ApiPropertyOptional({ description: 'ایمیل کاربر' })
@ApiPropertyOptional({ description: "ایمیل کاربر" })
@IsOptional()
@IsEmail({}, { message: 'ایمیل نامعتبر است' })
@IsEmail({}, { message: "ایمیل نامعتبر است" })
email?: string;
@ApiPropertyOptional({ description: 'شماره موبایل کاربر' })
@ApiPropertyOptional({ description: "شماره موبایل کاربر" })
@IsOptional()
@IsString()
mobile?: string;
@ApiPropertyOptional({ description: 'رمز عبور جدید' })
@ApiPropertyOptional({ description: "رمز عبور جدید" })
@IsOptional()
@IsString()
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
@MinLength(6, { message: "رمز عبور باید حداقل ۶ کاراکتر باشد" })
password?: string;
@ApiPropertyOptional({ description: 'رمز عبور فعلی (در صورت وجود)' })
@ApiPropertyOptional({ description: "رمز عبور فعلی (در صورت وجود)" })
@IsOptional()
@IsString()
currentPassword?: string;
+51 -51
View File
@@ -1,20 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { Test, TestingModule } from "@nestjs/testing";
import { UsersController } from "./users.controller";
import { UsersService } from "./users.service";
describe('UsersController', () => {
describe("UsersController", () => {
let controller: UsersController;
let service: UsersService;
const mockUsersService = {
findById: jest.fn().mockResolvedValue({ id: 'user-id', firstName: 'Test' }),
findById: jest.fn().mockResolvedValue({ id: "user-id", firstName: "Test" }),
update: jest
.fn()
.mockResolvedValue({ id: 'user-id', firstName: 'Updated' }),
addAddress: jest.fn().mockResolvedValue({ id: 'addr-id', title: 'Home' }),
.mockResolvedValue({ id: "user-id", firstName: "Updated" }),
addAddress: jest.fn().mockResolvedValue({ id: "addr-id", title: "Home" }),
updateAddress: jest
.fn()
.mockResolvedValue({ id: 'addr-id', title: 'Work' }),
.mockResolvedValue({ id: "addr-id", title: "Work" }),
deleteAddress: jest.fn().mockResolvedValue({ success: true }),
setDefaultAddress: jest.fn().mockResolvedValue({ success: true }),
};
@@ -33,74 +33,74 @@ describe('UsersController', () => {
jest.clearAllMocks();
});
it('should be defined', () => {
it("should be defined", () => {
expect(controller).toBeDefined();
});
it('should getProfile', async () => {
const req = { user: { id: 'user-id' } };
it("should getProfile", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.getProfile(req);
expect(service.findById).toHaveBeenCalledWith('user-id');
expect(result?.id).toBe('user-id');
expect(service.findById).toHaveBeenCalledWith("user-id");
expect(result?.id).toBe("user-id");
});
it('should updateProfile', async () => {
const req = { user: { id: 'user-id' } };
const dto = { firstName: 'Updated' };
it("should updateProfile", async () => {
const req = { user: { id: "user-id" } };
const dto = { firstName: "Updated" };
const result = await controller.updateProfile(req, dto);
expect(service.update).toHaveBeenCalledWith('user-id', dto);
expect(result.firstName).toBe('Updated');
expect(service.update).toHaveBeenCalledWith("user-id", dto);
expect(result.firstName).toBe("Updated");
});
it('should addAddress', async () => {
const req = { user: { id: 'user-id' } };
it("should addAddress", async () => {
const req = { user: { id: "user-id" } };
const dto = {
title: 'Home',
receptorName: 'Ali',
phone: '0912',
province: 'Teh',
city: 'Teh',
detail: 'Det',
zipCode: '123',
title: "Home",
receptorName: "Ali",
phone: "0912",
province: "Teh",
city: "Teh",
detail: "Det",
zipCode: "123",
};
const result = await controller.addAddress(req, dto);
expect(service.addAddress).toHaveBeenCalledWith('user-id', dto);
expect(result.id).toBe('addr-id');
expect(service.addAddress).toHaveBeenCalledWith("user-id", dto);
expect(result.id).toBe("addr-id");
});
it('should updateAddress', async () => {
const req = { user: { id: 'user-id' } };
it("should updateAddress", async () => {
const req = { user: { id: "user-id" } };
const dto = {
title: 'Work',
receptorName: 'Ali',
phone: '0912',
province: 'Teh',
city: 'Teh',
detail: 'Det',
zipCode: '123',
title: "Work",
receptorName: "Ali",
phone: "0912",
province: "Teh",
city: "Teh",
detail: "Det",
zipCode: "123",
};
const result = await controller.updateAddress(req, 'addr-id', dto);
const result = await controller.updateAddress(req, "addr-id", dto);
expect(service.updateAddress).toHaveBeenCalledWith(
'user-id',
'addr-id',
"user-id",
"addr-id",
dto,
);
expect(result.title).toBe('Work');
expect(result.title).toBe("Work");
});
it('should deleteAddress', async () => {
const req = { user: { id: 'user-id' } };
const result = await controller.deleteAddress(req, 'addr-id');
expect(service.deleteAddress).toHaveBeenCalledWith('user-id', 'addr-id');
it("should deleteAddress", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.deleteAddress(req, "addr-id");
expect(service.deleteAddress).toHaveBeenCalledWith("user-id", "addr-id");
expect(result).toBeDefined();
});
it('should setDefaultAddress', async () => {
const req = { user: { id: 'user-id' } };
const result = await controller.setDefaultAddress(req, 'addr-id');
it("should setDefaultAddress", async () => {
const req = { user: { id: "user-id" } };
const result = await controller.setDefaultAddress(req, "addr-id");
expect(service.setDefaultAddress).toHaveBeenCalledWith(
'user-id',
'addr-id',
"user-id",
"addr-id",
);
expect(result).toBeDefined();
});
+91 -91
View File
@@ -10,11 +10,11 @@ import {
Req,
HttpStatus,
BadRequestException,
} from '@nestjs/common';
import { UsersService } from './users.service';
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 { UsersService } from "./users.service";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
import {
ApiTags,
ApiBearerAuth,
@@ -23,21 +23,21 @@ import {
ApiOkResponse,
ApiCreatedResponse,
ApiBadRequestResponse,
} from '@nestjs/swagger';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { AddressDto } from './dto/address.dto';
} from "@nestjs/swagger";
import { UpdateProfileDto } from "./dto/update-profile.dto";
import { AddressDto } from "./dto/address.dto";
@ApiTags('Users - مدیریت کاربران و آدرس‌ها')
@ApiTags("Users - مدیریت کاربران و آدرس‌ها")
@ApiBearerAuth()
@Controller('users')
@Controller("users")
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: 'عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است',
description: "عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است",
schema: {
example: {
success: false,
message: 'Unauthorized',
code: 'UNAUTHORIZED',
message: "Unauthorized",
code: "UNAUTHORIZED",
details: {},
},
},
@@ -46,24 +46,24 @@ export class UsersController {
constructor(private readonly usersService: UsersService) {}
@UseGuards(JwtAuthGuard)
@Get('profile')
@ApiOperation({ summary: 'دریافت پروفایل کاربر فعلی' })
@Get("profile")
@ApiOperation({ summary: "دریافت پروفایل کاربر فعلی" })
@ApiOkResponse({
description: 'مشخصات کامل کاربر به همراه آدرس‌ها و اطلاعات حیوانات خانگی',
description: "مشخصات کامل کاربر به همراه آدرس‌ها و اطلاعات حیوانات خانگی",
schema: {
example: {
id: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
firstName: 'کاربر',
lastName: 'جدید',
email: '09123456789@temp.local',
mobile: '09123456789',
role: 'User_PetOwner',
walletBalance: '1500000.00',
charityDonationTotal: '25000.00',
id: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
firstName: "کاربر",
lastName: "جدید",
email: "09123456789@temp.local",
mobile: "09123456789",
role: "User_PetOwner",
walletBalance: "1500000.00",
charityDonationTotal: "25000.00",
addresses: [],
pets: [],
createdAt: '2026-05-26T15:20:00.000Z',
updatedAt: '2026-05-26T15:20:00.000Z',
createdAt: "2026-05-26T15:20:00.000Z",
updatedAt: "2026-05-26T15:20:00.000Z",
},
},
})
@@ -72,32 +72,32 @@ export class UsersController {
}
@UseGuards(JwtAuthGuard)
@Patch('profile')
@ApiOperation({ summary: 'ویرایش پروفایل کاربر فعلی' })
@Patch("profile")
@ApiOperation({ summary: "ویرایش پروفایل کاربر فعلی" })
@ApiOkResponse({
description: 'پروفایل با موفقیت ویرایش شد',
description: "پروفایل با موفقیت ویرایش شد",
schema: {
example: {
id: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
firstName: 'علی',
lastName: 'احمدی',
email: 'ali@example.com',
mobile: '09123456789',
role: 'User_PetOwner',
walletBalance: '1500000.00',
charityDonationTotal: '25000.00',
id: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
firstName: "علی",
lastName: "احمدی",
email: "ali@example.com",
mobile: "09123456789",
role: "User_PetOwner",
walletBalance: "1500000.00",
charityDonationTotal: "25000.00",
},
},
})
@ApiBadRequestResponse({
description: 'خطا در صحت‌سنجی فیلدهای ورودی',
description: "خطا در صحت‌سنجی فیلدهای ورودی",
schema: {
example: {
success: false,
message: 'ایمیل نامعتبر است',
code: 'BAD_REQUEST',
message: "ایمیل نامعتبر است",
code: "BAD_REQUEST",
details: {
message: ['ایمیل نامعتبر است'],
message: ["ایمیل نامعتبر است"],
},
},
},
@@ -110,23 +110,23 @@ export class UsersController {
}
@UseGuards(JwtAuthGuard)
@Post('addresses')
@ApiOperation({ summary: 'ایجاد آدرس جدید برای کاربر' })
@Post("addresses")
@ApiOperation({ summary: "ایجاد آدرس جدید برای کاربر" })
@ApiCreatedResponse({
description: 'آدرس جدید با موفقیت ایجاد شد',
description: "آدرس جدید با موفقیت ایجاد شد",
schema: {
example: {
id: 'b5a6c7d8-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
title: 'خانه',
receptorName: 'علی احمدی',
phone: '09123456789',
province: 'تهران',
city: 'تهران',
detail: 'خیابان آزادی، کوچه مریم، پلاک ۱۰',
zipCode: '1456789012',
id: "b5a6c7d8-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
title: "خانه",
receptorName: "علی احمدی",
phone: "09123456789",
province: "تهران",
city: "تهران",
detail: "خیابان آزادی، کوچه مریم، پلاک ۱۰",
zipCode: "1456789012",
isDefault: false,
createdAt: '2026-05-26T18:00:00.000Z',
createdAt: "2026-05-26T18:00:00.000Z",
},
},
})
@@ -138,99 +138,99 @@ export class UsersController {
}
@UseGuards(JwtAuthGuard)
@Patch('addresses/:addressId')
@ApiOperation({ summary: 'ویرایش آدرس کاربر' })
@Patch("addresses/:addressId")
@ApiOperation({ summary: "ویرایش آدرس کاربر" })
@ApiOkResponse({
description: 'آدرس با موفقیت ویرایش شد',
description: "آدرس با موفقیت ویرایش شد",
schema: {
example: {
id: 'b5a6c7d8-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
title: 'دفتر کار',
receptorName: 'علی احمدی',
phone: '09123456789',
province: 'تهران',
city: 'تهران',
detail: 'خیابان ولیعصر، برج سپهر، طبقه ۴',
zipCode: '1456789012',
id: "b5a6c7d8-1234-5678-abcd-ef1234567890",
userId: "d8c4e428-cd2f-4c55-bfa3-dfa312bb6480",
title: "دفتر کار",
receptorName: "علی احمدی",
phone: "09123456789",
province: "تهران",
city: "تهران",
detail: "خیابان ولیعصر، برج سپهر، طبقه ۴",
zipCode: "1456789012",
isDefault: false,
createdAt: '2026-05-26T18:00:00.000Z',
createdAt: "2026-05-26T18:00:00.000Z",
},
},
})
updateAddress(
@Req() req: { user: { id: string } },
@Param('addressId') addressId: string,
@Param("addressId") addressId: string,
@Body() addressDto: AddressDto,
) {
return this.usersService.updateAddress(req.user.id, addressId, addressDto);
}
@UseGuards(JwtAuthGuard)
@Delete('addresses/:addressId')
@ApiOperation({ summary: 'حذف آدرس کاربر' })
@Delete("addresses/:addressId")
@ApiOperation({ summary: "حذف آدرس کاربر" })
@ApiOkResponse({
description: 'آدرس با موفقیت حذف شد',
description: "آدرس با موفقیت حذف شد",
schema: {
example: {
success: true,
message: 'آدرس با موفقیت حذف شد',
message: "آدرس با موفقیت حذف شد",
},
},
})
deleteAddress(
@Req() req: { user: { id: string } },
@Param('addressId') addressId: string,
@Param("addressId") addressId: string,
) {
return this.usersService.deleteAddress(req.user.id, addressId);
}
@UseGuards(JwtAuthGuard)
@Patch('addresses/:addressId/default')
@ApiOperation({ summary: 'انتخاب آدرس به عنوان پیش‌فرض' })
@Patch("addresses/:addressId/default")
@ApiOperation({ summary: "انتخاب آدرس به عنوان پیش‌فرض" })
@ApiOkResponse({
description: 'آدرس به عنوان پیش‌فرض ثبت شد',
description: "آدرس به عنوان پیش‌فرض ثبت شد",
schema: {
example: {
success: true,
message: 'آدرس پیش‌فرض با موفقیت تغییر کرد',
message: "آدرس پیش‌فرض با موفقیت تغییر کرد",
},
},
})
setDefaultAddress(
@Req() req: { user: { id: string } },
@Param('addressId') addressId: string,
@Param("addressId") addressId: string,
) {
return this.usersService.setDefaultAddress(req.user.id, addressId);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin', 'ADMIN', 'SuperAdmin')
@Roles("Admin", "ADMIN", "SuperAdmin")
@ApiBearerAuth()
@Post('wallet/top-up')
@ApiOperation({ summary: 'شارژ دستی کیف پول کاربر (فقط مدیر سیستم)' })
@Post("wallet/top-up")
@ApiOperation({ summary: "شارژ دستی کیف پول کاربر (فقط مدیر سیستم)" })
@ApiCreatedResponse({
description: 'کیف پول با موفقیت شارژ شد',
description: "کیف پول با موفقیت شارژ شد",
schema: {
example: {
id: 'txn-uuid',
userId: 'user-uuid',
amount: '500000.00',
type: 'deposit',
status: 'completed',
description: 'شارژ کیف پول',
createdAt: '2026-07-11T08:00:00.000Z',
id: "txn-uuid",
userId: "user-uuid",
amount: "500000.00",
type: "deposit",
status: "completed",
description: "شارژ کیف پول",
createdAt: "2026-07-11T08:00:00.000Z",
},
},
})
@ApiBadRequestResponse({ description: 'مبلغ نامعتبر است' })
@ApiBadRequestResponse({ description: "مبلغ نامعتبر است" })
async topUpWallet(
@Req() req: { user: { id: string } },
@Body() body: { amount: number; targetUserId?: string },
) {
const amount = Number(body.amount);
if (!amount || amount <= 0) {
throw new BadRequestException('مبلغ شارژ باید بزرگتر از صفر باشد');
throw new BadRequestException("مبلغ شارژ باید بزرگتر از صفر باشد");
}
const targetUserId = body.targetUserId || req.user.id;
return this.usersService.topUpWallet(targetUserId, amount);
+3 -3
View File
@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { Module } from "@nestjs/common";
import { UsersService } from "./users.service";
import { UsersController } from "./users.controller";
@Module({
controllers: [UsersController],
+149 -85
View File
@@ -1,8 +1,10 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
import { PrismaService } from '../prisma/prisma.service';
import { Test, TestingModule } from "@nestjs/testing";
import { UsersService } from "./users.service";
import { PrismaService } from "../prisma/prisma.service";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import * as bcrypt from "bcryptjs";
describe('UsersService', () => {
describe("UsersService", () => {
let service: UsersService;
let prisma: PrismaService;
@@ -35,98 +37,160 @@ describe('UsersService', () => {
jest.clearAllMocks();
});
it('should be defined', () => {
it("should be defined", () => {
expect(service).toBeDefined();
});
it('should call prisma findUnique in findById', async () => {
const mockUser = { id: 'user-id' };
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
const result = await service.findById('user-id');
expect(prisma.user.findUnique).toHaveBeenCalled();
expect(result).toEqual({ ...mockUser, hasPassword: false });
describe("findById", () => {
it("should return null when user does not exist", async () => {
mockPrisma.user.findUnique.mockResolvedValue(null);
const res = await service.findById("missing-id");
expect(res).toBeNull();
});
it("should return safe user profile hiding password hash but indicating hasPassword", async () => {
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
mobile: "09121111111",
password: "hashed-password-string",
firstName: "Parsa",
});
const res = await service.findById("u-1");
expect(res).not.toHaveProperty("password");
expect(res?.hasPassword).toBe(true);
expect(res?.firstName).toBe("Parsa");
});
});
it('should call prisma update in update', async () => {
const data = { firstName: 'Ali' };
mockPrisma.user.update.mockResolvedValue({ id: 'user-id', ...data });
const result = await service.update('user-id', data);
expect(prisma.user.update).toHaveBeenCalled();
expect(result.firstName).toBe('Ali');
describe("update profile & security checks", () => {
it("should throw NotFoundException if user is not found", async () => {
mockPrisma.user.findUnique.mockResolvedValue(null);
await expect(
service.update("u-missing", { firstName: "Test" }),
).rejects.toThrow(NotFoundException);
});
it("should throw BadRequestException if new mobile is already taken by another user", async () => {
mockPrisma.user.findUnique
.mockResolvedValueOnce({ id: "u-1", mobile: "09121111111" }) // current user
.mockResolvedValueOnce({ id: "u-2", mobile: "09122222222" }); // conflict user
await expect(
service.update("u-1", { mobile: "09122222222" }),
).rejects.toThrow("این شماره موبایل قبلاً توسط کاربر دیگری ثبت شده است");
});
it("should throw BadRequestException if new email is already taken by another user", async () => {
mockPrisma.user.findUnique
.mockResolvedValueOnce({ id: "u-1", email: "user1@canina.ir" }) // current user
.mockResolvedValueOnce({ id: "u-2", email: "conflict@canina.ir" }); // conflict user
await expect(
service.update("u-1", { email: "conflict@canina.ir" }),
).rejects.toThrow("این آدرس ایمیل قبلاً توسط کاربر دیگری ثبت شده است");
});
it("should require currentPassword if user already has password set and attempts password change", async () => {
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
password: "existing-hash",
});
await expect(
service.update("u-1", { password: "new-strong-password" }),
).rejects.toThrow(
"برای تغییر رمز عبور، وارد کردن رمز عبور فعلی الزامی است",
);
});
it("should reject password update if currentPassword does not match existing password", async () => {
const hashedOld = await bcrypt.hash("correct-old-password", 10);
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
password: hashedOld,
});
await expect(
service.update("u-1", {
currentPassword: "wrong-password",
password: "new-strong-password",
}),
).rejects.toThrow("رمز عبور فعلی اشتباه است");
});
it("should update password and return safe user when currentPassword matches", async () => {
const hashedOld = await bcrypt.hash("correct-old-password", 10);
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
password: hashedOld,
});
mockPrisma.user.update.mockResolvedValue({
id: "u-1",
firstName: "Parsa",
password: "new-hashed-password",
});
const res = await service.update("u-1", {
currentPassword: "correct-old-password",
password: "new-password-123",
});
expect(res).not.toHaveProperty("password");
expect(res?.hasPassword).toBe(true);
expect(mockPrisma.user.update).toHaveBeenCalled();
});
});
it('should addAddress', async () => {
const addressData = {
title: 'Home',
receptorName: 'Ali',
phone: '09123456789',
province: 'Tehran',
city: 'Tehran',
detail: 'Street 1',
zipCode: '1234567890',
isDefault: true,
};
mockPrisma.userAddress.create.mockResolvedValue({
id: 'addr-id',
...addressData,
describe("address management", () => {
it("should addAddress and unset previous default addresses if isDefault is true", async () => {
const addressData = {
title: "Home",
receptorName: "Parsa",
phone: "09121111111",
province: "Tehran",
city: "Tehran",
detail: "Street 1",
zipCode: "1234567890",
isDefault: true,
};
mockPrisma.userAddress.create.mockResolvedValue({
id: "addr-id",
...addressData,
});
const result = await service.addAddress("user-id", addressData);
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
where: { userId: "user-id" },
data: { isDefault: false },
});
expect(prisma.userAddress.create).toHaveBeenCalled();
expect(result.id).toBe("addr-id");
});
const result = await service.addAddress('user-id', addressData);
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
where: { userId: 'user-id' },
data: { isDefault: false },
});
expect(prisma.userAddress.create).toHaveBeenCalled();
expect(result.id).toBe('addr-id');
});
it('should updateAddress', async () => {
const addressData = {
title: 'Work',
receptorName: 'Ali',
phone: '09123456789',
province: 'Tehran',
city: 'Tehran',
detail: 'Street 2',
zipCode: '1234567890',
isDefault: true,
};
mockPrisma.userAddress.update.mockResolvedValue({
id: 'addr-id',
...addressData,
it("should deleteAddress ensuring scoped by userId", async () => {
mockPrisma.userAddress.delete.mockResolvedValue({ id: "addr-id" });
const result = await service.deleteAddress("user-id", "addr-id");
expect(prisma.userAddress.delete).toHaveBeenCalledWith({
where: { id: "addr-id", userId: "user-id" },
});
expect(result.id).toBe("addr-id");
});
const result = await service.updateAddress(
'user-id',
'addr-id',
addressData,
);
expect(prisma.userAddress.updateMany).toHaveBeenCalled();
expect(prisma.userAddress.update).toHaveBeenCalled();
expect(result.title).toBe('Work');
});
it('should deleteAddress', async () => {
mockPrisma.userAddress.delete.mockResolvedValue({ id: 'addr-id' });
const result = await service.deleteAddress('user-id', 'addr-id');
expect(prisma.userAddress.delete).toHaveBeenCalled();
expect(result.id).toBe('addr-id');
});
it('should setDefaultAddress', async () => {
mockPrisma.userAddress.update.mockResolvedValue({
id: 'addr-id',
isDefault: true,
it("should setDefaultAddress by clearing others and updating target", async () => {
mockPrisma.userAddress.update.mockResolvedValue({
id: "addr-id",
isDefault: true,
});
const result = await service.setDefaultAddress("user-id", "addr-id");
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
where: { userId: "user-id" },
data: { isDefault: false },
});
expect(prisma.userAddress.update).toHaveBeenCalledWith({
where: { id: "addr-id", userId: "user-id" },
data: { isDefault: true },
});
expect(result.isDefault).toBe(true);
});
const result = await service.setDefaultAddress('user-id', 'addr-id');
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
where: { userId: 'user-id' },
data: { isDefault: false },
});
expect(prisma.userAddress.update).toHaveBeenCalledWith({
where: { id: 'addr-id', userId: 'user-id' },
data: { isDefault: true },
});
expect(result.isDefault).toBe(true);
});
});
+25 -25
View File
@@ -3,13 +3,13 @@ import {
BadRequestException,
NotFoundException,
Optional,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService } from '../common/services/sms.service';
import * as bcrypt from 'bcryptjs';
import { normalizeMobile } from '../common/utils/phone.utils';
import { UpdateProfileDto } from './dto/update-profile.dto';
} from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { PrismaService } from "../prisma/prisma.service";
import { SmsService } from "../common/services/sms.service";
import * as bcrypt from "bcryptjs";
import { normalizeMobile } from "../common/utils/phone.utils";
import { UpdateProfileDto } from "./dto/update-profile.dto";
export interface UserAddressInput {
title: string;
@@ -45,7 +45,7 @@ export class UsersService {
},
},
orders: {
orderBy: { createdAt: 'desc' },
orderBy: { createdAt: "desc" },
include: {
orderItems: {
include: { product: true },
@@ -54,7 +54,7 @@ export class UsersService {
},
addresses: true,
walletTransactions: {
orderBy: { createdAt: 'desc' },
orderBy: { createdAt: "desc" },
take: 50,
},
},
@@ -72,7 +72,7 @@ export class UsersService {
async update(id: string, dto: UpdateProfileDto) {
const user = await this.prisma.user.findUnique({ where: { id } });
if (!user) {
throw new NotFoundException('کاربر یافت نشد');
throw new NotFoundException("کاربر یافت نشد");
}
const updateData: Prisma.UserUpdateInput = {};
@@ -89,7 +89,7 @@ export class UsersService {
});
if (existing && existing.id !== id) {
throw new BadRequestException(
'این شماره موبایل قبلاً توسط کاربر دیگری ثبت شده است',
"این شماره موبایل قبلاً توسط کاربر دیگری ثبت شده است",
);
}
updateData.mobile = normalizedMobile;
@@ -104,7 +104,7 @@ export class UsersService {
});
if (existing && existing.id !== id) {
throw new BadRequestException(
'این آدرس ایمیل قبلاً توسط کاربر دیگری ثبت شده است',
"این آدرس ایمیل قبلاً توسط کاربر دیگری ثبت شده است",
);
}
}
@@ -116,7 +116,7 @@ export class UsersService {
if (user.password) {
if (!dto.currentPassword) {
throw new BadRequestException(
'برای تغییر رمز عبور، وارد کردن رمز عبور فعلی الزامی است',
"برای تغییر رمز عبور، وارد کردن رمز عبور فعلی الزامی است",
);
}
const isCurrentMatch = await bcrypt.compare(
@@ -124,7 +124,7 @@ export class UsersService {
user.password,
);
if (!isCurrentMatch) {
throw new BadRequestException('رمز عبور فعلی اشتباه است');
throw new BadRequestException("رمز عبور فعلی اشتباه است");
}
}
updateData.password = await bcrypt.hash(dto.password.trim(), 10);
@@ -221,7 +221,7 @@ export class UsersService {
async topUpWallet(userId: string, amount: number) {
if (amount <= 0) {
throw new Error('مبلغ شارژ باید بزرگتر از صفر باشد');
throw new Error("مبلغ شارژ باید بزرگتر از صفر باشد");
}
const [transaction, updatedUser] = await this.prisma.$transaction([
@@ -229,9 +229,9 @@ export class UsersService {
data: {
userId,
amount,
type: 'deposit',
status: 'completed',
description: 'شارژ کیف پول',
type: "deposit",
status: "completed",
description: "شارژ کیف پول",
},
}),
this.prisma.user.update({
@@ -244,22 +244,22 @@ export class UsersService {
try {
const customerFullName = (
updatedUser.firstName
? `${updatedUser.firstName} ${updatedUser.lastName || ''}`
: 'کاربر گرامی'
? `${updatedUser.firstName} ${updatedUser.lastName || ""}`
: "کاربر گرامی"
).trim();
const topupData = {
customerName: customerFullName,
customerPhone: updatedUser.mobile,
amount: Number(amount || 0).toLocaleString('fa-IR'),
amount: Number(amount || 0).toLocaleString("fa-IR"),
balance: Number(updatedUser.walletBalance || 0).toLocaleString(
'fa-IR',
"fa-IR",
),
reason: 'افزایش موجودی کیف پول',
date: new Date().toLocaleDateString('fa-IR'),
reason: "افزایش موجودی کیف پول",
date: new Date().toLocaleDateString("fa-IR"),
};
this.smsService
.triggerEvent('WALLET_CHARGED', topupData)
.triggerEvent("WALLET_CHARGED", topupData)
.catch(() => {});
} catch (err) {
// Silently catch SMS error