文件
hyb-oa/client/src/pages/ReimbursementDetailPage.tsx
T

1841 行
75 KiB
TypeScript
原始文件 Blame 文件历史

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
import { useCallback, useEffect, useState } from "react";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, ChevronRight } from "lucide-react";
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,
fetchReimbursementAttachmentPreviewUrl,
fetchReimbursementDetail,
fetchReimbursementMaterialPreviewBundle,
MAX_REIMBURSEMENT_ATTACHMENT_FILES,
precheckReimbursement,
submitReimbursement,
updateReimbursementItem,
uploadReimbursementAttachments,
withdrawReimbursement,
linkReimbursementProject,
type ReimbursementItem,
} from "../api/reimbursements";
import { remindWorkflowTask } from "../api/workflow";
import {
bindInvoice,
fetchBindableInvoices,
fetchInvoiceSignedUrl,
unbindInvoice,
uploadInvoice,
} from "../api/invoicePool";
import { toast } from "sonner";
import { isWecomWebView } from "../lib/runtimeContext";
import { openFileInBrowser, previewFileInWecom } from "../lib/wecomFilePreview";
import { hasCompleteTravelSummary } from "../lib/reimbursementTravel";
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 { ReimbursementTravelSummary } from "../components/reimbursements/ReimbursementTravelSummary";
import { ReimbursementProcessingProgress } from "../components/reimbursements/ReimbursementProcessingProgress";
import { StatusBadge } from "../components/common/StatusBadge";
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 { EntityOverviewHero } from "../components/patterns/EntityOverviewHero";
import { PageScaffold } from "../components/patterns/PageScaffold";
import { SectionPanel } from "../components/patterns/SectionPanel";
import {
formatInvoiceDisplayTitle,
resolveInvoicePartyText,
resolveInvoiceNextStepText,
resolveInvoiceStatusLabel,
resolveInvoiceUserMessage,
} from "../lib/invoiceStatus";
import { useInvoiceOcrTracker } from "../hooks/useInvoiceOcrTracker";
import { resolveReimbursementDisplayCode } from "../lib/reimbursementDisplay";
import { attachmentRequiresDownloadReason, type AttachmentGovernanceFields } from "../lib/attachmentGovernance";
import { formatDisplayDate, formatDisplayDateTime, formatMoney } from "../lib/displayFormat";
import {
buildPcDetailSource,
resolvePcDetailSource,
type PcDetailNavigationState,
} from "../lib/pcDetailNavigation";
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<string, string>;
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;
}
export function ReimbursementDetailPage() {
const { reimbursementId = "" } = useParams();
const location = useLocation();
const navigate = useNavigate();
const { permissions, me, accessToken } = useAuth();
const queryClient = useQueryClient();
const [actionError, setActionError] = useState("");
const [itemEditor, setItemEditor] = useState<ItemEditorState>(null);
const [itemError, setItemError] = useState("");
const [confirmDeleteItemId, setConfirmDeleteItemId] = useState("");
const [confirmDeleteReimbursement, setConfirmDeleteReimbursement] = useState(false);
const [showSecondaryDetail, setShowSecondaryDetail] = useState(false);
const [submitConfirmPrecheck, setSubmitConfirmPrecheck] = useState<PrecheckResponse | null>(null);
const [isInvoiceDialogOpen, setIsInvoiceDialogOpen] = useState(false);
const [invoiceSearchInput, setInvoiceSearchInput] = useState("");
const [invoiceSearch, setInvoiceSearch] = useState("");
const [selectedInvoices, setSelectedInvoices] = useState<SelectedInvoiceMap>({});
const [selectedInvoiceFiles, setSelectedInvoiceFiles] = useState<File[]>([]);
const [selectedAttachmentFiles, setSelectedAttachmentFiles] = useState<File[]>([]);
const [deleteAttachmentTarget, setDeleteAttachmentTarget] = useState<{ id: string; originalName: string } | null>(null);
const [invoiceActionError, setInvoiceActionError] = useState("");
const [materialPreviewError, setMaterialPreviewError] = useState("");
const [pendingOcrInvoiceIds, setPendingOcrInvoiceIds] = useState<string[]>([]);
const [invoiceUploadProgress, setInvoiceUploadProgress] = useState({ completed: 0, total: 0 });
const [editorInitialValues, setEditorInitialValues] = useState<ItemEditorInitialValues>({
expenseTypeId: "",
expenseDate: "",
amount: "",
description: "",
});
const currentDetailSource = buildPcDetailSource(location.pathname, location.search);
const navigationState = location.state as PcDetailNavigationState | null;
const backSource = resolvePcDetailSource(navigationState?.from, currentDetailSource) ?? "/reimbursements";
const backLabel = backSource.startsWith("/workflow/tasks/") ? "返回审批详情" : "返回报销列表";
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<string, string> = { 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<string, string>();
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("请选择附件材料");
}
if (files.length > MAX_REIMBURSEMENT_ATTACHMENT_FILES) {
throw new Error(`单次最多上传 ${MAX_REIMBURSEMENT_ATTACHMENT_FILES} 个附件,请分批上传。`);
}
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 openInvoiceMutation = useMutation({
mutationFn: async (invoiceId: string) => {
const result = await fetchInvoiceSignedUrl(invoiceId);
const openedInWecom = await previewFileInWecom({
url: result.signedUrl,
name: result.originalName,
size: result.fileSize,
});
if (!openedInWecom) {
openFileInBrowser(result.signedUrl);
}
},
onError: (error) => {
toast.error(buildActionErrorMessage(error, "打开发票失败"));
},
});
const openAttachmentMutation = useMutation({
mutationFn: async ({ attachment, reason }: {
attachment: { id: string; originalName: string; fileSize: number } & AttachmentGovernanceFields;
reason?: string;
}) => {
if (isWecomWebView()) {
const result = await fetchReimbursementAttachmentPreviewUrl(reimbursementId, attachment.id, reason);
await previewFileInWecom({ url: result.signedUrl, name: result.originalName, size: result.fileSize });
return null;
}
return downloadReimbursementAttachment(reimbursementId, attachment.id, reason);
},
onSuccess: (result) => {
if (!result) return;
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; fileSize: number } & AttachmentGovernanceFields) {
const reason = await requestDownloadReason(attachment);
if (reason === null) {
return;
}
openAttachmentMutation.mutate({ attachment, reason });
}
const materialPreviewMutation = useMutation({
mutationFn: (reason?: string) => fetchReimbursementMaterialPreviewBundle(reimbursementId, reason),
onSuccess: async (bundle) => {
setMaterialPreviewError("");
if (isWecomWebView()) {
try {
await previewFileInWecom({ url: bundle.signedUrl, name: bundle.originalName, size: bundle.fileSize });
return;
} catch {
toast.error("企业微信材料预览未打开,已切换到浏览器预览");
}
}
openFileInBrowser(bundle.signedUrl);
},
onError: (error) => {
const message = buildActionErrorMessage(error, "连续预览生成失败,可逐份打开原件");
setMaterialPreviewError(message);
toast.error("连续预览生成失败,可逐份打开原件");
},
});
async function handleOpenAllMaterials() {
const governedAttachment = (detailQuery.data?.attachments ?? []).find(attachmentRequiresDownloadReason);
const reason = governedAttachment ? await requestDownloadReason(governedAttachment) : undefined;
if (reason === null) return;
materialPreviewMutation.mutate(reason);
}
if (!reimbursementId) {
return (
<div className="card-std p-5">
<p className="text-sm text-red-600">缺少 reimbursementId 参数。</p>
</div>
);
}
if (detailQuery.isLoading) {
return <CardSkeleton lines={8} />;
}
if (detailQuery.isError || !detailQuery.data) {
const message = isApiError(detailQuery.error)
? `${detailQuery.error.code}: ${mapApiErrorMessage(
detailQuery.error.code,
detailQuery.error.details,
detailQuery.error.message,
)}`
: "加载报销详情失败";
return (
<div className="card-std space-y-3 p-5">
<p className="text-sm text-red-600">{message}</p>
<Button asChild variant="secondary">
<Link replace to={backSource}>{backLabel}</Link>
</Button>
</div>
);
}
const detail = detailQuery.data;
const displayCode = resolveReimbursementDisplayCode(detail);
const budgetHint = detail.budgetHint;
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 (!hasCompleteTravelSummary(detail)) {
const message = "请先补全出差事由、地点和起止日期";
setActionError(message);
toast.error(message);
return;
}
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 processingProgress = detail.processingProgress ?? { stages: [] };
const currentProcessingStage = processingProgress.stages.find((stage) =>
stage.state === "current" || stage.state === "exception",
);
const currentHandlerText = currentProcessingStage
? `${currentProcessingStage.label}${currentProcessingStage.actorName ? ` · ${currentProcessingStage.actorName}` : ""}`
: detail.status === "paid" ? "已完成" : "待处理";
const nextStepText = (() => {
if (["draft", "rejected"].includes(detail.status)) {
if (!itemCount) {
return "补报销明细";
}
if (!invoiceCount) {
return "添加发票";
}
if (hasBlockingPrecheck) {
return "修改超标明细";
}
return "提交审批";
}
if (detail.status === "reviewing") {
return currentProcessingStage?.detail ?? "查看处理进度";
}
if (detail.status === "approved") {
return "等待财务处理";
}
if (detail.status === "paid") {
return "查看付款结果";
}
return "查看记录";
})();
const showReviewHints = Boolean(budgetHint || detail.riskFlags.length);
const primaryAction = (() => {
if (["draft", "rejected"].includes(detail.status) && canEditItems) {
if (!itemCount) {
return (
<Button
data-testid="reimbursement-primary-action"
disabled={itemSaveMutation.isPending || itemDeleteMutation.isPending}
onClick={startCreateItem}
type="button"
>
新增明细
</Button>
);
}
if (!invoiceCount) {
return (
<Button
data-testid="reimbursement-primary-action"
disabled={!canOpenInvoiceBindDialog}
onClick={() => handleInvoiceDialogOpenChange(true)}
type="button"
>
添加发票
</Button>
);
}
return (
<Button
data-testid={TEST_IDS.reimbursement.submit}
disabled={mutation.isPending || hasBlockingPrecheck}
onClick={() => void handleSubmitAction()}
type="button"
>
{mutation.isPending ? "提交中..." : "提交报销"}
</Button>
);
}
if (detail.status === "reviewing") {
return (
<Button asChild data-testid="reimbursement-primary-action">
<a href="#reimbursement-workflow-progress-panel">看审批进度</a>
</Button>
);
}
if (detail.status === "approved") {
return (
<Button asChild data-testid="reimbursement-primary-action">
<a href="#reimbursement-processing-progress-panel">看处理进度</a>
</Button>
);
}
if (detail.status === "paid") {
return (
<Button asChild data-testid="reimbursement-primary-action">
<a href="#reimbursement-processing-progress-panel">查看付款结果</a>
</Button>
);
}
return null;
})();
const hasMoreActions = detail.status !== "paid" || canDeleteReimbursement;
const secondaryActions = [
detail.status === "reviewing" && canRemindPendingWorkflow && pendingTaskId ? (
<Button
key="remind"
data-testid="reimbursement-remind-workflow"
disabled={remindMutation.isPending}
onClick={() => remindMutation.mutate(pendingTaskId)}
type="button"
variant="secondary"
>
{remindMutation.isPending ? "催办中..." : "催办审批"}
</Button>
) : null,
detail.status === "paid" ? (
<Button key="print" asChild variant="secondary">
<Link to={`/reimbursements/${detail.id}/print`}>打印 / PDF</Link>
</Button>
) : null,
hasMoreActions ? (
<Button
key="more"
type="button"
variant="secondary"
data-testid="reimbursement-more-toggle"
onClick={() => setShowSecondaryDetail((value) => !value)}
>
{showSecondaryDetail ? "收起更多" : "更多"}
</Button>
) : null,
];
return (
<PageScaffold>
{downloadReasonDialog}
<div>
<Button asChild className="min-h-11 px-2" data-testid="reimbursement-back" variant="ghost">
<Link replace to={backSource}>
<ArrowLeft aria-hidden="true" className="size-4" />
{backLabel}
</Link>
</Button>
</div>
<EntityOverviewHero
title={`报销详情 ${displayCode}`}
meta={(
<>
<StatusBadge status={detail.status} />
</>
)}
actions={(
<div className="flex flex-wrap gap-2" data-testid="reimbursement-first-screen-actions">
{primaryAction}
{secondaryActions}
</div>
)}
/>
<div className="mx-auto w-full max-w-5xl space-y-5">
<div className="space-y-5">
<SectionPanel title="报销概况">
<div className="detail-command-panel space-y-4" data-testid="reimbursement-overview">
<div>
<div className="text-xs font-semibold text-zinc-500">下一步</div>
<div className="mt-1 text-xl font-semibold text-zinc-900">{nextStepText}</div>
</div>
<div data-testid="reimbursement-business-summary">
<div className="detail-fact-grid xl:grid-cols-3" data-testid="reimbursement-summary">
<div className="detail-fact-card">
<div className="detail-fact-card__label">金额</div>
<div className="detail-fact-card__value">{formatMoney(detail.totalAmount)}</div>
</div>
<div className="detail-fact-card">
<div className="detail-fact-card__label">当前处理</div>
<div className="detail-fact-card__value">{currentHandlerText}</div>
</div>
<div className="detail-fact-card">
<div className="detail-fact-card__label">部门</div>
<div className="detail-fact-card__value">
{detail.department?.name ?? "-"}
</div>
</div>
<div className="detail-fact-card">
<div className="detail-fact-card__label">报销日期</div>
<div className="detail-fact-card__value">{detail.reimbursementDate ?? "-"}</div>
</div>
<div className="detail-fact-card">
<div className="detail-fact-card__label">提交人 / 报销人</div>
<div className="detail-fact-card__value">{detail.submitter?.name ?? "-"} / {detail.owner?.name ?? "-"}</div>
</div>
<div className="detail-fact-card">
<div className="detail-fact-card__label">关联项目</div>
<div className="detail-fact-card__value">
{detail.project ? `${detail.project.projectNo} · ${detail.project.name}` : "未关联"}
</div>
</div>
</div>
{detail.description ? (
<div className="mt-3 rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm text-zinc-600">
{detail.description}
</div>
) : null}
<ReimbursementTravelSummary
detail={detail}
reimbursementId={reimbursementId}
editable={Boolean(canEditItems && isReimbursementParticipant)}
embedded
/>
{canEditItems || detail.project || detail.linkedTravelRequest ? (
<div className="mt-4 border-t border-zinc-200 pt-4 text-sm" data-testid="reimbursement-related-records">
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="font-medium text-zinc-900">关联事项</span>
{detail.linkedTravelRequest ? (
<Link to={`/travel-requests?tab=requests&id=${detail.linkedTravelRequest.id}`} className="text-primary hover:underline">
差旅申请 {detail.linkedTravelRequest.requestNo ?? "未编号"}
</Link>
) : null}
</div>
{canEditItems ? (
<select
className="select-std mt-3 max-w-xl"
value={detail.projectId ?? ""}
onChange={(event) => projectLinkMutation.mutate(event.target.value || null)}
disabled={projectLinkMutation.isPending}
aria-label="关联项目"
>
<option value="">不关联项目</option>
{(projectsQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>{item.projectNo} · {item.name}</option>
))}
</select>
) : detail.project ? (
<Link className="mt-2 inline-block text-primary hover:underline" to={`/projects/${detail.project.id}`}>
项目 {detail.project.projectNo} · {detail.project.name}
</Link>
) : null}
</div>
) : null}
</div>
{actionError ? (
<p
className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"
data-testid="reimbursement-action-error"
>
{actionError}
</p>
) : null}
{submitInvoiceNotice ? (
<p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
{submitInvoiceNotice}
</p>
) : null}
{hasBlockingPrecheck ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
请修改超标明细后提交。
</p>
) : null}
{showReviewHints ? (
<div className="space-y-3" data-testid="reimbursement-review-hints">
{budgetHint ? (
<p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
预算 {budgetHint.budgetCode}:提交后预计使用 {budgetHint.nextUsagePercent.toFixed(2)}%
{budgetHint.exceedsThreshold ? ",已达到预警阈值。" : "。"}
</p>
) : null}
{detail.riskFlags.length ? <RiskFlagsCard items={detail.riskFlags} title="待处理风险项" /> : null}
</div>
) : null}
</div>
{showSecondaryDetail ? (
<div className="space-y-4 pt-4" data-testid="reimbursement-secondary-detail">
<div className="detail-command-panel">
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<h4 className="text-base font-semibold text-zinc-900">更多</h4>
<div className="flex flex-wrap gap-2">
{detail.status !== "paid" ? (
<Button asChild variant="secondary">
<Link to={`/reimbursements/${detail.id}/print`}>打印 / PDF</Link>
</Button>
) : null}
{canDeleteReimbursement ? (
<Button
data-testid="reimbursement-delete-draft"
disabled={deleteReimbursementMutation.isPending}
onClick={() => setConfirmDeleteReimbursement(true)}
type="button"
variant="destructive"
>
删除草稿
</Button>
) : null}
</div>
</div>
</div>
</div>
) : null}
</SectionPanel>
<SectionPanel title="报销明细">
<div className="space-y-4">
<div className="space-y-4" data-testid="reimbursement-items">
{canEditItems ? (
<div className="flex justify-end">
<Button
data-testid="reimbursement-item-add"
disabled={itemSaveMutation.isPending || itemDeleteMutation.isPending}
onClick={startCreateItem}
type="button"
variant="secondary"
>
新增明细
</Button>
</div>
) : null}
{itemError ? (
<p
className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"
data-testid="reimbursement-item-error"
>
{itemError}
</p>
) : null}
{reimbursementPrecheckQuery.isLoading && canEditItems ? (
<p className="text-sm text-zinc-500">正在刷新费用标准校验结果...</p>
) : null}
<div className="ops-table-focus overflow-x-auto border border-zinc-200">
<Table data-testid="reimbursement-items-table">
<TableHeader>
<tr>
<TableHead>费用类型</TableHead>
<TableHead>发生日期</TableHead>
<TableHead>金额</TableHead>
<TableHead>说明</TableHead>
<TableHead className="w-44">操作</TableHead>
</tr>
</TableHeader>
<TableBody>
{detail.items.length ? (
detail.items.map((item) => (
<TableRow
data-testid="reimbursement-item-row"
key={item.id}
className={
blockStandardChecks.some((check) => check.itemId === item.id)
? "bg-red-50/70"
: warnStandardChecks.some((check) => check.itemId === item.id)
? "bg-amber-50/70"
: ""
}
>
<TableCell>
<div className="font-medium text-zinc-900">
{item.expenseType?.name ?? "未识别费用类型"}
</div>
</TableCell>
<TableCell>{item.expenseDate ?? "-"}</TableCell>
<TableCell>
<div>{formatMoney(item.amount)}</div>
{precheckStandardChecks
.filter((check) => check.itemId === item.id)
.map((check) => (
<div
key={check.standardId}
className={`mt-1 text-xs ${check.exceeded ? (check.controlMode === "block" ? "text-red-600" : "text-amber-600") : "text-zinc-500"}`}
>
标准 {formatMoney(check.maxAmount)}/{check.perUnit}
{check.exceeded ? `,超出 ${formatMoney(check.exceededAmount)}` : ""}
</div>
))}
</TableCell>
<TableCell>
<div>{item.description ?? "-"}</div>
{precheckStandardChecks
.filter((check) => check.itemId === item.id && check.exceeded)
.map((check) => (
<div
key={`${check.standardId}-warning`}
className={`mt-1 text-xs ${check.controlMode === "block" ? "text-red-600" : "text-amber-600"}`}
>
{check.standardName}:当前金额超出费用标准。
</div>
))}
</TableCell>
<TableCell>
{canEditItems ? (
<div className="flex min-w-36 items-center gap-2">
<Button
data-testid="reimbursement-item-edit"
className="min-w-16"
size="sm"
type="button"
variant="secondary"
onClick={() => startEditItem(item)}
>
编辑
</Button>
<Button
data-testid="reimbursement-item-delete"
className="min-w-16"
size="sm"
type="button"
variant="secondary"
disabled={itemDeleteMutation.isPending}
onClick={() => setConfirmDeleteItemId(item.id)}
>
删除
</Button>
</div>
) : null}
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell className="py-3 text-zinc-500" colSpan={5}>
暂无明细
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
{itemEditor ? (
<ReimbursementItemEditor
mode={itemEditor.mode}
expenseTypes={expenseTypes}
expenseTypesLoading={expenseTypesQuery.isLoading}
expenseTypesError={expenseTypesQuery.isError}
departmentId={detail.departmentId}
initialValues={editorInitialValues}
onSave={handleItemSave}
onCancel={handleItemCancel}
isPending={itemSaveMutation.isPending}
/>
) : null}
</div>
</div>
</SectionPanel>
<SectionPanel title="报销材料">
<div className="space-y-4 text-sm" data-testid="reimbursement-materials">
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<p className="text-sm text-zinc-600">
发票 {detail.invoices.length} · 补充附件 {(detail.attachments ?? []).length}
<span className="mt-1 block text-xs text-zinc-500">打开后上下滚动,连续查看全部材料。合并预览仅供核对,原始文件另行保留。</span>
</p>
<div className="flex flex-wrap gap-2">
{detail.invoices.length || (detail.attachments ?? []).length ? (
<Button
data-testid="reimbursement-materials-open-all"
type="button"
disabled={materialPreviewMutation.isPending}
onClick={() => void handleOpenAllMaterials()}
>
{materialPreviewMutation.isPending ? "正在准备材料预览…" : "查看材料合并预览"}
</Button>
) : null}
{canOpenInvoiceBindDialog ? (
<Button
data-testid={TEST_IDS.reimbursement.invoiceAdd}
type="button"
variant="secondary"
onClick={() => handleInvoiceDialogOpenChange(true)}
>
添加发票
</Button>
) : null}
</div>
</div>
{materialPreviewError ? (
<p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
{materialPreviewError},可在下方逐份打开原件。
</p>
) : null}
{invoiceActionError ? (
<p
className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"
data-testid={TEST_IDS.reimbursement.invoiceActionError}
>
{invoiceActionError}
</p>
) : null}
<div className="space-y-2" data-testid={TEST_IDS.reimbursement.invoices}>
{detail.invoices.map((invoice) => {
const invoiceHint = resolveInvoiceNextStepText(invoice);
return (
<div className="detail-evidence-card flex flex-col gap-3 md:flex-row md:items-center" key={invoice.id}>
<button
type="button"
className="flex min-h-11 min-w-0 flex-1 items-center gap-3 rounded-md text-left transition-colors hover:bg-white active:bg-zinc-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 disabled:cursor-wait disabled:opacity-60"
disabled={openInvoiceMutation.isPending}
aria-label={`查看发票原件:${formatInvoiceDisplayTitle(invoice)}`}
onClick={() => openInvoiceMutation.mutate(invoice.id)}
>
<span className="inline-flex shrink-0 rounded-full bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700">发票</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-zinc-900">{formatInvoiceDisplayTitle(invoice)}</span>
<span className="mt-1 block text-xs text-zinc-500">
{[resolveInvoicePartyText(invoice), invoice.invoiceDate ? formatDisplayDate(invoice.invoiceDate) : "", formatMoney(invoice.totalAmount)].filter(Boolean).join(" · ")}
</span>
<span className="mt-1 block text-xs text-zinc-500">明细:{resolveLinkedItemLabel(invoice.linkedItemId)}</span>
{invoiceHint ? <span className="mt-1 block text-xs text-zinc-500">{invoiceHint}</span> : null}
</span>
<span className="badge-neutral shrink-0">{resolveInvoiceStatusLabel(invoice.status)}</span>
<ChevronRight aria-hidden="true" className="size-4 shrink-0 text-zinc-400" />
</button>
{canUnbindInvoices ? (
<Button
type="button"
variant="secondary"
size="sm"
disabled={unbindInvoiceMutation.isPending}
onClick={() => unbindInvoiceMutation.mutate(invoice.id)}
>
移除
</Button>
) : null}
</div>
);
})}
</div>
<div className="space-y-4" data-testid="reimbursement-attachments">
{canEditItems ? (
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<p className="text-xs text-zinc-500">支持 PDF/JPG/PNG/WebP,单次最多 5 个。</p>
<div className="flex flex-col gap-2 md:flex-row md:items-center">
<label
htmlFor="reimbursement-attachment-upload"
className="inline-flex cursor-pointer items-center justify-center rounded-md border border-dashed border-zinc-300 bg-white px-4 py-2 text-sm font-medium text-zinc-600 transition-colors hover:bg-zinc-100 hover:text-zinc-900"
>
{selectedAttachmentFiles.length
? selectedAttachmentFiles.length === 1
? selectedAttachmentFiles[0].name
: `已选择 ${selectedAttachmentFiles.length} 个文件`
: "选择附件"}
</label>
<input
id="reimbursement-attachment-upload"
className="hidden"
type="file"
accept="application/pdf,image/jpeg,image/png,image/webp"
multiple
onChange={(event) => {
const files = Array.from(event.target.files ?? []);
if (files.length > MAX_REIMBURSEMENT_ATTACHMENT_FILES) {
setSelectedAttachmentFiles([]);
event.target.value = "";
toast.error(`单次最多上传 ${MAX_REIMBURSEMENT_ATTACHMENT_FILES} 个附件,请分批上传。`);
return;
}
setSelectedAttachmentFiles(files);
}}
/>
<Button
type="button"
variant="secondary"
disabled={!selectedAttachmentFiles.length || uploadAttachmentsMutation.isPending}
onClick={() => uploadAttachmentsMutation.mutate(selectedAttachmentFiles)}
>
{uploadAttachmentsMutation.isPending ? "上传中..." : "上传附件"}
</Button>
</div>
</div>
) : null}
{(detail.attachments ?? []).length ? (
<div className="space-y-2">
{(detail.attachments ?? []).map((attachment) => (
<div key={attachment.id} className="detail-evidence-card flex flex-col gap-3 md:flex-row md:items-center">
<button
type="button"
className="flex min-h-11 min-w-0 flex-1 items-center gap-3 rounded-md text-left transition-colors hover:bg-white active:bg-zinc-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 disabled:cursor-wait disabled:opacity-60"
disabled={openAttachmentMutation.isPending}
aria-label={`查看补充附件:${attachment.originalName}`}
onClick={() => void handleOpenAttachment(attachment)}
>
<span className="inline-flex shrink-0 rounded-full bg-zinc-100 px-2 py-1 text-xs font-medium text-zinc-600">补充附件</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-zinc-900">{attachment.originalName}</span>
<span className="mt-1 block text-xs text-zinc-500">
{Math.ceil(attachment.fileSize / 1024)} KB · {formatDisplayDateTime(attachment.createdAt)}
</span>
<AttachmentGovernanceBadges attachment={attachment} className="mt-2" />
</span>
<ChevronRight aria-hidden="true" className="size-4 shrink-0 text-zinc-400" />
</button>
{canEditItems ? (
<Button
type="button"
variant="destructive"
size="sm"
disabled={deleteAttachmentMutation.isPending}
onClick={() => setDeleteAttachmentTarget({ id: attachment.id, originalName: attachment.originalName })}
>
删除
</Button>
) : null}
</div>
))}
</div>
) : detail.invoices.length ? null : (
<p className="text-sm text-zinc-500">暂无报销材料</p>
)}
</div>
</div>
</SectionPanel>
<SectionPanel title="处理进度">
<div id="reimbursement-processing-progress-panel">
<ReimbursementProcessingProgress progress={processingProgress} />
</div>
</SectionPanel>
</div>
<div className="space-y-5">
<ReimbursementActions
status={detail.status}
showSubmitAction={false}
actionError={["reviewing", "approved"].includes(detail.status) ? actionError : ""}
submitDisabled={blockStandardChecks.length > 0}
submitHint=""
submitNotice=""
isPending={mutation.isPending}
onSubmit={() => void handleSubmitAction()}
onWithdraw={(comment) => mutation.mutate({ action: "withdraw", comment })}
/>
</div>
</div>
<Dialog open={isInvoiceDialogOpen} onOpenChange={handleInvoiceDialogOpenChange}>
<DialogContent
className="max-h-[85vh] max-w-3xl overflow-y-auto"
data-testid={TEST_IDS.reimbursement.invoiceDialog}
>
<DialogHeader>
<DialogTitle>添加发票</DialogTitle>
<DialogDescription>选择可添加发票,或上传新发票。</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="flex flex-col gap-3 md:flex-row md:items-center">
<Input
placeholder="搜索发票号、发票代码或卖方名称"
value={invoiceSearchInput}
onChange={(event) => setInvoiceSearchInput(event.target.value)}
/>
<Button
type="button"
variant="secondary"
disabled={bindableInvoicesQuery.isFetching}
onClick={() => void bindableInvoicesQuery.refetch()}
>
{bindableInvoicesQuery.isFetching ? "刷新中..." : "刷新列表"}
</Button>
</div>
{invoiceActionError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{invoiceActionError}
</p>
) : null}
<div className="max-h-[360px] space-y-3 overflow-y-auto pr-1">
{bindableInvoicesQuery.isLoading ? (
<p className="text-sm text-zinc-500">正在加载可添加发票...</p>
) : bindableInvoicesQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
{buildActionErrorMessage(bindableInvoicesQuery.error, "加载可添加发票失败")}
</p>
) : (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 (
<label
key={item.id}
className={`block rounded-lg border px-4 py-3 ${isSelected ? "border-primary-300 bg-primary-50/50" : "border-zinc-200"}`}
>
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
<div className="flex gap-3">
<input
type="checkbox"
className="mt-1 h-4 w-4 rounded border-zinc-300"
checked={isSelected}
onChange={(event) => toggleInvoiceSelection(item.id, event.target.checked)}
/>
<div className="space-y-1">
<div className="font-medium text-zinc-900">{formatInvoiceDisplayTitle(item)}</div>
<div className="text-zinc-600">
{[resolveInvoicePartyText(item), item.invoiceDate ? formatDisplayDate(item.invoiceDate) : "", `金额 ${formatMoney(item.totalAmount)}`].filter(Boolean).join(" · ")}
</div>
<div className="text-xs text-zinc-500">
原始文件:{item.originalName || "未记录原始文件"} · 上传时间 {formatDisplayDateTime(item.createdAt)}
</div>
</div>
</div>
<div className="min-w-[220px] rounded-md bg-primary-50 px-3 py-2 text-xs text-primary-700 md:max-w-[240px]">
{invoiceHint} 添加后自动生成或匹配报销明细。
</div>
</div>
</label>
);
})
) : (
<div className="rounded-lg border border-dashed border-zinc-300 px-4 py-6 text-center text-sm text-zinc-500">
当前没有可添加发票,可直接在下方上传新发票。
</div>
)}
</div>
<div className="flex flex-col gap-3 rounded-lg border border-zinc-200 bg-zinc-50 px-4 py-3 md:flex-row md:items-center md:justify-between">
<div className="text-sm text-zinc-600">已选 {selectedInvoiceEntries.length} 张发票</div>
<Button
type="button"
disabled={!selectedInvoiceEntries.length || bindInvoicesMutation.isPending}
onClick={handleBindSelectedInvoices}
>
{bindInvoicesMutation.isPending ? "添加中..." : "添加选中发票"}
</Button>
</div>
<div className="rounded-lg border border-dashed border-zinc-300 px-4 py-4">
<div className="space-y-1">
<div className="text-sm font-medium text-zinc-900">或者上传新发票</div>
<p className="text-xs text-zinc-500">仅支持 PDF 发票,可多选。</p>
</div>
<div className="mt-3 flex flex-col gap-3 md:flex-row md:items-center">
<label
htmlFor="reimbursement-inline-invoice-upload"
className="inline-flex cursor-pointer items-center justify-center rounded-md border border-dashed border-zinc-300 bg-white px-4 py-2 text-sm font-medium text-zinc-600 transition-colors hover:bg-zinc-100 hover:text-zinc-900"
>
{selectedInvoiceFiles.length
? selectedInvoiceFiles.length === 1
? selectedInvoiceFiles[0].name
: `已选择 ${selectedInvoiceFiles.length} 个文件`
: "选择发票文件"}
</label>
<input
id="reimbursement-inline-invoice-upload"
className="hidden"
data-testid={TEST_IDS.reimbursement.invoiceUploadFile}
type="file"
accept={PDF_FILE_ACCEPT}
multiple
onChange={(event) => {
handleInvoicePdfSelection(event.target.files);
event.target.value = "";
}}
/>
<Button
data-testid={TEST_IDS.reimbursement.invoiceUploadSubmit}
type="button"
disabled={!selectedInvoiceFiles.length || uploadInvoiceMutation.isPending}
onClick={() => selectedInvoiceFiles.length && uploadInvoiceMutation.mutate(selectedInvoiceFiles)}
>
{uploadInvoiceMutation.isPending
? `上传中 ${invoiceUploadProgress.completed}/${invoiceUploadProgress.total}`
: "上传发票"}
</Button>
</div>
{selectedInvoiceFiles.length ? (
<div className="mt-3 rounded-lg border border-zinc-200 bg-white px-3 py-2 text-xs text-zinc-500">
{selectedInvoiceFiles.slice(0, 5).map((file) => (
<div key={`${file.name}-${file.size}`} className="truncate">
{file.name} · {Math.ceil(file.size / 1024)} KB
</div>
))}
{selectedInvoiceFiles.length > 5 ? <div>另有 {selectedInvoiceFiles.length - 5} 个文件</div> : null}
</div>
) : null}
{pendingOcrInvoiceIds.length ? (
<p className="mt-3 text-xs text-zinc-500" data-testid={TEST_IDS.reimbursement.invoicePendingHint}>
{invoiceOcrTracker.statusMessage}
</p>
) : null}
</div>
</div>
</DialogContent>
</Dialog>
<Dialog
open={Boolean(submitConfirmPrecheck)}
onOpenChange={(open) => {
if (!open) {
setSubmitConfirmPrecheck(null);
}
}}
>
<DialogContent className="max-h-[85vh] max-w-2xl overflow-y-auto">
<DialogHeader>
<DialogTitle>确认提交报销单?</DialogTitle>
<DialogDescription>以下校验项不会阻止提交,但会作为预警或复核信息进入审批流程。</DialogDescription>
</DialogHeader>
{submitConfirmPrecheck ? (
<div className="space-y-4 text-sm">
<div className="rounded-lg border border-zinc-200 bg-zinc-50 p-4 whitespace-pre-wrap">
{buildPrecheckDialogMessage(submitConfirmPrecheck)}
</div>
{submitConfirmPrecheck.standardChecks.some((item) => item.exceeded && item.controlMode === "warn") ? (
<div className="space-y-2">
<h4 className="font-medium text-zinc-900">超出费用标准的明细</h4>
{submitConfirmPrecheck.standardChecks
.filter((item) => item.exceeded && item.controlMode === "warn")
.map((item: ExpenseStandardCheck) => (
<div key={`${item.itemId}-${item.standardId}`} className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-amber-700">
<div className="font-medium">{item.expenseTypeName}</div>
<div>
当前 {formatMoney(item.amount)} / 标准 {formatMoney(item.maxAmount)}/{item.perUnit} / 超出 {formatMoney(item.exceededAmount)}
</div>
<div>{item.standardName}</div>
</div>
))}
</div>
) : null}
<div className="flex justify-end gap-2">
<Button type="button" variant="secondary" onClick={() => setSubmitConfirmPrecheck(null)}>
取消
</Button>
<Button
type="button"
disabled={mutation.isPending}
onClick={() => mutation.mutate({ action: "submit" })}
>
{mutation.isPending ? "提交中..." : "确认提交"}
</Button>
</div>
</div>
) : null}
</DialogContent>
</Dialog>
<ConfirmDialog
open={Boolean(confirmDeleteItemId)}
onOpenChange={(open) => { if (!open) setConfirmDeleteItemId(""); }}
title="确认删除该明细?"
variant="destructive"
confirmLabel="删除"
onConfirm={() => { itemDeleteMutation.mutate(confirmDeleteItemId); }}
/>
<ConfirmDialog
open={confirmDeleteReimbursement}
onOpenChange={setConfirmDeleteReimbursement}
title={`确认删除 ${displayCode}?`}
description="删除后无法恢复,已添加发票会回到可添加状态。"
variant="destructive"
confirmLabel="删除草稿"
onConfirm={() => { deleteReimbursementMutation.mutate(); }}
/>
<AttachmentDeleteConfirmDialog
open={Boolean(deleteAttachmentTarget)}
targetName={deleteAttachmentTarget?.originalName}
pending={deleteAttachmentMutation.isPending}
onOpenChange={(open) => {
if (!open) setDeleteAttachmentTarget(null);
}}
onConfirm={(deleteReason) => {
if (!deleteAttachmentTarget) return;
deleteAttachmentMutation.mutate({ attachmentId: deleteAttachmentTarget.id, reason: deleteReason });
}}
/>
</PageScaffold>
);
}