diff --git a/docs/reviews/2026-10-28-local-progress-integration.md b/docs/reviews/2026-10-28-local-progress-integration.md new file mode 100644 index 0000000..a37a1b0 --- /dev/null +++ b/docs/reviews/2026-10-28-local-progress-integration.md @@ -0,0 +1,39 @@ +# 2026-10-28 本地开发进度筛选与整合报告 + +## 结论与范围 + +以 `main@c2d3673` 为基线,从本地 `fix/review-20261023@9bb2ab1` 中选择仍未被主分支覆盖的单据修复和离线身份参数修复。工作流引用扫描、嵌套执行摘要和 MVEL 在后续 PR 中已有更新实现,本次保留主分支版本。 + +用户已授权评估有用进度、提交 PR、检查后合并并同步主分支;同时要求保留现有工作区和分支。本次使用独立分支 `fix/restore-local-bill-fixes`,旧分支及其工作区保持原状。 + +## 实际修改与行为差异 + +| 问题与证据 | 修改位置 | 修改后的行为 | +|---|---|---| +| 创建时仅读取树节点本身,遗漏 `{feeType, children}` 包装;显式费用类型不存在时会静默回退 | [create.ts](../../src/domains/bill/create.ts) | 同时支持包装树和平面节点;仅在省略费用类型时采用默认值,显式名称不存在、停用或重名均拒绝 | +| 创建预演使用占位标题和默认费用类型,可能与实际执行选择不同 | [CLI create.ts](../../src/cli/commands/bill/create.ts) | 通过 `prepareBillDraft` 共用元数据解析与表单准备;预演读取元数据但不创建单据 | +| 复制保留了核销关联,却把支付金额设为报销总额 | [copy.ts](../../src/domains/bill/copy.ts) | 保留核销及关联,支付金额按报销合计减核销金额计算;例如 100 − 30 = 70,源单不变 | +| 校验器硬编码企业专有必填项和 800 字符上限;复制与提交未执行一致性校验 | [draft-validation.ts](../../src/domains/bill/draft-validation.ts)、[copy.ts](../../src/domains/bill/copy.ts)、[submit.ts](../../src/domains/bill/submit.ts)、[CLI validate.ts](../../src/cli/commands/bill/validate.ts) | 加载实际表头及明细规格,以 `optional === false` 和显式 `maxLength` 校验;校验失败先于创建、审批计划计算及送审请求 | +| 没有提供汇总金额的通用模板被误报缺失;缺少表头币种时混币可能漏检 | [draft-validation.ts](../../src/domains/bill/draft-validation.ts) | 未提供且未声明必填的汇总字段可省略;已有金额、汇率、总额始终检查,币种可从首个明细确定,并检查表头支付/报销币种冲突 | +| `whoami` handler 支持离线参数,但顶层参数白名单未注册 | [command-metadata.ts](../../src/cli/command-metadata.ts)、[parser.test.ts](../../src/cli/parser.test.ts) | `whoami --offline/--cached` 能通过完整参数解析进入既有 handler | + +规格不存在、缺少规格 ID 或规格读取失败时禁止继续写入。相对旧实现,仅补强规格 ID 的字符串/对象归一化和按 ID 复用明细规格读取;提交复用已经读取的表头规格。领域说明同步在 [README.bill.md](../../src/domains/bill/README.bill.md)。 + +## 验证 + +- 将相同的 6 个行为回归放入原主分支快照与本次代码:原主分支 **0 通过 / 6 失败**,本次 **6 通过 / 0 失败**。分别覆盖包装费用树、显式费用类型拒绝回退、核销净支付、混币拒绝写入、通用模板及离线参数。 +- 使用隔离配置、企业目录、账号文件和 SQLite 路径运行 `bun test`:**876 通过 / 0 失败,111 文件,4208 次断言**。 +- `bun run check`、`bun run check:version`、`git diff --check` 均退出 0;版本仍为 `0.8.21`。 +- 新增的 [写入契约测试](../../src/domains/bill/write-contract.test.ts)覆盖表头/明细必填项、未知规格、非法规格 ID、鉴权读取失败、重复规格读取复用、可选金额、币种,以及失败时没有创建/审批计划/送审请求。 +- [创建入口测试](../../src/cli/commands/bill/create.test.ts)通过完整参数解析比较预演和执行,确认预演不写入。 +- 完整测试包含架构边界、重新打包插件、MCP 协议和离线脚本冒烟验证;本次未执行真实企业单据创建、复制或送审。 + +本地验证日志保存在当前工作区忽略目录 `.drafts/restore-local-bill-evidence/`;不把历史日志或生成的插件 bundle 纳入版本管理。 + +## 保留与未覆盖 + +- 原 `fix/review-20261023` 分支和 c758 工作区保留;本次选择性整合,因此原提交不会因本次 PR 自动成为主分支祖先。 +- 主目录 `specs/hose/` 中的接口盘点、schema 及临时抓包作为待整理资料保留。文档自行标注部分接口未进行一对一抓包校验,临时请求/响应不作为本次修复的发布资产;`.mimosa/` 属于工具会话状态及快照,不作为功能源码提交。 +- 不回退已合并的工作流、MVEL、发票取消与插件分发修复;不重新跟踪 `dist/`,不打版本 tag,不发布新版。 +- 本地校验不替代服务端完整业务校验;真实模板兼容性、核销关联复制的服务端限制和业务写入端到端验证仍需独立测试。无重试写入或自动修改业务输入。 +- 重点复查:复制保留核销关联并计算净支付的业务选择,以及以前可直接复制/提交的错误表单现在会在本地被拒绝。规格读取失败也会阻止复制或送审。 diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index 278d267..aef52bc 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -29,7 +29,7 @@ export const COMMAND_METADATA: Record = { "env" ], "commandAliases": {}, - flags: { } + flags: { ...flagList("offline cached", "boolean") } }, "aipro": { "summary": "AI PRO 确定性审批仲裁", diff --git a/src/cli/commands/bill/create.test.ts b/src/cli/commands/bill/create.test.ts new file mode 100644 index 0000000..8292f0a --- /dev/null +++ b/src/cli/commands/bill/create.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from "bun:test"; +import { handleCreate } from "./create.js"; +import { parseArgs } from "../../parser.js"; + +test("create dry-run resolves the same available fee as execution and never posts", async () => { + const writes: any[] = []; + const client = { + get: (url: string) => ({ json: async () => url.includes("specifications/") + ? { items: [{ id: "spec", name: "模板", components: [{ field: "title" }] }] } + : url.includes("staffs/me") ? { value: { staff: { id: "staff", defaultDepartment: "dept" } } } + : { items: [{ feeType: { id: "travel", name: "差旅", expenseSpecificationId: "detail" }, children: [] }] } }), + post: (_: string, payload: any) => { writes.push(payload.json); return { json: async () => ({ flow: { id: "new" } }) }; }, + }; + const base = ["bill", "create", "--template", `spec:${"a".repeat(32)}`, "--json"]; + const context = (args: string[]) => ({ parsed: parseArgs(args), runtime: { jsonMode: true }, corpId: "corp", getClient: async () => client, requireWriteConfirmation: async () => {} }) as any; + const preview = await handleCreate(context([...base, "--dry-run"])); + expect(JSON.parse(preview.stdout)).toMatchObject({ dryRun: true, feeType: "差旅" }); + expect(writes).toEqual([]); + await handleCreate(context([...base, "--yes"])); + expect(writes[0].form.details[0].feeTypeId).toBe("travel"); + await expect(handleCreate(context([...base, "--fee-type", "不存在", "--dry-run"]))).rejects.toThrow("费用类型"); + expect(writes).toHaveLength(1); +}); diff --git a/src/cli/commands/bill/create.ts b/src/cli/commands/bill/create.ts index e631992..def0b63 100644 --- a/src/cli/commands/bill/create.ts +++ b/src/cli/commands/bill/create.ts @@ -1,4 +1,4 @@ -import { createBillDraft } from "../../../domains/bill/create.js"; +import { createBillDraft, prepareBillDraft } from "../../../domains/bill/create.js"; import { isDryRun } from "../../mutation.js"; import { stringOption } from "../../parser.js"; import { printJson } from "../../printer.js"; @@ -22,7 +22,8 @@ export async function handleCreate(ctx: BillActionContext): Promise { const feeTypeName = stringOption(parsed.options, ["fee-type", "feeType"]); if (isDryRun(parsed, runtime)) { - const preview = { template: templateId, title: title ?? "(模板名称)", amount, reason: reason ?? "", feeType: feeTypeName ?? "简单费用" }; + const prepared = await prepareBillDraft(await ctx.getClient(), corpId, { templateId, title, amount, reason, feeTypeName }); + const preview = { template: templateId, title: prepared.title, amount: prepared.amount, reason: reason ?? "", feeType: prepared.feeType }; if (runtime.jsonMode) { return { stdout: printJson({ dryRun: true, ...preview }, runtime.outputOptions), stderr: "", exitCode: 0 }; } diff --git a/src/cli/commands/bill/validate.ts b/src/cli/commands/bill/validate.ts index ce0882b..5b4a2a7 100644 --- a/src/cli/commands/bill/validate.ts +++ b/src/cli/commands/bill/validate.ts @@ -2,6 +2,7 @@ import { getRawBillFlow } from "../../../domains/bill/tools.js"; import { formatValidationIssues, validateBillDraft, + loadBillValidationOptions, type BillDraftForm, } from "../../../domains/bill/draft-validation.js"; import { stringOption } from "../../parser.js"; @@ -41,7 +42,7 @@ export async function handleValidate(ctx: BillActionContext): Promise }; } - const issues = validateBillDraft(form); + const issues = validateBillDraft(form, await loadBillValidationOptions(await ctx.getClient(), corpId, form)); const errors = issues.filter((item) => item.severity === "error"); const warnings = issues.filter((item) => item.severity === "warning"); const billCode = typeof form.title === "string" ? form.title : target; diff --git a/src/cli/parser.test.ts b/src/cli/parser.test.ts index ee02b20..0730c7e 100644 --- a/src/cli/parser.test.ts +++ b/src/cli/parser.test.ts @@ -9,6 +9,13 @@ import { CLI_COMMAND_REGISTRY, findCommandByArea } from "./registry.js"; import { runAiProCli } from "../aipro-cli.js"; describe("strict command options", () => { + test("top-level whoami accepts offline flags without changing the command target", () => { + for (const flag of ["offline", "cached"]) { + const parsed = parseArgs(["whoami", `--${flag}`, "--json"]); + expect(parsed.options[flag]).toBe(true); + expect(parsed.args).toEqual([]); + } + }); test("rejects misspellings and missing values instead of silently dropping filters", async () => { const typo = await runCli(["bill", "list", "--limitt", "5", "--json"]); expect(typo.exitCode).toBe(2); diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index 4e0abe5..db72778 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -84,6 +84,14 @@ src/domains/bill/ - 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造; - 再 `POST /api/flow/v1/flows/$`(`name: freeflow.submit`,携带 `nodes`)。 +### 草稿写入前校验 + +- 复制和提交会先加载单据及费用明细的真实规格,必填字段由 `components[].optional === false` 决定,字符串上限仅在规格明确提供 `maxLength` 时执行;不再假定所有模板均包含收款信息、法人实体或最晚付款日期。 +- 已存在的金额、币种、汇率及派生合计始终检查;规格未声明且表单未提供的可选汇总字段不按缺失报错。纯函数 `validateBillDraft` 可传入 `components` / `detailComponents`;CLI `bill validate` 自动加载实际规格。 +- 缺失规格 ID、规格读取失败或一致性错误会阻止写请求;校验失败不会创建新单或提交审批。 +- 复制保留核销金额及其原有关联,支付金额按“明细报销合计 − 核销金额”重算。 +- 创建兼容 `{feeType, children}` 树和既有平面节点格式;只有省略 `--fee-type` 时采用默认费用类型。显式名称不存在、停用或重名时均拒绝,`--dry-run` 与实际执行共用解析逻辑(预演会读取元数据,不发送创建请求)。 + ## 写接口契约(实测) ```text diff --git a/src/domains/bill/copy.ts b/src/domains/bill/copy.ts index 9bcdd11..5575741 100644 --- a/src/domains/bill/copy.ts +++ b/src/domains/bill/copy.ts @@ -1,7 +1,7 @@ import type { KyInstance } from "ky"; import { NotFoundError } from "../../core/errors.js"; import { getRawBillFlow } from "./api.js"; -import type { BillDraftForm, BillMoney } from "./draft-validation.js"; +import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm, type BillMoney } from "./draft-validation.js"; /** * 纯接口复制单据。 @@ -93,7 +93,7 @@ export function buildBillCopyForm( form.u_发票总金额 = zeroMoney(form.u_发票总金额); form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) }; - form.payMoney = { ...(form.payMoney ?? {}), standard: amountSum.toFixed(2) }; + form.payMoney = { ...(form.payMoney ?? {}), standard: (amountSum - moneyNumber(form.writtenOffMoney)).toFixed(2) }; if (!keepAttachments) { form.attachments = []; } @@ -123,6 +123,7 @@ export async function copyBillAsDraft( } const form = buildBillCopyForm(sourceForm, options); + assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form)); const response = await client.post("api/flow/v1/flows", { searchParams: { corpId }, json: { name: "freeflow.edit", form }, diff --git a/src/domains/bill/create.ts b/src/domains/bill/create.ts index 40edebd..b5f1be5 100644 --- a/src/domains/bill/create.ts +++ b/src/domains/bill/create.ts @@ -85,13 +85,14 @@ interface FeeTypeNode { active?: boolean; expenseSpecificationId?: string; children?: FeeTypeNode[]; + feeType?: Omit; } function flattenFeeTypes(nodes: FeeTypeNode[]): FeeTypeNode[] { const out: FeeTypeNode[] = []; const walk = (list: FeeTypeNode[]) => { for (const node of list) { - out.push(node); + out.push(node.feeType ?? node); if (Array.isArray(node.children)) walk(node.children); } }; @@ -110,11 +111,11 @@ function zeroMoney(): Record { }; } -export async function createBillDraft( +export async function prepareBillDraft( client: KyInstance, corpId: string, options: CreateBillOptions -): Promise { +): Promise<{ form: Record; title: string; amount: string; feeType: string }> { const templateId = options.templateId.trim(); if (!templateId) throw new ValidationError("请通过 --template 指定单据模板 ID"); @@ -173,12 +174,13 @@ export async function createBillDraft( const feeTypes = flattenFeeTypes((await getFeeTypeTree(client, corpId)) as FeeTypeNode[]); const preferred = options.feeTypeName?.trim(); - const feeType = - (preferred - ? feeTypes.find((item) => item.name === preferred && item.expenseSpecificationId) - : undefined) || - feeTypes.find((item) => item.name === "简单费用" && item.expenseSpecificationId) || - feeTypes.find((item) => item.active !== false && item.expenseSpecificationId); + const available = feeTypes.filter((item) => item.active !== false && item.id && item.expenseSpecificationId); + const matches = preferred ? available.filter((item) => item.name === preferred) : []; + if (preferred && matches.length !== 1) { + throw new ValidationError(`费用类型 [${preferred}] ${matches.length ? "存在重名,请使用唯一名称" : "不存在、已停用或无可用规格"}`); + } + const feeType = preferred ? matches[0] + : available.find((item) => item.name === "简单费用") ?? available[0]; if (!feeType?.id || !feeType.expenseSpecificationId) { throw new NotFoundError("未找到可用的费用类型(缺少 expenseSpecificationId)"); } @@ -234,6 +236,15 @@ export async function createBillDraft( ); } + return { form, title, amount, feeType: feeType.name ?? "" }; +} + +export async function createBillDraft( + client: KyInstance, + corpId: string, + options: CreateBillOptions +): Promise { + const { form, title, amount, feeType } = await prepareBillDraft(client, corpId, options); const response = await client.post("api/flow/v1/flows", { searchParams: { corpId }, json: { name: "freeflow.edit", form }, @@ -249,6 +260,6 @@ export async function createBillDraft( code: String(value?.form?.code ?? ""), title, amount, - feeType: feeType.name ?? "", + feeType, }; } diff --git a/src/domains/bill/draft-validation.ts b/src/domains/bill/draft-validation.ts index 99031aa..738d175 100644 --- a/src/domains/bill/draft-validation.ts +++ b/src/domains/bill/draft-validation.ts @@ -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, 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(); @@ -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 { + 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 }; +} diff --git a/src/domains/bill/submit.ts b/src/domains/bill/submit.ts index 0d76b7d..2ea6a6c 100644 --- a/src/domains/bill/submit.ts +++ b/src/domains/bill/submit.ts @@ -1,6 +1,7 @@ import type { KyInstance } from "ky"; import { NotFoundError, ValidationError } from "../../core/errors.js"; import { getFormSpecification, getRawBillFlow } from "./api.js"; +import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validation.js"; /** * 纯接口提交单据草稿。 @@ -53,10 +54,12 @@ export async function submitBillDraft( throw new ValidationError(`单据当前状态为 ${String(flow.state)},仅 draft 可提交`); } - const specificationId = form.specificationId; + const specificationId = typeof form.specificationId === "object" && form.specificationId + ? (form.specificationId as { id?: string }).id : form.specificationId; const spec = specificationId ? await getFormSpecification(client, corpId, String(specificationId)) : undefined; + assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form, spec)); const configs = (spec as { configs?: Array<{ ability?: string; flowPlanConfigId?: string }> } | undefined)?.configs; const flowPlanConfigId = configs?.find((config) => config.ability === "flow")?.flowPlanConfigId; if (!flowPlanConfigId) { diff --git a/src/domains/bill/write-contract.test.ts b/src/domains/bill/write-contract.test.ts new file mode 100644 index 0000000..e35f40a --- /dev/null +++ b/src/domains/bill/write-contract.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, test } from "bun:test"; +import type { KyInstance } from "ky"; +import { createBillDraft, prepareBillDraft } from "./create.js"; +import { buildBillCopyForm, copyBillAsDraft } from "./copy.js"; +import { submitBillDraft } from "./submit.js"; +import { loadBillValidationOptions, validateBillDraft, type BillDraftForm } from "./draft-validation.js"; +import { AuthenticationError } from "../../core/errors.js"; + +const versionedId = `spec:${"a".repeat(32)}`; +const fee = { id: "fee", name: "简单费用", active: true, expenseSpecificationId: "detail" }; +function form(): BillDraftForm { + return { specificationId: versionedId, title: "草稿", expenseMoney: { standard: "100", standardStrCode: "CNY" }, + payMoney: { standard: "70", standardStrCode: "CNY" }, writtenOffMoney: { standard: "30" }, + details: [{ specificationId: "detail", feeTypeForm: { amount: { standard: "100", standardStrCode: "CNY" } } }] }; +} +function fixture(options: { + tree?: unknown[]; + source?: BillDraftForm; + required?: string; + detailRequired?: string; + missingSpec?: boolean; + missingDetailSpec?: boolean; + specError?: Error; +} = {}) { + const writes: Array<{ url: string; json: any }> = []; + const reads: string[] = []; + const plans: unknown[] = []; + const source = options.source ?? form(); + const client = { + get: (url: string) => ({ json: async () => { + reads.push(url); + if (url.includes("specifications/")) { + if (options.specError) throw options.specError; + const detailSpec = url.endsWith("[detail]"); + const required = detailSpec ? options.detailRequired : options.required; + return { items: options.missingSpec || (detailSpec && options.missingDetailSpec) ? [] : [{ + id: detailSpec ? "detail" : "spec", name: "测试模板", + configs: [{ ability: "flow", flowPlanConfigId: "plan" }], + components: [{ field: "title", optional: true }, ...(required ? [{ field: required, optional: false }] : [])], + }] }; + } + if (url.includes("feeTypes/")) return { items: options.tree ?? [{ feeType: { id: "folder" }, children: [{ feeType: fee, children: [] }] }] }; + if (url.includes("staffs/me")) return { value: { staff: { id: "staff", defaultDepartment: "dept" } } }; + throw new Error(`Unexpected GET ${url}`); + } }), + post: (url: string, payload: { json: any }) => ({ json: async () => { + if (url.endsWith("/flows/my")) return { items: [{ flow: { id: "f", form: source } }] }; + if (url.includes("/flows/flowId/")) return { value: { id: "f", state: "draft", form: source } }; + if (url.endsWith("/plans/computed")) { + plans.push(payload.json); + return { value: { nodes: [{ id: "review", type: "approval", approverId: "staff" }] } }; + } + writes.push({ url, json: payload.json }); + return { flow: { id: "new", form: { code: "B1" } } }; + } }), + } as unknown as KyInstance; + return { client, writes, reads, plans }; +} + +describe("bill API write contracts", () => { + test("creates with nested canonical feeType nodes and retains flat response compatibility", async () => { + for (const tree of [undefined, [fee]]) { + const { client, writes } = fixture({ tree }); + await createBillDraft(client, "corp", { templateId: versionedId, amount: "10" }); + expect(writes).toHaveLength(1); + expect(writes[0].json.form.details[0].feeTypeId).toBe("fee"); + } + }); + test("explicit missing, inactive or ambiguous fee types never fall back or write", async () => { + for (const tree of [[fee], [{ ...fee, name: "差旅", active: false }, fee], [{ ...fee, name: "差旅" }, { ...fee, id: "other", name: "差旅" }]]) { + const { client, writes } = fixture({ tree }); + await expect(createBillDraft(client, "corp", { templateId: versionedId, feeTypeName: "差旅" })).rejects.toThrow("费用类型"); + await expect(prepareBillDraft(client, "corp", { templateId: versionedId, feeTypeName: "差旅" })).rejects.toThrow("费用类型"); + expect(writes).toEqual([]); + } + }); + test("default ignores disabled simple fee and preview resolves the same fee without writing", async () => { + const { client, writes } = fixture({ tree: [{ ...fee, active: false }, { ...fee, id: "travel", name: "差旅" }] }); + const preview = await prepareBillDraft(client, "corp", { templateId: versionedId, expenseDate: 1 }); + expect(preview.feeType).toBe("差旅"); + expect(writes).toHaveLength(0); + await createBillDraft(client, "corp", { templateId: versionedId, expenseDate: 1 }); + expect(writes[0].json.form).toEqual(preview.form); + }); + test.each([0, 30, 100])("copy retains offsets %d and computes net payment", (offset) => { + const source = form(); source.writtenOffMoney!.standard = String(offset); + const copy = buildBillCopyForm(source); + expect(copy.writtenOffMoney).toEqual(source.writtenOffMoney); + expect(copy.payMoney!.standard).toBe((100 - offset).toFixed(2)); + expect(validateBillDraft(copy)).toEqual([]); + expect(source.payMoney!.standard).toBe("70"); + expect(source.writtenOffMoney!.standard).toBe(String(offset)); + }); + for (const action of [copyBillAsDraft, submitBillDraft]) { + test(`${action.name}: mixed currencies are blocked before write`, async () => { + const source = form(); source.details!.push({ specificationId: "detail", feeTypeForm: { amount: { standard: "10", standardStrCode: "USD" } } }); + const { client, writes } = fixture({ source }); + await expect(action(client, "corp", "f")).rejects.toThrow("本位币"); + expect(writes).toEqual([]); + }); + test(`${action.name}: requires actual template fields and refuses unknown templates`, async () => { + for (const opts of [{ required: "u_项目" }, { missingSpec: true }]) { + const { client, writes } = fixture(opts); + await expect(action(client, "corp", "f")).rejects.toThrow(); + expect(writes).toEqual([]); + } + }); + test(`${action.name}: generic template without tenant-specific fields writes valid form`, async () => { + const { client, writes } = fixture(); + await action(client, "corp", "f"); + expect(writes).toHaveLength(1); + expect(writes[0].json.form.payMoney.standard).toBe(action === copyBillAsDraft ? "70.00" : "70"); + }); + test(`${action.name}: required detail fields and missing detail specifications block all writes`, async () => { + for (const options of [{ detailRequired: "u_项目" }, { missingDetailSpec: true }]) { + const { client, writes, plans } = fixture(options); + await expect(action(client, "corp", "f")).rejects.toThrow(); + expect(writes).toEqual([]); + expect(plans).toEqual([]); + } + }); + test(`${action.name}: invalid specification references and read errors block all writes`, async () => { + for (const reference of [undefined, " ", {}, { id: 123 }]) { + for (const header of [true, false]) { + const source = form(); + if (header) source.specificationId = reference; + else source.details![0].specificationId = reference; + const { client, writes, plans } = fixture({ source }); + await expect(action(client, "corp", "f")).rejects.toThrow(); + expect(writes).toEqual([]); + expect(plans).toEqual([]); + } + } + const error = new AuthenticationError("规格读取无权限"); + const { client, writes, plans } = fixture({ specError: error }); + await expect(action(client, "corp", "f")).rejects.toBe(error); + expect(writes).toEqual([]); + expect(plans).toEqual([]); + }); + } + test("specification references resolve object IDs and reuse identical detail specifications", async () => { + const source = form(); + source.specificationId = { id: versionedId }; + source.details!.push(structuredClone(source.details![0])); + source.details![0].specificationId = { id: "detail" }; + const { client, reads } = fixture({ source }); + const options = await loadBillValidationOptions(client, "corp", source); + expect(options.detailComponents).toHaveLength(2); + expect(reads.filter(url => url.includes("specifications/"))).toHaveLength(2); + expect(reads.filter(url => url.endsWith("[detail]"))).toHaveLength(1); + }); + test("submit reuses the header specification for validation and approval-plan lookup", async () => { + const { client, reads } = fixture(); + await submitBillDraft(client, "corp", "f"); + expect(reads.filter(url => url.includes("specifications/"))).toHaveLength(2); + }); + test("template optionality and length are authoritative; existing money values stay checked", () => { + const source = form(); source.description = "x".repeat(900); + expect(validateBillDraft(source)).toEqual([]); + expect(validateBillDraft(source, { components: [{ field: "u_项目", optional: false }, { field: "description", maxLength: 1000 }] }).map(x => x.code)).toEqual(["MISSING_FIELD"]); + expect(validateBillDraft(source, { components: [{ field: "description", maxLength: 800 }] }).map(x => x.code)).toEqual(["DESCRIPTION_TOO_LONG"]); + source.payMoney!.standard = "100"; + expect(validateBillDraft(source).map(x => x.code)).toContain("PAY_TOTAL_MISMATCH"); + }); + test("optional summary fields may be absent, but malformed amounts and currencies remain invalid", () => { + const source = form(); + delete source.expenseMoney; + delete source.payMoney; + expect(validateBillDraft(source)).toEqual([]); + source.details!.push({ feeTypeForm: { amount: { standard: "10", standardStrCode: "USD" } } }); + expect(validateBillDraft(source).map(issue => issue.code)).toContain("CURRENCY_MISMATCH"); + source.expenseMoney = { standard: "invalid" }; + source.writtenOffMoney = { standard: "invalid" }; + expect(validateBillDraft(source).map(issue => issue.code)).toEqual(expect.arrayContaining([ + "EXPENSE_MONEY_INVALID", "WRITTEN_OFF_MONEY_INVALID", + ])); + const headerMismatch = form(); + headerMismatch.payMoney!.standardStrCode = "USD"; + expect(validateBillDraft(headerMismatch).map(issue => issue.field)).toContain("payMoney.standardStrCode"); + }); +});