fix: 增加回单核对与付款登记门禁(09-08-reimbursement-payment-closeout)
ci-e2e / e2e (push) Canceled after 0s
ci-minimal / check-minimal (push) Canceled after 0s

这个提交包含在:
2026-09-15 07:21:55 +08:00
父节点 229867f5fd
当前提交 8d08d46d16
共修改 33 个文件,包含 3691 行新增和 11 行删除
@@ -0,0 +1,169 @@
const { normalizeBankSlip } = require("../../../src/services/paymentReceiptMatching");
const { buildManualReceiptProposal, assertIndependentReceiptReviewer } = require("../../../src/services/paymentReceiptManualReview");
const config = { fieldEncryptionKey: Buffer.alloc(32, 7).toString("base64") };
function reviewFixture() {
return { reviewer: { id: "reviewer", roleCodes: ["ceo"] }, hasReviewPermission: true,
makerId: "maker", proposedBy: "operator", participants: [{ ownerId: "owner", submitterId: "submitter" }] };
}
describe("independent manual receipt review identity", () => {
test("independent business reviewer is eligible", () => {
expect(() => assertIndependentReceiptReviewer(reviewFixture())).not.toThrow();
});
test.each(["maker", "operator", "owner", "submitter"])("cannot review as %s", (id) => {
const input = reviewFixture();
input.reviewer.id = id;
expect(() => assertIndependentReceiptReviewer(input)).toThrow("receipt_review_identity_conflict");
});
test.each([["admin"], ["finance"], ["*"]])("permission does not substitute for business role %j", (role) => {
const input = reviewFixture();
input.reviewer.roleCodes = [role];
expect(() => assertIndependentReceiptReviewer(input)).toThrow("receipt_review_permission_required");
});
test("business role does not substitute for review permission", () => {
expect(() => assertIndependentReceiptReviewer({ ...reviewFixture(), hasReviewPermission: false }))
.toThrow("receipt_review_permission_required");
});
test.each(["makerId", "proposedBy", "participants"])("missing %s fails closed", (key) => {
const input = reviewFixture();
delete input[key];
expect(() => assertIndependentReceiptReviewer(input)).toThrow("receipt_review_identity_unresolved");
});
test("every source participant is checked, not only the first reimbursement", () => {
const input = reviewFixture();
input.participants.push({ ownerId: "reviewer", submitterId: "another" });
expect(() => assertIndependentReceiptReviewer(input)).toThrow("receipt_review_identity_conflict");
});
});
function fixture() {
const fields = Object.entries({
小写金额: "10.00", 币别: "人民币", 付款人账号: "000011112222",
收款人账号: "000033334444", 单据状态: "交易成功", 凭证号: "SYN-MANUAL",
}).map(([Name, Value]) => ({ Name, Value }));
return {
original: { status: "recognized", pagesExpected: 1, pagesProcessed: 1,
pages: [{ pageNumber: 1, ...normalizeBankSlip(fields) }] },
pages: [{ pageNumber: 1, itemId: "item-2", fields }],
candidates: ["item-1", "item-2"].map((id) => ({
id, amount: "10.00", currency: "CNY", payerAccount: "000011112222", payeeAccount: "000033334444",
})),
};
}
describe("manual receipt proposal is evidence preparation, not authorization", () => {
test("explicit same-amount association needs no field reentry review", () => {
const input = fixture();
const before = JSON.stringify(input);
const result = buildManualReceiptProposal(config, input);
expect(result.requiresIndependentReview).toBe(false);
expect(result.associations).toEqual([{ pageNumber: 1, itemId: "item-2" }]);
expect(result.changedFields).toEqual([{ pageNumber: 1, fields: [] }]);
expect(result.bankVerified).toBe(false);
expect(JSON.stringify(input)).toBe(before);
});
test.each(["amount", "currency", "payerAccount", "payeeAccount", "reference", "transactionStatus"])(
"corrected %s cannot masquerade as an automatic match", (field) => {
const input = fixture();
input.original.pages[0][field] = null;
const result = buildManualReceiptProposal(config, input);
expect(result.requiresIndependentReview).toBe(true);
expect(result.changedFields[0].fields).toContain(field);
expect(input.original.pages[0][field]).toBeNull();
},
);
test("OCR failure requires independent review even with fully matching manual fields", () => {
const input = fixture();
input.original = { status: "ocr_failed", pagesExpected: 1, pagesProcessed: 0, pages: [] };
expect(buildManualReceiptProposal(config, input).requiresIndependentReview).toBe(true);
});
test.each(["failed", "pending"])("cannot rewrite original %s to success", (status) => {
const input = fixture();
input.original.pages[0].transactionStatus = status;
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_transaction_not_successful");
});
test.each(["交易失败", "处理中"])("conflicting status aliases retain %s veto", (status) => {
const input = fixture();
input.original.pages[0] = { pageNumber: 1, ...normalizeBankSlip([
...input.pages[0].fields, { Name: "交易状态", Value: status },
]) };
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_transaction_not_successful");
});
test.each([["小写金额", "11.00"], ["币别", "USD"], ["付款人账号", "111122223333"],
["收款人账号", "222233334444"], ["单据状态", "已受理"], ["凭证号", ""]])(
"%s mismatch cannot be overridden by item selection or reason", (name, value) => {
const input = fixture();
input.pages[0].fields.find((field) => field.Name === name).Value = value;
input.reason = "测试理由不能免除核验";
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_manual_match_required");
},
);
test("association cannot select another batch's item", () => {
const input = fixture();
input.pages[0].itemId = "outside";
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_item_unavailable");
});
test("missing PDF page cannot be waived", () => {
const input = fixture();
input.original.pagesExpected = 2;
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_pages_unresolved");
});
test("unknown original page count cannot be guessed from manual input", () => {
const input = fixture();
input.original.pagesExpected = null;
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_pages_unresolved");
});
test("duplicate transaction on two pages cannot pay two items", () => {
const input = fixture();
input.original.pagesExpected = 2;
input.pages.push({ ...input.pages[0], pageNumber: 2, itemId: "item-1" });
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_transaction_reused");
});
test("two transactions cannot be assigned to one reimbursement", () => {
const input = fixture();
input.original.pagesExpected = 2;
input.pages.push({ ...input.pages[0], pageNumber: 2,
fields: input.pages[0].fields.map((field) => field.Name === "凭证号" ?
{ ...field, Value: "SYN-SECOND" } : field) });
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_multiple_transactions");
});
test.each(["凭证号", "付款人账号"])("cannot hide original duplicate by correcting %s", (name) => {
const input = fixture();
input.original.pagesExpected = 2;
input.original.pagesProcessed = 2;
input.original.pages.push({ ...input.original.pages[0], pageNumber: 2 });
input.pages.push({ ...input.pages[0], pageNumber: 2, itemId: "item-1",
fields: input.pages[0].fields.map((field) => field.Name === name ?
{ ...field, Value: name === "凭证号" ? "SYN-ALTERED" : "999900001111" } : field) });
expect(() => buildManualReceiptProposal(config, input)).toThrow("receipt_transaction_reused");
});
test("retains original fingerprint for persistent cross-batch reuse checks", () => {
const input = fixture();
const original = buildManualReceiptProposal(config, input).originalFingerprints;
input.pages[0].fields.find((field) => field.Name === "凭证号").Value = "SYN-CORRECTED";
const changed = buildManualReceiptProposal(config, input);
expect(changed.originalFingerprints).toEqual(original);
expect(changed.requiresIndependentReview).toBe(true);
expect(original).toHaveLength(1);
expect(original[0]).toMatch(/^[a-f0-9]{64}$/);
});
});
@@ -0,0 +1,115 @@
const {
normalizeBankSlip,
matchBankSlip,
parseReceiptMinorUnits,
} = require("../../../src/services/paymentReceiptMatching");
function fields(overrides = {}) {
return Object.entries({
小写金额: "1,234.56", 币别: "人民币", 付款人账号: "000011112222",
收款人账号: "000033334444", 单据状态: "交易成功", 凭证号: "SYN-0001",
...overrides,
}).map(([Name, Value]) => ({ Name, Value }));
}
function candidates() {
return [{ id: "synthetic-item", amount: "1234.56", currency: "CNY",
payerAccount: "000011112222", payeeAccount: "000033334444" }];
}
describe("bank receipt normalization", () => {
test.each([
["1,234.56", "123456"], ["123.45", "12345"], ["0.01", "1"],
["1234", "123400"], ["¥ 1234.56 元", "123456"], ["1,23.45", null],
["123.456", null], ["-1.00", null], ["1e3", null], ["", null],
["已付123.45", null], ["1 234.56", null],
])("parses exact money without guessing %s", (input, expected) => {
expect(parseReceiptMinorUnits(input)).toBe(expected);
});
test("normalizes actual provider field aliases using synthetic values", () => {
const result = normalizeBankSlip(fields());
expect(result).toMatchObject({ amount: "123456", currency: "CNY",
payerAccount: "000011112222", payeeAccount: "000033334444",
transactionStatus: "success", reference: "SYN-0001", issues: [] });
});
test("does not use fees or uppercase text as transaction amount", () => {
const result = normalizeBankSlip(fields({ 小写金额: "", 手续费: "1234.56", 大写金额: "壹仟贰佰叁拾肆元伍角陆分" }));
expect(result.amount).toBeNull();
});
test("conflicting aliases are not silently resolved", () => {
const result = normalizeBankSlip(fields({ 交易金额: "999.00" }));
expect(result.amount).toBeNull();
expect(result.issues).toContain("amount_ambiguous");
});
test("repeated semantic fields may represent multiple receipts on one page", () => {
const result = normalizeBankSlip([...fields(), ...fields()]);
expect(result.issues).toContain("amount_ambiguous");
});
test.each(["已受理", "交易成功处理中", "未成功", "", "已打印"])("does not infer payment success from %s", (status) => {
expect(normalizeBankSlip(fields({ 单据状态: status })).transactionStatus).not.toBe("success");
});
test("masked accounts stay unresolved", () => {
expect(normalizeBankSlip(fields({ 收款人账号: "****4444" })).payeeAccount).toBeNull();
});
test("invalid response does not become an empty successful receipt", () => {
expect(normalizeBankSlip(null).issues).toContain("response_invalid");
});
});
describe("bank receipt candidate matching", () => {
test("matches one exact transaction but does not declare bank verification", () => {
expect(matchBankSlip(normalizeBankSlip(fields()), candidates()))
.toEqual({ status: "matched", itemId: "synthetic-item", reasons: [], bankVerified: false });
});
test.each([
[{ 小写金额: "1234.55" }, "amount_mismatch"],
[{ 收款人账号: "999933334444" }, "payee_account_mismatch"],
[{ 付款人账号: "999911112222" }, "payer_account_mismatch"],
[{ 币别: "USD" }, "currency_mismatch"],
])("blocks a known mismatch", (overrides, reason) => {
const result = matchBankSlip(normalizeBankSlip(fields(overrides)), candidates());
expect(result.status).toBe("mismatch");
expect(result.reasons).toContain(reason);
});
test.each(["交易失败", "已撤销", "已冲正", "已退汇"])("blocks %s", (status) => {
expect(matchBankSlip(normalizeBankSlip(fields({ 单据状态: status })), candidates()).status).toBe("mismatch");
});
test.each(["已受理", "未知", ""])("requires review for status %s", (status) => {
expect(matchBankSlip(normalizeBankSlip(fields({ 单据状态: status })), candidates()).status).toBe("needs_review");
});
test("requires a transaction reference for downstream duplicate protection", () => {
expect(matchBankSlip(normalizeBankSlip(fields({ 凭证号: "" })), candidates()).reasons).toContain("reference_unresolved");
});
test("same-account same-amount items require disambiguation", () => {
expect(matchBankSlip(normalizeBankSlip(fields()), [...candidates(), { ...candidates()[0], id: "second-item" }]).status)
.toBe("needs_review");
});
test("does not match receipt against combined batch total", () => {
const items = [ { ...candidates()[0], amount: "600.00" }, { ...candidates()[0], id: "second-item", amount: "634.56" } ];
expect(matchBankSlip(normalizeBankSlip(fields()), items).status).toBe("mismatch");
});
test("does not match missing expected accounts", () => {
expect(matchBankSlip(normalizeBankSlip(fields()), [{ ...candidates()[0], payerAccount: null }]).status)
.toBe("needs_review");
});
test("does not return receipt values in public matching results", () => {
const result = matchBankSlip(normalizeBankSlip(fields()), candidates());
expect(JSON.stringify(result)).not.toContain("000011112222");
expect(JSON.stringify(result)).not.toContain("SYN-0001");
});
});
@@ -0,0 +1,87 @@
const { PDFDocument } = require("pdf-lib");
const sharp = require("sharp");
const { recognizePaymentReceipt } = require("../../../src/services/paymentReceiptOcr");
async function pdfBuffer(pages = 1) {
const pdf = await PDFDocument.create();
for (let page = 0; page < pages; page += 1) pdf.addPage();
return Buffer.from(await pdf.save());
}
function providerResult() {
return { BankSlipInfos: Object.entries({
小写金额: "10.00", 币别: "人民币", 付款人账号: "000011112222",
收款人账号: "000033334444", 单据状态: "交易成功", 凭证号: "SYN-REFERENCE",
}).map(([Name, Value]) => ({ Name, Value })), RequestId: "not-persisted", RawSensitive: "not-persisted" };
}
describe("dedicated payment receipt OCR", () => {
test("processes every PDF page without public URLs or invoice writes", async () => {
const BankSlipOCR = vi.fn().mockResolvedValue(providerResult());
const result = await recognizePaymentReceipt({
buffer: await pdfBuffer(2), mimeType: "application/pdf", createClient: () => ({ BankSlipOCR }),
});
expect(result).toMatchObject({ status: "recognized", pagesExpected: 2, pagesProcessed: 2 });
expect(BankSlipOCR).toHaveBeenCalledTimes(2);
expect(BankSlipOCR.mock.calls.map(([request]) => request.PdfPageNumber)).toEqual([1, 2]);
expect(BankSlipOCR.mock.calls.every(([request]) => request.ImageUrl === undefined)).toBe(true);
expect(result.pages[0].amount).toBe("1000");
expect(JSON.stringify(result)).not.toContain("not-persisted");
});
test("does not claim completeness after a later page fails or retry automatically", async () => {
const BankSlipOCR = vi.fn().mockResolvedValueOnce(providerResult()).mockRejectedValueOnce(new Error("sensitive error"));
const result = await recognizePaymentReceipt({
buffer: await pdfBuffer(2), mimeType: "application/pdf", createClient: () => ({ BankSlipOCR }),
});
expect(result).toMatchObject({ status: "ocr_failed", pagesExpected: 2, pagesProcessed: 1, reason: "receipt_ocr_request_failed" });
expect(BankSlipOCR).toHaveBeenCalledTimes(2);
expect(JSON.stringify(result)).not.toContain("sensitive error");
});
test("preserves unknown fields as unresolved rather than success", async () => {
const result = await recognizePaymentReceipt({
buffer: await pdfBuffer(), mimeType: "application/pdf",
createClient: () => ({ BankSlipOCR: async () => ({ BankSlipInfos: [] }) }),
});
expect(result.status).toBe("needs_review");
expect(result.pages[0].issues).toContain("response_invalid");
});
test("rejects invalid PDF before creating cloud client", async () => {
const createClient = vi.fn();
const result = await recognizePaymentReceipt({ buffer: Buffer.from("not pdf"), mimeType: "application/pdf", createClient });
expect(result.reason).toBe("receipt_decode_failed");
expect(createClient).not.toHaveBeenCalled();
});
test("limits pages before any external call", async () => {
const createClient = vi.fn();
const result = await recognizePaymentReceipt({ buffer: await pdfBuffer(21), mimeType: "application/pdf", createClient });
expect(result.reason).toBe("receipt_page_limit");
expect(createClient).not.toHaveBeenCalled();
});
test("converts existing WEBP uploads to supported PNG in memory", async () => {
const buffer = await sharp({ create: { width: 10, height: 10, channels: 3, background: "white" } }).webp().toBuffer();
const BankSlipOCR = vi.fn().mockResolvedValue(providerResult());
const result = await recognizePaymentReceipt({ buffer, mimeType: "image/webp", createClient: () => ({ BankSlipOCR }) });
expect(result.status).toBe("recognized");
expect(BankSlipOCR.mock.calls[0][0].IsPdf).toBe(false);
const sent = Buffer.from(BankSlipOCR.mock.calls[0][0].ImageBase64, "base64");
expect((await sharp(sent).metadata()).format).toBe("png");
});
test("missing credentials do not silently disable OCR", async () => {
const result = await recognizePaymentReceipt({ buffer: await pdfBuffer(), mimeType: "application/pdf", config: {} });
expect(result).toMatchObject({ status: "ocr_failed", reason: "receipt_ocr_unavailable" });
});
test.each(["off", "mock"])("provider %s never falls through to real Tencent", async (ocrProvider) => {
const result = await recognizePaymentReceipt({
buffer: await pdfBuffer(), mimeType: "application/pdf",
config: { ocrProvider, tencentSecretId: "synthetic", tencentSecretKey: "synthetic" },
});
expect(result).toMatchObject({ status: "ocr_failed", reason: "receipt_ocr_unavailable" });
});
});
@@ -0,0 +1,157 @@
const { createHash } = require("node:crypto");
const { encryptStringOrThrow } = require("../../../src/services/crypto");
const { claimReceiptJob, runReceiptOcrOnce, startReceiptOcrJob, startReceiptPgBossJob } = require("../../../src/jobs/paymentReceiptOcrJob");
test("cron serializes ticks locally and removes timer on close", async () => {
const cron = require("node-cron");
let callback;
let onClose;
let release;
const task = { stop: vi.fn(), destroy: vi.fn() };
const schedule = vi.spyOn(cron, "schedule").mockImplementation((expression, handler) => { callback = handler; return task; });
const transaction = vi.fn(() => new Promise((resolve) => { release = resolve; }));
try {
startReceiptOcrJob({ config: { ocrPollCron: "* * * * *" }, prisma: { $transaction: transaction },
log: { warn: vi.fn() }, addHook: (name, handler) => { onClose = handler; } });
const running = callback();
await callback();
expect(transaction).toHaveBeenCalledTimes(1);
release(null);
await running;
await onClose();
expect(task.stop).toHaveBeenCalledTimes(1);
expect(task.destroy).toHaveBeenCalledTimes(1);
} finally { schedule.mockRestore(); }
});
test("pg-boss uses a separate receipt queue with no automatic request retry", async () => {
const boss = { createQueue: vi.fn(), work: vi.fn(), schedule: vi.fn() };
await startReceiptPgBossJob({ config: { ocrPollCron: "* * * * *", appTimezone: "Asia/Shanghai" } }, boss);
expect(boss.createQueue).toHaveBeenCalledWith("payment.receipt.ocr", { retryLimit: 0, expireInSeconds: 900 });
expect(boss.work).toHaveBeenCalledWith("payment.receipt.ocr", { batchSize: 1 }, expect.any(Function));
expect(boss.schedule.mock.calls[0][3]).toMatchObject({ retryLimit: 0, singletonKey: "payment.receipt.ocr" });
});
function fixture() {
const config = { fieldEncryptionKey: Buffer.alloc(32, 7).toString("base64") };
const buffer = Buffer.from("synthetic-pdf");
const attachment = { id: "attachment", payment_batch_id: "batch", receipt_ocr_version: 1,
file_size: buffer.length, file_sha256: createHash("sha256").update(buffer).digest("hex"),
mime_type: "application/pdf", storage_path: "private-synthetic", governance_status: "approved" };
const tx = {
$queryRaw: vi.fn().mockResolvedValue([{ id: "batch" }]),
paymentBatchReceiptAttachment: { update: vi.fn().mockResolvedValue(attachment), updateMany: vi.fn(),
findUnique: vi.fn().mockResolvedValue(attachment) },
paymentBatch: { findUnique: vi.fn().mockResolvedValue({ id: "batch", status: "reviewed", entity_type: "reimbursement",
payment_account_snapshot_json: { bankInstitutionCode: "CCB", accountNumberEncrypted: encryptStringOrThrow(config, "000011112222") },
items: [{ id: "item", status: "pending", amount: "10.00", currency_code: "CNY",
snapshot_json: { payee: { bankInstitutionCode: "CCB", bankAccountEncrypted: encryptStringOrThrow(config, "000033334444") } } }] }) },
paymentReceiptVerification: { create: vi.fn().mockResolvedValue({ id: "verification", status: "needs_review" }) },
};
const prisma = { $transaction: vi.fn((callback) => callback(tx)) };
const readBuffer = vi.fn().mockResolvedValue(buffer);
const recognize = vi.fn().mockResolvedValue({ status: "needs_review", pagesExpected: 1, pagesProcessed: 1, pages: [] });
return { prisma, config, readBuffer, recognize, tx, attachment };
}
test("idle workers do not read files or call OCR", async () => {
const args = fixture();
args.tx.$queryRaw.mockResolvedValue([]);
expect(await runReceiptOcrOnce(args)).toEqual({ status: "idle" });
expect(args.readBuffer).not.toHaveBeenCalled();
expect(args.recognize).not.toHaveBeenCalled();
});
test.each([
{ entity_type: "travel_order", default_payment_channel: "bank", items: [{ status: "pending" }] },
{ entity_type: "reimbursement", default_payment_channel: "cash", items: [{ status: "pending" }] },
{ entity_type: "reimbursement", items: [{ status: "executed" }] },
])("out-of-scope queued receipts never read files or call OCR: %j", async (batch) => {
const args = fixture();
args.tx.paymentBatch.findUnique.mockResolvedValue({ id: "batch", ...batch });
expect(await runReceiptOcrOnce(args)).toEqual({ status: "idle" });
expect(args.readBuffer).not.toHaveBeenCalled();
expect(args.recognize).not.toHaveBeenCalled();
expect(args.tx.paymentBatchReceiptAttachment.update).not.toHaveBeenCalled();
expect(args.tx.paymentBatchReceiptAttachment.updateMany).toHaveBeenCalledWith({
where: { payment_batch_id: "batch", receipt_ocr_state: "queued" }, data: { receipt_ocr_state: "legacy" },
});
});
test("claim marks processing and increments version in the transaction", async () => {
const args = fixture();
await claimReceiptJob(args.prisma);
expect(args.tx.paymentBatchReceiptAttachment.update.mock.calls[0][0].data)
.toMatchObject({ receipt_ocr_state: "processing", receipt_ocr_version: { increment: 1 } });
});
test("successful processing stores a result without raw file values in response", async () => {
const args = fixture();
expect(await runReceiptOcrOnce(args)).toEqual({ status: "needs_review" });
expect(args.recognize).toHaveBeenCalledTimes(1);
expect(args.tx.paymentReceiptVerification.create).toHaveBeenCalledTimes(1);
});
test("file mismatch prevents external transmission", async () => {
const args = fixture();
args.attachment.file_sha256 = "a".repeat(64);
expect(await runReceiptOcrOnce(args)).toEqual({ status: "ocr_failed" });
expect(args.recognize).not.toHaveBeenCalled();
});
test("provider errors are not leaked or automatically retried", async () => {
const args = fixture();
args.recognize.mockRejectedValue(new Error("sensitive-provider-value"));
expect(await runReceiptOcrOnce(args)).toEqual({ status: "ocr_failed" });
expect(args.recognize).toHaveBeenCalledTimes(1);
});
test("superseded result cannot update job state", async () => {
const args = fixture();
args.tx.paymentBatchReceiptAttachment.findUnique.mockResolvedValue({ ...args.attachment, receipt_ocr_version: 2 });
expect(await runReceiptOcrOnce(args)).toEqual({ status: "discarded" });
expect(args.tx.paymentReceiptVerification.create).not.toHaveBeenCalled();
expect(args.tx.paymentBatchReceiptAttachment.update).toHaveBeenCalledTimes(1);
});
test.each([
["receipt_key_unavailable", "key_failed"],
["receipt_bank_unsupported", "snapshot_failed"],
["unknown", "system_failed"],
])("persistence error %s records safe terminal state %s", async (code, state) => {
const args = fixture();
args.tx.paymentReceiptVerification.create.mockRejectedValue(Object.assign(new Error("sensitive"), { code }));
args.tx.paymentBatchReceiptAttachment.updateMany.mockResolvedValue({ count: 1 });
expect(await runReceiptOcrOnce(args)).toEqual({ status: state });
expect(args.tx.paymentBatchReceiptAttachment.updateMany).toHaveBeenCalledWith({
where: { id: args.attachment.id, payment_batch_id: args.attachment.payment_batch_id,
receipt_ocr_version: 1, file_sha256: args.attachment.file_sha256,
receipt_ocr_state: "processing", archived_at: null, governance_status: "approved" },
data: { receipt_ocr_state: state },
});
expect(args.recognize).toHaveBeenCalledTimes(1);
});
test("missing key is persisted before any file read or cloud call", async () => {
const args = fixture();
args.config = {};
args.tx.paymentBatchReceiptAttachment.updateMany.mockResolvedValue({ count: 1 });
expect(await runReceiptOcrOnce(args)).toEqual({ status: "key_failed" });
expect(args.readBuffer).not.toHaveBeenCalled();
expect(args.recognize).not.toHaveBeenCalled();
});
test("late failure cannot overwrite a changed attachment", async () => {
const args = fixture();
args.tx.paymentReceiptVerification.create.mockRejectedValue(new Error("synthetic"));
args.tx.paymentBatchReceiptAttachment.updateMany.mockResolvedValue({ count: 0 });
expect(await runReceiptOcrOnce(args)).toEqual({ status: "discarded" });
});
test("failure recording outage is reported without claiming persistence", async () => {
const args = fixture();
args.tx.paymentReceiptVerification.create.mockRejectedValue(new Error("sensitive"));
args.tx.paymentBatchReceiptAttachment.updateMany.mockRejectedValue(new Error("sensitive-db"));
expect(await runReceiptOcrOnce(args)).toEqual({ status: "failure_recording_failed" });
expect(args.recognize).toHaveBeenCalledTimes(1);
});
@@ -0,0 +1,139 @@
const { encryptStringOrThrow, decryptStringOrThrow } = require("../../../src/services/crypto");
const { normalizeBankSlip } = require("../../../src/services/paymentReceiptMatching");
const { buildVerificationData, claimVerifiedReceipts, transactionFingerprint, canRetryReceiptRecognition } = require("../../../src/services/paymentReceiptVerification");
const config = { fieldEncryptionKey: Buffer.alloc(32, 7).toString("base64") };
function fixture() {
const page = { pageNumber: 1, ...normalizeBankSlip(Object.entries({
小写金额: "10.00", 币别: "人民币", 付款人账号: "000011112222",
收款人账号: "000033334444", 单据状态: "交易成功", 凭证号: "SYN-REF",
}).map(([Name, Value]) => ({ Name, Value }))) };
const batch = {
id: "batch", entity_type: "reimbursement",
payment_account_snapshot_json: { bankInstitutionCode: "CCB", accountNumberEncrypted: encryptStringOrThrow(config, page.payerAccount) },
items: [{ id: "item", status: "pending", amount: "10.00", currency_code: "CNY",
snapshot_json: { payee: { bankInstitutionCode: "CCB", bankAccountEncrypted: encryptStringOrThrow(config, page.payeeAccount) } } }],
};
const attachment = { id: "attachment", payment_batch_id: batch.id, file_sha256: "a".repeat(64), governance_status: "approved", archived_at: null, receipt_ocr_version: 0 };
const recognition = { status: "recognized", pagesExpected: 1, pagesProcessed: 1, pages: [page] };
const data = buildVerificationData(config, batch, attachment, recognition);
const verification = { ...data, id: "verification", attachment, matches: data.matches.create };
const tx = {
$queryRaw: vi.fn().mockResolvedValue([{ id: attachment.id }]),
paymentReceiptVerification: { findFirst: vi.fn().mockResolvedValue(verification) },
paymentReceiptClaim: { count: vi.fn().mockResolvedValue(0), findMany: vi.fn().mockResolvedValue([]), create: vi.fn() },
paymentReceiptTransactionAlias: { count: vi.fn().mockResolvedValue(0), findMany: vi.fn().mockResolvedValue([]), create: vi.fn() },
paymentReceiptManualProposal: { findMany: vi.fn().mockResolvedValue([]) },
};
return { batch, attachment, recognition, data, verification, tx };
}
describe("receipt evidence and transaction claims", () => {
test("mixed historical cash items do not require bank snapshots or bank receipt claims", async () => {
const { batch, attachment, recognition, tx } = fixture();
batch.items.push({ id: "cash-item", status: "pending", amount: "10.00", currency_code: "CNY",
payment_channel_override: "cash", snapshot_json: {} });
expect(buildVerificationData(config, batch, attachment, recognition).status).toBe("matched");
await claimVerifiedReceipts(tx, config, batch);
expect(tx.paymentReceiptClaim.create).toHaveBeenCalledTimes(1);
expect(tx.paymentReceiptClaim.create.mock.calls[0][0].data.item_id).toBe("item");
});
test.each([[899999, false], [900000, true], [900001, true]])("retry becomes available only at timeout %s", (age, allowed) => {
const now = new Date("2026-09-14T00:00:00Z");
const attachment = { receipt_ocr_state: "processing", governance_status: "approved",
receipt_ocr_started_at: new Date(now.getTime() - age) };
expect(canRetryReceiptRecognition(attachment, now)).toBe(allowed);
expect(canRetryReceiptRecognition({ ...attachment, archived_at: now }, now)).toBe(false);
});
test("stores only encrypted normalized evidence and keyed transaction identity", () => {
const { data, recognition } = fixture();
expect(JSON.stringify(data)).not.toContain("000011112222");
expect(JSON.stringify(data)).not.toContain("SYN-REF");
expect(JSON.parse(decryptStringOrThrow(config, data.normalized_encrypted))).toEqual(recognition);
expect(data.matches.create[0].fingerprint).toMatch(/^[a-f0-9]{64}$/);
});
test("transaction identity is independent of file, amount and payee", () => {
const { recognition } = fixture();
const page = recognition.pages[0];
expect(transactionFingerprint(config, page)).toEqual(transactionFingerprint(config, { ...page, amount: "2000", payeeAccount: "999999999999" }));
expect(transactionFingerprint(config, page)).not.toEqual(transactionFingerprint(config, { ...page, payerAccount: "999999999999" }));
});
test("does not persist extra provider response fields even encrypted", () => {
const { batch, attachment, recognition } = fixture();
const data = buildVerificationData(config, batch, attachment, { ...recognition, RawSensitive: "provider-extra" });
expect(decryptStringOrThrow(config, data.normalized_encrypted)).not.toContain("provider-extra");
});
test("does not match partial pages", () => {
const { batch, attachment, recognition } = fixture();
expect(buildVerificationData(config, batch, attachment, { ...recognition, pagesExpected: 2 }).status).toBe("needs_review");
});
test("requires different items and transaction identities across pages", () => {
const { batch, attachment, recognition } = fixture();
const duplicated = { ...recognition, pagesExpected: 2, pagesProcessed: 2,
pages: [recognition.pages[0], { ...recognition.pages[0], pageNumber: 2 }] };
expect(buildVerificationData(config, batch, attachment, duplicated).status).toBe("needs_review");
});
test("claims a verified item inside supplied transaction", async () => {
const { tx, batch } = fixture();
await claimVerifiedReceipts(tx, config, batch);
expect(tx.paymentReceiptClaim.create).toHaveBeenCalledTimes(1);
expect(tx.paymentReceiptClaim.create.mock.calls[0][0].data.item_id).toBe("item");
expect(tx.$queryRaw).toHaveBeenCalledTimes(2);
});
test("idempotent claim does not insert again", async () => {
const { tx, batch, verification } = fixture();
tx.paymentReceiptClaim.findMany.mockResolvedValue([verification.matches[0]]);
await claimVerifiedReceipts(tx, config, batch);
expect(tx.paymentReceiptClaim.create).not.toHaveBeenCalled();
});
test("cannot reuse transaction in another item or batch", async () => {
const { tx, batch, verification } = fixture();
tx.paymentReceiptClaim.findMany.mockResolvedValue([{ ...verification.matches[0], item_id: "other-item" }]);
await expect(claimVerifiedReceipts(tx, config, batch)).rejects.toMatchObject({ code: "receipt_transaction_reused" });
expect(tx.paymentReceiptClaim.create).not.toHaveBeenCalled();
});
test("key rotation cannot bypass historical duplicate detection", async () => {
const { tx, batch } = fixture();
tx.paymentReceiptClaim.count.mockResolvedValue(1);
await expect(claimVerifiedReceipts(tx, config, batch)).rejects.toMatchObject({ code: "receipt_key_rotation_required" });
expect(tx.paymentReceiptClaim.create).not.toHaveBeenCalled();
});
test.each(["archived", "quarantined", "hash_changed", "latest_failed"])("rejects unavailable evidence: %s", async (reason) => {
const { tx, batch, verification } = fixture();
if (reason === "archived") verification.attachment.archived_at = new Date();
if (reason === "quarantined") verification.attachment.governance_status = "quarantined";
if (reason === "hash_changed") verification.attachment.file_sha256 = "b".repeat(64);
if (reason === "latest_failed") verification.status = "needs_review";
await expect(claimVerifiedReceipts(tx, config, batch)).rejects.toMatchObject({ code: "receipt_verification_required" });
expect(tx.paymentReceiptClaim.create).not.toHaveBeenCalled();
});
test("re-evaluates frozen amount rather than trusting persisted matched flag", async () => {
const { tx, batch } = fixture();
batch.items[0].amount = "11.00";
await expect(claimVerifiedReceipts(tx, config, batch)).rejects.toMatchObject({ code: "receipt_match_changed" });
});
test("checks persisted fingerprint against encrypted evidence", async () => {
const { tx, batch, verification } = fixture();
verification.matches[0].fingerprint = "f".repeat(64);
await expect(claimVerifiedReceipts(tx, config, batch)).rejects.toMatchObject({ code: "receipt_match_changed" });
});
test("does not reopen already executed items", async () => {
const { tx, batch } = fixture();
batch.items[0].status = "executed";
await claimVerifiedReceipts(tx, config, batch);
expect(tx.$queryRaw).not.toHaveBeenCalled();
});
});