Compare commits
5
Commits
d7a7203eeb
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e51dc9db5 | ||
|
|
e9f6caa76f | ||
|
|
df7b583014 | ||
|
|
dd67c88f49 | ||
|
|
debfdec77d |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.9",
|
||||
"version": "0.9.10",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.9.9)
|
||||
# hose-use (v0.9.10)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.9",
|
||||
"version": "0.9.10",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.9
|
||||
version: 0.9.10
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.9)
|
||||
# hose-aipro (v0.9.10)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.9.9
|
||||
version: 0.9.10
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.9.9)
|
||||
# hose-use (v0.9.10)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
@@ -53,6 +53,20 @@ hose-use bill get <单号|flowId>
|
||||
> 草稿列表只覆盖当前身份可见的「我发起」流程。他人或系统创建的草稿可能不在 `flows/my` 中;
|
||||
> 已知单号时用 `bill get <单号>`,已知 flowId 时用 `bill get <flowId>` 直读详情。
|
||||
|
||||
### 草稿复制与编辑(支持报销单与差旅申请单)
|
||||
- `bill copy <单号|ID>` 支持报销单与申请单(`requisition`)自动路由:
|
||||
- 复制差旅申请单时会自动清理历史流转字段、重置 `u_行程规划` 等 `dataLinkEdits` 条目为 `"dataLinkId": null`(避免审批通过后无法生成行程订单),并支持通过 `--title`、`--reason`/`--description`、`--amount`、`--start-date=YYYY-MM-DD`、`--end-date=YYYY-MM-DD` 覆写标题、事由、额度与差旅日期(联动行程内日期与天数)。
|
||||
- `bill edit <单号|ID>`(别名 `update`)支持在草稿态(`draft`)修改 `--title`、`--reason`/`--description`、`--amount`(申请单)、`--start-date` 与 `--end-date`,支持 `--dry-run` 预览与 `--yes` 保存。
|
||||
|
||||
```bash
|
||||
# 复制历史差旅申请单为新草稿(预览 → 确认)
|
||||
hose-use bill copy S26003502 --title="申请差旅建设行程(谢子豪)" --reason="参加团队建设活动" --amount=1000 --start-date=2026-12-04 --end-date=2026-12-05 --dry-run
|
||||
hose-use bill copy S26003502 --title="申请差旅建设行程(谢子豪)" --reason="参加团队建设活动" --amount=1000 --start-date=2026-12-04 --end-date=2026-12-05 --yes
|
||||
|
||||
# 修改已有草稿的标题或事由
|
||||
hose-use bill edit S26005804 --title="新标题" --reason="新事由" --yes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 单据详情精准下钻 (`bill get`)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.9.9
|
||||
version: 0.9.10
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.9.9",
|
||||
"version": "0.9.10",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -365,8 +365,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"attachments": "列出附件",
|
||||
"download": "下载附件",
|
||||
"link": "生成单据详情链接",
|
||||
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
|
||||
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
|
||||
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态/行程dataLinkId)",
|
||||
"copy": "复制单据为新草稿(支持报销单与申请单,不提交)",
|
||||
"edit": "编辑草稿单据字段(仅 draft,支持标题/事由/金额/差旅日期,需 --yes)",
|
||||
"delete": "删除草稿单据(仅 draft,需 --yes)",
|
||||
"templates": "查看单据模板(默认仅启用,--all 含停用)",
|
||||
"create": "按模板创建单据草稿(不提交)",
|
||||
@@ -414,9 +415,10 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"files": "attachments",
|
||||
"file-download": "download",
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
"specification": "spec",
|
||||
"update": "edit"
|
||||
},
|
||||
flags: { ...flagList("all 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 page 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 template title to amount reason fee-type feeType", "value") }
|
||||
flags: { ...flagList("all 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 description 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 page 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 template title to amount reason fee-type feeType", "value") }
|
||||
},
|
||||
"flow": {
|
||||
"summary": "审批流全域透视与穿透诊断",
|
||||
|
||||
@@ -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) | 审批时间线、风险预算、关联记录与附件 |
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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`);
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,10 @@
|
||||
src/domains/bill/
|
||||
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
|
||||
├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿
|
||||
├── write.ts # 草稿写动作门面:freeflow.delete 等(传输统一在 api.ts)
|
||||
├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态)
|
||||
├── copy.ts # 草稿复制:服务端读取 → 按单据类型路由转换(报销/申请) → 创建新草稿
|
||||
├── form-helpers.ts # 单据类型路由(expense/requisition)、东八区日期解析、dataLinkId 重置与编辑辅助
|
||||
├── write.ts # 草稿写动作门面:freeflow.edit / freeflow.delete 等(传输统一在 api.ts)
|
||||
├── draft-validation.ts # 草稿派生字段与必填项校验(含 dataLinkId 键检查与隐藏字段放行)
|
||||
├── templates.ts # 单据模板列表(与页面「快速新建」同源,默认仅启用)
|
||||
├── create.ts # 按模板创建草稿(最小表单 + 一条费用明细)
|
||||
├── submit.ts # 计算审批计划并提交送审(freeflow.submit)
|
||||
@@ -60,17 +61,18 @@ src/domains/bill/
|
||||
9. **草稿派生字段校验 (`validateBillDraft` / `assertBillDraftValid`)**:
|
||||
- 合思服务端把金额/币种/发票总额等派生字段的计算责任交给前端,保存接口只做弱校验
|
||||
(甚至允许 CNY 与 USD 直接相加)。CLI 在写入前先跑本层校验:
|
||||
必填表头、币种一致性、外币 `foreign × rate ≈ standard`、报销/支付/发票总额、
|
||||
`detailStatus=draft` 残留、明细序号重复、发票重复绑定、最晚付款日期早于提交日期。
|
||||
10. **纯接口复制 (`copyBillAsDraft`)**:
|
||||
- 读取服务端最新的 `flow.form`;
|
||||
- 清空发票绑定(`invoiceForm.invoices`)、明细与单据发票总额归零、剔除 `detailStatus`;
|
||||
- 只重置源单实际包含的发票字段,不向通用模板注入 `u_发票总金额` 等租户自定义属性。
|
||||
- 重算报销/支付金额,附件默认保留;
|
||||
必填表头(自动忽略 `hide`/`hidden` 字段)、币种一致性、外币 `foreign × rate ≈ standard`、报销/支付/发票总额、
|
||||
`detailStatus=draft` 残留、明细序号重复、发票重复绑定、最晚付款日期早于提交日期、
|
||||
`feeDatePeriod` 合法性以及 `dataLinkEdits`(如 `u_行程规划`)条目显式携带 `dataLinkId` 键(防止审批后无法生成行程实例);
|
||||
- 按 `resolveBillFormType` 自动路由单据类型:报销单(`expense`)强制至少一条 `details`,申请单(`requisition`)允许无明细。
|
||||
10. **纯接口复制 (`copyBillAsDraft` / `prepareBillCopy`)**:
|
||||
- 读取服务端最新的 `flow.form`,自动识别模板最新启用 `versionedId`,清理历史流转/只读字段;
|
||||
- 对所有 `dataLinkEdits` 条目强制重置 `"dataLinkId": null`(绝不删除键、绝不复用旧 ID);
|
||||
- 按单据类型路由:报销单清空发票绑定、发票总额归零、剔除 `detailStatus` 并重算报销/支付金额;申请单不注入 `expenseMoney`/`payMoney`,支持覆写标题、事由、金额与差旅起止日期(同步联动 `feeDatePeriod`、`u_差旅天数` 与行程内日期);
|
||||
- `POST /api/flow/v1/flows` 创建新草稿(`name: freeflow.edit`),默认不提交。
|
||||
11. **草稿删除 (`deleteBillDraft`)**:
|
||||
- `POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`;
|
||||
- CLI 仅允许删除 `draft` 状态单据,已提交/审批中/已支付一律拒绝。
|
||||
11. **草稿编辑与删除 (`editBillDraft` / `deleteBillDraft`)**:
|
||||
- `editBillDraft`:通过 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.edit`)保存修改,仅允许 `draft` 状态单据,支持修改标题、事由、申请单金额与差旅起止日期(同步联动行程日期),写入前必跑 `assertBillDraftValid`;
|
||||
- `deleteBillDraft`:`POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`,仅允许删除 `draft` 状态单据。
|
||||
|
||||
12. **单据模板列表 (`listBillTemplates`)**:
|
||||
- 与页面「快速新建单据」同源:`GET /api/form/v2/specificationGroups/withSpecificationVersioned`;
|
||||
@@ -82,9 +84,10 @@ src/domains/bill/
|
||||
- 读取模板规格与费用类型,构造最小表单:`specificationId`(版本化 ID)、标题、提交人、报销日期、报销部门 + 一条费用明细;
|
||||
- 创建后为 `draft`,不提交;`description`/金额/费用类型可由参数指定。
|
||||
14. **提交送审 (`submitBillDraft`)**:
|
||||
- 创建、复制、提交、删除和审批计划的 HTTP 传输及业务结果检查集中在 `api.ts`。HTTP 200 中的业务错误会抛出结构化异常;写入成功必须返回有效流程 ID,不能把空 ID 当作成功。
|
||||
- 创建、复制、编辑、提交、删除和审批计划的 HTTP 传输及业务结果检查集中在 `api.ts`。HTTP 200 中的业务错误会抛出结构化异常;写入成功必须返回有效流程 ID,不能把空 ID 当作成功。
|
||||
- 自动识别 `formType`(`spec.type` / `flow.formType` / 字段特征路由,确保申请单传 `requisition` 而非 `expense`);
|
||||
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
|
||||
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
|
||||
- 仅要求普通必填审批节点存在审批人(放行 `ebot`、自动跳过 `skippedType != NO_SKIPPED` 与条件/延迟计算节点,并原样回传),未指派节点必须由 `--approver` 显式指定;
|
||||
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
|
||||
15. **未提交草稿列表 (`searchAndFormatDraftBills`)**:
|
||||
- 草稿未进入 `POST /api/v2/invoice/search` 台账索引,`bill list --state=draft` 改走 `POST /api/flow/v1/flows/my`;
|
||||
|
||||
@@ -791,6 +791,14 @@ export async function createBillFlow(client: KyInstance, corpId: string, form: R
|
||||
return billFlowResult(await response.json());
|
||||
}
|
||||
|
||||
export async function updateBillFlow(client: KyInstance, corpId: string, flowId: string, form: Record<string, unknown>): Promise<BillFlowWriteResult> {
|
||||
const response = await client.post(`api/flow/v1/flows/$${flowId}`, {
|
||||
searchParams: { corpId },
|
||||
json: { id: flowId, name: "freeflow.edit", form },
|
||||
});
|
||||
return billFlowResult(await response.json());
|
||||
}
|
||||
|
||||
export async function computeBillApprovalPlan(client: KyInstance, corpId: string, flowId: string, flowPlanConfigId: string, form: Record<string, unknown>, formType: string): Promise<BillPlanNode[]> {
|
||||
const response = await client.post("api/v1/flow/plans/computed", {
|
||||
searchParams: { corpId }, json: { flowId, flowPlanConfigId, form, formType, params: {} },
|
||||
|
||||
@@ -94,3 +94,102 @@ describe("buildBillCopyForm", () => {
|
||||
expect(source.details![1].feeTypeForm?.detailStatus).toBe("draft");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildBillCopyForm 申请单 (requisition) 适配", () => {
|
||||
function makeTravelSource(): BillDraftForm {
|
||||
return {
|
||||
id: "ID01ULT7Igvigv",
|
||||
code: "S26003502",
|
||||
title: "申请部门季度总结及团队建设差旅-谢子豪",
|
||||
description: "旧事由说明",
|
||||
specificationId: "huI8ciI19Y3Q00:oldhash",
|
||||
submitterId: "corp:staff-1",
|
||||
submitDate: 1784614796613,
|
||||
flowEndTime: 1784615989225,
|
||||
preApprovedNodeName: "所属部门主管",
|
||||
preNodeApprovedTime: 1784615989218,
|
||||
rejectionNum: "0",
|
||||
printCount: "0",
|
||||
printState: "noPrint",
|
||||
voucherNo: "",
|
||||
voucherStatus: "未生成",
|
||||
voucherCreateTime: 0,
|
||||
onlyOwnerPrint: false,
|
||||
ownerAndApproverPrintNodeFlag: false,
|
||||
requisitionDate: 1784563200000,
|
||||
feeDatePeriod: { start: 1784822400000, end: 1784995199999 },
|
||||
u_差旅天数: "2",
|
||||
requisitionMoney: { standard: "1000", standardUnit: "元", standardScale: 2, standardSymbol: "¥", standardNumCode: "156", standardStrCode: "CNY" },
|
||||
u_申请额度: { standard: "1000.00", standardUnit: "元", standardScale: 2, standardSymbol: "¥", standardNumCode: "156", standardStrCode: "CNY" },
|
||||
u_行程规划: [
|
||||
{
|
||||
dataLinkId: "ID01ULUK6llXUH",
|
||||
dataLinkTemplateId: "s-IaWFum-QeI00",
|
||||
dataLinkForm: {
|
||||
E_88080aea9796fb433000_name: "杭州市区 - 苏州市区",
|
||||
E_88080aea9796fb433000_入住日期: 1784822400000,
|
||||
E_88080aea9796fb433000_离店日期: 1784995199999,
|
||||
E_88080aea9796fb433000_行程日期: 1784822400000,
|
||||
E_88080aea9796fb433000_行程开始日期: "2026-07-24",
|
||||
E_88080aea9796fb433000_行程结束日期: "2026-07-25",
|
||||
},
|
||||
},
|
||||
{
|
||||
dataLinkId: "ID01ULUI6VSSuj",
|
||||
dataLinkTemplateId: "GxUaWFum-Qek00",
|
||||
dataLinkForm: {
|
||||
E_88080aea9796fb433000_name: "苏州市区",
|
||||
E_88080aea9796fb433000_入住日期: 1784822400000,
|
||||
E_88080aea9796fb433000_离店日期: 1784995199999,
|
||||
E_88080aea9796fb433000_行程开始日期: "2026-07-24",
|
||||
E_88080aea9796fb433000_行程结束日期: "2026-07-25",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
it("不注入 expenseMoney/payMoney,剥离历史流转字段,并强制显式设置 dataLinkId: null", () => {
|
||||
const form = buildBillCopyForm(makeTravelSource(), {
|
||||
formType: "requisition",
|
||||
requisitionDate: 1796054400000,
|
||||
});
|
||||
expect(form.expenseMoney).toBeUndefined();
|
||||
expect(form.payMoney).toBeUndefined();
|
||||
expect((form as Record<string, unknown>).flowEndTime).toBeUndefined();
|
||||
expect((form as Record<string, unknown>).preApprovedNodeName).toBeUndefined();
|
||||
expect((form as Record<string, unknown>).submitDate).toBeUndefined();
|
||||
expect((form as Record<string, unknown>).requisitionDate).toBe(1796054400000);
|
||||
|
||||
const trips = (form as Record<string, unknown>).u_行程规划 as Array<Record<string, unknown>>;
|
||||
expect(trips).toHaveLength(2);
|
||||
for (const trip of trips) {
|
||||
expect(Object.prototype.hasOwnProperty.call(trip, "dataLinkId")).toBe(true);
|
||||
expect(trip.dataLinkId).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("支持覆写标题、事由、金额与差旅起止日期并联动行程和天数", () => {
|
||||
const form = buildBillCopyForm(makeTravelSource(), {
|
||||
title: "申请差旅建设行程(谢子豪)",
|
||||
reason: "根据公司统一安排,参加团队建设活动。",
|
||||
amount: "1500",
|
||||
startDate: "2026-12-04",
|
||||
endDate: "2026-12-06",
|
||||
}) as Record<string, any>;
|
||||
|
||||
expect(form.title).toBe("申请差旅建设行程(谢子豪)");
|
||||
expect(form.description).toBe("根据公司统一安排,参加团队建设活动。");
|
||||
expect(form.requisitionMoney.standard).toBe("1500");
|
||||
expect(form["u_申请额度"].standard).toBe("1500.00");
|
||||
expect(form["u_差旅天数"]).toBe("3");
|
||||
expect(form.feeDatePeriod).toEqual({
|
||||
start: Date.parse("2026-12-04T00:00:00+08:00"),
|
||||
end: Date.parse("2026-12-06T23:59:59.999+08:00"),
|
||||
});
|
||||
expect(form["u_行程规划"][0].dataLinkForm.E_88080aea9796fb433000_行程开始日期).toBe("2026-12-04");
|
||||
expect(form["u_行程规划"][0].dataLinkForm.E_88080aea9796fb433000_行程结束日期).toBe("2026-12-06");
|
||||
expect(form["u_行程规划"][0].dataLinkForm.E_88080aea9796fb433000_行程日期).toBe(Date.parse("2026-12-04T00:00:00+08:00"));
|
||||
expect(form["u_行程规划"][1].dataLinkForm.E_88080aea9796fb433000_离店日期).toBe(Date.parse("2026-12-06T23:59:59.999+08:00"));
|
||||
});
|
||||
});
|
||||
+205
-40
@@ -1,34 +1,81 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError } from "../../core/errors.js";
|
||||
import { createBillFlow, getRawBillFlow } from "./api.js";
|
||||
import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm, type BillMoney } from "./draft-validation.js";
|
||||
import {
|
||||
assertBillDraftValid,
|
||||
loadBillValidationOptions,
|
||||
type BillDraftForm,
|
||||
type BillMoney,
|
||||
type BillValidationComponent,
|
||||
} from "./draft-validation.js";
|
||||
import {
|
||||
applyCommonAndRequisitionEdits,
|
||||
collectDataLinkEditFields,
|
||||
resetDataLinkEditsForNewDraft,
|
||||
resolveBillFormType,
|
||||
stripHistoricalFlowFields,
|
||||
todayStartCstMs,
|
||||
} from "./form-helpers.js";
|
||||
import { listBillTemplates } from "./templates.js";
|
||||
|
||||
/**
|
||||
* 纯接口复制单据。
|
||||
* 纯接口复制单据(支持报销单与差旅/常规申请单)。
|
||||
*
|
||||
* 合思前端的「复制」是内存行为:读取源单 → 在编辑器里生成一份新表单,点保存时才创建。
|
||||
* 而且它复制的是编辑器内存里的旧状态(可能带旧汇率/旧金额)。
|
||||
*
|
||||
* CLI 的复制走「服务端读取 → 本地转换 → 创建」:
|
||||
* 1. 读取服务端最新的 form;
|
||||
* 2. 清空发票绑定(invoiceForm.invoices)、发票总额归零、剔除明细草稿标记;
|
||||
* 3. 重算报销/支付金额;
|
||||
* 4. POST /api/flow/v1/flows 创建新草稿。
|
||||
* CLI 的复制走「服务端读取 → 本地转换与校验 → 创建」:
|
||||
* 1. 读取服务端最新的 form,清理历史流转与只读字段;
|
||||
* 2. 对所有 dataLinkEdits(如行程规划)强制重置 `"dataLinkId": null`(不可删键,也不可复用旧 ID);
|
||||
* 3. 按单据类型路由:
|
||||
* - expense(报销单):清空发票绑定、发票总额归零、剔除明细草稿标记、重算报销/支付金额;
|
||||
* - requisition(申请单):不注入报销/支付金额,支持覆写事由、金额、差旅起止日期(同步更新行程日期与天数);
|
||||
* 4. 校验通过后 POST /api/flow/v1/flows 创建新草稿。
|
||||
*/
|
||||
|
||||
export interface CopyBillOptions {
|
||||
/** 新单据标题;默认沿用源单标题 */
|
||||
title?: string;
|
||||
/** 事由/描述覆写 */
|
||||
reason?: string;
|
||||
/** 申请单金额覆写(仅非报销单) */
|
||||
amount?: string;
|
||||
/** 差旅开始日期(YYYY-MM-DD,需与 endDate 成对使用) */
|
||||
startDate?: string;
|
||||
/** 差旅结束日期(YYYY-MM-DD,需与 startDate 成对使用) */
|
||||
endDate?: string;
|
||||
/** 申请日期时间戳(默认东八区当天 00:00) */
|
||||
requisitionDate?: number;
|
||||
/** 是否保留附件(默认保留,与前端行为一致) */
|
||||
keepAttachments?: boolean;
|
||||
/** 显式指定单据类型(不传时自动按模板或字段特征路由) */
|
||||
formType?: string;
|
||||
/** 覆写模板版本化 ID */
|
||||
specificationId?: string;
|
||||
/** 模板组件定义,用于字段识别与日期联动 */
|
||||
components?: BillValidationComponent[];
|
||||
}
|
||||
|
||||
export interface PreparedBillCopy {
|
||||
sourceCode: string;
|
||||
sourceTitle: string;
|
||||
formType: string;
|
||||
detailCount: number;
|
||||
expenseMoney: string;
|
||||
amount: string;
|
||||
tripCount: number;
|
||||
dataLinkIdsReset: boolean;
|
||||
feeDatePeriod?: { start?: number; end?: number };
|
||||
form: BillDraftForm;
|
||||
}
|
||||
|
||||
export interface CopyBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
title: string;
|
||||
formType: string;
|
||||
detailCount: number;
|
||||
expenseMoney: string;
|
||||
amount: string;
|
||||
tripCount: number;
|
||||
form: BillDraftForm;
|
||||
}
|
||||
|
||||
@@ -56,6 +103,24 @@ function moneyNumber(money: BillMoney | undefined): number {
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
function countDataLinkItems(form: Record<string, unknown>, components?: BillValidationComponent[]): number {
|
||||
let total = 0;
|
||||
for (const field of collectDataLinkEditFields(form, components)) {
|
||||
const list = form[field];
|
||||
if (Array.isArray(list)) total += list.length;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function resolveCopyAmount(form: BillDraftForm, formType: string): string {
|
||||
if (formType === "expense") {
|
||||
return String(form.expenseMoney?.standard ?? "0");
|
||||
}
|
||||
const reqMoney = (form as Record<string, unknown>).requisitionMoney as BillMoney | undefined;
|
||||
const quotaMoney = (form as Record<string, unknown>)["u_申请额度"] as BillMoney | undefined;
|
||||
return String(reqMoney?.standard ?? quotaMoney?.standard ?? "0");
|
||||
}
|
||||
|
||||
/**
|
||||
* 把源单 form 转换成一个可创建的新草稿 form。
|
||||
* 纯函数,便于单测与实际调用共享。
|
||||
@@ -66,50 +131,104 @@ export function buildBillCopyForm(
|
||||
): BillDraftForm {
|
||||
const keepAttachments = options.keepAttachments !== false;
|
||||
const form = structuredClone(source) as BillDraftForm;
|
||||
const formRecord = form as Record<string, unknown>;
|
||||
|
||||
delete (form as Record<string, unknown>).id;
|
||||
delete (form as Record<string, unknown>).code;
|
||||
if (options.title?.trim()) {
|
||||
form.title = options.title.trim();
|
||||
stripHistoricalFlowFields(formRecord);
|
||||
if (options.specificationId?.trim()) {
|
||||
form.specificationId = options.specificationId.trim();
|
||||
}
|
||||
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
let amountSum = 0;
|
||||
const formType = resolveBillFormType(form, { specType: options.formType });
|
||||
resetDataLinkEditsForNewDraft(formRecord, options.components);
|
||||
|
||||
for (const detail of details) {
|
||||
const ft = (detail.feeTypeForm ??= {});
|
||||
amountSum += moneyNumber(ft.amount);
|
||||
if (formType === "expense") {
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
let amountSum = 0;
|
||||
|
||||
// 复制不携带发票绑定;发票总额归零
|
||||
if (ft.invoice !== undefined) ft.invoice = "0";
|
||||
if (ft.invoiceForm !== undefined) ft.invoiceForm = { type: "exist", invoices: [] };
|
||||
if (ft.u_发票总金额 !== undefined) ft.u_发票总金额 = zeroMoney(ft.u_发票总金额);
|
||||
delete ft.detailStatus;
|
||||
for (const detail of details) {
|
||||
const ft = (detail.feeTypeForm ??= {});
|
||||
amountSum += moneyNumber(ft.amount);
|
||||
|
||||
if (!keepAttachments && ft.attachments !== undefined) {
|
||||
ft.attachments = [];
|
||||
// 复制不携带发票绑定;发票总额归零
|
||||
if (ft.invoice !== undefined) ft.invoice = "0";
|
||||
if (ft.invoiceForm !== undefined) ft.invoiceForm = { type: "exist", invoices: [] };
|
||||
if (ft.u_发票总金额 !== undefined) ft.u_发票总金额 = zeroMoney(ft.u_发票总金额);
|
||||
delete ft.detailStatus;
|
||||
|
||||
if (!keepAttachments && ft.attachments !== undefined) {
|
||||
ft.attachments = [];
|
||||
}
|
||||
}
|
||||
|
||||
if (form.u_发票总金额 !== undefined) form.u_发票总金额 = zeroMoney(form.u_发票总金额);
|
||||
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
form.payMoney = { ...(form.payMoney ?? {}), standard: (amountSum - moneyNumber(form.writtenOffMoney)).toFixed(2) };
|
||||
if (!keepAttachments && form.attachments !== undefined) {
|
||||
form.attachments = [];
|
||||
}
|
||||
|
||||
applyCommonAndRequisitionEdits(formRecord, {
|
||||
title: options.title,
|
||||
reason: options.reason,
|
||||
components: options.components,
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
if (form.u_发票总金额 !== undefined) form.u_发票总金额 = zeroMoney(form.u_发票总金额);
|
||||
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
form.payMoney = { ...(form.payMoney ?? {}), standard: (amountSum - moneyNumber(form.writtenOffMoney)).toFixed(2) };
|
||||
// 非报销单(如差旅申请单):不注入 expenseMoney/payMoney,保留原有申请金额并应用覆盖项
|
||||
if (!keepAttachments && form.attachments !== undefined) {
|
||||
form.attachments = [];
|
||||
}
|
||||
const hasReqDate =
|
||||
"requisitionDate" in formRecord ||
|
||||
Boolean(options.components?.some((item) => item.field === "requisitionDate")) ||
|
||||
options.requisitionDate !== undefined;
|
||||
if (hasReqDate) {
|
||||
formRecord.requisitionDate = options.requisitionDate ?? todayStartCstMs();
|
||||
}
|
||||
|
||||
applyCommonAndRequisitionEdits(formRecord, {
|
||||
title: options.title,
|
||||
reason: options.reason,
|
||||
amount: options.amount,
|
||||
startDate: options.startDate,
|
||||
endDate: options.endDate,
|
||||
components: options.components,
|
||||
});
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取源单并创建一份新草稿。
|
||||
*/
|
||||
export async function copyBillAsDraft(
|
||||
async function resolveLatestVersionedSpecId(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
currentSpecId: unknown
|
||||
): Promise<string | undefined> {
|
||||
const raw = typeof currentSpecId === "string"
|
||||
? currentSpecId.trim()
|
||||
: currentSpecId && typeof currentSpecId === "object"
|
||||
? String((currentSpecId as { id?: unknown }).id ?? "").trim()
|
||||
: "";
|
||||
if (!raw) return undefined;
|
||||
const cleanId = raw.replace(/:[0-9a-f]{32,64}$/i, "");
|
||||
try {
|
||||
const list = await listBillTemplates(client, corpId);
|
||||
const hit = list.groups
|
||||
.flatMap((group) => group.specifications)
|
||||
.find((item) => item.id === cleanId || item.versionedId === raw);
|
||||
return hit?.versionedId || raw;
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
/** 预演或创建前的公共准备工作:读取源单、升级模板版本、转换载荷并执行一致性校验。 */
|
||||
export async function prepareBillCopy(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: CopyBillOptions = {}
|
||||
): Promise<CopyBillResult> {
|
||||
): Promise<PreparedBillCopy> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object"
|
||||
? (raw.flowId as Record<string, unknown>)
|
||||
@@ -122,17 +241,63 @@ export async function copyBillAsDraft(
|
||||
throw new NotFoundError(`在企业 [${corpId}] 下未找到单号或 ID 为 [${target}] 的单据,无法复制`);
|
||||
}
|
||||
|
||||
const form = buildBillCopyForm(sourceForm, options);
|
||||
assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form));
|
||||
const value = await createBillFlow(client, corpId, form);
|
||||
const validationOptions = await loadBillValidationOptions(client, corpId, sourceForm);
|
||||
const flowFormType = typeof flow.formType === "string" ? flow.formType : undefined;
|
||||
const formType = resolveBillFormType(sourceForm, {
|
||||
specType: options.formType ?? validationOptions.formType,
|
||||
flowFormType,
|
||||
});
|
||||
const upgradedSpecId = options.specificationId ?? (await resolveLatestVersionedSpecId(client, corpId, sourceForm.specificationId));
|
||||
|
||||
const form = buildBillCopyForm(sourceForm, {
|
||||
...options,
|
||||
formType,
|
||||
specificationId: upgradedSpecId,
|
||||
components: validationOptions.components,
|
||||
});
|
||||
|
||||
assertBillDraftValid(form, { ...validationOptions, formType });
|
||||
|
||||
const formRecord = form as Record<string, unknown>;
|
||||
const tripCount = countDataLinkItems(formRecord, validationOptions.components);
|
||||
const period = formRecord.feeDatePeriod as { start?: number; end?: number } | undefined;
|
||||
|
||||
return {
|
||||
sourceCode: String((sourceForm as Record<string, unknown>).code ?? target),
|
||||
sourceTitle: String(sourceForm.title ?? ""),
|
||||
formType,
|
||||
detailCount: form.details?.length ?? 0,
|
||||
expenseMoney: String(form.expenseMoney?.standard ?? "0"),
|
||||
amount: resolveCopyAmount(form, formType),
|
||||
tripCount,
|
||||
dataLinkIdsReset: tripCount > 0,
|
||||
...(period ? { feeDatePeriod: { start: period.start, end: period.end } } : {}),
|
||||
form,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取源单并创建一份新草稿。
|
||||
*/
|
||||
export async function copyBillAsDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: CopyBillOptions = {}
|
||||
): Promise<CopyBillResult> {
|
||||
const prepared = await prepareBillCopy(client, corpId, target, options);
|
||||
const value = await createBillFlow(client, corpId, prepared.form);
|
||||
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,
|
||||
title: String(formSnapshot.title ?? prepared.form.title ?? ""),
|
||||
formType: prepared.formType,
|
||||
detailCount: prepared.detailCount,
|
||||
expenseMoney: prepared.expenseMoney,
|
||||
amount: prepared.amount,
|
||||
tripCount: prepared.tripCount,
|
||||
form: prepared.form,
|
||||
};
|
||||
}
|
||||
@@ -146,3 +146,65 @@ describe("assertBillDraftValid", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("申请单 (requisition) 与 dataLinkEdits 校验", () => {
|
||||
function makeTravelRequisition(): BillDraftForm {
|
||||
return {
|
||||
title: "申请差旅建设行程(谢子豪)",
|
||||
specificationId: "spec-req",
|
||||
submitterId: "corp:staff-1",
|
||||
requisitionDate: Date.UTC(2026, 11, 1),
|
||||
feeDatePeriod: {
|
||||
start: Date.parse("2026-12-04T00:00:00+08:00"),
|
||||
end: Date.parse("2026-12-05T23:59:59.999+08:00"),
|
||||
},
|
||||
requisitionMoney: { standard: "1000", standardStrCode: "CNY" },
|
||||
u_行程规划: [
|
||||
{
|
||||
dataLinkId: null,
|
||||
dataLinkTemplateId: "s-IaWFum-QeI00",
|
||||
dataLinkForm: {
|
||||
E_88080aea9796fb433000_name: "杭州市区 - 苏州市区",
|
||||
E_88080aea9796fb433000_行程开始日期: "2026-12-04",
|
||||
E_88080aea9796fb433000_行程结束日期: "2026-12-05",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
it("无 details 的合法差旅申请单通过校验,且放行 hide=true 的模板必填字段", () => {
|
||||
const form = makeTravelRequisition();
|
||||
const issues = validateBillDraft(form, {
|
||||
formType: "requisition",
|
||||
components: [
|
||||
{ field: "title", optional: false },
|
||||
{ field: "u_深度现场项目", label: "深度现场项目", optional: false, hide: true },
|
||||
{ field: "u_行程规划", label: "行程规划", type: "dataLinkEdits", optional: false },
|
||||
],
|
||||
});
|
||||
expect(issues).toEqual([]);
|
||||
});
|
||||
|
||||
it("自动根据字段特征路由申请单,不报 NO_DETAILS", () => {
|
||||
const form = makeTravelRequisition();
|
||||
expect(validateBillDraft(form)).toEqual([]);
|
||||
});
|
||||
|
||||
it("拦截缺少 dataLinkId 键的行程记录(防止审批后无法生成 TRIP)", () => {
|
||||
const form = makeTravelRequisition();
|
||||
const trips = form.u_行程规划 as Array<Record<string, unknown>>;
|
||||
delete trips[0].dataLinkId;
|
||||
const issues = validateBillDraft(form, { formType: "requisition" });
|
||||
expect(issues.map((item) => item.code)).toContain("DATALINK_ID_KEY_MISSING");
|
||||
});
|
||||
|
||||
it("拦截结束日期早于开始日期的 feeDatePeriod", () => {
|
||||
const form = makeTravelRequisition();
|
||||
form.feeDatePeriod = {
|
||||
start: Date.parse("2026-12-05T00:00:00+08:00"),
|
||||
end: Date.parse("2026-12-04T23:59:59.999+08:00"),
|
||||
};
|
||||
expect(codes(form)).toContain("FEE_DATE_PERIOD_INVALID");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { getFormSpecification } from "./api.js";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { collectDataLinkEditFields, resolveBillFormType } from "./form-helpers.js";
|
||||
|
||||
/**
|
||||
* 单据草稿的派生字段一致性校验。
|
||||
@@ -85,11 +86,16 @@ export interface ValidationIssue {
|
||||
export interface BillValidationComponent {
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
optional?: boolean;
|
||||
hide?: boolean;
|
||||
hidden?: boolean;
|
||||
maxLength?: number;
|
||||
}
|
||||
|
||||
export interface ValidateOptions {
|
||||
/** 单据业务类型(如 expense / requisition),未提供时按表单字段特征路由 */
|
||||
formType?: string;
|
||||
/** 实际模板字段;未提供时仅检查通用结构与已有金额。 */
|
||||
components?: BillValidationComponent[];
|
||||
detailComponents?: BillValidationComponent[][];
|
||||
@@ -144,13 +150,16 @@ export function validateBillDraft(
|
||||
return [issue("EMPTY_FORM", "form", "单据表单为空")];
|
||||
}
|
||||
|
||||
// 1. 必填表头
|
||||
const formType = resolveBillFormType(form, { specType: options.formType });
|
||||
|
||||
// 1. 必填表头(跳过模板显式隐藏字段)
|
||||
const checkComponents = (value: Record<string, unknown>, components: BillValidationComponent[], prefix = "") => {
|
||||
for (const component of components) {
|
||||
if (!component.field) continue;
|
||||
const content = value[component.field];
|
||||
const field = prefix + component.field;
|
||||
if (component.optional === false && (content == null || content === "" || (Array.isArray(content) && content.length === 0))) {
|
||||
const isHidden = component.hide === true || component.hidden === true;
|
||||
if (!isHidden && component.optional === false && (content == null || content === "" || (Array.isArray(content) && content.length === 0))) {
|
||||
issues.push(issue("MISSING_FIELD", field, `缺少必填字段:${component.label || component.field}`));
|
||||
}
|
||||
if (typeof content === "string" && typeof component.maxLength === "number" && content.length > component.maxLength) {
|
||||
@@ -160,239 +169,276 @@ export function validateBillDraft(
|
||||
};
|
||||
checkComponents(form, [{ field: "specificationId", optional: false }, ...(options.components ?? [])]);
|
||||
|
||||
// 2. 描述长度由实际模板的 maxLength 决定,不假设所有模板均为 800。
|
||||
|
||||
// 3. 明细数量
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
if (details.length === 0) {
|
||||
issues.push(issue("NO_DETAILS", "details", "费用明细为空,至少需要一条明细"));
|
||||
return issues;
|
||||
// 2. dataLinkEdits(如行程规划)与申请单通用字段校验
|
||||
for (const dlField of collectDataLinkEditFields(form as Record<string, unknown>, options.components)) {
|
||||
const list = (form as Record<string, unknown>)[dlField];
|
||||
if (!Array.isArray(list)) continue;
|
||||
list.forEach((item, index) => {
|
||||
if (item !== null && typeof item === "object" && !Array.isArray(item)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(item, "dataLinkId")) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DATALINK_ID_KEY_MISSING",
|
||||
`${dlField}[${index}].dataLinkId`,
|
||||
`${dlField} 第 ${index + 1} 条缺少 dataLinkId 键(新建/复制草稿必须显式设为 null,否则审批通过后无法生成行程实例)`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 4. 本位币(以表头报销金额为准)
|
||||
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode
|
||||
|| details.find((detail) => detail.feeTypeForm?.amount?.standardStrCode)?.feeTypeForm?.amount?.standardStrCode;
|
||||
if (form.expenseMoney?.standardStrCode && form.payMoney?.standardStrCode && form.expenseMoney.standardStrCode !== form.payMoney.standardStrCode) {
|
||||
issues.push(issue("CURRENCY_MISMATCH", "payMoney.standardStrCode", "支付金额与报销金额本位币不一致"));
|
||||
}
|
||||
|
||||
// 5. 逐条明细
|
||||
const seenDetailNos = new Map<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 ?? {};
|
||||
checkComponents(ft, options.detailComponents?.[index] ?? [], `details[${index}].feeTypeForm.`);
|
||||
const position = index + 1;
|
||||
const label = `明细 #${ft.detailNo ?? position}`;
|
||||
|
||||
if (ft.detailStatus === "draft") {
|
||||
const period = (form as Record<string, unknown>).feeDatePeriod;
|
||||
if (period !== undefined && period !== null) {
|
||||
const periodObj = typeof period === "object" && !Array.isArray(period) ? (period as Record<string, unknown>) : undefined;
|
||||
const periodStart = periodObj ? toNumber(periodObj.start) : undefined;
|
||||
const periodEnd = periodObj ? toNumber(periodObj.end) : undefined;
|
||||
if (periodStart === undefined || periodEnd === undefined || periodEnd < periodStart) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_DRAFT_STATUS",
|
||||
`details[${index}].feeTypeForm.detailStatus`,
|
||||
`${label} 仍处于草稿状态(detailStatus=draft),提交前必须保存该明细`
|
||||
)
|
||||
issue("FEE_DATE_PERIOD_INVALID", "feeDatePeriod", "差旅起止日期(feeDatePeriod)缺失有效 start/end 或结束早于开始")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof ft.detailNo === "number") {
|
||||
const previous = seenDetailNos.get(ft.detailNo);
|
||||
if (previous !== undefined) {
|
||||
const reqMoneyRaw = (form as Record<string, unknown>).requisitionMoney as BillMoney | undefined;
|
||||
const reqMoney = moneyStandard(reqMoneyRaw);
|
||||
if (reqMoneyRaw !== undefined && reqMoney === undefined) {
|
||||
issues.push(issue("REQUISITION_MONEY_INVALID", "requisitionMoney", "申请预估金额缺失或不是合法数字"));
|
||||
}
|
||||
|
||||
// 3. 明细数量(报销单强制要求至少一条;申请单等非报销单允许无 details)
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
if (details.length === 0) {
|
||||
if (formType === "expense") {
|
||||
issues.push(issue("NO_DETAILS", "details", "费用明细为空,至少需要一条明细"));
|
||||
return issues;
|
||||
}
|
||||
} else {
|
||||
// 4. 本位币(以表头报销金额为准)
|
||||
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode
|
||||
|| details.find((detail) => detail.feeTypeForm?.amount?.standardStrCode)?.feeTypeForm?.amount?.standardStrCode;
|
||||
if (form.expenseMoney?.standardStrCode && form.payMoney?.standardStrCode && form.expenseMoney.standardStrCode !== form.payMoney.standardStrCode) {
|
||||
issues.push(issue("CURRENCY_MISMATCH", "payMoney.standardStrCode", "支付金额与报销金额本位币不一致"));
|
||||
}
|
||||
|
||||
// 5. 逐条明细
|
||||
const seenDetailNos = new Map<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 ?? {};
|
||||
checkComponents(ft, options.detailComponents?.[index] ?? [], `details[${index}].feeTypeForm.`);
|
||||
const position = index + 1;
|
||||
const label = `明细 #${ft.detailNo ?? position}`;
|
||||
|
||||
if (ft.detailStatus === "draft") {
|
||||
issues.push(
|
||||
issue(
|
||||
"DUPLICATE_DETAIL_NO",
|
||||
`details[${index}].feeTypeForm.detailNo`,
|
||||
`明细序号 ${ft.detailNo} 重复(第 ${previous + 1} 条与第 ${position} 条)`
|
||||
"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 {
|
||||
seenDetailNos.set(ft.detailNo, index);
|
||||
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 拦截)`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
// 外币明细: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.foreignStrCode`,
|
||||
`${label} 有外资金额但缺少 foreignStrCode`
|
||||
)
|
||||
);
|
||||
} else if (billCurrency && amount.foreignStrCode === billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_SAME_CURRENCY",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的外币币种与本位币相同(${billCurrency}),不应同时设置外币字段`,
|
||||
"warning"
|
||||
`${label} 的外币金额与汇率必须成对出现`
|
||||
)
|
||||
);
|
||||
}
|
||||
} else if (foreign !== undefined || rate !== undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_FIELDS_INCOMPLETE",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的外币金额与汇率必须成对出现`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 明细发票总额
|
||||
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
|
||||
if (ft.u_发票总金额 !== undefined && detailInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_INVOICE_TOTAL_INVALID",
|
||||
`details[${index}].feeTypeForm.u_发票总金额`,
|
||||
`${label} 的发票总金额缺失或不是合法数字`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
detailInvoiceSum += detailInvoiceTotal ?? 0;
|
||||
if (billCurrency && ft.u_发票总金额?.standardStrCode && ft.u_发票总金额.standardStrCode !== billCurrency) {
|
||||
// 明细发票总额
|
||||
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
|
||||
if (ft.u_发票总金额 !== undefined && detailInvoiceTotal === undefined) {
|
||||
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"
|
||||
"DETAIL_INVOICE_TOTAL_INVALID",
|
||||
`details[${index}].feeTypeForm.u_发票总金额`,
|
||||
`${label} 的发票总金额缺失或不是合法数字`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
seenInvoiceIds.set(invoiceId, index);
|
||||
detailInvoiceSum += detailInvoiceTotal ?? 0;
|
||||
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} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 6. 表头派生金额
|
||||
const expenseMoney = moneyStandard(form.expenseMoney);
|
||||
if (form.expenseMoney !== undefined && expenseMoney === undefined) {
|
||||
issues.push(
|
||||
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (expenseMoney !== undefined && hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"EXPENSE_TOTAL_MISMATCH",
|
||||
"expenseMoney.standard",
|
||||
`报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
// 发票去重
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const payMoney = moneyStandard(form.payMoney);
|
||||
if (form.payMoney !== undefined && payMoney === undefined) {
|
||||
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
|
||||
} else if (payMoney !== undefined && expenseMoney !== undefined) {
|
||||
const writtenOff = moneyStandard(form.writtenOffMoney) ?? 0;
|
||||
const expectedPay = expenseMoney - writtenOff;
|
||||
if (!nearlyEqual(payMoney, expectedPay, moneyTolerance)) {
|
||||
// 6. 表头派生金额
|
||||
const expenseMoney = moneyStandard(form.expenseMoney);
|
||||
if (form.expenseMoney !== undefined && expenseMoney === undefined) {
|
||||
issues.push(
|
||||
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (expenseMoney !== undefined && hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"PAY_TOTAL_MISMATCH",
|
||||
"payMoney.standard",
|
||||
`支付金额 ${payMoney} 与报销金额 ${expenseMoney} - 核销借款 ${writtenOff} = ${expectedPay.toFixed(2)} 不一致`
|
||||
"EXPENSE_TOTAL_MISMATCH",
|
||||
"expenseMoney.standard",
|
||||
`报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
|
||||
if (form.u_发票总金额 !== undefined && billInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (billInvoiceTotal !== undefined && !nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"INVOICE_TOTAL_MISMATCH",
|
||||
"u_发票总金额.standard",
|
||||
`单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
const payMoney = moneyStandard(form.payMoney);
|
||||
if (form.payMoney !== undefined && payMoney === undefined) {
|
||||
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
|
||||
} else if (payMoney !== undefined && 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)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (form.writtenOffMoney !== undefined && moneyStandard(form.writtenOffMoney) === undefined) {
|
||||
issues.push(issue("WRITTEN_OFF_MONEY_INVALID", "writtenOffMoney", "核销借款金额不合法"));
|
||||
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
|
||||
if (form.u_发票总金额 !== undefined && billInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (billInvoiceTotal !== undefined && !nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"INVOICE_TOTAL_MISMATCH",
|
||||
"u_发票总金额.standard",
|
||||
`单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (form.writtenOffMoney !== undefined && moneyStandard(form.writtenOffMoney) === undefined) {
|
||||
issues.push(issue("WRITTEN_OFF_MONEY_INVALID", "writtenOffMoney", "核销借款金额不合法"));
|
||||
}
|
||||
}
|
||||
|
||||
// 7. 日期
|
||||
@@ -438,7 +484,7 @@ export async function loadBillValidationOptions(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
form: BillDraftForm,
|
||||
specification?: { components: BillValidationComponent[] }
|
||||
specification?: { type?: string; components: BillValidationComponent[] }
|
||||
): Promise<ValidateOptions> {
|
||||
const resolveId = (reference: unknown): string => {
|
||||
const value = typeof reference === "string"
|
||||
@@ -449,18 +495,20 @@ export async function loadBillValidationOptions(
|
||||
}
|
||||
return value.trim();
|
||||
};
|
||||
const load = async (id: string): Promise<BillValidationComponent[]> => {
|
||||
const loadSpec = async (id: string) => {
|
||||
const spec = await getFormSpecification(client, corpId, id);
|
||||
if (!spec) throw new NotFoundError(`未找到单据或费用类型规格: ${id}`);
|
||||
return spec.components as BillValidationComponent[];
|
||||
return spec;
|
||||
};
|
||||
const headerId = resolveId(form.specificationId);
|
||||
const components = specification?.components ?? await load(headerId);
|
||||
const loadedHeader = specification ? undefined : await loadSpec(headerId);
|
||||
const components = (specification?.components ?? loadedHeader!.components) as BillValidationComponent[];
|
||||
const formType = specification?.type ?? loadedHeader?.type;
|
||||
const cache = new Map<string, Promise<BillValidationComponent[]>>();
|
||||
const detailComponents = await Promise.all((form.details ?? []).map((detail) => {
|
||||
const id = resolveId(detail.specificationId);
|
||||
if (!cache.has(id)) cache.set(id, load(id));
|
||||
if (!cache.has(id)) cache.set(id, loadSpec(id).then((spec) => spec.components as BillValidationComponent[]));
|
||||
return cache.get(id)!;
|
||||
}));
|
||||
return { components, detailComponents };
|
||||
return { components, detailComponents, formType };
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
import type { BillDraftForm, BillMoney, BillValidationComponent } from "./draft-validation.js";
|
||||
|
||||
const CST_OFFSET_MS = 8 * 60 * 60 * 1000;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
const HISTORICAL_FLOW_FIELDS = [
|
||||
"id",
|
||||
"code",
|
||||
"submitDate",
|
||||
"flowEndTime",
|
||||
"preApprovedNodeName",
|
||||
"preNodeApprovedTime",
|
||||
"rejectionNum",
|
||||
"printCount",
|
||||
"printState",
|
||||
"voucherNo",
|
||||
"voucherStatus",
|
||||
"voucherCreateTime",
|
||||
"onlyOwnerPrint",
|
||||
"ownerAndApproverPrintNodeFlag",
|
||||
] as const;
|
||||
|
||||
export interface DataLinkEditItem {
|
||||
dataLinkId?: string | null;
|
||||
dataLinkForm?: Record<string, unknown>;
|
||||
dataLinkTemplateId?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface CommonAndRequisitionEditOptions {
|
||||
title?: string;
|
||||
reason?: string;
|
||||
amount?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
components?: BillValidationComponent[];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** 判断字段值是否为 dataLinkEdits(如行程规划)条目数组。 */
|
||||
export function isDataLinkEditArray(value: unknown): value is DataLinkEditItem[] {
|
||||
if (!Array.isArray(value) || value.length === 0) return false;
|
||||
return value.every(
|
||||
(item) =>
|
||||
isRecord(item) &&
|
||||
("dataLinkForm" in item || typeof item.dataLinkTemplateId === "string")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一路由单据业务类型(expense / requisition / ...)。
|
||||
* 优先级:模板规格类型 > 流程 formType / form.type > 表单字段特征 > 兜底 expense。
|
||||
*/
|
||||
export function resolveBillFormType(
|
||||
form: BillDraftForm | Record<string, unknown> | undefined,
|
||||
options?: { specType?: string; flowFormType?: string }
|
||||
): string {
|
||||
const specType = options?.specType?.trim();
|
||||
if (specType) return specType;
|
||||
|
||||
const flowFormType = options?.flowFormType?.trim();
|
||||
if (flowFormType) return flowFormType;
|
||||
|
||||
const explicitType = typeof form?.type === "string" ? form.type.trim() : "";
|
||||
if (explicitType) return explicitType;
|
||||
|
||||
if (!form) return "expense";
|
||||
|
||||
if (
|
||||
Array.isArray(form.details) ||
|
||||
form.expenseMoney !== undefined ||
|
||||
form.payMoney !== undefined
|
||||
) {
|
||||
return "expense";
|
||||
}
|
||||
|
||||
if (
|
||||
form.requisitionMoney !== undefined ||
|
||||
form.requisitionDate !== undefined ||
|
||||
form.feeDatePeriod !== undefined ||
|
||||
Object.values(form).some((value) => isDataLinkEditArray(value))
|
||||
) {
|
||||
return "requisition";
|
||||
}
|
||||
|
||||
return "expense";
|
||||
}
|
||||
|
||||
/** 合并模板声明的 dataLinkEdits 字段与表单中实际存在的同类数组字段(去重)。 */
|
||||
export function collectDataLinkEditFields(
|
||||
form: Record<string, unknown>,
|
||||
components?: BillValidationComponent[]
|
||||
): string[] {
|
||||
const fields = new Set<string>();
|
||||
for (const component of components ?? []) {
|
||||
if (component.field && component.type === "dataLinkEdits") {
|
||||
fields.add(component.field);
|
||||
}
|
||||
}
|
||||
for (const [key, value] of Object.entries(form)) {
|
||||
if (isDataLinkEditArray(value)) {
|
||||
fields.add(key);
|
||||
}
|
||||
}
|
||||
return Array.from(fields);
|
||||
}
|
||||
|
||||
function parseStrictCstDate(dateStr: string, label: string): { year: number; month: number; day: number; startMs: number } {
|
||||
const trimmed = dateStr.trim();
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(trimmed);
|
||||
if (!match) {
|
||||
throw new ValidationError(`${label} 格式无效(需 YYYY-MM-DD):${dateStr}`);
|
||||
}
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
const probe = new Date(Date.UTC(year, month - 1, day));
|
||||
if (
|
||||
probe.getUTCFullYear() !== year ||
|
||||
probe.getUTCMonth() !== month - 1 ||
|
||||
probe.getUTCDate() !== day
|
||||
) {
|
||||
throw new ValidationError(`${label} 不是合法日历日期:${dateStr}`);
|
||||
}
|
||||
const startMs = Date.UTC(year, month - 1, day) - CST_OFFSET_MS;
|
||||
return { year, month, day, startMs };
|
||||
}
|
||||
|
||||
/** 按东八区 (+08:00) 解析起止日期,返回毫秒边界与含首尾天数。 */
|
||||
export function parseCstDateRange(
|
||||
startDate: string,
|
||||
endDate: string
|
||||
): { startDate: string; endDate: string; startMs: number; endMs: number; days: number } {
|
||||
const start = parseStrictCstDate(startDate, "开始日期");
|
||||
const end = parseStrictCstDate(endDate, "结束日期");
|
||||
const endMs = end.startMs + DAY_MS - 1;
|
||||
if (endMs < start.startMs) {
|
||||
throw new ValidationError(`结束日期 ${endDate.trim()} 不能早于开始日期 ${startDate.trim()}`);
|
||||
}
|
||||
const days = Math.round((end.startMs - start.startMs) / DAY_MS) + 1;
|
||||
return {
|
||||
startDate: startDate.trim(),
|
||||
endDate: endDate.trim(),
|
||||
startMs: start.startMs,
|
||||
endMs,
|
||||
days,
|
||||
};
|
||||
}
|
||||
|
||||
/** 返回当前东八区 (+08:00) 当天 00:00:00 的毫秒时间戳。 */
|
||||
export function todayStartCstMs(nowMs: number = Date.now()): number {
|
||||
const cst = new Date(nowMs + CST_OFFSET_MS);
|
||||
return Date.UTC(cst.getUTCFullYear(), cst.getUTCMonth(), cst.getUTCDate()) - CST_OFFSET_MS;
|
||||
}
|
||||
|
||||
/** 构造保留源货币元信息的本位币金额对象。 */
|
||||
export function buildCnyMoney(standard: string, source?: BillMoney): BillMoney {
|
||||
const base: BillMoney = isRecord(source) ? { ...source } : {};
|
||||
return {
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
standardSymbol: "¥",
|
||||
standardNumCode: "156",
|
||||
standardStrCode: "CNY",
|
||||
...base,
|
||||
standard,
|
||||
};
|
||||
}
|
||||
|
||||
/** 清理复制单据时的历史流转与只读字段。 */
|
||||
export function stripHistoricalFlowFields(form: Record<string, unknown>): void {
|
||||
for (const field of HISTORICAL_FLOW_FIELDS) {
|
||||
delete form[field];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置表单中所有 dataLinkEdits(如行程规划)条目的 dataLinkId 为显式 null。
|
||||
* 合思服务端审批通过后创建行程实例依赖该键显式存在且值为 null,绝不可 delete。
|
||||
*/
|
||||
export function resetDataLinkEditsForNewDraft(
|
||||
form: Record<string, unknown>,
|
||||
components?: BillValidationComponent[]
|
||||
): number {
|
||||
let count = 0;
|
||||
for (const field of collectDataLinkEditFields(form, components)) {
|
||||
const list = form[field];
|
||||
if (!Array.isArray(list)) continue;
|
||||
form[field] = list.map((item) => {
|
||||
if (!isRecord(item)) return item;
|
||||
count += 1;
|
||||
const cloned = structuredClone(item) as DataLinkEditItem;
|
||||
cloned.dataLinkId = null;
|
||||
return cloned;
|
||||
});
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
function hasFieldOrDeclaration(
|
||||
form: Record<string, unknown>,
|
||||
field: string,
|
||||
components?: BillValidationComponent[]
|
||||
): boolean {
|
||||
return field in form || Boolean(components?.some((item) => item.field === field));
|
||||
}
|
||||
|
||||
/** 对通用单据与差旅申请单应用标题、事由、金额与起止日期变更。 */
|
||||
export function applyCommonAndRequisitionEdits(
|
||||
form: Record<string, unknown>,
|
||||
options: CommonAndRequisitionEditOptions
|
||||
): void {
|
||||
if (options.title?.trim()) {
|
||||
form.title = options.title.trim();
|
||||
}
|
||||
if (options.reason !== undefined) {
|
||||
form.description = options.reason;
|
||||
}
|
||||
|
||||
if (options.amount !== undefined) {
|
||||
const trimmed = options.amount.trim();
|
||||
const num = Number(trimmed);
|
||||
if (!trimmed || !Number.isFinite(num) || num <= 0) {
|
||||
throw new ValidationError(`金额不合法(需大于 0 的数字):${options.amount}`);
|
||||
}
|
||||
form.requisitionMoney = buildCnyMoney(trimmed, form.requisitionMoney as BillMoney | undefined);
|
||||
if (hasFieldOrDeclaration(form, "u_申请额度", options.components)) {
|
||||
form["u_申请额度"] = buildCnyMoney(
|
||||
num.toFixed(2),
|
||||
form["u_申请额度"] as BillMoney | undefined
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const hasStart = options.startDate !== undefined;
|
||||
const hasEnd = options.endDate !== undefined;
|
||||
if (hasStart !== hasEnd) {
|
||||
throw new ValidationError("请同时指定 --start-date 和 --end-date(格式 YYYY-MM-DD)");
|
||||
}
|
||||
|
||||
if (hasStart && hasEnd) {
|
||||
const range = parseCstDateRange(options.startDate!, options.endDate!);
|
||||
form.feeDatePeriod = { start: range.startMs, end: range.endMs };
|
||||
if (hasFieldOrDeclaration(form, "u_差旅天数", options.components)) {
|
||||
form["u_差旅天数"] = String(range.days);
|
||||
}
|
||||
|
||||
for (const field of collectDataLinkEditFields(form, options.components)) {
|
||||
const list = form[field];
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const item of list) {
|
||||
if (!isRecord(item)) continue;
|
||||
if (!Object.prototype.hasOwnProperty.call(item, "dataLinkId")) {
|
||||
item.dataLinkId = null;
|
||||
}
|
||||
const dlf = item.dataLinkForm;
|
||||
if (!isRecord(dlf)) continue;
|
||||
for (const key of Object.keys(dlf)) {
|
||||
if (key.endsWith("_入住日期") || key.endsWith("_行程日期")) {
|
||||
dlf[key] = range.startMs;
|
||||
} else if (key.endsWith("_离店日期")) {
|
||||
dlf[key] = range.endMs;
|
||||
} else if (key.endsWith("_行程开始日期")) {
|
||||
dlf[key] = range.startDate;
|
||||
} else if (key.endsWith("_行程结束日期")) {
|
||||
dlf[key] = range.endDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { computeBillApprovalPlan, getFormSpecification, getRawBillFlow, submitBillFlow } from "./api.js";
|
||||
import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validation.js";
|
||||
import { assertBillDraftValid, loadBillValidationOptions, type BillDraftForm } from "./draft-validation.js";
|
||||
import { resolveBillFormType } from "./form-helpers.js";
|
||||
import type { BillPlanNode } from "./types.js";
|
||||
|
||||
/**
|
||||
* 纯接口提交单据草稿。
|
||||
@@ -11,7 +13,8 @@ import { assertBillDraftValid, loadBillValidationOptions } from "./draft-validat
|
||||
* 2. `POST /api/flow/v1/flows/$<flowId>?pushMessageCode=debug`
|
||||
* body: { name: "freeflow.submit", formType, form, nodes }
|
||||
*
|
||||
* 未指派审批人的节点必须由调用方通过 `--approver` 指定,绝不自动编造。
|
||||
* 未指派审批人的普通必填节点必须由调用方通过 `--approver` 指定,绝不自动编造;
|
||||
* ebot、自动跳过(skippedType != NO_SKIPPED)与条件/延迟计算节点原样回传。
|
||||
*/
|
||||
|
||||
export interface SubmitBillOptions {
|
||||
@@ -26,6 +29,20 @@ export interface SubmitBillResult {
|
||||
response: unknown;
|
||||
}
|
||||
|
||||
function nodeRequiresApprover(node: BillPlanNode): boolean {
|
||||
if (node.type === "ebot") return false;
|
||||
if (typeof node.skippedType === "string" && node.skippedType.trim() !== "" && node.skippedType !== "NO_SKIPPED") {
|
||||
return false;
|
||||
}
|
||||
if (typeof node.conditionalType === "string" && node.conditionalType.trim() !== "") {
|
||||
return false;
|
||||
}
|
||||
if (typeof node.laterCalcReason === "string" && node.laterCalcReason.trim() !== "") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function submitBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
@@ -50,14 +67,17 @@ export async function submitBillDraft(
|
||||
const spec = specificationId
|
||||
? await getFormSpecification(client, corpId, String(specificationId))
|
||||
: undefined;
|
||||
assertBillDraftValid(form, await loadBillValidationOptions(client, corpId, form, spec));
|
||||
assertBillDraftValid(form as BillDraftForm, await loadBillValidationOptions(client, corpId, form as BillDraftForm, spec));
|
||||
const configs = (spec as { configs?: Array<{ ability?: string; flowPlanConfigId?: string }> } | undefined)?.configs;
|
||||
const flowPlanConfigId = configs?.find((config) => config.ability === "flow")?.flowPlanConfigId;
|
||||
if (!flowPlanConfigId) {
|
||||
throw new ValidationError("模板缺少审批流配置(flowPlanConfigId),无法计算审批计划");
|
||||
}
|
||||
|
||||
const formType = String(form.type ?? flow.formType ?? "expense");
|
||||
const formType = resolveBillFormType(form as BillDraftForm, {
|
||||
specType: spec?.type,
|
||||
flowFormType: typeof flow.formType === "string" ? flow.formType : undefined,
|
||||
});
|
||||
const nodes = await computeBillApprovalPlan(client, corpId, flowId, flowPlanConfigId, form, formType);
|
||||
if (nodes.length === 0) {
|
||||
throw new ValidationError("审批计划为空,无法提交");
|
||||
@@ -65,7 +85,7 @@ export async function submitBillDraft(
|
||||
|
||||
const unassigned: string[] = [];
|
||||
for (const node of nodes) {
|
||||
if (node.type === "ebot") continue;
|
||||
if (!nodeRequiresApprover(node)) continue;
|
||||
const hasApprover =
|
||||
Boolean(node.approverId) || (Array.isArray(node.approverIds) && node.approverIds.length > 0);
|
||||
if (hasApprover) continue;
|
||||
|
||||
@@ -49,6 +49,7 @@ export const FormSpecificationComponentSchema = z
|
||||
optional: z.boolean().optional().default(true),
|
||||
editable: z.boolean().optional().default(true),
|
||||
hidden: z.boolean().optional().default(false),
|
||||
hide: z.boolean().optional(),
|
||||
isLinkageAssignment: z.boolean().optional().default(false),
|
||||
assignmentRule: z.string().nullable().optional(),
|
||||
priorityList: z.array(FormPriorityItemSchema).nullable().optional(),
|
||||
@@ -92,6 +93,9 @@ export interface BillPlanNode {
|
||||
type?: string;
|
||||
approverId?: unknown;
|
||||
approverIds?: unknown[];
|
||||
skippedType?: string | null;
|
||||
conditionalType?: string | null;
|
||||
laterCalcReason?: string | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { KyInstance } from "ky";
|
||||
import { createBillDraft, prepareBillDraft } from "./create.js";
|
||||
import { buildBillCopyForm, copyBillAsDraft } from "./copy.js";
|
||||
import { submitBillDraft } from "./submit.js";
|
||||
import { editBillDraft } from "./write.js";
|
||||
import { loadBillValidationOptions, validateBillDraft, type BillDraftForm } from "./draft-validation.js";
|
||||
import { AuthenticationError } from "../../core/errors.js";
|
||||
|
||||
@@ -218,4 +219,159 @@ describe("bill API write contracts", () => {
|
||||
headerMismatch.payMoney!.standardStrCode = "USD";
|
||||
expect(validateBillDraft(headerMismatch).map(issue => issue.field)).toContain("payMoney.standardStrCode");
|
||||
});
|
||||
|
||||
test("申请单复制与编辑保持 dataLinkId: null,并按 requisition 路由提交含条件/跳过节点的计划", async () => {
|
||||
const reqSource: BillDraftForm = {
|
||||
id: "ID_REQ",
|
||||
code: "S26003502",
|
||||
title: "旧差旅申请",
|
||||
description: "旧事由",
|
||||
specificationId: `reqSpec:${"b".repeat(32)}`,
|
||||
submitterId: "staff",
|
||||
requisitionDate: 1784563200000,
|
||||
feeDatePeriod: { start: 1784822400000, end: 1784995199999 },
|
||||
u_差旅天数: "2",
|
||||
requisitionMoney: { standard: "1000", standardStrCode: "CNY" },
|
||||
u_行程规划: [
|
||||
{
|
||||
dataLinkId: "OLD_DL_1",
|
||||
dataLinkTemplateId: "tpl-trip",
|
||||
dataLinkForm: { E_x_行程开始日期: "2026-07-24", E_x_行程结束日期: "2026-07-25" },
|
||||
},
|
||||
],
|
||||
};
|
||||
const writes: Array<{ url: string; json: any }> = [];
|
||||
const plans: any[] = [];
|
||||
const reqClient = {
|
||||
get: (url: string) => ({
|
||||
json: async () => {
|
||||
if (url.includes("specifications/")) {
|
||||
return {
|
||||
items: [
|
||||
{
|
||||
id: "reqSpec",
|
||||
name: "4.1日常差旅申请单",
|
||||
type: "requisition",
|
||||
configs: [{ ability: "flow", flowPlanConfigId: "plan-req" }],
|
||||
components: [
|
||||
{ field: "title", optional: false },
|
||||
{ field: "u_深度现场项目", optional: false, hide: true },
|
||||
{ field: "u_行程规划", type: "dataLinkEdits", optional: false },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (url.includes("withSpecificationVersioned")) {
|
||||
return {
|
||||
items: [
|
||||
{
|
||||
name: "个人报销",
|
||||
specifications: [{ id: `reqSpec:${"c".repeat(32)}`, originalId: "reqSpec", name: "4.1日常差旅申请单", type: "requisition", active: true }],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected GET ${url}`);
|
||||
},
|
||||
}),
|
||||
post: (url: string, payload: { json: any }) => ({
|
||||
json: async () => {
|
||||
if (url.endsWith("/flows/searchByCode")) {
|
||||
return { items: [{ id: "ID01REQ", form: reqSource }] };
|
||||
}
|
||||
if (url.includes("/flows/flowId/")) {
|
||||
const isDraft = url.includes("ID01DRAFT");
|
||||
return {
|
||||
value: {
|
||||
id: isDraft ? "ID01DRAFT" : "ID01REQ",
|
||||
state: isDraft ? "draft" : "paid",
|
||||
formType: "requisition",
|
||||
form: reqSource,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (url.endsWith("/plans/computed")) {
|
||||
plans.push(payload.json);
|
||||
return {
|
||||
value: {
|
||||
nodes: [
|
||||
{ id: "", name: "费用标准检查", type: "ebot" },
|
||||
{ id: "", name: "所属部门主管", type: "normal", approverId: "staff-boss" },
|
||||
{ id: "", name: "SVP加签", type: "normal", approverId: null, conditionalType: "RULE", laterCalcReason: "超标时审批" },
|
||||
{ id: "", name: "出纳支付", type: "normal", approverId: null, skippedType: "NO_ABILITY" },
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
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: "S26005900" } } };
|
||||
},
|
||||
}),
|
||||
} as unknown as KyInstance;
|
||||
|
||||
const copied = await copyBillAsDraft(reqClient, "corp", "S26003502", {
|
||||
title: "新差旅申请",
|
||||
reason: "新事由",
|
||||
startDate: "2026-12-04",
|
||||
endDate: "2026-12-05",
|
||||
});
|
||||
expect(copied.formType).toBe("requisition");
|
||||
expect(copied.tripCount).toBe(1);
|
||||
expect(writes[0].json.form.specificationId).toBe(`reqSpec:${"c".repeat(32)}`);
|
||||
expect(writes[0].json.form.expenseMoney).toBeUndefined();
|
||||
expect(writes[0].json.form.u_行程规划[0]).toHaveProperty("dataLinkId", null);
|
||||
|
||||
// 模拟待编辑草稿中行程缺失 dataLinkId 会被拦截,正常草稿允许 editBillDraft
|
||||
(reqSource.u_行程规划 as Array<Record<string, unknown>>)[0].dataLinkId = null;
|
||||
await editBillDraft(reqClient, "corp", "ID01DRAFT", { title: "修改后标题", reason: "修改后事由", amount: "1200" });
|
||||
expect(writes[1].url).toContain("flows/$ID01DRAFT");
|
||||
expect(writes[1].json.name).toBe("freeflow.edit");
|
||||
expect(writes[1].json.form.requisitionMoney.standard).toBe("1200");
|
||||
|
||||
// submitBillDraft 应识别 formType=requisition,并放行 ebot / RULE 条件节点 / NO_ABILITY 跳过节点
|
||||
await submitBillDraft(reqClient, "corp", "ID01DRAFT");
|
||||
expect(plans[0].formType).toBe("requisition");
|
||||
expect(writes[2].json.name).toBe("freeflow.submit");
|
||||
expect(writes[2].json.formType).toBe("requisition");
|
||||
expect(writes[2].json.nodes).toHaveLength(4);
|
||||
});
|
||||
|
||||
test("submitBillDraft 仍拦截没有 conditionalType/skippedType 的普通未指派节点,以及非 draft 草稿 edit", async () => {
|
||||
const { client, writes } = fixture();
|
||||
await expect(
|
||||
editBillDraft(
|
||||
{
|
||||
post: (url: string) => ({
|
||||
json: async () =>
|
||||
url.includes("/flows/flowId/")
|
||||
? { value: { id: "ID01PAID", state: "paid", form: form() } }
|
||||
: { items: [] },
|
||||
}),
|
||||
} as unknown as KyInstance,
|
||||
"corp",
|
||||
"ID01PAID",
|
||||
{ title: "x" }
|
||||
)
|
||||
).rejects.toThrow("仅允许编辑 draft 草稿");
|
||||
|
||||
const unassignedClient = {
|
||||
...client,
|
||||
post: (url: string, payload: { json: any }) => {
|
||||
if (url.endsWith("/plans/computed")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
value: { nodes: [{ id: "n1", name: "部门主管", type: "normal", approverId: null, skippedType: "NO_SKIPPED" }] },
|
||||
}),
|
||||
};
|
||||
}
|
||||
return (client as any).post(url, payload);
|
||||
},
|
||||
} as unknown as KyInstance;
|
||||
await expect(submitBillDraft(unassignedClient, "corp", "f")).rejects.toThrow("未指派审批人");
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
});
|
||||
+166
-3
@@ -1,5 +1,18 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { deleteBillFlow } from "./api.js";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { deleteBillFlow, getRawBillFlow, updateBillFlow } from "./api.js";
|
||||
import {
|
||||
assertBillDraftValid,
|
||||
loadBillValidationOptions,
|
||||
type BillDraftForm,
|
||||
type BillMoney,
|
||||
type BillValidationComponent,
|
||||
} from "./draft-validation.js";
|
||||
import {
|
||||
applyCommonAndRequisitionEdits,
|
||||
collectDataLinkEditFields,
|
||||
resolveBillFormType,
|
||||
} from "./form-helpers.js";
|
||||
|
||||
/**
|
||||
* 单据草稿写入动作(均通过 `POST /api/flow/v1/flows/$<flowId>` + `name` 区分)。
|
||||
@@ -8,10 +21,160 @@ import { deleteBillFlow } from "./api.js";
|
||||
* - `freeflow.edit` —— 保存草稿
|
||||
* - `freeflow.submit` —— 提交送审(需先计算审批计划并把 nodes 带回)
|
||||
* - `freeflow.delete` —— 删除草稿
|
||||
*
|
||||
* 本文件目前只实现风险最低、已在生产草稿上验证过的删除动作。
|
||||
*/
|
||||
|
||||
export interface EditBillOptions {
|
||||
title?: string;
|
||||
reason?: string;
|
||||
amount?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
components?: BillValidationComponent[];
|
||||
}
|
||||
|
||||
export interface PreparedBillEdit {
|
||||
flowId: string;
|
||||
code: string;
|
||||
formType: string;
|
||||
beforeTitle: string;
|
||||
afterTitle: string;
|
||||
beforeDescription: string;
|
||||
afterDescription: string;
|
||||
amount: string;
|
||||
tripCount: number;
|
||||
feeDatePeriod?: { start?: number; end?: number };
|
||||
form: BillDraftForm;
|
||||
}
|
||||
|
||||
export interface EditBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
title: string;
|
||||
description: string;
|
||||
formType: string;
|
||||
amount: string;
|
||||
tripCount: number;
|
||||
form: BillDraftForm;
|
||||
}
|
||||
|
||||
function resolveDisplayAmount(form: BillDraftForm, formType: string): string {
|
||||
if (formType === "expense") {
|
||||
return String(form.expenseMoney?.standard ?? "0");
|
||||
}
|
||||
const reqMoney = (form as Record<string, unknown>).requisitionMoney as BillMoney | undefined;
|
||||
const quotaMoney = (form as Record<string, unknown>)["u_申请额度"] as BillMoney | undefined;
|
||||
return String(reqMoney?.standard ?? quotaMoney?.standard ?? "0");
|
||||
}
|
||||
|
||||
function countTrips(form: Record<string, unknown>, components?: BillValidationComponent[]): number {
|
||||
let total = 0;
|
||||
for (const field of collectDataLinkEditFields(form, components)) {
|
||||
const list = form[field];
|
||||
if (Array.isArray(list)) total += list.length;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/** 纯函数:基于现有草稿 form 构造更新后的草稿 form。 */
|
||||
export function buildBillEditForm(
|
||||
source: BillDraftForm,
|
||||
options: EditBillOptions
|
||||
): BillDraftForm {
|
||||
const hasAnyChange =
|
||||
options.title !== undefined ||
|
||||
options.reason !== undefined ||
|
||||
options.amount !== undefined ||
|
||||
options.startDate !== undefined ||
|
||||
options.endDate !== undefined;
|
||||
if (!hasAnyChange) {
|
||||
throw new ValidationError("请至少指定一项要修改的字段(--title / --reason / --amount / --start-date & --end-date)");
|
||||
}
|
||||
|
||||
const form = structuredClone(source) as BillDraftForm;
|
||||
const formType = resolveBillFormType(form);
|
||||
if (options.amount !== undefined && formType === "expense") {
|
||||
throw new ValidationError("报销单暂不支持通过 --amount 直接修改表头金额,请修改费用明细后保存");
|
||||
}
|
||||
|
||||
applyCommonAndRequisitionEdits(form as Record<string, unknown>, options);
|
||||
return form;
|
||||
}
|
||||
|
||||
/** 读取并校验待编辑草稿(仅允许 draft 状态),用于预演与正式写入共享。 */
|
||||
export async function prepareBillEdit(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: EditBillOptions
|
||||
): Promise<PreparedBillEdit> {
|
||||
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 flowId = String(flow.id ?? "");
|
||||
if (!flowId) throw new NotFoundError("单据缺少流程 ID");
|
||||
if (flow.state !== "draft") {
|
||||
throw new ValidationError(`单据当前状态为 ${String(flow.state ?? "unknown")},仅允许编辑 draft 草稿`);
|
||||
}
|
||||
|
||||
const validationOptions = await loadBillValidationOptions(client, corpId, sourceForm);
|
||||
const flowFormType = typeof flow.formType === "string" ? flow.formType : undefined;
|
||||
const formType = resolveBillFormType(sourceForm, {
|
||||
specType: validationOptions.formType,
|
||||
flowFormType,
|
||||
});
|
||||
|
||||
const form = buildBillEditForm(sourceForm, {
|
||||
...options,
|
||||
components: validationOptions.components,
|
||||
});
|
||||
|
||||
assertBillDraftValid(form, { ...validationOptions, formType });
|
||||
|
||||
const formRecord = form as Record<string, unknown>;
|
||||
const period = formRecord.feeDatePeriod as { start?: number; end?: number } | undefined;
|
||||
|
||||
return {
|
||||
flowId,
|
||||
code: String(formRecord.code ?? target),
|
||||
formType,
|
||||
beforeTitle: String(sourceForm.title ?? ""),
|
||||
afterTitle: String(form.title ?? ""),
|
||||
beforeDescription: String(sourceForm.description ?? ""),
|
||||
afterDescription: String(form.description ?? ""),
|
||||
amount: resolveDisplayAmount(form, formType),
|
||||
tripCount: countTrips(formRecord, validationOptions.components),
|
||||
...(period ? { feeDatePeriod: { start: period.start, end: period.end } } : {}),
|
||||
form,
|
||||
};
|
||||
}
|
||||
|
||||
/** 更新并保存草稿单据(`freeflow.edit`)。仅允许修改 draft 状态单据。 */
|
||||
export async function editBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: EditBillOptions
|
||||
): Promise<EditBillResult> {
|
||||
const prepared = await prepareBillEdit(client, corpId, target, options);
|
||||
const value = await updateBillFlow(client, corpId, prepared.flowId, prepared.form);
|
||||
const snapshot = (value.form ?? {}) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
flowId: String(value.id ?? prepared.flowId),
|
||||
code: String(snapshot.code ?? prepared.code),
|
||||
title: String(snapshot.title ?? prepared.afterTitle),
|
||||
description: String(snapshot.description ?? prepared.afterDescription),
|
||||
formType: prepared.formType,
|
||||
amount: prepared.amount,
|
||||
tripCount: prepared.tripCount,
|
||||
form: prepared.form,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除草稿单据及其费用明细(`freeflow.delete`)。
|
||||
* 仅允许对 `draft` 状态单据调用——调用方需自行校验状态。
|
||||
|
||||
Reference in new issue
Block a user