feat(bill): fix code lookup and add draft validate/copy/delete

- fix: resolve bill by code/ID via flows/my + flowId detail, covering draft and paid bills
- feat: draft validation engine (currency consistency, foreign rate, totals, draft status)
- feat: bill validate, bill copy, bill delete commands
- docs: write API contracts (freeflow.edit/delete/submit, plans/computed) and skill routing
This commit is contained in:
gitea committed 2026-10-23 16:46:42 +08:00
1 parent 4d921c09b3
commit 6628a546c5
13 files changed
+1274 -8

No files matched your search

+11
View File
@@ -72,6 +72,10 @@ metadata:
1. **导出/映射**:先将节点代码提取至本地独立文件(如 `scripts/clean.js` 或 `scripts/amortize.mvel`),或使用 `hose-use workflow node get <pipelineId> <nodeName> > ./scripts/xxx.mvel`;
2. **微创修改(Diff Edit)**:在本地文件上使用编辑工具进行精准、局部的差异修改(仅消耗几行 diff 的极少 Token);
3. **一键同步**:使用 `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/xxx.mvel --yes`(或 `node add ... --code-file=...`)通过文件流同步至云端。
15. **附件命名与用户协商(Attachment Naming is a Human Decision)**:
- 附件文件名属于企业业务习惯,**CLI 不设默认命名规则、不强制格式**;
- 上传或重命名附件前,Agent 必须先与用户确认文件名——可以直接沿用原文件名,也可以由用户指定(如"类型-金额/期间-日期");
- **不要自行套用历史单据的命名格式**,也不要因为命名与旧单不同而判定错误。
---
@@ -106,6 +110,9 @@ metadata:
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据实体模型与字段元数据查询 / 单据模板联动规格 | `hose-use bill schema`, `hose-use bill spec <specificationId>` | [references/bill.md](references/bill.md) |
| 草稿字段一致性校验(金额/币种/发票总额/明细草稿状态) | `hose-use bill validate <单号|ID>` | [references/bill.md](references/bill.md) |
| 复制单据为新草稿(清空发票绑定,不提交) | `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] --yes` | [references/bill.md](references/bill.md) |
| 删除草稿单据(仅 draft 状态) | `hose-use bill delete <单号|ID> --yes` | [references/bill.md](references/bill.md) |
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
@@ -167,6 +174,10 @@ hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明
hose-use bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名
hose-use bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
hose-use bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
hose-use bill validate B26015505 # 校验草稿派生字段(金额/币种/发票总额)
hose-use bill copy B26015505 --title "副本" --dry-run # 预览复制(默认保留附件)
hose-use bill copy B26015505 --title "副本" --yes # 复制为新草稿(不提交)
hose-use bill delete B26015505 --yes # 删除 draft 草稿(已提交单据会被拒绝)
hose-use bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型
hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联
hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态
+5 -2
View File
@@ -295,7 +295,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"relations": "查看关联单据",
"attachments": "列出附件",
"download": "下载附件",
"link": "生成单据详情链接"
"link": "生成单据详情链接",
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
"delete": "删除草稿单据(仅 draft,需 --yes)"
},
"options": [
"--dry-run 只预览审批动作",
@@ -339,7 +342,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"url": "link",
"specification": "spec"
},
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
flags: { ...flagList("audit basic confirm distinct drop-attachments dropAttachments force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target title to", "value") }
},
"flow": {
"summary": "审批流全域透视与穿透诊断",
+105
View File
@@ -0,0 +1,105 @@
import { getRawBillFlow } from "../../../domains/bill/tools.js";
import { buildBillCopyForm, copyBillAsDraft } from "../../../domains/bill/copy.js";
import type { BillDraftForm } from "../../../domains/bill/draft-validation.js";
import { isDryRun } from "../../mutation.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
/**
* `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] [--dry-run] --yes`
*
* 纯接口复制:读取服务端最新表单 → 清空发票绑定/重算金额 → 创建新草稿。
* 只创建草稿,不提交。
*/
export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] --yes");
}
const title = stringOption(parsed.options, ["title"]);
const keepAttachments = !booleanOption(parsed.options, ["drop-attachments", "dropAttachments"]);
const client = await ctx.getClient();
if (isDryRun(parsed, runtime)) {
const raw = await getRawBillFlow(client, corpId, target);
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined;
if (!form) {
return {
stdout: "",
stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据,无法复制\n`,
exitCode: 1,
};
}
const copy = buildBillCopyForm(form, { title, keepAttachments });
if (runtime.jsonMode) {
return {
stdout: printJson(
{
dryRun: true,
source: target,
sourceTitle: form.title,
title: copy.title,
detailCount: copy.details?.length ?? 0,
expenseMoney: copy.expenseMoney?.standard,
keepAttachments,
invoicesCleared: true,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout:
`====== 复制单据(dry-run,未创建) ======\n` +
` 源单 : ${target}(${form.title ?? "-"})\n` +
` 新标题 : ${copy.title ?? "-"}\n` +
` 明细 : ${copy.details?.length ?? 0} 条\n` +
` 金额 : ${copy.expenseMoney?.standard ?? "0"} CNY\n` +
` 附件 : ${keepAttachments ? "保留" : "清空"}\n` +
` 发票 : 清空绑定,发票总额归零\n` +
`\n提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)\n`,
stderr: "",
exitCode: 0,
};
}
await ctx.requireWriteConfirmation();
const result = await copyBillAsDraft(client, corpId, target, { title, keepAttachments });
if (runtime.jsonMode) {
return {
stdout: printJson(
{
source: target,
flowId: result.flowId,
code: result.code,
title: result.title,
detailCount: result.detailCount,
expenseMoney: result.expenseMoney,
submitted: false,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout:
`复制成功(已创建草稿,未提交)\n` +
` 新单号 : ${result.code}\n` +
` 单据 ID : ${result.flowId}\n` +
` 标题 : ${result.title}\n` +
` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`,
stderr: "",
exitCode: 0,
};
}
+86
View File
@@ -0,0 +1,86 @@
import { getRawBillFlow } from "../../../domains/bill/tools.js";
import { deleteBillDraft } from "../../../domains/bill/write.js";
import { isDryRun } from "../../mutation.js";
import { stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
/**
* `hose-use bill delete <单号|ID> [--dry-run] --yes`
*
* 仅允许删除 `draft` 状态单据(`freeflow.delete`)。
* 已提交/审批中/已支付的单据会被拒绝,避免误删真实业务单据。
*/
export async function handleDelete(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供要删除的单号或 ID: hose-use bill delete <单号|ID> --yes");
}
const client = await ctx.getClient();
const raw = await getRawBillFlow(client, corpId, target);
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
const form = flow && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : undefined;
if (!flow || !form) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据\n`,
exitCode: 1,
};
}
const flowId = String(flow.id ?? "");
const code = String(form.code ?? target);
const state = String(flow.state ?? "");
if (state !== "draft") {
return {
stdout: "",
stderr:
`[拒绝删除] 单据 ${code} 当前状态为 ${state || "unknown"},仅允许删除 draft 草稿。\n` +
`已提交单据请走撤回/作废流程,避免误删真实业务数据。\n`,
exitCode: 1,
};
}
if (isDryRun(parsed, runtime)) {
if (runtime.jsonMode) {
return {
stdout: printJson({ dryRun: true, code, flowId, state }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
return {
stdout:
`====== 删除单据(dry-run,未执行) ======\n` +
` 单号 : ${code}\n` +
` 流程 ID : ${flowId}\n` +
` 状态 : ${state}\n` +
`\n提示: 确认无误后追加 --yes 执行删除\n`,
stderr: "",
exitCode: 0,
};
}
await ctx.requireWriteConfirmation();
await deleteBillDraft(client, corpId, flowId);
if (runtime.jsonMode) {
return {
stdout: printJson({ deleted: true, code, flowId }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
return { stdout: `删除成功\n 单号: ${code}\n 流程 ID: ${flowId}\n`, stderr: "", exitCode: 0 };
}
+19 -1
View File
@@ -5,6 +5,9 @@ import { handleList, handleGet, handleTrace } from "./search.js";
import { handleFlow, handleRisk, handleBudget } from "./flow.js";
import { handleRefs, handleRelations, handleAttachments, handleDownload } from "./related.js";
import { handleSchema, handleLink, handleSpec } from "./meta.js";
import { handleValidate } from "./validate.js";
import { handleCopy } from "./copy.js";
import { handleDelete } from "./delete.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
@@ -104,7 +107,22 @@ export async function handleBillCommand(
case "specification":
return handleSpec(ctx);
case "validate":
case "check":
case "lint":
return handleValidate(ctx);
case "copy":
case "duplicate":
case "clone":
return handleCopy(ctx);
case "delete":
case "rm":
case "remove":
return handleDelete(ctx);
default:
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, delete <单号> --yes`);
}
}
+83
View File
@@ -0,0 +1,83 @@
import { getRawBillFlow } from "../../../domains/bill/tools.js";
import {
formatValidationIssues,
validateBillDraft,
type BillDraftForm,
} from "../../../domains/bill/draft-validation.js";
import { stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { CliResult } from "../../types.js";
import type { BillActionContext } from "./context.js";
/**
* `hose-use bill validate <单号|ID>`
*
* 读取单据的原始表单,校验派生字段(金额/币种/发票总额/明细草稿状态)是否自洽。
* 这是写入前的最后一道闸门:合思服务端只做弱校验,币种混加、发票总额不同步都能存进去。
*/
export async function handleValidate(ctx: BillActionContext): Promise<CliResult> {
const { parsed, runtime, corp, corpId } = ctx;
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供要校验的单号或 ID: hose-use bill validate <单号|ID>");
}
const raw = await getRawBillFlow(await ctx.getClient(), corpId, target);
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined;
if (!flow || !form) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
exitCode: 1,
};
}
const issues = validateBillDraft(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;
const code = typeof (form as Record<string, unknown>).code === "string"
? String((form as Record<string, unknown>).code)
: target;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
found: true,
corpId,
code,
title: billCode,
ok: errors.length === 0,
errorCount: errors.length,
warningCount: warnings.length,
issues,
},
runtime.outputOptions
),
stderr: "",
exitCode: errors.length === 0 ? 0 : 1,
};
}
const header =
`====== 单据校验 (${code}) ======\n` +
` 企业 : ${corp.name}\n` +
` 标题 : ${billCode}\n` +
` 结论 : ${errors.length === 0 ? "✅ 通过" : "❌ 未通过"}(错误 ${errors.length} / 警告 ${warnings.length})\n`;
const body = issues.length > 0 ? formatValidationIssues(issues) : " ✅ 派生字段与必填项一致";
return {
stdout: `${header}\n${body}\n`,
stderr: "",
exitCode: errors.length === 0 ? 0 : 1,
};
}
+49 -5
View File
@@ -6,11 +6,16 @@
```text
src/domains/bill/
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
├── bill.test.ts # 单元测试
└── README.bill.md # 本说明文件
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿
├── write.ts # 草稿写动作:freeflow.delete 等(提交契约见下文)
├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态)
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
├── bill.test.ts # 单元测试
├── copy.test.ts # 复制转换单测
├── draft-validation.test.ts # 校验规则单测
└── README.bill.md # 本说明文件
```
## 核心能力
@@ -48,4 +53,43 @@ src/domains/bill/
- 按实际流程状态(如 `PAYING`)和节点类型判断支付阶段,显示名称不参与阶段判定;流程状态优先于 backlog 状态。缺少当前身份的实际待办证据时,`diagnostic.canApprove` 为 `null`,CLI 显示“未知”,节点配置中的审批人不构成权限保证;
- 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。
9. **草稿派生字段校验 (`validateBillDraft` / `assertBillDraftValid`)**:
- 合思服务端把金额/币种/发票总额等派生字段的计算责任交给前端,保存接口只做弱校验
(甚至允许 CNY 与 USD 直接相加)。CLI 在写入前先跑本层校验:
必填表头、币种一致性、外币 `foreign × rate ≈ standard`、报销/支付/发票总额、
`detailStatus=draft` 残留、明细序号重复、发票重复绑定、最晚付款日期早于提交日期。
10. **纯接口复制 (`copyBillAsDraft`)**:
- 读取服务端最新的 `flow.form`;
- 清空发票绑定(`invoiceForm.invoices`)、明细与单据发票总额归零、剔除 `detailStatus`;
- 重算报销/支付金额,附件默认保留;
- `POST /api/flow/v1/flows` 创建新草稿(`name: freeflow.edit`),默认不提交。
11. **草稿删除 (`deleteBillDraft`)**:
- `POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`;
- CLI 仅允许删除 `draft` 状态单据,已提交/审批中/已支付一律拒绝。
## 写接口契约(实测)
```text
# 保存 / 提交 / 删除共用同一端点,靠 name 区分
POST /api/flow/v1/flows/$<flowId>?corpId=
{ id, name: "freeflow.edit", form } # 保存草稿
{ id, name: "freeflow.delete" } # 删除草稿
{ id, name: "freeflow.submit", form, formType, nodes } # 提交(nodes 来自审批计划)
# 新建草稿(不带 id)
POST /api/flow/v1/flows?corpId=
{ name: "freeflow.edit", form } -> { flow: { id, form: { code } } }
# 提交前必须先算审批计划
POST /api/v1/flow/plans/computed
{ flowId, flowPlanConfigId, form, formType, params } -> { value: { nodes: [...] } }
```
注意:
- 保存 `form` 必须使用**扁平 ID 字符串**(`specificationId`、`expenseDepartment`、`feeTypeId`、
`u_预算科目`、`法人实体`、`detailId` 等),直接回传读取接口的对象会 200 但不生效;
- 交付审批计划时 `nodes` 需原样回传给 `freeflow.submit`;
- 附件上传与发票上传目前仍依赖前端 Uploader,纯服务端 presign 链路尚未验证;
- 提交/撤回等破坏性动作只在测试企业验证,生产环境禁止演练。
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`,以及 `hose-use flow [get|trace] <单号|ID>` / `hose-use bill trace <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
+50
View File
@@ -66,6 +66,56 @@ export async function getRawBillFlow(
const cleanTarget = target.trim();
let match: Record<string, unknown> | undefined;
// 通道 0: flows/my & flows/approved 服务端按单号/ID 精确过滤
// 覆盖已支付/已归档等不在 backlogs 中的单据,避免回退到「最近 N 条」本地匹配。
try {
const endpoints = ["api/flow/v1/flows/my", "api/flow/v1/flows/approved"];
let flowId: string | undefined;
for (const ep of endpoints) {
let items: Record<string, unknown>[] = [];
try {
const res = await client.post(ep, {
searchParams: { corpId, type: "home5" },
json: {
limit: { start: 0, count: 10 },
filterBy: `(form.code.in(${quoted(cleanTarget)}))||(id==${quoted(cleanTarget)})`,
},
});
const body = (await res.json()) as { items?: Record<string, unknown>[] };
items = body.items ?? [];
} catch {
continue;
}
const item = items.find((it) => {
const flow = (it.flow && typeof it.flow === "object" ? it.flow : {}) as Record<string, unknown>;
const form = (it.form && typeof it.form === "object"
? it.form
: (flow.form && typeof flow.form === "object" ? flow.form : {})) as Record<string, unknown>;
return flow.id === cleanTarget || form.code === cleanTarget;
});
const flow = item && item.flow && typeof item.flow === "object" ? item.flow as Record<string, unknown> : undefined;
if (flow && typeof flow.id === "string") {
flowId = flow.id;
break;
}
}
if (flowId) {
const detail = await client.post(`api/flow/v1/flows/flowId/$${flowId}`, {
searchParams: { id: flowId, corpId },
json: {
filterBy: `(id==${quoted(flowId)})`,
select: "id,state,form,logs",
},
});
const json = (await detail.json()) as { value?: Record<string, unknown> };
if (json.value) {
return { flowId: json.value };
}
}
} catch {
// 通道 0 失败时继续走既有回溯通道
}
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
const searchFilters = [
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from "bun:test";
import { buildBillCopyForm } from "./copy.js";
import type { BillDraftForm } from "./draft-validation.js";
function makeSource(): BillDraftForm {
return {
id: "ID_SOURCE",
code: "B26015505",
title: "报销 10月AI工具费用",
specificationId: "spec-1",
submitterId: "corp:staff-1",
expenseDate: Date.UTC(2026, 9, 23),
expenseDepartment: "corp:dept-1",
payeeId: "payee-1",
法人实体: "entity-1",
u_最晚付款日期: Date.UTC(2026, 9, 31),
description: "",
expenseMoney: { standard: "321.14", standardStrCode: "CNY" },
payMoney: { standard: "321.14", standardStrCode: "CNY" },
u_发票总金额: { standard: "321.14", standardStrCode: "CNY", standardSymbol: "¥" },
attachments: [{ key: "bill-level.pdf" }],
details: [
{
feeTypeForm: {
detailNo: 1,
amount: { standard: "121.14", standardStrCode: "CNY" },
u_发票总金额: { standard: "121.14", standardStrCode: "CNY", standardSymbol: "¥" },
invoice: "1",
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-A" }] },
attachments: [{ key: "bank.jpeg" }],
},
},
{
feeTypeForm: {
detailNo: 2,
amount: { standard: "200", standardStrCode: "CNY" },
u_发票总金额: { standard: "200", standardStrCode: "CNY", standardSymbol: "¥" },
invoice: "1",
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-B" }] },
detailStatus: "draft",
attachments: [{ key: "alipay.pdf" }],
},
},
],
};
}
describe("buildBillCopyForm", () => {
it("清空发票绑定并把发票总额归零", () => {
const form = buildBillCopyForm(makeSource());
expect(form.u_发票总金额?.standard).toBe("0");
for (const detail of form.details!) {
expect(detail.feeTypeForm?.invoice).toBe("0");
expect(detail.feeTypeForm?.invoiceForm).toEqual({ type: "exist", invoices: [] });
expect(detail.feeTypeForm?.u_发票总金额?.standard).toBe("0");
}
});
it("重算报销金额与支付金额", () => {
const form = buildBillCopyForm(makeSource());
expect(form.expenseMoney?.standard).toBe("321.14");
expect(form.payMoney?.standard).toBe("321.14");
});
it("剔除明细草稿标记", () => {
const form = buildBillCopyForm(makeSource());
expect(form.details![1].feeTypeForm?.detailStatus).toBeUndefined();
});
it("默认保留附件", () => {
const form = buildBillCopyForm(makeSource());
expect(form.attachments?.length).toBe(1);
expect(form.details![0].feeTypeForm?.attachments?.length).toBe(1);
});
it("dropAttachments 清空单据与明细附件", () => {
const form = buildBillCopyForm(makeSource(), { keepAttachments: false });
expect(form.attachments).toEqual([]);
expect(form.details![0].feeTypeForm?.attachments).toEqual([]);
expect(form.details![1].feeTypeForm?.attachments).toEqual([]);
});
it("支持自定义标题并保留币种字段", () => {
const form = buildBillCopyForm(makeSource(), { title: "报销 10月AI工具费用(副本)" });
expect(form.title).toBe("报销 10月AI工具费用(副本)");
expect(form.u_发票总金额?.standardStrCode).toBe("CNY");
expect(form.u_发票总金额?.standardSymbol).toBe("¥");
});
it("不修改源对象", () => {
const source = makeSource();
buildBillCopyForm(source);
expect(source.u_发票总金额?.standard).toBe("321.14");
expect(source.details![1].feeTypeForm?.detailStatus).toBe("draft");
});
});
+149
View File
@@ -0,0 +1,149 @@
import type { KyInstance } from "ky";
import { NotFoundError } from "../../core/errors.js";
import { getRawBillFlow } from "./api.js";
import type { BillDraftForm, BillMoney } from "./draft-validation.js";
/**
* 纯接口复制单据。
*
* 合思前端的「复制」是内存行为:读取源单 → 在编辑器里生成一份新表单,点保存时才创建。
* 而且它复制的是编辑器内存里的旧状态(可能带旧汇率/旧金额)。
*
* CLI 的复制走「服务端读取 → 本地转换 → 创建」:
* 1. 读取服务端最新的 form;
* 2. 清空发票绑定(invoiceForm.invoices)、发票总额归零、剔除明细草稿标记;
* 3. 重算报销/支付金额;
* 4. POST /api/flow/v1/flows 创建新草稿。
*/
export interface CopyBillOptions {
/** 新单据标题;默认沿用源单标题 */
title?: string;
/** 是否保留附件(默认保留,与前端行为一致) */
keepAttachments?: boolean;
}
export interface CopyBillResult {
flowId: string;
code: string;
title: string;
detailCount: number;
expenseMoney: string;
form: BillDraftForm;
}
const CURRENCY_FIELDS = [
"standardStrCode",
"standardNumCode",
"standardSymbol",
"standardUnit",
"standardScale",
] as const;
/** 生成一个金额为 0 的本位币金额对象。 */
function zeroMoney(source: BillMoney | undefined): BillMoney {
const money: BillMoney = { standard: "0" };
for (const field of CURRENCY_FIELDS) {
if (source && source[field] !== undefined) {
(money as Record<string, unknown>)[field] = source[field];
}
}
return money;
}
function moneyNumber(money: BillMoney | undefined): number {
const value = Number(money?.standard ?? 0);
return Number.isFinite(value) ? value : 0;
}
/**
* 把源单 form 转换成一个可创建的新草稿 form。
* 纯函数,便于单测与实际调用共享。
*/
export function buildBillCopyForm(
source: BillDraftForm,
options: CopyBillOptions = {}
): BillDraftForm {
const keepAttachments = options.keepAttachments !== false;
const form = structuredClone(source) as BillDraftForm;
delete (form as Record<string, unknown>).id;
delete (form as Record<string, unknown>).code;
if (options.title?.trim()) {
form.title = options.title.trim();
}
const details = Array.isArray(form.details) ? form.details : [];
let amountSum = 0;
for (const detail of details) {
const ft = (detail.feeTypeForm ??= {});
amountSum += moneyNumber(ft.amount);
// 复制不携带发票绑定;发票总额归零
ft.invoice = "0";
ft.invoiceForm = { type: "exist", invoices: [] };
ft.u_发票总金额 = zeroMoney(ft.u_发票总金额);
delete ft.detailStatus;
if (!keepAttachments) {
ft.attachments = [];
}
}
form.u_发票总金额 = zeroMoney(form.u_发票总金额);
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
form.payMoney = { ...(form.payMoney ?? {}), standard: amountSum.toFixed(2) };
if (!keepAttachments) {
form.attachments = [];
}
return form;
}
/**
* 读取源单并创建一份新草稿。
*/
export async function copyBillAsDraft(
client: KyInstance,
corpId: string,
target: string,
options: CopyBillOptions = {}
): Promise<CopyBillResult> {
const raw = await getRawBillFlow(client, corpId, target);
const flow = raw && typeof raw.flowId === "object"
? (raw.flowId as Record<string, unknown>)
: undefined;
const sourceForm = flow && typeof flow.form === "object"
? (flow.form as BillDraftForm)
: undefined;
if (!flow || !sourceForm) {
throw new NotFoundError(`在企业 [${corpId}] 下未找到单号或 ID 为 [${target}] 的单据,无法复制`);
}
const form = buildBillCopyForm(sourceForm, options);
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 formSnapshot = (value.form ?? {}) as Record<string, unknown>;
return {
flowId: String(value.id ?? ""),
code: String(formSnapshot.code ?? ""),
title: String(formSnapshot.title ?? form.title ?? ""),
detailCount: form.details?.length ?? 0,
expenseMoney: String(form.expenseMoney?.standard ?? "0"),
form,
};
}
+148
View File
@@ -0,0 +1,148 @@
import { describe, expect, it } from "bun:test";
import {
validateBillDraft,
assertBillDraftValid,
formatValidationIssues,
type BillDraftForm,
} from "./draft-validation.js";
import { ValidationError } from "../../core/errors.js";
const DAY = 24 * 60 * 60 * 1000;
const SUBMIT_AT = Date.UTC(2026, 9, 23);
const PAY_BY = Date.UTC(2026, 9, 31);
function makeForm(): BillDraftForm {
return {
title: "报销 10月AI工具费用",
specificationId: "spec-1",
submitterId: "corp:staff-1",
expenseDate: SUBMIT_AT,
expenseDepartment: "corp:dept-1",
payeeId: "payee-1",
法人实体: "entity-1",
u_最晚付款日期: PAY_BY,
description: "",
expenseMoney: { standard: "321.14", standardStrCode: "CNY" },
payMoney: { standard: "321.14", standardStrCode: "CNY" },
u_发票总金额: { standard: "321.14", standardStrCode: "CNY" },
details: [
{
feeTypeForm: {
detailNo: 1,
amount: {
standard: "121.14",
standardStrCode: "CNY",
foreign: "2860",
foreignStrCode: "JPY",
rate: "0.04235664",
},
u_发票总金额: { standard: "121.14", standardStrCode: "CNY" },
invoice: "1",
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-A" }] },
},
},
{
feeTypeForm: {
detailNo: 2,
amount: { standard: "200", standardStrCode: "CNY" },
u_发票总金额: { standard: "200", standardStrCode: "CNY" },
invoice: "1",
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-B" }] },
},
},
],
};
}
function codes(form: BillDraftForm) {
return validateBillDraft(form).map((item) => item.code);
}
describe("validateBillDraft 派生字段校验", () => {
it("合法的两明细单据通过校验", () => {
expect(validateBillDraft(makeForm())).toEqual([]);
expect(formatValidationIssues([])).toContain("校验通过");
});
it("拦截币种混加(USD 明细混入 CNY 单据)", () => {
const form = makeForm();
form.details![1].feeTypeForm!.amount = {
standard: "250.00",
standardStrCode: "USD",
standardSymbol: "$",
standardUnit: "美元",
};
form.expenseMoney!.standard = "371.14";
form.payMoney!.standard = "371.14";
expect(codes(form)).toContain("CURRENCY_MISMATCH");
});
it("拦截外币金额与汇率不匹配", () => {
const form = makeForm();
form.details![0].feeTypeForm!.amount!.rate = "0.06";
form.details![0].feeTypeForm!.amount!.standard = "143.00";
form.expenseMoney!.standard = "343.00";
form.payMoney!.standard = "343.00";
expect(codes(form)).toContain("FOREIGN_RATE_MISMATCH");
});
it("拦截报销金额与明细合计不一致", () => {
const form = makeForm();
form.expenseMoney!.standard = "321.00";
form.payMoney!.standard = "321.00";
expect(codes(form)).toContain("EXPENSE_TOTAL_MISMATCH");
});
it("拦截发票总金额与明细发票合计不一致", () => {
const form = makeForm();
form.u_发票总金额!.standard = "321.00";
expect(codes(form)).toContain("INVOICE_TOTAL_MISMATCH");
});
it("拦截残留 draft 状态的明细", () => {
const form = makeForm();
form.details![1].feeTypeForm!.detailStatus = "draft";
expect(codes(form)).toContain("DETAIL_DRAFT_STATUS");
});
it("拦截重复的明细序号", () => {
const form = makeForm();
form.details![1].feeTypeForm!.detailNo = 1;
expect(codes(form)).toContain("DUPLICATE_DETAIL_NO");
});
it("拦截最晚付款日期早于提交日期", () => {
const form = makeForm();
form.u_最晚付款日期 = SUBMIT_AT - DAY;
expect(codes(form)).toContain("PAY_DATE_BEFORE_SUBMIT");
});
it("重复绑定同一张发票给出 warning", () => {
const form = makeForm();
form.details![1].feeTypeForm!.invoiceForm = {
type: "exist",
invoices: [{ invoiceId: "invoice-A" }],
};
const issues = validateBillDraft(form);
const duplicate = issues.find((item) => item.code === "DUPLICATE_INVOICE");
expect(duplicate?.severity).toBe("warning");
});
});
describe("assertBillDraftValid", () => {
it("合法表单不抛错", () => {
expect(() => assertBillDraftValid(makeForm())).not.toThrow();
});
it("非法表单抛出 ValidationError 并列出错误字段", () => {
const form = makeForm();
form.details![1].feeTypeForm!.detailStatus = "draft";
try {
assertBillDraftValid(form);
throw new Error("should have thrown");
} catch (error) {
expect(error).toBeInstanceOf(ValidationError);
expect(String((error as Error).message)).toContain("detailStatus");
}
});
});
+426
View File
@@ -0,0 +1,426 @@
import { 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 ValidateOptions {
/** 金额比较容差,默认 0.005(分位) */
moneyTolerance?: number;
/** 外币换算比较容差,默认 0.01 */
rateTolerance?: number;
}
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;
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 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}`));
}
}
// 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}`
)
);
}
// 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;
// 5. 逐条明细
const seenDetailNos = new Map<number, number>();
const seenInvoiceIds = new Map<string, number>();
let detailAmountSum = 0;
let detailInvoiceSum = 0;
let hasValidDetailAmounts = true;
details.forEach((detail, index) => {
const ft = detail.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 (detailInvoiceTotal === undefined) {
issues.push(
issue(
"DETAIL_INVOICE_TOTAL_INVALID",
`details[${index}].feeTypeForm.u_发票总金额`,
`${label} 的发票总金额缺失或不是合法数字`
)
);
} else {
detailInvoiceSum += detailInvoiceTotal;
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 (expenseMoney === undefined) {
issues.push(
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
);
} else if (hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
issues.push(
issue(
"EXPENSE_TOTAL_MISMATCH",
"expenseMoney.standard",
`报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致`
)
);
}
const payMoney = moneyStandard(form.payMoney);
if (payMoney === undefined) {
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
} else if (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 (billInvoiceTotal === undefined) {
issues.push(
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
);
} else if (!nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
issues.push(
issue(
"INVOICE_TOTAL_MISMATCH",
"u_发票总金额.standard",
`单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致`
)
);
}
// 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");
}
+47
View File
@@ -0,0 +1,47 @@
import type { KyInstance } from "ky";
import { EkbApiError } from "../../core/errors.js";
/**
* 单据草稿写入动作(均通过 `POST /api/flow/v1/flows/$<flowId>` + `name` 区分)。
*
* 合思把「保存 / 提交 / 删除」都收敛在同一个端点,靠 action 名区分:
* - `freeflow.edit` —— 保存草稿
* - `freeflow.submit` —— 提交送审(需先计算审批计划并把 nodes 带回)
* - `freeflow.delete` —— 删除草稿
*
* 本文件目前只实现风险最低、已在生产草稿上验证过的删除动作。
*/
async function postFlowAction(
client: KyInstance,
corpId: string,
flowId: string,
name: string,
extra: Record<string, unknown> = {},
searchParams: Record<string, string> = {}
): Promise<Record<string, unknown> | 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<string, unknown> };
if (json.flow) return json.flow;
return undefined;
}
/**
* 删除草稿单据及其费用明细(`freeflow.delete`)。
* 仅允许对 `draft` 状态单据调用——调用方需自行校验状态。
*/
export async function deleteBillDraft(
client: KyInstance,
corpId: string,
flowId: string
): Promise<void> {
const flow = await postFlowAction(client, corpId, flowId, "freeflow.delete");
if (!flow) {
throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500);
}
}