feat(admin): implement complete User CRUD with create, edit, delete, and direct wallet adjust capabilities
Deploy Canina / deploy (push) Successful in 1m53s

This commit is contained in:
parsa aghaei committed 2026-08-16 15:16:47 +03:30
1 parent 6ae35efb3e
commit ad854a717b
4 files changed
+970 -206

No files matched your search

+37
View File
@@ -19,6 +19,8 @@ import {
ApiQuery,
} from '@nestjs/swagger';
import { CreateUserDto, UpdateUserDto } from './dto/user.dto';
@ApiTags('Admin - مدیریت سیستم')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@@ -43,6 +45,17 @@ export class AdminController {
return { success: true, ...result };
}
@Post('users')
@ApiOperation({ summary: 'ایجاد کاربر جدید توسط ادمین' })
async createUser(@Body() dto: CreateUserDto) {
const user = await this.adminService.createUser(dto);
return {
success: true,
message: 'کاربر جدید با موفقیت ایجاد شد',
data: user,
};
}
@Get('users/:id')
@ApiOperation({ summary: 'جزئیات کاربر' })
async getUserDetails(@Param('id') id: string) {
@@ -50,6 +63,30 @@ export class AdminController {
return { success: true, data };
}
@Put('users/:id')
@ApiOperation({ summary: 'ویرایش مشخصات کامل کاربر' })
async updateUser(
@Param('id') id: string,
@Body() dto: UpdateUserDto,
) {
const user = await this.adminService.updateUser(id, dto);
return {
success: true,
message: 'اطلاعات کاربر با موفقیت ویرایش شد',
data: user,
};
}
@Delete('users/:id')
@ApiOperation({ summary: 'حذف کاربر و داده‌های مرتبط' })
async deleteUser(@Param('id') id: string) {
await this.adminService.deleteUser(id);
return {
success: true,
message: 'کاربر با موفقیت از سیستم حذف شد',
};
}
@Put('users/:id/role')
@ApiOperation({ summary: 'تغییر نقش کاربر' })
async updateUserRole(@Param('id') id: string, @Body('role') role: string) {
+113 -1
View File
@@ -1,7 +1,14 @@
import { Injectable, HttpException, NotFoundException } from '@nestjs/common';
import {
Injectable,
HttpException,
NotFoundException,
BadRequestException,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import * as bcrypt from 'bcryptjs';
import { CreateUserDto, UpdateUserDto } from './dto/user.dto';
export class PaginationQuery {
page?: number | string;
@@ -169,6 +176,88 @@ export class AdminService {
return user;
}
async createUser(dto: CreateUserDto) {
const existingMobile = await this.prisma.user.findUnique({
where: { mobile: dto.mobile },
});
if (existingMobile) {
throw new BadRequestException('کاربری با این شماره موبایل قبلاً در سیستم ثبت شده است');
}
if (dto.email) {
const existingEmail = await this.prisma.user.findUnique({
where: { email: dto.email },
});
if (existingEmail) {
throw new BadRequestException('کاربری با این آدرس ایمیل قبلاً در سیستم ثبت شده است');
}
}
const hashedPassword = dto.password ? await bcrypt.hash(dto.password, 10) : '';
return this.prisma.user.create({
data: {
firstName: dto.firstName,
lastName: dto.lastName,
mobile: dto.mobile,
email: dto.email || null,
password: hashedPassword,
role: dto.role || 'User_PetOwner',
walletBalance:
dto.walletBalance !== undefined
? new Prisma.Decimal(dto.walletBalance)
: new Prisma.Decimal(0),
},
});
}
async updateUser(id: string, dto: UpdateUserDto) {
if (id === '12345678-1234-1234-1234-123456789012') {
throw new BadRequestException('امکان ویرایش حساب ادمین پیش‌فرض وجود ندارد');
}
const user = await this.prisma.user.findUnique({ where: { id } });
if (!user) {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
}
if (dto.mobile && dto.mobile !== user.mobile) {
const existingMobile = await this.prisma.user.findUnique({
where: { mobile: dto.mobile },
});
if (existingMobile && existingMobile.id !== id) {
throw new BadRequestException('این شماره موبایل متعلق به کاربر دیگری است');
}
}
if (dto.email && dto.email !== user.email) {
const existingEmail = await this.prisma.user.findUnique({
where: { email: dto.email },
});
if (existingEmail && existingEmail.id !== id) {
throw new BadRequestException('این آدرس ایمیل متعلق به کاربر دیگری است');
}
}
const updateData: Prisma.UserUpdateInput = {};
if (dto.firstName !== undefined) updateData.firstName = dto.firstName;
if (dto.lastName !== undefined) updateData.lastName = dto.lastName;
if (dto.mobile !== undefined) updateData.mobile = dto.mobile;
if (dto.email !== undefined) updateData.email = dto.email || null;
if (dto.role !== undefined) updateData.role = dto.role;
if (dto.walletBalance !== undefined) {
updateData.walletBalance = new Prisma.Decimal(dto.walletBalance);
}
if (dto.password && dto.password.trim().length >= 6) {
updateData.password = await bcrypt.hash(dto.password, 10);
}
return this.prisma.user.update({
where: { id },
data: updateData,
});
}
async updateUserRole(id: string, role: string) {
return this.prisma.user.update({
where: { id },
@@ -176,6 +265,29 @@ export class AdminService {
});
}
async deleteUser(id: string) {
if (id === '12345678-1234-1234-1234-123456789012') {
throw new BadRequestException('امکان حذف حساب ادمین پیش‌فرض وجود ندارد');
}
const user = await this.prisma.user.findUnique({ where: { id } });
if (!user) {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
}
return this.prisma.$transaction(async (tx) => {
await tx.userAddress.deleteMany({ where: { userId: id } });
await tx.walletTransaction.deleteMany({ where: { userId: id } });
await tx.pet.deleteMany({ where: { userId: id } });
await tx.prescription.deleteMany({ where: { userId: id } });
await tx.paymentTransaction.deleteMany({ where: { userId: id } });
await tx.partnerAccount.deleteMany({ where: { userId: id } });
await tx.blog.deleteMany({ where: { authorId: id } });
await tx.order.deleteMany({ where: { userId: id } });
return tx.user.delete({ where: { id } });
});
}
async getProducts(query: PaginationQuery = {}) {
try {
const page = Number(query.page) || 1;
+78
View File
@@ -0,0 +1,78 @@
import { IsNotEmpty, IsString, IsOptional, IsEmail, MinLength, IsNumber } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ description: 'نام کاربر', example: 'علی' })
@IsNotEmpty({ message: 'نام الزامی است' })
@IsString()
firstName!: string;
@ApiProperty({ description: 'نام خانوادگی کاربر', example: 'محمدی' })
@IsNotEmpty({ message: 'نام خانوادگی الزامی است' })
@IsString()
lastName!: string;
@ApiProperty({ description: 'شماره موبایل', example: '09123456789' })
@IsNotEmpty({ message: 'شماره موبایل الزامی است' })
@IsString()
mobile!: string;
@ApiPropertyOptional({ description: 'ایمیل کاربر', example: 'ali@example.com' })
@IsOptional()
@IsEmail({}, { message: 'فرمت ایمیل نامعتبر است' })
email?: string;
@ApiPropertyOptional({ description: 'رمز عبور', example: 'Password123' })
@IsOptional()
@IsString()
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
password?: string;
@ApiPropertyOptional({ description: 'نقش کاربر', example: 'User_PetOwner' })
@IsOptional()
@IsString()
role?: string;
@ApiPropertyOptional({ description: 'موجودی اولیه کیف پول', example: 0 })
@IsOptional()
@IsNumber({}, { message: 'موجودی کیف پول باید عدد باشد' })
walletBalance?: number;
}
export class UpdateUserDto {
@ApiPropertyOptional({ description: 'نام کاربر', example: 'علی' })
@IsOptional()
@IsString()
firstName?: string;
@ApiPropertyOptional({ description: 'نام خانوادگی کاربر', example: 'محمدی' })
@IsOptional()
@IsString()
lastName?: string;
@ApiPropertyOptional({ description: 'شماره موبایل', example: '09123456789' })
@IsOptional()
@IsString()
mobile?: string;
@ApiPropertyOptional({ description: 'ایمیل کاربر', example: 'ali@example.com' })
@IsOptional()
@IsEmail({}, { message: 'فرمت ایمیل نامعتبر است' })
email?: string;
@ApiPropertyOptional({ description: 'رمز عبور جدید', example: 'NewPassword123' })
@IsOptional()
@IsString()
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
password?: string;
@ApiPropertyOptional({ description: 'نقش کاربر', example: 'User_PetOwner' })
@IsOptional()
@IsString()
role?: string;
@ApiPropertyOptional({ description: 'موجودی کیف پول', example: 500000 })
@IsOptional()
@IsNumber({}, { message: 'موجودی کیف پول باید عدد باشد' })
walletBalance?: number;
}
File diff suppressed because it is too large. Load diff