R52 A1-A6:完成 AP 运营深度操作

- AP 概览页 Tab 工作台化(待付款/异常付款/风险标记/对账异常)
- AP 导出端点支持 CSV/XLSX 与筛选
- 风险标记 resolve/dismiss 支持说明审计留痕
- 支付批次深链、高风险复核提示、对账确认权限收口
- OpenClaw 浏览器级回归全部通过
这个提交包含在:
2026-04-07 09:37:17 +08:00
父节点 02c01dadb9
当前提交 64d9ded024
共修改 9 个文件,包含 2325 行新增和 63 行删除
+450
查看文件
@@ -17,6 +17,7 @@ const {
buildEmployeeDirectoryWhere,
parseEmployeeDirectoryFilters,
} = require("../services/employeeDirectoryFilters");
const { BUDGET_RISK_CODES, toMoneyNumber, toMoneyString } = require("../services/feeControl");
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
const {
HISTORY_STATUS_VALUES,
@@ -102,8 +103,17 @@ const PRESENCE_HISTORY_EXPORT_QUERY_SCHEMA = z.object({
const CONTRACT_REGISTRY_EXPORT_BODY_SCHEMA = CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA.extend({
format: EXPORT_FORMAT_SCHEMA.optional(),
});
const AP_OPERATIONS_EXPORT_BODY_SCHEMA = z.object({
format: EXPORT_FORMAT_SCHEMA.optional(),
pendingEntityType: z.enum(["reimbursement", "travel_order"]).optional(),
pendingCreatedAtFrom: DATE_ONLY_SCHEMA.optional(),
pendingCreatedAtTo: DATE_ONLY_SCHEMA.optional(),
riskBucket: z.enum(["all", "exception", "budget_overspend"]).optional(),
}).strict();
const PRESENCE_HISTORY_EXPORT_LIMIT = 5000;
const AP_PENDING_BATCH_STATUSES = ["draft", "reviewed", "failed"];
const AP_OPERATIONS_PERMISSION_CODES = ["payment.batch.manage", "risk.review.manage"];
function csvCell(value) {
if (value == null) return "";
@@ -331,6 +341,24 @@ function setExportHeaders(reply, format, filename) {
reply.header("content-disposition", `attachment; filename=\"${filename}\"`);
}
async function ensureApOperationsExportEnabled(fastify) {
const gate = await evaluateFeatureFlag({
prisma: fastify.prisma,
config: fastify.config,
flagKey: FEATURE_FLAG_KEYS.paymentBatch,
strictDepartment: false,
});
if (!gate.enabled) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 409,
details: { featureFlag: "payment_batch_v1_disabled", reason: gate.reason },
});
}
}
async function ensureContractsRegistryExportEnabled(fastify, request) {
const gate = await evaluateFeatureFlag({
prisma: fastify.prisma,
@@ -373,6 +401,377 @@ function contractRegistryStatusLabel(value) {
return value ?? "";
}
function paymentBatchEntityTypeLabel(value) {
if (value === "reimbursement") return "报销";
if (value === "travel_order") return "差旅";
return value ?? "";
}
function paymentBatchStatusLabel(value) {
if (value === "draft") return "草稿";
if (value === "reviewed") return "已复核";
if (value === "executed") return "已执行";
if (value === "failed") return "执行失败";
if (value === "cancelled") return "已取消";
return value ?? "";
}
function riskBucketLabel(value) {
if (value === "budget_overspend") return "预算超支";
return "异常风险";
}
function riskFlagStatusLabel(value) {
if (value === "open") return "待处理";
if (value === "resolved") return "已解决";
if (value === "dismissed") return "已驳回";
return value ?? "";
}
function riskLevelLabel(value) {
if (value === "high") return "高";
if (value === "medium") return "中";
if (value === "low") return "低";
return value ?? "";
}
function reconciliationMatchStatusLabel(value) {
if (value === "amount_mismatch") return "金额不匹配";
if (value === "currency_mismatch") return "币种不匹配";
if (value === "missing_transaction") return "缺少交易";
if (value === "duplicate_charge") return "重复扣款";
if (value === "orphan_transaction") return "孤儿交易";
if (value === "reversed_after_payment") return "付款后冲正";
if (value === "matched") return "已匹配";
return value ?? "";
}
function reconciliationResolutionStatusLabel(value) {
if (value === "pending") return "待确认";
if (value === "confirmed") return "已确认";
return value ?? "";
}
function resolveApOperationsRiskBucket(riskCode) {
return BUDGET_RISK_CODES.includes(riskCode) ? "budget_overspend" : "exception";
}
function toDateOnlyRange(dateFrom, dateTo, fieldNames) {
const from = dateFrom ? new Date(`${dateFrom}T00:00:00.000Z`) : null;
const to = dateTo ? new Date(`${dateTo}T23:59:59.999Z`) : null;
if (from && to && from > to) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { [fieldNames.to]: "must_be_after_or_equal_to_from" },
});
}
return { from, to };
}
function buildApOperationsPendingBatchWhere(filters) {
const { from, to } = toDateOnlyRange(
filters.pendingCreatedAtFrom,
filters.pendingCreatedAtTo,
{ from: "pendingCreatedAtFrom", to: "pendingCreatedAtTo" },
);
return {
status: { in: AP_PENDING_BATCH_STATUSES },
...(filters.pendingEntityType ? { entity_type: filters.pendingEntityType } : {}),
...(from || to
? {
created_at: {
...(from ? { gte: from } : {}),
...(to ? { lte: to } : {}),
},
}
: {}),
};
}
function buildApOperationsRiskWhere(filters) {
if (filters.riskBucket === "budget_overspend") {
return {
status: "open",
risk_code: { in: BUDGET_RISK_CODES },
};
}
if (filters.riskBucket === "exception") {
return {
status: "open",
risk_code: { notIn: BUDGET_RISK_CODES },
};
}
return { status: "open" };
}
function mapApPendingBatchExportRow(item) {
const totalAmount = toMoneyString((item.items ?? []).reduce((sum, entry) => sum + toMoneyNumber(entry.amount), 0));
return [
item.batch_no,
paymentBatchEntityTypeLabel(item.entity_type),
item.name,
paymentBatchStatusLabel(item.status),
totalAmount,
toMoneyNumber(totalAmount) >= 50000 ? "是" : "否",
item.created_at?.toISOString?.() ?? "",
];
}
function mapApFailedPaymentItemExportRow(item) {
return [
item.payment_batch?.batch_no ?? item.payment_batch_id,
paymentBatchEntityTypeLabel(item.payment_batch?.entity_type),
item.entity_code,
item.entity_title,
toMoneyString(item.amount),
item.currency_code,
item.failure_code ?? "",
item.failure_message ?? "",
item.created_at?.toISOString?.() ?? "",
];
}
function mapApRiskFlagExportRow(item) {
return [
riskBucketLabel(resolveApOperationsRiskBucket(item.risk_code)),
item.title,
item.risk_code,
riskLevelLabel(item.level),
item.entity_type,
item.entity_id,
item.source,
riskFlagStatusLabel(item.status),
item.detail ?? "",
item.created_at?.toISOString?.() ?? "",
];
}
function mapApReconciliationAnomalyExportRow(item) {
return [
item.batch?.batch_no ?? item.travel_reconciliation_batch_id,
item.anomaly_code ?? "",
reconciliationMatchStatusLabel(item.match_status),
reconciliationResolutionStatusLabel(item.resolution_status),
item.travel_order_id ?? "",
item.travel_request_id ?? "",
item.order_amount != null ? toMoneyString(item.order_amount) : "",
item.transaction_amount != null ? toMoneyString(item.transaction_amount) : "",
item.currency ?? "",
item.created_at?.toISOString?.() ?? "",
];
}
async function loadApOperationsExportDataset(prisma, filters) {
const pendingWhere = buildApOperationsPendingBatchWhere(filters);
const riskWhere = buildApOperationsRiskWhere(filters);
const reconciliationWhere = {
resolution_status: "pending",
match_status: { not: "matched" },
};
const [pendingPaymentBatches, failedPaymentBatchItems, riskFlags, reconciliationAnomalies] = await Promise.all([
prisma.paymentBatch.findMany({
where: pendingWhere,
orderBy: [{ created_at: "desc" }, { id: "desc" }],
include: {
items: {
select: {
amount: true,
},
},
},
}),
prisma.paymentBatchItem.findMany({
where: { status: "failed" },
orderBy: [{ created_at: "desc" }, { id: "desc" }],
include: {
payment_batch: {
select: {
batch_no: true,
entity_type: true,
},
},
},
}),
prisma.entityRiskFlag.findMany({
where: riskWhere,
orderBy: [{ created_at: "desc" }, { id: "desc" }],
}),
prisma.travelReconciliationItem.findMany({
where: reconciliationWhere,
orderBy: [{ created_at: "desc" }, { id: "desc" }],
take: 50,
include: {
batch: {
select: {
batch_no: true,
},
},
},
}),
]);
return {
pendingWhere,
riskWhere,
reconciliationWhere,
pendingPaymentBatches,
failedPaymentBatchItems,
riskFlags,
reconciliationAnomalies,
};
}
async function* streamApOperationsCsv(dataset) {
yield "\ufeff";
yield csvRow(["待付款批次"]);
yield csvRow(["批次编号", "实体类型", "批次名称", "状态", "总金额", "高风险", "创建时间"]);
for (const item of dataset.pendingPaymentBatches) {
yield csvRow(mapApPendingBatchExportRow(item));
}
yield csvRow([]);
yield csvRow(["异常付款项"]);
yield csvRow(["批次编号", "实体类型", "单据编号", "单据标题", "金额", "币种", "失败码", "失败原因", "创建时间"]);
for (const item of dataset.failedPaymentBatchItems) {
yield csvRow(mapApFailedPaymentItemExportRow(item));
}
yield csvRow([]);
yield csvRow(["风险标记"]);
yield csvRow(["风险分组", "标题", "风险编码", "等级", "实体类型", "实体 ID", "来源", "状态", "明细", "创建时间"]);
for (const item of dataset.riskFlags) {
yield csvRow(mapApRiskFlagExportRow(item));
}
yield csvRow([]);
yield csvRow(["对账异常"]);
yield csvRow(["批次编号", "异常编码", "匹配状态", "确认状态", "差旅订单 ID", "差旅申请 ID", "订单金额", "交易金额", "币种", "创建时间"]);
for (const item of dataset.reconciliationAnomalies) {
yield csvRow(mapApReconciliationAnomalyExportRow(item));
}
}
async function buildApOperationsXlsx(dataset) {
const workbook = new ExcelJS.Workbook();
const pendingSheet = workbook.addWorksheet("待付款批次");
pendingSheet.columns = [
{ header: "批次编号", key: "batchNo", width: 24 },
{ header: "实体类型", key: "entityType", width: 14 },
{ header: "批次名称", key: "name", width: 30 },
{ header: "状态", key: "status", width: 14 },
{ header: "总金额", key: "totalAmount", width: 14 },
{ header: "高风险", key: "highRisk", width: 10 },
{ header: "创建时间", key: "createdAt", width: 24 },
];
for (const item of dataset.pendingPaymentBatches) {
const row = mapApPendingBatchExportRow(item);
pendingSheet.addRow({
batchNo: row[0],
entityType: row[1],
name: row[2],
status: row[3],
totalAmount: row[4],
highRisk: row[5],
createdAt: row[6],
});
}
const failedSheet = workbook.addWorksheet("异常付款项");
failedSheet.columns = [
{ header: "批次编号", key: "batchNo", width: 24 },
{ header: "实体类型", key: "entityType", width: 14 },
{ header: "单据编号", key: "entityCode", width: 24 },
{ header: "单据标题", key: "entityTitle", width: 28 },
{ header: "金额", key: "amount", width: 14 },
{ header: "币种", key: "currencyCode", width: 10 },
{ header: "失败码", key: "failureCode", width: 20 },
{ header: "失败原因", key: "failureMessage", width: 32 },
{ header: "创建时间", key: "createdAt", width: 24 },
];
for (const item of dataset.failedPaymentBatchItems) {
const row = mapApFailedPaymentItemExportRow(item);
failedSheet.addRow({
batchNo: row[0],
entityType: row[1],
entityCode: row[2],
entityTitle: row[3],
amount: row[4],
currencyCode: row[5],
failureCode: row[6],
failureMessage: row[7],
createdAt: row[8],
});
}
const riskSheet = workbook.addWorksheet("风险标记");
riskSheet.columns = [
{ header: "风险分组", key: "bucket", width: 14 },
{ header: "标题", key: "title", width: 28 },
{ header: "风险编码", key: "riskCode", width: 24 },
{ header: "等级", key: "level", width: 10 },
{ header: "实体类型", key: "entityType", width: 16 },
{ header: "实体 ID", key: "entityId", width: 38 },
{ header: "来源", key: "source", width: 14 },
{ header: "状态", key: "status", width: 12 },
{ header: "明细", key: "detail", width: 40 },
{ header: "创建时间", key: "createdAt", width: 24 },
];
for (const item of dataset.riskFlags) {
const row = mapApRiskFlagExportRow(item);
riskSheet.addRow({
bucket: row[0],
title: row[1],
riskCode: row[2],
level: row[3],
entityType: row[4],
entityId: row[5],
source: row[6],
status: row[7],
detail: row[8],
createdAt: row[9],
});
}
const reconciliationSheet = workbook.addWorksheet("对账异常");
reconciliationSheet.columns = [
{ header: "批次编号", key: "batchNo", width: 24 },
{ header: "异常编码", key: "anomalyCode", width: 20 },
{ header: "匹配状态", key: "matchStatus", width: 16 },
{ header: "确认状态", key: "resolutionStatus", width: 14 },
{ header: "差旅订单 ID", key: "travelOrderId", width: 38 },
{ header: "差旅申请 ID", key: "travelRequestId", width: 38 },
{ header: "订单金额", key: "orderAmount", width: 14 },
{ header: "交易金额", key: "transactionAmount", width: 14 },
{ header: "币种", key: "currency", width: 10 },
{ header: "创建时间", key: "createdAt", width: 24 },
];
for (const item of dataset.reconciliationAnomalies) {
const row = mapApReconciliationAnomalyExportRow(item);
reconciliationSheet.addRow({
batchNo: row[0],
anomalyCode: row[1],
matchStatus: row[2],
resolutionStatus: row[3],
travelOrderId: row[4],
travelRequestId: row[5],
orderAmount: row[6],
transactionAmount: row[7],
currency: row[8],
createdAt: row[9],
});
}
return workbook.xlsx.writeBuffer();
}
function mapContractRegistryExportRow(item, today) {
const effectiveStatus = resolveContractRegistryEffectiveStatus(item, today);
return [
@@ -1202,6 +1601,57 @@ async function exportsRoutes(fastify) {
},
);
fastify.post(
"/exports/ap-operations",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
await ensureApOperationsExportEnabled(fastify);
ensureHasAnyPermission(fastify, request, AP_OPERATIONS_PERMISSION_CODES);
const parsedBody = parseBody(AP_OPERATIONS_EXPORT_BODY_SCHEMA, request.body);
const format = parsedBody.format ?? "csv";
const filters = {
pendingEntityType: parsedBody.pendingEntityType,
pendingCreatedAtFrom: parsedBody.pendingCreatedAtFrom,
pendingCreatedAtTo: parsedBody.pendingCreatedAtTo,
riskBucket: parsedBody.riskBucket ?? "all",
};
const dataset = await loadApOperationsExportDataset(fastify.prisma, filters);
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "EXPORT_AP_OPERATIONS",
targetType: "export",
extra: {
format,
pendingEntityType: filters.pendingEntityType ?? null,
pendingCreatedAtFrom: filters.pendingCreatedAtFrom ?? null,
pendingCreatedAtTo: filters.pendingCreatedAtTo ?? null,
riskBucket: filters.riskBucket,
pendingPaymentBatchTotal: dataset.pendingPaymentBatches.length,
failedPaymentItemTotal: dataset.failedPaymentBatchItems.length,
openRiskFlagTotal: dataset.riskFlags.length,
reconciliationAnomalyTotal: dataset.reconciliationAnomalies.length,
},
}),
});
const filename = exportFilename("ap-operations", format);
setExportHeaders(reply, format, filename);
if (format === "xlsx") {
const buffer = await buildApOperationsXlsx(dataset);
return reply.send(Buffer.from(buffer));
}
const stream = Readable.from(streamApOperationsCsv(dataset));
return reply.send(stream);
},
);
fastify.get(
"/exports/employees",
{
+22
查看文件
@@ -12,6 +12,9 @@ const QUERY_SCHEMA = z.object({
status: z.enum(["open", "resolved", "dismissed"]).optional(),
source: z.string().trim().max(32).optional(),
});
const ACTION_BODY_SCHEMA = z.object({
note: z.string().trim().max(500).nullable().optional(),
}).strict();
function buildValidationError(details, statusCode = 400) {
return new AppError({
@@ -58,6 +61,22 @@ function parseId(value) {
return parsed.data;
}
function parseBody(body) {
const parsed = ACTION_BODY_SCHEMA.safeParse(body ?? {});
if (!parsed.success) {
throw buildValidationError(parsed.error.flatten());
}
return parsed.data;
}
function normalizeNote(value) {
if (value == null) {
return null;
}
const trimmed = String(value).trim();
return trimmed || null;
}
async function riskFlagsRoutes(fastify) {
fastify.get("/risk-flags", { preHandler: fastify.authenticate }, async (request, reply) => {
ensureListPermission(fastify, request);
@@ -78,6 +97,8 @@ async function riskFlagsRoutes(fastify) {
fastify.post(`/risk-flags/:id/${action}`, { preHandler: fastify.authenticate }, async (request, reply) => {
ensureManagePermission(fastify, request);
const riskFlagId = parseId(request.params?.id);
const body = parseBody(request.body);
const note = normalizeNote(body.note);
const current = await fastify.prisma.entityRiskFlag.findUnique({ where: { id: riskFlagId } });
if (!current) {
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
@@ -105,6 +126,7 @@ async function riskFlagsRoutes(fastify) {
entityType: updated.entity_type,
entityId: updated.entity_id,
riskCode: updated.risk_code,
note,
},
}),
});
@@ -0,0 +1,272 @@
const Fastify = require("fastify");
const exportsRoutes = require("../../../src/routes/exports");
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
function buildFeatureFlagRecord(flagKey) {
return {
id: `flag-${flagKey}`,
flag_key: flagKey,
override_mode: "force_on",
rollout_type: "global",
department_ids: [],
note: "unit-test",
version: 1,
created_at: new Date("2026-04-06T08:00:00.000Z"),
created_by: null,
updated_at: new Date("2026-04-06T08:00:00.000Z"),
updated_by: null,
};
}
function buildPendingBatch(overrides = {}) {
return {
id: "11111111-1111-4111-8111-111111111111",
batch_no: "PB-20260406-001",
entity_type: "travel_order",
name: "差旅待付款批次",
status: "reviewed",
created_at: new Date("2026-04-06T09:00:00.000Z"),
items: [{ amount: "1000.00" }, { amount: "560.50" }],
...overrides,
};
}
function buildFailedItem(overrides = {}) {
return {
id: "22222222-2222-4222-8222-222222222222",
payment_batch_id: "11111111-1111-4111-8111-111111111111",
entity_id: "33333333-3333-4333-8333-333333333333",
entity_code: "TR-001",
entity_title: "上海差旅订单",
amount: "560.50",
currency_code: "CNY",
failure_code: "BANK_TIMEOUT",
failure_message: "银行回执超时",
created_at: new Date("2026-04-06T10:00:00.000Z"),
payment_batch: {
batch_no: "PB-20260406-001",
entity_type: "travel_order",
},
...overrides,
};
}
function buildRiskFlag(overrides = {}) {
return {
id: "44444444-4444-4444-8444-444444444444",
entity_type: "travel_order",
entity_id: "33333333-3333-4333-8333-333333333333",
risk_code: "budget_exceeded",
level: "high",
title: "预算超支",
detail: "差旅预算已超支",
source: "budget_control",
status: "open",
created_at: new Date("2026-04-06T11:00:00.000Z"),
...overrides,
};
}
function buildAnomaly(overrides = {}) {
return {
id: "55555555-5555-4555-8555-555555555555",
travel_reconciliation_batch_id: "66666666-6666-4666-8666-666666666666",
travel_order_id: "77777777-7777-4777-8777-777777777777",
travel_request_id: "88888888-8888-4888-8888-888888888888",
match_status: "amount_mismatch",
resolution_status: "pending",
anomaly_code: "AMOUNT_MISMATCH",
order_amount: "880.00",
transaction_amount: "860.00",
currency: "CNY",
created_at: new Date("2026-04-06T12:00:00.000Z"),
batch: {
batch_no: "TRB-20260406-001",
},
...overrides,
};
}
async function buildApp(options = {}) {
const app = Fastify();
const actor = options.actor ?? {
id: ACTOR_ID,
permissionCodes: ["payment.batch.manage"],
};
const paymentBatchFindMany = options.paymentBatchFindMany ?? vi.fn().mockResolvedValue([buildPendingBatch()]);
const paymentBatchItemFindMany = options.paymentBatchItemFindMany ?? vi.fn().mockResolvedValue([buildFailedItem()]);
const entityRiskFlagFindMany = options.entityRiskFlagFindMany ?? vi.fn().mockResolvedValue([buildRiskFlag()]);
const travelReconciliationItemFindMany =
options.travelReconciliationItemFindMany ?? vi.fn().mockResolvedValue([buildAnomaly()]);
const auditCreate = options.auditCreate ?? vi.fn().mockResolvedValue({});
app.decorate("authenticate", async (request) => {
request.employee = actor;
});
app.decorate("hasPermission", (employee, permissionCode) => {
const permissionCodes = employee.permissionCodes ?? [];
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
});
app.decorate("requirePermission", (permissionCode) => async (request) => {
request.employee = actor;
const permissionCodes = actor.permissionCodes ?? [];
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
throw new Error(`unexpected permission check: ${permissionCode}`);
}
});
app.decorate("config", {
appTimezone: "Asia/Shanghai",
paymentBatchEnabled: true,
projectLinkingEnabled: true,
});
app.decorate("prisma", {
featureFlag: {
findUnique: vi.fn().mockImplementation(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
},
paymentBatch: {
findMany: paymentBatchFindMany,
},
paymentBatchItem: {
findMany: paymentBatchItemFindMany,
},
entityRiskFlag: {
findMany: entityRiskFlagFindMany,
},
travelReconciliationItem: {
findMany: travelReconciliationItemFindMany,
},
auditLog: {
create: auditCreate,
},
contractRegistry: {
count: vi.fn().mockResolvedValue(0),
findMany: vi.fn().mockResolvedValue([]),
},
});
await app.register(exportsRoutes, { prefix: "/api" });
return {
app,
paymentBatchFindMany,
paymentBatchItemFindMany,
entityRiskFlagFindMany,
travelReconciliationItemFindMany,
auditCreate,
};
}
describe("ap operations export route", () => {
it("exports ap operations as csv with section blocks and filters", async () => {
const {
app,
paymentBatchFindMany,
entityRiskFlagFindMany,
travelReconciliationItemFindMany,
auditCreate,
} = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/exports/ap-operations",
payload: {
format: "csv",
pendingEntityType: "travel_order",
pendingCreatedAtFrom: "2026-04-01",
pendingCreatedAtTo: "2026-04-30",
riskBucket: "budget_overspend",
},
});
expect(response.statusCode).toBe(200);
expect(response.headers["content-type"]).toContain("text/csv");
expect(response.headers["content-disposition"]).toContain("ap-operations-");
expect(response.body).toContain("待付款批次");
expect(response.body).toContain("异常付款项");
expect(response.body).toContain("风险标记");
expect(response.body).toContain("对账异常");
expect(response.body).toContain("预算超支");
expect(paymentBatchFindMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
entity_type: "travel_order",
status: { in: ["draft", "reviewed", "failed"] },
created_at: expect.objectContaining({
gte: new Date("2026-04-01T00:00:00.000Z"),
lte: new Date("2026-04-30T23:59:59.999Z"),
}),
}),
}),
);
expect(entityRiskFlagFindMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
status: "open",
risk_code: { in: ["budget_exceeded", "budget_threshold_exceeded"] },
}),
}),
);
expect(travelReconciliationItemFindMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
resolution_status: "pending",
match_status: { not: "matched" },
}),
take: 50,
}),
);
expect(auditCreate).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: "EXPORT_AP_OPERATIONS",
extra: expect.objectContaining({
format: "csv",
pendingEntityType: "travel_order",
pendingCreatedAtFrom: "2026-04-01",
pendingCreatedAtTo: "2026-04-30",
riskBucket: "budget_overspend",
pendingPaymentBatchTotal: 1,
failedPaymentItemTotal: 1,
openRiskFlagTotal: 1,
reconciliationAnomalyTotal: 1,
}),
}),
}),
);
await app.close();
});
it("exports ap operations as xlsx", async () => {
const { app, auditCreate } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/exports/ap-operations",
payload: {
format: "xlsx",
},
});
expect(response.statusCode).toBe(200);
expect(response.headers["content-type"]).toContain(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
);
expect(response.headers["content-disposition"]).toContain("ap-operations-");
expect(Buffer.from(response.rawPayload).length).toBeGreaterThan(0);
expect(auditCreate).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: "EXPORT_AP_OPERATIONS",
extra: expect.objectContaining({
format: "xlsx",
riskBucket: "all",
}),
}),
}),
);
await app.close();
});
});
+125
查看文件
@@ -0,0 +1,125 @@
const Fastify = require("fastify");
const riskFlagsRoutes = require("../../../src/routes/riskFlags");
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const RISK_FLAG_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
function buildRiskFlag(overrides = {}) {
return {
id: RISK_FLAG_ID,
entity_type: "reimbursement",
entity_id: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
risk_code: "budget_exceeded",
level: "high",
title: "预算已超支",
detail: "部门预算已超预算阈值",
source: "budget_control",
status: "open",
payload_json: null,
created_at: new Date("2026-04-06T08:00:00.000Z"),
created_by: null,
resolved_at: null,
resolved_by: null,
...overrides,
};
}
async function buildApp(options = {}) {
const app = Fastify();
const actor = options.actor ?? {
id: ACTOR_ID,
permissionCodes: ["risk.review.manage"],
};
const currentRecord = options.currentRecord ?? buildRiskFlag();
const findUnique = options.findUnique ?? vi.fn().mockResolvedValue(currentRecord);
const update = options.update ?? vi.fn().mockImplementation(async ({ data }) => ({
...currentRecord,
status: data.status,
resolved_at: data.resolved_at,
resolved_by: data.resolved_by,
}));
const auditCreate = options.auditCreate ?? vi.fn().mockResolvedValue({});
app.decorate("authenticate", async (request) => {
request.employee = actor;
});
app.decorate("hasPermission", (employee, permissionCode) => {
const permissionCodes = employee.permissionCodes ?? [];
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
});
app.decorate("prisma", {
entityRiskFlag: {
findMany: vi.fn().mockResolvedValue([]),
findUnique,
update,
},
auditLog: {
create: auditCreate,
},
});
await app.register(riskFlagsRoutes, { prefix: "/api" });
return { app, findUnique, update, auditCreate };
}
describe("risk flags routes", () => {
it("writes resolve note into audit extra while keeping response shape", async () => {
const { app, update, auditCreate } = await buildApp();
const response = await app.inject({
method: "POST",
url: `/api/risk-flags/${RISK_FLAG_ID}/resolve`,
payload: {
note: "已人工核查,无需继续挂起",
},
});
expect(response.statusCode).toBe(200);
expect(update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: RISK_FLAG_ID },
data: expect.objectContaining({
status: "resolved",
resolved_by: ACTOR_ID,
}),
}),
);
expect(auditCreate).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: "ENTITY_RISK_FLAG_RESOLVED",
extra: expect.objectContaining({
riskCode: "budget_exceeded",
note: "已人工核查,无需继续挂起",
}),
}),
}),
);
const payload = response.json();
expect(payload.data.item.status).toBe("resolved");
expect(payload.data.item.resolvedBy).toBe(ACTOR_ID);
await app.close();
});
it("rejects unexpected fields for resolve action body", async () => {
const { app, update, auditCreate } = await buildApp();
const response = await app.inject({
method: "POST",
url: `/api/risk-flags/${RISK_FLAG_ID}/resolve`,
payload: {
note: "ok",
extra: "not-allowed",
},
});
expect(response.statusCode).toBe(400);
expect(update).not.toHaveBeenCalled();
expect(auditCreate).not.toHaveBeenCalled();
await app.close();
});
});