import { type CreateUserInput, type DisableUserInput, ErrorCode, type ListResponse, Permission, SUPER_ADMIN_SOFT_LIMIT, ulid, type UpdateUserInput, type UserDetail, type UserListQuery, type UserSummary, } from '@lingxi/shared'; import { Inject, Injectable, Logger } from '@nestjs/common'; import { Prisma } from '@prisma/client'; import { AppException } from '../../common/errors/app-exception'; import type { PrismaService } from '../../infra/prisma/prisma.service'; import { PRISMA } from '../../infra/tokens'; import { PasswordService } from './password.service'; import { toUserDetail, toUserSummary, type UserWithRelations } from './user.mapper'; const USER_INCLUDE = { department: { include: { parent: true } }, roles: { include: { role: true } }, } satisfies Prisma.UserInclude; function hasPermission(permissions: string[], code: string): boolean { return permissions.includes(code); } /** 用户管理:列表(游标 + 筛选 + 排序)、详情、新建、更新、停用 / 启用 */ @Injectable() export class UsersService { private readonly logger = new Logger('UsersService'); constructor( @Inject(PRISMA) private readonly prisma: PrismaService, @Inject(PasswordService) private readonly passwords: PasswordService, ) {} async list(query: UserListQuery): Promise> { const where = this.buildWhere(query); const orderBy = this.buildOrderBy(query); const cursor = query.cursor; const rows = await this.prisma.user.findMany({ where, orderBy, take: query.limit + 1, include: USER_INCLUDE, ...(cursor === undefined ? {} : { cursor: { id: cursor }, skip: 1 }), }); const page = rows.slice(0, query.limit); const next = rows.length > query.limit ? (page[page.length - 1]?.id ?? null) : null; return { items: page.map((row) => toUserSummary(row)), next_cursor: next }; } async detail(id: string, permissions: string[]): Promise { const user = await this.findOrThrow(id); return toUserDetail(user, hasPermission(permissions, Permission.USER_MANAGE)); } async create( input: CreateUserInput, actorId: string, permissions: string[], ): Promise { await this.ensureDepartment(input.departmentId); await this.ensureRoles(input.roleIds); const account = input.account.trim().toLowerCase(); const email = `${account}@lingxi.cn`; await this.ensureUnique({ account, phone: input.phone }); const passwordHash = await this.passwords.hash(input.password); const id = ulid(); try { await this.prisma.$transaction([ this.prisma.user.create({ data: { id, name: input.name, account, email, phone: input.phone, passwordHash, departmentId: input.departmentId, mustChangePassword: true, createdBy: actorId, ...(input.remark === undefined ? {} : { remark: input.remark }), roles: { create: input.roleIds.map((roleId) => ({ roleId })) }, }, }), ]); } catch (error) { throw this.mapUniqueError(error); } await this.warnIfSuperAdminExceeded(input.roleIds); return this.detail(id, permissions); } async update(id: string, input: UpdateUserInput, permissions: string[]): Promise { const existing = await this.findOrThrow(id); if (input.departmentId !== undefined) { await this.ensureDepartment(input.departmentId); } if (input.roleIds !== undefined) { await this.ensureRoles(input.roleIds); } if (input.phone !== undefined && input.phone !== existing.phone) { await this.ensureUnique({ phone: input.phone }); } const data: Prisma.UserUpdateInput = { ...(input.name === undefined ? {} : { name: input.name }), ...(input.phone === undefined ? {} : { phone: input.phone }), ...(input.departmentId === undefined ? {} : { department: { connect: { id: input.departmentId } } }), ...(input.remark === undefined ? {} : { remark: input.remark }), }; try { await this.prisma.$transaction(async (tx) => { await tx.user.update({ where: { id }, data }); if (input.roleIds !== undefined) { await tx.userRole.deleteMany({ where: { userId: id } }); await tx.userRole.createMany({ data: input.roleIds.map((roleId) => ({ userId: id, roleId })), }); } }); } catch (error) { throw this.mapUniqueError(error); } if (input.roleIds !== undefined) { await this.warnIfSuperAdminExceeded(input.roleIds); } return this.detail(id, permissions); } async disable( id: string, input: DisableUserInput, actorId: string, permissions: string[], ): Promise { const existing = await this.findOrThrow(id); if (existing.status === 'DISABLED') { throw new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: '账号已是停用状态' }); } if (existing.id === actorId) { throw new AppException({ code: ErrorCode.BUSINESS_RULE_VIOLATION, message: '不能停用当前登录账号', }); } await this.prisma.$transaction([ this.prisma.user.update({ where: { id }, data: { status: 'DISABLED', disabledAt: new Date(), ...(input.reason === undefined ? {} : { remark: input.reason }), }, }), this.prisma.refreshToken.updateMany({ where: { userId: id, revokedAt: null }, data: { revokedAt: new Date() }, }), ]); return this.detail(id, permissions); } async enable(id: string, permissions: string[]): Promise { const existing = await this.findOrThrow(id); if (existing.status === 'ACTIVE') { throw new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: '账号已是启用状态' }); } await this.prisma.user.update({ where: { id }, data: { status: 'ACTIVE', disabledAt: null }, }); return this.detail(id, permissions); } /** 客户转交占位:A3 客户模块落地前按契约返回 42201(不自造 5xx 错误码) */ transferCustomers(): never { throw new AppException({ code: ErrorCode.BUSINESS_RULE_VIOLATION, message: '客户转交将在客户模块(A3)提供', }); } /** * 超管人数软上限(PRD §5.4.1 建议 ≤ 2 人):只记录告警,不阻断保存; * 前端「超管授予二次确认」是主要提示手段。A4 阈值迁 system_configs。 */ private async warnIfSuperAdminExceeded(roleIds: readonly string[]): Promise { const superAdminRole = await this.prisma.role.findUnique({ where: { code: 'super_admin' }, select: { id: true }, }); if (superAdminRole === null || !roleIds.includes(superAdminRole.id)) { return; } const count = await this.prisma.user.count({ where: { status: 'ACTIVE', roles: { some: { roleId: superAdminRole.id } } }, }); if (count > SUPER_ADMIN_SOFT_LIMIT) { this.logger.warn( `超级管理员 ${String(count)} 人已超过建议上限 ${String(SUPER_ADMIN_SOFT_LIMIT)} 人(仅提示,不阻断)`, ); } } private async findOrThrow(id: string): Promise { const user = await this.prisma.user.findUnique({ where: { id }, include: USER_INCLUDE }); if (user === null) { throw new AppException({ code: ErrorCode.NOT_FOUND, message: '用户不存在' }); } return user; } private async ensureDepartment(departmentId: string): Promise { const department = await this.prisma.department.findUnique({ where: { id: departmentId }, select: { status: true }, }); if (department === null) { throw new AppException({ code: ErrorCode.PARAM_INVALID, message: '所属部门不存在' }); } if (department.status !== 'ACTIVE') { throw new AppException({ code: ErrorCode.BUSINESS_RULE_VIOLATION, message: '所属部门已停用,请选择启用中的部门', }); } } private async ensureRoles(roleIds: string[]): Promise { const count = await this.prisma.role.count({ where: { id: { in: roleIds }, status: 'ACTIVE' }, }); if (count !== new Set(roleIds).size) { throw new AppException({ code: ErrorCode.PARAM_INVALID, message: '角色不存在或已停用' }); } } private async ensureUnique(input: { account?: string; phone?: string }): Promise { const existing = await this.prisma.user.findFirst({ where: { OR: [ ...(input.account === undefined ? [] : [{ account: input.account }]), ...(input.phone === undefined ? [] : [{ phone: input.phone }]), ], }, select: { account: true, phone: true }, }); if (existing !== null) { throw new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: existing.account === input.account ? '登录账号已存在' : '手机号已存在', }); } } private mapUniqueError(error: unknown): AppException { if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') { return new AppException({ code: ErrorCode.STATE_NOT_ALLOWED, message: '账号或手机号已存在' }); } return error instanceof AppException ? error : new AppException({ code: ErrorCode.INTERNAL_ERROR, message: '用户保存失败' }); } private buildWhere(query: UserListQuery): Prisma.UserWhereInput { const where: Prisma.UserWhereInput = {}; if (query.status !== 'all') { where.status = query.status === 'active' ? 'ACTIVE' : 'DISABLED'; } if (query.keyword !== undefined && query.keyword.length > 0) { where.OR = [ { name: { contains: query.keyword, mode: 'insensitive' } }, { account: { contains: query.keyword, mode: 'insensitive' } }, { phone: { contains: query.keyword } }, ]; } if (query.department_id !== undefined) { where.department = { OR: [{ id: query.department_id }, { parentId: query.department_id }], }; } if (query.role_id !== undefined) { where.roles = { some: { roleId: query.role_id } }; } return where; } private buildOrderBy(query: UserListQuery): Prisma.UserOrderByWithRelationInput[] { const direction: Prisma.SortOrder = query.order === 'asc' ? 'asc' : 'desc'; if (query.sort === 'created_at') { return [{ createdAt: direction }, { id: 'asc' }]; } return [{ lastLoginAt: { sort: direction, nulls: 'last' } }, { id: 'asc' }]; } }