feat(server): 完成 P0+P1 后端能力(工作流、RBAC、付款归档)
P0 MVP: - 认证:login/refresh/logout/forgot/reset + tokenVersion - RBAC:角色到权限映射 + requirePermission - 发票池:upload/bind/signed-url + 判重(VALID_003/VALID_005) - 报销:create/view/submit + 单号生成 - 工作流:approve + department_manager 解析 P1 扩展: - 动作:reject/return/withdraw(含 comment) - transfer:任务转审 + 链路上限 3 - pay:approved -> paid + 发票归档 used_complete - 动态审批链:approval_rules 驱动 回归脚本: - smoke-test.sh / regression-dedup.sh / regression-workflow-actions.sh
这个提交包含在:
@@ -0,0 +1,528 @@
|
||||
const { z } = require("zod");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
const { hashPassword, randomRefreshToken, sha256Hex, verifyPassword } = require("../utils/crypto");
|
||||
const { validatePassword } = require("../utils/passwordPolicy");
|
||||
const { sendData } = require("../utils/reply");
|
||||
|
||||
function getHeaderString(request, name) {
|
||||
const value = request.headers[name];
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function getRequestOrigin(request) {
|
||||
const origin = getHeaderString(request, "origin");
|
||||
if (origin) return origin;
|
||||
|
||||
const referer = getHeaderString(request, "referer");
|
||||
if (!referer) return null;
|
||||
try {
|
||||
return new URL(referer).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function refreshCookieOptions(config) {
|
||||
return {
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure: config.cookieSecure,
|
||||
path: "/api/auth",
|
||||
maxAge: config.refreshTtlSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
async function authRoutes(fastify) {
|
||||
const loginBodySchema = z.object({
|
||||
identifier: z.string().min(3),
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
fastify.post("/login", async (request, reply) => {
|
||||
const parsed = loginBodySchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const deviceFingerprint = getHeaderString(request, "x-device-fingerprint");
|
||||
if (!deviceFingerprint) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { "x-device-fingerprint": "missing" },
|
||||
});
|
||||
}
|
||||
|
||||
const { identifier, password } = parsed.data;
|
||||
const employee = await fastify.prisma.employee.findFirst({
|
||||
where: { OR: [{ phone: identifier }, { email: identifier }] },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
password_hash: true,
|
||||
token_version: true,
|
||||
},
|
||||
});
|
||||
if (!employee) {
|
||||
throw new AppError({
|
||||
code: "AUTH_001",
|
||||
message: "用户名或密码错误",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
if (employee.status !== "active") {
|
||||
throw new AppError({
|
||||
code: "AUTH_003",
|
||||
message: "账号已离职/禁用",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const ok = await verifyPassword(password, employee.password_hash);
|
||||
if (!ok) {
|
||||
throw new AppError({
|
||||
code: "AUTH_001",
|
||||
message: "用户名或密码错误",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const refreshToken = randomRefreshToken();
|
||||
const refreshTokenHash = sha256Hex(refreshToken);
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + fastify.config.refreshTtlSeconds * 1000);
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const activeSessions = await tx.authSession.findMany({
|
||||
where: {
|
||||
employee_id: employee.id,
|
||||
revoked_at: null,
|
||||
expires_at: { gt: now },
|
||||
},
|
||||
orderBy: { created_at: "asc" },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const maxSessions = 5;
|
||||
const allowedExisting = maxSessions - 1;
|
||||
if (activeSessions.length > allowedExisting) {
|
||||
const revokeCount = activeSessions.length - allowedExisting;
|
||||
const idsToRevoke = activeSessions.slice(0, revokeCount).map((s) => s.id);
|
||||
await tx.authSession.updateMany({
|
||||
where: { id: { in: idsToRevoke } },
|
||||
data: { revoked_at: now },
|
||||
});
|
||||
}
|
||||
|
||||
await tx.authSession.create({
|
||||
data: {
|
||||
employee_id: employee.id,
|
||||
refresh_token_hash: refreshTokenHash,
|
||||
device_fingerprint: deviceFingerprint,
|
||||
ip_address: request.ip,
|
||||
user_agent: getHeaderString(request, "user-agent") ?? "",
|
||||
expires_at: expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: employee.id,
|
||||
action: "AUTH_LOGIN_SUCCESS",
|
||||
targetType: "employee",
|
||||
targetId: employee.id,
|
||||
extra: {},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
reply.setCookie(
|
||||
fastify.config.refreshCookieName,
|
||||
refreshToken,
|
||||
refreshCookieOptions(fastify.config),
|
||||
);
|
||||
|
||||
const accessToken = fastify.issueAccessToken(employee);
|
||||
return sendData(reply, request, { accessToken });
|
||||
});
|
||||
|
||||
fastify.post("/refresh", async (request, reply) => {
|
||||
const refreshToken = request.cookies?.[fastify.config.refreshCookieName];
|
||||
if (typeof refreshToken !== "string" || !refreshToken) {
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const deviceFingerprint = getHeaderString(request, "x-device-fingerprint");
|
||||
if (!deviceFingerprint) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { "x-device-fingerprint": "missing" },
|
||||
});
|
||||
}
|
||||
|
||||
const refreshTokenHash = sha256Hex(refreshToken);
|
||||
const now = new Date();
|
||||
|
||||
const session = await fastify.prisma.authSession.findFirst({
|
||||
where: { refresh_token_hash: refreshTokenHash },
|
||||
select: {
|
||||
id: true,
|
||||
employee_id: true,
|
||||
device_fingerprint: true,
|
||||
expires_at: true,
|
||||
revoked_at: true,
|
||||
},
|
||||
});
|
||||
if (!session) {
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
if (session.device_fingerprint !== deviceFingerprint) {
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const expectedOrigin = fastify.config.appOrigin;
|
||||
const requestOrigin = getRequestOrigin(request);
|
||||
if (expectedOrigin && requestOrigin && requestOrigin !== expectedOrigin) {
|
||||
await fastify.prisma.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: session.employee_id,
|
||||
action: "AUTH_REFRESH_ORIGIN_MISMATCH",
|
||||
targetType: "employee",
|
||||
targetId: session.employee_id,
|
||||
extra: { expectedOrigin, requestOrigin },
|
||||
}),
|
||||
});
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
if (session.expires_at <= now) {
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
if (session.revoked_at) {
|
||||
const rotatedReplacement = await fastify.prisma.authSession.findFirst({
|
||||
where: {
|
||||
employee_id: session.employee_id,
|
||||
device_fingerprint: session.device_fingerprint,
|
||||
revoked_at: null,
|
||||
expires_at: { gt: now },
|
||||
created_at: { gt: session.revoked_at },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (rotatedReplacement) {
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
await tx.authSession.updateMany({
|
||||
where: { employee_id: session.employee_id, revoked_at: null },
|
||||
data: { revoked_at: now },
|
||||
});
|
||||
|
||||
await tx.employee.update({
|
||||
where: { id: session.employee_id },
|
||||
data: { token_version: { increment: 1 } },
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: session.employee_id,
|
||||
action: "REFRESH_REUSE_DETECTED",
|
||||
targetType: "employee",
|
||||
targetId: session.employee_id,
|
||||
extra: {},
|
||||
}),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
reply.clearCookie(fastify.config.refreshCookieName, refreshCookieOptions(fastify.config));
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const employee = await fastify.prisma.employee.findUnique({
|
||||
where: { id: session.employee_id },
|
||||
select: { id: true, status: true, token_version: true },
|
||||
});
|
||||
if (!employee || employee.status !== "active") {
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
const newRefreshToken = randomRefreshToken();
|
||||
const newRefreshTokenHash = sha256Hex(newRefreshToken);
|
||||
const newExpiresAt = new Date(now.getTime() + fastify.config.refreshTtlSeconds * 1000);
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const updated = await tx.authSession.updateMany({
|
||||
where: {
|
||||
id: session.id,
|
||||
revoked_at: null,
|
||||
expires_at: { gt: now },
|
||||
},
|
||||
data: { revoked_at: now, last_seen_at: now },
|
||||
});
|
||||
if (updated.count !== 1) {
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: employee.id,
|
||||
action: "REFRESH_REUSE_DETECTED",
|
||||
targetType: "employee",
|
||||
targetId: employee.id,
|
||||
extra: {},
|
||||
}),
|
||||
});
|
||||
|
||||
throw new AppError({
|
||||
code: "AUTH_005",
|
||||
message: "Refresh Token 无效/已撤销",
|
||||
statusCode: 401,
|
||||
});
|
||||
}
|
||||
|
||||
await tx.authSession.create({
|
||||
data: {
|
||||
employee_id: employee.id,
|
||||
refresh_token_hash: newRefreshTokenHash,
|
||||
device_fingerprint: deviceFingerprint,
|
||||
ip_address: request.ip,
|
||||
user_agent: getHeaderString(request, "user-agent") ?? "",
|
||||
expires_at: newExpiresAt,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
reply.setCookie(
|
||||
fastify.config.refreshCookieName,
|
||||
newRefreshToken,
|
||||
refreshCookieOptions(fastify.config),
|
||||
);
|
||||
|
||||
const accessToken = fastify.issueAccessToken(employee);
|
||||
return sendData(reply, request, { accessToken });
|
||||
});
|
||||
|
||||
fastify.post("/logout", async (request, reply) => {
|
||||
const refreshToken = request.cookies?.[fastify.config.refreshCookieName];
|
||||
if (typeof refreshToken === "string" && refreshToken) {
|
||||
const refreshTokenHash = sha256Hex(refreshToken);
|
||||
const now = new Date();
|
||||
|
||||
const session = await fastify.prisma.authSession.findFirst({
|
||||
where: { refresh_token_hash: refreshTokenHash },
|
||||
select: { id: true, employee_id: true, revoked_at: true },
|
||||
});
|
||||
|
||||
await fastify.prisma.authSession.updateMany({
|
||||
where: { refresh_token_hash: refreshTokenHash, revoked_at: null },
|
||||
data: { revoked_at: now, last_seen_at: now },
|
||||
});
|
||||
|
||||
if (session?.employee_id) {
|
||||
await fastify.prisma.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: session.employee_id,
|
||||
action: "AUTH_LOGOUT",
|
||||
targetType: "employee",
|
||||
targetId: session.employee_id,
|
||||
extra: {},
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
reply.clearCookie(fastify.config.refreshCookieName, refreshCookieOptions(fastify.config));
|
||||
return sendData(reply, request, {});
|
||||
});
|
||||
|
||||
const forgotPasswordBodySchema = z.object({
|
||||
email: z.string().email(),
|
||||
});
|
||||
|
||||
fastify.post("/forgot-password", async (request, reply) => {
|
||||
const parsed = forgotPasswordBodySchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const { email } = parsed.data;
|
||||
const employee = await fastify.prisma.employee.findFirst({
|
||||
where: { email },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
|
||||
if (!employee || employee.status !== "active") {
|
||||
return sendData(reply, request, {});
|
||||
}
|
||||
|
||||
const code = String(Math.floor(Math.random() * 1_000_000)).padStart(6, "0");
|
||||
const codeHash = sha256Hex(code);
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + fastify.config.passwordResetCodeTtlSeconds * 1000);
|
||||
|
||||
await fastify.prisma.passwordResetCode.create({
|
||||
data: {
|
||||
employee_id: employee.id,
|
||||
code_hash: codeHash,
|
||||
expires_at: expiresAt,
|
||||
created_ip: request.ip,
|
||||
created_user_agent: getHeaderString(request, "user-agent"),
|
||||
},
|
||||
});
|
||||
|
||||
await fastify.prisma.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: employee.id,
|
||||
action: "AUTH_PASSWORD_RESET_REQUESTED",
|
||||
targetType: "employee",
|
||||
targetId: employee.id,
|
||||
extra: {},
|
||||
}),
|
||||
});
|
||||
|
||||
if (fastify.config.devShowPasswordResetCode) {
|
||||
fastify.log.info(
|
||||
{ employeeId: employee.id, email, code, requestId: request.id },
|
||||
"DEV password reset code",
|
||||
);
|
||||
}
|
||||
|
||||
return sendData(reply, request, {});
|
||||
});
|
||||
|
||||
const resetPasswordBodySchema = z.object({
|
||||
email: z.string().email(),
|
||||
code: z.string().length(6),
|
||||
newPassword: z.string().min(12),
|
||||
});
|
||||
|
||||
fastify.post("/reset-password", async (request, reply) => {
|
||||
const parsed = resetPasswordBodySchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const { email, code, newPassword } = parsed.data;
|
||||
|
||||
const policyErrors = validatePassword(newPassword);
|
||||
if (policyErrors.length) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { password: policyErrors },
|
||||
});
|
||||
}
|
||||
|
||||
const employee = await fastify.prisma.employee.findFirst({
|
||||
where: { email },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
if (!employee || employee.status !== "active") {
|
||||
return sendData(reply, request, {});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const codeHash = sha256Hex(code);
|
||||
const resetCode = await fastify.prisma.passwordResetCode.findFirst({
|
||||
where: {
|
||||
employee_id: employee.id,
|
||||
code_hash: codeHash,
|
||||
used_at: null,
|
||||
expires_at: { gt: now },
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!resetCode) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { code: "invalid_or_expired" },
|
||||
});
|
||||
}
|
||||
|
||||
const newPasswordHash = await hashPassword(newPassword);
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
await tx.passwordResetCode.update({
|
||||
where: { id: resetCode.id },
|
||||
data: { used_at: now },
|
||||
});
|
||||
|
||||
await tx.employee.update({
|
||||
where: { id: employee.id },
|
||||
data: {
|
||||
password_hash: newPasswordHash,
|
||||
token_version: { increment: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
await tx.authSession.updateMany({
|
||||
where: { employee_id: employee.id, revoked_at: null },
|
||||
data: { revoked_at: now },
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: employee.id,
|
||||
action: "AUTH_PASSWORD_RESET_SUCCEEDED",
|
||||
targetType: "employee",
|
||||
targetId: employee.id,
|
||||
extra: {},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
reply.clearCookie(fastify.config.refreshCookieName, refreshCookieOptions(fastify.config));
|
||||
return sendData(reply, request, {});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = authRoutes;
|
||||
@@ -0,0 +1,645 @@
|
||||
const crypto = require("node:crypto");
|
||||
const fs = require("node:fs/promises");
|
||||
const fsSync = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const { z } = require("zod");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { compactDateString } = require("../utils/date");
|
||||
const { sha256Hex } = require("../utils/crypto");
|
||||
const { signPayload, verifyToken } = require("../utils/signedUrl");
|
||||
const { toMoneyString } = require("../utils/workflow");
|
||||
|
||||
const MIME_ALLOWLIST = new Set([
|
||||
"application/pdf",
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
]);
|
||||
const OCR_TYPE_ALLOWLIST = new Set(["vat", "train", "flight", "taxi", "general"]);
|
||||
|
||||
const bindBodySchema = z.object({
|
||||
reimbursementId: z.string().uuid(),
|
||||
linkedItemId: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
const DEDUP_CONSTRAINT_NAMES = new Set([
|
||||
"invoice_pool_file_sha256_dedup_ux",
|
||||
"invoice_pool_invoice_code_number_dedup_ux",
|
||||
]);
|
||||
|
||||
const DEDUP_FIELD_NAMES = new Set(["file_sha256", "invoice_code", "invoice_number"]);
|
||||
|
||||
function tokenizeMetaString(value) {
|
||||
if (typeof value !== "string") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const splitTokens = normalized
|
||||
.split(/[^a-z0-9_]+/i)
|
||||
.map((item) => item.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
|
||||
return [normalized, ...splitTokens];
|
||||
}
|
||||
|
||||
function normalizeConstraintMeta(value) {
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.flatMap((item) => tokenizeMetaString(String(item)))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
return tokenizeMetaString(value);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function collectFieldTokens(meta) {
|
||||
return new Set(
|
||||
[
|
||||
...normalizeConstraintMeta(meta.target),
|
||||
...normalizeConstraintMeta(meta?.driverAdapterError?.cause?.constraint?.fields),
|
||||
].filter((token) => DEDUP_FIELD_NAMES.has(token)),
|
||||
);
|
||||
}
|
||||
|
||||
function containsDedupConstraintName(metaTokens) {
|
||||
const constraints = Array.from(DEDUP_CONSTRAINT_NAMES);
|
||||
return metaTokens.some((token) => constraints.some((constraint) => token.includes(constraint)));
|
||||
}
|
||||
|
||||
function isFieldBasedDedup(fieldTokens) {
|
||||
if (fieldTokens.size === 1 && fieldTokens.has("file_sha256")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
fieldTokens.size === 2 &&
|
||||
fieldTokens.has("invoice_code") &&
|
||||
fieldTokens.has("invoice_number")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function isInvoiceDedupConflict(error) {
|
||||
if (!error || error.code !== "P2002") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const meta = error.meta ?? {};
|
||||
const metaTokens = [
|
||||
...normalizeConstraintMeta(meta.constraint),
|
||||
...normalizeConstraintMeta(meta.target),
|
||||
...normalizeConstraintMeta(meta?.driverAdapterError?.cause?.originalMessage),
|
||||
];
|
||||
|
||||
if (containsDedupConstraintName(metaTokens)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const fieldTokens = collectFieldTokens(meta);
|
||||
return isFieldBasedDedup(fieldTokens);
|
||||
}
|
||||
|
||||
function ensureInvoiceReadableByUser(request, invoice) {
|
||||
const roleCodes = request.employee.roleCodes;
|
||||
if (
|
||||
roleCodes.includes("admin") ||
|
||||
roleCodes.includes("finance") ||
|
||||
roleCodes.includes("finance_mgr")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
invoice.owner_employee_id === request.employee.id ||
|
||||
invoice.uploaded_by_employee_id === request.employee.id
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (invoice.linked_reimbursement) {
|
||||
const reimbursement = invoice.linked_reimbursement;
|
||||
if (
|
||||
reimbursement.owner_id === request.employee.id ||
|
||||
reimbursement.submitter_id === request.employee.id
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function sanitizeFilename(fileName) {
|
||||
if (!fileName) return "file";
|
||||
return fileName.replace(/[\r\n"]/g, "_");
|
||||
}
|
||||
|
||||
async function invoicePoolRoutes(fastify) {
|
||||
fastify.post(
|
||||
"/invoice-pool/upload",
|
||||
{
|
||||
preHandler: fastify.requirePermission("invoice.upload"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
let filePart = null;
|
||||
const fields = {};
|
||||
|
||||
try {
|
||||
for await (const part of request.parts()) {
|
||||
if (part.type === "file") {
|
||||
if (filePart) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { file: "only_single_file_supported" },
|
||||
});
|
||||
}
|
||||
filePart = part;
|
||||
} else {
|
||||
fields[part.fieldname] = part.value;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.code === "FST_REQ_FILE_TOO_LARGE") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { file: "file_too_large" },
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!filePart) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { file: "missing" },
|
||||
});
|
||||
}
|
||||
|
||||
if (!MIME_ALLOWLIST.has(filePart.mimetype)) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { file: "unsupported_mime_type" },
|
||||
});
|
||||
}
|
||||
|
||||
const ownerEmployeeId = fields.owner_employee_id ?? request.employee.id;
|
||||
if (ownerEmployeeId !== request.employee.id) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
details: { owner_employee_id: "cross_owner_upload_not_allowed_in_mvp" },
|
||||
});
|
||||
}
|
||||
|
||||
const ocrType = fields.ocr_type ?? "general";
|
||||
if (!OCR_TYPE_ALLOWLIST.has(ocrType)) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { ocr_type: "invalid" },
|
||||
});
|
||||
}
|
||||
|
||||
const chunks = [];
|
||||
let fileSize = 0;
|
||||
for await (const chunk of filePart.file) {
|
||||
fileSize += chunk.length;
|
||||
if (fileSize > fastify.config.maxUploadSizeBytes) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { file: "file_too_large" },
|
||||
});
|
||||
}
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
if (fileSize === 0) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { file: "empty_file" },
|
||||
});
|
||||
}
|
||||
|
||||
const fileBuffer = Buffer.concat(chunks);
|
||||
const fileSha256 = sha256Hex(fileBuffer);
|
||||
const datePrefix = compactDateString(fastify.config.appTimezone);
|
||||
const extension = path.extname(filePart.filename ?? "").toLowerCase();
|
||||
const storagePath = path.join(datePrefix, `${crypto.randomUUID()}${extension}`);
|
||||
const absoluteStoragePath = path.resolve(fastify.config.storageDir, storagePath);
|
||||
|
||||
await fs.mkdir(path.dirname(absoluteStoragePath), { recursive: true });
|
||||
await fs.writeFile(absoluteStoragePath, fileBuffer);
|
||||
|
||||
const invoice = await fastify.prisma.invoicePool.create({
|
||||
data: {
|
||||
owner_employee_id: ownerEmployeeId,
|
||||
uploaded_by_employee_id: request.employee.id,
|
||||
storage_path: storagePath,
|
||||
original_name: filePart.filename ?? "upload",
|
||||
mime_type: filePart.mimetype,
|
||||
file_size: fileSize,
|
||||
file_sha256: fileSha256,
|
||||
ocr_type: ocrType,
|
||||
status: "available",
|
||||
created_by: request.employee.id,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
file_sha256: true,
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
invoicePoolId: invoice.id,
|
||||
status: invoice.status,
|
||||
fileSha256: invoice.file_sha256,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/invoice-pool/:id/signed-url",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
|
||||
if (!parsedInvoiceId.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { id: "invalid_uuid" },
|
||||
});
|
||||
}
|
||||
|
||||
const invoice = await fastify.prisma.invoicePool.findUnique({
|
||||
where: { id: parsedInvoiceId.data },
|
||||
select: {
|
||||
id: true,
|
||||
owner_employee_id: true,
|
||||
uploaded_by_employee_id: true,
|
||||
linked_reimbursement_id: true,
|
||||
linked_reimbursement: {
|
||||
select: {
|
||||
owner_id: true,
|
||||
submitter_id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!invoice) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
let canAccess = ensureInvoiceReadableByUser(request, invoice);
|
||||
|
||||
if (!canAccess && invoice.linked_reimbursement_id) {
|
||||
const pendingTask = await fastify.prisma.workflowTask.findFirst({
|
||||
where: {
|
||||
status: "pending",
|
||||
workflow_instance: {
|
||||
entity_type: "reimbursement",
|
||||
entity_id: invoice.linked_reimbursement_id,
|
||||
current_status: "pending",
|
||||
},
|
||||
OR: [
|
||||
{ assignee_id: request.employee.id },
|
||||
{ assignee_role: { in: request.employee.roleCodes } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
canAccess = Boolean(pendingTask);
|
||||
}
|
||||
|
||||
if (!canAccess) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const expiresAt = Date.now() + fastify.config.signedUrlTtlSeconds * 1000;
|
||||
const token = signPayload(
|
||||
{
|
||||
invoiceId: invoice.id,
|
||||
exp: expiresAt,
|
||||
},
|
||||
fastify.config.jwtSecret,
|
||||
);
|
||||
|
||||
const origin =
|
||||
fastify.config.appOrigin ||
|
||||
`${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
|
||||
const signedUrl = `${origin}/api/invoice-pool/${invoice.id}/file?token=${encodeURIComponent(token)}`;
|
||||
|
||||
return sendData(reply, request, {
|
||||
signedUrl,
|
||||
expiresAt: new Date(expiresAt).toISOString(),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get("/invoice-pool/:id/file", async (request, reply) => {
|
||||
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
|
||||
const token = request.query?.token;
|
||||
if (!parsedInvoiceId.success || typeof token !== "string") {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const verified = verifyToken(token, fastify.config.jwtSecret);
|
||||
if (!verified.ok) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const payload = verified.payload;
|
||||
if (
|
||||
payload?.invoiceId !== parsedInvoiceId.data ||
|
||||
typeof payload?.exp !== "number" ||
|
||||
payload.exp <= Date.now()
|
||||
) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const invoice = await fastify.prisma.invoicePool.findUnique({
|
||||
where: { id: parsedInvoiceId.data },
|
||||
select: {
|
||||
storage_path: true,
|
||||
mime_type: true,
|
||||
original_name: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!invoice) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const storageRoot = path.resolve(fastify.config.storageDir);
|
||||
const absolutePath = path.resolve(storageRoot, invoice.storage_path);
|
||||
if (!absolutePath.startsWith(`${storageRoot}${path.sep}`)) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.access(absolutePath);
|
||||
} catch {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
reply.type(invoice.mime_type || "application/octet-stream");
|
||||
reply.header(
|
||||
"content-disposition",
|
||||
`inline; filename=\"${sanitizeFilename(invoice.original_name)}\"`,
|
||||
);
|
||||
return reply.send(fsSync.createReadStream(absolutePath));
|
||||
});
|
||||
|
||||
fastify.post(
|
||||
"/invoice-pool/:id/bind",
|
||||
{
|
||||
preHandler: fastify.requirePermission("invoice.upload"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
|
||||
if (!parsedInvoiceId.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { id: "invalid_uuid" },
|
||||
});
|
||||
}
|
||||
|
||||
const parsedBody = bindBodySchema.safeParse(request.body ?? {});
|
||||
if (!parsedBody.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsedBody.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const invoiceId = parsedInvoiceId.data;
|
||||
const { reimbursementId, linkedItemId } = parsedBody.data;
|
||||
|
||||
try {
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const reimbursementRows = await tx.$queryRaw`
|
||||
SELECT id, owner_id, submitter_id, status
|
||||
FROM "reimbursement_forms"
|
||||
WHERE id = ${reimbursementId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
if (!Array.isArray(reimbursementRows) || reimbursementRows.length === 0) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const reimbursement = reimbursementRows[0];
|
||||
const isOwn =
|
||||
reimbursement.owner_id === request.employee.id ||
|
||||
reimbursement.submitter_id === request.employee.id;
|
||||
const canViewAll = fastify.hasPermission(request.employee, "expense.view_all");
|
||||
if (!isOwn && !canViewAll) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
if (![
|
||||
"draft",
|
||||
"rejected",
|
||||
].includes(reimbursement.status)) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { reimbursement: "invalid_status_for_bind" },
|
||||
});
|
||||
}
|
||||
|
||||
if (linkedItemId) {
|
||||
const linkedItem = await tx.reimbursementItem.findFirst({
|
||||
where: {
|
||||
id: linkedItemId,
|
||||
reimbursement_id: reimbursementId,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!linkedItem) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { linkedItemId: "item_not_in_reimbursement" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const invoiceRows = await tx.$queryRaw`
|
||||
SELECT id
|
||||
FROM "invoice_pool"
|
||||
WHERE id = ${invoiceId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
if (!Array.isArray(invoiceRows) || invoiceRows.length === 0) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const invoice = await tx.invoicePool.findUnique({
|
||||
where: { id: invoiceId },
|
||||
select: {
|
||||
status: true,
|
||||
linked_reimbursement_id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!invoice) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
if (invoice.status === "bound" || invoice.linked_reimbursement_id) {
|
||||
throw new AppError({
|
||||
code: "VALID_005",
|
||||
message: "发票已被其他报销单占用/绑定",
|
||||
statusCode: 409,
|
||||
});
|
||||
}
|
||||
|
||||
if (invoice.status !== "available") {
|
||||
throw new AppError({
|
||||
code: "VALID_005",
|
||||
message: "发票已被其他报销单占用/绑定",
|
||||
statusCode: 409,
|
||||
details: { status: invoice.status },
|
||||
});
|
||||
}
|
||||
|
||||
await tx.invoicePool.update({
|
||||
where: { id: invoiceId },
|
||||
data: {
|
||||
status: "bound",
|
||||
linked_reimbursement_id: reimbursementId,
|
||||
linked_item_id: linkedItemId ?? null,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (isInvoiceDedupConflict(error)) {
|
||||
throw new AppError({
|
||||
code: "VALID_003",
|
||||
message: "发票判重命中",
|
||||
statusCode: 409,
|
||||
});
|
||||
}
|
||||
|
||||
if (error?.code === "P2002") {
|
||||
fastify.log.warn(
|
||||
{ meta: error?.meta ?? {} },
|
||||
"Unexpected P2002 not from invoice dedup constraints",
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
const invoice = await fastify.prisma.invoicePool.findUnique({
|
||||
where: { id: invoiceId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
linked_reimbursement_id: true,
|
||||
linked_item_id: true,
|
||||
total_amount: true,
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
id: invoice.id,
|
||||
status: invoice.status,
|
||||
linkedReimbursementId: invoice.linked_reimbursement_id,
|
||||
linkedItemId: invoice.linked_item_id,
|
||||
totalAmount: toMoneyString(invoice.total_amount),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = invoicePoolRoutes;
|
||||
@@ -0,0 +1,42 @@
|
||||
const { sendData } = require("../utils/reply");
|
||||
|
||||
async function meRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/me",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const employee = await fastify.prisma.employee.findUnique({
|
||||
where: { id: request.employee.id },
|
||||
select: {
|
||||
id: true,
|
||||
employee_no: true,
|
||||
name: true,
|
||||
phone: true,
|
||||
email: true,
|
||||
department_id: true,
|
||||
direct_manager_id: true,
|
||||
status: true,
|
||||
roles: { select: { role_code: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const roleCodes = (employee?.roles ?? []).map((r) => r.role_code);
|
||||
return sendData(reply, request, {
|
||||
id: employee?.id ?? request.employee.id,
|
||||
employeeNo: employee?.employee_no ?? "",
|
||||
name: employee?.name ?? "",
|
||||
phone: employee?.phone ?? "",
|
||||
email: employee?.email ?? "",
|
||||
departmentId: employee?.department_id ?? "",
|
||||
directManagerId: employee?.direct_manager_id ?? null,
|
||||
status: employee?.status ?? "active",
|
||||
roleCodes,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = meRoutes;
|
||||
|
||||
@@ -0,0 +1,724 @@
|
||||
const { z } = require("zod");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { compactDateString, currentDateString, parseDateOnlyString } = require("../utils/date");
|
||||
const {
|
||||
buildWorkflowStepsFromApprovalRule,
|
||||
resolveActionableStep,
|
||||
toMoneyString,
|
||||
} = require("../utils/workflow");
|
||||
|
||||
const UUID_SCHEMA = z.string().uuid();
|
||||
|
||||
function ensureOwnOrCanViewAll(fastify, request, reimbursement) {
|
||||
const canViewAll = fastify.hasPermission(request.employee, "expense.view_all");
|
||||
if (canViewAll) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!fastify.hasPermission(request.employee, "expense.view_own")) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const isOwn =
|
||||
reimbursement.owner_id === request.employee.id ||
|
||||
reimbursement.submitter_id === request.employee.id;
|
||||
if (!isOwn) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function formatFormNumber(sequence, timezone) {
|
||||
const datePart = compactDateString(timezone);
|
||||
const serial = String(sequence.current_number).padStart(sequence.number_length, "0");
|
||||
return `${sequence.prefix}${sequence.separator}${datePart}${sequence.separator}${serial}`;
|
||||
}
|
||||
|
||||
function parseWithdrawBody(body) {
|
||||
const bodySchema = z.object({
|
||||
comment: z.string().trim().min(1).max(500).optional(),
|
||||
});
|
||||
|
||||
const parsed = bodySchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseReimbursementId(id) {
|
||||
const parsed = UUID_SCHEMA.safeParse(id);
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { id: "invalid_uuid" },
|
||||
});
|
||||
}
|
||||
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function ensureNonNegativeAmount(totalAmount) {
|
||||
const asNumber = Number(totalAmount);
|
||||
if (!Number.isFinite(asNumber)) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { total_amount: "invalid" },
|
||||
});
|
||||
}
|
||||
|
||||
if (asNumber < 0) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { total_amount: "negative_not_allowed" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadApprovalRuleForAmount(tx, totalAmount) {
|
||||
const amountString = toMoneyString(totalAmount);
|
||||
const approvalRule = await tx.approvalRule.findFirst({
|
||||
where: {
|
||||
enabled: true,
|
||||
min_amount: { lte: amountString },
|
||||
OR: [{ max_amount: null }, { max_amount: { gt: amountString } }],
|
||||
},
|
||||
orderBy: { priority: "asc" },
|
||||
select: {
|
||||
id: true,
|
||||
level1_role: true,
|
||||
level2_role: true,
|
||||
level3_role: true,
|
||||
priority: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!approvalRule) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { workflow: "missing_approval_rule" },
|
||||
});
|
||||
}
|
||||
|
||||
return approvalRule;
|
||||
}
|
||||
|
||||
async function reimbursementRoutes(fastify) {
|
||||
const createBodySchema = z.object({
|
||||
reimbursementDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||
description: z.string().max(500).optional(),
|
||||
});
|
||||
|
||||
fastify.post(
|
||||
"/reimbursements",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.create"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const parsed = createBodySchema.safeParse(request.body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const reimbursementDate =
|
||||
parsed.data.reimbursementDate ?? currentDateString(fastify.config.appTimezone);
|
||||
|
||||
const reimbursement = await fastify.prisma.reimbursementForm.create({
|
||||
data: {
|
||||
submitter_id: request.employee.id,
|
||||
owner_id: request.employee.id,
|
||||
department_id: request.employee.department_id,
|
||||
reimbursement_date: parseDateOnlyString(reimbursementDate),
|
||||
description: parsed.data.description ?? null,
|
||||
created_by: request.employee.id,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
reimbursement_date: true,
|
||||
description: true,
|
||||
total_amount: true,
|
||||
form_number: true,
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
id: reimbursement.id,
|
||||
formNumber: reimbursement.form_number,
|
||||
reimbursementDate,
|
||||
status: reimbursement.status,
|
||||
description: reimbursement.description,
|
||||
totalAmount: toMoneyString(reimbursement.total_amount),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get(
|
||||
"/reimbursements/:id",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const reimbursementId = parseReimbursementId(request.params?.id);
|
||||
|
||||
const reimbursement = await fastify.prisma.reimbursementForm.findUnique({
|
||||
where: { id: reimbursementId },
|
||||
select: {
|
||||
id: true,
|
||||
form_number: true,
|
||||
submitter_id: true,
|
||||
owner_id: true,
|
||||
department_id: true,
|
||||
reimbursement_date: true,
|
||||
total_amount: true,
|
||||
status: true,
|
||||
description: true,
|
||||
owner: {
|
||||
select: { id: true, employee_no: true, name: true },
|
||||
},
|
||||
submitter: {
|
||||
select: { id: true, employee_no: true, name: true },
|
||||
},
|
||||
invoice_pool_items: {
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
invoice_code: true,
|
||||
invoice_number: true,
|
||||
total_amount: true,
|
||||
},
|
||||
},
|
||||
workflow_instances: {
|
||||
where: { current_status: "pending" },
|
||||
orderBy: { created_at: "desc" },
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
current_step_id: true,
|
||||
workflow_tasks: {
|
||||
where: { status: "pending" },
|
||||
take: 1,
|
||||
select: {
|
||||
id: true,
|
||||
step_name: true,
|
||||
assignee_id: true,
|
||||
assignee_role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!reimbursement) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
ensureOwnOrCanViewAll(fastify, request, reimbursement);
|
||||
|
||||
const pendingInstance = reimbursement.workflow_instances[0] ?? null;
|
||||
const pendingTask = pendingInstance?.workflow_tasks?.[0] ?? null;
|
||||
|
||||
return sendData(reply, request, {
|
||||
id: reimbursement.id,
|
||||
formNumber: reimbursement.form_number,
|
||||
submitterId: reimbursement.submitter_id,
|
||||
ownerId: reimbursement.owner_id,
|
||||
departmentId: reimbursement.department_id,
|
||||
reimbursementDate: reimbursement.reimbursement_date.toISOString().slice(0, 10),
|
||||
totalAmount: toMoneyString(reimbursement.total_amount),
|
||||
status: reimbursement.status,
|
||||
description: reimbursement.description,
|
||||
owner: reimbursement.owner,
|
||||
submitter: reimbursement.submitter,
|
||||
invoices: reimbursement.invoice_pool_items.map((item) => ({
|
||||
id: item.id,
|
||||
status: item.status,
|
||||
invoiceCode: item.invoice_code,
|
||||
invoiceNumber: item.invoice_number,
|
||||
totalAmount: toMoneyString(item.total_amount),
|
||||
})),
|
||||
pendingWorkflow: pendingInstance
|
||||
? {
|
||||
instanceId: pendingInstance.id,
|
||||
stepId: pendingInstance.current_step_id,
|
||||
task: pendingTask,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/reimbursements/:id/submit",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.submit"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const reimbursementId = parseReimbursementId(request.params?.id);
|
||||
let submitResult = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const reimbursementRows = await tx.$queryRaw`
|
||||
SELECT id, owner_id, submitter_id, department_id, status, form_number, total_amount
|
||||
FROM "reimbursement_forms"
|
||||
WHERE id = ${reimbursementId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
|
||||
if (!Array.isArray(reimbursementRows) || reimbursementRows.length === 0) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const reimbursement = reimbursementRows[0];
|
||||
ensureOwnOrCanViewAll(fastify, request, reimbursement);
|
||||
|
||||
if (!["draft", "rejected"].includes(reimbursement.status)) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { status: "invalid_submit_status" },
|
||||
});
|
||||
}
|
||||
|
||||
ensureNonNegativeAmount(reimbursement.total_amount);
|
||||
|
||||
const activeInstance = await tx.workflowInstance.findFirst({
|
||||
where: {
|
||||
entity_type: "reimbursement",
|
||||
entity_id: reimbursementId,
|
||||
current_status: "pending",
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (activeInstance) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { submit: "already_in_review" },
|
||||
});
|
||||
}
|
||||
|
||||
const boundInvoiceCount = await tx.invoicePool.count({
|
||||
where: {
|
||||
linked_reimbursement_id: reimbursementId,
|
||||
status: "bound",
|
||||
},
|
||||
});
|
||||
if (boundInvoiceCount < 1) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { invoices: "bound_invoice_required" },
|
||||
});
|
||||
}
|
||||
|
||||
const workflowDefinition = await tx.workflowDefinition.findFirst({
|
||||
where: {
|
||||
entity_type: "reimbursement",
|
||||
is_active: true,
|
||||
},
|
||||
orderBy: { version: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
if (!workflowDefinition) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { workflow: "missing_definition" },
|
||||
});
|
||||
}
|
||||
|
||||
const approvalRule = await loadApprovalRuleForAmount(tx, reimbursement.total_amount);
|
||||
const workflowSteps = buildWorkflowStepsFromApprovalRule(approvalRule);
|
||||
const { actionable, skipped } = await resolveActionableStep({
|
||||
tx,
|
||||
steps: workflowSteps,
|
||||
startIndex: 0,
|
||||
ownerId: reimbursement.owner_id,
|
||||
logger: fastify.log,
|
||||
});
|
||||
|
||||
if (!actionable) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: {
|
||||
workflow: "no_actionable_approver",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let formNumber = reimbursement.form_number;
|
||||
if (!formNumber) {
|
||||
const sequence = await tx.documentSequence.upsert({
|
||||
where: { document_type: "reimbursement" },
|
||||
update: {
|
||||
current_number: { increment: 1 },
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
create: {
|
||||
document_type: "reimbursement",
|
||||
prefix: "BX",
|
||||
date_format: "YYYYMMDD",
|
||||
separator: "-",
|
||||
number_length: 4,
|
||||
reset_period: "none",
|
||||
current_number: 1,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
prefix: true,
|
||||
separator: true,
|
||||
number_length: true,
|
||||
current_number: true,
|
||||
},
|
||||
});
|
||||
|
||||
formNumber = formatFormNumber(sequence, fastify.config.appTimezone);
|
||||
}
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: reimbursementId },
|
||||
data: {
|
||||
form_number: formNumber,
|
||||
status: "reviewing",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
const workflowInstance = await tx.workflowInstance.create({
|
||||
data: {
|
||||
workflow_id: workflowDefinition.id,
|
||||
entity_type: "reimbursement",
|
||||
entity_id: reimbursementId,
|
||||
submitter_id: request.employee.id,
|
||||
current_status: "pending",
|
||||
current_step_id: actionable.step.id,
|
||||
context_data: {
|
||||
owner_id: reimbursement.owner_id,
|
||||
department_id: reimbursement.department_id,
|
||||
workflow_steps_snapshot: workflowSteps,
|
||||
approval_rule_id: approvalRule.id,
|
||||
},
|
||||
context_department_id: reimbursement.department_id,
|
||||
created_by: request.employee.id,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
current_step_id: true,
|
||||
},
|
||||
});
|
||||
|
||||
for (const skippedStep of skipped) {
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
actor_id: request.employee.id,
|
||||
action: "skip",
|
||||
payload: {
|
||||
step_id: skippedStep.step.id,
|
||||
reason: skippedStep.reason,
|
||||
owner_id: reimbursement.owner_id,
|
||||
depth_checked: skippedStep.depthChecked,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const workflowTask = await tx.workflowTask.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
step_id: actionable.step.id,
|
||||
step_name: actionable.step.name ?? actionable.step.id,
|
||||
assignee_id: actionable.assigneeId,
|
||||
assignee_role: actionable.assigneeRole,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
assignee_id: true,
|
||||
assignee_role: true,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: workflowTask.id,
|
||||
actor_id: request.employee.id,
|
||||
action: "start",
|
||||
payload: {
|
||||
step_id: actionable.step.id,
|
||||
approval_rule_id: approvalRule.id,
|
||||
skipped_step_count: skipped.length,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
submitResult = {
|
||||
reimbursementId,
|
||||
formNumber,
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
currentTaskId: workflowTask.id,
|
||||
status: "reviewing",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, submitResult);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/reimbursements/:id/withdraw",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.withdraw"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const reimbursementId = parseReimbursementId(request.params?.id);
|
||||
const { comment } = parseWithdrawBody(request.body);
|
||||
let response = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const reimbursementRows = await tx.$queryRaw`
|
||||
SELECT id, owner_id, submitter_id, status
|
||||
FROM "reimbursement_forms"
|
||||
WHERE id = ${reimbursementId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
|
||||
if (!Array.isArray(reimbursementRows) || reimbursementRows.length === 0) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const reimbursement = reimbursementRows[0];
|
||||
const isApplicant =
|
||||
reimbursement.owner_id === request.employee.id ||
|
||||
reimbursement.submitter_id === request.employee.id;
|
||||
if (!isApplicant) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
details: { withdraw: "only_owner_or_submitter" },
|
||||
});
|
||||
}
|
||||
|
||||
if (reimbursement.status !== "reviewing") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { status: "invalid_withdraw_status" },
|
||||
});
|
||||
}
|
||||
|
||||
const activeInstance = await tx.workflowInstance.findFirst({
|
||||
where: {
|
||||
entity_type: "reimbursement",
|
||||
entity_id: reimbursementId,
|
||||
current_status: "pending",
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!activeInstance) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { withdraw: "no_pending_instance" },
|
||||
});
|
||||
}
|
||||
|
||||
const processedTaskCount = await tx.workflowTask.count({
|
||||
where: {
|
||||
instance_id: activeInstance.id,
|
||||
status: { in: ["completed", "rejected"] },
|
||||
},
|
||||
});
|
||||
if (processedTaskCount > 0) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { withdraw: "already_processed_by_approver" },
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
await tx.workflowTask.updateMany({
|
||||
where: {
|
||||
instance_id: activeInstance.id,
|
||||
status: "pending",
|
||||
},
|
||||
data: {
|
||||
status: "cancelled",
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: activeInstance.id },
|
||||
data: {
|
||||
current_status: "cancelled",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: reimbursementId },
|
||||
data: {
|
||||
status: "draft",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: activeInstance.id,
|
||||
actor_id: request.employee.id,
|
||||
action: "withdraw",
|
||||
comment: comment ?? null,
|
||||
payload: {
|
||||
reimbursement_id: reimbursementId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
response = {
|
||||
reimbursementId,
|
||||
outcome: "withdrawn",
|
||||
workflowInstanceId: activeInstance.id,
|
||||
reimbursementStatus: "draft",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, response);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/reimbursements/:id/pay",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.finance.pay"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const reimbursementId = parseReimbursementId(request.params?.id);
|
||||
let response = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const reimbursementRows = await tx.$queryRaw`
|
||||
SELECT id, status
|
||||
FROM "reimbursement_forms"
|
||||
WHERE id = ${reimbursementId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
|
||||
if (!Array.isArray(reimbursementRows) || reimbursementRows.length === 0) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const reimbursement = reimbursementRows[0];
|
||||
if (!["approved", "paid"].includes(reimbursement.status)) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { status: "invalid_pay_status" },
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const archivedResult = await tx.invoicePool.updateMany({
|
||||
where: {
|
||||
linked_reimbursement_id: reimbursementId,
|
||||
status: "bound",
|
||||
},
|
||||
data: {
|
||||
status: "archived",
|
||||
archived_reason: "used_complete",
|
||||
archived_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (reimbursement.status === "approved") {
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: reimbursementId },
|
||||
data: {
|
||||
status: "paid",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
response = {
|
||||
reimbursementId,
|
||||
outcome: "paid",
|
||||
reimbursementStatus: "paid",
|
||||
// archivedInvoiceCount=0 is valid for idempotent pay or when no bound invoices remain.
|
||||
archivedInvoiceCount: archivedResult.count,
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, response);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = reimbursementRoutes;
|
||||
@@ -0,0 +1,659 @@
|
||||
const { z } = require("zod");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { resolvePermissionsForRoles, hasPermission } = require("../constants/permissions");
|
||||
const { getWorkflowStepsSnapshot, resolveActionableStep } = require("../utils/workflow");
|
||||
|
||||
const TASK_ID_SCHEMA = z.string().uuid();
|
||||
const REQUIRED_COMMENT_SCHEMA = z.object({
|
||||
comment: z.string().trim().min(1).max(500),
|
||||
});
|
||||
const TRANSFER_BODY_SCHEMA = z.object({
|
||||
toApproverId: z.string().uuid(),
|
||||
reason: z.string().max(500),
|
||||
});
|
||||
|
||||
function parseRequiredComment(body) {
|
||||
const parsed = REQUIRED_COMMENT_SCHEMA.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
return parsed.data.comment;
|
||||
}
|
||||
|
||||
function parseTransferBody(body) {
|
||||
const parsed = TRANSFER_BODY_SCHEMA.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const reason = parsed.data.reason.trim();
|
||||
if (reason.length < 10) {
|
||||
throw new AppError({
|
||||
code: "VALID_002",
|
||||
message: "转审原因不足 10 字",
|
||||
statusCode: 400,
|
||||
details: { reason: "too_short" },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
toApproverId: parsed.data.toApproverId,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
function parseTaskId(taskId) {
|
||||
const parsed = TASK_ID_SCHEMA.safeParse(taskId);
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { taskId: "invalid_uuid" },
|
||||
});
|
||||
}
|
||||
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async function lockWorkflowTask(tx, taskId) {
|
||||
const taskRows = await tx.$queryRaw`
|
||||
SELECT id, instance_id, step_id, step_name, assignee_id, assignee_role, status
|
||||
FROM "workflow_tasks"
|
||||
WHERE id = ${taskId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
|
||||
if (!Array.isArray(taskRows) || taskRows.length === 0) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
return taskRows[0];
|
||||
}
|
||||
|
||||
function ensurePendingTask(task) {
|
||||
if (task.status !== "pending") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { task: "already_processed" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function ensureTaskAssignableToCurrentEmployee(task, request) {
|
||||
const matchesAssigneeId = Boolean(task.assignee_id && task.assignee_id === request.employee.id);
|
||||
const matchesAssigneeRole = Boolean(
|
||||
task.assignee_role && request.employee.roleCodes.includes(task.assignee_role),
|
||||
);
|
||||
const isUnassigned = !task.assignee_id && !task.assignee_role;
|
||||
|
||||
if (!(matchesAssigneeId || matchesAssigneeRole || isUnassigned)) {
|
||||
throw new AppError({
|
||||
code: "PERM_002",
|
||||
message: "不在审批范围/非当前处理人",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadWorkflowInstanceForTask(tx, instanceId) {
|
||||
const workflowInstance = await tx.workflowInstance.findUnique({
|
||||
where: { id: instanceId },
|
||||
select: {
|
||||
id: true,
|
||||
entity_id: true,
|
||||
current_step_id: true,
|
||||
context_data: true,
|
||||
workflow_definition: {
|
||||
select: {
|
||||
definition_json: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!workflowInstance) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
return workflowInstance;
|
||||
}
|
||||
|
||||
async function createSkipHistoryRecords(tx, workflowInstanceId, actorId, ownerId, skippedSteps) {
|
||||
for (const skipped of skippedSteps) {
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstanceId,
|
||||
actor_id: actorId,
|
||||
action: "skip",
|
||||
payload: {
|
||||
step_id: skipped.step.id,
|
||||
reason: skipped.reason,
|
||||
owner_id: ownerId,
|
||||
depth_checked: skipped.depthChecked,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelOtherPendingTasks(tx, workflowInstanceId, taskId, actorId) {
|
||||
await tx.workflowTask.updateMany({
|
||||
where: {
|
||||
instance_id: workflowInstanceId,
|
||||
status: "pending",
|
||||
NOT: { id: taskId },
|
||||
},
|
||||
data: {
|
||||
status: "cancelled",
|
||||
completed_at: new Date(),
|
||||
completed_by: actorId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureTransferChainNotExceeded(tx, taskId) {
|
||||
const transferCount = await tx.workflowHistory.count({
|
||||
where: {
|
||||
task_id: taskId,
|
||||
action: "transfer",
|
||||
},
|
||||
});
|
||||
|
||||
if (transferCount >= 3) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { transfer: "chain_limit_exceeded" },
|
||||
});
|
||||
}
|
||||
|
||||
return transferCount;
|
||||
}
|
||||
|
||||
async function ensureTransferTargetEligible(tx, toApproverId) {
|
||||
const target = await tx.employee.findUnique({
|
||||
where: { id: toApproverId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
roles: {
|
||||
select: {
|
||||
role_code: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!target || target.status !== "active") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { toApproverId: "invalid_target" },
|
||||
});
|
||||
}
|
||||
|
||||
const roleCodes = target.roles.map((item) => item.role_code);
|
||||
const permissionCodes = resolvePermissionsForRoles(roleCodes);
|
||||
if (!hasPermission(permissionCodes, "expense.approve")) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { toApproverId: "target_not_approver" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function workflowRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/workflow/tasks",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const querySchema = z.object({
|
||||
status: z.enum(["pending", "completed", "rejected", "cancelled", "skipped"]).optional(),
|
||||
});
|
||||
const parsedQuery = querySchema.safeParse(request.query ?? {});
|
||||
if (!parsedQuery.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsedQuery.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const status = parsedQuery.data.status ?? "pending";
|
||||
const roleFilters = request.employee.roleCodes.length
|
||||
? [{ assignee_role: { in: request.employee.roleCodes } }]
|
||||
: [];
|
||||
|
||||
const tasks = await fastify.prisma.workflowTask.findMany({
|
||||
where: {
|
||||
status,
|
||||
OR: [{ assignee_id: request.employee.id }, ...roleFilters],
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
instance_id: true,
|
||||
step_id: true,
|
||||
step_name: true,
|
||||
assignee_id: true,
|
||||
assignee_role: true,
|
||||
status: true,
|
||||
outcome: true,
|
||||
created_at: true,
|
||||
completed_at: true,
|
||||
workflow_instance: {
|
||||
select: {
|
||||
entity_type: true,
|
||||
entity_id: true,
|
||||
current_status: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
items: tasks,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/approve",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.approve"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const steps = getWorkflowStepsSnapshot(workflowInstance);
|
||||
const currentStepIndex = steps.findIndex((step) => step.id === workflowInstance.current_step_id);
|
||||
if (currentStepIndex < 0) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { workflow: "current_step_not_found" },
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
status: "completed",
|
||||
outcome: "approved",
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
const { actionable, skipped } = await resolveActionableStep({
|
||||
tx,
|
||||
steps,
|
||||
startIndex: currentStepIndex + 1,
|
||||
ownerId: workflowInstance.context_data?.owner_id,
|
||||
logger: fastify.log,
|
||||
});
|
||||
|
||||
await createSkipHistoryRecords(
|
||||
tx,
|
||||
workflowInstance.id,
|
||||
request.employee.id,
|
||||
workflowInstance.context_data?.owner_id,
|
||||
skipped,
|
||||
);
|
||||
|
||||
if (actionable) {
|
||||
const nextTask = await tx.workflowTask.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
step_id: actionable.step.id,
|
||||
step_name: actionable.step.name ?? actionable.step.id,
|
||||
assignee_id: actionable.assigneeId,
|
||||
assignee_role: actionable.assigneeRole,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_step_id: actionable.step.id,
|
||||
current_status: "pending",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "approve",
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
to_step_id: actionable.step.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "approved",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
nextTaskId: nextTask.id,
|
||||
reimbursementStatus: "reviewing",
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_status: "approved",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
status: "approved",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "approve",
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
terminal: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "approved",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
nextTaskId: null,
|
||||
reimbursementStatus: "approved",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/reject",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.approve"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
const comment = parseRequiredComment(request.body);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const now = new Date();
|
||||
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
status: "rejected",
|
||||
outcome: "rejected",
|
||||
comment,
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await cancelOtherPendingTasks(tx, workflowInstance.id, taskId, request.employee.id);
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_status: "rejected",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
status: "rejected",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "reject",
|
||||
comment,
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "rejected",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
reimbursementStatus: "rejected",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/return",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.approve"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
const comment = parseRequiredComment(request.body);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const now = new Date();
|
||||
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
status: "completed",
|
||||
outcome: "returned",
|
||||
comment,
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await cancelOtherPendingTasks(tx, workflowInstance.id, taskId, request.employee.id);
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_status: "terminated",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
status: "draft",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "return",
|
||||
comment,
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "returned",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
reimbursementStatus: "draft",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/transfer",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.transfer"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
const { toApproverId, reason } = parseTransferBody(request.body);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const transferCount = await ensureTransferChainNotExceeded(tx, taskId);
|
||||
await ensureTransferTargetEligible(tx, toApproverId);
|
||||
|
||||
if (toApproverId === request.employee.id) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { transfer: "same_assignee_not_allowed" },
|
||||
});
|
||||
}
|
||||
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
assignee_id: toApproverId,
|
||||
assignee_role: null,
|
||||
},
|
||||
});
|
||||
|
||||
const transfer = await tx.approvalTransfer.create({
|
||||
data: {
|
||||
reimbursement_id: workflowInstance.entity_id,
|
||||
from_approver_id: request.employee.id,
|
||||
to_approver_id: toApproverId,
|
||||
reason,
|
||||
status: "active",
|
||||
created_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "transfer",
|
||||
comment: reason,
|
||||
payload: {
|
||||
from_approver_id: request.employee.id,
|
||||
to_approver_id: toApproverId,
|
||||
reason,
|
||||
transfer_count: transferCount + 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "transferred",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
reimbursementStatus: "reviewing",
|
||||
transferId: transfer.id,
|
||||
fromApproverId: request.employee.id,
|
||||
toApproverId,
|
||||
transferCount: transferCount + 1,
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = workflowRoutes;
|
||||
在新工单中引用
屏蔽一个用户