R56 A1-A6:费用标准管控
这个提交包含在:
@@ -34,6 +34,7 @@ const employeesRoutes = require("./routes/employees");
|
||||
const performanceRoutes = require("./routes/performance");
|
||||
const payrollRoutes = require("./routes/payroll");
|
||||
const expenseTypesRoutes = require("./routes/expenseTypes");
|
||||
const expenseStandardsRoutes = require("./routes/expenseStandards");
|
||||
const configReadRoutes = require("./routes/configRead");
|
||||
const approvalRulesRoutes = require("./routes/approvalRules");
|
||||
const featureFlagsRoutes = require("./routes/featureFlags");
|
||||
@@ -322,6 +323,7 @@ async function buildApp() {
|
||||
await app.register(masterDataHolidayCalendarsRoutes, { prefix: "/api" });
|
||||
await app.register(masterDataSuppliersRoutes, { prefix: "/api" });
|
||||
await app.register(expenseTypesRoutes, { prefix: "/api" });
|
||||
await app.register(expenseStandardsRoutes, { prefix: "/api" });
|
||||
await app.register(configReadRoutes, { prefix: "/api" });
|
||||
await app.register(approvalRulesRoutes, { prefix: "/api" });
|
||||
await app.register(featureFlagsRoutes, { prefix: "/api" });
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
const { z } = require("zod");
|
||||
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
const { sendData } = require("../utils/reply");
|
||||
|
||||
const UUID_SCHEMA = z.string().uuid();
|
||||
const MONEY_SCHEMA = z.string().trim().regex(/^\d+(\.\d{1,2})?$/);
|
||||
const PER_UNIT_VALUES = ["item", "day", "trip"];
|
||||
const CONTROL_MODE_VALUES = ["warn", "block"];
|
||||
const SCOPE_TYPE_VALUES = ["global", "department"];
|
||||
|
||||
const LIST_QUERY_SCHEMA = z
|
||||
.object({
|
||||
expenseTypeId: UUID_SCHEMA.optional(),
|
||||
expense_type_id: UUID_SCHEMA.optional(),
|
||||
scopeType: z.enum(SCOPE_TYPE_VALUES).optional(),
|
||||
scope_type: z.enum(SCOPE_TYPE_VALUES).optional(),
|
||||
enabled: z.enum(["true", "false", "1", "0"]).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const CREATE_BODY_SCHEMA = z
|
||||
.object({
|
||||
expenseTypeId: UUID_SCHEMA,
|
||||
name: z.string().trim().min(1).max(100),
|
||||
maxAmount: MONEY_SCHEMA,
|
||||
perUnit: z.enum(PER_UNIT_VALUES).optional(),
|
||||
controlMode: z.enum(CONTROL_MODE_VALUES).optional(),
|
||||
scopeType: z.enum(SCOPE_TYPE_VALUES).optional(),
|
||||
scopeKey: UUID_SCHEMA.nullish(),
|
||||
enabled: z.boolean().optional(),
|
||||
note: z.string().trim().max(500).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const UPDATE_BODY_SCHEMA = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(100).optional(),
|
||||
maxAmount: MONEY_SCHEMA.optional(),
|
||||
perUnit: z.enum(PER_UNIT_VALUES).optional(),
|
||||
controlMode: z.enum(CONTROL_MODE_VALUES).optional(),
|
||||
scopeType: z.enum(SCOPE_TYPE_VALUES).optional(),
|
||||
scopeKey: UUID_SCHEMA.nullish().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
note: z.string().trim().max(500).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
function buildValidationError(details, statusCode = 400) {
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
function toMoneyString(value) {
|
||||
const numeric = Number(value ?? 0);
|
||||
if (!Number.isFinite(numeric)) {
|
||||
return "0.00";
|
||||
}
|
||||
return numeric.toFixed(2);
|
||||
}
|
||||
|
||||
function parseExpenseStandardId(params) {
|
||||
const parsed = UUID_SCHEMA.safeParse(params?.id);
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError({ id: "invalid_uuid" });
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseListQuery(query) {
|
||||
const parsed = LIST_QUERY_SCHEMA.safeParse(query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
const enabledRaw = parsed.data.enabled;
|
||||
const enabled =
|
||||
enabledRaw == null
|
||||
? null
|
||||
: ["true", "1"].includes(enabledRaw)
|
||||
? true
|
||||
: false;
|
||||
|
||||
return {
|
||||
expenseTypeId: parsed.data.expenseTypeId ?? parsed.data.expense_type_id ?? null,
|
||||
scopeType: parsed.data.scopeType ?? parsed.data.scope_type ?? null,
|
||||
enabled,
|
||||
};
|
||||
}
|
||||
|
||||
function parseBody(schema, body) {
|
||||
const parsed = schema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
if ("maxAmount" in data && data.maxAmount != null && Number(data.maxAmount) <= 0) {
|
||||
throw buildValidationError({ maxAmount: "must_be_positive" });
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async function ensureExpenseTypeExists(tx, expenseTypeId) {
|
||||
const expenseType = await tx.expenseType.findUnique({
|
||||
where: { id: expenseTypeId },
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!expenseType) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { expenseTypeId: "not_found" },
|
||||
});
|
||||
}
|
||||
|
||||
return expenseType;
|
||||
}
|
||||
|
||||
async function ensureScopeKeyValid(tx, scopeType, scopeKey) {
|
||||
if (scopeType === "global") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!scopeKey) {
|
||||
throw buildValidationError({ scopeKey: "required_for_department_scope" });
|
||||
}
|
||||
|
||||
const department = await tx.department.findUnique({
|
||||
where: { id: scopeKey },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
archived_at: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!department || department.archived_at) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { scopeKey: "invalid_department" },
|
||||
});
|
||||
}
|
||||
|
||||
return department;
|
||||
}
|
||||
|
||||
function buildStandardPayload(body, actorId) {
|
||||
const scopeType = body.scopeType ?? "global";
|
||||
return {
|
||||
...(typeof body.name === "string" ? { name: body.name } : {}),
|
||||
...(typeof body.maxAmount === "string" ? { max_amount: body.maxAmount } : {}),
|
||||
...(typeof body.perUnit === "string" ? { per_unit: body.perUnit } : {}),
|
||||
...(typeof body.controlMode === "string" ? { control_mode: body.controlMode } : {}),
|
||||
scope_type: scopeType,
|
||||
scope_key: scopeType === "department" ? body.scopeKey ?? null : null,
|
||||
...(typeof body.enabled === "boolean" ? { enabled: body.enabled } : {}),
|
||||
...(Object.prototype.hasOwnProperty.call(body, "note") ? { note: body.note?.trim?.() || null } : {}),
|
||||
updated_by: actorId,
|
||||
};
|
||||
}
|
||||
|
||||
function buildScopeLabel(item, departmentMap) {
|
||||
if (item.scope_type === "global") {
|
||||
return "全局";
|
||||
}
|
||||
return departmentMap.get(item.scope_key) ?? item.scope_key ?? "指定部门";
|
||||
}
|
||||
|
||||
function mapExpenseStandard(item, departmentMap) {
|
||||
return {
|
||||
id: item.id,
|
||||
expenseTypeId: item.expense_type_id,
|
||||
expenseTypeName: item.expense_type?.name ?? null,
|
||||
name: item.name,
|
||||
maxAmount: toMoneyString(item.max_amount),
|
||||
perUnit: item.per_unit,
|
||||
controlMode: item.control_mode,
|
||||
scopeType: item.scope_type,
|
||||
scopeKey: item.scope_key ?? null,
|
||||
scopeLabel: buildScopeLabel(item, departmentMap),
|
||||
enabled: item.enabled,
|
||||
note: item.note ?? null,
|
||||
createdAt: item.created_at?.toISOString?.() ?? null,
|
||||
updatedAt: item.updated_at?.toISOString?.() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRecordSnapshot(item) {
|
||||
if (!item) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: item.id,
|
||||
expenseTypeId: item.expense_type_id,
|
||||
name: item.name,
|
||||
maxAmount: toMoneyString(item.max_amount),
|
||||
perUnit: item.per_unit,
|
||||
controlMode: item.control_mode,
|
||||
scopeType: item.scope_type,
|
||||
scopeKey: item.scope_key ?? null,
|
||||
enabled: item.enabled,
|
||||
note: item.note ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildDepartmentMap(prisma, items) {
|
||||
const departmentIds = Array.from(
|
||||
new Set(
|
||||
items
|
||||
.filter((item) => item.scope_type === "department" && item.scope_key)
|
||||
.map((item) => item.scope_key),
|
||||
),
|
||||
);
|
||||
|
||||
if (!departmentIds.length) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const departments = await prisma.department.findMany({
|
||||
where: {
|
||||
id: { in: departmentIds },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
});
|
||||
|
||||
return new Map(departments.map((item) => [item.id, item.name]));
|
||||
}
|
||||
|
||||
async function expenseStandardsRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/expense-standards",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const query = parseListQuery(request.query);
|
||||
const canManage = fastify.hasPermission(request.employee, "system.settings");
|
||||
|
||||
if (!canManage && (!query.expenseTypeId || query.enabled !== true)) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const items = await fastify.prisma.expenseStandard.findMany({
|
||||
where: {
|
||||
...(query.expenseTypeId ? { expense_type_id: query.expenseTypeId } : {}),
|
||||
...(query.scopeType ? { scope_type: query.scopeType } : {}),
|
||||
...(query.enabled == null ? {} : { enabled: query.enabled }),
|
||||
},
|
||||
orderBy: [
|
||||
{ expense_type: { sort_order: "asc" } },
|
||||
{ expense_type: { code: "asc" } },
|
||||
{ scope_type: "asc" },
|
||||
{ name: "asc" },
|
||||
{ created_at: "asc" },
|
||||
],
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
name: true,
|
||||
max_amount: true,
|
||||
per_unit: true,
|
||||
control_mode: true,
|
||||
scope_type: true,
|
||||
scope_key: true,
|
||||
enabled: true,
|
||||
note: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
expense_type: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const departmentMap = await buildDepartmentMap(fastify.prisma, items);
|
||||
return sendData(reply, request, {
|
||||
expenseTypeId: query.expenseTypeId,
|
||||
scopeType: query.scopeType,
|
||||
enabled: query.enabled,
|
||||
items: items.map((item) => mapExpenseStandard(item, departmentMap)),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/expense-standards",
|
||||
{
|
||||
preHandler: fastify.requirePermission("system.settings"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const body = parseBody(CREATE_BODY_SCHEMA, request.body);
|
||||
const now = new Date();
|
||||
|
||||
let created = null;
|
||||
try {
|
||||
created = await fastify.prisma.$transaction(async (tx) => {
|
||||
const expenseType = await ensureExpenseTypeExists(tx, body.expenseTypeId);
|
||||
const scopeType = body.scopeType ?? "global";
|
||||
const department = await ensureScopeKeyValid(tx, scopeType, body.scopeKey ?? null);
|
||||
|
||||
const record = await tx.expenseStandard.create({
|
||||
data: {
|
||||
expense_type_id: body.expenseTypeId,
|
||||
name: body.name,
|
||||
max_amount: body.maxAmount,
|
||||
per_unit: body.perUnit ?? "item",
|
||||
control_mode: body.controlMode ?? "warn",
|
||||
scope_type: scopeType,
|
||||
scope_key: scopeType === "department" ? department?.id ?? body.scopeKey ?? null : null,
|
||||
enabled: body.enabled ?? true,
|
||||
note: body.note?.trim?.() || null,
|
||||
created_at: now,
|
||||
created_by: request.employee.id,
|
||||
updated_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
name: true,
|
||||
max_amount: true,
|
||||
per_unit: true,
|
||||
control_mode: true,
|
||||
scope_type: true,
|
||||
scope_key: true,
|
||||
enabled: true,
|
||||
note: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
expense_type: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "EXPENSE_STANDARD_CREATED",
|
||||
targetType: "expense_standard",
|
||||
targetId: record.id,
|
||||
extra: {
|
||||
expenseTypeId: expenseType.id,
|
||||
expenseTypeName: expenseType.name,
|
||||
scopeType: record.scope_type,
|
||||
scopeKey: record.scope_key,
|
||||
controlMode: record.control_mode,
|
||||
maxAmount: toMoneyString(record.max_amount),
|
||||
after: normalizeRecordSnapshot(record),
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return record;
|
||||
});
|
||||
} catch (error) {
|
||||
if (error?.code === "P2002") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { duplicate: "expense_type_scope_conflict" },
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const departmentMap = await buildDepartmentMap(fastify.prisma, [created]);
|
||||
return sendData(reply, request, mapExpenseStandard(created, departmentMap));
|
||||
},
|
||||
);
|
||||
|
||||
fastify.patch(
|
||||
"/expense-standards/:id",
|
||||
{
|
||||
preHandler: fastify.requirePermission("system.settings"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const standardId = parseExpenseStandardId(request.params);
|
||||
const body = parseBody(UPDATE_BODY_SCHEMA, request.body);
|
||||
if (!Object.keys(body).length) {
|
||||
throw buildValidationError({ body: "empty" });
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
let updated = null;
|
||||
try {
|
||||
updated = await fastify.prisma.$transaction(async (tx) => {
|
||||
const current = await tx.expenseStandard.findUnique({
|
||||
where: { id: standardId },
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
name: true,
|
||||
max_amount: true,
|
||||
per_unit: true,
|
||||
control_mode: true,
|
||||
scope_type: true,
|
||||
scope_key: true,
|
||||
enabled: true,
|
||||
note: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!current) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const mergedBody = {
|
||||
...body,
|
||||
scopeType: body.scopeType ?? current.scope_type,
|
||||
scopeKey:
|
||||
Object.prototype.hasOwnProperty.call(body, "scopeKey")
|
||||
? body.scopeKey ?? null
|
||||
: current.scope_key ?? null,
|
||||
};
|
||||
|
||||
await ensureScopeKeyValid(tx, mergedBody.scopeType, mergedBody.scopeKey);
|
||||
|
||||
const record = await tx.expenseStandard.update({
|
||||
where: { id: standardId },
|
||||
data: {
|
||||
...buildStandardPayload(mergedBody, request.employee.id),
|
||||
updated_at: now,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
name: true,
|
||||
max_amount: true,
|
||||
per_unit: true,
|
||||
control_mode: true,
|
||||
scope_type: true,
|
||||
scope_key: true,
|
||||
enabled: true,
|
||||
note: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
expense_type: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "EXPENSE_STANDARD_UPDATED",
|
||||
targetType: "expense_standard",
|
||||
targetId: standardId,
|
||||
extra: {
|
||||
expenseTypeId: record.expense_type_id,
|
||||
scopeType: record.scope_type,
|
||||
scopeKey: record.scope_key,
|
||||
controlMode: record.control_mode,
|
||||
maxAmount: toMoneyString(record.max_amount),
|
||||
before: normalizeRecordSnapshot(current),
|
||||
after: normalizeRecordSnapshot(record),
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return record;
|
||||
});
|
||||
} catch (error) {
|
||||
if (error?.code === "P2002") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { duplicate: "expense_type_scope_conflict" },
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const departmentMap = await buildDepartmentMap(fastify.prisma, [updated]);
|
||||
return sendData(reply, request, mapExpenseStandard(updated, departmentMap));
|
||||
},
|
||||
);
|
||||
|
||||
fastify.delete(
|
||||
"/expense-standards/:id",
|
||||
{
|
||||
preHandler: fastify.requirePermission("system.settings"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const standardId = parseExpenseStandardId(request.params);
|
||||
const now = new Date();
|
||||
|
||||
const deleted = await fastify.prisma.$transaction(async (tx) => {
|
||||
const current = await tx.expenseStandard.findUnique({
|
||||
where: { id: standardId },
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
name: true,
|
||||
max_amount: true,
|
||||
per_unit: true,
|
||||
control_mode: true,
|
||||
scope_type: true,
|
||||
scope_key: true,
|
||||
enabled: true,
|
||||
note: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
expense_type: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!current) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const record = await tx.expenseStandard.update({
|
||||
where: { id: standardId },
|
||||
data: {
|
||||
enabled: false,
|
||||
updated_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
name: true,
|
||||
max_amount: true,
|
||||
per_unit: true,
|
||||
control_mode: true,
|
||||
scope_type: true,
|
||||
scope_key: true,
|
||||
enabled: true,
|
||||
note: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
expense_type: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "EXPENSE_STANDARD_DELETED",
|
||||
targetType: "expense_standard",
|
||||
targetId: standardId,
|
||||
extra: {
|
||||
expenseTypeId: record.expense_type_id,
|
||||
scopeType: record.scope_type,
|
||||
scopeKey: record.scope_key,
|
||||
controlMode: record.control_mode,
|
||||
maxAmount: toMoneyString(record.max_amount),
|
||||
before: normalizeRecordSnapshot(current),
|
||||
after: normalizeRecordSnapshot(record),
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return record;
|
||||
});
|
||||
|
||||
const departmentMap = await buildDepartmentMap(fastify.prisma, [deleted]);
|
||||
return sendData(reply, request, mapExpenseStandard(deleted, departmentMap));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = expenseStandardsRoutes;
|
||||
@@ -663,16 +663,37 @@ function buildBudgetHint(budgetPool, reimbursementAmount, controlMode) {
|
||||
}
|
||||
|
||||
function buildPrecheckBlockedError(precheck) {
|
||||
const standardViolations = Array.isArray(precheck?.standardChecks)
|
||||
? precheck.standardChecks.filter((item) => item.exceeded && item.controlMode === "block")
|
||||
: [];
|
||||
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
statusCode: standardViolations.length ? 400 : 409,
|
||||
details: {
|
||||
precheck: precheck.blockingReasons,
|
||||
...(standardViolations.length ? { standardViolations } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function listExceededStandardViolations(precheck, controlMode = null) {
|
||||
if (!Array.isArray(precheck?.standardChecks)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return precheck.standardChecks.filter((item) => {
|
||||
if (!item.exceeded) {
|
||||
return false;
|
||||
}
|
||||
if (!controlMode) {
|
||||
return true;
|
||||
}
|
||||
return item.controlMode === controlMode;
|
||||
});
|
||||
}
|
||||
|
||||
function buildSkippedNotificationResult(reason) {
|
||||
return { skipped: true, reason };
|
||||
}
|
||||
@@ -2079,6 +2100,8 @@ async function reimbursementRoutes(fastify) {
|
||||
if (authoritativePrecheck.decision === "block") {
|
||||
throw buildPrecheckBlockedError(authoritativePrecheck);
|
||||
}
|
||||
const standardViolations = listExceededStandardViolations(authoritativePrecheck);
|
||||
const standardWarnings = listExceededStandardViolations(authoritativePrecheck, "warn");
|
||||
const openedRiskFlags = await createRiskFlagsFromPrecheck(tx, {
|
||||
entityType: "reimbursement",
|
||||
entityId: reimbursementId,
|
||||
@@ -2238,6 +2261,7 @@ async function reimbursementRoutes(fastify) {
|
||||
department_id: reimbursement.department_id,
|
||||
workflow_steps_snapshot: workflowSteps,
|
||||
approval_rule_id: approvalRule.id,
|
||||
standardViolations,
|
||||
},
|
||||
context_department_id: reimbursement.department_id,
|
||||
created_by: request.employee.id,
|
||||
@@ -2319,6 +2343,7 @@ async function reimbursementRoutes(fastify) {
|
||||
status: "reviewing",
|
||||
budget: budgetCheck,
|
||||
precheckDecision: authoritativePrecheck.decision,
|
||||
standardWarnings,
|
||||
openedRiskFlagCount: openedRiskFlags.length,
|
||||
},
|
||||
sideEffectsContext: {
|
||||
|
||||
@@ -1450,6 +1450,7 @@ async function workflowRoutes(fastify) {
|
||||
entity_id: true,
|
||||
current_status: true,
|
||||
current_step_id: true,
|
||||
context_data: true,
|
||||
started_at: true,
|
||||
completed_at: true,
|
||||
reimbursement_form: {
|
||||
@@ -1676,6 +1677,11 @@ async function workflowRoutes(fastify) {
|
||||
entityType: task.workflow_instance.entity_type,
|
||||
currentStatus: task.workflow_instance.current_status,
|
||||
currentStepId: task.workflow_instance.current_step_id,
|
||||
contextData: {
|
||||
standardViolations: Array.isArray(task.workflow_instance.context_data?.standardViolations)
|
||||
? task.workflow_instance.context_data.standardViolations
|
||||
: [],
|
||||
},
|
||||
startedAt: isoOrNull(task.workflow_instance.started_at),
|
||||
completedAt: isoOrNull(task.workflow_instance.completed_at),
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ function buildBasePrecheck(entityType, entityId) {
|
||||
decision: "pass",
|
||||
matchedBudgetControlRule: null,
|
||||
budgetHint: null,
|
||||
standardChecks: [],
|
||||
warnings: [],
|
||||
blockingReasons: [],
|
||||
riskFlags: [],
|
||||
@@ -70,6 +71,7 @@ function buildDisabledPrecheck(entityType, entityId) {
|
||||
decision: "pass",
|
||||
matchedBudgetControlRule: null,
|
||||
budgetHint: null,
|
||||
standardChecks: [],
|
||||
warnings: [],
|
||||
blockingReasons: [],
|
||||
riskFlags: [],
|
||||
@@ -272,6 +274,165 @@ function appendBlockingReasons(response, issues) {
|
||||
return response;
|
||||
}
|
||||
|
||||
function buildStandardIssueDetail(check) {
|
||||
return `标准:${check.standardName},上限 ¥${check.maxAmount}/${check.perUnit},当前 ¥${check.amount},超出 ¥${check.exceededAmount}`;
|
||||
}
|
||||
|
||||
function buildStandardIssue(check) {
|
||||
return buildIssue(
|
||||
`expense_standard_${check.controlMode}_${check.itemId}`,
|
||||
`${check.expenseTypeName} 超出费用标准`,
|
||||
buildStandardIssueDetail(check),
|
||||
);
|
||||
}
|
||||
|
||||
async function checkExpenseStandards(tx, { reimbursementId }) {
|
||||
const reimbursement = await tx.reimbursementForm.findUnique({
|
||||
where: { id: reimbursementId },
|
||||
select: {
|
||||
id: true,
|
||||
department_id: true,
|
||||
items: {
|
||||
orderBy: [{ created_at: "asc" }, { id: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
amount: true,
|
||||
expense_type: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!reimbursement) {
|
||||
throw buildNotFoundError();
|
||||
}
|
||||
|
||||
const expenseTypeIds = Array.from(
|
||||
new Set(reimbursement.items.map((item) => item.expense_type_id).filter(Boolean)),
|
||||
);
|
||||
|
||||
if (!expenseTypeIds.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const standards = await tx.expenseStandard.findMany({
|
||||
where: {
|
||||
enabled: true,
|
||||
expense_type_id: { in: expenseTypeIds },
|
||||
OR: [
|
||||
{ scope_type: "global" },
|
||||
...(reimbursement.department_id
|
||||
? [{ scope_type: "department", scope_key: reimbursement.department_id }]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
orderBy: [{ created_at: "asc" }, { id: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
expense_type_id: true,
|
||||
name: true,
|
||||
max_amount: true,
|
||||
per_unit: true,
|
||||
control_mode: true,
|
||||
scope_type: true,
|
||||
scope_key: true,
|
||||
},
|
||||
});
|
||||
|
||||
const standardMap = new Map();
|
||||
for (const standard of standards) {
|
||||
const current = standardMap.get(standard.expense_type_id);
|
||||
if (!current) {
|
||||
standardMap.set(standard.expense_type_id, standard);
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentPriority = current.scope_type === "department" ? 2 : 1;
|
||||
const nextPriority = standard.scope_type === "department" ? 2 : 1;
|
||||
if (nextPriority > currentPriority) {
|
||||
standardMap.set(standard.expense_type_id, standard);
|
||||
}
|
||||
}
|
||||
|
||||
return reimbursement.items
|
||||
.map((item) => {
|
||||
const standard = standardMap.get(item.expense_type_id);
|
||||
if (!standard) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const amount = toMoneyNumber(item.amount);
|
||||
const maxAmount = toMoneyNumber(standard.max_amount);
|
||||
const exceededAmount = Math.max(0, toMoneyNumber(amount - maxAmount));
|
||||
|
||||
return {
|
||||
itemId: item.id,
|
||||
expenseTypeId: item.expense_type_id,
|
||||
expenseTypeName: item.expense_type?.name ?? item.expense_type_id,
|
||||
amount: toMoneyString(amount),
|
||||
standardId: standard.id,
|
||||
standardName: standard.name,
|
||||
maxAmount: toMoneyString(maxAmount),
|
||||
perUnit: standard.per_unit,
|
||||
controlMode: standard.control_mode,
|
||||
scopeType: standard.scope_type,
|
||||
scopeKey: standard.scope_key ?? null,
|
||||
exceeded: amount > maxAmount,
|
||||
exceededAmount: toMoneyString(exceededAmount),
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function mergeReimbursementPrecheck(precheck, standardChecks) {
|
||||
const response = {
|
||||
...precheck,
|
||||
warnings: [...precheck.warnings],
|
||||
blockingReasons: [...precheck.blockingReasons],
|
||||
riskFlags: [...precheck.riskFlags],
|
||||
nextActions: [...precheck.nextActions],
|
||||
standardChecks,
|
||||
};
|
||||
|
||||
const warnChecks = standardChecks.filter((item) => item.exceeded && item.controlMode === "warn");
|
||||
const blockChecks = standardChecks.filter((item) => item.exceeded && item.controlMode === "block");
|
||||
|
||||
if (warnChecks.length) {
|
||||
response.warnings.push(...warnChecks.map((item) => buildStandardIssue(item)));
|
||||
}
|
||||
if (blockChecks.length) {
|
||||
response.blockingReasons.push(...blockChecks.map((item) => buildStandardIssue(item)));
|
||||
}
|
||||
|
||||
if (response.blockingReasons.length) {
|
||||
response.decision = "block";
|
||||
response.nextActions = ["修正阻断项后再提交"];
|
||||
return response;
|
||||
}
|
||||
|
||||
if (response.riskFlags.length) {
|
||||
response.decision = "manual_review";
|
||||
response.nextActions = ["允许提交,但会生成待复核风险项"];
|
||||
return response;
|
||||
}
|
||||
|
||||
if (response.warnings.length) {
|
||||
response.decision = "warn";
|
||||
response.nextActions = ["确认提示后可继续提交"];
|
||||
return response;
|
||||
}
|
||||
|
||||
response.decision = "pass";
|
||||
response.nextActions = ["可直接提交"];
|
||||
return response;
|
||||
}
|
||||
|
||||
async function createRiskFlagsFromPrecheck(tx, { entityType, entityId, actorId, precheck, source = "precheck" }) {
|
||||
if (precheck.decision !== "manual_review" || !precheck.riskFlags.length) {
|
||||
return [];
|
||||
@@ -308,6 +469,7 @@ async function createRiskFlagsFromPrecheck(tx, { entityType, entityId, actorId,
|
||||
openedByDecision: precheck.decision,
|
||||
matchedBudgetControlRule: precheck.matchedBudgetControlRule,
|
||||
budgetHint: precheck.budgetHint,
|
||||
standardChecks: precheck.standardChecks ?? [],
|
||||
},
|
||||
created_by: actorId ?? null,
|
||||
},
|
||||
@@ -843,15 +1005,27 @@ async function resolveEntityPrecheck({
|
||||
});
|
||||
|
||||
if (!gate.enabled) {
|
||||
return buildDisabledPrecheck(entityType, entityId);
|
||||
const disabledPrecheck = buildDisabledPrecheck(entityType, entityId);
|
||||
if (entityType !== "reimbursement") {
|
||||
return disabledPrecheck;
|
||||
}
|
||||
const standardChecks = await checkExpenseStandards(prisma, { reimbursementId: entityId });
|
||||
return mergeReimbursementPrecheck(disabledPrecheck, standardChecks);
|
||||
}
|
||||
|
||||
return buildEntityPrecheck(prisma, {
|
||||
const precheck = await buildEntityPrecheck(prisma, {
|
||||
entityType,
|
||||
entityId,
|
||||
config,
|
||||
logger,
|
||||
});
|
||||
|
||||
if (entityType !== "reimbursement") {
|
||||
return precheck;
|
||||
}
|
||||
|
||||
const standardChecks = await checkExpenseStandards(prisma, { reimbursementId: entityId });
|
||||
return mergeReimbursementPrecheck(precheck, standardChecks);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
@@ -870,6 +1044,8 @@ module.exports = {
|
||||
buildReimbursementPrecheck,
|
||||
buildPurchaseRequestPrecheck,
|
||||
buildTravelRequestPrecheck,
|
||||
checkExpenseStandards,
|
||||
loadPrecheckEntityContext,
|
||||
mergeReimbursementPrecheck,
|
||||
resolveEntityPrecheck,
|
||||
};
|
||||
|
||||
在新工单中引用
屏蔽一个用户