import { Injectable } from '@nestjs/common'; import { Prisma } from '@prisma/client'; import * as bcrypt from 'bcryptjs'; import { ErrorCode } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { BusinessException } from '../common/exceptions/business.exception'; import { buildPage } from '../common/utils/pagination.util'; import { buildOrderBy } from '../common/utils/sort.util'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { QueryUserDto } from './dto/query-user.dto'; const userSelect = { id: true, username: true, realName: true, role: true, status: true, lastLoginAt: true, createdAt: true, }; @Injectable() export class UserService { constructor(private readonly prisma: PrismaService) {} async list(query: QueryUserDto) { const where: Prisma.SysUserWhereInput = {}; if (query.keyword) { const id = Number(query.keyword); where.OR = [ ...(Number.isInteger(id) && id > 0 ? [{ id }] : []), { username: { contains: query.keyword } }, { realName: { contains: query.keyword } }, ]; } if (query.role) where.role = query.role; if (query.status) where.status = query.status; const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'lastLoginAt'] as const, { id: 'desc' }); const [list, total] = await this.prisma.$transaction([ this.prisma.sysUser.findMany({ where, select: userSelect, orderBy, skip: query.skip, take: query.take, }), this.prisma.sysUser.count({ where }), ]); return buildPage(list, total, query.page, query.pageSize); } async create(dto: CreateUserDto) { const exists = await this.prisma.sysUser.findUnique({ where: { username: dto.username } }); if (exists) { throw new BusinessException(ErrorCode.USERNAME_EXISTS, '用户名已存在'); } const passwordHash = await bcrypt.hash(dto.password, 10); return this.prisma.sysUser.create({ data: { username: dto.username, passwordHash, realName: dto.realName, role: dto.role, }, select: userSelect, }); } async update(id: number, dto: UpdateUserDto) { await this.ensureExists(id); return this.prisma.sysUser.update({ where: { id }, data: { realName: dto.realName, role: dto.role, status: dto.status }, select: userSelect, }); } async resetPassword(id: number, newPassword: string) { await this.ensureExists(id); const passwordHash = await bcrypt.hash(newPassword, 10); await this.prisma.sysUser.update({ where: { id }, data: { passwordHash } }); return { success: true }; } async remove(id: number, currentUserId: number) { if (id === currentUserId) { throw new BusinessException(ErrorCode.BAD_REQUEST, '不能删除当前登录账号'); } await this.ensureExists(id); await this.prisma.sysUser.delete({ where: { id } }); return { success: true }; } private async ensureExists(id: number) { const user = await this.prisma.sysUser.findUnique({ where: { id } }); if (!user) { throw new BusinessException(ErrorCode.NOT_FOUND, '用户不存在', 404); } return user; } }