R49 合同台账增强:金额分类、筛选、到期预警、续约与导出

这个提交包含在:
2026-04-05 11:21:15 +08:00
父节点 a960c9b57f
当前提交 ff0a677bf3
共修改 10 个文件,包含 2214 行新增和 168 行删除
@@ -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");
+47 -1
查看文件
@@ -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
@@ -753,13 +768,34 @@ model Notification {
read_at DateTime?
created_at DateTime @default(now())
recipient Employee @relation(fields: [recipient_employee_id], references: [id], onDelete: Cascade)
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")
+297 -63
查看文件
@@ -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({
contractNo: z.string().trim().min(1).max(80),
projectId: UUID_SCHEMA.nullable().optional(),
counterpartyName: z.string().trim().min(1).max(200),
summary: z.string().trim().min(1).max(4000),
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" });
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());
function buildValidationError(details, statusCode = 400) {
return new AppError({ code: "VALID_001", message: "参数校验失败", statusCode, details });
}
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: STATUS_WRITE_SCHEMA.optional(),
})
.strict();
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) });
});
}
+250
查看文件
@@ -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();
});
});