import { useCallback, useEffect, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { isApiError } from "../api/types"; import { mapApiErrorMessage } from "../api/errorMessages"; import { fetchExpenseTypes } from "../api/expenseTypes"; import type { ExpenseStandardCheck, PrecheckResponse } from "../api/feeControl"; import { fetchProjects } from "../api/projects"; import { createReimbursementItem, deleteReimbursementAttachment, deleteReimbursement, deleteReimbursementItem, downloadReimbursementAttachment, fetchReimbursementDetail, precheckReimbursement, submitReimbursement, updateReimbursementItem, uploadReimbursementAttachments, withdrawReimbursement, linkReimbursementProject, type ReimbursementItem, type ReimbursementStatus, } from "../api/reimbursements"; import { remindWorkflowTask } from "../api/workflow"; import { bindInvoice, fetchBindableInvoices, unbindInvoice, uploadInvoice, } from "../api/invoicePool"; import { toast } from "sonner"; import { useAuth } from "../auth/AuthContext"; import { hasPermission } from "../auth/permissions"; import { CardSkeleton } from "../components/common/CardSkeleton"; import { ConfirmDialog } from "../components/common/ConfirmDialog"; import { useUnsavedChangesGuard } from "../components/common/UnsavedChangesGuard"; import { AttachmentGovernanceBadges } from "../components/common/AttachmentGovernanceBadges"; import { AttachmentDeleteConfirmDialog } from "../components/common/AttachmentDeleteConfirmDialog"; import { useAttachmentDownloadReasonDialog } from "../components/common/useAttachmentDownloadReasonDialog"; import { RiskFlagsCard } from "../components/common/RiskFlagsCard"; import { StatusBadge } from "../components/common/StatusBadge"; import { AiSuggestionCard } from "../components/ai/AiSuggestionCard"; import { Button } from "../components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "../components/ui/dialog"; import { Input } from "../components/ui/input"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table"; import { DetailSideMeta } from "../components/patterns/DetailSideMeta"; import { EntityOverviewHero } from "../components/patterns/EntityOverviewHero"; import { PageScaffold } from "../components/patterns/PageScaffold"; import { SectionPanel } from "../components/patterns/SectionPanel"; import { formatInvoiceDisplayTitle, resolveInvoiceNextStepText, resolveInvoiceStatusLabel, resolveInvoiceUserMessage, } from "../lib/invoiceStatus"; import { useInvoiceOcrTracker } from "../hooks/useInvoiceOcrTracker"; import { resolveReimbursementDisplayCode } from "../lib/reimbursementDisplay"; import type { AttachmentGovernanceFields } from "../lib/attachmentGovernance"; import { formatDisplayDate } from "../lib/displayFormat"; import { TEST_IDS } from "../lib/testIds"; import { PDF_FILE_ACCEPT, rejectedPdfMessage, splitPdfFiles } from "../lib/pdfFiles"; import { ReimbursementActions } from "./reimbursement-detail/ReimbursementActions"; import { ReimbursementItemEditor, type ItemEditorInitialValues, type ItemEditorSaveData, } from "./reimbursement-detail/ReimbursementItemEditor"; import { buildPrecheckDialogMessage } from "../lib/precheck"; type ItemEditorState = { mode: "create" } | { mode: "edit"; itemId: string } | null; type SelectedInvoiceMap = Record; function formatDateTime(value: string | null) { if (!value) return "-"; return value.slice(0, 19).replace("T", " "); } function buildActionErrorMessage(error: unknown, fallbackMessage: string) { if (isApiError(error)) { return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`; } if (error instanceof Error) { return error.message; } return fallbackMessage; } function workflowActionLabel(action: string) { const labels: Record = { start: "提交", approve: "通过", reject: "驳回", return: "退回", transfer: "转审", withdraw: "撤回", remind: "催办", overdue_remind: "超时提醒", }; return labels[action] ?? action; } function budgetControlModeLabel(controlMode: string | null | undefined) { const labels: Record = { block: "超额阻断", warn: "超额提醒", manual_review: "人工复核", }; return controlMode ? labels[controlMode] ?? "按制度处理" : "按制度处理"; } function reimbursementStatusLabel(status: ReimbursementStatus) { const labels: Record = { draft: "草稿", reviewing: "审批中", approved: "已批准", paid: "已支付", rejected: "已驳回", cancelled: "已取消", }; return labels[status] ?? status; } function materialCompletenessLabel(count: number, noun: string) { return count > 0 ? `${count} ${noun}` : `缺${noun}`; } function paymentChannelLabel(value: string | null | undefined) { if (value === "bank") return "银行转账"; if (value === "alipay") return "支付宝"; if (value === "wechat") return "微信"; if (value === "cash") return "现金"; if (value === "other") return "其他"; return value || "-"; } export function ReimbursementDetailPage() { const { reimbursementId = "" } = useParams(); const navigate = useNavigate(); const { permissions, me, accessToken } = useAuth(); const queryClient = useQueryClient(); const [actionError, setActionError] = useState(""); const [itemEditor, setItemEditor] = useState(null); const [itemError, setItemError] = useState(""); const [confirmDeleteItemId, setConfirmDeleteItemId] = useState(""); const [confirmDeleteReimbursement, setConfirmDeleteReimbursement] = useState(false); const [showSecondaryDetail, setShowSecondaryDetail] = useState(false); const [submitConfirmPrecheck, setSubmitConfirmPrecheck] = useState(null); const [isInvoiceDialogOpen, setIsInvoiceDialogOpen] = useState(false); const [invoiceSearchInput, setInvoiceSearchInput] = useState(""); const [invoiceSearch, setInvoiceSearch] = useState(""); const [selectedInvoices, setSelectedInvoices] = useState({}); const [selectedInvoiceFiles, setSelectedInvoiceFiles] = useState([]); const [selectedAttachmentFiles, setSelectedAttachmentFiles] = useState([]); const [deleteAttachmentTarget, setDeleteAttachmentTarget] = useState<{ id: string; originalName: string } | null>(null); const [invoiceActionError, setInvoiceActionError] = useState(""); const [pendingOcrInvoiceIds, setPendingOcrInvoiceIds] = useState([]); const [invoiceUploadProgress, setInvoiceUploadProgress] = useState({ completed: 0, total: 0 }); const [editorInitialValues, setEditorInitialValues] = useState({ expenseTypeId: "", expenseDate: "", amount: "", description: "", }); const runGuarded = useUnsavedChangesGuard( Boolean(itemEditor) || selectedInvoiceFiles.length > 0 || selectedAttachmentFiles.length > 0 || Object.keys(selectedInvoices).length > 0, "报销表单", ); const detailQuery = useQuery({ enabled: Boolean(reimbursementId), queryKey: ["reimbursements", reimbursementId], queryFn: () => fetchReimbursementDetail(reimbursementId), }); const expenseTypesQuery = useQuery({ queryKey: ["expenseTypes", "enabled"], queryFn: () => fetchExpenseTypes({ enabled: true }), }); const projectsQuery = useQuery({ queryKey: ["projects", "reimbursement-link"], queryFn: () => fetchProjects({ mine: true }), }); const canSubmitExpense = hasPermission(permissions, "expense.submit"); const canUploadInvoice = hasPermission(permissions, "invoice.upload"); const canViewOwnInvoice = hasPermission(permissions, "invoice.view_own"); const canViewAllExpense = hasPermission(permissions, "expense.view_all"); const canDeleteExpense = hasPermission(permissions, "expense.delete_own"); const reimbursementPrecheckQuery = useQuery({ enabled: Boolean(reimbursementId) && canSubmitExpense && ["draft", "rejected"].includes(detailQuery.data?.status ?? ""), queryKey: ["reimbursements", reimbursementId, "precheck"], queryFn: () => precheckReimbursement(reimbursementId), }); const bindableInvoicesQuery = useQuery({ enabled: Boolean(reimbursementId) && isInvoiceDialogOpen && canUploadInvoice && canViewOwnInvoice && Boolean(detailQuery.data) && ["draft", "rejected"].includes(detailQuery.data?.status ?? "") && Boolean(me?.id) && [detailQuery.data?.ownerId, detailQuery.data?.submitterId].includes(me?.id ?? ""), queryKey: ["invoice-pool", "bindable", reimbursementId, invoiceSearch], queryFn: () => fetchBindableInvoices({ reimbursementId, search: invoiceSearch || undefined, limit: 20, }), refetchInterval: pendingOcrInvoiceIds.length ? 3_000 : false, }); useEffect(() => { const timerId = window.setTimeout(() => { setInvoiceSearch(invoiceSearchInput.trim()); }, 300); return () => window.clearTimeout(timerId); }, [invoiceSearchInput]); useEffect(() => { const candidateIds = new Set((bindableInvoicesQuery.data?.items ?? []).map((item) => item.id)); setSelectedInvoices((previous) => Object.fromEntries(Object.entries(previous).filter(([invoiceId]) => candidateIds.has(invoiceId))), ); }, [bindableInvoicesQuery.data?.items]); const mutation = useMutation({ mutationFn: async (params: { action: "submit" } | { action: "withdraw"; comment: string }) => { if (!reimbursementId) { throw new Error("missing reimbursementId"); } if (params.action === "submit") { return submitReimbursement(reimbursementId); } if (params.action === "withdraw") { return withdrawReimbursement(reimbursementId, params.comment); } }, onSuccess: async (_data, params) => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["reimbursements"] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId, "precheck"] }), ]); setActionError(""); if (params.action === "submit") { setSubmitConfirmPrecheck(null); } const actionMessages: Record = { submit: "已提交", withdraw: "已撤回" }; toast.success(actionMessages[params.action] ?? "操作成功"); }, onError: (error) => { if (isApiError(error)) { const msg = `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`; setActionError(msg); toast.error(msg); return; } if (error instanceof Error) { setActionError(error.message); toast.error(error.message); return; } setActionError("操作失败,请稍后重试"); toast.error("操作失败,请稍后重试"); }, }); const remindMutation = useMutation({ mutationFn: (taskId: string) => remindWorkflowTask(taskId), onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }), queryClient.invalidateQueries({ queryKey: ["notifications"] }), queryClient.invalidateQueries({ queryKey: ["workflow", "tasks"] }), queryClient.invalidateQueries({ queryKey: ["workflow", "tasks", "summary"] }), queryClient.invalidateQueries({ queryKey: ["portal-home"] }), ]); toast.success("已催办当前审批人"); }, onError: (error) => { toast.error(buildActionErrorMessage(error, "催办失败,请稍后重试")); }, }); const itemSaveMutation = useMutation({ mutationFn: async (data: ItemEditorSaveData) => { if (!reimbursementId) { throw new Error("missing reimbursementId"); } if (!itemEditor) { throw new Error("missing itemEditor"); } const payload = { expenseTypeId: data.expenseTypeId, expenseDate: data.expenseDate, amount: data.amount, description: data.description.trim() || undefined, }; if (itemEditor.mode === "create") { return createReimbursementItem(reimbursementId, payload); } return updateReimbursementItem(reimbursementId, itemEditor.itemId, payload); }, onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["reimbursements"] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId, "precheck"] }), ]); setItemEditor(null); setItemError(""); toast.success("明细已保存"); }, onError: (error) => { if (isApiError(error)) { const msg = `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`; setItemError(msg); toast.error(msg); return; } if (error instanceof Error) { setItemError(error.message); toast.error(error.message); return; } setItemError("保存明细失败,请稍后重试"); toast.error("保存明细失败,请稍后重试"); }, }); const itemDeleteMutation = useMutation({ mutationFn: async (itemId: string) => { if (!reimbursementId) { throw new Error("missing reimbursementId"); } return deleteReimbursementItem(reimbursementId, itemId); }, onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["reimbursements"] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId, "precheck"] }), ]); setItemError(""); toast.success("明细已删除"); }, onError: (error) => { if (isApiError(error)) { const msg = `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`; setItemError(msg); toast.error(msg); return; } if (error instanceof Error) { setItemError(error.message); toast.error(error.message); return; } setItemError("删除明细失败,请稍后重试"); toast.error("删除明细失败,请稍后重试"); }, }); const deleteReimbursementMutation = useMutation({ mutationFn: async () => { if (!reimbursementId) { throw new Error("missing reimbursementId"); } return deleteReimbursement(reimbursementId); }, onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["reimbursements"] }); toast.success("草稿已删除"); navigate("/reimbursements?status=draft"); }, onError: (error) => { const message = buildActionErrorMessage(error, "删除草稿失败"); setActionError(message); toast.error(message); }, }); const projectLinkMutation = useMutation({ mutationFn: (projectId: string | null) => linkReimbursementProject(reimbursementId, projectId), onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["reimbursements"] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }), queryClient.invalidateQueries({ queryKey: ["projects"] }), queryClient.invalidateQueries({ queryKey: ["portal-home"] }), ]); toast.success("已更新关联项目"); }, onError: (error) => { const message = isApiError(error) ? `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}` : error instanceof Error ? error.message : "关联项目失败"; toast.error(message); }, }); const bindInvoicesMutation = useMutation({ mutationFn: async (invoiceSelections: Array<{ invoiceId: string; linkedItemId?: string }>) => { if (!reimbursementId) { throw new Error("missing reimbursementId"); } const results: Array<{ invoiceId: string; success: boolean; message?: string }> = []; for (const selection of invoiceSelections) { try { await bindInvoice(selection.invoiceId, { reimbursementId, ...(selection.linkedItemId ? { linkedItemId: selection.linkedItemId } : {}), }); results.push({ invoiceId: selection.invoiceId, success: true }); } catch (error) { results.push({ invoiceId: selection.invoiceId, success: false, message: buildActionErrorMessage(error, "添加发票失败"), }); } } return results; }, onSuccess: async (results) => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["reimbursements"] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }), queryClient.invalidateQueries({ queryKey: ["invoice-pool", "bindable", reimbursementId] }), ]); const failedResults = results.filter((item) => !item.success); const succeededIds = results.filter((item) => item.success).map((item) => item.invoiceId); setSelectedInvoices((previous) => Object.fromEntries(Object.entries(previous).filter(([invoiceId]) => !succeededIds.includes(invoiceId))), ); if (!failedResults.length) { setInvoiceActionError(""); setIsInvoiceDialogOpen(false); setInvoiceSearchInput(""); setInvoiceSearch(""); setSelectedInvoices({}); setSelectedInvoiceFiles([]); setPendingOcrInvoiceIds((previous) => previous.filter((invoiceId) => !succeededIds.includes(invoiceId)), ); toast.success(`已添加 ${succeededIds.length} 张发票`); return; } const summary = failedResults .map((item) => { const invoice = (bindableInvoicesQuery.data?.items ?? []).find((candidate) => candidate.id === item.invoiceId); return `${formatInvoiceDisplayTitle(invoice)}:${item.message ?? "添加失败"}`; }) .join(";"); setInvoiceActionError(summary); if (succeededIds.length) { toast.success(`已添加 ${succeededIds.length} 张,${failedResults.length} 张失败`); } else { toast.error("发票添加失败"); } }, onError: (error) => { const message = buildActionErrorMessage(error, "发票添加失败"); setInvoiceActionError(message); toast.error(message); }, }); const handleTrackedInvoicesAvailable = useCallback( (invoiceIds: string[]) => { if (!invoiceIds.length) { return; } bindInvoicesMutation.mutate(invoiceIds.map((invoiceId) => ({ invoiceId }))); }, [bindInvoicesMutation], ); const handleTrackedInvoicesUnavailable = useCallback((items: Array<{ id: string; originalName: string | null; message: string; availabilityMessage?: string | null; ocrLastError?: string | null }>) => { const message = items .map((item) => `${formatInvoiceDisplayTitle(item)}:${resolveInvoiceUserMessage(item)}`) .join(";"); setInvoiceActionError(message); toast.error("部分发票需要处理"); }, []); const invoiceOcrTracker = useInvoiceOcrTracker({ accessToken, enabled: Boolean(reimbursementId), pendingInvoiceIds: pendingOcrInvoiceIds, setPendingInvoiceIds: setPendingOcrInvoiceIds, onAvailable: handleTrackedInvoicesAvailable, onUnavailable: handleTrackedInvoicesUnavailable, }); const unbindInvoiceMutation = useMutation({ mutationFn: (invoiceId: string) => unbindInvoice(invoiceId), onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ["reimbursements"] }), queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }), queryClient.invalidateQueries({ queryKey: ["invoice-pool", "bindable", reimbursementId] }), ]); setInvoiceActionError(""); toast.success("发票已移除"); }, onError: (error) => { const message = buildActionErrorMessage(error, "移除发票失败"); setInvoiceActionError(message); toast.error(message); }, }); const uploadInvoiceMutation = useMutation({ mutationFn: async (files: File[]) => { const ownerEmployeeId = detailQuery.data?.ownerId; if (!ownerEmployeeId) { throw new Error("missing ownerEmployeeId"); } if (!files.length) { throw new Error("请选择发票文件"); } const uploadFailures: Array<{ file: File; message: string }> = []; const pendingById = new Map(); const availableIds: string[] = []; const ocrFailures: string[] = []; const bindFailures: string[] = []; let boundCount = 0; setInvoiceUploadProgress({ completed: 0, total: files.length }); for (const [index, file] of files.entries()) { try { const result = await uploadInvoice(file, "vat", ownerEmployeeId); if (result.uploadAction === "blocked" || !result.invoicePoolId) { uploadFailures.push({ file, message: resolveInvoiceUserMessage(result), }); } else if (result.status === "available") { availableIds.push(result.invoicePoolId); } else if (result.status === "pending_ocr") { pendingById.set(result.invoicePoolId, file.name); } else { uploadFailures.push({ file, message: resolveInvoiceUserMessage(result), }); } } catch (error) { uploadFailures.push({ file, message: buildActionErrorMessage(error, "上传发票失败") }); } setInvoiceUploadProgress({ completed: index + 1, total: files.length }); } setPendingOcrInvoiceIds((previous) => Array.from(new Set([...previous, ...Array.from(pendingById.keys())])), ); for (const invoiceId of availableIds) { try { await bindInvoice(invoiceId, { reimbursementId }); boundCount += 1; } catch (error) { bindFailures.push(`新上传发票:${buildActionErrorMessage(error, "添加发票失败")}`); } } return { uploadedCount: files.length - uploadFailures.length, uploadFailures, boundCount, bindFailures, pendingIds: Array.from(pendingById.keys()), ocrFailures, }; }, onSuccess: async (result) => { setInvoiceSearchInput(""); setInvoiceSearch(""); setSelectedInvoiceFiles(result.uploadFailures.map((item) => item.file)); setPendingOcrInvoiceIds((previous) => Array.from(new Set([...previous, ...result.pendingIds]))); await queryClient.invalidateQueries({ queryKey: ["invoice-pool"] }); await queryClient.invalidateQueries({ queryKey: ["reimbursements"] }); await queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }); await bindableInvoicesQuery.refetch(); const blockingMessages = [ ...result.uploadFailures.map((item) => `${item.file.name}: ${item.message}`), ...result.ocrFailures, ...result.bindFailures, ]; if (blockingMessages.length) { const message = blockingMessages.join(";"); setInvoiceActionError(message); toast.error(`发票上传完成:${result.uploadedCount} 张已上传,${blockingMessages.length} 项需处理`); return; } setInvoiceActionError(""); if (result.pendingIds.length) { toast.success(`已上传 ${result.pendingIds.length} 张发票,识别完成后会自动添加`); return; } toast.success(`发票上传完成:${result.boundCount || result.uploadedCount} 张已添加`); }, onSettled: () => setInvoiceUploadProgress({ completed: 0, total: 0 }), onError: (error) => { const message = buildActionErrorMessage(error, "上传发票失败"); setInvoiceActionError(message); toast.error(message); }, }); const uploadAttachmentsMutation = useMutation({ mutationFn: async (files: File[]) => { if (!files.length) { throw new Error("请选择附件材料"); } return uploadReimbursementAttachments(reimbursementId, files); }, onSuccess: async () => { setSelectedAttachmentFiles([]); await queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }); toast.success("附件材料已上传"); }, onError: (error) => { toast.error(buildActionErrorMessage(error, "上传附件失败")); }, }); const deleteAttachmentMutation = useMutation({ mutationFn: ({ attachmentId, reason }: { attachmentId: string; reason: string }) => deleteReimbursementAttachment(reimbursementId, attachmentId, reason), onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["reimbursements", reimbursementId] }); setDeleteAttachmentTarget(null); toast.success("附件材料已删除"); }, onError: (error) => { toast.error(buildActionErrorMessage(error, "删除附件失败")); }, }); const { requestDownloadReason, downloadReasonDialog } = useAttachmentDownloadReasonDialog(); const openAttachmentMutation = useMutation({ mutationFn: ({ attachmentId, reason }: { attachmentId: string; reason?: string }) => downloadReimbursementAttachment(reimbursementId, attachmentId, reason), onSuccess: (result) => { const url = URL.createObjectURL(result.blob); window.open(url, "_blank", "noopener,noreferrer"); window.setTimeout(() => URL.revokeObjectURL(url), 60_000); }, onError: (error) => { toast.error(buildActionErrorMessage(error, "打开附件失败")); }, }); async function handleOpenAttachment(attachment: { id: string; originalName?: string } & AttachmentGovernanceFields) { const reason = await requestDownloadReason(attachment); if (reason === null) { return; } openAttachmentMutation.mutate({ attachmentId: attachment.id, reason }); } if (!reimbursementId) { return (

缺少 reimbursementId 参数。

); } if (detailQuery.isLoading) { return ; } if (detailQuery.isError || !detailQuery.data) { const message = isApiError(detailQuery.error) ? `${detailQuery.error.code}: ${mapApiErrorMessage( detailQuery.error.code, detailQuery.error.details, detailQuery.error.message, )}` : "加载报销详情失败"; return (

{message}

); } const detail = detailQuery.data; const payment = detail.payment ?? { paymentVoucherNo: null, paymentDate: null, paymentChannel: null, paidAt: null, paidBy: null, }; const displayCode = resolveReimbursementDisplayCode(detail); const budgetHint = detail.budgetHint; const canPay = hasPermission(permissions, "expense.finance.pay"); const canEditItems = ["draft", "rejected"].includes(detail.status); const isReimbursementParticipant = Boolean(me?.id) && [detail.ownerId, detail.submitterId].includes(me?.id ?? ""); const pendingTaskId = detail.pendingWorkflow?.task?.id ?? null; const canRemindPendingWorkflow = Boolean( detail.status === "reviewing" && pendingTaskId && isReimbursementParticipant && detail.pendingWorkflow?.task?.assignee_id !== me?.id, ); const canOpenInvoiceBindDialog = canEditItems && isReimbursementParticipant && canUploadInvoice && canViewOwnInvoice; const canUnbindInvoices = canEditItems && (isReimbursementParticipant || canViewAllExpense); const canDeleteReimbursement = detail.status === "draft" && canDeleteExpense && (isReimbursementParticipant || canViewAllExpense); const precheckStandardChecks = reimbursementPrecheckQuery.data?.standardChecks ?? []; const blockStandardChecks = precheckStandardChecks.filter((item) => item.exceeded && item.controlMode === "block"); const warnStandardChecks = precheckStandardChecks.filter((item) => item.exceeded && item.controlMode === "warn"); const missingInvoiceSubmitMessage = "提交前需先添加至少 1 张发票。"; const submitInvoiceNotice = canEditItems && detail.invoices.length < 1 ? missingInvoiceSubmitMessage : ""; const selectedInvoiceEntries = Object.entries(selectedInvoices); function handleInvoicePdfSelection(files: FileList | null) { const { accepted, rejected } = splitPdfFiles(files); setSelectedInvoiceFiles(accepted); const message = rejectedPdfMessage(rejected); setActionError(message); if (message) { toast.warning(message); } } const expenseTypes = expenseTypesQuery.data?.items ?? []; const computeEditorDefaults = (item?: ReimbursementItem): ItemEditorInitialValues => { const defaultDate = item?.expenseDate ?? detail.reimbursementDate ?? new Date().toISOString().slice(0, 10); const defaultExpenseTypeId = item?.expenseTypeId ?? expenseTypes[0]?.id ?? ""; return { expenseDate: defaultDate, expenseTypeId: defaultExpenseTypeId, amount: item?.amount ?? "", description: item?.description ?? "", }; }; const startCreateItem = () => { runGuarded(() => { setItemEditor({ mode: "create" }); setEditorInitialValues(computeEditorDefaults()); setItemError(""); }); }; const startEditItem = (item: ReimbursementItem) => { runGuarded(() => { setItemEditor({ mode: "edit", itemId: item.id }); setEditorInitialValues(computeEditorDefaults(item)); setItemError(""); }); }; const handleItemSave = (data: ItemEditorSaveData) => { itemSaveMutation.mutate(data); }; const handleItemCancel = () => { runGuarded(() => { setItemEditor(null); setItemError(""); }); }; const handleSubmitAction = async () => { if (!reimbursementId) { return; } try { setActionError(""); if (detail.invoices.length < 1) { setActionError(missingInvoiceSubmitMessage); toast.error(missingInvoiceSubmitMessage); return; } const precheck = await precheckReimbursement(reimbursementId); const message = buildPrecheckDialogMessage(precheck); if (precheck.decision === "block") { setActionError(message); toast.error("提交前校验未通过"); return; } if (precheck.decision === "warn" || precheck.decision === "manual_review") { setSubmitConfirmPrecheck(precheck); return; } mutation.mutate({ action: "submit" }); } catch (error) { if (isApiError(error)) { const message = `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`; setActionError(message); toast.error(message); return; } if (error instanceof Error) { setActionError(error.message); toast.error(error.message); return; } setActionError("提交前校验失败,请稍后重试"); toast.error("提交前校验失败,请稍后重试"); } }; const handleInvoiceDialogOpenChange = (open: boolean) => { setIsInvoiceDialogOpen(open); if (!open) { setInvoiceSearchInput(""); setInvoiceSearch(""); setSelectedInvoices({}); setSelectedInvoiceFiles([]); setInvoiceActionError(""); setPendingOcrInvoiceIds([]); } }; const toggleInvoiceSelection = (invoiceId: string, checked: boolean) => { setSelectedInvoices((previous) => { if (!checked) { const next = { ...previous }; delete next[invoiceId]; return next; } return { ...previous, [invoiceId]: previous[invoiceId] ?? "", }; }); }; const handleBindSelectedInvoices = () => { if (!selectedInvoiceEntries.length) { return; } bindInvoicesMutation.mutate( selectedInvoiceEntries.map(([invoiceId]) => ({ invoiceId, linkedItemId: undefined, })), ); }; const resolveLinkedItemLabel = (linkedItemId: string | null) => { if (!linkedItemId) { return "自动生成或匹配明细"; } const linkedItem = detail.items.find((item) => item.id === linkedItemId); if (!linkedItem) { return "未识别明细"; } return `${linkedItem.expenseType?.name ?? "未识别费用类型"} · ${linkedItem.description ?? "未填写说明"}`; }; const itemCount = detail.items.length; const invoiceCount = detail.invoices.length; const hasBlockingPrecheck = blockStandardChecks.length > 0; const currentHandlerText = (() => { if (detail.status === "reviewing") { return detail.pendingWorkflow?.task?.step_name ?? "当前审批节点"; } if (detail.status === "approved") { return canPay ? "财务处理" : "等待财务"; } if (detail.status === "paid") { return payment.paidBy?.name ?? "财务已处理"; } if (["draft", "rejected"].includes(detail.status)) { return detail.owner?.name ?? "报销人"; } return "-"; })(); const nextStepText = (() => { if (["draft", "rejected"].includes(detail.status)) { if (!itemCount) { return "补报销明细"; } if (!invoiceCount) { return "添加发票"; } if (hasBlockingPrecheck) { return "修改超标明细"; } return "提交审批"; } if (detail.status === "reviewing") { return detail.workflowProgress ? `查看第 ${detail.workflowProgress.currentStepIndex + 1} / ${detail.workflowProgress.totalSteps} 步` : "查看审批进度"; } if (detail.status === "approved") { return "等待财务处理"; } if (detail.status === "paid") { return "查看付款结果"; } return "查看记录"; })(); const primaryAction = (() => { if (["draft", "rejected"].includes(detail.status) && canEditItems) { if (!itemCount) { return ( ); } if (!invoiceCount) { return ( ); } return ( ); } if (detail.status === "reviewing") { return ( ); } if (detail.status === "approved") { return ( ); } if (detail.status === "paid") { return ( ); } return ( ); })(); const secondaryActions = [ detail.status === "reviewing" && canRemindPendingWorkflow && pendingTaskId ? ( ) : detail.status === "paid" ? ( ) : ( ), , ]; return ( {downloadReasonDialog} 报销日期:{detail.reimbursementDate ?? "-"} 报销人:{detail.owner?.name ?? "-"} 提交人:{detail.submitter?.name ?? "-"} 金额:{detail.totalAmount ?? "-"} )} actions={(
{primaryAction} {secondaryActions}
)} />
下一步
{nextStepText}
状态
{reimbursementStatusLabel(detail.status)}
处理人
{currentHandlerText}
金额
¥{detail.totalAmount ?? "-"}
材料完整性
{materialCompletenessLabel(itemCount, "条明细")} / {materialCompletenessLabel(invoiceCount, "张发票")}
{actionError ? (

{actionError}

) : null} {submitInvoiceNotice ? (

{submitInvoiceNotice}

) : null} {hasBlockingPrecheck ? (

请修改超标明细后提交。

) : null}
{["approved", "paid"].includes(detail.status) ? (

付款状态

{detail.status === "paid" ? "已付款" : "未付款"}
付款日期
{payment.paymentDate ?? "-"}
付款凭证号
{payment.paymentVoucherNo ?? "-"}
付款渠道
{paymentChannelLabel(payment.paymentChannel)}
操作人 / 时间
{payment.paidBy?.name ?? "-"} · {formatDateTime(payment.paidAt)}
) : null} {showSecondaryDetail ? (

更多入口

低频操作集中在这里,材料和关联事项已放在主内容区。

{detail.status !== "paid" ? ( ) : null} {canDeleteReimbursement ? ( ) : null}
) : null}
报销编号
{displayCode}
报销日期
{detail.reimbursementDate ?? "-"}
提交人 / 报销人
{detail.submitter?.name ?? "-"} / {detail.owner?.name ?? "-"}
关联项目
{detail.project ? `${detail.project.projectNo} · ${detail.project.name}` : "未关联"}
{detail.description || "未填写报销说明"}

报销明细

明细变更会自动重算总金额。

{canEditItems ? ( ) : (

当前状态不可编辑明细

)}
{itemError ? (

{itemError}

) : null} {reimbursementPrecheckQuery.isLoading && canEditItems ? (

正在刷新费用标准校验结果...

) : null}
费用类型发生日期金额说明操作 {detail.items.length ? ( detail.items.map((item) => ( check.itemId === item.id) ? "bg-red-50/70" : warnStandardChecks.some((check) => check.itemId === item.id) ? "bg-amber-50/70" : "" } >
{item.expenseType?.name ?? "未识别费用类型"}
{item.expenseDate ?? "-"}
{item.amount}
{precheckStandardChecks .filter((check) => check.itemId === item.id) .map((check) => (
标准 ¥{check.maxAmount}/{check.perUnit} {check.exceeded ? `,超出 ¥${check.exceededAmount}` : ""}
))}
{item.description ?? "-"}
{precheckStandardChecks .filter((check) => check.itemId === item.id && check.exceeded) .map((check) => (
{check.standardName}:当前金额超出费用标准。
))}
{canEditItems ? (
) : null}
)) ) : ( 暂无明细 )}
{itemEditor ? ( ) : null}

发票

提交前至少添加 1 张发票;重复或不可用发票会给出原因。

{canOpenInvoiceBindDialog ? ( ) : canEditItems ? (

当前账号不可在此页添加发票

) : null}
{invoiceActionError ? (

{invoiceActionError}

) : null} {(detail.invoices ?? []).length ? (
{detail.invoices.map((item) => { const invoiceHint = resolveInvoiceNextStepText(item); return (
{formatInvoiceDisplayTitle(item)}
{item.sellerName || "未识别销售方"} · {item.invoiceDate ? formatDisplayDate(item.invoiceDate) : "未识别日期"} · 金额 ¥{item.totalAmount ?? "-"}
原始文件:{item.originalName || "未记录原始文件"}
明细:{resolveLinkedItemLabel(item.linkedItemId)}
{resolveInvoiceStatusLabel(item.status)} {canUnbindInvoices ? ( ) : null}
{invoiceHint ? (
{invoiceHint}
) : null}
); })}
) : (

暂无发票

)}

补充附件

合同、订单、支付截图或情况说明;敏感附件下载会要求填写用途。

{canEditItems ? (
setSelectedAttachmentFiles(Array.from(event.target.files ?? []))} />
) : null}
{(detail.attachments ?? []).length ? (
{(detail.attachments ?? []).map((attachment) => (
{attachment.originalName}
{Math.ceil(attachment.fileSize / 1024)} KB · {formatDateTime(attachment.createdAt)}
{canEditItems ? ( ) : null}
))}
) : (

暂无附件材料

)}

关联项目

用于项目执行面板汇总,不在报销详情复制项目流程。

{detail.project ? ( 查看项目 ) : null}
{canEditItems ? ( ) : (
{detail.project ? `${detail.project.projectNo} · ${detail.project.name}` : "未关联项目"}
)}
{detail.linkedTravelRequest ? (

关联差旅申请:{detail.linkedTravelRequest.requestNo ?? "未生成申请编号"}

{detail.linkedTravelRequest.purpose || "未填写出差目的"}

查看申请
日期范围
{detail.linkedTravelRequest.startDate ?? "-"} 至 {detail.linkedTravelRequest.endDate ?? "-"}
预估金额
¥{detail.linkedTravelRequest.estimatedAmount}
申请编号
{detail.linkedTravelRequest.requestNo ?? "未生成申请编号"}
) : (
未关联差旅申请。
)}
{budgetHint ? (

预算提示

预算池:{budgetHint.budgetCode} / {budgetHint.budgetName}
本次提交后预计占用:{budgetHint.nextUsedAmount} / {budgetHint.allocatedAmount} ({budgetHint.nextUsagePercent.toFixed(2)}%)
控制方式:{budgetControlModeLabel(budgetHint.controlMode)}
{budgetHint.exceedsBudget && budgetHint.controlMode === "block" ? (

当前金额将超出预算上限,提交时会被阻断。

) : budgetHint.exceedsThreshold ? (

当前金额已达到预算预警阈值,提交后会记录预算预警审计。

) : (

当前预算充足,可继续提交。

)}
) : null}
{detail.workflowProgress ? (
当前位于第 {detail.workflowProgress.currentStepIndex + 1} / {detail.workflowProgress.totalSteps} 步。
{detail.workflowProgress.steps.map((step, index) => (
第 {index + 1} 步 · {step.name} {step.status === "completed" ? "已完成" : step.status === "current" ? "当前节点" : "待处理"}
))}
) : (
当前没有进行中的审批节点。
)}

审批记录

{detail.approvalHistory.length ? (
{detail.approvalHistory.map((item) => (
{workflowActionLabel(item.action)} {formatDateTime(item.createdAt)}
{item.stepName ?? "-"} · {item.actorName || "系统"}
{item.comment ?
{item.comment}
: null}
))}
) : (
暂无审批记录。
)}
{["draft", "rejected"].includes(detail.status) ? (
补齐明细和 PDF 发票后提交审批;附件作为补充材料放在主内容区。
) : null} {detail.status === "reviewing" ? (
审批动作只在“待我处理”或任务详情执行;如需修改,可撤回后补正。
) : null} {detail.status === "approved" ? (
本页只显示付款状态;付款登记、批量付款和回单处理请进入付款上下文。
{canPay ? ( ) : null}
) : null} {detail.status === "paid" ? (
已付款报销用于查证据、看回单状态和打印归档,不再编辑或重复付款。
) : null} {detail.status === "cancelled" ? (
该报销已取消,仅保留查看和归档记录。
) : null}
0} submitHint="" submitNotice="" isPending={mutation.isPending} onSubmit={() => void handleSubmitAction()} onWithdraw={(comment) => mutation.mutate({ action: "withdraw", comment })} />
添加发票 选择可添加发票,或上传新发票。
setInvoiceSearchInput(event.target.value)} />
{invoiceActionError ? (

{invoiceActionError}

) : null}
{bindableInvoicesQuery.isLoading ? (

正在加载可添加发票...

) : bindableInvoicesQuery.isError ? (

{buildActionErrorMessage(bindableInvoicesQuery.error, "加载可添加发票失败")}

) : (bindableInvoicesQuery.data?.items ?? []).length ? ( bindableInvoicesQuery.data?.items.map((item) => { const isSelected = Object.prototype.hasOwnProperty.call(selectedInvoices, item.id); const invoiceHint = resolveInvoiceNextStepText({ ...item, status: "available" }); return ( ); }) ) : (
当前没有可添加发票,可直接在下方上传新发票。
)}
已选 {selectedInvoiceEntries.length} 张发票
或者上传新发票

仅支持 PDF 发票,可多选。

{ handleInvoicePdfSelection(event.target.files); event.target.value = ""; }} />
{selectedInvoiceFiles.length ? (
{selectedInvoiceFiles.slice(0, 5).map((file) => (
{file.name} · {Math.ceil(file.size / 1024)} KB
))} {selectedInvoiceFiles.length > 5 ?
另有 {selectedInvoiceFiles.length - 5} 个文件
: null}
) : null} {pendingOcrInvoiceIds.length ? (

{invoiceOcrTracker.statusMessage}

) : null}
{ if (!open) { setSubmitConfirmPrecheck(null); } }} > 确认提交报销单? 以下校验项不会阻止提交,但会作为预警或复核信息进入审批流程。 {submitConfirmPrecheck ? (
{buildPrecheckDialogMessage(submitConfirmPrecheck)}
{submitConfirmPrecheck.standardChecks.some((item) => item.exceeded && item.controlMode === "warn") ? (

超出费用标准的明细

{submitConfirmPrecheck.standardChecks .filter((item) => item.exceeded && item.controlMode === "warn") .map((item: ExpenseStandardCheck) => (
{item.expenseTypeName}
当前 ¥{item.amount} / 标准 ¥{item.maxAmount}/{item.perUnit} / 超出 ¥{item.exceededAmount}
{item.standardName}
))}
) : null}
) : null}
{ if (!open) setConfirmDeleteItemId(""); }} title="确认删除该明细?" variant="destructive" confirmLabel="删除" onConfirm={() => { itemDeleteMutation.mutate(confirmDeleteItemId); }} /> { deleteReimbursementMutation.mutate(); }} /> { if (!open) setDeleteAttachmentTarget(null); }} onConfirm={(deleteReason) => { if (!deleteAttachmentTarget) return; deleteAttachmentMutation.mutate({ attachmentId: deleteAttachmentTarget.id, reason: deleteReason }); }} />
); }