完善付款回单凭证核验与本地重检(09-17-company-loan-principal-repayment)

区分正式付款回单、非最终回执与未知凭证,在核验构建、人工证据重建和最终核销时使用同一份有效依据。非最终说明、入账方向、状态矛盾及重复交易不能经人工覆盖。

正式回单无字面成功状态时,允许财务按原件实际记账支出、日期及说明提出核验,由本批次适用的确认人确认;不补造银行成功文字。旧核验可显式本地重检,新版本与审计原子保存,不重新外发 OCR,不沿用旧人工批准或改写已核销历史。

本地验证:82 个迁移、借款 HTTP 116 组、关联电脑/手机 18 组、共享回单数据库与真实认证 38 组、共享报销页面限定重验 24 项、最新回单/报销定向 292 项通过;9 个资金守卫变异均被捕获。服务端全量 4554 项通过、1 项既有可选跳过,后续合成数据及零页详情改动由最新定向验证覆盖。

本次无新增迁移,新增本地 PDF 文本解析依赖。后续对本提交运行完整 verify-candidate,实际候选与结果以本轮回执为准。

限制:独立代码复核及真实还款验收待完成;历史材料预验不证明真实还本或银行提交对应。未推送、未部署、未访问生产或写入真实业务数据。
这个提交包含在:
2026-10-09 06:18:09 +08:00
父节点 ce11dea976
当前提交 5a7a13524e
共修改 31 个文件,包含 1325 行新增和 49 行删除
+2
查看文件
@@ -803,6 +803,8 @@ export const ERROR_REASON_MESSAGES: Record<string, string> = {
"payment_batch.receipt_transaction_reused": "回单交易已被使用或存在重复,请核对原回单;不能通过修改参考号重复登记。",
"payment_batch.receipt_manual_state_changed": "回单或核验版本已变化,请刷新后重新查看当前状态。",
"payment_batch.receipt_manual_verification_required": "回单信息尚不能确认与付款一致,请核对全部页、交易状态、金额、币种及收付款账号;不要直接登记付款。",
"payment_batch.receipt_document_check_required": "这份回单尚未检查凭证性质,请在核验详情中更新凭证核验后重新核对。",
"payment_batch.receipt_final_evidence_required": "当前材料不能证明本笔付款已完成。请核对正式回单的实际付款或记账依据;非最终回执、入账方向不符或证据不明时不能登记付款。",
"payment_batch.receipt_key_unavailable": "回单核验密钥不可用,请联系管理员修复;不要重复识别或登记付款。",
"payment_batch.receipt_key_rotation_required": "回单交易记录使用的密钥版本不一致,请管理员完成受控密钥迁移;人工核验不能绕过。",
"payment_batch.receipt_snapshot_unsupported": "付款业务或银行快照不支持回单核验,请联系管理员核实;不要重复识别。",
+27 -1
查看文件
@@ -293,6 +293,23 @@ export async function retryPaymentBatchReceiptOcr(batchId: string, attachmentId:
);
}
export type ReceiptPaymentProof = {
basis: "explicit_success" | "booked_debit";
originalChecked: true;
note: string;
bookedOn?: string;
};
export type ReceiptDocumentEvidence = {
version: number;
kind: "bank_receipt" | "non_final" | "unknown";
source: "pdf_text" | "image" | "unreadable" | "manual";
direction: "debit" | "credit" | null;
explicitSuccess: boolean;
issues: string[];
proof?: ReceiptPaymentProof;
};
export type ReceiptVerificationPage = {
pageNumber: number;
amount: string | null;
@@ -302,10 +319,12 @@ export type ReceiptVerificationPage = {
transactionStatus: string | null;
reference: string | null;
itemId?: string;
document?: ReceiptDocumentEvidence | null;
};
export type ReceiptVerificationDetail = {
canReview?: boolean;
documentInspectionRequired?: boolean;
version: number;
state: string;
pagesExpected: number;
@@ -331,7 +350,7 @@ export function fetchReceiptReadiness(batchId: string, signal?: AbortSignal) {
export function saveReceiptVerification(batchId: string, attachmentId: string, body: {
expectedVersion: number; reason?: string;
pages: { pageNumber: number; itemId: string; fields?: { Name: string; Value: string }[] }[];
pages: { pageNumber: number; itemId: string; fields?: { Name: string; Value: string }[]; paymentProof?: ReceiptPaymentProof }[];
}) {
return apiRequestData<{ item: { id: string; status: string; version: number } }>(
`/api/payment-batches/${batchId}/receipt-attachments/${attachmentId}/manual-verification`,
@@ -339,6 +358,13 @@ export function saveReceiptVerification(batchId: string, attachmentId: string, b
);
}
export function checkReceiptDocument(batchId: string, attachmentId: string, expectedVersion: number) {
return apiRequestData<{ item: { id: string; status: string; version: number } }>(
`/api/payment-batches/${batchId}/receipt-attachments/${attachmentId}/document-check`,
{ method: "POST", body: JSON.stringify({ expectedVersion }) },
);
}
export function reviewReceiptVerification(batchId: string, attachmentId: string, proposalId: string, body: {
expectedVersion: number; decision: "approve" | "reject"; reason: string;
}) {
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
fetchReceiptVerification, saveReceiptVerification, reviewReceiptVerification,
fetchReceiptVerification, saveReceiptVerification, reviewReceiptVerification, checkReceiptDocument,
type ReceiptVerificationPage,
} from "../../api/paymentBatches";
import { resolveErrorMessage } from "../../lib/resolveErrorMessage";
@@ -13,7 +13,7 @@ import { Textarea } from "../ui/textarea";
const FIELD_NAMES = ["小写金额", "币别", "付款人账号", "收款人账号", "凭证号", "单据状态"] as const;
const CHANGE_LABELS: Record<string, string> = {
amount: "金额", currency: "币种", payerAccount: "付款账号", payeeAccount: "收款账号",
reference: "交易参考", transactionStatus: "交易状态",
reference: "交易参考", transactionStatus: "交易状态", paymentProof: "付款凭证依据",
};
function PageFacts({ page }: { page?: ReceiptVerificationPage }) {
@@ -22,7 +22,11 @@ function PageFacts({ page }: { page?: ReceiptVerificationPage }) {
<div>付款账号:{page?.payerAccountMasked ?? "未识别"}</div>
<div>收款账号:{page?.payeeAccountMasked ?? "未识别"}</div>
<div>交易参考:{page?.reference ?? "未识别"}</div>
<div>状态:{{ success: "成功", failed: "失败", pending: "受理或处理中" }[page?.transactionStatus ?? ""] ?? "未确认"}</div>
<div>状态:{page?.document?.proof?.basis === "booked_debit" ? "已记账支出(人工核对)" :
({ success: "成功", failed: "失败", pending: "受理或处理中" }[page?.transactionStatus ?? ""] ?? "未确认")}</div>
<div>凭证性质:{{ bank_receipt: "银行正式回单", non_final: "非最终回执", unknown: "需核对原件" }[page?.document?.kind ?? "unknown"]}</div>
{page?.document?.proof ? <div>付款依据:{page.document.proof.basis === "booked_debit" ?
`正式回单记载已记账支出,记账日期 ${page.document.proof.bookedOn}` : "正式回单原件明确显示付款成功"}</div> : null}
</div>;
}
@@ -40,6 +44,7 @@ export function PaymentReceiptVerificationDialog(props: Props) {
const [editing, setEditing] = useState<Record<number, boolean>>({});
const [changes, setChanges] = useState<Record<number, Record<string, string>>>({});
const [reason, setReason] = useState("");
const [proofs, setProofs] = useState<Record<number, { basis: "" | "explicit_success" | "booked_debit"; bookedOn: string; checked: boolean }>>({});
const query = useQuery({
queryKey: ["receipt-verification", props.actorId, props.batchId, props.attachmentId],
queryFn: ({ signal }) => fetchReceiptVerification(props.batchId, props.attachmentId, signal),
@@ -59,7 +64,14 @@ export function PaymentReceiptVerificationDialog(props: Props) {
const pageNumber = index + 1;
const fields = Object.entries(changes[pageNumber] ?? {}).filter(([, value]) => value.trim())
.map(([Name, Value]) => ({ Name, Value }));
return { pageNumber, itemId: selections[pageNumber] ?? "", ...(fields.length ? { fields } : {}) };
const proof = proofs[pageNumber];
if (proof?.basis === "booked_debit") {
const status = fields.find((field) => field.Name === "单据状态");
if (status) status.Value = ""; else fields.push({ Name: "单据状态", Value: "" });
}
return { pageNumber, itemId: selections[pageNumber] ?? "", ...(fields.length ? { fields } : {}),
...(proof?.basis ? { paymentProof: { basis: proof.basis, originalChecked: true as const, note: reason.trim(),
...(proof.basis === "booked_debit" ? { bookedOn: proof.bookedOn } : {}) } } : {}) };
}),
}),
onSuccess: changed,
@@ -71,15 +83,26 @@ export function PaymentReceiptVerificationDialog(props: Props) {
),
onSuccess: changed,
});
const busy = save.isPending || review.isPending;
const inspect = useMutation({
mutationFn: () => checkReceiptDocument(props.batchId, props.attachmentId, detail!.version),
onSuccess: changed,
});
const busy = save.isPending || review.isPending || inspect.isPending;
const pageCount = detail && Number.isInteger(detail.pagesExpected) && detail.pagesExpected > 0 &&
detail.pagesExpected <= 20 ? detail.pagesExpected : 0;
const editable = props.canManage && detail && ["needs_review", "ocr_failed"].includes(detail.state) && !query.isError;
const editable = props.canManage && detail && !detail.documentInspectionRequired && ["needs_review", "ocr_failed"].includes(detail.state) && !query.isError;
const reviewable = props.canReview && detail?.canReview === true && detail?.proposal?.status === "pending_review" &&
props.actorId !== detail.proposal.proposedBy && props.actorId !== props.makerId && !query.isError;
const complete = pageCount > 0 && Array.from({ length: pageCount }, (_unused, index) => selections[index + 1]).every(Boolean);
const blocked = (page?: ReceiptVerificationPage) => page?.document?.kind === "non_final" ||
page?.document?.direction === "credit" || Boolean(page?.document?.issues.length);
const needsProof = (page?: ReceiptVerificationPage) => page?.document?.kind !== "bank_receipt" || !page.document.explicitSuccess;
const complete = pageCount > 0 && Array.from({ length: pageCount }, (_unused, index) => {
const n = index + 1; const page = detail?.pages.find((entry) => entry.pageNumber === n); const proof = proofs[n];
return selections[n] && !blocked(page) && (!needsProof(page) || (proof?.basis && proof.checked &&
reason.trim().length >= 5 && (proof.basis !== "booked_debit" || /^\d{4}-\d{2}-\d{2}$/.test(proof.bookedOn))));
}).every(Boolean);
const hasCorrections = Object.values(changes).some((fields) => Object.values(fields).some((value) => value.trim()));
const error = query.error ?? save.error ?? review.error;
const error = query.error ?? save.error ?? review.error ?? inspect.error;
return <Dialog open onOpenChange={(open) => { if (!open && !busy) props.onClose(); }}>
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-2xl">
<DialogHeader>
@@ -90,10 +113,15 @@ export function PaymentReceiptVerificationDialog(props: Props) {
{error ? <div role="alert" className="space-y-2 text-sm text-red-600">
<p>{resolveErrorMessage(error)}</p>
<Button variant="secondary" disabled={busy} onClick={() => {
setSelections({}); setChanges({}); setEditing({}); setReason(""); save.reset(); review.reset();
setSelections({}); setChanges({}); setEditing({}); setProofs({}); setReason(""); save.reset(); review.reset(); inspect.reset();
void query.refetch();
}}>刷新核验信息</Button>
</div> : null}
{detail?.documentInspectionRequired ? <div role="status" className="space-y-2 rounded-lg border p-3 text-sm">
<p>旧核验尚未记录凭证性质。更新后会保留原记录,并要求重新核对原件;不会重新发送文件识别。</p>
{props.canManage && !query.isError ? <Button variant="secondary" disabled={busy || query.isFetching}
onClick={() => inspect.mutate()}>{inspect.isPending ? "检查中…" : "更新凭证核验"}</Button> : null}
</div> : null}
{detail && !pageCount ? <p role="status">尚无完整页数,请先重新识别或上传可读取的原回单。</p> : null}
{Array.from({ length: pageCount }, (_unused, index) => index + 1).map((pageNumber) => {
const original = detail?.pages.find((page) => page.pageNumber === pageNumber);
@@ -101,13 +129,14 @@ export function PaymentReceiptVerificationDialog(props: Props) {
return <section key={pageNumber} className="space-y-3 rounded-lg border p-3">
<h3 className="font-medium">第{pageNumber}页 · 原识别结果</h3>
<PageFacts page={original} />
{blocked(original) ? <p role="status" className="text-sm text-red-600">这份材料不能证明本笔付款完成。请提供对应的正式付款回单;不能通过更正字段覆盖非最终说明、收付方向或交易矛盾。</p> : null}
{proposed ? <div className="space-y-2 border-t pt-3">
<h4 className="font-medium">人工核验结果</h4>
<PageFacts page={proposed} />
<p className="text-sm">对应明细:{props.items.find((item) => item.id === proposed.itemId)?.label ?? "当前明细不可用"}</p>
<p className="text-sm">更正字段:{detail?.proposal?.changedFields.find((entry) => entry.pageNumber === pageNumber)?.fields.map((field) => CHANGE_LABELS[field] ?? "字段").join("、") || "未更正,仅关联"}</p>
</div> : null}
{editable ? <>
{editable && !blocked(original) ? <>
<label className="block space-y-1 text-sm">
<span>第{pageNumber}页对应付款明细</span>
<select className="min-h-11 w-full rounded-md border bg-white px-3" disabled={busy}
@@ -117,13 +146,39 @@ export function PaymentReceiptVerificationDialog(props: Props) {
{props.items.map((item) => <option key={item.id} value={item.id}>{item.label}</option>)}
</select>
</label>
{needsProof(original) ? <div className="space-y-3 rounded-md border p-3 text-sm">
<label className="block space-y-1">
<span>第{pageNumber}页付款凭证依据</span>
<select className="min-h-11 w-full rounded-md border bg-white px-3" disabled={busy}
value={proofs[pageNumber]?.basis ?? ""} onChange={(event) => setProofs((current) => ({ ...current,
[pageNumber]: { bookedOn: current[pageNumber]?.bookedOn ?? "", checked: false,
basis: event.target.value as "" | "explicit_success" | "booked_debit" } }))}>
<option value="">请先查看原件,再选择依据</option>
<option value="explicit_success">正式回单原件明确显示付款成功</option>
<option value="booked_debit">正式回单记载公司已记账支出</option>
</select>
</label>
{proofs[pageNumber]?.basis === "booked_debit" ? <label className="block space-y-1">
<span>第{pageNumber}页原件记账日期</span>
<Input type="date" disabled={busy} value={proofs[pageNumber]?.bookedOn ?? ""}
onChange={(event) => setProofs((current) => ({ ...current,
[pageNumber]: { ...current[pageNumber], bookedOn: event.target.value } }))} />
</label> : null}
<label className="flex min-h-11 items-start gap-2">
<input type="checkbox" className="mt-1" disabled={busy || !proofs[pageNumber]?.basis}
checked={proofs[pageNumber]?.checked ?? false} onChange={(event) => setProofs((current) => ({ ...current,
[pageNumber]: { ...current[pageNumber], checked: event.target.checked } }))} />
<span>已查看第{pageNumber}页完整原件,确认为本公司付款的正式回单,无非最终依据说明或矛盾;核验说明中填写原件依据。</span>
</label>
<p className="text-xs text-zinc-500">记账支出不要求补填“交易成功”。凭证性质或资金方向不能确认时,请先补证。</p>
</div> : null}
<Button type="button" variant="secondary" disabled={busy} onClick={() => {
setEditing((current) => ({ ...current, [pageNumber]: !current[pageNumber] }));
if (editing[pageNumber]) setChanges((current) => ({ ...current, [pageNumber]: {} }));
}}>{editing[pageNumber] ? "取消本页更正" : "更正识别"}</Button>
{editing[pageNumber] ? <div className="space-y-3">
<p className="text-xs text-zinc-500">只填写要更正的字段,其他字段保留原识别值。更正后需要{props.relatedParty ? "公司代表确认" : "独立复核"}。</p>
{FIELD_NAMES.map((name) => <label key={name} className="block space-y-1 text-sm">
{FIELD_NAMES.filter((name) => name !== "单据状态" || proofs[pageNumber]?.basis !== "booked_debit").map((name) => <label key={name} className="block space-y-1 text-sm">
<span>第{pageNumber}页更正{name}</span>
{name === "单据状态" ? <select className="min-h-11 w-full rounded-md border bg-white px-3"
disabled={busy} value={changes[pageNumber]?.[name] ?? ""} onChange={(event) =>
@@ -152,7 +207,7 @@ export function PaymentReceiptVerificationDialog(props: Props) {
onClick={() => save.mutate()}>{save.isPending ? "保存中…" : "保存核验"}</Button> : null}
{reviewable ? <>
<Button variant="secondary" disabled={busy || query.isFetching || !reason.trim()} onClick={() => review.mutate("reject")}>不通过</Button>
<Button disabled={busy || query.isFetching || !reason.trim()} onClick={() => review.mutate("approve")}>{props.relatedParty ? "公司代表确认" : "确认复核"}</Button>
<Button disabled={busy || query.isFetching || !reason.trim() || detail?.documentInspectionRequired || detail?.pages.some(blocked)} onClick={() => review.mutate("approve")}>{props.relatedParty ? "公司代表确认" : "确认复核"}</Button>
</> : null}
</DialogFooter>
</DialogContent>
@@ -196,7 +196,9 @@ export async function reimbursementPaymentFlow(page: Page) {
await page.goto(`/payment-batches?id=${batch.id}`);
expect((await finance.api.post(`/api/payment-batches/${batch.id}/execute`, {data: {}})).status()).toBe(409);
checkpoint("receipt-upload:start");
const receiptPdf = await syntheticPdf(`Synthetic receipt ${batch.id}`);
const receiptPdf = await requireServer('../scripts/qa/synthetic-bank-receipt.cjs').syntheticBankReceiptPdf({
tag: `Synthetic receipt ${batch.id}`, reference: `SYNTHETIC-${batch.id}`, payerAccount: payer, payeeAccount: payee,
});
const uploading = page.waitForResponse(response => response.request().method() === "POST" && new URL(response.url()).pathname === `/api/payment-batches/${batch.id}/receipt-attachments`);
await page.getByTestId("payment-batch-receipt-file-input").setInputFiles({name: "synthetic-receipt.pdf", mimeType: "application/pdf", buffer: receiptPdf});
const upload = await uploading;
@@ -582,9 +582,10 @@ async function mockSystemActionApis(
const verificationPath = `/api/payment-batches/${paymentBatchId}/receipt-attachments/${paymentReceiptId}/manual-verification`;
if (path === verificationPath && request.method() === "GET") {
const facts = { pageNumber: 1, amount: "88.00", currency: "CNY", payerAccountMasked: "0000****2222",
payeeAccountMasked: "0000****4444", reference: "SYN-MANUAL-UI", transactionStatus: "success" };
payeeAccountMasked: "0000****4444", reference: "SYN-MANUAL-UI", transactionStatus: "success",
document: { version: 1, kind: "bank_receipt", source: "pdf_text", direction: "debit", explicitSuccess: true, issues: [] } };
await fulfillJson(route, { item: { version: 3, state: options.receiptManualReview ? "pending_review" : "needs_review",
canReview: Boolean(options.receiptManualReview), pagesExpected: 1, pages: [facts],
canReview: Boolean(options.receiptManualReview), documentInspectionRequired: false, pagesExpected: 1, pages: [facts],
proposal: options.receiptManualReview ? { id: "synthetic-proposal", status: "pending_review",
proposedBy: "another-finance", reviewedBy: null, reason: "合成核验说明",
changedFields: [{ pageNumber: 1, fields: ["amount"] }],