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

这个提交包含在:
2026-04-05 11:21:15 +08:00
父节点 a960c9b57f
当前提交 ff0a677bf3
共修改 10 个文件,包含 2214 行新增和 168 行删除
+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,
};