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 行删除
+9
查看文件
@@ -70,6 +70,15 @@ export const ERROR_REASON_MESSAGES: Record<string, string> = {
"payment_batch.invalid_identifier": "付款记录标识已失效,请刷新后重新选择。",
"payment_batch.invalid_input": "付款操作内容不完整或格式不正确,请核对页面必填项后重试。",
"payment_batch.bank_receipt_required": "银行付款登记前必须上传有效银行回单,请先补充回单。",
"payment_batch.receipt_retry_unavailable": "回单状态已变化或仍在识别,请刷新后查看;处理中超过15分钟仍未完成时可重试。",
"payment_batch.receipt_independent_review_required": "回单人工核验需要独立审批人复核;制单人、核验人及报销归属人或提交人不能自审。",
"payment_batch.receipt_transaction_reused": "回单交易已被使用或存在重复,请核对原回单;不能通过修改参考号重复登记。",
"payment_batch.receipt_manual_state_changed": "回单或核验版本已变化,请刷新后重新查看当前状态。",
"payment_batch.receipt_manual_verification_required": "回单信息尚不能确认与付款一致,请核对全部页、交易状态、金额、币种及收付款账号;不要直接登记付款。",
"payment_batch.receipt_key_unavailable": "回单核验密钥不可用,请联系管理员修复;不要重复识别或登记付款。",
"payment_batch.receipt_key_rotation_required": "回单交易记录使用的密钥版本不一致,请管理员完成受控密钥迁移;人工核验不能绕过。",
"payment_batch.receipt_snapshot_unsupported": "付款业务或银行快照不支持回单核验,请联系管理员核实;不要重复识别。",
"payment_batch.receipt_identity_unresolved": "无法完整确认报销参与人身份,请管理员核实人员关系后再复核;不能自行批准。",
"payment_batch.department_unavailable": "当前单据所属部门暂不能使用付款批次,请联系管理员确认处理方式。",
"payment_batch.source_not_found": "部分来源单据已不存在或不可用,请刷新后重新选择。",
"payment_batch.daily_sequence_exhausted": "今日付款批次编号已用完,请联系管理员处理,勿重复提交。",
+68
查看文件
@@ -118,6 +118,12 @@ export type PaymentBatchCandidatesResponse = {
};
export type PaymentBatchReceiptAttachment = {
ocrState?: "legacy" | "queued" | "processing" | "ocr_failed" | "needs_review" | "matched"
| "pending_review" | "association_ready" | "manual_approved" | "manual_rejected"
| "system_failed" | "key_failed" | "snapshot_failed";
ocrVersion?: number;
ocrStartedAt?: string | null;
ocrRetryAvailable?: boolean;
id: string;
originalName: string;
mimeType: string;
@@ -276,3 +282,65 @@ export async function voidPaymentBatchReceiptAttachment(batchId: string, attachm
{ method: "POST", body: JSON.stringify({ reason }) },
);
}
export async function retryPaymentBatchReceiptOcr(batchId: string, attachmentId: string, expectedVersion: number) {
return apiRequestData<{ item: { id: string; ocrState: string; ocrVersion: number } }>(
`/api/payment-batches/${batchId}/receipt-attachments/${attachmentId}/ocr-retry`,
{ method: "POST", body: JSON.stringify({ expectedVersion }) },
);
}
export type ReceiptVerificationPage = {
pageNumber: number;
amount: string | null;
currency: string | null;
payerAccountMasked: string | null;
payeeAccountMasked: string | null;
transactionStatus: string | null;
reference: string | null;
itemId?: string;
};
export type ReceiptVerificationDetail = {
canReview?: boolean;
version: number;
state: string;
pagesExpected: number;
pages: ReceiptVerificationPage[];
proposal: null | {
id: string; status: string; proposedBy: string; reviewedBy: string | null; reason: string;
changedFields: { pageNumber: number; fields: string[] }[];
pages: ReceiptVerificationPage[];
};
};
export function fetchReceiptVerification(batchId: string, attachmentId: string, signal?: AbortSignal) {
return apiRequestData<{ item: ReceiptVerificationDetail }>(
`/api/payment-batches/${batchId}/receipt-attachments/${attachmentId}/manual-verification`, { signal },
);
}
export function fetchReceiptReadiness(batchId: string, signal?: AbortSignal) {
return apiRequestData<{ item: { ready: boolean } }>(
`/api/payment-batches/${batchId}/receipt-readiness`, { signal },
);
}
export function saveReceiptVerification(batchId: string, attachmentId: string, body: {
expectedVersion: number; reason?: string;
pages: { pageNumber: number; itemId: string; fields?: { Name: string; Value: string }[] }[];
}) {
return apiRequestData<{ item: { id: string; status: string; version: number } }>(
`/api/payment-batches/${batchId}/receipt-attachments/${attachmentId}/manual-verification`,
{ method: "POST", body: JSON.stringify(body) },
);
}
export function reviewReceiptVerification(batchId: string, attachmentId: string, proposalId: string, body: {
expectedVersion: number; decision: "approve" | "reject"; reason: string;
}) {
return apiRequestData<{ item: { id: string; status: string; version: number } }>(
`/api/payment-batches/${batchId}/receipt-attachments/${attachmentId}/manual-verification/${proposalId}/review`,
{ method: "POST", body: JSON.stringify(body) },
);
}
@@ -0,0 +1,160 @@
import { useEffect, useRef, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
fetchReceiptVerification, saveReceiptVerification, reviewReceiptVerification,
type ReceiptVerificationPage,
} from "../../api/paymentBatches";
import { resolveErrorMessage } from "../../lib/resolveErrorMessage";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "../ui/dialog";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Textarea } from "../ui/textarea";
const FIELD_NAMES = ["小写金额", "币别", "付款人账号", "收款人账号", "凭证号", "单据状态"] as const;
const CHANGE_LABELS: Record<string, string> = {
amount: "金额", currency: "币种", payerAccount: "付款账号", payeeAccount: "收款账号",
reference: "交易参考", transactionStatus: "交易状态",
};
function PageFacts({ page }: { page?: ReceiptVerificationPage }) {
return <div className="space-y-1 break-all text-sm text-zinc-600">
<div>金额:{page?.amount ?? "未识别"} · 币种:{page?.currency ?? "未识别"}</div>
<div>付款账号:{page?.payerAccountMasked ?? "未识别"}</div>
<div>收款账号:{page?.payeeAccountMasked ?? "未识别"}</div>
<div>交易参考:{page?.reference ?? "未识别"}</div>
<div>状态:{{ success: "成功", failed: "失败", pending: "受理或处理中" }[page?.transactionStatus ?? ""] ?? "未确认"}</div>
</div>;
}
type Props = {
actorId: string; batchId: string; attachmentId: string; makerId: string | null;
canManage: boolean; canReview: boolean;
items: { id: string; label: string }[];
onClose: () => void; onChanged: () => void;
};
export function PaymentReceiptVerificationDialog(props: Props) {
const mounted = useRef(true);
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const [selections, setSelections] = useState<Record<number, string>>({});
const [editing, setEditing] = useState<Record<number, boolean>>({});
const [changes, setChanges] = useState<Record<number, Record<string, string>>>({});
const [reason, setReason] = useState("");
const query = useQuery({
queryKey: ["receipt-verification", props.actorId, props.batchId, props.attachmentId],
queryFn: ({ signal }) => fetchReceiptVerification(props.batchId, props.attachmentId, signal),
enabled: Boolean(props.actorId), staleTime: 0, gcTime: 0,
refetchOnWindowFocus: false, refetchOnReconnect: false, retry: false,
});
const detail = query.data?.item;
const changed = () => {
if (!mounted.current) return;
props.onChanged();
props.onClose();
};
const save = useMutation({
mutationFn: () => saveReceiptVerification(props.batchId, props.attachmentId, {
expectedVersion: detail!.version, ...(reason.trim() ? { reason: reason.trim() } : {}),
pages: Array.from({ length: detail!.pagesExpected }, (_unused, index) => {
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 } : {}) };
}),
}),
onSuccess: changed,
});
const review = useMutation({
mutationFn: (decision: "approve" | "reject") => reviewReceiptVerification(
props.batchId, props.attachmentId, detail!.proposal!.id,
{ expectedVersion: detail!.version, decision, reason: reason.trim() },
),
onSuccess: changed,
});
const busy = save.isPending || review.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 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 hasCorrections = Object.values(changes).some((fields) => Object.values(fields).some((value) => value.trim()));
const error = query.error ?? save.error ?? review.error;
return <Dialog open onOpenChange={(open) => { if (!open && !busy) props.onClose(); }}>
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>回单核验</DialogTitle>
<DialogDescription>核对原回单与付款明细。账号仅显示掩码;需要核对完整内容时请使用回单“在线查看”。核验不代表银行验真,也不会自动登记付款。</DialogDescription>
</DialogHeader>
{query.isPending ? <p role="status">正在加载核验信息…</p> : null}
{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();
void query.refetch();
}}>刷新核验信息</Button>
</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);
const proposed = detail?.proposal?.pages.find((page) => page.pageNumber === pageNumber);
return <section key={pageNumber} className="space-y-3 rounded-lg border p-3">
<h3 className="font-medium">第{pageNumber}页 · 原识别结果</h3>
<PageFacts page={original} />
{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 ? <>
<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}
value={selections[pageNumber] ?? ""} onChange={(event) =>
setSelections((current) => ({ ...current, [pageNumber]: event.target.value }))}>
<option value="">请选择对应明细</option>
{props.items.map((item) => <option key={item.id} value={item.id}>{item.label}</option>)}
</select>
</label>
<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">只填写要更正的字段,其他字段保留原识别值。更正后需要独立复核。</p>
{FIELD_NAMES.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) =>
setChanges((current) => ({ ...current, [pageNumber]: { ...current[pageNumber], [name]: event.target.value } }))}>
<option value="">不更正</option><option value="交易成功">原件明确显示交易成功</option>
</select> : <Input autoComplete="off" disabled={busy} maxLength={256}
placeholder="不更正则留空" value={changes[pageNumber]?.[name] ?? ""}
onChange={(event) => setChanges((current) => ({
...current, [pageNumber]: { ...current[pageNumber], [name]: event.target.value },
}))} />}
</label>)}
</div> : null}
</> : null}
</section>;
})}
{detail?.proposal ? <p className="whitespace-pre-wrap break-words text-sm">核验说明:{detail.proposal.reason}</p> : null}
{detail?.proposal?.status === "pending_review" && !reviewable ?
<p role="status" className="text-sm text-zinc-600">等待有资格的独立审批人复核;经办人和报销参与人不能自审。</p> : null}
{editable || reviewable ? <label className="block space-y-1 text-sm">
<span>{reviewable ? "复核说明" : "更正说明(仅关联可留空)"}</span>
<Textarea value={reason} maxLength={500} disabled={busy} onChange={(event) => setReason(event.target.value)} />
</label> : null}
<DialogFooter className="flex-wrap gap-2">
<Button variant="secondary" disabled={busy} onClick={props.onClose}>关闭</Button>
{editable ? <Button disabled={busy || query.isFetching || !complete || (hasCorrections && !reason.trim())}
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")}>确认复核</Button>
</> : null}
</DialogFooter>
</DialogContent>
</Dialog>;
}
+86 -3
查看文件
@@ -21,6 +21,8 @@ import {
updatePaymentBatchItem,
uploadPaymentBatchReceiptAttachments,
voidPaymentBatchReceiptAttachment,
retryPaymentBatchReceiptOcr,
fetchReceiptReadiness,
type PaymentBatchReceiptAttachment,
type PaymentChannel,
} from "../api/paymentBatches";
@@ -40,6 +42,7 @@ import {
BusinessTable,
} from "../components/patterns/BusinessListTemplate";
import { ActionConfirmDialog } from "../components/common/ActionConfirmDialog";
import { PaymentReceiptVerificationDialog } from "../components/common/PaymentReceiptVerificationDialog";
import { AttachmentGovernanceBadges } from "../components/common/AttachmentGovernanceBadges";
import { useAttachmentDownloadReasonDialog } from "../components/common/useAttachmentDownloadReasonDialog";
import { Button } from "../components/ui/button";
@@ -170,6 +173,9 @@ export function PaymentBatchesPage() {
| null
>(null);
const [actionReason, setActionReason] = useState("");
const [verificationTarget, setVerificationTarget] = useState<{
actorId: string; batchId: string; attachmentId: string;
} | null>(null);
const [revealedPayeeAccount, setRevealedPayeeAccount] = useState("");
const [receiptPreview, setReceiptPreview] = useState<{
attachment: PaymentBatchReceiptAttachment;
@@ -184,6 +190,7 @@ export function PaymentBatchesPage() {
}, [receiptPreview?.objectUrl]);
const selectedBatchId = searchParams.get("id") ?? "";
useEffect(() => { setVerificationTarget(null); }, [me?.id, selectedBatchId]);
const requestedView = searchParams.get("view");
const activeView = selectedBatchId
? "detail"
@@ -254,7 +261,11 @@ export function PaymentBatchesPage() {
const receiptAttachmentsQuery = useQuery({
queryKey: ["payment-batch-receipts", selectedBatch?.id],
enabled: Boolean(selectedBatch?.id),
staleTime: 0,
refetchOnWindowFocus: "always",
queryFn: () => fetchPaymentBatchReceiptAttachments(selectedBatch!.id),
refetchInterval: (query) => query.state.data?.items.some((item) =>
["queued", "processing"].includes(item.ocrState ?? "")) ? 5000 : false,
});
const canEditSelectedBatch =
@@ -286,9 +297,17 @@ export function PaymentBatchesPage() {
const activeReceiptCount = (receiptAttachmentsQuery.data?.items ?? []).filter((item) => !item.archivedAt).length;
const needsBankReceipt =
canExecuteSelectedBatch && requiresBankReceipt && receiptAttachmentsQuery.isSuccess && activeReceiptCount === 0;
const receiptReadinessQuery = useQuery({
queryKey: ["payment-receipt-readiness", me?.id, selectedBatch?.id,
(receiptAttachmentsQuery.data?.items ?? []).map((item) => `${item.id}:${item.ocrVersion}:${item.ocrState}:${item.archivedAt}`).join("|")],
enabled: Boolean(me?.id && canExecuteSelectedBatch && requiresBankReceipt && activeReceiptCount > 0),
queryFn: ({ signal }) => fetchReceiptReadiness(selectedBatch!.id, signal),
staleTime: 0, gcTime: 0, retry: false, refetchOnWindowFocus: "always",
});
const canRegisterPaymentComplete =
canExecuteSelectedBatch &&
(!requiresBankReceipt || (receiptAttachmentsQuery.isSuccess && activeReceiptCount > 0));
(!requiresBankReceipt || (receiptAttachmentsQuery.isSuccess && activeReceiptCount > 0 &&
receiptReadinessQuery.isSuccess && !receiptReadinessQuery.isFetching && receiptReadinessQuery.data.item.ready));
const canCancelSelectedBatch =
canManageBatch &&
!!selectedBatch &&
@@ -495,6 +514,21 @@ export function PaymentBatchesPage() {
},
});
const retryReceiptOcrMutation = useMutation({
mutationFn: ({ batchId, attachment }: { batchId: string; attachment: PaymentBatchReceiptAttachment }) =>
retryPaymentBatchReceiptOcr(batchId, attachment.id, attachment.ocrVersion ?? 0),
onSuccess: async () => {
setError("");
await refresh();
toast.success("回单已加入识别队列");
},
onError: (err) => {
const message = resolveError(err);
setError(message);
toast.error(message);
},
});
const { requestDownloadReason, downloadReasonDialog } = useAttachmentDownloadReasonDialog();
const downloadReceiptMutation = useMutation({
@@ -959,7 +993,9 @@ export function PaymentBatchesPage() {
<div>
<h3 className="text-base font-semibold text-zinc-900">银行回单</h3>
<p className="mt-1 text-sm text-zinc-500">
{!requiresBankReceipt
{selectedBatch.status === "executed"
? "付款已登记完成,回单与核验记录作为凭据保留;核验不代表银行验真。"
: !requiresBankReceipt
? "当前付款渠道不要求银行回单,核对付款结果后可直接登记完成。"
: selectedBatch.status === "draft"
? "付款复核通过后,由财务在线下完成付款并上传银行回单。"
@@ -994,6 +1030,16 @@ export function PaymentBatchesPage() {
</div>
) : null}
</div>
{canExecuteSelectedBatch && requiresBankReceipt && activeReceiptCount > 0 && !canRegisterPaymentComplete ? (
<div className="space-y-2 rounded-lg border p-3 text-sm" role="status">
<p>{receiptReadinessQuery.isFetching ? "正在核对回单…" : receiptReadinessQuery.isError ?
resolveError(receiptReadinessQuery.error) : "回单尚未满足付款登记条件,请查看核验详情,完成识别、更正或独立复核。"}</p>
<Button type="button" size="sm" variant="secondary" disabled={receiptReadinessQuery.isFetching}
onClick={() => { void receiptReadinessQuery.refetch(); void receiptAttachmentsQuery.refetch(); }}>
重新核对回单
</Button>
</div>
) : null}
{receiptAttachmentsQuery.isError ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
<span>{resolveError(receiptAttachmentsQuery.error)}</span>
@@ -1018,8 +1064,26 @@ export function PaymentBatchesPage() {
{attachment.uploadedBy ? ` · ${attachment.uploadedBy.name}` : ""}
</div>
<AttachmentGovernanceBadges attachment={attachment} className="mt-2" />
{attachment.ocrState && !attachment.archivedAt ? (
<div className="mt-1 text-xs text-zinc-500" role="status">
{{ legacy: "尚未识别", queued: "等待识别", processing: "正在识别",
system_failed: "核验结果保存失败,请联系管理员;不要重复识别或登记付款",
key_failed: "核验密钥不可用,请联系管理员修复;不要重复识别",
snapshot_failed: "付款业务或银行快照不支持,请联系管理员核实",
ocr_failed: "识别未完成,可重试", needs_review: "待核验", matched: "回单信息匹配,非银行验真",
pending_review: "人工核验待独立复核", association_ready: "明细已关联",
manual_approved: "人工核验已复核,非银行验真", manual_rejected: "人工核验未通过" }[attachment.ocrState]}
</div>
) : null}
</div>
<div className="flex flex-wrap gap-2">
{!attachment.archivedAt && attachment.ocrState &&
!["queued", "processing", "system_failed", "key_failed", "snapshot_failed"].includes(attachment.ocrState) && me?.id ? (
<Button type="button" size="sm" variant="secondary" className="min-h-11"
onClick={() => setVerificationTarget({
actorId: me.id, batchId: selectedBatch.id, attachmentId: attachment.id,
})}>核验详情</Button>
) : null}
<Button
type="button"
size="sm"
@@ -1040,6 +1104,13 @@ export function PaymentBatchesPage() {
>
下载
</Button>
{canEditReceiptAttachments && attachment.ocrRetryAvailable ? (
<Button type="button" size="sm" variant="secondary" className="min-h-11"
disabled={retryReceiptOcrMutation.isPending}
onClick={() => retryReceiptOcrMutation.mutate({ batchId: selectedBatch.id, attachment })}>
重新识别
</Button>
) : null}
{canEditReceiptAttachments ? (
<Button
type="button"
@@ -1065,7 +1136,7 @@ export function PaymentBatchesPage() {
))}
{requiresBankReceipt && receiptAttachmentsQuery.isSuccess && !(receiptAttachmentsQuery.data?.items ?? []).length ? (
<div className="rounded-lg border border-zinc-200 px-3 py-3 text-sm text-zinc-500">
暂无银行回单;银行转账必须先上传回单,才能登记付款完成。
暂无银行回单;银行转账必须先上传回单并完成核验,才能登记付款完成。
</div>
) : null}
</div>
@@ -1374,6 +1445,18 @@ export function PaymentBatchesPage() {
</DialogFooter>
</DialogContent>
</Dialog>
{verificationTarget && me?.id === verificationTarget.actorId &&
selectedBatch?.id === verificationTarget.batchId ? (
<PaymentReceiptVerificationDialog
key={`${me.id}:${selectedBatch.id}:${verificationTarget.attachmentId}`}
actorId={me.id} batchId={selectedBatch.id} attachmentId={verificationTarget.attachmentId}
makerId={selectedBatch.createdBy ?? null}
canManage={Boolean(canEditReceiptAttachments)} canReview={Boolean(canReviewBatch)}
items={selectedBatch.items.map((item) => ({ id: item.id, label: `${item.entityCode} · ${formatMoney(item.amount)}` }))}
onClose={() => setVerificationTarget(null)}
onChanged={() => { void receiptAttachmentsQuery.refetch(); }}
/>
) : null}
</ListWorkspace>
);
}
@@ -303,6 +303,9 @@ async function mockSystemActionApis(
batchStatus?: SyntheticPaymentBatchStatus;
hasReceipt?: boolean;
receiptQueryError?: boolean;
receiptOcrState?: "ocr_failed" | "queued" | "system_failed" | "key_failed" | "snapshot_failed";
receiptManualReview?: boolean;
receiptReady?: boolean;
highRisk?: boolean;
paymentChannel?: "bank" | "cash";
canExportPaymentOrder?: boolean;
@@ -319,6 +322,7 @@ async function mockSystemActionApis(
const currentMe = { ...me, ...options.meOverride };
const batchStatus = options.batchStatus ?? "reviewed";
let hasReceipt = options.hasReceipt ?? true;
let receiptOcrState = options.receiptOcrState;
let paymentOrderExportCount = options.paymentOrderExportCount ?? 0;
let currentReimbursementStatus = options.reimbursementStatus ?? "draft";
const calls = {
@@ -331,6 +335,9 @@ async function mockSystemActionApis(
previewPaymentReceipt: 0,
uploadPaymentReceipt: 0,
voidPaymentReceipt: 0,
retryReceiptOcr: 0,
manualReceiptSaves: [] as Array<Record<string, unknown>>,
manualReceiptReviews: [] as Array<Record<string, unknown>>,
attachmentDeleteReasons: [] as string[],
receiptVoidReasons: [] as string[],
reimbursementUpdates: [] as Array<Record<string, unknown>>,
@@ -568,6 +575,39 @@ async function mockSystemActionApis(
return;
}
if (path === `/api/payment-batches/${paymentBatchId}/receipt-readiness` && request.method() === "GET") {
await fulfillJson(route, { item: { ready: options.receiptReady ?? true } });
return;
}
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" };
await fulfillJson(route, { item: { version: 3, state: options.receiptManualReview ? "pending_review" : "needs_review",
canReview: Boolean(options.receiptManualReview), pagesExpected: 1, pages: [facts],
proposal: options.receiptManualReview ? { id: "synthetic-proposal", status: "pending_review",
proposedBy: "another-finance", reviewedBy: null, reason: "合成核验说明",
changedFields: [{ pageNumber: 1, fields: ["amount"] }],
pages: [{ ...facts, itemId: "payment-batch-item-action-confirm" }] } : null } });
return;
}
if (path === verificationPath && request.method() === "POST") {
calls.manualReceiptSaves.push(request.postDataJSON());
await fulfillJson(route, { item: { id: "synthetic-proposal", version: 4, status: "pending_review" } });
return;
}
if (path === `${verificationPath}/synthetic-proposal/review` && request.method() === "POST") {
calls.manualReceiptReviews.push(request.postDataJSON());
await fulfillJson(route, { item: { id: "synthetic-proposal", version: 3, status: "approved" } });
return;
}
if (path === `/api/payment-batches/${paymentBatchId}/receipt-attachments/${paymentReceiptId}/ocr-retry` && request.method() === "POST") {
expect(request.postDataJSON()).toEqual({ expectedVersion: 3 });
calls.retryReceiptOcr += 1;
receiptOcrState = "queued";
await fulfillJson(route, { item: { id: paymentReceiptId, ocrState: "queued", ocrVersion: 4 } });
return;
}
if (path === `/api/payment-batches/${paymentBatchId}/receipt-attachments` && request.method() === "GET") {
if (options.receiptQueryError) {
await route.fulfill({
@@ -585,6 +625,9 @@ async function mockSystemActionApis(
{
id: paymentReceiptId,
originalName: "合成银行回单.pdf",
ocrState: receiptOcrState,
ocrVersion: receiptOcrState === "queued" ? 4 : 3,
ocrRetryAvailable: receiptOcrState === "ocr_failed",
mimeType: "application/pdf",
fileSize: 2048,
fileSha256: "synthetic-receipt-hash",
@@ -1312,6 +1355,94 @@ test.describe("R7E 全站高风险操作二次确认", () => {
await expect(dialog).not.toBeVisible();
});
for (const width of [1440, 390]) {
for (const state of ["system_failed", "key_failed", "snapshot_failed"] as const) {
test(`回单系统失败引导管理员且不重传 ${width} ${state}`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
const calls = await mockSystemActionApis(page, { receiptOcrState: state, receiptReady: false });
await login(page, user);
await page.goto(`/payment-batches?id=${paymentBatchId}`);
const receipt = page.locator(".detail-evidence-card").filter({ hasText: "合成银行回单.pdf" });
await expect(receipt).toContainText("请联系管理员");
await expect(receipt.getByRole("button", { name: "重新识别", exact: true })).toHaveCount(0);
await expect(receipt.getByRole("button", { name: "核验详情", exact: true })).toHaveCount(0);
await expect(page.getByRole("button", { name: "登记付款完成", exact: true })).toHaveCount(0);
expect(calls.retryReceiptOcr).toBe(0);
expect(calls.executePaymentBatch).toBe(0);
});
}
test(`回单未核验不能登记付款 ${width}`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
const calls = await mockSystemActionApis(page, { receiptOcrState: "ocr_failed", receiptReady: false });
await login(page, user);
await page.goto(`/payment-batches?id=${paymentBatchId}`);
await expect(page.getByText("回单尚未满足付款登记条件", { exact: false })).toBeVisible();
await expect(page.getByRole("button", { name: "登记付款完成", exact: true })).toHaveCount(0);
expect(calls.executePaymentBatch).toBe(0);
});
for (const correction of [false, true]) {
test(`回单人工核验只提交关联或更正且不付款 ${width} ${correction}`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
const calls = await mockSystemActionApis(page, { receiptOcrState: "ocr_failed" });
await login(page, user);
await page.goto(`/payment-batches?id=${paymentBatchId}`);
await page.getByRole("button", { name: "核验详情", exact: true }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toContainText("0000****2222");
await dialog.getByRole("combobox", { name: "第1页对应付款明细" }).selectOption("payment-batch-item-action-confirm");
if (correction) {
await dialog.getByRole("button", { name: "更正识别", exact: true }).click();
await dialog.getByRole("textbox", { name: "第1页更正小写金额", exact: true }).fill("88.00");
await expect(dialog.getByRole("button", { name: "保存核验", exact: true })).toBeDisabled();
await dialog.getByRole("textbox", { name: "更正说明(仅关联可留空)", exact: true }).fill("核对原件更正金额");
}
await expect(dialog).toBeInViewport();
await dialog.getByRole("button", { name: "保存核验", exact: true }).click();
await expect.poll(() => calls.manualReceiptSaves.length).toBe(1);
expect(calls.manualReceiptSaves[0]).toEqual({
expectedVersion: 3, ...(correction ? { reason: "核对原件更正金额" } : {}),
pages: [{ pageNumber: 1, itemId: "payment-batch-item-action-confirm",
...(correction ? { fields: [{ Name: "小写金额", Value: "88.00" }] } : {}) }],
});
expect(calls.executePaymentBatch).toBe(0);
expect(calls.uploadPaymentReceipt).toBe(0);
await expect(dialog).not.toBeVisible();
});
}
test(`回单独立复核查看更正且不触发付款 ${width}`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
const calls = await mockSystemActionApis(page, { receiptOcrState: "ocr_failed", receiptManualReview: true,
meOverride: { id: "independent-receipt-reviewer" } });
await login(page, user);
await page.goto(`/payment-batches?id=${paymentBatchId}`);
await page.getByRole("button", { name: "核验详情", exact: true }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toContainText("人工核验结果");
await expect(dialog).toContainText("更正字段:金额");
await expect(dialog.getByRole("button", { name: "确认复核", exact: true })).toBeDisabled();
await dialog.getByRole("textbox", { name: "复核说明", exact: true }).fill("已核对合成原回单");
await dialog.getByRole("button", { name: "确认复核", exact: true }).click();
await expect.poll(() => calls.manualReceiptReviews.length).toBe(1);
expect(calls.manualReceiptReviews[0]).toEqual({ expectedVersion: 3, decision: "approve", reason: "已核对合成原回单" });
expect(calls.executePaymentBatch).toBe(0);
expect(calls.manualReceiptSaves).toHaveLength(0);
});
test(`回单OCR失败可重试且不触发付款登记 ${width}`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
const calls = await mockSystemActionApis(page, { receiptOcrState: "ocr_failed" });
await login(page, user);
await page.goto(`/payment-batches?id=${paymentBatchId}`);
const receipt = page.locator(".detail-evidence-card").filter({ hasText: "合成银行回单.pdf" });
await expect(receipt).toContainText("识别未完成,可重试");
await receipt.getByRole("button", { name: "重新识别", exact: true }).click();
await expect(receipt).toContainText("等待识别");
await expect(receipt.getByRole("button", { name: "重新识别", exact: true })).toHaveCount(0);
expect(calls.retryReceiptOcr).toBe(1);
expect(calls.executePaymentBatch).toBe(0);
expect(calls.uploadPaymentReceipt).toBe(0);
});
}
test("付款回单作废要求对象、后果和理由,取消与理由不足均为零请求", async ({ page }) => {
const calls = await mockSystemActionApis(page);
await login(page, user);