文件
hyb-oa/client/src/pages/WorkflowTaskDetailPage.tsx
T
wangsli 39c3e808a3
ci-e2e / e2e (push) Canceled after 0s
ci-minimal / check-minimal (push) Canceled after 0s
修复报销详情时区并按 KISS 收敛页面(07-27-yang-jun-reimbursement-readiness)
2026-07-31 16:44:31 +08:00

642 行
26 KiB
TypeScript

import type { ReactNode } from "react";
import { useMemo, useState } from "react";
import { Link, Navigate, 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 {
approveWorkflowTask,
fetchWorkflowApprovers,
fetchWorkflowTaskDetail,
rejectWorkflowTask,
returnWorkflowTask,
transferWorkflowTask,
} from "../api/workflow";
import { toast } from "sonner";
import { useAuth } from "../auth/AuthContext";
import { hasPermission } from "../auth/permissions";
import { buildMobileApprovalsPath, shouldPreferMobileApprovalExperience } from "../pwa";
import { CardSkeleton } from "../components/common/CardSkeleton";
import { ConfirmDialog } from "../components/common/ConfirmDialog";
import { StatusBadge } from "../components/common/StatusBadge";
import {
BusinessDetailActionPanel,
BusinessDetailAside,
BusinessDetailMain,
BusinessDetailWorkspace,
} from "../components/patterns/BusinessDetailTemplate";
import { EntityOverviewHero } from "../components/patterns/EntityOverviewHero";
import { StatStrip } from "../components/patterns/ListWorkspace";
import { MetricCard } from "../components/patterns/MetricCard";
import { PageScaffold } from "../components/patterns/PageScaffold";
import { SectionPanel } from "../components/patterns/SectionPanel";
import { Button } from "../components/ui/button";
import { Textarea } from "../components/ui/textarea";
import { resolvePurchaseDisplayCode } from "../lib/approvalDisplay";
import { formatDisplayDateTime } from "../lib/displayFormat";
import { getWorkflowConfirmCopy, type WorkflowConfirmAction } from "../lib/workflowActionConfirm";
function entityTitle(entityType: string | undefined) {
if (entityType === "leave") {
return "请假申请";
}
if (entityType === "reimbursement") {
return "报销单";
}
if (entityType === "attendance_correction") {
return "考勤修正";
}
if (entityType === "purchase_request") {
return "采购申请";
}
if (entityType === "travel_request") {
return "差旅申请";
}
return entityType || "业务单据";
}
function correctionKindLabel(kind: string | undefined | null) {
if (kind === "missed_punch") return "补卡";
if (kind === "out") return "外出";
if (kind === "overtime") return "加班";
return "考勤修正";
}
function workflowInstanceStatusLabel(status: string | undefined | null) {
if (!status) {
return "-";
}
const labels: Record<string, string> = {
pending: "审批中",
active: "审批中",
approved: "已通过",
rejected: "已驳回",
terminated: "已终止",
cancelled: "已取消",
completed: "已完成",
};
return labels[status] ?? status;
}
function workflowActionLabel(action: string | undefined | null) {
if (!action) {
return "-";
}
const labels: Record<string, string> = {
submit: "提交",
approve: "通过",
reject: "驳回",
return: "退回",
transfer: "转审",
withdraw: "撤回",
remind: "催办",
overdue_remind: "超时提醒",
cancel: "取消",
skip: "跳过",
};
return labels[action] ?? action;
}
function DetailField({ label, value }: { label: string; value: ReactNode }) {
return (
<div className="detail-fact-card">
<dt className="detail-fact-card__label">{label}</dt>
<dd className="detail-fact-card__value">{value || "-"}</dd>
</div>
);
}
function isAlreadyProcessedTaskError(error: unknown) {
return isApiError(error) && error.details?.task === "already_processed";
}
type SecondaryWorkflowAction = "reject" | "return" | "transfer";
export function WorkflowTaskDetailPage() {
const { taskId = "" } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { permissions } = useAuth();
const [rejectComment, setRejectComment] = useState("请补充必要说明后重提");
const [returnComment, setReturnComment] = useState("请补充必要信息并修正后重新提交");
const [transferReason, setTransferReason] = useState("当前事项需转交对应审批人处理,请尽快处理。");
const [selectedApprover, setSelectedApprover] = useState("");
const [actionError, setActionError] = useState("");
const [activeSecondaryAction, setActiveSecondaryAction] = useState<SecondaryWorkflowAction | null>(null);
const [confirmAction, setConfirmAction] = useState<WorkflowConfirmAction | null>(null);
const [transferConfirmOpen, setTransferConfirmOpen] = useState(false);
const detailQuery = useQuery({
enabled: Boolean(taskId),
queryKey: ["workflow", "task", taskId],
queryFn: () => fetchWorkflowTaskDetail(taskId),
});
const approverQuery = useQuery({
enabled: hasPermission(permissions, "expense.transfer"),
queryKey: ["workflow", "approvers"],
queryFn: () => fetchWorkflowApprovers({ page: 1, pageSize: 50 }),
});
const allowedActions = useMemo(() => {
return new Set(detailQuery.data?.allowedActions ?? []);
}, [detailQuery.data?.allowedActions]);
const mutation = useMutation({
mutationFn: async (action: "approve" | "reject" | "return" | "transfer") => {
if (!taskId) {
throw new Error("missing taskId");
}
if (action === "approve") {
return approveWorkflowTask(taskId);
}
if (action === "reject") {
return rejectWorkflowTask(taskId, rejectComment.trim());
}
if (action === "return") {
return returnWorkflowTask(taskId, returnComment.trim());
}
if (!selectedApprover) {
throw new Error("请选择转审目标");
}
return transferWorkflowTask(taskId, selectedApprover, transferReason.trim());
},
onSuccess: async (_data, action) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["workflow", "tasks"] }),
queryClient.invalidateQueries({ queryKey: ["workflow", "task", taskId] }),
]);
setActionError("");
setActiveSecondaryAction(null);
setTransferConfirmOpen(false);
const messages: Record<string, string> = { approve: "已通过", reject: "已驳回", return: "已退回", transfer: "已转审" };
toast.success(messages[action] ?? "操作成功");
},
onError: (error) => {
if (isAlreadyProcessedTaskError(error)) {
void Promise.all([
queryClient.invalidateQueries({ queryKey: ["workflow", "tasks"] }),
queryClient.invalidateQueries({ queryKey: ["workflow", "task", taskId] }),
]);
}
let msg: string;
if (error instanceof Error && !isApiError(error)) {
msg = error.message;
} else if (isApiError(error)) {
msg = `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
} else {
msg = "动作执行失败,请稍后重试";
}
setActionError(msg);
toast.error(msg);
},
});
const confirmCopy = confirmAction ? getWorkflowConfirmCopy(confirmAction) : null;
function requestWorkflowAction(action: WorkflowConfirmAction) {
if (action === "reject" && rejectComment.trim().length < 1) {
setActionError("驳回必须填写意见");
return;
}
if (action === "return" && returnComment.trim().length < 1) {
setActionError("退回必须填写意见");
return;
}
setActionError("");
setConfirmAction(action);
}
function requestWorkflowTransfer() {
if (!selectedApprover) {
setActionError("请选择转审目标");
return;
}
if (transferReason.trim().length < 10) {
setActionError("转审理由至少 10 个字");
return;
}
setActionError("");
setTransferConfirmOpen(true);
}
if (!taskId) {
return (
<div className="card-std p-5">
<p className="text-sm text-red-600">缺少 taskId 参数。</p>
</div>
);
}
if (shouldPreferMobileApprovalExperience()) {
return <Navigate replace to={buildMobileApprovalsPath(taskId)} />;
}
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
variant="secondary"
onClick={() => navigate("/workflow/tasks")}
type="button"
>
返回待办列表
</Button>
</div>
);
}
const detail = detailQuery.data;
const canTransfer = allowedActions.has("transfer");
const allowedActionLabels = detail.allowedActions.map(workflowActionLabel).join(" / ");
const businessStatusLabel = workflowInstanceStatusLabel(detail.workflowInstance?.currentStatus);
return (
<>
<PageScaffold>
<EntityOverviewHero
title="审批详情"
meta={(
<>
<StatusBadge status={detail.task.status} />
<span className="info-chip">业务状态:{businessStatusLabel}</span>
<span className="info-chip">类型:{entityTitle(detail.workflowInstance?.entityType)}</span>
<span className="info-chip">节点:{detail.task.stepName}</span>
</>
)}
actions={(
<Button asChild variant="secondary" data-testid="workflow-task-back">
<Link to="/workflow/tasks">返回待办列表</Link>
</Button>
)}
/>
<BusinessDetailWorkspace>
<BusinessDetailMain>
<SectionPanel title="当前状态与审批对象">
<div className="space-y-4" data-testid="workflow-task-overview">
<StatStrip columns={4} className="ops-status-strip">
<MetricCard title="当前节点" value={<span className="text-base">{detail.task.stepName}</span>} />
<MetricCard title="业务类型" value={<span className="text-base">{entityTitle(detail.workflowInstance?.entityType)}</span>} />
<MetricCard title="可执行动作" value={<span className="text-base">{allowedActionLabels || "-"}</span>} />
<MetricCard title="创建时间" value={<span className="text-base">{formatDisplayDateTime(detail.task.createdAt)}</span>} />
</StatStrip>
<dl className="detail-fact-grid" data-testid="workflow-task-summary">
{detail.reimbursement ? (
<>
<DetailField label="报销单号" value={detail.reimbursement.formNumber ?? "-"} />
<DetailField label="报销金额" value={detail.reimbursement.totalAmount ?? "-"} />
<DetailField label="提交人" value={detail.reimbursement.submitter?.name ?? "-"} />
<DetailField label="报销人" value={detail.reimbursement.owner?.name ?? "-"} />
</>
) : null}
{detail.leaveRequest ? (
<>
<DetailField label="假期类型" value={detail.leaveRequest.leaveType?.name ?? "-"} />
<DetailField label="申请人" value={detail.leaveRequest.owner?.name ?? "-"} />
<DetailField
label="时间段"
value={
<>
{detail.leaveRequest.startDate ?? "-"} {detail.leaveRequest.startSession === "am" ? "上午" : "下午"}
{" → "}
{detail.leaveRequest.endDate ?? "-"} {detail.leaveRequest.endSession === "am" ? "上午" : "下午"}
</>
}
/>
<DetailField label="请假天数" value={detail.leaveRequest.requestedDays} />
<DetailField label="说明" value={detail.leaveRequest.reason ?? "-"} />
<DetailField label="附件" value={detail.leaveRequest.attachment?.originalName ?? "-"} />
</>
) : null}
{detail.attendanceCorrection ? (
<>
<DetailField label="修正类型" value={correctionKindLabel(detail.attendanceCorrection.kind)} />
<DetailField label="申请人" value={detail.attendanceCorrection.owner?.name ?? "-"} />
<DetailField label="考勤日期" value={detail.attendanceCorrection.workDate ?? "-"} />
<DetailField label="状态" value={workflowInstanceStatusLabel(detail.attendanceCorrection.status)} />
<DetailField
label="时间"
value={
detail.attendanceCorrection.kind === "missed_punch"
? formatDisplayDateTime(detail.attendanceCorrection.missedPunchAt)
: `${formatDisplayDateTime(detail.attendanceCorrection.startAt)} → ${formatDisplayDateTime(detail.attendanceCorrection.endAt)}`
}
/>
<DetailField label="外出地点" value={detail.attendanceCorrection.locationSummary ?? "-"} />
<DetailField label="补偿口径" value={detail.attendanceCorrection.compensationPolicy ?? "-"} />
<DetailField label="说明" value={detail.attendanceCorrection.reason ?? "-"} />
</>
) : null}
{detail.purchaseRequest ? (
<>
<DetailField label="采购单号" value={resolvePurchaseDisplayCode(detail.purchaseRequest)} />
<DetailField label="标题" value={detail.purchaseRequest.title || "-"} />
<DetailField label="申请人" value={detail.purchaseRequest.applicant?.name ?? "-"} />
<DetailField label="供应商" value={detail.purchaseRequest.supplier?.name ?? "-"} />
<DetailField label="法体" value={detail.purchaseRequest.legalEntity?.name ?? "-"} />
<DetailField label="成本中心" value={detail.purchaseRequest.costCenter?.name ?? "-"} />
<DetailField label="单据分类" value={detail.purchaseRequest.documentCategory?.name ?? "-"} />
<DetailField label="金额" value={`${detail.purchaseRequest.totalAmount ?? "-"} ${detail.purchaseRequest.currencyCode}`} />
<DetailField label="预计到货" value={detail.purchaseRequest.expectedDeliveryDate ?? "-"} />
<DetailField label="说明" value={detail.purchaseRequest.reason ?? "-"} />
</>
) : null}
{detail.travelRequest ? (
<>
<DetailField label="差旅单号" value={detail.travelRequest.requestNo ?? "暂未生成"} />
<DetailField label="申请人" value={detail.travelRequest.applicant?.name ?? "-"} />
<DetailField label="出差类型" value={detail.travelRequest.tripType === "international" ? "国际" : "国内"} />
<DetailField label="法体" value={detail.travelRequest.legalEntity?.name ?? "-"} />
<DetailField label="成本中心" value={detail.travelRequest.costCenter?.name ?? "-"} />
<DetailField label="起止日期" value={`${detail.travelRequest.startDate ?? "-"} → ${detail.travelRequest.endDate ?? "-"}`} />
<DetailField label="预估金额" value={detail.travelRequest.estimatedAmount ?? "-"} />
<DetailField label="出差目的" value={detail.travelRequest.purpose || "-"} />
<DetailField
label="行程段"
value={
detail.travelRequest.segments.length
? detail.travelRequest.segments
.map((item) => `${item.fromCity}→${item.toCity}(${item.segmentRole})`)
.join(";")
: "-"
}
/>
</>
) : null}
</dl>
{detail.reimbursement ? (
<Button asChild variant="secondary">
<Link
data-testid="workflow-task-reimbursement-detail-link"
to={`/reimbursements/${encodeURIComponent(detail.reimbursement.id)}`}
>
查看报销单
</Link>
</Button>
) : null}
</div>
</SectionPanel>
{detail.workflowInstance?.entityType === "reimbursement" &&
detail.workflowInstance.contextData.standardViolations.length ? (
<SectionPanel title="费用标准提示">
<div className="space-y-2">
{detail.workflowInstance.contextData.standardViolations.map((item) => (
<div
key={`${item.itemId}-${item.standardId}`}
className={
item.controlMode === "block"
? "rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700"
: "rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700"
}
>
<div className="font-medium text-zinc-900">{item.expenseTypeName}</div>
<div>
当前 ¥{item.amount} / 标准 ¥{item.maxAmount}/{item.perUnit}
</div>
<div>超出 ¥{item.exceededAmount} · {item.standardName}</div>
<div>管控模式:{item.controlMode === "block" ? "阻断" : "预警"}</div>
</div>
))}
</div>
</SectionPanel>
) : null}
<SectionPanel title="处理历史">
<div className="detail-timeline">
{detail.history.length ? (
detail.history.map((item) => (
<div className="detail-timeline-item" key={item.id}>
<div className="font-medium text-zinc-900">
{workflowActionLabel(item.action)} · {item.actorName || item.actorId}
</div>
<div className="text-zinc-600">{item.comment || "-"}</div>
<div className="text-xs text-zinc-500">{item.createdAt || "-"}</div>
</div>
))
) : (
<p className="text-sm text-zinc-500">暂无历史记录</p>
)}
</div>
</SectionPanel>
</BusinessDetailMain>
<BusinessDetailAside>
<BusinessDetailActionPanel
title="处理"
className="workflow-action-panel xl:top-20"
secondaryActions={(
<>
<Button
data-testid="workflow-task-approve"
disabled={!allowedActions.has("approve") || mutation.isPending}
onClick={() => requestWorkflowAction("approve")}
type="button"
>
通过
</Button>
<Button
data-testid="workflow-task-return-toggle"
variant="secondary"
disabled={!allowedActions.has("return") || mutation.isPending}
onClick={() => setActiveSecondaryAction(activeSecondaryAction === "return" ? null : "return")}
type="button"
>
退回
</Button>
<Button
data-testid="workflow-task-reject-toggle"
variant="secondary"
disabled={!allowedActions.has("reject") || mutation.isPending}
onClick={() => setActiveSecondaryAction(activeSecondaryAction === "reject" ? null : "reject")}
type="button"
>
驳回
</Button>
{canTransfer ? (
<details className="workflow-action-more">
<summary>更多</summary>
<button
data-testid="workflow-task-transfer-menu-item"
type="button"
onClick={() => setActiveSecondaryAction("transfer")}
>
转审
</button>
</details>
) : null}
</>
)}
summary={(
<>
<div>节点:{detail.task.stepName}</div>
<div>实例状态:{workflowInstanceStatusLabel(detail.workflowInstance?.currentStatus)}</div>
<div>当前审批角色:{detail.task.assigneeRole ?? "-"}</div>
<div>创建时间:{formatDisplayDateTime(detail.task.createdAt)}</div>
<div>完成时间:{formatDisplayDateTime(detail.task.completedAt)}</div>
<div>发起时间:{formatDisplayDateTime(detail.workflowInstance?.startedAt)}</div>
</>
)}
testId="workflow-task-action-panel"
>
{actionError ? (
<p
className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600"
data-testid="workflow-task-action-error"
>
{actionError}
</p>
) : null}
{activeSecondaryAction === "reject" ? (
<div className="detail-action-card space-y-2">
<p className="text-sm font-medium text-zinc-800">驳回意见</p>
<Textarea
data-testid="workflow-task-reject-comment"
onChange={(event) => setRejectComment(event.target.value)}
rows={3}
value={rejectComment}
/>
<Button
data-testid="workflow-task-reject"
variant="secondary"
disabled={!allowedActions.has("reject") || mutation.isPending || rejectComment.trim().length < 1}
onClick={() => requestWorkflowAction("reject")}
type="button"
>
确认驳回
</Button>
</div>
) : null}
{activeSecondaryAction === "return" ? (
<div className="detail-action-card space-y-2">
<p className="text-sm font-medium text-zinc-800">退回意见</p>
<Textarea
data-testid="workflow-task-return-comment"
onChange={(event) => setReturnComment(event.target.value)}
rows={3}
value={returnComment}
/>
<Button
data-testid="workflow-task-return"
variant="secondary"
disabled={!allowedActions.has("return") || mutation.isPending || returnComment.trim().length < 1}
onClick={() => requestWorkflowAction("return")}
type="button"
>
确认退回
</Button>
</div>
) : null}
{activeSecondaryAction === "transfer" && canTransfer ? (
<div className="detail-action-card space-y-2">
<p className="text-sm font-medium text-zinc-800">转审</p>
<select
className="select-std"
data-testid="workflow-task-transfer-approver"
onChange={(event) => setSelectedApprover(event.target.value)}
value={selectedApprover}
>
<option value="">请选择目标审批人</option>
{(approverQuery.data?.items ?? []).map((item) => (
<option key={item.id} value={item.id}>
{item.name} ({item.employeeNo})
</option>
))}
</select>
<Textarea
data-testid="workflow-task-transfer-reason"
onChange={(event) => setTransferReason(event.target.value)}
rows={3}
value={transferReason}
/>
<Button
data-testid="workflow-task-transfer"
variant="secondary"
disabled={
!allowedActions.has("transfer") ||
mutation.isPending ||
!selectedApprover ||
transferReason.trim().length < 10
}
onClick={requestWorkflowTransfer}
type="button"
>
确认转审
</Button>
</div>
) : null}
</BusinessDetailActionPanel>
</BusinessDetailAside>
</BusinessDetailWorkspace>
</PageScaffold>
<ConfirmDialog
open={Boolean(confirmCopy)}
onOpenChange={(open) => {
if (!open) {
setConfirmAction(null);
}
}}
title={confirmCopy?.title ?? ""}
description={confirmCopy?.description}
confirmLabel={confirmCopy?.confirmLabel}
variant={confirmCopy?.variant}
testId="workflow-action-confirm-dialog"
confirmTestId="workflow-action-confirm-submit"
cancelTestId="workflow-action-confirm-cancel"
onConfirm={async () => {
if (!confirmAction) {
return;
}
await mutation.mutateAsync(confirmAction);
}}
/>
<ConfirmDialog
open={transferConfirmOpen}
onOpenChange={setTransferConfirmOpen}
title="确认转审审批?"
description={`事项:${entityTitle(detail.workflowInstance?.entityType)} · ${detail.task.stepName}。转审后当前任务会交给目标审批人处理,系统会写入审批历史。`}
confirmLabel="确认转审"
variant="default"
testId="workflow-transfer-confirm-dialog"
confirmTestId="workflow-transfer-confirm-submit"
cancelTestId="workflow-transfer-confirm-cancel"
onConfirm={async () => {
await mutation.mutateAsync("transfer");
}}
/>
</>
);
}