R111/A3-A6 强化发票查重和状态治理
这个提交包含在:
+222
-17
@@ -15,6 +15,11 @@ const { registerInvoicePoolReadRoutes } = require("./invoicePool/read");
|
||||
const { normalizeInvoiceResponse } = require("./invoicePool/shared/mappers");
|
||||
const { buildInvoiceDetailSelect } = require("./invoicePool/shared/selects");
|
||||
const { writeBuffer } = require("../services/storage");
|
||||
const {
|
||||
mapInvoiceUnavailableReason,
|
||||
resolveInvoiceDedupBlocker,
|
||||
resolveUploadDedupDecision,
|
||||
} = require("../services/invoiceGovernance");
|
||||
|
||||
const MIME_ALLOWLIST = new Set([
|
||||
"application/pdf",
|
||||
@@ -193,6 +198,145 @@ function parseDateOnlyString(value) {
|
||||
return new Date(`${trimmed}T00:00:00.000Z`);
|
||||
}
|
||||
|
||||
async function resolveDefaultExpenseType(tx) {
|
||||
const preferred = await tx.expenseType.findFirst({
|
||||
where: {
|
||||
enabled: true,
|
||||
code: { in: ["other_misc", "office_supplies", "business_client_meal"] },
|
||||
},
|
||||
orderBy: { sort_order: "asc" },
|
||||
select: { id: true },
|
||||
});
|
||||
if (preferred) {
|
||||
return preferred;
|
||||
}
|
||||
|
||||
return tx.expenseType.findFirst({
|
||||
where: { enabled: true },
|
||||
orderBy: { sort_order: "asc" },
|
||||
select: { id: true },
|
||||
});
|
||||
}
|
||||
|
||||
function toDateOnlyFromDate(value) {
|
||||
if (value instanceof Date) {
|
||||
return new Date(`${value.toISOString().slice(0, 10)}T00:00:00.000Z`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildAutoItemDescription(invoice) {
|
||||
const sellerName = String(invoice.seller_name ?? "").trim();
|
||||
if (sellerName) {
|
||||
return `发票自动生成:${sellerName}`;
|
||||
}
|
||||
|
||||
const originalName = String(invoice.original_name ?? "").trim();
|
||||
if (originalName) {
|
||||
return `发票自动生成:${originalName}`.slice(0, 500);
|
||||
}
|
||||
|
||||
return "发票自动生成明细";
|
||||
}
|
||||
|
||||
async function recomputeReimbursementTotal(tx, reimbursementId, actorId) {
|
||||
const aggregate = await tx.reimbursementItem.aggregate({
|
||||
where: { reimbursement_id: reimbursementId },
|
||||
_sum: { amount: true },
|
||||
});
|
||||
|
||||
const nextTotal = aggregate._sum.amount ?? "0";
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: reimbursementId },
|
||||
data: {
|
||||
total_amount: nextTotal,
|
||||
updated_by: actorId,
|
||||
},
|
||||
});
|
||||
|
||||
return nextTotal;
|
||||
}
|
||||
|
||||
async function resolveInvoiceLinkedItem(tx, { reimbursementId, reimbursementDate, invoice, linkedItemId, actorId }) {
|
||||
if (linkedItemId) {
|
||||
const linkedItem = await tx.reimbursementItem.findFirst({
|
||||
where: {
|
||||
id: linkedItemId,
|
||||
reimbursement_id: reimbursementId,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!linkedItem) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { linkedItemId: "item_not_in_reimbursement" },
|
||||
});
|
||||
}
|
||||
return { linkedItemId: linkedItem.id, createdItem: false };
|
||||
}
|
||||
|
||||
const items = await tx.reimbursementItem.findMany({
|
||||
where: { reimbursement_id: reimbursementId },
|
||||
orderBy: [{ created_at: "asc" }, { id: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
amount: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (items.length === 1) {
|
||||
return { linkedItemId: items[0].id, createdItem: false };
|
||||
}
|
||||
|
||||
if (items.length > 1 && invoice.total_amount != null) {
|
||||
const invoiceAmount = toMoneyString(invoice.total_amount);
|
||||
const matched = items.filter((item) => toMoneyString(item.amount) === invoiceAmount);
|
||||
if (matched.length === 1) {
|
||||
return { linkedItemId: matched[0].id, createdItem: false };
|
||||
}
|
||||
}
|
||||
|
||||
if (invoice.total_amount == null) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { invoice: "missing_total_amount_for_auto_item" },
|
||||
});
|
||||
}
|
||||
|
||||
const expenseType = await resolveDefaultExpenseType(tx);
|
||||
if (!expenseType) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { expenseTypeId: "missing_enabled_expense_type" },
|
||||
});
|
||||
}
|
||||
|
||||
const expenseDate =
|
||||
toDateOnlyFromDate(invoice.invoice_date) ??
|
||||
toDateOnlyFromDate(reimbursementDate) ??
|
||||
new Date();
|
||||
const created = await tx.reimbursementItem.create({
|
||||
data: {
|
||||
reimbursement_id: reimbursementId,
|
||||
expense_type_id: expenseType.id,
|
||||
expense_date: expenseDate,
|
||||
amount: toMoneyString(invoice.total_amount),
|
||||
description: buildAutoItemDescription(invoice),
|
||||
created_by: actorId,
|
||||
updated_by: actorId,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
return { linkedItemId: created.id, createdItem: true };
|
||||
}
|
||||
|
||||
async function invoicePoolRoutes(fastify) {
|
||||
|
||||
registerInvoicePoolReadRoutes(fastify);
|
||||
@@ -346,6 +490,28 @@ async function invoicePoolRoutes(fastify) {
|
||||
}
|
||||
|
||||
const fileSha256 = sha256Hex(fileBuffer);
|
||||
const uploadDedupDecision = await fastify.prisma.$transaction((tx) =>
|
||||
resolveUploadDedupDecision(tx, {
|
||||
fileSha256,
|
||||
ownerEmployeeId,
|
||||
}),
|
||||
);
|
||||
|
||||
if (uploadDedupDecision.action !== "create") {
|
||||
const message = mapInvoiceUnavailableReason(uploadDedupDecision.reason);
|
||||
return sendData(reply, request, {
|
||||
invoicePoolId:
|
||||
uploadDedupDecision.action === "reuse_existing"
|
||||
? uploadDedupDecision.invoice.id
|
||||
: null,
|
||||
status: uploadDedupDecision.invoice?.status ?? "ocr_failed",
|
||||
fileSha256,
|
||||
uploadAction: uploadDedupDecision.action,
|
||||
unavailableReason: uploadDedupDecision.reason,
|
||||
unavailableMessage: message,
|
||||
});
|
||||
}
|
||||
|
||||
const datePrefix = compactDateString(fastify.config.appTimezone);
|
||||
const extension = path.extname(fileName ?? "").toLowerCase();
|
||||
const objectKey = path.posix.join(datePrefix, `${crypto.randomUUID()}${extension}`);
|
||||
@@ -1296,8 +1462,20 @@ async function invoicePoolRoutes(fastify) {
|
||||
where: { id: invoiceId },
|
||||
select: {
|
||||
status: true,
|
||||
owner_employee_id: true,
|
||||
uploaded_by_employee_id: true,
|
||||
file_sha256: true,
|
||||
invoice_code: true,
|
||||
invoice_number: true,
|
||||
invoice_date: true,
|
||||
seller_name: true,
|
||||
original_name: true,
|
||||
total_amount: true,
|
||||
linked_reimbursement_id: true,
|
||||
linked_item_id: true,
|
||||
travel_order_id: true,
|
||||
archived_reason: true,
|
||||
is_duplicate_override: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1326,6 +1504,30 @@ async function invoicePoolRoutes(fastify) {
|
||||
});
|
||||
}
|
||||
|
||||
if (!invoice.is_duplicate_override) {
|
||||
const duplicateBlocker = await resolveInvoiceDedupBlocker(tx, {
|
||||
excludeInvoiceId: invoiceId,
|
||||
fileSha256: invoice.file_sha256,
|
||||
invoiceCode: invoice.invoice_code,
|
||||
invoiceNumber: invoice.invoice_number,
|
||||
ownerEmployeeId: invoice.owner_employee_id,
|
||||
});
|
||||
if (duplicateBlocker) {
|
||||
throw new AppError({
|
||||
code: "VALID_003",
|
||||
message: "发票不能重复添加",
|
||||
statusCode: 409,
|
||||
details: {
|
||||
invoice: duplicateBlocker.reason,
|
||||
message: mapInvoiceUnavailableReason(duplicateBlocker.reason),
|
||||
conflictInvoiceId: duplicateBlocker.conflict.id,
|
||||
conflictFormNumber:
|
||||
duplicateBlocker.conflict.linked_reimbursement?.form_number ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if ("reimbursementId" in parsedBody.data) {
|
||||
if (!fastify.hasPermission(request.employee, "invoice.upload")) {
|
||||
throw new AppError({
|
||||
@@ -1337,7 +1539,7 @@ async function invoicePoolRoutes(fastify) {
|
||||
|
||||
const { reimbursementId, linkedItemId } = parsedBody.data;
|
||||
const reimbursementRows = await tx.$queryRaw`
|
||||
SELECT id, owner_id, submitter_id, status
|
||||
SELECT id, owner_id, submitter_id, status, reimbursement_date
|
||||
FROM "reimbursement_forms"
|
||||
WHERE id = ${reimbursementId}::uuid
|
||||
FOR UPDATE
|
||||
@@ -1372,34 +1574,37 @@ async function invoicePoolRoutes(fastify) {
|
||||
});
|
||||
}
|
||||
|
||||
if (linkedItemId) {
|
||||
const linkedItem = await tx.reimbursementItem.findFirst({
|
||||
where: {
|
||||
id: linkedItemId,
|
||||
reimbursement_id: reimbursementId,
|
||||
},
|
||||
select: { id: true },
|
||||
if (invoice.owner_employee_id !== reimbursement.owner_id) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { invoice: "owner_mismatch" },
|
||||
});
|
||||
if (!linkedItem) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { linkedItemId: "item_not_in_reimbursement" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedLink = await resolveInvoiceLinkedItem(tx, {
|
||||
reimbursementId,
|
||||
reimbursementDate: reimbursement.reimbursement_date,
|
||||
invoice,
|
||||
linkedItemId,
|
||||
actorId: request.employee.id,
|
||||
});
|
||||
|
||||
await tx.invoicePool.update({
|
||||
where: { id: invoiceId },
|
||||
data: {
|
||||
status: "bound",
|
||||
linked_reimbursement_id: reimbursementId,
|
||||
linked_item_id: linkedItemId ?? null,
|
||||
linked_item_id: resolvedLink.linkedItemId,
|
||||
travel_order_id: null,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (resolvedLink.createdItem) {
|
||||
await recomputeReimbursementTotal(tx, reimbursementId, request.employee.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
在新工单中引用
屏蔽一个用户