From 51fb54dfe81e795f8875e2f4eb57c1ba9563171c Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 29 Oct 2026 18:14:52 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=BB=9F=E4=B8=80=E5=8D=95=E6=8D=AE?= =?UTF-8?q?=E5=86=99=E5=89=8D=E6=A0=A1=E9=AA=8C=E4=B8=8E=E4=BC=A0=E8=BE=93?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E5=A5=91=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将模板、当前员工、草稿创建/删除、审批计划和送审共七处 HTTP 调用收口到 bill/api.ts,业务层函数签名保持兼容。创建与预演复用实际规格校验,缺失明细规格、必填字段或超长文本均先于写入拒绝。 统一检查已知业务错误及有效流程 ID,保留 flow/value/裸对象成功包装与已有单号字段;补充业务拒绝、HTTP 失败、无效 ID、计划失败不送审及 CLI 非零退出回归,同步域文档。 验证:bun test 911 通过、0 失败;bun run check、git diff --check 通过。未调用真实企业接口。 --- src/cli/commands/bill/create.test.ts | 15 +++++ src/domains/bill/README.bill.md | 4 +- src/domains/bill/api.ts | 89 +++++++++++++++++++++++++ src/domains/bill/copy.ts | 16 +---- src/domains/bill/create.ts | 24 +++---- src/domains/bill/submit.ts | 25 ++----- src/domains/bill/templates.ts | 25 +------ src/domains/bill/types.ts | 21 ++++++ src/domains/bill/write-contract.test.ts | 35 +++++++++- src/domains/bill/write-response.test.ts | 43 ++++++++++++ src/domains/bill/write.ts | 26 +------- 11 files changed, 222 insertions(+), 101 deletions(-) create mode 100644 src/domains/bill/write-response.test.ts diff --git a/src/cli/commands/bill/create.test.ts b/src/cli/commands/bill/create.test.ts index 8292f0a..ce448ce 100644 --- a/src/cli/commands/bill/create.test.ts +++ b/src/cli/commands/bill/create.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test"; import { handleCreate } from "./create.js"; import { parseArgs } from "../../parser.js"; +import { cliErrorResult } from "../../runner.js"; test("create dry-run resolves the same available fee as execution and never posts", async () => { const writes: any[] = []; @@ -21,3 +22,17 @@ test("create dry-run resolves the same available fee as execution and never post await expect(handleCreate(context([...base, "--fee-type", "不存在", "--dry-run"]))).rejects.toThrow("费用类型"); expect(writes).toHaveLength(1); }); + +test("创建收到业务错误时由 CLI 错误边界返回非零,不输出创建成功", async () => { + 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: [{ id: "fee", name: "费用", expenseSpecificationId: "detail" }] } }), + post: () => ({ json: async () => ({ errorCode: "REJECTED", errorMessage: "服务端拒绝创建" }) }), + }; + const context = { parsed: parseArgs(["bill", "create", "--template", `spec:${"a".repeat(32)}`, "--yes", "--json"]), runtime: { jsonMode: true }, corpId: "corp", getClient: async () => client, requireWriteConfirmation: async () => {} } as any; + const result = await handleCreate(context).catch(error => cliErrorResult(error, true)); + expect(result.exitCode).not.toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ error: true, message: "服务端拒绝创建" }); +}); diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index db72778..a05e37b 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -9,7 +9,7 @@ src/domains/bill/ ├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API ├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排 ├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿 -├── write.ts # 草稿写动作:freeflow.delete 等(提交契约见下文) +├── write.ts # 草稿写动作门面:freeflow.delete 等(传输统一在 api.ts) ├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态) ├── templates.ts # 单据模板列表(与页面「快速新建」同源,默认仅启用) ├── create.ts # 按模板创建草稿(最小表单 + 一条费用明细) @@ -77,9 +77,11 @@ src/domains/bill/ - 默认只返回启用中的模板,`--all` 才会尝试带出停用项(服务端未返回停用项时两者一致)。 13. **按模板创建草稿 (`createBillDraft`)**: + - 与复制/提交共用实际规格校验;明细规格不存在、必填项缺失或文本超过模板上限时,预演和执行均拒绝创建。 - 读取模板规格与费用类型,构造最小表单:`specificationId`(版本化 ID)、标题、提交人、报销日期、报销部门 + 一条费用明细; - 创建后为 `draft`,不提交;`description`/金额/费用类型可由参数指定。 14. **提交送审 (`submitBillDraft`)**: + - 创建、复制、提交、删除和审批计划的 HTTP 传输及业务结果检查集中在 `api.ts`。HTTP 200 中的业务错误会抛出结构化异常;写入成功必须返回有效流程 ID,不能把空 ID 当作成功。 - 先 `POST /api/v1/flow/plans/computed` 计算审批计划; - 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造; - 再 `POST /api/flow/v1/flows/$`(`name: freeflow.submit`,携带 `nodes`)。 diff --git a/src/domains/bill/api.ts b/src/domains/bill/api.ts index d695ba8..515c017 100644 --- a/src/domains/bill/api.ts +++ b/src/domains/bill/api.ts @@ -1,5 +1,6 @@ import { KyInstance } from "ky"; import { z } from "zod"; +import { AuthenticationError, EkbApiError, PermissionError } from "../../core/errors.js"; import { RawBillSearchResponseSchema, RawBillBatchGetResponseSchema, @@ -9,6 +10,9 @@ import { type RawBillItem, type EntityMeta, type FormSpecification, + type BillTemplateRawGroup, + type BillPlanNode, + type BillFlowWriteResult, } from "./types.js"; function quoted(value: string): string { @@ -628,6 +632,7 @@ export async function getFormSpecification( value?: unknown; id?: string; }; + assertBillResponse(json); const raw = Array.isArray(json.items) ? json.items[0] : json.value ?? (typeof json.id === "string" ? json : undefined); @@ -635,3 +640,87 @@ export async function getFormSpecification( return FormSpecificationSchema.parse(raw); } +/** 检查已知业务错误包装;单据的 code(如 B26000001)不是状态码。 */ +function assertBillResponse(value: unknown): asserts value is Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new EkbApiError("单据接口返回的响应格式无效", "BILL_RESPONSE_INVALID", 502); + } + const record = value as Record; + const errorCode = record.errorCode; + const hasErrorCode = errorCode != null && ![0, "0", "", "SUCCESS", false].includes(errorCode as string | number | boolean); + if (!hasErrorCode && record.success !== false && record.error !== true && !(typeof record.code === "number" && record.code !== 0 && record.code !== 200)) return; + const message = [record.errorMessage, record.message, record.msg].find((item): item is string => typeof item === "string" && item.length > 0) || "单据接口拒绝了操作"; + const status = Number(errorCode ?? record.code); + if (status === 401) throw new AuthenticationError(message); + if (status === 403) throw new PermissionError(message); + throw new EkbApiError(message, "BILL_API_ERROR", 400); +} + +function billFlowResult(json: unknown): BillFlowWriteResult { + assertBillResponse(json); + const flow = json.flow ?? json.value ?? json; + assertBillResponse(flow); + if (typeof flow.id !== "string" || !flow.id.trim() || (flow.form !== undefined && (!flow.form || typeof flow.form !== "object" || Array.isArray(flow.form)))) { + throw new EkbApiError("单据写入响应缺少有效流程 ID 或表单结构", "BILL_WRITE_RESPONSE_INVALID", 502); + } + return flow as BillFlowWriteResult; +} + +export async function getBillCurrentStaff(client: KyInstance, corpId: string): Promise> { + const response = await client.get("api/v1/organization/staffs/me", { searchParams: { corpId } }); + const json: unknown = await response.json(); + assertBillResponse(json); + const value = json.value; + const staff = value && typeof value === "object" ? (value as Record).staff ?? json : json; + assertBillResponse(staff); + return staff; +} + +export async function getBillTemplateGroups(client: KyInstance, corpId: string): Promise { + // 服务端/CDN 会缓存该 GET 响应,改名后可能读到旧名称;带时间戳强制回源。 + const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", { + searchParams: { corpId, _t: String(Date.now()) }, + headers: { "cache-control": "no-cache", pragma: "no-cache" }, + }); + const json: unknown = await response.json(); + assertBillResponse(json); + const value = json.value as { items?: unknown } | undefined; + return z.array(z.object({ + name: z.string().optional(), active: z.boolean().optional(), + specifications: z.array(z.object({ id: z.string().optional(), originalId: z.string().optional(), name: z.string().optional(), type: z.string().optional(), active: z.boolean().optional() })).optional(), + })).parse(json.items ?? value?.items ?? []); +} + +export async function createBillFlow(client: KyInstance, corpId: string, form: Record): Promise { + const response = await client.post("api/flow/v1/flows", { searchParams: { corpId }, json: { name: "freeflow.edit", form } }); + return billFlowResult(await response.json()); +} + +export async function computeBillApprovalPlan(client: KyInstance, corpId: string, flowId: string, flowPlanConfigId: string, form: Record, formType: string): Promise { + const response = await client.post("api/v1/flow/plans/computed", { + searchParams: { corpId }, json: { flowId, flowPlanConfigId, form, formType, params: {} }, + }); + const json: unknown = await response.json(); + assertBillResponse(json); + const value = json.value as { nodes?: unknown } | undefined; + const parsed = z.array(z.object({ id: z.string().optional(), name: z.string().optional(), type: z.string().optional(), approverId: z.unknown().optional(), approverIds: z.array(z.unknown()).optional() }).passthrough()).safeParse(value?.nodes ?? []); + if (!parsed.success) throw new EkbApiError("审批计划节点格式无效", "BILL_PLAN_RESPONSE_INVALID", 502); + return parsed.data; +} + +export async function submitBillFlow(client: KyInstance, corpId: string, flowId: string, form: Record, formType: string, nodes: BillPlanNode[]): Promise { + const response = await client.post(`api/flow/v1/flows/$${flowId}`, { + searchParams: { corpId, pushMessageCode: "debug" }, json: { id: flowId, name: "freeflow.submit", formType, form, nodes }, + }); + const json: unknown = await response.json(); + billFlowResult(json); + return json; +} + +export async function deleteBillFlow(client: KyInstance, corpId: string, flowId: string): Promise { + const response = await client.post(`api/flow/v1/flows/$${flowId}`, { searchParams: { corpId }, json: { id: flowId, name: "freeflow.delete" } }); + const text = await response.text(); + if (!text) throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500); + billFlowResult(JSON.parse(text)); +} + diff --git a/src/domains/bill/copy.ts b/src/domains/bill/copy.ts index 5575741..46af062 100644 --- a/src/domains/bill/copy.ts +++ b/src/domains/bill/copy.ts @@ -1,6 +1,6 @@ import type { KyInstance } from "ky"; import { NotFoundError } from "../../core/errors.js"; -import { getRawBillFlow } from "./api.js"; +import { createBillFlow, getRawBillFlow } from "./api.js"; import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm, type BillMoney } from "./draft-validation.js"; /** @@ -124,19 +124,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 }, - }); - const json = (await response.json()) as { - value?: { id?: string; form?: { code?: string } } | string; - flow?: { id?: string; form?: { code?: string } }; - id?: string; - form?: { code?: string }; - }; - const value = (json.value && typeof json.value === "object" ? json.value : undefined) - ?? json.flow - ?? json; + const value = await createBillFlow(client, corpId, form); const formSnapshot = (value.form ?? {}) as Record; return { diff --git a/src/domains/bill/create.ts b/src/domains/bill/create.ts index b5f1be5..1567c39 100644 --- a/src/domains/bill/create.ts +++ b/src/domains/bill/create.ts @@ -1,7 +1,8 @@ import type { KyInstance } from "ky"; import { NotFoundError, ValidationError } from "../../core/errors.js"; -import { getDepartmentTree, getFeeTypeTree, getFormSpecification } from "./api.js"; +import { createBillFlow, getBillCurrentStaff, getDepartmentTree, getFeeTypeTree, getFormSpecification } from "./api.js"; import { listBillTemplates } from "./templates.js"; +import { assertBillDraftValid } from "./draft-validation.js"; /** * 纯接口创建单据草稿。 @@ -57,7 +58,7 @@ export function filterBillFormByTemplate( /** * 按费用类型 schema 过滤明细字段:费用类型没有声明的字段不发(如 feeDate)。 - * schema 拉取失败(components 为空)时保留候选字段,由服务端兜底。 + * 规格未声明字段(components 为空)时保留候选字段;调用方须先确认规格存在。 */ export function filterFeeTypeFormBySpec( candidate: Record, @@ -136,11 +137,7 @@ export async function prepareBillDraft( versionedSpecificationId = hit.versionedId; } - const meResponse = await client.get("api/v1/organization/staffs/me", { - searchParams: { corpId }, - }); - const meJson = (await meResponse.json()) as Record; - const staff = meJson.value?.staff ?? meJson; + const staff = await getBillCurrentStaff(client, corpId); const submitterId = options.submitterId || staff.id; const corpDeptCandidate = (value: unknown): string | undefined => { if (typeof value === "string" && value && value !== corpId) return value; @@ -201,6 +198,7 @@ export async function prepareBillDraft( standardStrCode: "CNY", }; const detailSpec = await getFormSpecification(client, corpId, feeType.expenseSpecificationId); + if (!detailSpec) throw new NotFoundError(`未找到费用类型规格: ${feeType.expenseSpecificationId}`); const detailComponents = ((detailSpec as { components?: TemplateComponent[] } | undefined)?.components ?? []) as TemplateComponent[]; const feeTypeForm = filterFeeTypeFormBySpec( @@ -236,6 +234,8 @@ export async function prepareBillDraft( ); } + assertBillDraftValid(form, { components: specification.components, detailComponents: [detailSpec.components] }); + return { form, title, amount, feeType: feeType.name ?? "" }; } @@ -245,15 +245,7 @@ export async function createBillDraft( 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 }, - }); - const json = (await response.json()) as Record; - const value = - (json.value && typeof json.value === "object" ? json.value : undefined) ?? - json.flow ?? - json; + const value = await createBillFlow(client, corpId, form); return { flowId: String(value?.id ?? ""), diff --git a/src/domains/bill/submit.ts b/src/domains/bill/submit.ts index 2ea6a6c..733bc6f 100644 --- a/src/domains/bill/submit.ts +++ b/src/domains/bill/submit.ts @@ -1,6 +1,6 @@ import type { KyInstance } from "ky"; import { NotFoundError, ValidationError } from "../../core/errors.js"; -import { getFormSpecification, getRawBillFlow } from "./api.js"; +import { computeBillApprovalPlan, getFormSpecification, getRawBillFlow, submitBillFlow } from "./api.js"; import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validation.js"; /** @@ -26,15 +26,6 @@ export interface SubmitBillResult { response: unknown; } -interface PlanNode { - id?: string; - name?: string; - type?: string; - approverId?: unknown; - approverIds?: unknown[]; - [key: string]: unknown; -} - export async function submitBillDraft( client: KyInstance, corpId: string, @@ -67,12 +58,7 @@ export async function submitBillDraft( } const formType = String(form.type ?? flow.formType ?? "expense"); - const planResponse = await client.post("api/v1/flow/plans/computed", { - searchParams: { corpId }, - json: { flowId, flowPlanConfigId, form, formType, params: {} }, - }); - const planJson = (await planResponse.json()) as { value?: { nodes?: PlanNode[] } }; - const nodes = planJson.value?.nodes ?? []; + const nodes = await computeBillApprovalPlan(client, corpId, flowId, flowPlanConfigId, form, formType); if (nodes.length === 0) { throw new ValidationError("审批计划为空,无法提交"); } @@ -96,15 +82,12 @@ export async function submitBillDraft( ); } - const response = await client.post(`api/flow/v1/flows/$${flowId}`, { - searchParams: { corpId, pushMessageCode: "debug" }, - json: { id: flowId, name: "freeflow.submit", formType, form, nodes }, - }); + const response = await submitBillFlow(client, corpId, flowId, form, formType, nodes); return { flowId, code: String(form.code ?? target), nodeCount: nodes.length, - response: await response.json(), + response, }; } diff --git a/src/domains/bill/templates.ts b/src/domains/bill/templates.ts index 2795fc3..ee61084 100644 --- a/src/domains/bill/templates.ts +++ b/src/domains/bill/templates.ts @@ -1,4 +1,6 @@ import type { KyInstance } from "ky"; +import { getBillTemplateGroups } from "./api.js"; +import type { BillTemplateRawGroup as RawGroup } from "./types.js"; /** * 单据模板(表单规格)列表。 @@ -32,25 +34,11 @@ export interface BillTemplateList { inactive: number; } -interface RawSpecification { - id?: string; - originalId?: string; - name?: string; - type?: string; - active?: boolean; -} - /** 去掉版本化 ID 末尾的 `:`,保留可被 `bill spec` 使用的原始 ID。 */ function stripVersionHash(id: string): string { return id.replace(/:[0-9a-f]{32,64}$/i, ""); } -interface RawGroup { - name?: string; - active?: boolean; - specifications?: RawSpecification[]; -} - export interface ListBillTemplatesOptions { includeInactive?: boolean; } @@ -101,12 +89,5 @@ export async function listBillTemplates( corpId: string, options: ListBillTemplatesOptions = {} ): Promise { - // 服务端/CDN 会缓存该 GET 响应,改名后可能读到旧名称;带时间戳强制回源。 - const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", { - searchParams: { corpId, _t: String(Date.now()) }, - headers: { "cache-control": "no-cache", pragma: "no-cache" }, - }); - const json = (await response.json()) as { items?: RawGroup[]; value?: { items?: RawGroup[] } }; - const items = json.items ?? json.value?.items ?? []; - return normalizeTemplateGroups(items, options); + return normalizeTemplateGroups(await getBillTemplateGroups(client, corpId), options); } diff --git a/src/domains/bill/types.ts b/src/domains/bill/types.ts index 7f2884b..38718f3 100644 --- a/src/domains/bill/types.ts +++ b/src/domains/bill/types.ts @@ -80,6 +80,27 @@ export type FormPriorityItem = z.infer; export type FormSpecificationComponent = z.infer; export type FormSpecification = z.infer; +export interface BillTemplateRawGroup { + name?: string; + active?: boolean; + specifications?: Array<{ id?: string; originalId?: string; name?: string; type?: string; active?: boolean }>; +} + +export interface BillPlanNode { + id?: string; + name?: string; + type?: string; + approverId?: unknown; + approverIds?: unknown[]; + [key: string]: unknown; +} + +export interface BillFlowWriteResult { + id: string; + form?: Record; + [key: string]: unknown; +} + // ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)───────────────────── export const RawBillMoneySchema = z.object({ diff --git a/src/domains/bill/write-contract.test.ts b/src/domains/bill/write-contract.test.ts index e35f40a..3f678be 100644 --- a/src/domains/bill/write-contract.test.ts +++ b/src/domains/bill/write-contract.test.ts @@ -21,6 +21,9 @@ function fixture(options: { missingSpec?: boolean; missingDetailSpec?: boolean; specError?: Error; + titleMaxLength?: number; + writeResponse?: unknown; + planResponse?: unknown; } = {}) { const writes: Array<{ url: string; json: any }> = []; const reads: string[] = []; @@ -36,7 +39,7 @@ function fixture(options: { 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 }] : [])], + 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: [] }] }] }; @@ -48,16 +51,42 @@ function fixture(options: { 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" }] } }; + return options.planResponse ?? { value: { nodes: [{ id: "review", type: "approval", approverId: "staff" }] } }; } writes.push({ url, json: payload.json }); - return { flow: { id: "new", form: { code: "B1" } } }; + 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 () => { + 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 }); diff --git a/src/domains/bill/write-response.test.ts b/src/domains/bill/write-response.test.ts new file mode 100644 index 0000000..45cead5 --- /dev/null +++ b/src/domains/bill/write-response.test.ts @@ -0,0 +1,43 @@ +import { expect, test } from "bun:test"; +import ky from "ky"; +import { createBillFlow, deleteBillFlow, submitBillFlow } from "./api.js"; +import { AuthenticationError, EkbApiError, PermissionError } from "../../core/errors.js"; + +function fixture(response: unknown, status = 200) { + let requests = 0; + const client = ky.create({ prefix: "https://tenant.invalid", retry: 0, fetch: async () => { + requests++; + return Response.json(response, { status }); + } }); + return { client, count: () => requests }; +} + +test("创建兼容 flow/value/裸对象包装,保留正常业务单号", async () => { + const flow = { id: "created", code: "B26000001", form: { code: "B26000001" } }; + for (const response of [{ flow }, { value: flow }, flow]) { + expect(await createBillFlow(fixture(response).client, "corp", { title: "草稿" })).toEqual(flow); + } +}); + +test("所有单据写动作检查 HTTP 200 中的业务拒绝与鉴权错误", async () => { + for (const action of [ + (client: ReturnType) => createBillFlow(client, "corp", {}), + (client: ReturnType) => submitBillFlow(client, "corp", "f", {}, "expense", []), + (client: ReturnType) => deleteBillFlow(client, "corp", "f"), + ]) { + for (const [errorCode, ErrorClass] of [["REJECTED", EkbApiError], [401, AuthenticationError], [403, PermissionError]] as const) { + const { client, count } = fixture({ errorCode, errorMessage: "拒绝操作" }); + await expect(action(client)).rejects.toBeInstanceOf(ErrorClass); + expect(count()).toBe(1); + } + } +}); + +test("HTTP 失败不被吞掉;无效或空流程 ID 不被强转为成功", async () => { + const { client, count } = fixture({ error: "unavailable" }, 503); + await expect(createBillFlow(client, "corp", {})).rejects.toThrow(); + expect(count()).toBe(1); + for (const response of [{ flow: {} }, { flow: { id: 1 } }, { value: { id: " " } }, { id: "f", form: [] }]) { + await expect(createBillFlow(fixture(response).client, "corp", {})).rejects.toBeInstanceOf(EkbApiError); + } +}); diff --git a/src/domains/bill/write.ts b/src/domains/bill/write.ts index daafb88..d6e0224 100644 --- a/src/domains/bill/write.ts +++ b/src/domains/bill/write.ts @@ -1,5 +1,5 @@ import type { KyInstance } from "ky"; -import { EkbApiError } from "../../core/errors.js"; +import { deleteBillFlow } from "./api.js"; /** * 单据草稿写入动作(均通过 `POST /api/flow/v1/flows/$` + `name` 区分)。 @@ -12,25 +12,6 @@ import { EkbApiError } from "../../core/errors.js"; * 本文件目前只实现风险最低、已在生产草稿上验证过的删除动作。 */ -async function postFlowAction( - client: KyInstance, - corpId: string, - flowId: string, - name: string, - extra: Record = {}, - searchParams: Record = {} -): Promise | undefined> { - const response = await client.post(`api/flow/v1/flows/$${flowId}`, { - searchParams: { corpId, ...searchParams }, - json: { id: flowId, name, ...extra }, - }); - const text = await response.text(); - if (!text) return undefined; - const json = JSON.parse(text) as { flow?: Record }; - if (json.flow) return json.flow; - return undefined; -} - /** * 删除草稿单据及其费用明细(`freeflow.delete`)。 * 仅允许对 `draft` 状态单据调用——调用方需自行校验状态。 @@ -40,8 +21,5 @@ export async function deleteBillDraft( corpId: string, flowId: string ): Promise { - const flow = await postFlowAction(client, corpId, flowId, "freeflow.delete"); - if (!flow) { - throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500); - } + await deleteBillFlow(client, corpId, flowId); }