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; titleMaxLength?: number; writeResponse?: unknown; planResponse?: unknown; } = {}) { 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, maxLength: options.titleMaxLength }, ...(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 options.planResponse ?? { value: { nodes: [{ id: "review", type: "approval", approverId: "staff" }] } }; } writes.push({ url, json: payload.json }); return options.writeResponse ?? { flow: { id: "new", form: { code: "B1" } } }; } }), } as unknown as KyInstance; return { client, writes, reads, plans }; } describe("bill API write contracts", () => { test("复制通用模板不注入源单没有的发票或租户自定义字段", async () => { const { client, writes } = fixture(); await copyBillAsDraft(client, "corp", "f", { keepAttachments: false }); expect(writes).toHaveLength(1); expect(writes[0].json.form).not.toHaveProperty("u_发票总金额"); expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("u_发票总金额"); expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("invoice"); expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("invoiceForm"); expect(writes[0].json.form).not.toHaveProperty("attachments"); expect(writes[0].json.form.details[0].feeTypeForm).not.toHaveProperty("attachments"); }); test("创建和预演均拒绝缺失明细规格、必填明细与过长表头,不发起创建", async () => { for (const options of [{ missingDetailSpec: true }, { detailRequired: "u_项目" }, { titleMaxLength: 1 }]) { const { client, writes } = fixture(options); await expect(prepareBillDraft(client, "corp", { templateId: versionedId, title: "过长标题" })).rejects.toThrow(); await expect(createBillDraft(client, "corp", { templateId: versionedId, title: "过长标题" })).rejects.toThrow(); expect(writes).toEqual([]); } }); for (const action of [ (client: KyInstance) => createBillDraft(client, "corp", { templateId: versionedId }), (client: KyInstance) => copyBillAsDraft(client, "corp", "f"), (client: KyInstance) => submitBillDraft(client, "corp", "f"), ]) { test("单据写入明确拒绝业务错误或缺失 ID 的成功响应", async () => { for (const writeResponse of [{ errorCode: "REJECTED", errorMessage: "规则拒绝" }, {}, { flow: { id: "" } }]) { const { client, writes } = fixture({ writeResponse }); await expect(action(client)).rejects.toThrow(); expect(writes).toHaveLength(1); } }); } test("计算计划返回业务错误时不会继续送审", async () => { const { client, writes } = fixture({ planResponse: { errorCode: "DENIED", errorMessage: "计划不可用" } }); await expect(submitBillDraft(client, "corp", "f")).rejects.toThrow("计划不可用"); expect(writes).toEqual([]); }); 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"); }); });