import type { KyInstance } from "ky"; import { getFormSpecification } from "./api.js"; import { NotFoundError, ValidationError } from "../../core/errors.js"; /** * 单据草稿的派生字段一致性校验。 * * 合思服务端把「金额/币种/发票总额」等派生字段的计算责任交给前端: * 保存接口只做弱校验,甚至允许 CNY/USD 直接相加。CLI 在写入前必须先跑这一层, * 避免把语义错误的表单写回服务端。 */ export interface BillMoney { standard?: string | number; standardStrCode?: string; standardSymbol?: string; standardUnit?: string; standardScale?: number; foreign?: string | number; foreignStrCode?: string; rate?: string | number; [key: string]: unknown; } export interface BillDraftInvoiceRef { invoiceId?: string; taxAmount?: BillMoney; [key: string]: unknown; } export interface BillDraftInvoiceForm { type?: string; invoices?: BillDraftInvoiceRef[]; [key: string]: unknown; } export interface BillDraftDetailForm { amount?: BillMoney; u_发票总金额?: BillMoney; invoice?: string | number; invoiceForm?: BillDraftInvoiceForm; attachments?: unknown[]; detailNo?: number; detailId?: string; detailStatus?: string; consumptionReasons?: string; [key: string]: unknown; } export interface BillDraftDetail { feeTypeForm?: BillDraftDetailForm; feeTypeId?: unknown; specificationId?: unknown; [key: string]: unknown; } export interface BillDraftForm { title?: string; specificationId?: unknown; submitterId?: unknown; expenseDate?: number; expenseDepartment?: unknown; payeeId?: unknown; 法人实体?: unknown; u_最晚付款日期?: number; description?: string; expenseMoney?: BillMoney; payMoney?: BillMoney; writtenOffMoney?: BillMoney; u_发票总金额?: BillMoney; attachments?: unknown[]; details?: BillDraftDetail[]; [key: string]: unknown; } export type ValidationSeverity = "error" | "warning"; export interface ValidationIssue { code: string; severity: ValidationSeverity; field: string; message: string; } export interface BillValidationComponent { field?: string; label?: string; optional?: boolean; maxLength?: number; } export interface ValidateOptions { /** 实际模板字段;未提供时仅检查通用结构与已有金额。 */ components?: BillValidationComponent[]; detailComponents?: BillValidationComponent[][]; /** 金额比较容差,默认 0.005(分位) */ moneyTolerance?: number; /** 外币换算比较容差,默认 0.01 */ rateTolerance?: number; } const DEFAULT_MONEY_TOLERANCE = 0.005; const DEFAULT_RATE_TOLERANCE = 0.01; function toNumber(value: unknown): number | undefined { if (typeof value === "number" && Number.isFinite(value)) return value; if (typeof value === "string" && value.trim() !== "") { const parsed = Number(value.replaceAll(",", "")); if (Number.isFinite(parsed)) return parsed; } return undefined; } function moneyStandard(money: BillMoney | undefined): number | undefined { return money ? toNumber(money.standard) : undefined; } function issue( code: string, field: string, message: string, severity: ValidationSeverity = "error" ): ValidationIssue { return { code, severity, field, message }; } function nearlyEqual(a: number, b: number, tolerance: number): boolean { return Math.abs(a - b) <= tolerance; } /** * 校验单张草稿表单的派生字段一致性与必填项。 * 返回空数组代表可以安全写入。 */ export function validateBillDraft( form: BillDraftForm | undefined, options: ValidateOptions = {} ): ValidationIssue[] { const moneyTolerance = options.moneyTolerance ?? DEFAULT_MONEY_TOLERANCE; const rateTolerance = options.rateTolerance ?? DEFAULT_RATE_TOLERANCE; const issues: ValidationIssue[] = []; if (!form) { return [issue("EMPTY_FORM", "form", "单据表单为空")]; } // 1. 必填表头 const checkComponents = (value: Record, components: BillValidationComponent[], prefix = "") => { for (const component of components) { if (!component.field) continue; const content = value[component.field]; const field = prefix + component.field; if (component.optional === false && (content == null || content === "" || (Array.isArray(content) && content.length === 0))) { issues.push(issue("MISSING_FIELD", field, `缺少必填字段:${component.label || component.field}`)); } if (typeof content === "string" && typeof component.maxLength === "number" && content.length > component.maxLength) { issues.push(issue(component.field === "description" ? "DESCRIPTION_TOO_LONG" : "FIELD_TOO_LONG", field, `字段长度 ${content.length} 超过模板上限 ${component.maxLength}`)); } } }; checkComponents(form, [{ field: "specificationId", optional: false }, ...(options.components ?? [])]); // 2. 描述长度由实际模板的 maxLength 决定,不假设所有模板均为 800。 // 3. 明细数量 const details = Array.isArray(form.details) ? form.details : []; if (details.length === 0) { issues.push(issue("NO_DETAILS", "details", "费用明细为空,至少需要一条明细")); return issues; } // 4. 本位币(以表头报销金额为准) const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode || details.find((detail) => detail.feeTypeForm?.amount?.standardStrCode)?.feeTypeForm?.amount?.standardStrCode; if (form.expenseMoney?.standardStrCode && form.payMoney?.standardStrCode && form.expenseMoney.standardStrCode !== form.payMoney.standardStrCode) { issues.push(issue("CURRENCY_MISMATCH", "payMoney.standardStrCode", "支付金额与报销金额本位币不一致")); } // 5. 逐条明细 const seenDetailNos = new Map(); const seenInvoiceIds = new Map(); let detailAmountSum = 0; let detailInvoiceSum = 0; let hasValidDetailAmounts = true; details.forEach((detail, index) => { const ft = detail.feeTypeForm ?? {}; checkComponents(ft, options.detailComponents?.[index] ?? [], `details[${index}].feeTypeForm.`); const position = index + 1; const label = `明细 #${ft.detailNo ?? position}`; if (ft.detailStatus === "draft") { issues.push( issue( "DETAIL_DRAFT_STATUS", `details[${index}].feeTypeForm.detailStatus`, `${label} 仍处于草稿状态(detailStatus=draft),提交前必须保存该明细` ) ); } if (typeof ft.detailNo === "number") { const previous = seenDetailNos.get(ft.detailNo); if (previous !== undefined) { issues.push( issue( "DUPLICATE_DETAIL_NO", `details[${index}].feeTypeForm.detailNo`, `明细序号 ${ft.detailNo} 重复(第 ${previous + 1} 条与第 ${position} 条)` ) ); } else { seenDetailNos.set(ft.detailNo, index); } } const amount = ft.amount; const standard = moneyStandard(amount); if (standard === undefined) { hasValidDetailAmounts = false; issues.push( issue( "DETAIL_AMOUNT_INVALID", `details[${index}].feeTypeForm.amount`, `${label} 的本位币金额缺失或不是合法数字` ) ); } else { detailAmountSum += standard; if (standard <= 0) { issues.push( issue( "DETAIL_AMOUNT_NOT_POSITIVE", `details[${index}].feeTypeForm.amount.standard`, `${label} 的金额为 ${standard},应大于 0`, "warning" ) ); } if (billCurrency && amount?.standardStrCode && amount.standardStrCode !== billCurrency) { issues.push( issue( "CURRENCY_MISMATCH", `details[${index}].feeTypeForm.amount.standardStrCode`, `${label} 的本位币币种为 ${amount.standardStrCode},与单据本位币 ${billCurrency} 不一致` + `(合思服务端会直接相加不同币种,必须由 CLI 拦截)` ) ); } } // 外币明细:foreign × rate 必须能还原 standard const foreign = toNumber(amount?.foreign); const rate = toNumber(amount?.rate); if (foreign !== undefined && rate !== undefined) { if (rate <= 0) { issues.push( issue( "FOREIGN_RATE_INVALID", `details[${index}].feeTypeForm.amount.rate`, `${label} 的汇率为 ${rate},应大于 0` ) ); } else if (standard !== undefined && !nearlyEqual(standard, foreign * rate, rateTolerance)) { issues.push( issue( "FOREIGN_RATE_MISMATCH", `details[${index}].feeTypeForm.amount`, `${label} 的本位币金额 ${standard} 与外币 ${foreign} × 汇率 ${rate} = ${(foreign * rate).toFixed(2)} 不一致` ) ); } if (!amount?.foreignStrCode) { issues.push( issue( "FOREIGN_FIELDS_INCOMPLETE", `details[${index}].feeTypeForm.amount.foreignStrCode`, `${label} 有外资金额但缺少 foreignStrCode` ) ); } else if (billCurrency && amount.foreignStrCode === billCurrency) { issues.push( issue( "FOREIGN_SAME_CURRENCY", `details[${index}].feeTypeForm.amount`, `${label} 的外币币种与本位币相同(${billCurrency}),不应同时设置外币字段`, "warning" ) ); } } else if (foreign !== undefined || rate !== undefined) { issues.push( issue( "FOREIGN_FIELDS_INCOMPLETE", `details[${index}].feeTypeForm.amount`, `${label} 的外币金额与汇率必须成对出现` ) ); } // 明细发票总额 const detailInvoiceTotal = moneyStandard(ft.u_发票总金额); if (ft.u_发票总金额 !== undefined && detailInvoiceTotal === undefined) { issues.push( issue( "DETAIL_INVOICE_TOTAL_INVALID", `details[${index}].feeTypeForm.u_发票总金额`, `${label} 的发票总金额缺失或不是合法数字` ) ); } else { detailInvoiceSum += detailInvoiceTotal ?? 0; if (billCurrency && ft.u_发票总金额?.standardStrCode && ft.u_发票总金额.standardStrCode !== billCurrency) { issues.push( issue( "INVOICE_CURRENCY_MISMATCH", `details[${index}].feeTypeForm.u_发票总金额.standardStrCode`, `${label} 的发票总金额币种 ${ft.u_发票总金额.standardStrCode} 与单据本位币 ${billCurrency} 不一致` ) ); } } // 发票去重 const invoices = ft.invoiceForm?.invoices ?? []; for (const invoice of invoices) { const invoiceId = typeof invoice.invoiceId === "string" ? invoice.invoiceId : undefined; if (!invoiceId) continue; const previous = seenInvoiceIds.get(invoiceId); if (previous !== undefined) { issues.push( issue( "DUPLICATE_INVOICE", `details[${index}].feeTypeForm.invoiceForm.invoices`, `发票 ${invoiceId} 同时绑定在明细 #${previous + 1} 与 ${label}`, "warning" ) ); } else { seenInvoiceIds.set(invoiceId, index); } } }); // 6. 表头派生金额 const expenseMoney = moneyStandard(form.expenseMoney); if (form.expenseMoney !== undefined && expenseMoney === undefined) { issues.push( issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字") ); } else if (expenseMoney !== undefined && hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) { issues.push( issue( "EXPENSE_TOTAL_MISMATCH", "expenseMoney.standard", `报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致` ) ); } const payMoney = moneyStandard(form.payMoney); if (form.payMoney !== undefined && payMoney === undefined) { issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字")); } else if (payMoney !== undefined && expenseMoney !== undefined) { const writtenOff = moneyStandard(form.writtenOffMoney) ?? 0; const expectedPay = expenseMoney - writtenOff; if (!nearlyEqual(payMoney, expectedPay, moneyTolerance)) { issues.push( issue( "PAY_TOTAL_MISMATCH", "payMoney.standard", `支付金额 ${payMoney} 与报销金额 ${expenseMoney} - 核销借款 ${writtenOff} = ${expectedPay.toFixed(2)} 不一致` ) ); } } const billInvoiceTotal = moneyStandard(form.u_发票总金额); if (form.u_发票总金额 !== undefined && billInvoiceTotal === undefined) { issues.push( issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字") ); } else if (billInvoiceTotal !== undefined && !nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) { issues.push( issue( "INVOICE_TOTAL_MISMATCH", "u_发票总金额.standard", `单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致` ) ); } if (form.writtenOffMoney !== undefined && moneyStandard(form.writtenOffMoney) === undefined) { issues.push(issue("WRITTEN_OFF_MONEY_INVALID", "writtenOffMoney", "核销借款金额不合法")); } // 7. 日期 const submitAt = toNumber(form.expenseDate); const payBy = toNumber(form.u_最晚付款日期); if (submitAt !== undefined && payBy !== undefined && payBy < submitAt) { issues.push( issue( "PAY_DATE_BEFORE_SUBMIT", "u_最晚付款日期", `最晚付款日期 ${new Date(payBy).toLocaleDateString("zh-CN")} 早于提交日期 ${new Date(submitAt).toLocaleDateString("zh-CN")}` ) ); } return issues; } /** 存在 error 级别的校验问题时抛出 ValidationError。 */ export function assertBillDraftValid( form: BillDraftForm | undefined, options: ValidateOptions = {} ): void { const issues = validateBillDraft(form, options); const errors = issues.filter((item) => item.severity === "error"); if (errors.length === 0) return; throw new ValidationError( `单据校验未通过(${errors.length} 项错误):\n` + errors.map((item) => ` - [${item.field}] ${item.message}`).join("\n") ); } /** 文本输出格式化,供 CLI 复用。 */ export function formatValidationIssues(issues: ValidationIssue[]): string { if (issues.length === 0) return "✅ 单据校验通过:派生字段与必填项一致"; return issues .map((item) => `${item.severity === "error" ? "❌" : "⚠️"} [${item.field}] ${item.message}`) .join("\n"); } /** 读取真实表头与费用明细规格;失败时禁止退回猜测模板规则。 */ export async function loadBillValidationOptions( client: KyInstance, corpId: string, form: BillDraftForm, specification?: { components: BillValidationComponent[] } ): Promise { const resolveId = (reference: unknown): string => { const value = typeof reference === "string" ? reference : reference && typeof reference === "object" ? (reference as { id?: unknown }).id : undefined; if (typeof value !== "string" || !value.trim()) { throw new ValidationError("单据或费用明细缺少规格 ID,无法校验模板"); } return value.trim(); }; const load = async (id: string): Promise => { const spec = await getFormSpecification(client, corpId, id); if (!spec) throw new NotFoundError(`未找到单据或费用类型规格: ${id}`); return spec.components as BillValidationComponent[]; }; const headerId = resolveId(form.specificationId); const components = specification?.components ?? await load(headerId); const cache = new Map>(); const detailComponents = await Promise.all((form.details ?? []).map((detail) => { const id = resolveId(detail.specificationId); if (!cache.has(id)) cache.set(id, load(id)); return cache.get(id)!; })); return { components, detailComponents }; }