汇总已落盘的借款本金与还款、兼容历史编号的周期化编号、付款责任与回单核验、报销进度和排序、PWA/采购事务、错误原因与日期校验及ERP退役。 统一共享预算池锁序和锁后判断,恢复差旅原预算选择,补原因码固定夹具及反向完整性检查。 纳入配套迁移、测试、受管QA、分层验收合同、规约及任务记录;原始证据留在ignored artifacts。 关联任务:09-17-company-loan-principal-repayment、09-17-erp-exclusive-retirement、09-18-reimbursement-periodic-numbering、09-08-reimbursement-payment-closeout、09-18-local-concurrency-product-fixes、09-19-budget-pool-concurrency、09-05-error-explainability-payment-readiness。 预算补审由Claude定向验证2文件928项通过,原4446/28及r6结果仍仅对应各自历史输入;本轮未重跑测试。 完整新候选门禁、R1真实入口接入与12项公网义务仍开放。生产编号未启用、差旅仍冻结;不推送、不部署,不宣称发布资格。
411 行
14 KiB
JavaScript
411 行
14 KiB
JavaScript
const Fastify = require("fastify");
|
|
|
|
const exportsRoutes = require("../../../src/routes/exports");
|
|
const { AppError } = require("../../../src/utils/AppError");
|
|
|
|
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,
|
|
};
|
|
}
|
|
|
|
function buildFinanceLedgerItem(overrides = {}) {
|
|
return {
|
|
id: "99999999-9999-4999-8999-999999999999",
|
|
form_number: "BX-20260406-001",
|
|
reimbursement_date: new Date("2026-04-05T00:00:00.000Z"),
|
|
status: "paid",
|
|
total_amount: "1688.00",
|
|
description: "财务台账测试报销",
|
|
payment_voucher_no: "PAY-001",
|
|
payment_date: new Date("2026-04-06T00:00:00.000Z"),
|
|
payment_channel: "bank",
|
|
paid_at: new Date("2026-04-06T13:00:00.000Z"),
|
|
created_at: new Date("2026-04-05T09:00:00.000Z"),
|
|
updated_at: new Date("2026-04-06T13:00:00.000Z"),
|
|
owner: { id: ACTOR_ID, employee_no: "E001", name: "张三" },
|
|
submitter: { id: ACTOR_ID, employee_no: "E001", name: "张三" },
|
|
department: { id: "dept-1", name: "财务部" },
|
|
project: { id: "project-1", project_no: "PJ-001", name: "交付项目" },
|
|
paid_by_employee: { id: ACTOR_ID, employee_no: "F001", name: "财务" },
|
|
invoice_pool_items: [{ id: "invoice-1", status: "archived", archived_reason: "used_complete" }],
|
|
_count: { attachments: 1, invoice_pool_items: 1 },
|
|
...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 reimbursementFormFindMany = options.reimbursementFormFindMany ?? vi.fn().mockResolvedValue([buildFinanceLedgerItem()]);
|
|
const reimbursementFormCount = options.reimbursementFormCount ?? vi.fn().mockResolvedValue(1);
|
|
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 AppError({
|
|
code: "PERM_001",
|
|
message: "无权限",
|
|
statusCode: 403,
|
|
details: { permission: 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,
|
|
},
|
|
reimbursementForm: {
|
|
findMany: reimbursementFormFindMany,
|
|
count: reimbursementFormCount,
|
|
},
|
|
auditLog: {
|
|
create: auditCreate,
|
|
},
|
|
contractRegistry: {
|
|
count: vi.fn().mockResolvedValue(0),
|
|
findMany: vi.fn().mockResolvedValue([]),
|
|
},
|
|
});
|
|
|
|
app.setErrorHandler((error, request, reply) => {
|
|
if (error instanceof AppError) {
|
|
return reply.status(error.statusCode).send({
|
|
requestId: request.id,
|
|
error: {
|
|
code: error.code,
|
|
message: error.message,
|
|
details: error.details ?? {},
|
|
},
|
|
});
|
|
}
|
|
return reply.status(500).send({
|
|
requestId: request.id,
|
|
error: {
|
|
code: "SYS_001",
|
|
message: error.message,
|
|
},
|
|
});
|
|
});
|
|
|
|
await app.register(exportsRoutes, { prefix: "/api" });
|
|
return {
|
|
app,
|
|
paymentBatchFindMany,
|
|
paymentBatchItemFindMany,
|
|
entityRiskFlagFindMany,
|
|
travelReconciliationItemFindMany,
|
|
reimbursementFormFindMany,
|
|
reimbursementFormCount,
|
|
auditCreate,
|
|
};
|
|
}
|
|
|
|
describe("ap operations export route", () => {
|
|
it.each(["manager", "ceo", "system_admin"])("does not grant AP export through ledger or reviewer access for %s", async (role) => {
|
|
const { resolvePermissionsForRoles } = require("../../../src/constants/permissions");
|
|
const { app, paymentBatchFindMany, auditCreate } = await buildApp({
|
|
actor: { id: ACTOR_ID, permissionCodes: resolvePermissionsForRoles([role]) },
|
|
});
|
|
try {
|
|
const response = await app.inject({ method: "POST", url: "/api/exports/ap-operations", payload: { format: "csv" } });
|
|
expect(response.statusCode).toBe(403);
|
|
expect(paymentBatchFindMany).not.toHaveBeenCalled();
|
|
expect(auditCreate).not.toHaveBeenCalled();
|
|
} finally {
|
|
await app.close();
|
|
}
|
|
});
|
|
|
|
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("BX-20260406-001");
|
|
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,
|
|
financeLedgerTotal: 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();
|
|
});
|
|
|
|
it.each([
|
|
["employee", ["expense.view_own"]],
|
|
["admin-only", ["system.users"]],
|
|
])("rejects ap operations export for %s without finance permissions", async (_roleName, permissionCodes) => {
|
|
const { app, auditCreate } = await buildApp({
|
|
actor: {
|
|
id: ACTOR_ID,
|
|
permissionCodes,
|
|
},
|
|
});
|
|
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: "/api/exports/ap-operations",
|
|
payload: {
|
|
format: "csv",
|
|
},
|
|
});
|
|
|
|
expect(response.statusCode).toBe(403);
|
|
expect(response.json().error.code).toBe("PERM_001");
|
|
expect(auditCreate).not.toHaveBeenCalled();
|
|
|
|
await app.close();
|
|
});
|
|
});
|
|
|
|
|
|
describe("AP export calendar filters", () => {
|
|
const fields = ["pendingCreatedAtFrom", "pendingCreatedAtTo", "ledgerDateFrom", "ledgerDateTo"];
|
|
it.each(["csv", "xlsx"].flatMap((format) => fields.flatMap((field) => ["2026-02-29", "2026-04-31", "2026-13-01", "", null].map((date) => [format, field, date]))))("rejects %s %s=%s before business reads or export audit", async (format, field, date) => {
|
|
const { app, auditCreate, ...reads } = await buildApp();
|
|
try {
|
|
const response = await app.inject({ method: "POST", url: "/api/exports/ap-operations", payload: { format, [field]: date } });
|
|
expect(response.statusCode).toBe(400);
|
|
expect(response.json().error.details.fieldErrors[field].length).toBeGreaterThan(0);
|
|
for (const fn of [...Object.values(reads), auditCreate]) expect(fn).not.toHaveBeenCalled();
|
|
expect(response.headers["content-disposition"]).toBeUndefined();
|
|
} finally { await app.close(); }
|
|
});
|
|
it.each(["csv", "xlsx"])("preserves %s leap-day/month-end bounds for both datasets", async (format) => {
|
|
const { app, paymentBatchFindMany, reimbursementFormFindMany } = await buildApp();
|
|
try {
|
|
const response = await app.inject({ method: "POST", url: "/api/exports/ap-operations", payload: { format, pendingCreatedAtFrom: "2024-02-29", pendingCreatedAtTo: "2024-04-30", ledgerDateFrom: "2024-02-29", ledgerDateTo: "2024-04-30" } });
|
|
expect(response.statusCode).toBe(200);
|
|
const range = { gte: new Date("2024-02-29T00:00:00.000Z"), lte: new Date("2024-04-30T23:59:59.999Z") };
|
|
expect(paymentBatchFindMany.mock.calls[0][0].where.created_at).toEqual(range);
|
|
expect(reimbursementFormFindMany.mock.calls[0][0].where.AND).toContainEqual({ reimbursement_date: range });
|
|
} finally { await app.close(); }
|
|
});
|
|
it("preserves reversed pending-range status and details before reads", async () => {
|
|
const { app, auditCreate, ...reads } = await buildApp();
|
|
try {
|
|
const response = await app.inject({ method: "POST", url: "/api/exports/ap-operations", payload: { pendingCreatedAtFrom: "2024-05-01", pendingCreatedAtTo: "2024-04-30" } });
|
|
expect(response.statusCode).toBe(400);
|
|
expect(response.json().error.details).toEqual({ pendingCreatedAtTo: "must_be_after_or_equal_to_from", reasonCode: "export.ap_pending_date_range_invalid" });
|
|
for (const fn of [...Object.values(reads), auditCreate]) expect(fn).not.toHaveBeenCalled();
|
|
} finally { await app.close(); }
|
|
});
|
|
});
|