feat(bill): 统一单据类型路由并适配申请单复制、编辑、校验与提交

- 新增 `src/domains/bill/form-helpers.ts`:统一单据类型路由(`resolveBillFormType`:模板类型 > 流程类型 > 字段特征)、东八区日期区间解析、历史流转字段剥离、以及 `dataLinkEdits` 强制重置 `dataLinkId: null`
- 更新 `draft-validation.ts`:按类型路由明细校验(非报销单允许无 `details`)、跳过 `hide`/`hidden` 必填字段、强制拦截缺失 `dataLinkId` 键的行程条目(`DATALINK_ID_KEY_MISSING`)与非法 `feeDatePeriod`
- 更新 `copy.ts` 与 `cli/commands/bill/copy.ts`:支持申请单复制(不注入 `expenseMoney`/`payMoney`,自动升级最新启用模板版本并重置行程 `dataLinkId: null`),新增 `--reason`/`--description`、`--amount`、`--start-date`、`--end-date`
- 新增 `bill edit`(别名 `update`)草稿编辑命令与 `editBillDraft` / `updateBillFlow`,支持修改 `draft` 草稿的标题、事由、申请金额与差旅起止日期(同步联动行程日期)
- 更新 `submit.ts`:正确传递 `requisition` 等 `formType`,放行 `ebot`、自动跳过节点(`skippedType`)及条件/延迟计算节点(`conditionalType` / `laterCalcReason`)
- 补齐域层与 CLI 单元测试并同步更新 `README.bill.md` 与 `skills/hose-use/references/bill.md`
This commit is contained in:
gitea committed 2026-12-02 10:45:25 +08:00
1 parent debfdec77d
commit dd67c88f49
18 files changed
+1631 -307

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
|---|---|
| [search.ts](./search.ts) | 列表、详情和定位诊断 |
| [templates.ts](./templates.ts)、[meta.ts](./meta.ts) | 可用模板、字段规格、结构与链接 |
| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[delete.ts](./delete.ts) | 草稿创建、复制与删除 |
| [create.ts](./create.ts)、[copy.ts](./copy.ts)、[edit.ts](./edit.ts)、[delete.ts](./delete.ts) | 草稿创建、复制(含申请单/行程适配)、编辑与删除 |
| [validate.ts](./validate.ts)、[submit.ts](./submit.ts) | 现有草稿校验及提交 |
| [approve.ts](./approve.ts) | 同意、驳回、转交、加签、评论的命令适配 |
| [flow.ts](./flow.ts)、[related.ts](./related.ts) | 审批时间线、风险预算、关联记录与附件 |
+69 -33
View File
@@ -1,53 +1,62 @@
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 { copyBillAsDraft, prepareBillCopy } from "../../../domains/bill/copy.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";
function formatPeriodCst(period: { start?: number; end?: number } | undefined): string {
if (!period?.start || !period?.end) return "-";
const fmt = (ms: number) =>
new Date(ms).toLocaleDateString("sv-SE", { timeZone: "Asia/Shanghai" });
return `${fmt(period.start)} ~ ${fmt(period.end)}`;
}
/**
* `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] [--dry-run] --yes`
* `hose-use bill copy <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD] [--end-date=YYYY-MM-DD] [--drop-attachments] [--dry-run] --yes`
*
* 纯接口复制:读取服务端最新表单 → 清空发票绑定/重算金额 → 创建新草稿。
* 纯接口复制(支持报销单与差旅/常规申请单):
* 读取服务端最新表单 → 重置行程 dataLinkId 为 null / 清空发票绑定 → 一致性校验 → 创建新草稿。
* 只创建草稿,不提交。
*/
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");
throw new Error(
"请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD --end-date=YYYY-MM-DD] --yes"
);
}
const title = stringOption(parsed.options, ["title"]);
const reason = stringOption(parsed.options, ["reason", "description"]);
const amount = stringOption(parsed.options, ["amount"]);
const startDate = stringOption(parsed.options, ["start-date", "startDate"]);
const endDate = stringOption(parsed.options, ["end-date", "endDate"]);
const keepAttachments = !booleanOption(parsed.options, ["drop-attachments", "dropAttachments"]);
const copyOptions = { title, reason, amount, startDate, endDate, keepAttachments };
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 });
const prepared = await prepareBillCopy(client, corpId, target, copyOptions);
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,
sourceTitle: prepared.sourceTitle,
title: prepared.form.title,
formType: prepared.formType,
detailCount: prepared.detailCount,
expenseMoney: prepared.expenseMoney,
amount: prepared.amount,
tripCount: prepared.tripCount,
dataLinkIdsReset: prepared.dataLinkIdsReset,
...(prepared.feeDatePeriod ? { feeDatePeriod: prepared.feeDatePeriod } : {}),
keepAttachments,
invoicesCleared: true,
invoicesCleared: prepared.formType === "expense",
},
runtime.outputOptions
),
@@ -55,23 +64,41 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
exitCode: 0,
};
}
const lines = [
`====== 复制单据(dry-run,未创建) ======`,
` 源单 : ${target}(${prepared.sourceTitle || "-"})`,
` 类型 : ${prepared.formType}`,
` 新标题 : ${prepared.form.title ?? "-"}`,
];
if (prepared.form.description) {
lines.push(` 事由 : ${prepared.form.description}`);
}
if (prepared.formType === "expense") {
lines.push(` 明细 : ${prepared.detailCount} 条`);
lines.push(` 金额 : ${prepared.expenseMoney} CNY`);
lines.push(` 发票 : 清空绑定,发票总额归零`);
} else {
lines.push(` 金额 : ${prepared.amount} CNY`);
if (prepared.feeDatePeriod) {
lines.push(` 日期 : ${formatPeriodCst(prepared.feeDatePeriod)}`);
}
if (prepared.tripCount > 0) {
lines.push(` 行程 : ${prepared.tripCount} 条(dataLinkId 已重置为 null)`);
}
}
lines.push(` 附件 : ${keepAttachments ? "保留" : "清空"}`);
lines.push("", "提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)", "");
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`,
stdout: lines.join("\n"),
stderr: "",
exitCode: 0,
};
}
await ctx.requireWriteConfirmation();
const result = await copyBillAsDraft(client, corpId, target, { title, keepAttachments });
const result = await copyBillAsDraft(client, corpId, target, copyOptions);
if (runtime.jsonMode) {
return {
@@ -81,8 +108,11 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
flowId: result.flowId,
code: result.code,
title: result.title,
formType: result.formType,
detailCount: result.detailCount,
expenseMoney: result.expenseMoney,
amount: result.amount,
tripCount: result.tripCount,
submitted: false,
},
runtime.outputOptions
@@ -92,13 +122,19 @@ export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
};
}
const summaryLine =
result.formType === "expense"
? ` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`
: ` 金额 : ${result.amount} CNY${result.tripCount > 0 ? `(行程 ${result.tripCount} 条)` : ""}\n`;
return {
stdout:
`复制成功(已创建草稿,未提交)\n` +
` 新单号 : ${result.code}\n` +
` 单据 ID : ${result.flowId}\n` +
` 类型 : ${result.formType}\n` +
` 标题 : ${result.title}\n` +
` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`,
summaryLine,
stderr: "",
exitCode: 0,
};
+143
View File
@@ -0,0 +1,143 @@
import { expect, test } from "bun:test";
import { handleCopy } from "./copy.js";
import { handleEdit } from "./edit.js";
import { parseArgs } from "../../parser.js";
function makeReqFixture() {
const writes: Array<{ url: string; json: any }> = [];
const sourceForm = {
code: "S26003502",
title: "旧差旅标题",
description: "旧事由",
specificationId: `reqSpec:${"a".repeat(32)}`,
submitterId: "staff-1",
requisitionDate: 1784563200000,
feeDatePeriod: { start: 1784822400000, end: 1784995199999 },
u_差旅天数: "2",
requisitionMoney: { standard: "1000", standardStrCode: "CNY" },
u_行程规划: [
{
dataLinkId: "OLD_TRIP_ID",
dataLinkTemplateId: "tpl-trip",
dataLinkForm: { E_x_行程开始日期: "2026-07-24", E_x_行程结束日期: "2026-07-25" },
},
],
};
const draftForm = structuredClone(sourceForm) as Record<string, any>;
draftForm.code = "S26005804";
draftForm.u_行程规划[0].dataLinkId = null;
const client = {
get: (url: string) => ({
json: async () => {
if (url.includes("specifications/")) {
return {
items: [
{
id: "reqSpec",
name: "4.1日常差旅申请单",
type: "requisition",
components: [
{ field: "title", optional: false },
{ field: "u_行程规划", type: "dataLinkEdits", optional: false },
],
},
],
};
}
return { items: [] };
},
}),
post: (url: string, payload: { json: any }) => ({
json: async () => {
if (url.endsWith("/flows/searchByCode")) {
return {
items: [
{ id: "ID01SRC", form: sourceForm },
{ id: "ID01DRAFT", form: draftForm },
],
};
}
if (url.includes("/flows/flowId/")) {
const isDraft = url.includes("ID01DRAFT");
return {
value: {
id: isDraft ? "ID01DRAFT" : "ID01SRC",
state: isDraft ? "draft" : "paid",
formType: "requisition",
form: isDraft ? draftForm : sourceForm,
},
};
}
if (url.includes("/backlogs/") || url.endsWith("/flows/my") || url.endsWith("/flows/approved") || url.endsWith("/carbonCopy/search")) {
return { items: [] };
}
writes.push({ url, json: payload.json });
return { flow: { id: "ID01DRAFT", form: { ...(payload.json?.form ?? {}), code: payload.json?.form?.code ?? "S26005999" } } };
},
}),
};
const context = (args: string[]) =>
({
parsed: parseArgs(args),
runtime: { jsonMode: true },
corpId: "corp",
getClient: async () => client,
requireWriteConfirmation: async () => {},
}) as any;
return { writes, context };
}
test("bill copy 支持申请单 --dry-run 预览并校验,不发写请求", async () => {
const { writes, context } = makeReqFixture();
const res = await handleCopy(
context([
"bill",
"copy",
"S26003502",
"--title",
"新差旅标题",
"--reason",
"团建",
"--amount",
"1000",
"--start-date",
"2026-12-04",
"--end-date",
"2026-12-05",
"--dry-run",
"--json",
])
);
const out = JSON.parse(res.stdout);
expect(out.dryRun).toBe(true);
expect(out.formType).toBe("requisition");
expect(out.tripCount).toBe(1);
expect(out.dataLinkIdsReset).toBe(true);
expect(out.amount).toBe("1000");
expect(writes).toEqual([]);
});
test("bill edit 支持 --dry-run 预览与 --yes 保存草稿", async () => {
const { writes, context } = makeReqFixture();
const preview = await handleEdit(
context(["bill", "edit", "S26005804", "--title", "更新后标题", "--reason", "新事由", "--dry-run", "--json"])
);
const pOut = JSON.parse(preview.stdout);
expect(pOut.dryRun).toBe(true);
expect(pOut.beforeTitle).toBe("旧差旅标题");
expect(pOut.afterTitle).toBe("更新后标题");
expect(writes).toEqual([]);
const saved = await handleEdit(
context(["bill", "edit", "S26005804", "--title", "更新后标题", "--reason", "新事由", "--yes", "--json"])
);
const sOut = JSON.parse(saved.stdout);
expect(sOut.updated).toBe(true);
expect(sOut.title).toBe("更新后标题");
expect(sOut.description).toBe("新事由");
expect(writes).toHaveLength(1);
expect(writes[0].json.name).toBe("freeflow.edit");
});
+120
View File
@@ -0,0 +1,120 @@
import { editBillDraft, prepareBillEdit } 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";
function formatPeriodCst(period: { start?: number; end?: number } | undefined): string {
if (!period?.start || !period?.end) return "-";
const fmt = (ms: number) =>
new Date(ms).toLocaleDateString("sv-SE", { timeZone: "Asia/Shanghai" });
return `${fmt(period.start)} ~ ${fmt(period.end)}`;
}
/**
* `hose-use bill edit <单号|ID> [--title=...] [--reason=...] [--description=...] [--amount=...] [--start-date=YYYY-MM-DD] [--end-date=YYYY-MM-DD] [--dry-run] --yes`
*
* 仅允许编辑 `draft` 状态草稿(`freeflow.edit`)。
*/
export async function handleEdit(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 edit <单号|ID> [--title=...] [--reason=...] [--amount=...] [--start-date=YYYY-MM-DD --end-date=YYYY-MM-DD] --yes"
);
}
const title = stringOption(parsed.options, ["title"]);
const reason = stringOption(parsed.options, ["reason", "description"]);
const amount = stringOption(parsed.options, ["amount"]);
const startDate = stringOption(parsed.options, ["start-date", "startDate"]);
const endDate = stringOption(parsed.options, ["end-date", "endDate"]);
const editOptions = { title, reason, amount, startDate, endDate };
const client = await ctx.getClient();
if (isDryRun(parsed, runtime)) {
const prepared = await prepareBillEdit(client, corpId, target, editOptions);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
dryRun: true,
code: prepared.code,
flowId: prepared.flowId,
formType: prepared.formType,
beforeTitle: prepared.beforeTitle,
afterTitle: prepared.afterTitle,
beforeDescription: prepared.beforeDescription,
afterDescription: prepared.afterDescription,
amount: prepared.amount,
tripCount: prepared.tripCount,
...(prepared.feeDatePeriod ? { feeDatePeriod: prepared.feeDatePeriod } : {}),
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const lines = [
`====== 编辑草稿(dry-run,未保存) ======`,
` 单号 : ${prepared.code}(${prepared.flowId})`,
` 类型 : ${prepared.formType}`,
` 标题 : ${prepared.beforeTitle === prepared.afterTitle ? prepared.afterTitle : `${prepared.beforeTitle} -> ${prepared.afterTitle}`}`,
` 事由 : ${prepared.beforeDescription === prepared.afterDescription ? (prepared.afterDescription || "-") : `${prepared.beforeDescription || "(空)"} -> ${prepared.afterDescription || "(空)"}`}`,
` 金额 : ${prepared.amount} CNY`,
];
if (prepared.feeDatePeriod) {
lines.push(` 日期 : ${formatPeriodCst(prepared.feeDatePeriod)}`);
}
if (prepared.tripCount > 0) {
lines.push(` 行程 : ${prepared.tripCount} 条`);
}
lines.push("", "提示: 确认无误后追加 --yes 保存草稿(不会提交)", "");
return {
stdout: lines.join("\n"),
stderr: "",
exitCode: 0,
};
}
await ctx.requireWriteConfirmation();
const result = await editBillDraft(client, corpId, target, editOptions);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
updated: true,
code: result.code,
flowId: result.flowId,
title: result.title,
description: result.description,
formType: result.formType,
amount: result.amount,
tripCount: result.tripCount,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout:
`草稿保存成功(未提交)\n` +
` 单号 : ${result.code}\n` +
` 单据 ID : ${result.flowId}\n` +
` 标题 : ${result.title}\n` +
` 事由 : ${result.description || "-"}\n` +
` 金额 : ${result.amount} CNY${result.tripCount > 0 ? `(行程 ${result.tripCount} 条)` : ""}\n`,
stderr: "",
exitCode: 0,
};
}
+6 -1
View File
@@ -7,6 +7,7 @@ import { handleRefs, handleRelations, handleAttachments, handleDownload } from "
import { handleSchema, handleLink, handleSpec } from "./meta.js";
import { handleValidate } from "./validate.js";
import { handleCopy } from "./copy.js";
import { handleEdit } from "./edit.js";
import { handleDelete } from "./delete.js";
import { handleTemplates } from "./templates.js";
import { handleCreate } from "./create.js";
@@ -120,6 +121,10 @@ export async function handleBillCommand(
case "clone":
return handleCopy(ctx);
case "edit":
case "update":
return handleEdit(ctx);
case "delete":
case "rm":
case "remove":
@@ -140,6 +145,6 @@ export async function handleBillCommand(
return handleSubmit(ctx);
default:
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, templates [--all], create --template <ID> --yes, submit <单号> --yes`);
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>, validate <单号>, copy <单号> --yes, edit <单号> --yes, delete <单号> --yes, templates [--all], create --template <ID> --yes, submit <单号> --yes`);
}
}