Files
lingxi/apps/api/src/modules/identity/users.service.ts
T
Stev_Wang 6661c42e84
ci / 质量门禁 (push) Canceled after 0s
feat(identity): 补齐部门管理(两级组织树、停用启用)
背景:
- A1 只实现了部门树读取与新建 / 改名接口,没有部门管理入口,
  负责人、排序、停用状态都无法维护;
- 用户必须关联部门,部门无法维护会让 A2 的数据范围缺少组织基础。

改动:
- shared:DepartmentNode 增加 status / sortOrder / directMemberCount;
  新增 createDepartmentInput / updateDepartmentInput / departmentTreeQuery 契约;
- api:GET /departments/tree?include_disabled;POST/PATCH /departments
  (名称 / 负责人 / 排序);POST /departments/{id}/disable|enable;
  只停用不删除,有在职成员 / 启用子部门 / 下级在职成员时禁止停用;
  新建 / 编辑用户校验部门必须启用;@Audit 与 OpenAPI 同步;
- web:管理中心新增「部门管理」/system/departments,左两级组织树 +
  右详情 / 内联编辑 + 新建部门/小组 + 停用启用二次确认;显示已停用、
  ?id= 选中可恢复、无 user:manage 只读;用户页部门选择仍只取启用部门;
- 测试:shared 契约、api 单测 + int、web 树/表单/接口单测同步。

影响面:
- 新增部门写接口与页面;GET tree 默认仍只返回启用部门,对用户页无破坏;
- 权限复用 user:view / user:manage,不新增权限点;
- 无数据库迁移(status / leader_user_id / sort_order 列已存在)。

回滚方式:
- 回滚本提交即移除部门管理页与写接口,保留原只读树;数据库无需回滚。

验证证据:
- pnpm format:check / lint / typecheck 全绿;
- pnpm test:shared 121 / api 90 / web 120;test:int 4 files / 33 tests;
- pnpm openapi:diff:无破坏性变更;
- 真实 API + 浏览器(jiang.lan):新建一级部门 / 小组、改名、停用空小组、
  重名 40903、树/详情/停用确认均正常;
  截图 design/a1-ui-v1/shots/impl/70-departments.png。
2026-11-03 15:01:07 +08:00

304 lines
11 KiB
TypeScript

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<ListResponse<UserSummary>> {
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<UserDetail> {
const user = await this.findOrThrow(id);
return toUserDetail(user, hasPermission(permissions, Permission.USER_MANAGE));
}
async create(
input: CreateUserInput,
actorId: string,
permissions: string[],
): Promise<UserDetail> {
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<UserDetail> {
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<UserDetail> {
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<UserDetail> {
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<void> {
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<UserWithRelations> {
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<void> {
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<void> {
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<void> {
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' }];
}
}