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

978 行
41 KiB
TypeScript

import { useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
createContractRegistry,
exportContractsRegistry,
fetchContractsRegistry,
fetchExpiringContracts,
patchContractRegistry,
renewContractRegistry,
type ContractRegistryExportFormat,
type ContractRegistryFilters,
type ContractRegistryItem,
type ContractRegistryPersistedStatus,
type ContractRegistryStatus,
type ContractRegistryType,
} from "../api/contractsRegistry";
import { fetchEmployees } from "../api/employees";
import { mapApiErrorMessage } from "../api/errorMessages";
import { fetchProjects, type ConfidentialityLevel } from "../api/projects";
import { isApiError } from "../api/types";
import { useAuth } from "../auth/AuthContext";
import { hasAnyPermission } from "../auth/permissions";
import { ActionConfirmDialog } from "../components/common/ActionConfirmDialog";
import { useUnsavedChangesGuard } from "../components/common/UnsavedChangesGuard";
import { PageHeader } from "../components/common/PageHeader";
import { StatusBadge } from "../components/common/StatusBadge";
import { DateTextInput } from "../components/common/DateTextInput";
import { HeaderActionGroup, WorkspaceNotice } from "../components/patterns/ListWorkspace";
import {
BusinessListToolbar,
BusinessMobileList,
BusinessTable,
} from "../components/patterns/BusinessListTemplate";
import { PageScaffold } from "../components/patterns/PageScaffold";
import { Button } from "../components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "../components/ui/dropdown-menu";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { Textarea } from "../components/ui/textarea";
import { downloadBlob } from "../lib/download";
import { formatDisplayDate } from "../lib/displayFormat";
import { hasTrialNoise } from "../lib/trialNoise";
import { toast } from "sonner";
const CONFIDENTIALITY_OPTIONS: ConfidentialityLevel[] = ["public", "internal", "confidential", "restricted"];
const CONTRACT_TYPE_OPTIONS: ContractRegistryType[] = ["purchase", "sales", "service", "framework", "other"];
const FILTER_STATUS_OPTIONS: Array<{ value: ContractRegistryStatus; label: string }> = [
{ value: "active", label: "生效中" },
{ value: "expired", label: "已过期" },
{ value: "draft", label: "草稿" },
{ value: "archived", label: "已归档" },
];
const EDITOR_STATUS_OPTIONS: Array<{ value: ContractRegistryPersistedStatus; label: string }> = [
{ value: "active", label: "生效中" },
{ value: "draft", label: "草稿" },
{ value: "archived", label: "已归档" },
];
const AMOUNT_PATTERN = /^\d{1,12}(\.\d{1,2})?$/;
const EXPIRING_DAYS = 30;
type FiltersState = {
projectId: string;
status: "" | ContractRegistryStatus;
contractType: "" | ContractRegistryType;
counterpartyName: string;
expiryDateFrom: string;
expiryDateTo: string;
};
type EditorState = {
contractNo: string;
projectId: string;
contractType: ContractRegistryType;
counterpartyName: string;
summary: string;
amount: string;
currency: string;
signedDate: string;
effectiveDate: string;
expiryDate: string;
confidentialityLevel: ConfidentialityLevel;
archiveLocation: string;
offlineArchiveNo: string;
ownerEmployeeId: string;
status: ContractRegistryPersistedStatus;
};
function resolveError(error: unknown, fallback = "操作失败") {
if (isApiError(error)) {
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
}
return error instanceof Error ? error.message : fallback;
}
function confidentialityLabel(value: ConfidentialityLevel) {
if (value === "public") return "公开";
if (value === "internal") return "内部";
if (value === "confidential") return "机密";
return "限制";
}
function contractTypeLabel(value: ContractRegistryType) {
if (value === "purchase") return "采购合同";
if (value === "sales") return "销售合同";
if (value === "service") return "服务合同";
if (value === "framework") return "框架协议";
return "其他";
}
function contractStatusLabel(value: ContractRegistryStatus | ContractRegistryPersistedStatus) {
if (value === "active") return "生效中";
if (value === "expired") return "已过期";
if (value === "draft") return "草稿";
if (value === "archived") return "已归档";
return value || "-";
}
function buildEmptyEditor(projectId = ""): EditorState {
return {
contractNo: "",
projectId,
contractType: "other",
counterpartyName: "",
summary: "",
amount: "",
currency: "CNY",
signedDate: "",
effectiveDate: "",
expiryDate: "",
confidentialityLevel: "internal",
archiveLocation: "",
offlineArchiveNo: "",
ownerEmployeeId: "",
status: "active",
};
}
function buildFiltersPayload(filters: FiltersState): ContractRegistryFilters {
return {
...(filters.projectId ? { projectId: filters.projectId } : {}),
...(filters.status ? { status: filters.status } : {}),
...(filters.contractType ? { contractType: filters.contractType } : {}),
...(filters.counterpartyName.trim() ? { counterpartyName: filters.counterpartyName.trim() } : {}),
...(filters.expiryDateFrom ? { expiryDateFrom: filters.expiryDateFrom } : {}),
...(filters.expiryDateTo ? { expiryDateTo: filters.expiryDateTo } : {}),
};
}
function buildSavePayload(form: EditorState, options: { includeOwnerEmployeeId?: boolean } = {}) {
const includeOwnerEmployeeId = options.includeOwnerEmployeeId ?? true;
return {
contractNo: form.contractNo.trim(),
projectId: form.projectId || null,
contractType: form.contractType,
counterpartyName: form.counterpartyName.trim(),
summary: form.summary.trim(),
amount: form.amount.trim() ? form.amount.trim() : null,
currency: form.currency.trim().toUpperCase(),
signedDate: form.signedDate || null,
effectiveDate: form.effectiveDate || null,
expiryDate: form.expiryDate || null,
confidentialityLevel: form.confidentialityLevel,
archiveLocation: form.archiveLocation.trim(),
offlineArchiveNo: form.offlineArchiveNo.trim() || null,
...(includeOwnerEmployeeId && form.ownerEmployeeId ? { ownerEmployeeId: form.ownerEmployeeId } : {}),
status: form.status,
};
}
function loadEditorFromItem(item: ContractRegistryItem): EditorState {
return {
contractNo: item.contractNo,
projectId: item.projectId ?? "",
contractType: item.contractType,
counterpartyName: item.counterpartyName,
summary: item.summary,
amount: item.amount ?? "",
currency: item.currency,
signedDate: item.signedDate ?? "",
effectiveDate: item.effectiveDate ?? "",
expiryDate: item.expiryDate ?? "",
confidentialityLevel: item.confidentialityLevel,
archiveLocation: item.archiveLocation,
offlineArchiveNo: item.offlineArchiveNo ?? "",
ownerEmployeeId: item.ownerEmployeeId,
status: item.persistedStatus,
};
}
function nextPersistedStatus(item: ContractRegistryItem): ContractRegistryPersistedStatus {
return item.persistedStatus === "archived" ? "active" : "archived";
}
export function ContractsRegistryPage() {
const queryClient = useQueryClient();
const { permissions } = useAuth();
const [searchParams] = useSearchParams();
const initialProjectId = searchParams.get("projectId") ?? "";
const canBrowseEmployees = hasAnyPermission(permissions, ["system.users", "report.dashboard.view"]);
const canManageContracts = hasAnyPermission(permissions, ["project.manage", "project.view_all", "system.settings"]);
const [filters, setFilters] = useState<FiltersState>({
projectId: initialProjectId,
status: "",
contractType: "",
counterpartyName: "",
expiryDateFrom: "",
expiryDateTo: "",
});
const [editorId, setEditorId] = useState<string | null>(null);
const [editor, setEditor] = useState<EditorState>(() => buildEmptyEditor(initialProjectId));
const [savedEditorSignature, setSavedEditorSignature] = useState(() => JSON.stringify(buildEmptyEditor(initialProjectId)));
const [showExpiring, setShowExpiring] = useState(false);
const [showTrialData, setShowTrialData] = useState(false);
const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
const [showEditor, setShowEditor] = useState(false);
const [confirmExportFormat, setConfirmExportFormat] = useState<ContractRegistryExportFormat | null>(null);
const [confirmStatusTarget, setConfirmStatusTarget] = useState<ContractRegistryItem | null>(null);
const filterPayload = buildFiltersPayload(filters);
const contractsQuery = useQuery({
queryKey: ["contracts-registry", filterPayload],
queryFn: () => fetchContractsRegistry(filterPayload),
});
const expiringQuery = useQuery({
queryKey: ["contracts-registry", "expiring", EXPIRING_DAYS],
queryFn: () => fetchExpiringContracts(EXPIRING_DAYS),
});
const projectsQuery = useQuery({
queryKey: ["projects", "contracts-page"],
queryFn: () => fetchProjects({}),
});
const employeesQuery = useQuery({
enabled: canBrowseEmployees,
queryKey: ["employees", "contracts-page"],
queryFn: () => fetchEmployees({ page: 1, pageSize: 100, status: "active" }),
});
const projectOptions = projectsQuery.data?.items ?? [];
const employeeOptions = canBrowseEmployees ? employeesQuery.data?.items ?? [] : [];
const contracts = contractsQuery.data?.items ?? [];
const visibleContracts = useMemo(
() =>
showTrialData
? contracts
: contracts.filter(
(item) => !hasTrialNoise(item.contractNo, item.counterpartyName, item.summary, item.project?.name),
),
[contracts, showTrialData],
);
const hiddenTrialContractCount = contracts.length - visibleContracts.length;
const expiringItems = expiringQuery.data?.items ?? [];
const editingItem = editorId ? contracts.find((item) => item.id === editorId) ?? null : null;
const readonlyOwnerLabel = editingItem?.owner
? `${editingItem.owner.name} · ${editingItem.owner.employeeNo}`
: editor.ownerEmployeeId
? "保留现有责任人"
: "默认当前用户";
const amountInvalid = Boolean(editor.amount.trim()) && !AMOUNT_PATTERN.test(editor.amount.trim());
const expiringContractCount = expiringQuery.data?.total ?? expiringItems.length;
const runGuarded = useUnsavedChangesGuard(
showEditor && JSON.stringify(editor) !== savedEditorSignature,
"合同表单",
);
const refreshAll = async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["contracts-registry"] }),
queryClient.invalidateQueries({ queryKey: ["projects"] }),
]);
};
const resetEditor = () => {
const nextEditor = buildEmptyEditor(filters.projectId);
setEditorId(null);
setEditor(nextEditor);
setSavedEditorSignature(JSON.stringify(nextEditor));
};
const openEditor = (item: ContractRegistryItem) => {
runGuarded(() => {
const nextEditor = loadEditorFromItem(item);
setEditorId(item.id);
setEditor(nextEditor);
setSavedEditorSignature(JSON.stringify(nextEditor));
setShowEditor(true);
});
};
const saveMutation = useMutation({
mutationFn: async () => {
const payload = buildSavePayload(editor, { includeOwnerEmployeeId: canBrowseEmployees });
if (editorId) {
return patchContractRegistry(editorId, payload);
}
return createContractRegistry(payload);
},
onSuccess: async () => {
await refreshAll();
setShowEditor(false);
resetEditor();
toast.success(editorId ? "合同已更新" : "合同已创建");
},
onError: (error) => toast.error(resolveError(error, editorId ? "更新合同失败" : "创建合同失败")),
});
const toggleStatusMutation = useMutation({
mutationFn: (item: ContractRegistryItem) => patchContractRegistry(item.id, { status: nextPersistedStatus(item) }),
onSuccess: async () => {
await refreshAll();
toast.success("合同状态已更新");
},
onError: (error) => toast.error(resolveError(error, "更新合同状态失败")),
});
const renewMutation = useMutation({
mutationFn: (item: ContractRegistryItem) => renewContractRegistry(item.id),
onSuccess: async () => {
await refreshAll();
toast.success("合同已续约,新的草稿合同已创建");
},
onError: (error) => toast.error(resolveError(error, "续约合同失败")),
});
const exportMutation = useMutation({
mutationFn: (format: ContractRegistryExportFormat) =>
exportContractsRegistry({
...filterPayload,
format,
}),
onSuccess: (response, format) => {
downloadBlob(response.blob, response.filename ?? `contracts-registry.${format}`);
toast.success(`合同已导出为 ${format.toUpperCase()}`);
},
onError: (error) => toast.error(resolveError(error, "导出合同失败")),
});
return (
<PageScaffold>
<PageHeader
title="合同"
actions={
<HeaderActionGroup>
{canManageContracts ? (
<Button
type="button"
onClick={() => {
runGuarded(() => {
resetEditor();
setShowEditor(true);
});
}}
>
新增合同
</Button>
) : null}
</HeaderActionGroup>
}
/>
{expiringQuery.isError ? (
<div className="text-sm text-red-600">{resolveError(expiringQuery.error, "加载到期预警失败")}</div>
) : null}
{showExpiring ? (
<div className="detail-command-panel space-y-2" data-testid="contracts-expiring-list">
{expiringItems.map((item) => (
<div key={item.id} className="flex items-center justify-between gap-3 rounded-lg border border-zinc-200 px-3 py-2 text-sm">
<div className="min-w-0">
<div className="truncate font-medium text-zinc-900">{item.contractNo} · {item.counterpartyName}</div>
<div className="text-xs text-zinc-500">到期日 {formatDisplayDate(item.expiryDate)} · 责任人 {item.owner?.name ?? "-"}</div>
</div>
{canManageContracts ? (
<Button type="button" size="sm" variant="secondary" onClick={() => openEditor(item)}>
编辑
</Button>
) : null}
</div>
))}
{!expiringQuery.isLoading && !expiringItems.length ? (
<div className="text-sm text-zinc-500">暂无到期合同</div>
) : null}
</div>
) : null}
<div className="grid gap-6">
{showEditor ? (
<div className="card-std space-y-4 p-6" data-testid="contracts-editor-panel">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="text-base font-semibold text-zinc-900">{editorId ? "编辑合同" : "新建合同"}</h3>
<p className="mt-1 text-sm text-zinc-500">
补齐合同类型、金额、签署/生效/到期日期,续约将自动创建新的草稿合同。
</p>
</div>
<div className="flex flex-wrap gap-2">
{editorId ? (
<Button type="button" variant="secondary" size="sm" onClick={() => runGuarded(resetEditor)}>
切换到新建
</Button>
) : null}
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => {
runGuarded(() => {
setShowEditor(false);
resetEditor();
});
}}
>
关闭
</Button>
</div>
</div>
{editingItem?.status === "expired" ? (
<div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
当前合同因到期日已过,列表状态显示为“已过期”;保存时仍按“{contractStatusLabel(editingItem.persistedStatus)}”留存。
</div>
) : null}
<div className="space-y-6">
<section className="space-y-4">
<div>
<h4 className="text-sm font-semibold text-zinc-900">基础信息</h4>
<p className="text-xs text-zinc-500">填写编号、类型、相对方、摘要和金额。</p>
</div>
<div className="space-y-2">
<Label>合同编号</Label>
<Input
value={editor.contractNo}
onChange={(event) => setEditor((current) => ({ ...current, contractNo: event.target.value }))}
placeholder="例如 HT-2026-001"
/>
</div>
<div className="grid gap-3 md:grid-cols-2">
<div className="space-y-2">
<Label>合同类型</Label>
<select
className="select-std"
value={editor.contractType}
onChange={(event) => setEditor((current) => ({ ...current, contractType: event.target.value as ContractRegistryType }))}
>
{CONTRACT_TYPE_OPTIONS.map((item) => (
<option key={item} value={item}>
{contractTypeLabel(item)}
</option>
))}
</select>
</div>
<div className="space-y-2">
<Label>状态</Label>
<select
className="select-std"
value={editor.status}
onChange={(event) => setEditor((current) => ({ ...current, status: event.target.value as ContractRegistryPersistedStatus }))}
>
{EDITOR_STATUS_OPTIONS.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
</div>
<div className="space-y-2">
<Label>相对方</Label>
<Input
value={editor.counterpartyName}
onChange={(event) => setEditor((current) => ({ ...current, counterpartyName: event.target.value }))}
placeholder="合同对方名称"
/>
</div>
<div className="space-y-2">
<Label>摘要</Label>
<Textarea
value={editor.summary}
onChange={(event) => setEditor((current) => ({ ...current, summary: event.target.value }))}
placeholder="只写最小必要摘要,不录入涉密正文"
/>
</div>
<div className="grid gap-3 md:grid-cols-2">
<div className="space-y-2">
<Label>合同金额</Label>
<Input
value={editor.amount}
onChange={(event) => setEditor((current) => ({ ...current, amount: event.target.value }))}
placeholder="例如 100000.00"
/>
</div>
<div className="space-y-2">
<Label>币种</Label>
<Input
value={editor.currency}
onChange={(event) => setEditor((current) => ({ ...current, currency: event.target.value.toUpperCase() }))}
placeholder="CNY"
/>
</div>
</div>
{amountInvalid ? <div className="text-xs text-red-600">合同金额需为最多 12 位整数、最多 2 位小数。</div> : null}
</section>
<section className="space-y-4 border-t border-zinc-200 pt-5">
<div>
<h4 className="text-sm font-semibold text-zinc-900">项目关联</h4>
<p className="text-xs text-zinc-500">将合同归入项目,便于项目页汇总合同、费用和交付风险。</p>
</div>
<div className="space-y-2">
<Label>关联项目</Label>
<select
className="select-std"
value={editor.projectId}
onChange={(event) => setEditor((current) => ({ ...current, projectId: event.target.value }))}
>
<option value="">未关联</option>
{projectOptions.map((item) => (
<option key={item.id} value={item.id}>
{item.projectNo} · {item.name}
</option>
))}
</select>
</div>
</section>
<section className="space-y-4 border-t border-zinc-200 pt-5">
<div>
<h4 className="text-sm font-semibold text-zinc-900">日期与续约</h4>
<p className="text-xs text-zinc-500">用于到期预警、续约草稿和归档判断。</p>
</div>
<div className="grid gap-3 md:grid-cols-3">
<div className="space-y-2">
<Label>签署日期</Label>
<DateTextInput
value={editor.signedDate}
onChange={(event) => setEditor((current) => ({ ...current, signedDate: event.target.value }))}
/>
</div>
<div className="space-y-2">
<Label>生效日期</Label>
<DateTextInput
value={editor.effectiveDate}
onChange={(event) => setEditor((current) => ({ ...current, effectiveDate: event.target.value }))}
/>
</div>
<div className="space-y-2">
<Label>到期日期</Label>
<DateTextInput
value={editor.expiryDate}
onChange={(event) => setEditor((current) => ({ ...current, expiryDate: event.target.value }))}
/>
</div>
</div>
</section>
<section className="space-y-4 border-t border-zinc-200 pt-5">
<div>
<h4 className="text-sm font-semibold text-zinc-900">归档与责任</h4>
<p className="text-xs text-zinc-500">登记线下归档位置、密级和责任人,不上传涉密正文。</p>
</div>
<div className="space-y-2">
<Label>归档位置</Label>
<Input
value={editor.archiveLocation}
onChange={(event) => setEditor((current) => ({ ...current, archiveLocation: event.target.value }))}
placeholder="文件柜、档案盒或归档目录摘要"
/>
</div>
<div className="grid gap-3 md:grid-cols-2">
<div className="space-y-2">
<Label>离线档案号</Label>
<Input
value={editor.offlineArchiveNo}
onChange={(event) => setEditor((current) => ({ ...current, offlineArchiveNo: event.target.value }))}
placeholder="可选"
/>
</div>
<div className="space-y-2">
<Label>密级</Label>
<select
className="select-std"
value={editor.confidentialityLevel}
onChange={(event) => setEditor((current) => ({ ...current, confidentialityLevel: event.target.value as ConfidentialityLevel }))}
>
{CONFIDENTIALITY_OPTIONS.map((item) => (
<option key={item} value={item}>
{confidentialityLabel(item)}
</option>
))}
</select>
</div>
</div>
<div className="space-y-2">
<Label>责任人</Label>
{canBrowseEmployees ? (
<select
className="select-std"
value={editor.ownerEmployeeId}
onChange={(event) => setEditor((current) => ({ ...current, ownerEmployeeId: event.target.value }))}
>
<option value="">默认当前用户</option>
{employeeOptions.map((item) => (
<option key={item.id} value={item.id}>
{item.name} · {item.employeeNo}
</option>
))}
</select>
) : (
<div className="rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-2 text-sm">
<div className="font-medium text-zinc-900">{readonlyOwnerLabel}</div>
<div className="mt-1 text-xs text-zinc-500">
当前账号无人员目录权限,新建时使用当前用户,编辑时保留原责任人。
</div>
</div>
)}
</div>
</section>
</div>
<Button
type="button"
disabled={
saveMutation.isPending ||
amountInvalid ||
!editor.contractNo.trim() ||
!editor.counterpartyName.trim() ||
!editor.summary.trim() ||
!editor.archiveLocation.trim() ||
!editor.currency.trim()
}
onClick={() => saveMutation.mutate()}
>
{saveMutation.isPending ? (editorId ? "保存中..." : "创建中...") : editorId ? "保存修改" : "创建合同"}
</Button>
</div>
) : null}
<>
<BusinessListToolbar
actions={
<>
<Button
type="button"
size="sm"
variant={showAdvancedFilters || filters.expiryDateFrom || filters.expiryDateTo || showTrialData ? "default" : "secondary"}
onClick={() => setShowAdvancedFilters((value) => !value)}
>
筛选
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" size="sm" variant={showExpiring ? "default" : "secondary"}>
更多
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{initialProjectId ? (
<DropdownMenuItem asChild>
<Link to="/projects">返回项目</Link>
</DropdownMenuItem>
) : null}
<DropdownMenuItem
disabled={expiringQuery.isLoading}
onSelect={() => setShowExpiring((value) => !value)}
>
{showExpiring ? "退出到期列表" : `到期列表 ${expiringContractCount}`}
</DropdownMenuItem>
<DropdownMenuItem
disabled={exportMutation.isPending}
onSelect={() => setConfirmExportFormat("csv")}
>
导出 CSV
</DropdownMenuItem>
<DropdownMenuItem
disabled={exportMutation.isPending}
onSelect={() => setConfirmExportFormat("xlsx")}
>
导出 Excel
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
}
advanced={showAdvancedFilters || filters.expiryDateFrom || filters.expiryDateTo || showTrialData ? (
<div className="grid gap-3 md:grid-cols-[160px_160px_auto_auto] xl:grid-cols-[180px_180px_auto_auto]" data-testid="contracts-advanced-filters">
<div className="space-y-2">
<Label>到期日开始</Label>
<DateTextInput
value={filters.expiryDateFrom}
onChange={(event) => setFilters((current) => ({ ...current, expiryDateFrom: event.target.value }))}
/>
</div>
<div className="space-y-2">
<Label>到期日结束</Label>
<DateTextInput
value={filters.expiryDateTo}
onChange={(event) => setFilters((current) => ({ ...current, expiryDateTo: event.target.value }))}
/>
</div>
<div className="flex items-end">
<Button type="button" variant={showTrialData ? "default" : "secondary"} onClick={() => setShowTrialData((value) => !value)}>
{showTrialData ? "隐藏测试数据" : "显示测试数据"}
</Button>
</div>
<div className="flex items-end">
<Button
type="button"
variant="secondary"
onClick={() => {
runGuarded(() => {
const nextEditor = buildEmptyEditor(initialProjectId);
setFilters({
projectId: initialProjectId,
status: "",
contractType: "",
counterpartyName: "",
expiryDateFrom: "",
expiryDateTo: "",
});
setShowEditor(false);
setEditorId(null);
setEditor(nextEditor);
setSavedEditorSignature(JSON.stringify(nextEditor));
});
}}
>
重置筛选
</Button>
</div>
</div>
) : null}
>
<div className="grid gap-3 xl:grid-cols-[minmax(180px,1fr)_160px_160px_minmax(220px,1fr)]">
<div>
<select
className="select-std"
aria-label="项目"
value={filters.projectId}
onChange={(event) => setFilters((current) => ({ ...current, projectId: event.target.value }))}
>
<option value="">全部项目</option>
{projectOptions.map((item) => (
<option key={item.id} value={item.id}>
{item.projectNo} · {item.name}
</option>
))}
</select>
</div>
<div>
<select
className="select-std"
aria-label="状态"
value={filters.status}
onChange={(event) => setFilters((current) => ({ ...current, status: event.target.value as FiltersState["status"] }))}
>
<option value="">全部状态</option>
{FILTER_STATUS_OPTIONS.map((item) => (
<option key={item.value} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
<div>
<select
className="select-std"
aria-label="合同类型"
value={filters.contractType}
onChange={(event) => setFilters((current) => ({ ...current, contractType: event.target.value as FiltersState["contractType"] }))}
>
<option value="">全部类型</option>
{CONTRACT_TYPE_OPTIONS.map((item) => (
<option key={item} value={item}>
{contractTypeLabel(item)}
</option>
))}
</select>
</div>
<div>
<Input
aria-label="相对方"
value={filters.counterpartyName}
onChange={(event) => setFilters((current) => ({ ...current, counterpartyName: event.target.value }))}
placeholder="搜索相对方"
/>
</div>
</div>
</BusinessListToolbar>
{contractsQuery.isLoading ? <div className="text-sm text-zinc-500">加载中...</div> : null}
{contractsQuery.isError ? (
<div className="text-sm text-red-600">{resolveError(contractsQuery.error, "加载合同失败")}</div>
) : null}
{!showTrialData && hiddenTrialContractCount > 0 ? (
<WorkspaceNotice title={`已隐藏 ${hiddenTrialContractCount} 条 TEST/SMOKE 合同`} tone="neutral">
试运行默认只展示正式合同;需要核对测试样本时可临时显示。
</WorkspaceNotice>
) : null}
<BusinessMobileList>
{visibleContracts.map((item) => (
<article key={item.id} className="rounded-lg border border-zinc-200 bg-white p-3 text-sm" data-testid="contracts-registry-row">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="truncate font-semibold text-zinc-900">{item.contractNo}</div>
<div className="mt-1 truncate text-zinc-600">{item.counterpartyName}</div>
</div>
<StatusBadge status={item.status} label={contractStatusLabel(item.status)} />
</div>
<div className="mt-2 text-xs text-zinc-500">
{contractTypeLabel(item.contractType)}
{item.amount ? ` · ${item.amount} ${item.currency}` : ""}
{item.expiryDate ? ` · ${formatDisplayDate(item.expiryDate)}` : ""}
</div>
{canManageContracts ? (
<Button className="mt-3" type="button" size="sm" variant="secondary" onClick={() => openEditor(item)}>
编辑
</Button>
) : null}
</article>
))}
{!contractsQuery.isLoading && !visibleContracts.length ? (
<div className="rounded-lg border border-zinc-200 bg-white p-4 text-sm text-zinc-500">暂无合同</div>
) : null}
</BusinessMobileList>
<BusinessTable testId="contracts-registry-table">
<thead className="table-header">
<tr>
<th className="table-th">合同</th>
<th className="table-th">相对方</th>
<th className="table-th">项目 / 责任人</th>
<th className="table-th">金额 / 日期</th>
<th className="table-th">状态</th>
<th className="table-th w-32">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-50">
{visibleContracts.length ? (
visibleContracts.map((item) => (
<tr key={item.id} className="table-row" data-testid="contracts-registry-row">
<td className="table-td">
<div className="font-semibold text-zinc-900">{item.contractNo}</div>
<div className="text-xs text-zinc-500">{contractTypeLabel(item.contractType)}</div>
<div className="text-xs text-zinc-500">{confidentialityLabel(item.confidentialityLevel)}</div>
</td>
<td className="table-td">
<div className="font-medium text-zinc-900">{item.counterpartyName}</div>
<div className="line-clamp-2 text-xs text-zinc-500">{item.summary}</div>
</td>
<td className="table-td">
<div className="font-medium text-zinc-900">
{item.project ? `${item.project.projectNo} · ${item.project.name}` : "-"}
</div>
<div className="text-xs text-zinc-500">{item.owner?.name ?? "-"}</div>
</td>
<td className="table-td">
<div className="font-semibold text-zinc-900">{item.amount ? `${item.amount} ${item.currency}` : "-"}</div>
<div className="text-xs text-zinc-500">到期 {formatDisplayDate(item.expiryDate)}</div>
<div className="text-xs text-zinc-500">签署 {formatDisplayDate(item.signedDate)}</div>
</td>
<td className="table-td">
<StatusBadge status={item.status} label={contractStatusLabel(item.status)} />
</td>
<td className="table-td">
<div className="flex flex-wrap gap-2">
{canManageContracts ? (
<Button type="button" size="sm" variant="secondary" onClick={() => openEditor(item)}>
编辑
</Button>
) : null}
{canManageContracts || item.project ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" size="sm" variant="secondary">
更多
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{canManageContracts ? (
<DropdownMenuItem
disabled={renewMutation.isPending || !["active", "expired"].includes(item.status)}
onSelect={() => renewMutation.mutate(item)}
>
续约
</DropdownMenuItem>
) : null}
{item.project ? (
<DropdownMenuItem asChild>
<Link to={`/projects/${item.project.id}`}>查看项目</Link>
</DropdownMenuItem>
) : null}
{canManageContracts ? (
<DropdownMenuItem
disabled={toggleStatusMutation.isPending}
onSelect={() => setConfirmStatusTarget(item)}
>
{item.persistedStatus === "archived" ? "恢复生效" : "归档"}
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
</td>
</tr>
))
) : (
<tr>
<td className="py-8 text-center text-sm text-zinc-500" colSpan={6}>
暂无合同
</td>
</tr>
)}
</tbody>
</BusinessTable>
</>
</div>
<ActionConfirmDialog
open={Boolean(confirmExportFormat)}
onOpenChange={(open) => {
if (!open) setConfirmExportFormat(null);
}}
kind="sensitiveExport"
targetName="合同"
description="导出文件可能包含合同金额、相对方、项目归属、责任人和归档位置摘要。请确认当前筛选范围和用途合规。"
onConfirm={() => {
if (!confirmExportFormat) return;
exportMutation.mutate(confirmExportFormat);
}}
/>
<ActionConfirmDialog
open={Boolean(confirmStatusTarget)}
onOpenChange={(open) => {
if (!open) setConfirmStatusTarget(null);
}}
kind={confirmStatusTarget?.persistedStatus === "archived" ? "enable" : "archive"}
targetName={confirmStatusTarget?.contractNo}
description={
confirmStatusTarget?.persistedStatus === "archived"
? "恢复后该合同会重新作为生效台账参与到期提醒和项目关联摘要。"
: "归档后该合同不再作为生效合同推进,台账、项目关联和离线归档索引仍保留。"
}
confirmLabel={confirmStatusTarget?.persistedStatus === "archived" ? "确认恢复" : "确认归档"}
onConfirm={() => {
if (!confirmStatusTarget) return;
toggleStatusMutation.mutate(confirmStatusTarget);
}}
/>
</PageScaffold>
);
}
export default ContractsRegistryPage;