R49 合同台账增强:金额分类、筛选、到期预警、续约与导出
这个提交包含在:
@@ -1,38 +1,88 @@
|
||||
import { apiRequestData } from "./http";
|
||||
import { apiRequestBlob, apiRequestData } from "./http";
|
||||
import type { ConfidentialityLevel, EmployeeBasic } from "./projects";
|
||||
|
||||
export type ContractRegistryType = "purchase" | "sales" | "service" | "framework" | "other";
|
||||
export type ContractRegistryPersistedStatus = "draft" | "active" | "archived";
|
||||
export type ContractRegistryStatus = ContractRegistryPersistedStatus | "expired";
|
||||
export type ContractRegistryExportFormat = "csv" | "xlsx";
|
||||
|
||||
export type ContractRegistryFilters = {
|
||||
projectId?: string;
|
||||
status?: ContractRegistryStatus;
|
||||
contractType?: ContractRegistryType;
|
||||
counterpartyName?: string;
|
||||
expiryDateFrom?: string;
|
||||
expiryDateTo?: string;
|
||||
};
|
||||
|
||||
export type ContractRegistryItem = {
|
||||
id: string;
|
||||
contractNo: string;
|
||||
projectId: string | null;
|
||||
contractType: ContractRegistryType;
|
||||
counterpartyName: string;
|
||||
summary: string;
|
||||
amount: string | null;
|
||||
currency: string;
|
||||
signedDate: string | null;
|
||||
effectiveDate: string | null;
|
||||
expiryDate: string | null;
|
||||
confidentialityLevel: ConfidentialityLevel;
|
||||
archiveLocation: string;
|
||||
offlineArchiveNo: string | null;
|
||||
ownerEmployeeId: string;
|
||||
status: string;
|
||||
status: ContractRegistryStatus;
|
||||
persistedStatus: ContractRegistryPersistedStatus;
|
||||
createdAt: string | null;
|
||||
updatedAt: string | null;
|
||||
owner: EmployeeBasic | null;
|
||||
project: { id: string; projectNo: string; name: string } | null;
|
||||
};
|
||||
|
||||
export async function fetchContractsRegistry(projectId?: string) {
|
||||
const suffix = projectId ? `?projectId=${encodeURIComponent(projectId)}` : "";
|
||||
return apiRequestData<{ items: ContractRegistryItem[] }>(`/api/contracts-registry${suffix}`);
|
||||
function buildFiltersSearch(filters?: ContractRegistryFilters | string) {
|
||||
const normalized =
|
||||
typeof filters === "string"
|
||||
? { projectId: filters }
|
||||
: (filters ?? {});
|
||||
const search = new URLSearchParams();
|
||||
|
||||
if (normalized.projectId) search.set("projectId", normalized.projectId);
|
||||
if (normalized.status) search.set("status", normalized.status);
|
||||
if (normalized.contractType) search.set("contractType", normalized.contractType);
|
||||
if (normalized.counterpartyName) search.set("counterpartyName", normalized.counterpartyName);
|
||||
if (normalized.expiryDateFrom) search.set("expiryDateFrom", normalized.expiryDateFrom);
|
||||
if (normalized.expiryDateTo) search.set("expiryDateTo", normalized.expiryDateTo);
|
||||
|
||||
const suffix = search.toString();
|
||||
return suffix ? `?${suffix}` : "";
|
||||
}
|
||||
|
||||
export async function fetchContractsRegistry(filters?: ContractRegistryFilters | string) {
|
||||
return apiRequestData<{ items: ContractRegistryItem[] }>(`/api/contracts-registry${buildFiltersSearch(filters)}`);
|
||||
}
|
||||
|
||||
export async function fetchExpiringContracts(days = 30) {
|
||||
return apiRequestData<{ days: number; total: number; items: ContractRegistryItem[] }>(
|
||||
`/api/contracts-registry/expiring?days=${encodeURIComponent(String(days))}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function createContractRegistry(payload: {
|
||||
contractNo: string;
|
||||
projectId?: string | null;
|
||||
contractType: ContractRegistryType;
|
||||
counterpartyName: string;
|
||||
summary: string;
|
||||
amount?: string | null;
|
||||
currency?: string;
|
||||
signedDate?: string | null;
|
||||
effectiveDate?: string | null;
|
||||
expiryDate?: string | null;
|
||||
confidentialityLevel?: ConfidentialityLevel;
|
||||
archiveLocation: string;
|
||||
offlineArchiveNo?: string | null;
|
||||
ownerEmployeeId?: string;
|
||||
status?: string;
|
||||
status?: ContractRegistryPersistedStatus;
|
||||
}) {
|
||||
return apiRequestData<{ item: ContractRegistryItem }>("/api/contracts-registry", {
|
||||
method: "POST",
|
||||
@@ -45,13 +95,19 @@ export async function patchContractRegistry(
|
||||
payload: Partial<{
|
||||
contractNo: string;
|
||||
projectId: string | null;
|
||||
contractType: ContractRegistryType;
|
||||
counterpartyName: string;
|
||||
summary: string;
|
||||
amount: string | null;
|
||||
currency: string;
|
||||
signedDate: string | null;
|
||||
effectiveDate: string | null;
|
||||
expiryDate: string | null;
|
||||
confidentialityLevel: ConfidentialityLevel;
|
||||
archiveLocation: string;
|
||||
offlineArchiveNo: string | null;
|
||||
ownerEmployeeId: string;
|
||||
status: string;
|
||||
status: ContractRegistryPersistedStatus;
|
||||
}>,
|
||||
) {
|
||||
return apiRequestData<{ item: ContractRegistryItem }>(`/api/contracts-registry/${id}`, {
|
||||
@@ -59,3 +115,22 @@ export async function patchContractRegistry(
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function renewContractRegistry(id: string) {
|
||||
return apiRequestData<{ item: ContractRegistryItem; sourceItem: ContractRegistryItem }>(
|
||||
`/api/contracts-registry/${id}/renew`,
|
||||
{
|
||||
method: "POST",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export async function exportContractsRegistry(params: ContractRegistryFilters & { format: ContractRegistryExportFormat }) {
|
||||
return apiRequestBlob("/api/exports/contracts-registry", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(params),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { 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 { createContractRegistry, fetchContractsRegistry, patchContractRegistry, type ContractRegistryItem } from "../api/contractsRegistry";
|
||||
import { fetchProjects, type ConfidentialityLevel } from "../api/projects";
|
||||
import { isApiError } from "../api/types";
|
||||
import { PageHeader } from "../components/common/PageHeader";
|
||||
@@ -12,9 +25,51 @@ import { Button } from "../components/ui/button";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Label } from "../components/ui/label";
|
||||
import { Textarea } from "../components/ui/textarea";
|
||||
import { downloadBlob } from "../lib/download";
|
||||
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: "active" },
|
||||
{ value: "draft", label: "draft" },
|
||||
{ value: "archived", label: "archived" },
|
||||
];
|
||||
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)) {
|
||||
@@ -30,8 +85,87 @@ function confidentialityLabel(value: ConfidentialityLevel) {
|
||||
return "限制";
|
||||
}
|
||||
|
||||
function nextStatus(item: ContractRegistryItem) {
|
||||
return item.status === "archived" ? "active" : "archived";
|
||||
function contractTypeLabel(value: ContractRegistryType) {
|
||||
if (value === "purchase") return "采购合同";
|
||||
if (value === "sales") return "销售合同";
|
||||
if (value === "service") return "服务合同";
|
||||
if (value === "framework") return "框架协议";
|
||||
return "其他";
|
||||
}
|
||||
|
||||
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) {
|
||||
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,
|
||||
ownerEmployeeId: form.ownerEmployeeId || undefined,
|
||||
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() {
|
||||
@@ -39,27 +173,42 @@ export function ContractsRegistryPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const initialProjectId = searchParams.get("projectId") ?? "";
|
||||
|
||||
const [projectId, setProjectId] = useState(initialProjectId);
|
||||
const [contractNo, setContractNo] = useState("");
|
||||
const [counterpartyName, setCounterpartyName] = useState("");
|
||||
const [summary, setSummary] = useState("");
|
||||
const [archiveLocation, setArchiveLocation] = useState("");
|
||||
const [offlineArchiveNo, setOfflineArchiveNo] = useState("");
|
||||
const [ownerEmployeeId, setOwnerEmployeeId] = useState("");
|
||||
const [confidentialityLevel, setConfidentialityLevel] = useState<ConfidentialityLevel>("internal");
|
||||
const [status, setStatus] = useState("active");
|
||||
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 [showExpiring, setShowExpiring] = useState(false);
|
||||
|
||||
const filterPayload = buildFiltersPayload(filters);
|
||||
const contractsQuery = useQuery({
|
||||
queryKey: ["contracts-registry", projectId],
|
||||
queryFn: () => fetchContractsRegistry(projectId || undefined),
|
||||
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({
|
||||
queryKey: ["employees", "contracts-page"],
|
||||
queryFn: () => fetchEmployees({ page: 1, pageSize: 100, status: "active" }),
|
||||
});
|
||||
const projectsQuery = useQuery({ queryKey: ["projects", "contracts-page"], queryFn: () => fetchProjects({}) });
|
||||
const employeesQuery = useQuery({ queryKey: ["employees", "contracts-page"], queryFn: () => fetchEmployees({ page: 1, pageSize: 100, status: "active" }) });
|
||||
|
||||
const projectOptions = projectsQuery.data?.items ?? [];
|
||||
const employeeOptions = employeesQuery.data?.items ?? [];
|
||||
|
||||
const groupedContracts = useMemo(() => contractsQuery.data?.items ?? [], [contractsQuery.data?.items]);
|
||||
const contracts = contractsQuery.data?.items ?? [];
|
||||
const expiringItems = expiringQuery.data?.items ?? [];
|
||||
const editingItem = editorId ? contracts.find((item) => item.id === editorId) ?? null : null;
|
||||
const amountInvalid = Boolean(editor.amount.trim()) && !AMOUNT_PATTERN.test(editor.amount.trim());
|
||||
|
||||
const refreshAll = async () => {
|
||||
await Promise.all([
|
||||
@@ -68,62 +217,216 @@ export function ContractsRegistryPage() {
|
||||
]);
|
||||
};
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
createContractRegistry({
|
||||
contractNo: contractNo.trim(),
|
||||
projectId: projectId || null,
|
||||
counterpartyName: counterpartyName.trim(),
|
||||
summary: summary.trim(),
|
||||
archiveLocation: archiveLocation.trim(),
|
||||
offlineArchiveNo: offlineArchiveNo.trim() || null,
|
||||
ownerEmployeeId: ownerEmployeeId || undefined,
|
||||
confidentialityLevel,
|
||||
status,
|
||||
}),
|
||||
onSuccess: async () => {
|
||||
setContractNo("");
|
||||
setCounterpartyName("");
|
||||
setSummary("");
|
||||
setArchiveLocation("");
|
||||
setOfflineArchiveNo("");
|
||||
setOwnerEmployeeId("");
|
||||
setConfidentialityLevel("internal");
|
||||
setStatus("active");
|
||||
await refreshAll();
|
||||
toast.success("合同台账已创建");
|
||||
const resetEditor = () => {
|
||||
setEditorId(null);
|
||||
setEditor(buildEmptyEditor(filters.projectId));
|
||||
};
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (editorId) {
|
||||
return patchContractRegistry(editorId, buildSavePayload(editor));
|
||||
}
|
||||
return createContractRegistry(buildSavePayload(editor));
|
||||
},
|
||||
onError: (error) => toast.error(resolveError(error, "创建合同台账失败")),
|
||||
onSuccess: async () => {
|
||||
await refreshAll();
|
||||
resetEditor();
|
||||
toast.success(editorId ? "合同台账已更新" : "合同台账已创建");
|
||||
},
|
||||
onError: (error) => toast.error(resolveError(error, editorId ? "更新合同台账失败" : "创建合同台账失败")),
|
||||
});
|
||||
|
||||
const toggleStatusMutation = useMutation({
|
||||
mutationFn: (item: ContractRegistryItem) => patchContractRegistry(item.id, { status: nextStatus(item) }),
|
||||
onSuccess: refreshAll,
|
||||
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 (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="合同台账"
|
||||
subtitle="只维护合同元数据、归档位置和项目关联,不在 OA 存放涉密正文附件。"
|
||||
subtitle="维护合同元数据、生命周期、到期预警与导出,不在 OA 存放涉密正文附件。"
|
||||
actions={
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
disabled={exportMutation.isPending}
|
||||
onClick={() => exportMutation.mutate("csv")}
|
||||
>
|
||||
导出 CSV
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
disabled={exportMutation.isPending}
|
||||
onClick={() => exportMutation.mutate("xlsx")}
|
||||
>
|
||||
导出 Excel
|
||||
</Button>
|
||||
<Button asChild variant="secondary" type="button">
|
||||
<Link to="/projects">返回项目</Link>
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-[360px,minmax(0,1fr)]">
|
||||
<div className="card-std space-y-4 p-6">
|
||||
<h3 className="text-base font-semibold text-zinc-900">新建合同台账</h3>
|
||||
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div>
|
||||
<div className="text-sm text-zinc-500">到期预警</div>
|
||||
<div className="mt-1 text-3xl font-semibold text-zinc-900">{expiringQuery.data?.total ?? 0}</div>
|
||||
<div className="text-sm text-zinc-600">份合同将在 {EXPIRING_DAYS} 天内到期</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
disabled={expiringQuery.isLoading}
|
||||
onClick={() => setShowExpiring((value) => !value)}
|
||||
>
|
||||
{showExpiring ? "收起到期列表" : "展开到期列表"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expiringQuery.isError ? (
|
||||
<div className="text-sm text-red-600">{resolveError(expiringQuery.error, "加载到期预警失败")}</div>
|
||||
) : null}
|
||||
|
||||
{showExpiring ? (
|
||||
<div className="space-y-3 border-t border-zinc-200 pt-4">
|
||||
{expiringItems.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex flex-col gap-2 rounded-lg border border-amber-200 bg-amber-50/70 p-4 lg:flex-row lg:items-center lg:justify-between"
|
||||
>
|
||||
<div>
|
||||
<div className="font-medium text-zinc-900">
|
||||
{item.contractNo} · {item.counterpartyName}
|
||||
</div>
|
||||
<div className="mt-1 text-sm text-zinc-600">
|
||||
{contractTypeLabel(item.contractType)} · 到期日 {item.expiryDate ?? "-"} · 责任人 {item.owner?.name ?? "-"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditorId(item.id);
|
||||
setEditor(loadEditorFromItem(item));
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!expiringQuery.isLoading && !expiringItems.length ? (
|
||||
<div className="text-sm text-zinc-500">未来 {EXPIRING_DAYS} 天内暂无即将到期合同。</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-[400px,minmax(0,1fr)]">
|
||||
<div className="card-std space-y-4 p-6">
|
||||
<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>
|
||||
{editorId ? (
|
||||
<Button type="button" variant="secondary" size="sm" onClick={resetEditor}>
|
||||
切换到新建
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{editingItem?.status === "expired" ? (
|
||||
<div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
|
||||
当前合同因到期日已过,列表状态显示为“已过期”;保存时仍以数据库状态 {editingItem.persistedStatus} 持久化。
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>合同编号</Label>
|
||||
<Input value={contractNo} onChange={(event) => setContractNo(event.target.value)} placeholder="例如 HT-2026-001" />
|
||||
<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>
|
||||
<select className="select-std" value={projectId} onChange={(event) => setProjectId(event.target.value)}>
|
||||
<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}>
|
||||
@@ -132,98 +435,319 @@ export function ContractsRegistryPage() {
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>相对方</Label>
|
||||
<Input value={counterpartyName} onChange={(event) => setCounterpartyName(event.target.value)} placeholder="合同对方名称" />
|
||||
<Input
|
||||
value={editor.counterpartyName}
|
||||
onChange={(event) => setEditor((current) => ({ ...current, counterpartyName: event.target.value }))}
|
||||
placeholder="合同对方名称"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>摘要</Label>
|
||||
<Textarea value={summary} onChange={(event) => setSummary(event.target.value)} placeholder="只写最小必要摘要,不录入涉密正文" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>归档位置</Label>
|
||||
<Input value={archiveLocation} onChange={(event) => setArchiveLocation(event.target.value)} placeholder="NAS/文件柜/共享盘路径" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>离线档案号</Label>
|
||||
<Input value={offlineArchiveNo} onChange={(event) => setOfflineArchiveNo(event.target.value)} placeholder="可选" />
|
||||
<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}
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<div className="space-y-2">
|
||||
<Label>签署日期</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={editor.signedDate}
|
||||
onChange={(event) => setEditor((current) => ({ ...current, signedDate: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>生效日期</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={editor.effectiveDate}
|
||||
onChange={(event) => setEditor((current) => ({ ...current, effectiveDate: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>到期日期</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={editor.expiryDate}
|
||||
onChange={(event) => setEditor((current) => ({ ...current, expiryDate: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>归档位置</Label>
|
||||
<Input
|
||||
value={editor.archiveLocation}
|
||||
onChange={(event) => setEditor((current) => ({ ...current, archiveLocation: event.target.value }))}
|
||||
placeholder="NAS/文件柜/共享盘路径"
|
||||
/>
|
||||
</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={confidentialityLevel} onChange={(event) => setConfidentialityLevel(event.target.value as ConfidentialityLevel)}>
|
||||
<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>
|
||||
<option key={item} value={item}>
|
||||
{confidentialityLabel(item)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>状态</Label>
|
||||
<select className="select-std" value={status} onChange={(event) => setStatus(event.target.value)}>
|
||||
<option value="active">active</option>
|
||||
<option value="draft">draft</option>
|
||||
<option value="archived">archived</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>责任人</Label>
|
||||
<select className="select-std" value={ownerEmployeeId} onChange={(event) => setOwnerEmployeeId(event.target.value)}>
|
||||
<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>
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name} · {item.employeeNo}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
disabled={createMutation.isPending || !contractNo.trim() || !counterpartyName.trim() || !summary.trim() || !archiveLocation.trim()}
|
||||
onClick={() => createMutation.mutate()}
|
||||
disabled={
|
||||
saveMutation.isPending ||
|
||||
amountInvalid ||
|
||||
!editor.contractNo.trim() ||
|
||||
!editor.counterpartyName.trim() ||
|
||||
!editor.summary.trim() ||
|
||||
!editor.archiveLocation.trim() ||
|
||||
!editor.currency.trim()
|
||||
}
|
||||
onClick={() => saveMutation.mutate()}
|
||||
>
|
||||
{createMutation.isPending ? "创建中..." : "创建合同台账"}
|
||||
{saveMutation.isPending ? (editorId ? "保存中..." : "创建中...") : editorId ? "保存修改" : "创建合同台账"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="card-std space-y-4 p-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-zinc-900">台账列表</h3>
|
||||
<div className="text-sm text-zinc-500">{projectId ? "已按项目过滤" : "显示全部可见合同"}</div>
|
||||
<div className="mt-1 text-sm text-zinc-500">{filters.projectId ? "已按项目过滤" : "显示全部可见合同"}</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setFilters({
|
||||
projectId: initialProjectId,
|
||||
status: "",
|
||||
contractType: "",
|
||||
counterpartyName: "",
|
||||
expiryDateFrom: "",
|
||||
expiryDateTo: "",
|
||||
});
|
||||
setEditorId(null);
|
||||
setEditor(buildEmptyEditor(initialProjectId));
|
||||
}}
|
||||
>
|
||||
重置筛选
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
|
||||
<div className="space-y-2">
|
||||
<Label>项目</Label>
|
||||
<select
|
||||
className="select-std"
|
||||
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 className="space-y-2">
|
||||
<Label>状态</Label>
|
||||
<select
|
||||
className="select-std"
|
||||
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 className="space-y-2">
|
||||
<Label>合同类型</Label>
|
||||
<select
|
||||
className="select-std"
|
||||
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 className="space-y-2">
|
||||
<Label>相对方模糊筛选</Label>
|
||||
<Input
|
||||
value={filters.counterpartyName}
|
||||
onChange={(event) => setFilters((current) => ({ ...current, counterpartyName: event.target.value }))}
|
||||
placeholder="输入相对方名称关键字"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>到期日开始</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={filters.expiryDateFrom}
|
||||
onChange={(event) => setFilters((current) => ({ ...current, expiryDateFrom: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>到期日结束</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={filters.expiryDateTo}
|
||||
onChange={(event) => setFilters((current) => ({ ...current, expiryDateTo: event.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{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}
|
||||
{contractsQuery.isError ? (
|
||||
<div className="text-sm text-red-600">{resolveError(contractsQuery.error, "加载合同台账失败")}</div>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-3">
|
||||
{groupedContracts.map((item) => (
|
||||
{contracts.map((item) => (
|
||||
<div key={item.id} className="rounded-lg border border-zinc-200 p-4">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="font-semibold text-zinc-900">{item.contractNo}</div>
|
||||
<StatusBadge status={item.status} />
|
||||
<span className="rounded-full bg-zinc-100 px-2 py-1 text-xs text-zinc-600">{confidentialityLabel(item.confidentialityLevel)}</span>
|
||||
<span className="rounded-full bg-zinc-100 px-2 py-1 text-xs text-zinc-600">
|
||||
{confidentialityLabel(item.confidentialityLevel)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 text-sm text-zinc-900">{item.counterpartyName}</div>
|
||||
<div className="mt-1 text-sm text-zinc-600">{item.summary}</div>
|
||||
<div className="mt-2 text-xs text-zinc-500">
|
||||
项目:{item.project ? `${item.project.projectNo} · ${item.project.name}` : "未关联"} · 责任人:{item.owner?.name ?? "-"}
|
||||
<div className="text-sm text-zinc-900">{item.counterpartyName}</div>
|
||||
<div className="text-sm text-zinc-600">{item.summary}</div>
|
||||
<div className="text-xs text-zinc-500">
|
||||
{contractTypeLabel(item.contractType)}
|
||||
{item.amount ? ` · ${item.amount} ${item.currency}` : " · 金额未录入"}
|
||||
{item.expiryDate ? ` · 到期日 ${item.expiryDate}` : " · 未设置到期日"}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-zinc-500">归档:{item.archiveLocation}{item.offlineArchiveNo ? ` · 离线档案号 ${item.offlineArchiveNo}` : ""}</div>
|
||||
<div className="text-xs text-zinc-500">
|
||||
项目:{item.project ? `${item.project.projectNo} · ${item.project.name}` : "未关联"} · 责任人:
|
||||
{item.owner?.name ?? "-"}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<div className="text-xs text-zinc-500">
|
||||
签署:{item.signedDate ?? "-"} · 生效:{item.effectiveDate ?? "-"} · 归档:{item.archiveLocation}
|
||||
{item.offlineArchiveNo ? ` · 离线档案号 ${item.offlineArchiveNo}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 md:max-w-[260px] md:justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setEditorId(item.id);
|
||||
setEditor(loadEditorFromItem(item));
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={renewMutation.isPending || !["active", "expired"].includes(item.status)}
|
||||
onClick={() => renewMutation.mutate(item)}
|
||||
>
|
||||
续约
|
||||
</Button>
|
||||
{item.project ? (
|
||||
<Button asChild size="sm" variant="secondary" type="button">
|
||||
<Link to={`/projects/${item.project.id}`}>查看项目</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
<Button size="sm" variant="secondary" type="button" disabled={toggleStatusMutation.isPending} onClick={() => toggleStatusMutation.mutate(item)}>
|
||||
{item.status === "archived" ? "恢复为 active" : "归档"}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={toggleStatusMutation.isPending}
|
||||
onClick={() => toggleStatusMutation.mutate(item)}
|
||||
>
|
||||
{item.persistedStatus === "archived" ? "恢复为 active" : "归档"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!contractsQuery.isLoading && !groupedContracts.length ? <div className="text-sm text-zinc-500">暂无合同台账。</div> : null}
|
||||
|
||||
{!contractsQuery.isLoading && !contracts.length ? (
|
||||
<div className="text-sm text-zinc-500">暂无符合筛选条件的合同台账。</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||
"A1","R49 执行合同建档与范围冻结","创建并校验 R49 合同台账增强执行合同 CSV,冻结范围仅包含合同台账字段扩展、读时 expired 推导、续约事务、到期预警、合同导出与前端筛选/预警/导出交互;明确本轮不包含 R50 通知投递、权限码调整、导航改造或定时任务。","issues/2026-04-04_r49-contracts-registry.csv 列完整、Dependencies 为 JSON 数组字符串、Test_Method 可复现;范围仅覆盖 R49 合同台账增强,不混入 R50 或其他项目域改造。","命令:python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-04-04_r49-contracts-registry.csv。检查:1) 对照 AGENTS.md 与 issues/README.md 确认 12 列完整;2) A2-A7 依赖链与 backend→frontend→reviewer→qa 收口一致;3) 方案明确 expired 为读时状态,数据库不新增 expired 持久化值。","manual","DONE","DONE","DONE","issues/2026-04-04_r49-contracts-registry.csv","[]","2026-04-04:Issue CSV 已创建并通过 validate_issues_csv.py 校验,范围与依赖已冻结。续约语义固定为复制原合同字段并创建新草稿合同。"
|
||||
"A2","合同台账 Schema 与列表筛选增强","为 ContractRegistry 增加 contract_type、amount、currency、signed_date、effective_date、expiry_date 字段;新增共享筛选服务,扩展列表接口支持 status、contractType、counterpartyName、expiryDateFrom、expiryDateTo 过滤,并在读时推导 expired 状态。","Prisma schema 与迁移可通过校验;旧数据回填 contract_type=other、currency=CNY;GET /api/contracts-registry 支持新筛选参数,status=expired 返回数据库 active 且 expiry_date 早于今天的合同,status=active 不包含已过期合同;写接口禁止写入 expired。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && npx prisma validate && node --check src/routes/contractsRegistry.js && npm test -- server/tests/unit/routes/contractsRegistry.test.js。业务:1) 创建含金额/币种/日期的新合同成功返回;2) 列表按状态、类型、相对方、到期日期区间过滤正确;3) expiryDateTo 早于 expiryDateFrom 返回 VALID_001。","manual","DONE","DONE","DONE","server/prisma/schema.prisma|server/prisma/migrations|server/src/routes/contractsRegistry.js|server/src/services/contractRegistryFilters.js|server/tests/unit/routes/contractsRegistry.test.js","[""A1""]","2026-04-04:Schema、迁移、共享筛选服务与列表接口已实现;npx prisma validate、node --check、contractsRegistry.test.js 通过。2026-04-05:公网 smoke 回归通过,金额/分类/筛选能力验收完成。"
|
||||
"A3","合同生命周期与续约事务","新增 POST /api/contracts-registry/:id/renew,并补齐生命周期审计;续约时在事务内创建带 -R 序号的新草稿合同、归档旧合同、继承同一项目与业务字段。","仅对有效状态 active/expired 的合同允许续约;首次续约生成 -R1,后续递增;原合同自动归档并写审计;对 draft/archived 合同续约返回明确错误。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && node --check src/routes/contractsRegistry.js && npm test -- server/tests/unit/routes/contractsRegistry.test.js。业务:1) active 合同续约后原合同归档、新合同为 draft;2) expired 合同续约同样可生成新草稿;3) draft/archived 合同续约被拒绝;4) CONTRACT_REGISTRY_RENEWED 与状态变更审计已记录。","manual","DONE","DONE","DONE","server/src/routes/contractsRegistry.js|server/src/services/contractRegistryFilters.js|server/tests/unit/routes/contractsRegistry.test.js","[""A2""]","2026-04-04:续约事务、-R 序号计算与审计已实现;单测覆盖 active 续约和 draft 拒绝路径通过。2026-04-05:公网 smoke 回归通过,续约链路与生命周期状态验证通过。"
|
||||
"A4","到期预警与合同导出","新增 GET /api/contracts-registry/expiring 与 POST /api/exports/contracts-registry;复用共享筛选条件实现所见即所导,并沿用 exports.js 的文件头与审计模式。","/expiring?days=30 返回当前可见且在 N 天内到期的 active 合同;POST /api/exports/contracts-registry 支持 csv/xlsx,导出列与需求一致,且与当前筛选参数完全同步;导出写入 EXPORT_CONTRACTS_REGISTRY 审计。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && node --check src/routes/contractsRegistry.js && node --check src/routes/exports.js && npm test -- server/tests/unit/routes/exports.contractsRegistry.test.js。业务:1) days 默认 30,越界返回 VALID_001;2) expiring 仅包含 active 且未过今天边界的即将到期合同;3) csv/xlsx 导出包含合同编号、类型、相对方、金额、币种、状态、签署日期、生效日期、到期日期、项目、责任人、密级。","manual","DONE","DONE","DONE","server/src/routes/contractsRegistry.js|server/src/routes/exports.js|server/src/services/contractRegistryFilters.js|server/tests/unit/routes/exports.contractsRegistry.test.js","[""A2""]","2026-04-04:expiring 接口与 POST 导出已实现,csv/xlsx 单测通过,导出审计已写入。2026-04-05:公网 smoke 回归通过,预警卡片与导出链路验收完成。"
|
||||
"A5","前端 API 类型与编辑器扩展","扩展 contractsRegistry API 与类型定义,重构合同台账页编辑器,使其支持新字段的新建与编辑,并在列表卡片展示合同类型、金额、到期日期与有效状态。","client 端可创建和编辑带 contractType、amount、currency、signedDate、effectiveDate、expiryDate 的合同;列表卡片展示新字段且状态标签能识别 expired;金额按字符串提交与显示。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) 打开 /contracts-registry 可见扩展后的表单;2) 填写金额与日期字段后可创建合同;3) 选择现有合同进入编辑态并保存成功;4) 卡片展示类型、金额+币种、到期日期和状态。","manual","DONE","DONE","DONE","client/src/api/contractsRegistry.ts|client/src/pages/ContractsRegistryPage.tsx|client/src/components/common/StatusBadge.tsx","[""A2""]","2026-04-04:API 类型、编辑器与卡片展示已完成;client typecheck/build 通过。2026-04-05:公网 smoke 回归通过,新建/编辑主链路验收完成。"
|
||||
"A6","前端筛选 预警 续约 导出交互收口","在合同台账页补齐状态/类型/相对方/到期日范围筛选、到期预警卡片、续约按钮与导出按钮,并保持项目详情页对合同台账列表的兼容。","/contracts-registry 支持多条件筛选并刷新列表;顶部显示“N 份合同将在 30 天内到期”卡片并可展开;合同可直接续约;CSV/XLSX 导出成功下载;ProjectDetailPage 继续按 projectId 获取合同列表且不回归。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) 设置筛选条件后列表与预警卡片同步刷新;2) 点击续约后列表出现新的 draft 合同且原合同归档;3) 点击导出可下载 csv/xlsx;4) 从项目详情页进入合同台账时 projectId 过滤仍生效。","manual","DONE","DONE","DONE","client/src/api/contractsRegistry.ts|client/src/pages/ContractsRegistryPage.tsx|client/src/pages/ProjectDetailPage.tsx|client/src/lib/download.ts","[""A3"",""A4"",""A5""]","2026-04-04:筛选、预警卡片、续约和导出交互已接入,导出 POST 请求头已补齐;client build 通过。2026-04-05:公网 smoke 回归通过,筛选/预警/续约/导出交互验收完成。"
|
||||
"A7","R49 reviewer QA 与提交收口","对 Prisma 迁移、expired 推导、续约事务和导出一致性进行 reviewer 风格复核,并完成 backend/frontend post-check 与业务回归,回填 Issue CSV 状态。","review 重点结论、自动化结果和业务回归证据完整;A2-A6 的 Review1_Status 与 Regression_Status 回填;所有 post-check 通过后方可提交。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && npx prisma validate && node --check src/routes/contractsRegistry.js && node --check src/routes/exports.js && npm test -- server/tests/unit/routes/contractsRegistry.test.js server/tests/unit/routes/exports.contractsRegistry.test.js && cd ../client && npm run typecheck && npm run build。业务:1) 新建/编辑/筛选/预警/续约/导出主链路通过;2) status=expired、days 边界、date range 非法输入返回正确错误;3) 项目详情页合同列表无回归。","manual","DONE","DONE","DONE","issues/2026-04-04_r49-contracts-registry.csv|server/src/routes/contractsRegistry.js|server/src/routes/exports.js|client/src/pages/ContractsRegistryPage.tsx|client/src/pages/ProjectDetailPage.tsx","[""A3"",""A4"",""A6""]","2026-04-04:已完成 reviewer 风格代码复核、git diff --check、Prisma validate、后端单测、client typecheck/build。2026-04-05:公网 smoke 测试通过(OpenClaw 验收 2026-04-05),R49 合同台账增强主链路回归完成。"
|
||||
|
@@ -0,0 +1,17 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ContractRegistryType" AS ENUM ('purchase', 'sales', 'service', 'framework', 'other');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "contract_registry"
|
||||
ADD COLUMN "contract_type" "ContractRegistryType" NOT NULL DEFAULT 'other',
|
||||
ADD COLUMN "amount" DECIMAL(14, 2),
|
||||
ADD COLUMN "currency" VARCHAR(8) NOT NULL DEFAULT 'CNY',
|
||||
ADD COLUMN "signed_date" DATE,
|
||||
ADD COLUMN "effective_date" DATE,
|
||||
ADD COLUMN "expiry_date" DATE;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_contract_registry_status_expiry" ON "contract_registry"("status", "expiry_date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_contract_registry_type_status" ON "contract_registry"("contract_type", "status");
|
||||
@@ -412,6 +412,12 @@ enum TodoStatus {
|
||||
cancelled
|
||||
}
|
||||
|
||||
enum NotificationDeliveryStatus {
|
||||
pending
|
||||
success
|
||||
failed
|
||||
}
|
||||
|
||||
enum TodoSource {
|
||||
manual
|
||||
weekly_report
|
||||
@@ -492,6 +498,14 @@ enum ConfidentialityLevel {
|
||||
restricted
|
||||
}
|
||||
|
||||
enum ContractRegistryType {
|
||||
purchase
|
||||
sales
|
||||
service
|
||||
framework
|
||||
other
|
||||
}
|
||||
|
||||
enum DocumentStorageType {
|
||||
oa_link
|
||||
nas
|
||||
@@ -549,6 +563,7 @@ model Employee {
|
||||
emergency_contact_phone String?
|
||||
notes String?
|
||||
avatar_path String?
|
||||
notification_push_enabled Boolean @default(true)
|
||||
|
||||
bank_account_encrypted String
|
||||
bank_name String
|
||||
@@ -754,12 +769,33 @@ model Notification {
|
||||
created_at DateTime @default(now())
|
||||
|
||||
recipient Employee @relation(fields: [recipient_employee_id], references: [id], onDelete: Cascade)
|
||||
deliveries NotificationDelivery[]
|
||||
|
||||
@@index([recipient_employee_id, created_at])
|
||||
@@index([recipient_employee_id, read_at, created_at], map: "idx_notifications_unread_query")
|
||||
@@map("notifications")
|
||||
}
|
||||
|
||||
model NotificationDelivery {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
notification_id String @db.Uuid
|
||||
channel_id String @db.Uuid
|
||||
status NotificationDeliveryStatus
|
||||
attempt_no Int
|
||||
result_code String? @db.VarChar(64)
|
||||
error_message String?
|
||||
response_body Json?
|
||||
attempted_at DateTime @default(now())
|
||||
|
||||
notification Notification @relation(fields: [notification_id], references: [id], onDelete: Cascade)
|
||||
channel NotificationChannel @relation(fields: [channel_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([notification_id, attempted_at], map: "idx_notification_deliveries_notification_attempted")
|
||||
@@index([channel_id, attempted_at], map: "idx_notification_deliveries_channel_attempted")
|
||||
@@index([status, attempted_at], map: "idx_notification_deliveries_status_attempted")
|
||||
@@map("notification_deliveries")
|
||||
}
|
||||
|
||||
model ExpenseType {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique
|
||||
@@ -2014,8 +2050,14 @@ model ContractRegistry {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
contract_no String @unique
|
||||
project_id String? @db.Uuid
|
||||
contract_type ContractRegistryType @default(other)
|
||||
counterparty_name String
|
||||
summary String
|
||||
amount Decimal? @db.Decimal(14, 2)
|
||||
currency String @default("CNY") @db.VarChar(8)
|
||||
signed_date DateTime? @db.Date
|
||||
effective_date DateTime? @db.Date
|
||||
expiry_date DateTime? @db.Date
|
||||
confidentiality_level ConfidentialityLevel @default(internal)
|
||||
archive_location String
|
||||
offline_archive_no String?
|
||||
@@ -2030,6 +2072,8 @@ model ContractRegistry {
|
||||
document_refs ConfidentialDocumentRef[]
|
||||
|
||||
@@index([project_id, status], map: "idx_contract_registry_project_status")
|
||||
@@index([status, expiry_date], map: "idx_contract_registry_status_expiry")
|
||||
@@index([contract_type, status], map: "idx_contract_registry_type_status")
|
||||
@@index([owner_employee_id, created_at], map: "idx_contract_registry_owner_created")
|
||||
@@map("contract_registry")
|
||||
}
|
||||
@@ -2649,6 +2693,8 @@ model NotificationChannel {
|
||||
updated_at DateTime @default(now()) @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
deliveries NotificationDelivery[]
|
||||
|
||||
@@unique([channel_type, name], map: "notification_channels_type_name_ux")
|
||||
@@index([enabled, channel_type], map: "idx_notification_channels_enabled_type")
|
||||
@@map("notification_channels")
|
||||
|
||||
@@ -1,147 +1,381 @@
|
||||
const { z } = require("zod");
|
||||
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
const {
|
||||
CONTRACT_REGISTRY_PERSISTED_STATUS_VALUES,
|
||||
CONTRACT_REGISTRY_TYPE_VALUES,
|
||||
buildContractRegistryExpiringWhere,
|
||||
buildContractRegistryValidationError,
|
||||
buildContractRegistryWhere,
|
||||
canManageContractRegistry,
|
||||
formatContractRegistryAmount,
|
||||
formatContractRegistryDateOnly,
|
||||
parseContractRegistryExpiringQuery,
|
||||
parseContractRegistryFilters,
|
||||
resolveContractRegistryEffectiveStatus,
|
||||
resolveContractRegistryToday,
|
||||
} = require("../services/contractRegistryFilters");
|
||||
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
const { parseDateOnlyString } = require("../utils/date");
|
||||
const { sendData } = require("../utils/reply");
|
||||
|
||||
const UUID_SCHEMA = z.string().uuid();
|
||||
const DATE_ONLY_SCHEMA = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const CONFIDENTIALITY_SCHEMA = z.enum(["public", "internal", "confidential", "restricted"]);
|
||||
const LIST_QUERY_SCHEMA = z.object({ projectId: UUID_SCHEMA.optional() });
|
||||
const WRITE_SCHEMA = z.object({
|
||||
const CONTRACT_TYPE_SCHEMA = z.enum(CONTRACT_REGISTRY_TYPE_VALUES);
|
||||
const STATUS_WRITE_SCHEMA = z.enum(CONTRACT_REGISTRY_PERSISTED_STATUS_VALUES);
|
||||
const MONEY_INPUT_SCHEMA = z.string().regex(/^\d{1,12}(\.\d{1,2})?$/);
|
||||
const CURRENCY_SCHEMA = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(8)
|
||||
.transform((value) => value.toUpperCase());
|
||||
|
||||
const WRITE_SCHEMA = z
|
||||
.object({
|
||||
contractNo: z.string().trim().min(1).max(80),
|
||||
projectId: UUID_SCHEMA.nullable().optional(),
|
||||
contractType: CONTRACT_TYPE_SCHEMA,
|
||||
counterpartyName: z.string().trim().min(1).max(200),
|
||||
summary: z.string().trim().min(1).max(4000),
|
||||
amount: MONEY_INPUT_SCHEMA.nullable().optional(),
|
||||
currency: CURRENCY_SCHEMA.optional(),
|
||||
signedDate: DATE_ONLY_SCHEMA.nullable().optional(),
|
||||
effectiveDate: DATE_ONLY_SCHEMA.nullable().optional(),
|
||||
expiryDate: DATE_ONLY_SCHEMA.nullable().optional(),
|
||||
confidentialityLevel: CONFIDENTIALITY_SCHEMA.optional(),
|
||||
archiveLocation: z.string().trim().min(1).max(500),
|
||||
offlineArchiveNo: z.string().trim().max(120).nullable().optional(),
|
||||
ownerEmployeeId: UUID_SCHEMA.optional(),
|
||||
status: z.string().trim().min(1).max(32).optional(),
|
||||
}).strict();
|
||||
const PATCH_SCHEMA = WRITE_SCHEMA.partial().refine((value) => Object.keys(value).length > 0, { message: "empty_patch" });
|
||||
status: STATUS_WRITE_SCHEMA.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
function buildValidationError(details, statusCode = 400) {
|
||||
return new AppError({ code: "VALID_001", message: "参数校验失败", statusCode, details });
|
||||
}
|
||||
const PATCH_SCHEMA = WRITE_SCHEMA.partial().refine((value) => Object.keys(value).length > 0, {
|
||||
message: "empty_patch",
|
||||
});
|
||||
|
||||
const CONTRACT_REGISTRY_INCLUDE = {
|
||||
owner: { select: { id: true, employee_no: true, name: true } },
|
||||
project: { select: { id: true, project_no: true, name: true } },
|
||||
};
|
||||
|
||||
function parseBody(schema, body) {
|
||||
const parsed = schema.safeParse(body ?? {});
|
||||
if (!parsed.success) throw buildValidationError(parsed.error.flatten());
|
||||
if (!parsed.success) {
|
||||
throw buildContractRegistryValidationError(parsed.error.flatten());
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async function ensureFeatureEnabled(fastify, request) {
|
||||
const gate = await evaluateFeatureFlag({ prisma: fastify.prisma, config: fastify.config, flagKey: FEATURE_FLAG_KEYS.projectLinking, departmentId: request.employee.department_id ?? null, strictDepartment: false });
|
||||
if (!gate.enabled) throw buildValidationError({ featureFlag: "project_linking_v1_disabled", reason: gate.reason }, 409);
|
||||
const gate = await evaluateFeatureFlag({
|
||||
prisma: fastify.prisma,
|
||||
config: fastify.config,
|
||||
flagKey: FEATURE_FLAG_KEYS.projectLinking,
|
||||
departmentId: request.employee.department_id ?? null,
|
||||
strictDepartment: false,
|
||||
});
|
||||
if (!gate.enabled) {
|
||||
throw buildContractRegistryValidationError(
|
||||
{ featureFlag: "project_linking_v1_disabled", reason: gate.reason },
|
||||
409,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function canManage(fastify, employee) {
|
||||
return fastify.hasPermission(employee, "project.manage") || fastify.hasPermission(employee, "project.view_all") || fastify.hasPermission(employee, "system.settings");
|
||||
}
|
||||
|
||||
async function writeAudit(fastify, request, action, targetId, extra = {}) {
|
||||
async function writeAudit(prisma, request, action, targetId, extra = {}) {
|
||||
try {
|
||||
await fastify.prisma.auditLog.create({ data: buildAuditLogData(request, { actorId: request.employee.id, action, targetType: "contract_registry", targetId, extra }) });
|
||||
await prisma.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action,
|
||||
targetType: "contract_registry",
|
||||
targetId,
|
||||
extra,
|
||||
}),
|
||||
});
|
||||
} catch (error) {
|
||||
request.log.error({ err: error, action, targetId }, "contract registry audit failed");
|
||||
}
|
||||
}
|
||||
|
||||
function mapRow(item) {
|
||||
function parseOptionalDate(value) {
|
||||
return value ? parseDateOnlyString(value) : null;
|
||||
}
|
||||
|
||||
function mapRow(item, today) {
|
||||
return {
|
||||
id: item.id,
|
||||
contractNo: item.contract_no,
|
||||
projectId: item.project_id ?? null,
|
||||
contractType: item.contract_type,
|
||||
counterpartyName: item.counterparty_name,
|
||||
summary: item.summary,
|
||||
amount: formatContractRegistryAmount(item.amount),
|
||||
currency: item.currency,
|
||||
signedDate: formatContractRegistryDateOnly(item.signed_date),
|
||||
effectiveDate: formatContractRegistryDateOnly(item.effective_date),
|
||||
expiryDate: formatContractRegistryDateOnly(item.expiry_date),
|
||||
confidentialityLevel: item.confidentiality_level,
|
||||
archiveLocation: item.archive_location,
|
||||
offlineArchiveNo: item.offline_archive_no ?? null,
|
||||
ownerEmployeeId: item.owner_employee_id,
|
||||
status: item.status,
|
||||
status: resolveContractRegistryEffectiveStatus(item, today),
|
||||
persistedStatus: item.status,
|
||||
createdAt: item.created_at?.toISOString?.() ?? null,
|
||||
updatedAt: item.updated_at?.toISOString?.() ?? null,
|
||||
owner: item.owner ? { id: item.owner.id, employeeNo: item.owner.employee_no, name: item.owner.name } : null,
|
||||
project: item.project ? { id: item.project.id, projectNo: item.project.project_no, name: item.project.name } : null,
|
||||
owner: item.owner
|
||||
? { id: item.owner.id, employeeNo: item.owner.employee_no, name: item.owner.name }
|
||||
: null,
|
||||
project: item.project
|
||||
? { id: item.project.id, projectNo: item.project.project_no, name: item.project.name }
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildNotFoundError() {
|
||||
return new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||
}
|
||||
|
||||
function buildRenewalContractNo(baseContractNo, rows) {
|
||||
const escaped = baseContractNo.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const pattern = new RegExp(`^${escaped}-R(\\d+)$`);
|
||||
const maxRenewalIndex = rows.reduce((currentMax, row) => {
|
||||
const match = row.contract_no.match(pattern);
|
||||
if (!match) {
|
||||
return currentMax;
|
||||
}
|
||||
return Math.max(currentMax, Number(match[1]) || 0);
|
||||
}, 0);
|
||||
|
||||
return `${baseContractNo}-R${maxRenewalIndex + 1}`;
|
||||
}
|
||||
|
||||
async function contractsRegistryRoutes(fastify) {
|
||||
fastify.get("/contracts-registry", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const parsed = LIST_QUERY_SCHEMA.safeParse(request.query ?? {});
|
||||
if (!parsed.success) throw buildValidationError(parsed.error.flatten());
|
||||
const filters = parseContractRegistryFilters(request.query);
|
||||
const today = resolveContractRegistryToday(fastify.config.appTimezone);
|
||||
const rows = await fastify.prisma.contractRegistry.findMany({
|
||||
where: {
|
||||
AND: [
|
||||
parsed.data.projectId ? { project_id: parsed.data.projectId } : {},
|
||||
canManage(fastify, request.employee)
|
||||
? {}
|
||||
: {
|
||||
OR: [
|
||||
{ owner_employee_id: request.employee.id },
|
||||
{ project: { owner_employee_id: request.employee.id } },
|
||||
{ project: { manager_employee_id: request.employee.id } },
|
||||
{ project: { members: { some: { employee_id: request.employee.id, left_at: null } } } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { updated_at: "desc" },
|
||||
include: { owner: { select: { id: true, employee_no: true, name: true } }, project: { select: { id: true, project_no: true, name: true } } },
|
||||
where: buildContractRegistryWhere({
|
||||
filters,
|
||||
employee: request.employee,
|
||||
hasPermission: fastify.hasPermission,
|
||||
timeZone: fastify.config.appTimezone,
|
||||
}),
|
||||
orderBy: [{ updated_at: "desc" }, { id: "desc" }],
|
||||
include: CONTRACT_REGISTRY_INCLUDE,
|
||||
});
|
||||
|
||||
return sendData(reply, request, { items: rows.map((item) => mapRow(item, today)) });
|
||||
});
|
||||
|
||||
fastify.get("/contracts-registry/expiring", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const { days } = parseContractRegistryExpiringQuery(request.query);
|
||||
const today = resolveContractRegistryToday(fastify.config.appTimezone);
|
||||
const rows = await fastify.prisma.contractRegistry.findMany({
|
||||
where: buildContractRegistryExpiringWhere({
|
||||
employee: request.employee,
|
||||
hasPermission: fastify.hasPermission,
|
||||
timeZone: fastify.config.appTimezone,
|
||||
days,
|
||||
}),
|
||||
orderBy: [{ expiry_date: "asc" }, { updated_at: "desc" }, { id: "desc" }],
|
||||
include: CONTRACT_REGISTRY_INCLUDE,
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
days,
|
||||
total: rows.length,
|
||||
items: rows.map((item) => mapRow(item, today)),
|
||||
});
|
||||
return sendData(reply, request, { items: rows.map(mapRow) });
|
||||
});
|
||||
|
||||
fastify.post("/contracts-registry", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
if (!canManage(fastify, request.employee)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "project.manage" } });
|
||||
if (!canManageContractRegistry(fastify.hasPermission, request.employee)) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
details: { permission: "project.manage" },
|
||||
});
|
||||
}
|
||||
|
||||
const body = parseBody(WRITE_SCHEMA, request.body);
|
||||
const today = resolveContractRegistryToday(fastify.config.appTimezone);
|
||||
const created = await fastify.prisma.contractRegistry.create({
|
||||
data: {
|
||||
contract_no: body.contractNo,
|
||||
project_id: body.projectId ?? null,
|
||||
contract_type: body.contractType,
|
||||
counterparty_name: body.counterpartyName,
|
||||
summary: body.summary,
|
||||
amount: body.amount ?? null,
|
||||
currency: body.currency ?? "CNY",
|
||||
signed_date: parseOptionalDate(body.signedDate),
|
||||
effective_date: parseOptionalDate(body.effectiveDate),
|
||||
expiry_date: parseOptionalDate(body.expiryDate),
|
||||
confidentiality_level: body.confidentialityLevel ?? "internal",
|
||||
archive_location: body.archiveLocation,
|
||||
offline_archive_no: body.offlineArchiveNo ?? null,
|
||||
owner_employee_id: body.ownerEmployeeId ?? request.employee.id,
|
||||
status: body.status ?? "active",
|
||||
},
|
||||
include: { owner: { select: { id: true, employee_no: true, name: true } }, project: { select: { id: true, project_no: true, name: true } } },
|
||||
include: CONTRACT_REGISTRY_INCLUDE,
|
||||
});
|
||||
|
||||
await writeAudit(fastify.prisma, request, "CONTRACT_REGISTRY_CREATED", created.id, {
|
||||
contractNo: created.contract_no,
|
||||
});
|
||||
return reply.code(201).send({
|
||||
requestId: request.id,
|
||||
data: { item: mapRow(created, today) },
|
||||
});
|
||||
await writeAudit(fastify, request, "CONTRACT_REGISTRY_CREATED", created.id, { contractNo: created.contract_no });
|
||||
return reply.code(201).send({ requestId: request.id, data: { item: mapRow(created) } });
|
||||
});
|
||||
|
||||
fastify.patch("/contracts-registry/:id", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
if (!canManage(fastify, request.employee)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "project.manage" } });
|
||||
if (!canManageContractRegistry(fastify.hasPermission, request.employee)) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
details: { permission: "project.manage" },
|
||||
});
|
||||
}
|
||||
|
||||
const contractId = UUID_SCHEMA.parse(request.params?.id);
|
||||
const body = parseBody(PATCH_SCHEMA, request.body);
|
||||
const existing = await fastify.prisma.contractRegistry.findUnique({
|
||||
where: { id: contractId },
|
||||
select: { id: true, status: true, contract_no: true },
|
||||
});
|
||||
if (!existing) {
|
||||
throw buildNotFoundError();
|
||||
}
|
||||
|
||||
const today = resolveContractRegistryToday(fastify.config.appTimezone);
|
||||
const updated = await fastify.prisma.contractRegistry.update({
|
||||
where: { id: contractId },
|
||||
data: {
|
||||
...(body.contractNo !== undefined ? { contract_no: body.contractNo } : {}),
|
||||
...(body.projectId !== undefined ? { project_id: body.projectId ?? null } : {}),
|
||||
...(body.contractType !== undefined ? { contract_type: body.contractType } : {}),
|
||||
...(body.counterpartyName !== undefined ? { counterparty_name: body.counterpartyName } : {}),
|
||||
...(body.summary !== undefined ? { summary: body.summary } : {}),
|
||||
...(body.confidentialityLevel !== undefined ? { confidentiality_level: body.confidentialityLevel } : {}),
|
||||
...(body.amount !== undefined ? { amount: body.amount ?? null } : {}),
|
||||
...(body.currency !== undefined ? { currency: body.currency } : {}),
|
||||
...(body.signedDate !== undefined ? { signed_date: parseOptionalDate(body.signedDate) } : {}),
|
||||
...(body.effectiveDate !== undefined ? { effective_date: parseOptionalDate(body.effectiveDate) } : {}),
|
||||
...(body.expiryDate !== undefined ? { expiry_date: parseOptionalDate(body.expiryDate) } : {}),
|
||||
...(body.confidentialityLevel !== undefined
|
||||
? { confidentiality_level: body.confidentialityLevel }
|
||||
: {}),
|
||||
...(body.archiveLocation !== undefined ? { archive_location: body.archiveLocation } : {}),
|
||||
...(body.offlineArchiveNo !== undefined ? { offline_archive_no: body.offlineArchiveNo ?? null } : {}),
|
||||
...(body.ownerEmployeeId !== undefined ? { owner_employee_id: body.ownerEmployeeId } : {}),
|
||||
...(body.status !== undefined ? { status: body.status } : {}),
|
||||
},
|
||||
include: { owner: { select: { id: true, employee_no: true, name: true } }, project: { select: { id: true, project_no: true, name: true } } },
|
||||
include: CONTRACT_REGISTRY_INCLUDE,
|
||||
});
|
||||
|
||||
await writeAudit(fastify.prisma, request, "CONTRACT_REGISTRY_UPDATED", updated.id, {
|
||||
fields: Object.keys(body),
|
||||
});
|
||||
if (body.status !== undefined && body.status !== existing.status) {
|
||||
await writeAudit(fastify.prisma, request, "CONTRACT_REGISTRY_STATUS_CHANGED", updated.id, {
|
||||
fromStatus: existing.status,
|
||||
toStatus: body.status,
|
||||
});
|
||||
}
|
||||
|
||||
return sendData(reply, request, { item: mapRow(updated, today) });
|
||||
});
|
||||
|
||||
fastify.post("/contracts-registry/:id/renew", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
if (!canManageContractRegistry(fastify.hasPermission, request.employee)) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
details: { permission: "project.manage" },
|
||||
});
|
||||
}
|
||||
|
||||
const contractId = UUID_SCHEMA.parse(request.params?.id);
|
||||
const today = resolveContractRegistryToday(fastify.config.appTimezone);
|
||||
const result = await fastify.prisma.$transaction(async (tx) => {
|
||||
const original = await tx.contractRegistry.findUnique({
|
||||
where: { id: contractId },
|
||||
include: CONTRACT_REGISTRY_INCLUDE,
|
||||
});
|
||||
if (!original) {
|
||||
throw buildNotFoundError();
|
||||
}
|
||||
|
||||
const effectiveStatus = resolveContractRegistryEffectiveStatus(original, today);
|
||||
if (!["active", "expired"].includes(effectiveStatus)) {
|
||||
throw buildContractRegistryValidationError({ status: "renew_not_allowed" }, 409);
|
||||
}
|
||||
|
||||
const baseContractNo = original.contract_no.replace(/-R\d+$/, "");
|
||||
const lineageRows = await tx.contractRegistry.findMany({
|
||||
where: { contract_no: { startsWith: baseContractNo } },
|
||||
select: { contract_no: true },
|
||||
});
|
||||
const nextContractNo = buildRenewalContractNo(baseContractNo, lineageRows);
|
||||
|
||||
const renewed = await tx.contractRegistry.create({
|
||||
data: {
|
||||
contract_no: nextContractNo,
|
||||
project_id: original.project_id ?? null,
|
||||
contract_type: original.contract_type,
|
||||
counterparty_name: original.counterparty_name,
|
||||
summary: original.summary,
|
||||
amount: original.amount ?? null,
|
||||
currency: original.currency,
|
||||
signed_date: original.signed_date,
|
||||
effective_date: original.effective_date,
|
||||
expiry_date: original.expiry_date,
|
||||
confidentiality_level: original.confidentiality_level,
|
||||
archive_location: original.archive_location,
|
||||
offline_archive_no: original.offline_archive_no ?? null,
|
||||
owner_employee_id: original.owner_employee_id,
|
||||
status: "draft",
|
||||
},
|
||||
include: CONTRACT_REGISTRY_INCLUDE,
|
||||
});
|
||||
|
||||
const archivedSource = await tx.contractRegistry.update({
|
||||
where: { id: original.id },
|
||||
data: { status: "archived" },
|
||||
include: CONTRACT_REGISTRY_INCLUDE,
|
||||
});
|
||||
|
||||
await writeAudit(tx, request, "CONTRACT_REGISTRY_RENEWED", renewed.id, {
|
||||
sourceContractId: original.id,
|
||||
sourceContractNo: original.contract_no,
|
||||
renewedContractNo: renewed.contract_no,
|
||||
});
|
||||
await writeAudit(tx, request, "CONTRACT_REGISTRY_STATUS_CHANGED", archivedSource.id, {
|
||||
fromStatus: original.status,
|
||||
toStatus: "archived",
|
||||
reason: "renew",
|
||||
});
|
||||
|
||||
return { renewed, archivedSource };
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
item: mapRow(result.renewed, today),
|
||||
sourceItem: mapRow(result.archivedSource, today),
|
||||
});
|
||||
await writeAudit(fastify, request, "CONTRACT_REGISTRY_UPDATED", updated.id, { fields: Object.keys(body) });
|
||||
return sendData(reply, request, { item: mapRow(updated) });
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -3,11 +3,21 @@ const { Readable } = require("node:stream");
|
||||
const ExcelJS = require("exceljs");
|
||||
const { z } = require("zod");
|
||||
|
||||
const {
|
||||
CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA,
|
||||
buildContractRegistryWhere,
|
||||
formatContractRegistryAmount,
|
||||
formatContractRegistryDateOnly,
|
||||
parseContractRegistryFilters,
|
||||
resolveContractRegistryEffectiveStatus,
|
||||
resolveContractRegistryToday,
|
||||
} = require("../services/contractRegistryFilters");
|
||||
const {
|
||||
EMPLOYMENT_STATUS_VALUES,
|
||||
buildEmployeeDirectoryWhere,
|
||||
parseEmployeeDirectoryFilters,
|
||||
} = require("../services/employeeDirectoryFilters");
|
||||
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
||||
const {
|
||||
HISTORY_STATUS_VALUES,
|
||||
buildPresenceValidationError,
|
||||
@@ -88,6 +98,11 @@ const PRESENCE_HISTORY_EXPORT_QUERY_SCHEMA = z.object({
|
||||
employeeId: z.string().uuid().optional(),
|
||||
status: z.enum(HISTORY_STATUS_VALUES).optional(),
|
||||
});
|
||||
|
||||
const CONTRACT_REGISTRY_EXPORT_BODY_SCHEMA = CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA.extend({
|
||||
format: EXPORT_FORMAT_SCHEMA.optional(),
|
||||
});
|
||||
|
||||
const PRESENCE_HISTORY_EXPORT_LIMIT = 5000;
|
||||
|
||||
function csvCell(value) {
|
||||
@@ -118,6 +133,20 @@ function parseQuery(schema, query) {
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseBody(schema, body) {
|
||||
const parsed = schema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function resolveExportFormat(query) {
|
||||
return query.format ?? "csv";
|
||||
}
|
||||
@@ -302,6 +331,170 @@ function setExportHeaders(reply, format, filename) {
|
||||
reply.header("content-disposition", `attachment; filename=\"${filename}\"`);
|
||||
}
|
||||
|
||||
async function ensureContractsRegistryExportEnabled(fastify, request) {
|
||||
const gate = await evaluateFeatureFlag({
|
||||
prisma: fastify.prisma,
|
||||
config: fastify.config,
|
||||
flagKey: FEATURE_FLAG_KEYS.projectLinking,
|
||||
departmentId: request.employee.department_id ?? null,
|
||||
strictDepartment: false,
|
||||
});
|
||||
|
||||
if (!gate.enabled) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { featureFlag: "project_linking_v1_disabled", reason: gate.reason },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function confidentialityLevelLabel(value) {
|
||||
if (value === "public") return "公开";
|
||||
if (value === "internal") return "内部";
|
||||
if (value === "confidential") return "机密";
|
||||
return "限制";
|
||||
}
|
||||
|
||||
function contractRegistryTypeLabel(value) {
|
||||
if (value === "purchase") return "采购合同";
|
||||
if (value === "sales") return "销售合同";
|
||||
if (value === "service") return "服务合同";
|
||||
if (value === "framework") return "框架协议";
|
||||
return "其他";
|
||||
}
|
||||
|
||||
function contractRegistryStatusLabel(value) {
|
||||
if (value === "draft") return "草稿";
|
||||
if (value === "active") return "生效中";
|
||||
if (value === "expired") return "已过期";
|
||||
if (value === "archived") return "已归档";
|
||||
return value ?? "";
|
||||
}
|
||||
|
||||
function mapContractRegistryExportRow(item, today) {
|
||||
const effectiveStatus = resolveContractRegistryEffectiveStatus(item, today);
|
||||
return [
|
||||
item.contract_no,
|
||||
contractRegistryTypeLabel(item.contract_type),
|
||||
item.counterparty_name,
|
||||
formatContractRegistryAmount(item.amount),
|
||||
item.currency,
|
||||
contractRegistryStatusLabel(effectiveStatus),
|
||||
formatContractRegistryDateOnly(item.signed_date),
|
||||
formatContractRegistryDateOnly(item.effective_date),
|
||||
formatContractRegistryDateOnly(item.expiry_date),
|
||||
item.project ? `${item.project.project_no} · ${item.project.name}` : "",
|
||||
item.owner?.name ?? "",
|
||||
confidentialityLevelLabel(item.confidentiality_level),
|
||||
];
|
||||
}
|
||||
|
||||
async function* streamContractsRegistryCsv(prisma, where, today) {
|
||||
yield "\ufeff";
|
||||
yield csvRow([
|
||||
"合同编号",
|
||||
"类型",
|
||||
"相对方",
|
||||
"金额",
|
||||
"币种",
|
||||
"状态",
|
||||
"签署日期",
|
||||
"生效日期",
|
||||
"到期日期",
|
||||
"项目",
|
||||
"责任人",
|
||||
"密级",
|
||||
]);
|
||||
|
||||
const batchSize = 500;
|
||||
let cursorUpdatedAt = null;
|
||||
let cursorId = null;
|
||||
|
||||
while (true) {
|
||||
const rows = await prisma.contractRegistry.findMany({
|
||||
where: {
|
||||
...where,
|
||||
...(cursorUpdatedAt
|
||||
? {
|
||||
OR: [
|
||||
{ updated_at: { lt: cursorUpdatedAt } },
|
||||
{ updated_at: cursorUpdatedAt, id: { lt: cursorId } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: [{ updated_at: "desc" }, { id: "desc" }],
|
||||
take: batchSize,
|
||||
include: {
|
||||
owner: { select: { name: true } },
|
||||
project: { select: { project_no: true, name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!rows.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
for (const item of rows) {
|
||||
yield csvRow(mapContractRegistryExportRow(item, today));
|
||||
}
|
||||
|
||||
const last = rows[rows.length - 1];
|
||||
cursorUpdatedAt = last.updated_at;
|
||||
cursorId = last.id;
|
||||
}
|
||||
}
|
||||
|
||||
async function buildContractsRegistryXlsx(prisma, where, today) {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet("contracts_registry");
|
||||
|
||||
sheet.columns = [
|
||||
{ header: "合同编号", key: "contractNo", width: 22 },
|
||||
{ header: "类型", key: "contractType", width: 16 },
|
||||
{ header: "相对方", key: "counterpartyName", width: 24 },
|
||||
{ header: "金额", key: "amount", width: 16 },
|
||||
{ header: "币种", key: "currency", width: 12 },
|
||||
{ header: "状态", key: "status", width: 12 },
|
||||
{ header: "签署日期", key: "signedDate", width: 14 },
|
||||
{ header: "生效日期", key: "effectiveDate", width: 14 },
|
||||
{ header: "到期日期", key: "expiryDate", width: 14 },
|
||||
{ header: "项目", key: "projectName", width: 24 },
|
||||
{ header: "责任人", key: "ownerName", width: 16 },
|
||||
{ header: "密级", key: "confidentialityLevel", width: 12 },
|
||||
];
|
||||
|
||||
const rows = await prisma.contractRegistry.findMany({
|
||||
where,
|
||||
orderBy: [{ updated_at: "desc" }, { id: "desc" }],
|
||||
include: {
|
||||
owner: { select: { name: true } },
|
||||
project: { select: { project_no: true, name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
for (const item of rows) {
|
||||
sheet.addRow({
|
||||
contractNo: item.contract_no,
|
||||
contractType: contractRegistryTypeLabel(item.contract_type),
|
||||
counterpartyName: item.counterparty_name,
|
||||
amount: formatContractRegistryAmount(item.amount),
|
||||
currency: item.currency,
|
||||
status: contractRegistryStatusLabel(resolveContractRegistryEffectiveStatus(item, today)),
|
||||
signedDate: formatContractRegistryDateOnly(item.signed_date),
|
||||
effectiveDate: formatContractRegistryDateOnly(item.effective_date),
|
||||
expiryDate: formatContractRegistryDateOnly(item.expiry_date),
|
||||
projectName: item.project ? `${item.project.project_no} · ${item.project.name}` : "",
|
||||
ownerName: item.owner?.name ?? "",
|
||||
confidentialityLevel: confidentialityLevelLabel(item.confidentiality_level),
|
||||
});
|
||||
}
|
||||
|
||||
return workbook.xlsx.writeBuffer();
|
||||
}
|
||||
|
||||
async function* streamReimbursementsCsv(prisma, where, limit) {
|
||||
yield "\ufeff";
|
||||
yield csvRow([
|
||||
@@ -952,6 +1145,63 @@ async function buildPresenceHistoryXlsx(items) {
|
||||
}
|
||||
|
||||
async function exportsRoutes(fastify) {
|
||||
fastify.post(
|
||||
"/exports/contracts-registry",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
},
|
||||
async (request, reply) => {
|
||||
await ensureContractsRegistryExportEnabled(fastify, request);
|
||||
const parsedBody = parseBody(CONTRACT_REGISTRY_EXPORT_BODY_SCHEMA, request.body);
|
||||
const format = parsedBody.format ?? "csv";
|
||||
const filters = parseContractRegistryFilters({
|
||||
projectId: parsedBody.projectId,
|
||||
status: parsedBody.status,
|
||||
contractType: parsedBody.contractType,
|
||||
counterpartyName: parsedBody.counterpartyName,
|
||||
expiryDateFrom: parsedBody.expiryDateFrom,
|
||||
expiryDateTo: parsedBody.expiryDateTo,
|
||||
});
|
||||
const where = buildContractRegistryWhere({
|
||||
filters,
|
||||
employee: request.employee,
|
||||
hasPermission: fastify.hasPermission,
|
||||
timeZone: fastify.config.appTimezone,
|
||||
});
|
||||
const matchedTotal = await fastify.prisma.contractRegistry.count({ where });
|
||||
|
||||
await fastify.prisma.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "EXPORT_CONTRACTS_REGISTRY",
|
||||
targetType: "export",
|
||||
extra: {
|
||||
format,
|
||||
projectId: filters.projectId ?? null,
|
||||
status: filters.status ?? null,
|
||||
contractType: filters.contractType ?? null,
|
||||
counterpartyName: filters.counterpartyName ?? null,
|
||||
expiryDateFrom: filters.expiryDateFrom ?? null,
|
||||
expiryDateTo: filters.expiryDateTo ?? null,
|
||||
matchedTotal,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const filename = exportFilename("contracts-registry", format);
|
||||
const today = resolveContractRegistryToday(fastify.config.appTimezone);
|
||||
setExportHeaders(reply, format, filename);
|
||||
|
||||
if (format === "xlsx") {
|
||||
const buffer = await buildContractsRegistryXlsx(fastify.prisma, where, today);
|
||||
return reply.send(Buffer.from(buffer));
|
||||
}
|
||||
|
||||
const stream = Readable.from(streamContractsRegistryCsv(fastify.prisma, where, today));
|
||||
return reply.send(stream);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get(
|
||||
"/exports/employees",
|
||||
{
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
const { z } = require("zod");
|
||||
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { currentDateString, parseDateOnlyString } = require("../utils/date");
|
||||
|
||||
const CONTRACT_REGISTRY_TYPE_VALUES = ["purchase", "sales", "service", "framework", "other"];
|
||||
const CONTRACT_REGISTRY_PERSISTED_STATUS_VALUES = ["draft", "active", "archived"];
|
||||
const CONTRACT_REGISTRY_EFFECTIVE_STATUS_VALUES = [...CONTRACT_REGISTRY_PERSISTED_STATUS_VALUES, "expired"];
|
||||
const DATE_ONLY_SCHEMA = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
|
||||
const CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA = z
|
||||
.object({
|
||||
projectId: z.string().uuid().optional(),
|
||||
status: z.enum(CONTRACT_REGISTRY_EFFECTIVE_STATUS_VALUES).optional(),
|
||||
contractType: z.enum(CONTRACT_REGISTRY_TYPE_VALUES).optional(),
|
||||
counterpartyName: z.string().trim().max(200).optional(),
|
||||
expiryDateFrom: DATE_ONLY_SCHEMA.optional(),
|
||||
expiryDateTo: DATE_ONLY_SCHEMA.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const CONTRACT_REGISTRY_EXPIRING_QUERY_SCHEMA = z
|
||||
.object({
|
||||
days: z.coerce.number().int().min(1).max(365).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
function buildContractRegistryValidationError(details, statusCode = 400) {
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
function parseContractRegistryFilters(input) {
|
||||
const parsed = CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA.safeParse(input ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildContractRegistryValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
const filters = {
|
||||
...parsed.data,
|
||||
counterpartyName: parsed.data.counterpartyName?.trim() || undefined,
|
||||
};
|
||||
|
||||
if (filters.expiryDateFrom && filters.expiryDateTo) {
|
||||
const start = parseDateOnlyString(filters.expiryDateFrom);
|
||||
const end = parseDateOnlyString(filters.expiryDateTo);
|
||||
if (start > end) {
|
||||
throw buildContractRegistryValidationError({
|
||||
expiryDateTo: "must_be_after_or_equal_expiryDateFrom",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return filters;
|
||||
}
|
||||
|
||||
function parseContractRegistryExpiringQuery(input) {
|
||||
const parsed = CONTRACT_REGISTRY_EXPIRING_QUERY_SCHEMA.safeParse(input ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildContractRegistryValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
return {
|
||||
days: parsed.data.days ?? 30,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveContractRegistryToday(timeZone) {
|
||||
return parseDateOnlyString(currentDateString(timeZone ?? "Asia/Shanghai"));
|
||||
}
|
||||
|
||||
function addUtcDays(dateValue, days) {
|
||||
const next = new Date(dateValue.getTime());
|
||||
next.setUTCDate(next.getUTCDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
function canManageContractRegistry(hasPermission, employee) {
|
||||
return (
|
||||
hasPermission(employee, "project.manage") ||
|
||||
hasPermission(employee, "project.view_all") ||
|
||||
hasPermission(employee, "system.settings")
|
||||
);
|
||||
}
|
||||
|
||||
function buildContractRegistryScopeWhere({ employee, hasPermission }) {
|
||||
if (canManageContractRegistry(hasPermission, employee)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
OR: [
|
||||
{ owner_employee_id: employee.id },
|
||||
{ project: { owner_employee_id: employee.id } },
|
||||
{ project: { manager_employee_id: employee.id } },
|
||||
{ project: { members: { some: { employee_id: employee.id, left_at: null } } } },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function buildEffectiveStatusWhere(status, today) {
|
||||
if (!status) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (status === "draft") {
|
||||
return { status: "draft" };
|
||||
}
|
||||
|
||||
if (status === "archived") {
|
||||
return { status: "archived" };
|
||||
}
|
||||
|
||||
if (status === "expired") {
|
||||
return {
|
||||
status: "active",
|
||||
expiry_date: { lt: today },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: "active",
|
||||
OR: [{ expiry_date: null }, { expiry_date: { gte: today } }],
|
||||
};
|
||||
}
|
||||
|
||||
function buildContractRegistryWhere({ filters, employee, hasPermission, timeZone }) {
|
||||
const today = resolveContractRegistryToday(timeZone);
|
||||
const conditions = [];
|
||||
const scopeWhere = buildContractRegistryScopeWhere({ employee, hasPermission });
|
||||
if (Object.keys(scopeWhere).length) {
|
||||
conditions.push(scopeWhere);
|
||||
}
|
||||
|
||||
if (filters.projectId) {
|
||||
conditions.push({ project_id: filters.projectId });
|
||||
}
|
||||
if (filters.contractType) {
|
||||
conditions.push({ contract_type: filters.contractType });
|
||||
}
|
||||
if (filters.counterpartyName) {
|
||||
conditions.push({
|
||||
counterparty_name: {
|
||||
contains: filters.counterpartyName,
|
||||
mode: "insensitive",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (filters.expiryDateFrom || filters.expiryDateTo) {
|
||||
conditions.push({
|
||||
expiry_date: {
|
||||
...(filters.expiryDateFrom ? { gte: parseDateOnlyString(filters.expiryDateFrom) } : {}),
|
||||
...(filters.expiryDateTo ? { lte: parseDateOnlyString(filters.expiryDateTo) } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const statusWhere = buildEffectiveStatusWhere(filters.status, today);
|
||||
if (statusWhere) {
|
||||
conditions.push(statusWhere);
|
||||
}
|
||||
|
||||
return conditions.length ? { AND: conditions } : {};
|
||||
}
|
||||
|
||||
function buildContractRegistryExpiringWhere({ employee, hasPermission, timeZone, days }) {
|
||||
const today = resolveContractRegistryToday(timeZone);
|
||||
const conditions = [];
|
||||
const scopeWhere = buildContractRegistryScopeWhere({ employee, hasPermission });
|
||||
if (Object.keys(scopeWhere).length) {
|
||||
conditions.push(scopeWhere);
|
||||
}
|
||||
|
||||
conditions.push({ status: "active" });
|
||||
conditions.push({
|
||||
expiry_date: {
|
||||
gte: today,
|
||||
lte: addUtcDays(today, days),
|
||||
},
|
||||
});
|
||||
|
||||
return { AND: conditions };
|
||||
}
|
||||
|
||||
function resolveContractRegistryEffectiveStatus(item, todayOrTimeZone) {
|
||||
const today = todayOrTimeZone instanceof Date ? todayOrTimeZone : resolveContractRegistryToday(todayOrTimeZone);
|
||||
if (!item || item.status !== "active" || !item.expiry_date) {
|
||||
return item?.status ?? "draft";
|
||||
}
|
||||
return item.expiry_date < today ? "expired" : item.status;
|
||||
}
|
||||
|
||||
function formatContractRegistryDateOnly(value) {
|
||||
return value?.toISOString?.()?.slice(0, 10) ?? null;
|
||||
}
|
||||
|
||||
function formatContractRegistryAmount(value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
return value.toFixed(2);
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value.toFixed === "function") {
|
||||
return value.toFixed(2);
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CONTRACT_REGISTRY_EFFECTIVE_STATUS_VALUES,
|
||||
CONTRACT_REGISTRY_EXPIRING_QUERY_SCHEMA,
|
||||
CONTRACT_REGISTRY_FILTER_INPUT_SCHEMA,
|
||||
CONTRACT_REGISTRY_PERSISTED_STATUS_VALUES,
|
||||
CONTRACT_REGISTRY_TYPE_VALUES,
|
||||
buildContractRegistryExpiringWhere,
|
||||
buildContractRegistryValidationError,
|
||||
buildContractRegistryWhere,
|
||||
canManageContractRegistry,
|
||||
formatContractRegistryAmount,
|
||||
formatContractRegistryDateOnly,
|
||||
parseContractRegistryExpiringQuery,
|
||||
parseContractRegistryFilters,
|
||||
resolveContractRegistryEffectiveStatus,
|
||||
resolveContractRegistryToday,
|
||||
};
|
||||
@@ -0,0 +1,453 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const contractsRegistryRoutes = require("../../../src/routes/contractsRegistry");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
const { currentDateString, parseDateOnlyString } = require("../../../src/utils/date");
|
||||
|
||||
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
const PROJECT_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const OWNER_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const MANAGER_ID = "33333333-3333-4333-8333-333333333333";
|
||||
const MEMBER_ID = "44444444-4444-4444-8444-444444444444";
|
||||
const DEPARTMENT_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||
|
||||
function buildFeatureFlagRecord(flagKey) {
|
||||
return {
|
||||
id: `flag-${flagKey}`,
|
||||
flag_key: flagKey,
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "unit-test",
|
||||
version: 1,
|
||||
created_at: new Date("2026-04-04T08:00:00.000Z"),
|
||||
created_by: null,
|
||||
updated_at: new Date("2026-04-04T08:00:00.000Z"),
|
||||
updated_by: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildContractRow(overrides = {}) {
|
||||
return {
|
||||
id: "55555555-5555-4555-8555-555555555551",
|
||||
contract_no: "HT-2026-001",
|
||||
project_id: PROJECT_ID,
|
||||
contract_type: "service",
|
||||
counterparty_name: "测试客户",
|
||||
summary: "合同摘要",
|
||||
amount: "100000.00",
|
||||
currency: "CNY",
|
||||
signed_date: new Date("2026-03-01T00:00:00.000Z"),
|
||||
effective_date: new Date("2026-03-05T00:00:00.000Z"),
|
||||
expiry_date: new Date("2026-03-31T00:00:00.000Z"),
|
||||
confidentiality_level: "internal",
|
||||
archive_location: "/archive/contracts/001",
|
||||
offline_archive_no: "OFF-001",
|
||||
owner_employee_id: OWNER_ID,
|
||||
status: "active",
|
||||
created_at: new Date("2026-03-01T08:00:00.000Z"),
|
||||
updated_at: new Date("2026-04-01T08:00:00.000Z"),
|
||||
owner: {
|
||||
id: OWNER_ID,
|
||||
employee_no: "E001",
|
||||
name: "Owner",
|
||||
},
|
||||
project: {
|
||||
id: PROJECT_ID,
|
||||
project_no: "PRJ-001",
|
||||
name: "试点项目",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function mapSelectedRow(row, select) {
|
||||
if (!select) {
|
||||
return row;
|
||||
}
|
||||
|
||||
return Object.entries(select).reduce((result, [key, enabled]) => {
|
||||
if (enabled === true) {
|
||||
result[key] = row[key];
|
||||
}
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function cloneRow(row) {
|
||||
return {
|
||||
...row,
|
||||
owner: row.owner ? { ...row.owner } : null,
|
||||
project: row.project ? { ...row.project } : null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildStatefulPrisma(initialContracts) {
|
||||
const state = {
|
||||
contracts: initialContracts.map((item) => cloneRow(item)),
|
||||
audits: [],
|
||||
};
|
||||
|
||||
const auditCreate = vi.fn(async ({ data }) => {
|
||||
state.audits.push(data);
|
||||
return data;
|
||||
});
|
||||
|
||||
const contractRegistry = {
|
||||
findMany: vi.fn(async ({ where, select, include }) => {
|
||||
let rows = [...state.contracts];
|
||||
if (where?.contract_no?.startsWith) {
|
||||
rows = rows.filter((item) => item.contract_no.startsWith(where.contract_no.startsWith));
|
||||
}
|
||||
|
||||
if (select) {
|
||||
return rows.map((item) => mapSelectedRow(item, select));
|
||||
}
|
||||
|
||||
if (include) {
|
||||
return rows.map((item) => cloneRow(item));
|
||||
}
|
||||
|
||||
return rows.map((item) => cloneRow(item));
|
||||
}),
|
||||
findUnique: vi.fn(async ({ where, select, include }) => {
|
||||
const row = state.contracts.find((item) => item.id === where.id);
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
if (select) {
|
||||
return mapSelectedRow(row, select);
|
||||
}
|
||||
if (include) {
|
||||
return cloneRow(row);
|
||||
}
|
||||
return cloneRow(row);
|
||||
}),
|
||||
create: vi.fn(async ({ data, include }) => {
|
||||
const created = buildContractRow({
|
||||
id: `66666666-6666-4666-8666-${String(state.contracts.length + 1).padStart(12, "0")}`,
|
||||
contract_no: data.contract_no,
|
||||
project_id: data.project_id ?? null,
|
||||
contract_type: data.contract_type,
|
||||
counterparty_name: data.counterparty_name,
|
||||
summary: data.summary,
|
||||
amount: data.amount ?? null,
|
||||
currency: data.currency,
|
||||
signed_date: data.signed_date,
|
||||
effective_date: data.effective_date,
|
||||
expiry_date: data.expiry_date,
|
||||
confidentiality_level: data.confidentiality_level,
|
||||
archive_location: data.archive_location,
|
||||
offline_archive_no: data.offline_archive_no,
|
||||
owner_employee_id: data.owner_employee_id,
|
||||
status: data.status,
|
||||
});
|
||||
state.contracts.push(created);
|
||||
return include ? cloneRow(created) : created;
|
||||
}),
|
||||
update: vi.fn(async ({ where, data, include }) => {
|
||||
const index = state.contracts.findIndex((item) => item.id === where.id);
|
||||
if (index < 0) {
|
||||
return null;
|
||||
}
|
||||
state.contracts[index] = {
|
||||
...state.contracts[index],
|
||||
...data,
|
||||
updated_at: new Date("2026-04-04T09:30:00.000Z"),
|
||||
};
|
||||
return include ? cloneRow(state.contracts[index]) : state.contracts[index];
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
prisma: {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockImplementation(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
|
||||
},
|
||||
auditLog: {
|
||||
create: auditCreate,
|
||||
},
|
||||
contractRegistry,
|
||||
$transaction: async (callback) =>
|
||||
callback({
|
||||
auditLog: { create: auditCreate },
|
||||
contractRegistry,
|
||||
}),
|
||||
},
|
||||
auditCreate,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const actor = options.actor ?? {
|
||||
id: ACTOR_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
permissionCodes: ["project.manage"],
|
||||
};
|
||||
const prisma =
|
||||
options.prisma ??
|
||||
(() => {
|
||||
const fallback = {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockImplementation(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
contractRegistry: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findUnique: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn().mockResolvedValue(buildContractRow()),
|
||||
update: vi.fn().mockResolvedValue(buildContractRow()),
|
||||
},
|
||||
};
|
||||
fallback.$transaction = async (callback) => callback(fallback);
|
||||
return fallback;
|
||||
})();
|
||||
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||
const permissionCodes = employee.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
projectLinkingEnabled: true,
|
||||
});
|
||||
app.decorate("prisma", prisma);
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof AppError) {
|
||||
return reply.status(error.statusCode).send({
|
||||
requestId: request.id,
|
||||
error: { code: error.code, message: error.message, details: error.details ?? {} },
|
||||
});
|
||||
}
|
||||
return reply.status(500).send({
|
||||
requestId: request.id,
|
||||
error: { code: "SYS_001", message: "服务器内部错误", details: {} },
|
||||
});
|
||||
});
|
||||
|
||||
await app.register(contractsRegistryRoutes, { prefix: "/api" });
|
||||
return { app, prisma };
|
||||
}
|
||||
|
||||
describe("contracts registry routes", () => {
|
||||
it("lists contracts with expired filtering and computed status", async () => {
|
||||
const contractFindMany = vi.fn().mockResolvedValue([buildContractRow()]);
|
||||
const { app } = await buildApp({
|
||||
prisma: (() => {
|
||||
const prisma = {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockImplementation(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
|
||||
},
|
||||
auditLog: { create: vi.fn().mockResolvedValue({}) },
|
||||
contractRegistry: {
|
||||
findMany: contractFindMany,
|
||||
findUnique: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
};
|
||||
prisma.$transaction = async (callback) => callback(prisma);
|
||||
return prisma;
|
||||
})(),
|
||||
});
|
||||
|
||||
const today = parseDateOnlyString(currentDateString("Asia/Shanghai"));
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/contracts-registry?status=expired&contractType=service&counterpartyName=%E6%B5%8B%E8%AF%95&expiryDateFrom=2026-03-01&expiryDateTo=2026-03-31`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const payload = response.json();
|
||||
expect(payload.data.items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
status: "expired",
|
||||
persistedStatus: "active",
|
||||
contractType: "service",
|
||||
amount: "100000.00",
|
||||
}),
|
||||
);
|
||||
expect(contractFindMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
AND: expect.arrayContaining([
|
||||
expect.objectContaining({ status: "active", expiry_date: { lt: today } }),
|
||||
expect.objectContaining({ contract_type: "service" }),
|
||||
expect.objectContaining({
|
||||
counterparty_name: expect.objectContaining({ contains: "测试", mode: "insensitive" }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
expiry_date: expect.objectContaining({
|
||||
gte: new Date("2026-03-01T00:00:00.000Z"),
|
||||
lte: new Date("2026-03-31T00:00:00.000Z"),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects invalid expiry date range", async () => {
|
||||
const { app } = await buildApp();
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/contracts-registry?expiryDateFrom=2026-04-10&expiryDateTo=2026-04-01",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().error).toEqual(
|
||||
expect.objectContaining({
|
||||
code: "VALID_001",
|
||||
details: expect.objectContaining({
|
||||
expiryDateTo: "must_be_after_or_equal_expiryDateFrom",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("returns expiring contracts within the default window", async () => {
|
||||
const contractFindMany = vi.fn().mockResolvedValue([
|
||||
buildContractRow({
|
||||
id: "contract-2",
|
||||
contract_no: "HT-2026-002",
|
||||
expiry_date: new Date("2026-04-10T00:00:00.000Z"),
|
||||
}),
|
||||
]);
|
||||
const { app } = await buildApp({
|
||||
prisma: (() => {
|
||||
const prisma = {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockImplementation(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
|
||||
},
|
||||
auditLog: { create: vi.fn().mockResolvedValue({}) },
|
||||
contractRegistry: {
|
||||
findMany: contractFindMany,
|
||||
findUnique: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
};
|
||||
prisma.$transaction = async (callback) => callback(prisma);
|
||||
return prisma;
|
||||
})(),
|
||||
});
|
||||
|
||||
const today = parseDateOnlyString(currentDateString("Asia/Shanghai"));
|
||||
const end = new Date(today.getTime());
|
||||
end.setUTCDate(end.getUTCDate() + 30);
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/contracts-registry/expiring",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data).toEqual(
|
||||
expect.objectContaining({
|
||||
days: 30,
|
||||
total: 1,
|
||||
}),
|
||||
);
|
||||
expect(contractFindMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
AND: expect.arrayContaining([
|
||||
{ status: "active" },
|
||||
expect.objectContaining({
|
||||
expiry_date: expect.objectContaining({
|
||||
gte: today,
|
||||
lte: end,
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("renews an active contract into the next draft revision and archives the source", async () => {
|
||||
const stateful = buildStatefulPrisma([
|
||||
buildContractRow({
|
||||
id: "55555555-5555-4555-8555-555555555551",
|
||||
contract_no: "HT-2026-001",
|
||||
status: "active",
|
||||
}),
|
||||
buildContractRow({
|
||||
id: "55555555-5555-4555-8555-555555555552",
|
||||
contract_no: "HT-2026-001-R1",
|
||||
status: "archived",
|
||||
}),
|
||||
]);
|
||||
const { app } = await buildApp({ prisma: stateful.prisma });
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/contracts-registry/55555555-5555-4555-8555-555555555551/renew",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data).toEqual(
|
||||
expect.objectContaining({
|
||||
item: expect.objectContaining({
|
||||
contractNo: "HT-2026-001-R2",
|
||||
status: "draft",
|
||||
persistedStatus: "draft",
|
||||
}),
|
||||
sourceItem: expect.objectContaining({
|
||||
contractNo: "HT-2026-001",
|
||||
status: "archived",
|
||||
persistedStatus: "archived",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(stateful.state.contracts.find((item) => item.id === "55555555-5555-4555-8555-555555555551")?.status).toBe("archived");
|
||||
expect(
|
||||
stateful.state.contracts.some((item) => item.contract_no === "HT-2026-001-R2" && item.status === "draft"),
|
||||
).toBe(true);
|
||||
expect(stateful.state.audits.map((item) => item.action)).toEqual(
|
||||
expect.arrayContaining(["CONTRACT_REGISTRY_RENEWED", "CONTRACT_REGISTRY_STATUS_CHANGED"]),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects renewing a draft contract", async () => {
|
||||
const stateful = buildStatefulPrisma([
|
||||
buildContractRow({
|
||||
id: "55555555-5555-4555-8555-555555555553",
|
||||
contract_no: "HT-2026-003",
|
||||
status: "draft",
|
||||
}),
|
||||
]);
|
||||
const { app } = await buildApp({ prisma: stateful.prisma });
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/contracts-registry/55555555-5555-4555-8555-555555555553/renew",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().error).toEqual(
|
||||
expect.objectContaining({
|
||||
code: "VALID_001",
|
||||
details: expect.objectContaining({ status: "renew_not_allowed" }),
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const exportsRoutes = require("../../../src/routes/exports");
|
||||
|
||||
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
const PROJECT_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const OWNER_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const DEPARTMENT_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||
|
||||
function buildFeatureFlagRecord(flagKey) {
|
||||
return {
|
||||
id: `flag-${flagKey}`,
|
||||
flag_key: flagKey,
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "unit-test",
|
||||
version: 1,
|
||||
created_at: new Date("2026-04-04T08:00:00.000Z"),
|
||||
created_by: null,
|
||||
updated_at: new Date("2026-04-04T08:00:00.000Z"),
|
||||
updated_by: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildContractRow(overrides = {}) {
|
||||
return {
|
||||
id: "contract-1",
|
||||
contract_no: "HT-2026-001",
|
||||
project_id: PROJECT_ID,
|
||||
contract_type: "service",
|
||||
counterparty_name: "测试客户",
|
||||
summary: "合同摘要",
|
||||
amount: "88000.00",
|
||||
currency: "CNY",
|
||||
signed_date: new Date("2026-03-01T00:00:00.000Z"),
|
||||
effective_date: new Date("2026-03-05T00:00:00.000Z"),
|
||||
expiry_date: new Date("2026-03-31T00:00:00.000Z"),
|
||||
confidentiality_level: "internal",
|
||||
archive_location: "/archive/contracts/001",
|
||||
offline_archive_no: "OFF-001",
|
||||
owner_employee_id: OWNER_ID,
|
||||
status: "active",
|
||||
created_at: new Date("2026-03-01T08:00:00.000Z"),
|
||||
updated_at: new Date("2026-04-01T08:00:00.000Z"),
|
||||
owner: {
|
||||
name: "Owner",
|
||||
},
|
||||
project: {
|
||||
project_no: "PRJ-001",
|
||||
name: "试点项目",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const actor = options.actor ?? {
|
||||
id: ACTOR_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
permissionCodes: ["project.manage"],
|
||||
};
|
||||
const count = options.count ?? vi.fn().mockResolvedValue(1);
|
||||
const findMany =
|
||||
options.findMany ??
|
||||
vi.fn().mockImplementation(async ({ where }) => {
|
||||
if (where?.OR) {
|
||||
return [];
|
||||
}
|
||||
return [buildContractRow()];
|
||||
});
|
||||
const auditCreate = options.auditCreate ?? vi.fn().mockResolvedValue({});
|
||||
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = actor;
|
||||
const permissionCodes = actor.permissionCodes ?? [];
|
||||
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
|
||||
throw new Error(`unexpected permission check: ${permissionCode}`);
|
||||
}
|
||||
});
|
||||
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||
const permissionCodes = employee.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
projectLinkingEnabled: true,
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockImplementation(async ({ where }) => buildFeatureFlagRecord(where.flag_key)),
|
||||
},
|
||||
auditLog: {
|
||||
create: auditCreate,
|
||||
},
|
||||
contractRegistry: {
|
||||
count,
|
||||
findMany,
|
||||
},
|
||||
});
|
||||
|
||||
await app.register(exportsRoutes, { prefix: "/api" });
|
||||
return { app, count, findMany, auditCreate };
|
||||
}
|
||||
|
||||
describe("contracts registry export route", () => {
|
||||
it("exports filtered contracts registry as csv", async () => {
|
||||
const { app, count, findMany, auditCreate } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/exports/contracts-registry",
|
||||
payload: {
|
||||
format: "csv",
|
||||
status: "expired",
|
||||
contractType: "service",
|
||||
counterpartyName: "测试",
|
||||
expiryDateFrom: "2026-03-01",
|
||||
expiryDateTo: "2026-03-31",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.headers["content-type"]).toContain("text/csv");
|
||||
expect(response.headers["content-disposition"]).toContain("contracts-registry-");
|
||||
expect(response.body).toContain("合同编号");
|
||||
expect(response.body).toContain("服务合同");
|
||||
expect(response.body).toContain("已过期");
|
||||
expect(count).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
AND: expect.arrayContaining([
|
||||
expect.objectContaining({ contract_type: "service" }),
|
||||
expect.objectContaining({
|
||||
counterparty_name: expect.objectContaining({ contains: "测试", mode: "insensitive" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(findMany).toHaveBeenCalled();
|
||||
expect(auditCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
action: "EXPORT_CONTRACTS_REGISTRY",
|
||||
extra: expect.objectContaining({
|
||||
format: "csv",
|
||||
status: "expired",
|
||||
contractType: "service",
|
||||
counterpartyName: "测试",
|
||||
matchedTotal: 1,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("exports contracts registry as xlsx", async () => {
|
||||
const { app, auditCreate } = await buildApp({
|
||||
count: vi.fn().mockResolvedValue(1),
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
buildContractRow({
|
||||
id: "contract-2",
|
||||
contract_no: "HT-2026-002",
|
||||
contract_type: "purchase",
|
||||
status: "archived",
|
||||
expiry_date: new Date("2026-04-15T00:00:00.000Z"),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/exports/contracts-registry",
|
||||
payload: {
|
||||
format: "xlsx",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.headers["content-type"]).toContain(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
);
|
||||
expect(response.headers["content-disposition"]).toContain("contracts-registry-");
|
||||
expect(Buffer.from(response.rawPayload).length).toBeGreaterThan(0);
|
||||
expect(auditCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
action: "EXPORT_CONTRACTS_REGISTRY",
|
||||
extra: expect.objectContaining({
|
||||
format: "xlsx",
|
||||
matchedTotal: 1,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户