fix: 整合本地单据校验与离线身份修复

从旧审查分支选择仍未进入主分支的单据修复,保留主分支较新的工作流与插件分发实现。
兼容费用类型包装树,统一创建预演与执行,修正核销净支付,并将真实规格校验接入复制及送审。
注册 whoami 离线参数,补充写入契约和完整入口回归,保留旧分支与工作区。

验证:bun test 876 pass / 0 fail;bun run check、check:version、git diff --check 通过。
This commit is contained in:
gitea committed 2026-10-28 15:00:37 +08:00
1 parent c2d36733fb
commit ebeec98f6d
12 files changed
+369 -54

No files matched your search

+77 -37
View File
@@ -1,4 +1,6 @@
import { ValidationError } from "../../core/errors.js";
import type { KyInstance } from "ky";
import { getFormSpecification } from "./api.js";
import { NotFoundError, ValidationError } from "../../core/errors.js";
/**
* 单据草稿的派生字段一致性校验。
@@ -80,7 +82,17 @@ export interface ValidationIssue {
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 */
@@ -89,7 +101,6 @@ export interface ValidateOptions {
const DEFAULT_MONEY_TOLERANCE = 0.005;
const DEFAULT_RATE_TOLERANCE = 0.01;
const MAX_DESCRIPTION_LENGTH = 800;
function toNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value)) return value;
@@ -134,34 +145,22 @@ export function validateBillDraft(
}
// 1. 必填表头
const requiredHeader: Array<[keyof BillDraftForm, string]> = [
["title", "标题"],
["specificationId", "单据模板"],
["submitterId", "提交人"],
["expenseDate", "提交日期"],
["expenseDepartment", "费用承担部门"],
["payeeId", "收款信息"],
["法人实体", "公司(法人实体)"],
["u_最晚付款日期", "最晚付款日期"],
];
for (const [key, label] of requiredHeader) {
const value = form[key];
if (value === undefined || value === null || value === "") {
issues.push(issue("MISSING_FIELD", String(key), `缺少必填字段:${label}`));
const checkComponents = (value: Record<string, unknown>, 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. 描述长度
const description = typeof form.description === "string" ? form.description : "";
if (description.length > MAX_DESCRIPTION_LENGTH) {
issues.push(
issue(
"DESCRIPTION_TOO_LONG",
"description",
`描述长度 ${description.length} 超过模板上限 ${MAX_DESCRIPTION_LENGTH}`
)
);
}
// 2. 描述长度由实际模板的 maxLength 决定,不假设所有模板均为 800。
// 3. 明细数量
const details = Array.isArray(form.details) ? form.details : [];
@@ -171,7 +170,11 @@ export function validateBillDraft(
}
// 4. 本位币(以表头报销金额为准)
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode;
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<number, number>();
@@ -183,6 +186,7 @@ export function validateBillDraft(
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}`;
@@ -297,7 +301,7 @@ export function validateBillDraft(
// 明细发票总额
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
if (detailInvoiceTotal === undefined) {
if (ft.u_发票总金额 !== undefined && detailInvoiceTotal === undefined) {
issues.push(
issue(
"DETAIL_INVOICE_TOTAL_INVALID",
@@ -306,7 +310,7 @@ export function validateBillDraft(
)
);
} else {
detailInvoiceSum += detailInvoiceTotal;
detailInvoiceSum += detailInvoiceTotal ?? 0;
if (billCurrency && ft.u_发票总金额?.standardStrCode && ft.u_发票总金额.standardStrCode !== billCurrency) {
issues.push(
issue(
@@ -341,11 +345,11 @@ export function validateBillDraft(
// 6. 表头派生金额
const expenseMoney = moneyStandard(form.expenseMoney);
if (expenseMoney === undefined) {
if (form.expenseMoney !== undefined && expenseMoney === undefined) {
issues.push(
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
);
} else if (hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
} else if (expenseMoney !== undefined && hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
issues.push(
issue(
"EXPENSE_TOTAL_MISMATCH",
@@ -356,9 +360,9 @@ export function validateBillDraft(
}
const payMoney = moneyStandard(form.payMoney);
if (payMoney === undefined) {
if (form.payMoney !== undefined && payMoney === undefined) {
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
} else if (expenseMoney !== undefined) {
} else if (payMoney !== undefined && expenseMoney !== undefined) {
const writtenOff = moneyStandard(form.writtenOffMoney) ?? 0;
const expectedPay = expenseMoney - writtenOff;
if (!nearlyEqual(payMoney, expectedPay, moneyTolerance)) {
@@ -373,11 +377,11 @@ export function validateBillDraft(
}
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
if (billInvoiceTotal === undefined) {
if (form.u_发票总金额 !== undefined && billInvoiceTotal === undefined) {
issues.push(
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
);
} else if (!nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
} else if (billInvoiceTotal !== undefined && !nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
issues.push(
issue(
"INVOICE_TOTAL_MISMATCH",
@@ -387,6 +391,10 @@ export function validateBillDraft(
);
}
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_最晚付款日期);
@@ -424,3 +432,35 @@ export function formatValidationIssues(issues: ValidationIssue[]): string {
.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<ValidateOptions> {
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<BillValidationComponent[]> => {
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<string, Promise<BillValidationComponent[]>>();
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 };
}