feat: 增加员工端工作台后端能力

This commit is contained in:
湛兮
2026-06-02 12:23:00 +08:00
parent 667dc411fc
commit 98cea63203
33 changed files with 3021 additions and 18 deletions
@@ -0,0 +1,29 @@
import type { FastifyInstance } from "fastify";
import { ok, paginated } from "../../shared/response";
import { permissionGuard } from "../auth/auth.guard";
import { authService } from "../auth/auth.service";
import { PERMISSIONS } from "../permissions/permission.policy";
import { credentialEmployeeIdParamSchema, listCredentialAuditsQuerySchema, resetPasswordBodySchema } from "./credential.schema";
import { credentialService } from "./credential.service";
export async function credentialAdminRoutes(app: FastifyInstance): Promise<void> {
app.post("/admin/employees/:id/password/reset", { preHandler: permissionGuard(PERMISSIONS.CREDENTIAL_RESET) }, async (request) => {
const actor = await authService.getCurrentUser(request.user);
const params = credentialEmployeeIdParamSchema.parse(request.params);
const body = resetPasswordBodySchema.parse(request.body ?? {});
return ok(
await credentialService.resetEmployeePassword(params.id, actor, {
reason: body.reason,
ip: request.ip,
userAgent: request.headers["user-agent"] ?? null,
}),
);
});
app.get("/admin/credential-audits", { preHandler: permissionGuard(PERMISSIONS.CREDENTIAL_AUDIT_VIEW) }, async (request) => {
const actor = await authService.getCurrentUser(request.user);
const query = listCredentialAuditsQuerySchema.parse(request.query);
const result = await credentialService.listAudits(query, actor);
return paginated(result.items, query.page, query.pageSize, result.total);
});
}
@@ -0,0 +1,192 @@
import type { RowDataPacket } from "mysql2/promise";
import { pool } from "../../db/pool";
import type { AuthUser } from "../auth/auth.types";
import type { Employee } from "../employees/employee.types";
import type { CredentialAudit, ListCredentialAuditsQuery, ResetEmployeePasswordInput } from "./credential.types";
type SqlParam = string | number | null;
interface AuditRow extends RowDataPacket {
id: number;
actor_account_type: CredentialAudit["actorAccountType"];
actor_admin_id: number | null;
actor_employee_id: number | null;
actor_name: string | null;
target_employee_id: number;
target_employee_name: string;
target_employee_phone: string;
store_name: string | null;
action: CredentialAudit["action"];
reason: string | null;
ip: string | null;
user_agent: string | null;
created_at: Date;
}
interface CountRow extends RowDataPacket {
total: number;
}
function toIso(value: Date): string {
return value.toISOString();
}
function toAudit(row: AuditRow): CredentialAudit {
return {
id: row.id,
actorAccountType: row.actor_account_type,
actorAdminId: row.actor_admin_id,
actorEmployeeId: row.actor_employee_id,
actorName: row.actor_name,
targetEmployeeId: row.target_employee_id,
targetEmployeeName: row.target_employee_name,
targetEmployeePhone: row.target_employee_phone,
storeName: row.store_name,
action: row.action,
reason: row.reason,
ip: row.ip,
userAgent: row.user_agent,
createdAt: toIso(row.created_at),
};
}
function actorColumns(user: AuthUser): [CredentialAudit["actorAccountType"], number | null, number | null] {
return user.accountType === "SUPER_ADMIN" ? ["SUPER_ADMIN", user.id, null] : ["EMPLOYEE", null, user.id];
}
export const credentialRepository = {
async updatePasswordForReset(employeeId: number, passwordHash: string, actor: AuthUser): Promise<void> {
const [, adminId, actorEmployeeId] = actorColumns(actor);
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
await connection.execute(
"UPDATE employees SET password_hash = ? WHERE id = ? AND deleted_at IS NULL",
[passwordHash, employeeId],
);
await connection.execute(
`
INSERT INTO employee_password_states
(employee_id, must_change_password, last_reset_at, last_reset_by_admin_id, last_reset_by_employee_id)
VALUES (?, 1, CURRENT_TIMESTAMP(3), ?, ?)
ON DUPLICATE KEY UPDATE
must_change_password = 1,
last_reset_at = CURRENT_TIMESTAMP(3),
last_reset_by_admin_id = VALUES(last_reset_by_admin_id),
last_reset_by_employee_id = VALUES(last_reset_by_employee_id)
`,
[employeeId, adminId, actorEmployeeId],
);
await connection.commit();
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
},
async markOwnPasswordChanged(employeeId: number): Promise<void> {
await pool.execute(
`
INSERT INTO employee_password_states (employee_id, must_change_password)
VALUES (?, 0)
ON DUPLICATE KEY UPDATE must_change_password = 0
`,
[employeeId],
);
},
async recordAudit(
actor: AuthUser,
target: Employee,
action: CredentialAudit["action"],
input: ResetEmployeePasswordInput,
): Promise<void> {
const [actorAccountType, actorAdminId, actorEmployeeId] = actorColumns(actor);
await pool.execute(
`
INSERT INTO credential_audits
(actor_account_type, actor_admin_id, actor_employee_id, target_employee_id, action, reason, ip, user_agent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`,
[
actorAccountType,
actorAdminId,
actorEmployeeId,
target.id,
action,
input.reason ?? null,
input.ip ?? null,
input.userAgent ?? null,
],
);
},
async listAudits(query: ListCredentialAuditsQuery): Promise<{ items: CredentialAudit[]; total: number }> {
const where: string[] = [];
const params: SqlParam[] = [];
if (query.operatorId !== undefined) {
where.push("(ca.actor_admin_id = ? OR ca.actor_employee_id = ?)");
params.push(query.operatorId, query.operatorId);
}
if (query.targetEmployeeId !== undefined) {
where.push("ca.target_employee_id = ?");
params.push(query.targetEmployeeId);
}
if (query.storeId !== undefined) {
where.push("te.store_id = ?");
params.push(query.storeId);
}
if (query.startDate) {
where.push("ca.created_at >= ?");
params.push(`${query.startDate} 00:00:00.000`);
}
if (query.endDate) {
where.push("ca.created_at < DATE_ADD(?, INTERVAL 1 DAY)");
params.push(`${query.endDate} 00:00:00.000`);
}
const whereSql = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
const offset = (query.page - 1) * query.pageSize;
const [countRows] = await pool.execute<CountRow[]>(
`
SELECT COUNT(*) AS total
FROM credential_audits ca
INNER JOIN employees te ON te.id = ca.target_employee_id
${whereSql}
`,
params,
);
const [rows] = await pool.execute<AuditRow[]>(
`
SELECT
ca.*,
COALESCE(sa.display_name, ae.name) AS actor_name,
te.name AS target_employee_name,
te.phone AS target_employee_phone,
s.name AS store_name
FROM credential_audits ca
LEFT JOIN super_admins sa ON sa.id = ca.actor_admin_id
LEFT JOIN employees ae ON ae.id = ca.actor_employee_id
INNER JOIN employees te ON te.id = ca.target_employee_id
LEFT JOIN stores s ON s.id = te.store_id
${whereSql}
ORDER BY ca.id DESC
LIMIT ${query.pageSize} OFFSET ${offset}
`,
params,
);
return {
items: rows.map(toAudit),
total: countRows[0]?.total ?? 0,
};
},
};
@@ -0,0 +1,23 @@
import { z } from "zod";
const emptyStringToUndefined = (value: unknown) =>
typeof value === "string" && value.trim() === "" ? undefined : value;
const dateSchema = z.string().trim().regex(/^\d{4}-\d{2}-\d{2}$/, "日期格式应为 YYYY-MM-DD");
export const credentialEmployeeIdParamSchema = z.object({
id: z.coerce.number().int().positive(),
});
export const resetPasswordBodySchema = z.object({
reason: z.string().trim().max(500).nullable().optional(),
});
export const listCredentialAuditsQuerySchema = z.object({
operatorId: z.preprocess(emptyStringToUndefined, z.coerce.number().int().positive().optional()),
targetEmployeeId: z.preprocess(emptyStringToUndefined, z.coerce.number().int().positive().optional()),
storeId: z.preprocess(emptyStringToUndefined, z.coerce.number().int().positive().optional()),
startDate: z.preprocess(emptyStringToUndefined, dateSchema.optional()),
endDate: z.preprocess(emptyStringToUndefined, dateSchema.optional()),
page: z.coerce.number().int().min(1).default(1),
pageSize: z.coerce.number().int().min(1).max(100).default(20),
});
@@ -0,0 +1,86 @@
import { randomBytes } from "node:crypto";
import { badRequest, forbidden } from "../../shared/http-error";
import type { AuthUser } from "../auth/auth.types";
import { hashPassword } from "../auth/password";
import { employeeService } from "../employees/employee.service";
import type { Employee } from "../employees/employee.types";
import { hasAnyPermission, hasPermission, PERMISSIONS } from "../permissions/permission.policy";
import { credentialRepository } from "./credential.repository";
import type { ListCredentialAuditsQuery, ResetEmployeePasswordInput } from "./credential.types";
function generateTemporaryPassword(): string {
return `Tmp-${randomBytes(9).toString("base64url")}9`;
}
function assertCanReset(actor: AuthUser, target: Employee): void {
if (!hasPermission(actor.permissions, PERMISSIONS.CREDENTIAL_RESET)) {
throw forbidden("当前账号没有重置密码权限");
}
if (actor.accountType === "EMPLOYEE" && actor.id === target.id) {
throw badRequest("本人改密请使用修改本人密码接口");
}
if (hasPermission(actor.permissions, PERMISSIONS.EMPLOYEE_VIEW_ALL)) {
return;
}
if (
hasPermission(actor.permissions, PERMISSIONS.EMPLOYEE_VIEW_STORE) &&
actor.storeId === target.storeId
) {
return;
}
throw forbidden("当前账号无权重置该员工密码");
}
function assertCanViewAudit(actor: AuthUser): void {
if (!hasPermission(actor.permissions, PERMISSIONS.CREDENTIAL_AUDIT_VIEW)) {
throw forbidden("当前账号没有查看凭据审计权限");
}
if (
!hasAnyPermission(actor.permissions, [
PERMISSIONS.EMPLOYEE_VIEW_ALL,
PERMISSIONS.EMPLOYEE_VIEW_STORE,
])
) {
throw forbidden("当前账号缺少员工数据范围权限");
}
}
export const credentialService = {
async resetEmployeePassword(employeeId: number, actor: AuthUser, input: ResetEmployeePasswordInput) {
const target = await employeeService.getById(employeeId);
assertCanReset(actor, target);
const temporaryPassword = generateTemporaryPassword();
const passwordHash = await hashPassword(temporaryPassword);
await credentialRepository.updatePasswordForReset(employeeId, passwordHash, actor);
await credentialRepository.recordAudit(actor, target, "RESET_PASSWORD", input);
return {
employee: await employeeService.getById(employeeId),
temporaryPassword,
mustChangePassword: true,
};
},
async recordOwnPasswordChanged(employeeId: number, actor: AuthUser, input: ResetEmployeePasswordInput) {
const target = await employeeService.getById(employeeId);
await credentialRepository.markOwnPasswordChanged(employeeId);
await credentialRepository.recordAudit(actor, target, "CHANGE_OWN_PASSWORD", input);
},
listAudits(query: ListCredentialAuditsQuery, actor: AuthUser) {
assertCanViewAudit(actor);
const scopedQuery =
hasPermission(actor.permissions, PERMISSIONS.EMPLOYEE_VIEW_STORE) &&
!hasPermission(actor.permissions, PERMISSIONS.EMPLOYEE_VIEW_ALL)
? { ...query, storeId: actor.storeId }
: query;
return credentialRepository.listAudits(scopedQuery);
},
};
@@ -0,0 +1,32 @@
export interface CredentialAudit {
id: number;
actorAccountType: "SUPER_ADMIN" | "EMPLOYEE";
actorAdminId: number | null;
actorEmployeeId: number | null;
actorName: string | null;
targetEmployeeId: number;
targetEmployeeName: string;
targetEmployeePhone: string;
storeName: string | null;
action: "RESET_PASSWORD" | "CHANGE_OWN_PASSWORD";
reason: string | null;
ip: string | null;
userAgent: string | null;
createdAt: string;
}
export interface ListCredentialAuditsQuery {
operatorId?: number;
targetEmployeeId?: number;
storeId?: number;
startDate?: string;
endDate?: string;
page: number;
pageSize: number;
}
export interface ResetEmployeePasswordInput {
reason?: string | null;
ip?: string | null;
userAgent?: string | null;
}