Merge pull request #144 from yunyingk/feat/bill-draft-ops
CI / validate (push) Has been cancelled
CI / validate (push) Has been cancelled
feat(bill): 修复单号查询并新增草稿校验/复制/删除
This commit is contained in:
27 files changed
+2936
-565
No files matched your search
Vendored
+635
-549
File diff suppressed because it is too large.
Load diff
@@ -72,6 +72,14 @@ metadata:
|
||||
1. **导出/映射**:先将节点代码提取至本地独立文件(如 `scripts/clean.js` 或 `scripts/amortize.mvel`),或使用 `hose-use workflow node get <pipelineId> <nodeName> > ./scripts/xxx.mvel`;
|
||||
2. **微创修改(Diff Edit)**:在本地文件上使用编辑工具进行精准、局部的差异修改(仅消耗几行 diff 的极少 Token);
|
||||
3. **一键同步**:使用 `hose-use workflow node edit <pipelineId> <nodeName> --code-file=./scripts/xxx.mvel --yes`(或 `node add ... --code-file=...`)通过文件流同步至云端。
|
||||
15. **附件命名与用户协商(Attachment Naming is a Human Decision)**:
|
||||
- 附件文件名属于企业业务习惯,**CLI 不设默认命名规则、不强制格式**;
|
||||
- 上传或重命名附件前,Agent 必须先与用户确认文件名——可以直接沿用原文件名,也可以由用户指定(如"类型-金额/期间-日期");
|
||||
- **不要自行套用历史单据的命名格式**,也不要因为命名与旧单不同而判定错误。
|
||||
16. **业务输入必须来自用户(Never Invent Business Inputs)**:
|
||||
- 驳回原因、转交/加签审批人、提交/撤回/删除、金额与期间等关键业务内容,**必须由用户明确提供或确认**;
|
||||
- **严禁自行编造**驳回意见、审批人、金额、期间等业务输入,也不要用"测试环境驳回(CLI 验证)"之类的占位文案代替;
|
||||
- 用户没有给出时,先停下来询问;宁可多问一句,也不要替客户写业务内容。
|
||||
|
||||
---
|
||||
|
||||
@@ -106,6 +114,12 @@ metadata:
|
||||
| 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 / 单据模板联动规格 | `hose-use bill schema`, `hose-use bill spec <specificationId>` | [references/bill.md](references/bill.md) |
|
||||
| 草稿字段一致性校验(金额/币种/发票总额/明细草稿状态) | `hose-use bill validate <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据模板列表(默认仅启用,与页面快速新建同源) | `hose-use bill templates [--all] [--keyword=...]` | [references/bill.md](references/bill.md) |
|
||||
| 按模板创建单据草稿(不提交) | `hose-use bill create --template <模板ID> [--title] [--amount] [--reason] --yes` | [references/bill.md](references/bill.md) |
|
||||
| 提交单据送审 | `hose-use bill submit <单号|ID> [--approver=<员工>] --yes` | [references/bill.md](references/bill.md) |
|
||||
| 复制单据为新草稿(清空发票绑定,不提交) | `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] --yes` | [references/bill.md](references/bill.md) |
|
||||
| 删除草稿单据(仅 draft 状态) | `hose-use bill delete <单号|ID> --yes` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose-use contact search`, `hose-use contact list`, `hose-use contact get` | [references/contact.md](references/contact.md) |
|
||||
| 待办中心 / 已审批 / 我发起的 / 审批记录 / 抄送 | `hose-use task todo`, `hose-use task submitted`, `hose-use task records`, `hose-use task cc` | [references/task.md](references/task.md) |
|
||||
| 应用管理 (桌面端工作台开通的用车/套件/制度/自建前台应用) | `hose-use app list [--keyword]`, `hose-use app get <应用>` | [references/workflow.md](references/workflow.md) |
|
||||
@@ -167,6 +181,14 @@ hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并写明
|
||||
hose-use bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名
|
||||
hose-use bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签
|
||||
hose-use bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论
|
||||
hose-use bill templates # 查看当前可见的启用模板(按分组)
|
||||
hose-use bill templates --all --keyword=报销 # 含停用 + 关键字过滤
|
||||
hose-use bill create --template ID01ok2mM0IroP --amount 0.01 --yes # 按模板建草稿
|
||||
hose-use bill submit B26000019 --approver 沈玥妍 --yes # 提交送审
|
||||
hose-use bill validate B26015505 # 校验草稿派生字段(金额/币种/发票总额)
|
||||
hose-use bill copy B26015505 --title "副本" --dry-run # 预览复制(默认保留附件)
|
||||
hose-use bill copy B26015505 --title "副本" --yes # 复制为新草稿(不提交)
|
||||
hose-use bill delete B26015505 --yes # 删除 draft 草稿(已提交单据会被拒绝)
|
||||
hose-use bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型
|
||||
hose-use bill relations S26000001 # 追溯冲借款、事前申请和合同关联
|
||||
hose-use bill budget S26000001 # 查看单据预算超限和预算接口状态
|
||||
|
||||
@@ -166,7 +166,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"sync-from-seal": "sync-seal",
|
||||
"import-seal": "sync-seal"
|
||||
},
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
flags: { ...flagList("a add all as-hose demo elevate elevate-hose f force migrate-all no-elevate overwrite p persist plain prod production r refresh reveal save save-staff t test upgrade-all verify offline cached", "boolean"), ...flagList("app-key app-security appKey appSecurity base-url baseUrl corp corp-id corpId data days domain e env expire expires expires-in expiresIn filter id k key key-id keyId keyword link name operator page-type pageType password proxyStaffBizId q query role roleDefId seal-dir sealDir secret staff staff-id staff-name staff-phone staffId staffName staffPhone ttl url user", "value") }
|
||||
},
|
||||
"config": {
|
||||
"summary": "全局运行模式与路径配置",
|
||||
@@ -295,7 +295,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"relations": "查看关联单据",
|
||||
"attachments": "列出附件",
|
||||
"download": "下载附件",
|
||||
"link": "生成单据详情链接"
|
||||
"link": "生成单据详情链接",
|
||||
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
|
||||
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
|
||||
"delete": "删除草稿单据(仅 draft,需 --yes)",
|
||||
"templates": "查看单据模板(默认仅启用,--all 含停用)",
|
||||
"create": "按模板创建单据草稿(不提交)",
|
||||
"submit": "提交单据送审(会进入审批流)"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
@@ -339,7 +345,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
},
|
||||
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
|
||||
flags: { ...flagList("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 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": "审批流全域透视与穿透诊断",
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import { buildBillCopyForm, copyBillAsDraft } from "../../../domains/bill/copy.js";
|
||||
import type { BillDraftForm } from "../../../domains/bill/draft-validation.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill copy <单号|ID> [--title=...] [--drop-attachments] [--dry-run] --yes`
|
||||
*
|
||||
* 纯接口复制:读取服务端最新表单 → 清空发票绑定/重算金额 → 创建新草稿。
|
||||
* 只创建草稿,不提交。
|
||||
*/
|
||||
export async function handleCopy(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要复制的单号或 ID: hose-use bill copy <单号|ID> [--title=...] --yes");
|
||||
}
|
||||
|
||||
const title = stringOption(parsed.options, ["title"]);
|
||||
const keepAttachments = !booleanOption(parsed.options, ["drop-attachments", "dropAttachments"]);
|
||||
const client = await ctx.getClient();
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined;
|
||||
if (!form) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据,无法复制\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
const copy = buildBillCopyForm(form, { title, keepAttachments });
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
dryRun: true,
|
||||
source: target,
|
||||
sourceTitle: form.title,
|
||||
title: copy.title,
|
||||
detailCount: copy.details?.length ?? 0,
|
||||
expenseMoney: copy.expenseMoney?.standard,
|
||||
keepAttachments,
|
||||
invoicesCleared: true,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 复制单据(dry-run,未创建) ======\n` +
|
||||
` 源单 : ${target}(${form.title ?? "-"})\n` +
|
||||
` 新标题 : ${copy.title ?? "-"}\n` +
|
||||
` 明细 : ${copy.details?.length ?? 0} 条\n` +
|
||||
` 金额 : ${copy.expenseMoney?.standard ?? "0"} CNY\n` +
|
||||
` 附件 : ${keepAttachments ? "保留" : "清空"}\n` +
|
||||
` 发票 : 清空绑定,发票总额归零\n` +
|
||||
`\n提示: 确认无误后追加 --yes 执行创建(仍为草稿,不会提交)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const result = await copyBillAsDraft(client, corpId, target, { title, keepAttachments });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
source: target,
|
||||
flowId: result.flowId,
|
||||
code: result.code,
|
||||
title: result.title,
|
||||
detailCount: result.detailCount,
|
||||
expenseMoney: result.expenseMoney,
|
||||
submitted: false,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`复制成功(已创建草稿,未提交)\n` +
|
||||
` 新单号 : ${result.code}\n` +
|
||||
` 单据 ID : ${result.flowId}\n` +
|
||||
` 标题 : ${result.title}\n` +
|
||||
` 明细 : ${result.detailCount} 条 / ${result.expenseMoney} CNY\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { createBillDraft } from "../../../domains/bill/create.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill create --template <模板ID> [--title=...] [--amount=0.01] [--reason=...] [--dry-run] --yes`
|
||||
*
|
||||
* 纯接口创建草稿:最小表头 + 一条费用明细,创建后不提交。
|
||||
*/
|
||||
export async function handleCreate(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const templateId = stringOption(parsed.options, ["template", "spec", "specification"]);
|
||||
if (!templateId) {
|
||||
throw new Error("请通过 --template 指定单据模板 ID: hose-use bill create --template <ID> --yes");
|
||||
}
|
||||
const title = stringOption(parsed.options, ["title"]);
|
||||
const amount = stringOption(parsed.options, ["amount"]) ?? "0.01";
|
||||
const reason = stringOption(parsed.options, ["reason"]);
|
||||
const feeTypeName = stringOption(parsed.options, ["fee-type", "feeType"]);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
const preview = { template: templateId, title: title ?? "(模板名称)", amount, reason: reason ?? "", feeType: feeTypeName ?? "简单费用" };
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ dryRun: true, ...preview }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 创建单据(dry-run,未创建) ======\n` +
|
||||
` 模板 : ${preview.template}\n` +
|
||||
` 标题 : ${preview.title}\n` +
|
||||
` 金额 : ${preview.amount} CNY\n` +
|
||||
` 费用类型: ${preview.feeType}\n` +
|
||||
` 事由 : ${preview.reason || "-"}\n` +
|
||||
`\n提示: 追加 --yes 执行创建(仍为草稿,不会提交)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const result = await createBillDraft(await ctx.getClient(), corpId, {
|
||||
templateId,
|
||||
title,
|
||||
amount,
|
||||
reason,
|
||||
feeTypeName,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ ...result, submitted: false }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`创建成功(草稿,未提交)\n` +
|
||||
` 单号 : ${result.code}\n` +
|
||||
` 流程 ID : ${result.flowId}\n` +
|
||||
` 标题 : ${result.title}\n` +
|
||||
` 金额 : ${result.amount} CNY(${result.feeType})\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import { deleteBillDraft } from "../../../domains/bill/write.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill delete <单号|ID> [--dry-run] --yes`
|
||||
*
|
||||
* 仅允许删除 `draft` 状态单据(`freeflow.delete`)。
|
||||
* 已提交/审批中/已支付的单据会被拒绝,避免误删真实业务单据。
|
||||
*/
|
||||
export async function handleDelete(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要删除的单号或 ID: hose-use bill delete <单号|ID> --yes");
|
||||
}
|
||||
|
||||
const client = await ctx.getClient();
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : undefined;
|
||||
|
||||
if (!flow || !form) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const flowId = String(flow.id ?? "");
|
||||
const code = String(form.code ?? target);
|
||||
const state = String(flow.state ?? "");
|
||||
if (state !== "draft") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr:
|
||||
`[拒绝删除] 单据 ${code} 当前状态为 ${state || "unknown"},仅允许删除 draft 草稿。\n` +
|
||||
`已提交单据请走撤回/作废流程,避免误删真实业务数据。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ dryRun: true, code, flowId, state }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 删除单据(dry-run,未执行) ======\n` +
|
||||
` 单号 : ${code}\n` +
|
||||
` 流程 ID : ${flowId}\n` +
|
||||
` 状态 : ${state}\n` +
|
||||
`\n提示: 确认无误后追加 --yes 执行删除\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
await deleteBillDraft(client, corpId, flowId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ deleted: true, code, flowId }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return { stdout: `删除成功\n 单号: ${code}\n 流程 ID: ${flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -5,6 +5,12 @@ import { handleList, handleGet, handleTrace } from "./search.js";
|
||||
import { handleFlow, handleRisk, handleBudget } from "./flow.js";
|
||||
import { handleRefs, handleRelations, handleAttachments, handleDownload } from "./related.js";
|
||||
import { handleSchema, handleLink, handleSpec } from "./meta.js";
|
||||
import { handleValidate } from "./validate.js";
|
||||
import { handleCopy } from "./copy.js";
|
||||
import { handleDelete } from "./delete.js";
|
||||
import { handleTemplates } from "./templates.js";
|
||||
import { handleCreate } from "./create.js";
|
||||
import { handleSubmit } from "./submit.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -104,7 +110,36 @@ export async function handleBillCommand(
|
||||
case "specification":
|
||||
return handleSpec(ctx);
|
||||
|
||||
case "validate":
|
||||
case "check":
|
||||
case "lint":
|
||||
return handleValidate(ctx);
|
||||
|
||||
case "copy":
|
||||
case "duplicate":
|
||||
case "clone":
|
||||
return handleCopy(ctx);
|
||||
|
||||
case "delete":
|
||||
case "rm":
|
||||
case "remove":
|
||||
return handleDelete(ctx);
|
||||
|
||||
case "templates":
|
||||
case "template":
|
||||
case "specs":
|
||||
case "spec-list":
|
||||
return handleTemplates(ctx);
|
||||
|
||||
case "create":
|
||||
case "new":
|
||||
return handleCreate(ctx);
|
||||
|
||||
case "submit":
|
||||
case "send":
|
||||
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 <单号>`);
|
||||
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`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
|
||||
import { submitBillDraft } from "../../../domains/bill/submit.js";
|
||||
import { isDryRun } from "../../mutation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill submit <单号|ID> [--approver=<员工>] [--dry-run] --yes`
|
||||
*
|
||||
* 纯接口提交:计算审批计划 → 补齐未指派审批人 → freeflow.submit。
|
||||
*/
|
||||
export async function handleSubmit(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 submit <单号|ID> [--approver=<员工>] --yes");
|
||||
}
|
||||
const approverRaw = stringOption(parsed.options, ["approver", "approver-id", "staff"]);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ dryRun: true, target, approver: approverRaw ?? null }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`====== 提交单据(dry-run,未提交) ======\n` +
|
||||
` 目标 : ${target}\n` +
|
||||
` 审批人 : ${approverRaw ?? "(使用计划中已指派的人)"}\n` +
|
||||
`\n提示: 追加 --yes 执行提交(会真实进入审批流)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.requireWriteConfirmation();
|
||||
const client = await ctx.getClient();
|
||||
let approverId: string | undefined;
|
||||
if (approverRaw) {
|
||||
const ids = await resolveBillStaffIds(client, corpId, [approverRaw]);
|
||||
approverId = ids[0];
|
||||
}
|
||||
const result = await submitBillDraft(client, corpId, target, { approverId });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
return {
|
||||
stdout:
|
||||
`提交成功(已进入审批流)\n` +
|
||||
` 单号 : ${result.code}\n` +
|
||||
` 流程 ID : ${result.flowId}\n` +
|
||||
` 节点数 : ${result.nodeCount}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { listBillTemplates } from "../../../domains/bill/templates.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill templates [--all] [--keyword=...]`
|
||||
*
|
||||
* 默认返回当前身份可见且启用中的模板(与页面「快速新建单据」同源、同分组);
|
||||
* `--all` 才会带出停用模板。
|
||||
*/
|
||||
export async function handleTemplates(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const includeInactive = booleanOption(parsed.options, ["all"]);
|
||||
const keyword = (stringOption(parsed.options, ["keyword", "k", "q", "query"]) ?? "").trim();
|
||||
|
||||
const result = await listBillTemplates(await ctx.getClient(), corpId, { includeInactive });
|
||||
let groups = result.groups;
|
||||
if (keyword) {
|
||||
groups = groups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
specifications: group.specifications.filter((spec) => spec.name.includes(keyword)),
|
||||
}))
|
||||
.filter((group) => group.specifications.length > 0);
|
||||
}
|
||||
const total = groups.reduce((sum, group) => sum + group.specifications.length, 0);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
includeInactive,
|
||||
total,
|
||||
inactive: result.inactive,
|
||||
groups,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines: string[] = [
|
||||
`====== 单据模板(${corp.name} | ${groups.length} 组 / ${total} 个${includeInactive ? ",含停用" : ""})======`,
|
||||
"",
|
||||
];
|
||||
for (const group of groups) {
|
||||
lines.push(`${group.name || "未分组"}`);
|
||||
for (const spec of group.specifications) {
|
||||
const inactiveMark = spec.active ? "" : "(已停用)";
|
||||
lines.push(` - ${spec.name}${inactiveMark} [${spec.type}] ID: ${spec.id}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
if (!includeInactive) {
|
||||
lines.push("提示: 追加 --all 可查看包含停用模板的全量列表");
|
||||
}
|
||||
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { getRawBillFlow } from "../../../domains/bill/tools.js";
|
||||
import {
|
||||
formatValidationIssues,
|
||||
validateBillDraft,
|
||||
type BillDraftForm,
|
||||
} from "../../../domains/bill/draft-validation.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
/**
|
||||
* `hose-use bill validate <单号|ID>`
|
||||
*
|
||||
* 读取单据的原始表单,校验派生字段(金额/币种/发票总额/明细草稿状态)是否自洽。
|
||||
* 这是写入前的最后一道闸门:合思服务端只做弱校验,币种混加、发票总额不同步都能存进去。
|
||||
*/
|
||||
export async function handleValidate(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要校验的单号或 ID: hose-use bill validate <单号|ID>");
|
||||
}
|
||||
|
||||
const raw = await getRawBillFlow(await ctx.getClient(), corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as BillDraftForm) : undefined;
|
||||
|
||||
if (!flow || !form) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const issues = validateBillDraft(form);
|
||||
const errors = issues.filter((item) => item.severity === "error");
|
||||
const warnings = issues.filter((item) => item.severity === "warning");
|
||||
const billCode = typeof form.title === "string" ? form.title : target;
|
||||
const code = typeof (form as Record<string, unknown>).code === "string"
|
||||
? String((form as Record<string, unknown>).code)
|
||||
: target;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
found: true,
|
||||
corpId,
|
||||
code,
|
||||
title: billCode,
|
||||
ok: errors.length === 0,
|
||||
errorCount: errors.length,
|
||||
warningCount: warnings.length,
|
||||
issues,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: errors.length === 0 ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
const header =
|
||||
`====== 单据校验 (${code}) ======\n` +
|
||||
` 企业 : ${corp.name}\n` +
|
||||
` 标题 : ${billCode}\n` +
|
||||
` 结论 : ${errors.length === 0 ? "✅ 通过" : "❌ 未通过"}(错误 ${errors.length} / 警告 ${warnings.length})\n`;
|
||||
const body = issues.length > 0 ? formatValidationIssues(issues) : " ✅ 派生字段与必填项一致";
|
||||
return {
|
||||
stdout: `${header}\n${body}\n`,
|
||||
stderr: "",
|
||||
exitCode: errors.length === 0 ? 0 : 1,
|
||||
};
|
||||
}
|
||||
@@ -48,7 +48,7 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
expect(data.runtime.configFile).toBeDefined();
|
||||
});
|
||||
|
||||
test("hose-use status 与 whoami 别名成功解析至 context", async () => {
|
||||
test("hose-use status 解析至 context,whoami 输出逐企业执行身份", async () => {
|
||||
const resStatus = await runCli(["status", "--json"]);
|
||||
expect(resStatus.exitCode).toBe(0);
|
||||
const dataStatus = JSON.parse(resStatus.stdout);
|
||||
@@ -57,7 +57,7 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
const resWhoami = await runCli(["whoami", "--json"]);
|
||||
expect(resWhoami.exitCode).toBe(0);
|
||||
const dataWhoami = JSON.parse(resWhoami.stdout);
|
||||
expect(dataWhoami.tool).toBe("hose-use");
|
||||
expect(Array.isArray(dataWhoami.corporations)).toBe(true);
|
||||
});
|
||||
|
||||
test("hose-aipro status 输出 AI PRO 专属上下文", async () => {
|
||||
|
||||
@@ -10,11 +10,17 @@ import { ApprovalRepository } from "../../domains/approval/index.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { handleWhoami } from "./corps/whoami.js";
|
||||
|
||||
export async function handleContextCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
// `whoami` 输出按企业逐一列出当前执行身份;`context/status` 保留全局诊断。
|
||||
const invoked = (parsed.raw ?? []).find((arg) => !arg.startsWith("-"));
|
||||
if (invoked?.toLowerCase() === "whoami") {
|
||||
return handleWhoami(parsed, runtime);
|
||||
}
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
const allCorps = runtime.corpContext.listCorps();
|
||||
const activeAccount = getActiveAccount();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { stringOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleSearch } from "./query.js";
|
||||
import { handleSwitch, handleCurrent } from "./context.js";
|
||||
import { handleWhoami } from "./whoami.js";
|
||||
import { handleGenerateCorpLink, handleAddLink } from "./link.js";
|
||||
import { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
import { handleProbeHose, handleHoseStaffs } from "./probe.js";
|
||||
@@ -36,8 +37,11 @@ export async function handleCorpsCommand(
|
||||
case "switch":
|
||||
case "use":
|
||||
return handleSwitch(parsed, runtime);
|
||||
case "current":
|
||||
case "whoami":
|
||||
case "identities":
|
||||
case "identity":
|
||||
return handleWhoami(parsed, runtime);
|
||||
case "current":
|
||||
case "status":
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
|
||||
@@ -233,6 +233,7 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
formatCorpEnvLabel(c.env),
|
||||
c.id,
|
||||
c.name,
|
||||
c.staffName || "-",
|
||||
c.staffId,
|
||||
formatSourceLabel(c.source, c.hasOpenApi),
|
||||
formatExpiresAt(c.expiresAt, c.persistent, c.hasOpenApi ? "openapi" : c.source),
|
||||
@@ -240,7 +241,7 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "环境", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
["#", "环境", "企业 ID", "企业名称", "员工姓名", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
rows
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { loadCorpConfigs } from "../../../core/config/loader.js";
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { booleanOption } from "../../parser.js";
|
||||
import { formatSourceLabel, printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
/**
|
||||
* `hose-use whoami` — 按企业逐行显示当前执行身份。
|
||||
*
|
||||
* 名称以在线 `staffs/me` 为准(配置里只存工号即可);
|
||||
* `--offline` 时退回本地缓存的 staffName(没有则显示 -)。
|
||||
*/
|
||||
|
||||
async function resolveStaffName(config: any): Promise<string | undefined> {
|
||||
try {
|
||||
const client = await Promise.race([
|
||||
createSessionClient(config),
|
||||
new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timeout")), 8000)),
|
||||
]);
|
||||
const corpId = config.corpId || config.id;
|
||||
const response = await (client as any).get("api/v1/organization/staffs/me", {
|
||||
searchParams: { corpId },
|
||||
timeout: 8000,
|
||||
});
|
||||
const json = (await response.json()) as Record<string, any>;
|
||||
const staff = json.value?.staff ?? json;
|
||||
const name = typeof staff?.name === "string" ? staff.name.trim() : "";
|
||||
return name || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
|
||||
const results: R[] = new Array(items.length);
|
||||
let cursor = 0;
|
||||
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (cursor < items.length) {
|
||||
const index = cursor++;
|
||||
results[index] = await fn(items[index]);
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function handleWhoami(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const offline = booleanOption(parsed.options, ["offline", "cached"]);
|
||||
const corps = runtime.corpContext.listCorps();
|
||||
const configs = new Map<string, any>();
|
||||
for (const config of loadCorpConfigs()) {
|
||||
configs.set(config.id, config);
|
||||
}
|
||||
|
||||
const resolved: Array<{ name?: string; online: boolean }> = offline
|
||||
? corps.map((corp: any) => ({ name: corp.staffName || undefined, online: false }))
|
||||
: await mapLimit(corps, 5, async (corp: any) => {
|
||||
const config = configs.get(corp.id);
|
||||
if (!config) return { name: corp.staffName || undefined, online: false };
|
||||
const name = await resolveStaffName(config);
|
||||
return { name: name ?? corp.staffName ?? undefined, online: Boolean(name) };
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
resolvedOnline: !offline,
|
||||
corporations: corps.map((corp: any, index: number) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
env: corp.env,
|
||||
staffId: corp.staffId,
|
||||
staffName: resolved[index]?.name ?? null,
|
||||
staffNameResolved: resolved[index]?.online ?? false,
|
||||
source: corp.source,
|
||||
current: Boolean(corp.current),
|
||||
})),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (corps.length === 0) {
|
||||
return { stdout: "未配置任何企业,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = corps.map((corp: any, index: number) => [
|
||||
corp.current ? `* ${index + 1}` : ` ${index + 1}`,
|
||||
corp.name,
|
||||
corp.id,
|
||||
resolved[index]?.name || "-",
|
||||
corp.staffId || "-",
|
||||
formatSourceLabel(corp.source, corp.hasOpenApi),
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业名称", "企业 ID", "执行身份", "员工工号", "来源"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout:
|
||||
`====== 当前执行身份(共 ${corps.length} 家企业${offline ? ",离线缓存" : ",在线核验"})======\n${table}\n` +
|
||||
`\n提示: 标记 * 为当前激活企业;追加 --offline 可只看本地缓存、不发起网络请求。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -6,11 +6,19 @@
|
||||
|
||||
```text
|
||||
src/domains/bill/
|
||||
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
|
||||
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
|
||||
├── bill.test.ts # 单元测试
|
||||
└── README.bill.md # 本说明文件
|
||||
├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排
|
||||
├── copy.ts # 草稿复制:服务端读取 → 本地转换 → 创建新草稿
|
||||
├── write.ts # 草稿写动作:freeflow.delete 等(提交契约见下文)
|
||||
├── draft-validation.ts # 草稿派生字段一致性校验(金额/币种/发票总额/草稿状态)
|
||||
├── templates.ts # 单据模板列表(与页面「快速新建」同源,默认仅启用)
|
||||
├── create.ts # 按模板创建草稿(最小表单 + 一条费用明细)
|
||||
├── submit.ts # 计算审批计划并提交送审(freeflow.submit)
|
||||
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
|
||||
├── bill.test.ts # 单元测试
|
||||
├── copy.test.ts # 复制转换单测
|
||||
├── draft-validation.test.ts # 校验规则单测
|
||||
└── README.bill.md # 本说明文件
|
||||
```
|
||||
|
||||
## 核心能力
|
||||
@@ -48,4 +56,56 @@ src/domains/bill/
|
||||
- 按实际流程状态(如 `PAYING`)和节点类型判断支付阶段,显示名称不参与阶段判定;流程状态优先于 backlog 状态。缺少当前身份的实际待办证据时,`diagnostic.canApprove` 为 `null`,CLI 显示“未知”,节点配置中的审批人不构成权限保证;
|
||||
- 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。
|
||||
|
||||
9. **草稿派生字段校验 (`validateBillDraft` / `assertBillDraftValid`)**:
|
||||
- 合思服务端把金额/币种/发票总额等派生字段的计算责任交给前端,保存接口只做弱校验
|
||||
(甚至允许 CNY 与 USD 直接相加)。CLI 在写入前先跑本层校验:
|
||||
必填表头、币种一致性、外币 `foreign × rate ≈ standard`、报销/支付/发票总额、
|
||||
`detailStatus=draft` 残留、明细序号重复、发票重复绑定、最晚付款日期早于提交日期。
|
||||
10. **纯接口复制 (`copyBillAsDraft`)**:
|
||||
- 读取服务端最新的 `flow.form`;
|
||||
- 清空发票绑定(`invoiceForm.invoices`)、明细与单据发票总额归零、剔除 `detailStatus`;
|
||||
- 重算报销/支付金额,附件默认保留;
|
||||
- `POST /api/flow/v1/flows` 创建新草稿(`name: freeflow.edit`),默认不提交。
|
||||
11. **草稿删除 (`deleteBillDraft`)**:
|
||||
- `POST /api/flow/v1/flows/$<flowId>`,`name: freeflow.delete`;
|
||||
- CLI 仅允许删除 `draft` 状态单据,已提交/审批中/已支付一律拒绝。
|
||||
|
||||
12. **单据模板列表 (`listBillTemplates`)**:
|
||||
- 与页面「快速新建单据」同源:`GET /api/form/v2/specificationGroups/withSpecificationVersioned`;
|
||||
- 响应按「规格分组 → 规格」组织,且已由服务端按当前身份做可见性过滤;
|
||||
- 默认只返回启用中的模板,`--all` 才会尝试带出停用项(服务端未返回停用项时两者一致)。
|
||||
|
||||
13. **按模板创建草稿 (`createBillDraft`)**:
|
||||
- 读取模板规格与费用类型,构造最小表单:`specificationId`(版本化 ID)、标题、提交人、报销日期、报销部门 + 一条费用明细;
|
||||
- 创建后为 `draft`,不提交;`description`/金额/费用类型可由参数指定。
|
||||
14. **提交送审 (`submitBillDraft`)**:
|
||||
- 先 `POST /api/v1/flow/plans/computed` 计算审批计划;
|
||||
- 未指派审批人的节点必须由 `--approver` 显式指定,绝不自动编造;
|
||||
- 再 `POST /api/flow/v1/flows/$<flowId>`(`name: freeflow.submit`,携带 `nodes`)。
|
||||
|
||||
## 写接口契约(实测)
|
||||
|
||||
```text
|
||||
# 保存 / 提交 / 删除共用同一端点,靠 name 区分
|
||||
POST /api/flow/v1/flows/$<flowId>?corpId=
|
||||
{ id, name: "freeflow.edit", form } # 保存草稿
|
||||
{ id, name: "freeflow.delete" } # 删除草稿
|
||||
{ id, name: "freeflow.submit", form, formType, nodes } # 提交(nodes 来自审批计划)
|
||||
|
||||
# 新建草稿(不带 id)
|
||||
POST /api/flow/v1/flows?corpId=
|
||||
{ name: "freeflow.edit", form } -> { flow: { id, form: { code } } }
|
||||
|
||||
# 提交前必须先算审批计划
|
||||
POST /api/v1/flow/plans/computed
|
||||
{ flowId, flowPlanConfigId, form, formType, params } -> { value: { nodes: [...] } }
|
||||
```
|
||||
|
||||
注意:
|
||||
- 保存 `form` 必须使用**扁平 ID 字符串**(`specificationId`、`expenseDepartment`、`feeTypeId`、
|
||||
`u_预算科目`、`法人实体`、`detailId` 等),直接回传读取接口的对象会 200 但不生效;
|
||||
- 交付审批计划时 `nodes` 需原样回传给 `freeflow.submit`;
|
||||
- 附件上传与发票上传目前仍依赖前端 Uploader,纯服务端 presign 链路尚未验证;
|
||||
- 提交/撤回等破坏性动作只在测试企业验证,生产环境禁止演练。
|
||||
|
||||
CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`,以及 `hose-use flow [get|trace] <单号|ID>` / `hose-use bill trace <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。
|
||||
+87
-3
@@ -66,6 +66,56 @@ export async function getRawBillFlow(
|
||||
const cleanTarget = target.trim();
|
||||
let match: Record<string, unknown> | undefined;
|
||||
|
||||
// 通道 0: flows/my & flows/approved 服务端按单号/ID 精确过滤
|
||||
// 覆盖已支付/已归档等不在 backlogs 中的单据,避免回退到「最近 N 条」本地匹配。
|
||||
try {
|
||||
const endpoints = ["api/flow/v1/flows/my", "api/flow/v1/flows/approved"];
|
||||
let flowId: string | undefined;
|
||||
for (const ep of endpoints) {
|
||||
let items: Record<string, unknown>[] = [];
|
||||
try {
|
||||
const res = await client.post(ep, {
|
||||
searchParams: { corpId, type: "home5" },
|
||||
json: {
|
||||
limit: { start: 0, count: 10 },
|
||||
filterBy: `(form.code.in(${quoted(cleanTarget)}))||(id==${quoted(cleanTarget)})`,
|
||||
},
|
||||
});
|
||||
const body = (await res.json()) as { items?: Record<string, unknown>[] };
|
||||
items = body.items ?? [];
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const item = items.find((it) => {
|
||||
const flow = (it.flow && typeof it.flow === "object" ? it.flow : {}) as Record<string, unknown>;
|
||||
const form = (it.form && typeof it.form === "object"
|
||||
? it.form
|
||||
: (flow.form && typeof flow.form === "object" ? flow.form : {})) as Record<string, unknown>;
|
||||
return flow.id === cleanTarget || form.code === cleanTarget;
|
||||
});
|
||||
const flow = item && item.flow && typeof item.flow === "object" ? item.flow as Record<string, unknown> : undefined;
|
||||
if (flow && typeof flow.id === "string") {
|
||||
flowId = flow.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (flowId) {
|
||||
const detail = await client.post(`api/flow/v1/flows/flowId/$${flowId}`, {
|
||||
searchParams: { id: flowId, corpId },
|
||||
json: {
|
||||
filterBy: `(id==${quoted(flowId)})`,
|
||||
select: "id,state,form,logs",
|
||||
},
|
||||
});
|
||||
const json = (await detail.json()) as { value?: Record<string, unknown> };
|
||||
if (json.value) {
|
||||
return { flowId: json.value };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 通道 0 失败时继续走既有回溯通道
|
||||
}
|
||||
|
||||
// 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配
|
||||
const searchFilters = [
|
||||
`(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`,
|
||||
@@ -122,6 +172,36 @@ export async function getRawBillFlow(
|
||||
}
|
||||
}
|
||||
|
||||
// 通道 0.5: 企业级按单号索引(跨身份,不依赖 flows/my 的“我发起”范围)
|
||||
// 部分单据由系统或其他员工创建,当前凭证身份在 flows/my 中不可见,但 searchByCode 可查。
|
||||
try {
|
||||
const res = await client.post("api/flow/v2/flows/searchByCode", {
|
||||
searchParams: { corpId },
|
||||
json: {},
|
||||
});
|
||||
const json = (await res.json()) as { items?: Record<string, unknown>[] };
|
||||
const item = (json.items ?? []).find((it) => {
|
||||
const form = (it.form && typeof it.form === "object" ? it.form : {}) as Record<string, unknown>;
|
||||
return it.id === cleanTarget || form.code === cleanTarget;
|
||||
});
|
||||
if (item) {
|
||||
const flowId = typeof item.id === "string" ? item.id : undefined;
|
||||
// searchByCode 返回的是精简表单(可能缺收款信息/部门等表头字段),
|
||||
// 命中后统一再拉一次完整详情,保证 bill get / bill validate 拿到的字段齐全。
|
||||
if (flowId) {
|
||||
const detail = await client.post(`api/flow/v1/flows/flowId/$${flowId}`, {
|
||||
searchParams: { id: flowId, corpId },
|
||||
json: { filterBy: `(id==${quoted(flowId)})`, select: "id,state,form,logs" },
|
||||
});
|
||||
const detailJson = (await detail.json()) as { value?: Record<string, unknown> };
|
||||
if (detailJson.value) return { flowId: detailJson.value };
|
||||
}
|
||||
return { flowId: item };
|
||||
}
|
||||
} catch {
|
||||
// 通道 0.5 失败时继续走既有回溯通道
|
||||
}
|
||||
|
||||
const backlogId = typeof match?.id === "string" ? match.id : cleanTarget;
|
||||
const flowIdFromMatch = match?.flowId && typeof match.flowId === "object" && typeof (match.flowId as any).id === "string"
|
||||
? (match.flowId as any).id
|
||||
@@ -528,12 +608,16 @@ export async function getFormSpecification(
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecification | undefined> {
|
||||
const cleanId = specificationId.replace(/^\[|\]$/g, "").trim();
|
||||
if (!cleanId) return undefined;
|
||||
const rawId = specificationId.replace(/^\[|\]$/g, "").trim();
|
||||
if (!rawId) return undefined;
|
||||
// 服务端用于查询的是「原始规格 ID」,版本化 ID 形如 `<originalId>:<hash>`;
|
||||
// 仅剥离末尾的 hash(originalId 本身可能包含冒号,如 `<corpId>:system:<name>`)。
|
||||
const cleanId = rawId.replace(/:[0-9a-f]{32,64}$/i, "");
|
||||
const response = await client.get(
|
||||
`api/form/v2/specifications/[${encodeURIComponent(cleanId)}]`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
searchParams: { corpId, _t: String(Date.now()) },
|
||||
headers: { "cache-control": "no-cache", pragma: "no-cache" },
|
||||
}
|
||||
);
|
||||
const json = (await response.json()) as {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { buildBillCopyForm } from "./copy.js";
|
||||
import type { BillDraftForm } from "./draft-validation.js";
|
||||
|
||||
function makeSource(): BillDraftForm {
|
||||
return {
|
||||
id: "ID_SOURCE",
|
||||
code: "B26015505",
|
||||
title: "报销 10月AI工具费用",
|
||||
specificationId: "spec-1",
|
||||
submitterId: "corp:staff-1",
|
||||
expenseDate: Date.UTC(2026, 9, 23),
|
||||
expenseDepartment: "corp:dept-1",
|
||||
payeeId: "payee-1",
|
||||
法人实体: "entity-1",
|
||||
u_最晚付款日期: Date.UTC(2026, 9, 31),
|
||||
description: "",
|
||||
expenseMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
payMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "321.14", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
attachments: [{ key: "bill-level.pdf" }],
|
||||
details: [
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 1,
|
||||
amount: { standard: "121.14", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "121.14", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-A" }] },
|
||||
attachments: [{ key: "bank.jpeg" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 2,
|
||||
amount: { standard: "200", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "200", standardStrCode: "CNY", standardSymbol: "¥" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-B" }] },
|
||||
detailStatus: "draft",
|
||||
attachments: [{ key: "alipay.pdf" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildBillCopyForm", () => {
|
||||
it("清空发票绑定并把发票总额归零", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.u_发票总金额?.standard).toBe("0");
|
||||
for (const detail of form.details!) {
|
||||
expect(detail.feeTypeForm?.invoice).toBe("0");
|
||||
expect(detail.feeTypeForm?.invoiceForm).toEqual({ type: "exist", invoices: [] });
|
||||
expect(detail.feeTypeForm?.u_发票总金额?.standard).toBe("0");
|
||||
}
|
||||
});
|
||||
|
||||
it("重算报销金额与支付金额", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.expenseMoney?.standard).toBe("321.14");
|
||||
expect(form.payMoney?.standard).toBe("321.14");
|
||||
});
|
||||
|
||||
it("剔除明细草稿标记", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.details![1].feeTypeForm?.detailStatus).toBeUndefined();
|
||||
});
|
||||
|
||||
it("默认保留附件", () => {
|
||||
const form = buildBillCopyForm(makeSource());
|
||||
expect(form.attachments?.length).toBe(1);
|
||||
expect(form.details![0].feeTypeForm?.attachments?.length).toBe(1);
|
||||
});
|
||||
|
||||
it("dropAttachments 清空单据与明细附件", () => {
|
||||
const form = buildBillCopyForm(makeSource(), { keepAttachments: false });
|
||||
expect(form.attachments).toEqual([]);
|
||||
expect(form.details![0].feeTypeForm?.attachments).toEqual([]);
|
||||
expect(form.details![1].feeTypeForm?.attachments).toEqual([]);
|
||||
});
|
||||
|
||||
it("支持自定义标题并保留币种字段", () => {
|
||||
const form = buildBillCopyForm(makeSource(), { title: "报销 10月AI工具费用(副本)" });
|
||||
expect(form.title).toBe("报销 10月AI工具费用(副本)");
|
||||
expect(form.u_发票总金额?.standardStrCode).toBe("CNY");
|
||||
expect(form.u_发票总金额?.standardSymbol).toBe("¥");
|
||||
});
|
||||
|
||||
it("不修改源对象", () => {
|
||||
const source = makeSource();
|
||||
buildBillCopyForm(source);
|
||||
expect(source.u_发票总金额?.standard).toBe("321.14");
|
||||
expect(source.details![1].feeTypeForm?.detailStatus).toBe("draft");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError } from "../../core/errors.js";
|
||||
import { getRawBillFlow } from "./api.js";
|
||||
import type { BillDraftForm, BillMoney } from "./draft-validation.js";
|
||||
|
||||
/**
|
||||
* 纯接口复制单据。
|
||||
*
|
||||
* 合思前端的「复制」是内存行为:读取源单 → 在编辑器里生成一份新表单,点保存时才创建。
|
||||
* 而且它复制的是编辑器内存里的旧状态(可能带旧汇率/旧金额)。
|
||||
*
|
||||
* CLI 的复制走「服务端读取 → 本地转换 → 创建」:
|
||||
* 1. 读取服务端最新的 form;
|
||||
* 2. 清空发票绑定(invoiceForm.invoices)、发票总额归零、剔除明细草稿标记;
|
||||
* 3. 重算报销/支付金额;
|
||||
* 4. POST /api/flow/v1/flows 创建新草稿。
|
||||
*/
|
||||
|
||||
export interface CopyBillOptions {
|
||||
/** 新单据标题;默认沿用源单标题 */
|
||||
title?: string;
|
||||
/** 是否保留附件(默认保留,与前端行为一致) */
|
||||
keepAttachments?: boolean;
|
||||
}
|
||||
|
||||
export interface CopyBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
title: string;
|
||||
detailCount: number;
|
||||
expenseMoney: string;
|
||||
form: BillDraftForm;
|
||||
}
|
||||
|
||||
const CURRENCY_FIELDS = [
|
||||
"standardStrCode",
|
||||
"standardNumCode",
|
||||
"standardSymbol",
|
||||
"standardUnit",
|
||||
"standardScale",
|
||||
] as const;
|
||||
|
||||
/** 生成一个金额为 0 的本位币金额对象。 */
|
||||
function zeroMoney(source: BillMoney | undefined): BillMoney {
|
||||
const money: BillMoney = { standard: "0" };
|
||||
for (const field of CURRENCY_FIELDS) {
|
||||
if (source && source[field] !== undefined) {
|
||||
(money as Record<string, unknown>)[field] = source[field];
|
||||
}
|
||||
}
|
||||
return money;
|
||||
}
|
||||
|
||||
function moneyNumber(money: BillMoney | undefined): number {
|
||||
const value = Number(money?.standard ?? 0);
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把源单 form 转换成一个可创建的新草稿 form。
|
||||
* 纯函数,便于单测与实际调用共享。
|
||||
*/
|
||||
export function buildBillCopyForm(
|
||||
source: BillDraftForm,
|
||||
options: CopyBillOptions = {}
|
||||
): BillDraftForm {
|
||||
const keepAttachments = options.keepAttachments !== false;
|
||||
const form = structuredClone(source) as BillDraftForm;
|
||||
|
||||
delete (form as Record<string, unknown>).id;
|
||||
delete (form as Record<string, unknown>).code;
|
||||
if (options.title?.trim()) {
|
||||
form.title = options.title.trim();
|
||||
}
|
||||
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
let amountSum = 0;
|
||||
|
||||
for (const detail of details) {
|
||||
const ft = (detail.feeTypeForm ??= {});
|
||||
amountSum += moneyNumber(ft.amount);
|
||||
|
||||
// 复制不携带发票绑定;发票总额归零
|
||||
ft.invoice = "0";
|
||||
ft.invoiceForm = { type: "exist", invoices: [] };
|
||||
ft.u_发票总金额 = zeroMoney(ft.u_发票总金额);
|
||||
delete ft.detailStatus;
|
||||
|
||||
if (!keepAttachments) {
|
||||
ft.attachments = [];
|
||||
}
|
||||
}
|
||||
|
||||
form.u_发票总金额 = zeroMoney(form.u_发票总金额);
|
||||
form.expenseMoney = { ...(form.expenseMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
form.payMoney = { ...(form.payMoney ?? {}), standard: amountSum.toFixed(2) };
|
||||
if (!keepAttachments) {
|
||||
form.attachments = [];
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取源单并创建一份新草稿。
|
||||
*/
|
||||
export async function copyBillAsDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: CopyBillOptions = {}
|
||||
): Promise<CopyBillResult> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object"
|
||||
? (raw.flowId as Record<string, unknown>)
|
||||
: undefined;
|
||||
const sourceForm = flow && typeof flow.form === "object"
|
||||
? (flow.form as BillDraftForm)
|
||||
: undefined;
|
||||
|
||||
if (!flow || !sourceForm) {
|
||||
throw new NotFoundError(`在企业 [${corpId}] 下未找到单号或 ID 为 [${target}] 的单据,无法复制`);
|
||||
}
|
||||
|
||||
const form = buildBillCopyForm(sourceForm, options);
|
||||
const response = await client.post("api/flow/v1/flows", {
|
||||
searchParams: { corpId },
|
||||
json: { name: "freeflow.edit", form },
|
||||
});
|
||||
const json = (await response.json()) as {
|
||||
value?: { id?: string; form?: { code?: string } } | string;
|
||||
flow?: { id?: string; form?: { code?: string } };
|
||||
id?: string;
|
||||
form?: { code?: string };
|
||||
};
|
||||
const value = (json.value && typeof json.value === "object" ? json.value : undefined)
|
||||
?? json.flow
|
||||
?? json;
|
||||
const formSnapshot = (value.form ?? {}) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
flowId: String(value.id ?? ""),
|
||||
code: String(formSnapshot.code ?? ""),
|
||||
title: String(formSnapshot.title ?? form.title ?? ""),
|
||||
detailCount: form.details?.length ?? 0,
|
||||
expenseMoney: String(form.expenseMoney?.standard ?? "0"),
|
||||
form,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { filterBillFormByTemplate, filterFeeTypeFormBySpec } from "./create.js";
|
||||
|
||||
const components = [
|
||||
{ field: "title", optional: false },
|
||||
{ field: "submitterId", optional: false },
|
||||
{ field: "description", optional: true },
|
||||
{ field: "u_自定义字段", optional: true },
|
||||
];
|
||||
|
||||
describe("filterBillFormByTemplate", () => {
|
||||
it("只保留模板声明的字段,剔除未声明字段", () => {
|
||||
const { form, missingRequired } = filterBillFormByTemplate(
|
||||
{
|
||||
specificationId: "spec",
|
||||
title: "t",
|
||||
submitterId: "s",
|
||||
u_发票总金额: { standard: "0" },
|
||||
details: [],
|
||||
},
|
||||
components
|
||||
);
|
||||
expect(form).toEqual({ specificationId: "spec", title: "t", submitterId: "s", details: [] });
|
||||
expect(missingRequired).toEqual([]);
|
||||
});
|
||||
|
||||
it("返回缺失的必填字段", () => {
|
||||
const { missingRequired } = filterBillFormByTemplate(
|
||||
{ specificationId: "spec", details: [] },
|
||||
components
|
||||
);
|
||||
expect(missingRequired).toEqual(["title", "submitterId"]);
|
||||
});
|
||||
|
||||
it("模板没有 components 时保留 specificationId 与 details", () => {
|
||||
const { form } = filterBillFormByTemplate(
|
||||
{ specificationId: "spec", title: "t", details: [] },
|
||||
[]
|
||||
);
|
||||
expect(form).toEqual({ specificationId: "spec", details: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterFeeTypeFormBySpec", () => {
|
||||
it("剔除费用类型未声明的字段(如 feeDate)", () => {
|
||||
const form = filterFeeTypeFormBySpec(
|
||||
{ amount: { standard: "1" }, feeDate: 123 },
|
||||
[{ field: "amount" }, { field: "apportions" }]
|
||||
);
|
||||
expect(form).toEqual({ amount: { standard: "1" } });
|
||||
});
|
||||
|
||||
it("schema 为空时保留候选字段", () => {
|
||||
const candidate = { amount: { standard: "1" }, feeDate: 123 };
|
||||
expect(filterFeeTypeFormBySpec(candidate, [])).toEqual(candidate);
|
||||
});
|
||||
|
||||
it("保留 schema 声明的其它字段", () => {
|
||||
const form = filterFeeTypeFormBySpec(
|
||||
{ amount: { standard: "1" }, apportions: [], feeDate: 123 },
|
||||
[{ field: "amount" }, { field: "apportions" }]
|
||||
);
|
||||
expect(form).toEqual({ amount: { standard: "1" }, apportions: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { getDepartmentTree, getFeeTypeTree, getFormSpecification } from "./api.js";
|
||||
import { listBillTemplates } from "./templates.js";
|
||||
|
||||
/**
|
||||
* 纯接口创建单据草稿。
|
||||
*
|
||||
* 模板决定必填字段;这里构造最小可用表单:
|
||||
* - 表头:specificationId / title / submitterId / expenseDate / expenseDepartment
|
||||
* - 明细:选中一个费用类型(默认「简单费用」或第一个可用类型),金额可配置
|
||||
*
|
||||
* 创建后仍为 draft,不会提交。
|
||||
*/
|
||||
|
||||
export interface CreateBillOptions {
|
||||
/** 模板 ID(bill templates 输出的 id) */
|
||||
templateId: string;
|
||||
title?: string;
|
||||
/** 本位币金额,默认 0.01 */
|
||||
amount?: string;
|
||||
reason?: string;
|
||||
/** 指定费用类型名称,默认「简单费用」,找不到则取第一个可用类型 */
|
||||
feeTypeName?: string;
|
||||
submitterId?: string;
|
||||
expenseDepartment?: string;
|
||||
expenseDate?: number;
|
||||
}
|
||||
|
||||
export interface TemplateComponent {
|
||||
field?: string;
|
||||
optional?: boolean;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按模板字段白名单过滤表单:只保留模板声明过的字段 + specificationId/details。
|
||||
* 返回缺失的必填字段,供调用方明确报错(而不是让服务端 412)。
|
||||
*/
|
||||
export function filterBillFormByTemplate(
|
||||
form: Record<string, unknown>,
|
||||
components: TemplateComponent[]
|
||||
): { form: Record<string, unknown>; missingRequired: string[] } {
|
||||
const allowed = new Set<string>(["specificationId", "details"]);
|
||||
for (const component of components) {
|
||||
if (component.field) allowed.add(component.field);
|
||||
}
|
||||
const filtered: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(form)) {
|
||||
if (allowed.has(key)) filtered[key] = value;
|
||||
}
|
||||
const missingRequired = components
|
||||
.filter((component) => component.field && component.optional === false && !(component.field in filtered))
|
||||
.map((component) => component.field as string);
|
||||
return { form: filtered, missingRequired };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按费用类型 schema 过滤明细字段:费用类型没有声明的字段不发(如 feeDate)。
|
||||
* schema 拉取失败(components 为空)时保留候选字段,由服务端兜底。
|
||||
*/
|
||||
export function filterFeeTypeFormBySpec(
|
||||
candidate: Record<string, unknown>,
|
||||
components: TemplateComponent[]
|
||||
): Record<string, unknown> {
|
||||
const allowed = new Set<string>();
|
||||
for (const component of components) {
|
||||
if (component.field) allowed.add(component.field);
|
||||
}
|
||||
if (allowed.size === 0) return candidate;
|
||||
return Object.fromEntries(Object.entries(candidate).filter(([key]) => allowed.has(key)));
|
||||
}
|
||||
|
||||
export interface CreateBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
title: string;
|
||||
amount: string;
|
||||
feeType: string;
|
||||
}
|
||||
|
||||
interface FeeTypeNode {
|
||||
id?: string;
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
expenseSpecificationId?: string;
|
||||
children?: FeeTypeNode[];
|
||||
}
|
||||
|
||||
function flattenFeeTypes(nodes: FeeTypeNode[]): FeeTypeNode[] {
|
||||
const out: FeeTypeNode[] = [];
|
||||
const walk = (list: FeeTypeNode[]) => {
|
||||
for (const node of list) {
|
||||
out.push(node);
|
||||
if (Array.isArray(node.children)) walk(node.children);
|
||||
}
|
||||
};
|
||||
walk(nodes);
|
||||
return out;
|
||||
}
|
||||
|
||||
function zeroMoney(): Record<string, unknown> {
|
||||
return {
|
||||
standard: "0",
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
standardSymbol: "¥",
|
||||
standardNumCode: "156",
|
||||
standardStrCode: "CNY",
|
||||
};
|
||||
}
|
||||
|
||||
export async function createBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: CreateBillOptions
|
||||
): Promise<CreateBillResult> {
|
||||
const templateId = options.templateId.trim();
|
||||
if (!templateId) throw new ValidationError("请通过 --template 指定单据模板 ID");
|
||||
|
||||
const specification = await getFormSpecification(client, corpId, templateId);
|
||||
if (!specification) {
|
||||
throw new NotFoundError(`未找到单据模板: ${templateId}`);
|
||||
}
|
||||
|
||||
// 创建接口要求版本化 specificationId(`<originalId>:<hash>`);
|
||||
// 用户传入的通常是 bill templates 输出的原始 ID。
|
||||
let versionedSpecificationId = templateId;
|
||||
if (!/:[0-9a-f]{32,64}$/i.test(templateId)) {
|
||||
const templates = await listBillTemplates(client, corpId);
|
||||
const hit = templates.groups
|
||||
.flatMap((group) => group.specifications)
|
||||
.find((item) => item.id === templateId || item.name === templateId);
|
||||
if (!hit) throw new NotFoundError(`未找到单据模板: ${templateId}`);
|
||||
versionedSpecificationId = hit.versionedId;
|
||||
}
|
||||
|
||||
const meResponse = await client.get("api/v1/organization/staffs/me", {
|
||||
searchParams: { corpId },
|
||||
});
|
||||
const meJson = (await meResponse.json()) as Record<string, any>;
|
||||
const staff = meJson.value?.staff ?? meJson;
|
||||
const submitterId = options.submitterId || staff.id;
|
||||
const corpDeptCandidate = (value: unknown): string | undefined => {
|
||||
if (typeof value === "string" && value && value !== corpId) return value;
|
||||
if (value && typeof value === "object" && typeof (value as any).id === "string") {
|
||||
const id = (value as any).id as string;
|
||||
return id === corpId ? undefined : id;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
let expenseDepartment =
|
||||
options.expenseDepartment ||
|
||||
corpDeptCandidate(staff.defaultDepartment) ||
|
||||
corpDeptCandidate(staff.defaultDepartmentId) ||
|
||||
corpDeptCandidate(Array.isArray(staff.departments) ? staff.departments[0] : undefined);
|
||||
if (!expenseDepartment) {
|
||||
// OpenAPI/协助身份可能只返回企业 ID 作为部门;回退到部门树第一个有效节点。
|
||||
const tree = (await getDepartmentTree(client, corpId)) as Array<Record<string, any>>;
|
||||
const flat: Array<Record<string, any>> = [];
|
||||
const walk = (nodes: Array<Record<string, any>>) => {
|
||||
for (const node of nodes) {
|
||||
flat.push(node);
|
||||
if (Array.isArray(node.children)) walk(node.children);
|
||||
}
|
||||
};
|
||||
walk(tree);
|
||||
expenseDepartment = corpDeptCandidate(flat.find((node) => corpDeptCandidate(node.id))?.id);
|
||||
}
|
||||
if (!submitterId || !expenseDepartment) {
|
||||
throw new ValidationError("无法确定提交人或报销部门,请通过 --submitter / --department 指定");
|
||||
}
|
||||
|
||||
const feeTypes = flattenFeeTypes((await getFeeTypeTree(client, corpId)) as FeeTypeNode[]);
|
||||
const preferred = options.feeTypeName?.trim();
|
||||
const feeType =
|
||||
(preferred
|
||||
? feeTypes.find((item) => item.name === preferred && item.expenseSpecificationId)
|
||||
: undefined) ||
|
||||
feeTypes.find((item) => item.name === "简单费用" && item.expenseSpecificationId) ||
|
||||
feeTypes.find((item) => item.active !== false && item.expenseSpecificationId);
|
||||
if (!feeType?.id || !feeType.expenseSpecificationId) {
|
||||
throw new NotFoundError("未找到可用的费用类型(缺少 expenseSpecificationId)");
|
||||
}
|
||||
|
||||
const amount = options.amount?.trim() || "0.01";
|
||||
if (!Number.isFinite(Number(amount)) || Number(amount) <= 0) {
|
||||
throw new ValidationError(`金额不合法: ${amount}`);
|
||||
}
|
||||
const expenseDate = options.expenseDate ?? Date.now();
|
||||
const title = options.title?.trim() || specification.name;
|
||||
|
||||
const amountMoney = {
|
||||
standard: amount,
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
standardSymbol: "¥",
|
||||
standardNumCode: "156",
|
||||
standardStrCode: "CNY",
|
||||
};
|
||||
const detailSpec = await getFormSpecification(client, corpId, feeType.expenseSpecificationId);
|
||||
const detailComponents = ((detailSpec as { components?: TemplateComponent[] } | undefined)?.components ??
|
||||
[]) as TemplateComponent[];
|
||||
const feeTypeForm = filterFeeTypeFormBySpec(
|
||||
{ amount: amountMoney, feeDate: expenseDate },
|
||||
detailComponents
|
||||
);
|
||||
// 金额是核心字段:即使 schema 未声明也必须保留。
|
||||
if (!("amount" in feeTypeForm)) feeTypeForm.amount = amountMoney;
|
||||
|
||||
const detail = {
|
||||
feeTypeId: feeType.id,
|
||||
specificationId: feeType.expenseSpecificationId,
|
||||
feeTypeForm,
|
||||
};
|
||||
|
||||
const candidate = {
|
||||
specificationId: versionedSpecificationId,
|
||||
title,
|
||||
submitterId,
|
||||
expenseDate,
|
||||
expenseDepartment,
|
||||
...(options.reason?.trim() ? { description: options.reason.trim() } : {}),
|
||||
details: [detail],
|
||||
};
|
||||
const { form, missingRequired } = filterBillFormByTemplate(
|
||||
candidate as Record<string, unknown>,
|
||||
((specification as { components?: TemplateComponent[] }).components ?? []) as TemplateComponent[]
|
||||
);
|
||||
if (missingRequired.length > 0) {
|
||||
throw new ValidationError(
|
||||
`模板要求以下字段但 CLI 未提供:${missingRequired.join("、")}。` +
|
||||
`当前 create 仅自动填充标准表头与一条费用明细,请补充对应模板字段后再创建。`
|
||||
);
|
||||
}
|
||||
|
||||
const response = await client.post("api/flow/v1/flows", {
|
||||
searchParams: { corpId },
|
||||
json: { name: "freeflow.edit", form },
|
||||
});
|
||||
const json = (await response.json()) as Record<string, any>;
|
||||
const value =
|
||||
(json.value && typeof json.value === "object" ? json.value : undefined) ??
|
||||
json.flow ??
|
||||
json;
|
||||
|
||||
return {
|
||||
flowId: String(value?.id ?? ""),
|
||||
code: String(value?.form?.code ?? ""),
|
||||
title,
|
||||
amount,
|
||||
feeType: feeType.name ?? "",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
validateBillDraft,
|
||||
assertBillDraftValid,
|
||||
formatValidationIssues,
|
||||
type BillDraftForm,
|
||||
} from "./draft-validation.js";
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const SUBMIT_AT = Date.UTC(2026, 9, 23);
|
||||
const PAY_BY = Date.UTC(2026, 9, 31);
|
||||
|
||||
function makeForm(): BillDraftForm {
|
||||
return {
|
||||
title: "报销 10月AI工具费用",
|
||||
specificationId: "spec-1",
|
||||
submitterId: "corp:staff-1",
|
||||
expenseDate: SUBMIT_AT,
|
||||
expenseDepartment: "corp:dept-1",
|
||||
payeeId: "payee-1",
|
||||
法人实体: "entity-1",
|
||||
u_最晚付款日期: PAY_BY,
|
||||
description: "",
|
||||
expenseMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
payMoney: { standard: "321.14", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "321.14", standardStrCode: "CNY" },
|
||||
details: [
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 1,
|
||||
amount: {
|
||||
standard: "121.14",
|
||||
standardStrCode: "CNY",
|
||||
foreign: "2860",
|
||||
foreignStrCode: "JPY",
|
||||
rate: "0.04235664",
|
||||
},
|
||||
u_发票总金额: { standard: "121.14", standardStrCode: "CNY" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-A" }] },
|
||||
},
|
||||
},
|
||||
{
|
||||
feeTypeForm: {
|
||||
detailNo: 2,
|
||||
amount: { standard: "200", standardStrCode: "CNY" },
|
||||
u_发票总金额: { standard: "200", standardStrCode: "CNY" },
|
||||
invoice: "1",
|
||||
invoiceForm: { type: "exist", invoices: [{ invoiceId: "invoice-B" }] },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function codes(form: BillDraftForm) {
|
||||
return validateBillDraft(form).map((item) => item.code);
|
||||
}
|
||||
|
||||
describe("validateBillDraft 派生字段校验", () => {
|
||||
it("合法的两明细单据通过校验", () => {
|
||||
expect(validateBillDraft(makeForm())).toEqual([]);
|
||||
expect(formatValidationIssues([])).toContain("校验通过");
|
||||
});
|
||||
|
||||
it("拦截币种混加(USD 明细混入 CNY 单据)", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.amount = {
|
||||
standard: "250.00",
|
||||
standardStrCode: "USD",
|
||||
standardSymbol: "$",
|
||||
standardUnit: "美元",
|
||||
};
|
||||
form.expenseMoney!.standard = "371.14";
|
||||
form.payMoney!.standard = "371.14";
|
||||
expect(codes(form)).toContain("CURRENCY_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截外币金额与汇率不匹配", () => {
|
||||
const form = makeForm();
|
||||
form.details![0].feeTypeForm!.amount!.rate = "0.06";
|
||||
form.details![0].feeTypeForm!.amount!.standard = "143.00";
|
||||
form.expenseMoney!.standard = "343.00";
|
||||
form.payMoney!.standard = "343.00";
|
||||
expect(codes(form)).toContain("FOREIGN_RATE_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截报销金额与明细合计不一致", () => {
|
||||
const form = makeForm();
|
||||
form.expenseMoney!.standard = "321.00";
|
||||
form.payMoney!.standard = "321.00";
|
||||
expect(codes(form)).toContain("EXPENSE_TOTAL_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截发票总金额与明细发票合计不一致", () => {
|
||||
const form = makeForm();
|
||||
form.u_发票总金额!.standard = "321.00";
|
||||
expect(codes(form)).toContain("INVOICE_TOTAL_MISMATCH");
|
||||
});
|
||||
|
||||
it("拦截残留 draft 状态的明细", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.detailStatus = "draft";
|
||||
expect(codes(form)).toContain("DETAIL_DRAFT_STATUS");
|
||||
});
|
||||
|
||||
it("拦截重复的明细序号", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.detailNo = 1;
|
||||
expect(codes(form)).toContain("DUPLICATE_DETAIL_NO");
|
||||
});
|
||||
|
||||
it("拦截最晚付款日期早于提交日期", () => {
|
||||
const form = makeForm();
|
||||
form.u_最晚付款日期 = SUBMIT_AT - DAY;
|
||||
expect(codes(form)).toContain("PAY_DATE_BEFORE_SUBMIT");
|
||||
});
|
||||
|
||||
it("重复绑定同一张发票给出 warning", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.invoiceForm = {
|
||||
type: "exist",
|
||||
invoices: [{ invoiceId: "invoice-A" }],
|
||||
};
|
||||
const issues = validateBillDraft(form);
|
||||
const duplicate = issues.find((item) => item.code === "DUPLICATE_INVOICE");
|
||||
expect(duplicate?.severity).toBe("warning");
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertBillDraftValid", () => {
|
||||
it("合法表单不抛错", () => {
|
||||
expect(() => assertBillDraftValid(makeForm())).not.toThrow();
|
||||
});
|
||||
|
||||
it("非法表单抛出 ValidationError 并列出错误字段", () => {
|
||||
const form = makeForm();
|
||||
form.details![1].feeTypeForm!.detailStatus = "draft";
|
||||
try {
|
||||
assertBillDraftValid(form);
|
||||
throw new Error("should have thrown");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ValidationError);
|
||||
expect(String((error as Error).message)).toContain("detailStatus");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,426 @@
|
||||
import { ValidationError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 单据草稿的派生字段一致性校验。
|
||||
*
|
||||
* 合思服务端把「金额/币种/发票总额」等派生字段的计算责任交给前端:
|
||||
* 保存接口只做弱校验,甚至允许 CNY/USD 直接相加。CLI 在写入前必须先跑这一层,
|
||||
* 避免把语义错误的表单写回服务端。
|
||||
*/
|
||||
|
||||
export interface BillMoney {
|
||||
standard?: string | number;
|
||||
standardStrCode?: string;
|
||||
standardSymbol?: string;
|
||||
standardUnit?: string;
|
||||
standardScale?: number;
|
||||
foreign?: string | number;
|
||||
foreignStrCode?: string;
|
||||
rate?: string | number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftInvoiceRef {
|
||||
invoiceId?: string;
|
||||
taxAmount?: BillMoney;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftInvoiceForm {
|
||||
type?: string;
|
||||
invoices?: BillDraftInvoiceRef[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftDetailForm {
|
||||
amount?: BillMoney;
|
||||
u_发票总金额?: BillMoney;
|
||||
invoice?: string | number;
|
||||
invoiceForm?: BillDraftInvoiceForm;
|
||||
attachments?: unknown[];
|
||||
detailNo?: number;
|
||||
detailId?: string;
|
||||
detailStatus?: string;
|
||||
consumptionReasons?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftDetail {
|
||||
feeTypeForm?: BillDraftDetailForm;
|
||||
feeTypeId?: unknown;
|
||||
specificationId?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface BillDraftForm {
|
||||
title?: string;
|
||||
specificationId?: unknown;
|
||||
submitterId?: unknown;
|
||||
expenseDate?: number;
|
||||
expenseDepartment?: unknown;
|
||||
payeeId?: unknown;
|
||||
法人实体?: unknown;
|
||||
u_最晚付款日期?: number;
|
||||
description?: string;
|
||||
expenseMoney?: BillMoney;
|
||||
payMoney?: BillMoney;
|
||||
writtenOffMoney?: BillMoney;
|
||||
u_发票总金额?: BillMoney;
|
||||
attachments?: unknown[];
|
||||
details?: BillDraftDetail[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type ValidationSeverity = "error" | "warning";
|
||||
|
||||
export interface ValidationIssue {
|
||||
code: string;
|
||||
severity: ValidationSeverity;
|
||||
field: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ValidateOptions {
|
||||
/** 金额比较容差,默认 0.005(分位) */
|
||||
moneyTolerance?: number;
|
||||
/** 外币换算比较容差,默认 0.01 */
|
||||
rateTolerance?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_MONEY_TOLERANCE = 0.005;
|
||||
const DEFAULT_RATE_TOLERANCE = 0.01;
|
||||
const MAX_DESCRIPTION_LENGTH = 800;
|
||||
|
||||
function toNumber(value: unknown): number | undefined {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
if (typeof value === "string" && value.trim() !== "") {
|
||||
const parsed = Number(value.replaceAll(",", ""));
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function moneyStandard(money: BillMoney | undefined): number | undefined {
|
||||
return money ? toNumber(money.standard) : undefined;
|
||||
}
|
||||
|
||||
function issue(
|
||||
code: string,
|
||||
field: string,
|
||||
message: string,
|
||||
severity: ValidationSeverity = "error"
|
||||
): ValidationIssue {
|
||||
return { code, severity, field, message };
|
||||
}
|
||||
|
||||
function nearlyEqual(a: number, b: number, tolerance: number): boolean {
|
||||
return Math.abs(a - b) <= tolerance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验单张草稿表单的派生字段一致性与必填项。
|
||||
* 返回空数组代表可以安全写入。
|
||||
*/
|
||||
export function validateBillDraft(
|
||||
form: BillDraftForm | undefined,
|
||||
options: ValidateOptions = {}
|
||||
): ValidationIssue[] {
|
||||
const moneyTolerance = options.moneyTolerance ?? DEFAULT_MONEY_TOLERANCE;
|
||||
const rateTolerance = options.rateTolerance ?? DEFAULT_RATE_TOLERANCE;
|
||||
const issues: ValidationIssue[] = [];
|
||||
|
||||
if (!form) {
|
||||
return [issue("EMPTY_FORM", "form", "单据表单为空")];
|
||||
}
|
||||
|
||||
// 1. 必填表头
|
||||
const requiredHeader: Array<[keyof BillDraftForm, string]> = [
|
||||
["title", "标题"],
|
||||
["specificationId", "单据模板"],
|
||||
["submitterId", "提交人"],
|
||||
["expenseDate", "提交日期"],
|
||||
["expenseDepartment", "费用承担部门"],
|
||||
["payeeId", "收款信息"],
|
||||
["法人实体", "公司(法人实体)"],
|
||||
["u_最晚付款日期", "最晚付款日期"],
|
||||
];
|
||||
for (const [key, label] of requiredHeader) {
|
||||
const value = form[key];
|
||||
if (value === undefined || value === null || value === "") {
|
||||
issues.push(issue("MISSING_FIELD", String(key), `缺少必填字段:${label}`));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 描述长度
|
||||
const description = typeof form.description === "string" ? form.description : "";
|
||||
if (description.length > MAX_DESCRIPTION_LENGTH) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DESCRIPTION_TOO_LONG",
|
||||
"description",
|
||||
`描述长度 ${description.length} 超过模板上限 ${MAX_DESCRIPTION_LENGTH}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 3. 明细数量
|
||||
const details = Array.isArray(form.details) ? form.details : [];
|
||||
if (details.length === 0) {
|
||||
issues.push(issue("NO_DETAILS", "details", "费用明细为空,至少需要一条明细"));
|
||||
return issues;
|
||||
}
|
||||
|
||||
// 4. 本位币(以表头报销金额为准)
|
||||
const billCurrency = form.expenseMoney?.standardStrCode || form.payMoney?.standardStrCode;
|
||||
|
||||
// 5. 逐条明细
|
||||
const seenDetailNos = new Map<number, number>();
|
||||
const seenInvoiceIds = new Map<string, number>();
|
||||
|
||||
let detailAmountSum = 0;
|
||||
let detailInvoiceSum = 0;
|
||||
let hasValidDetailAmounts = true;
|
||||
|
||||
details.forEach((detail, index) => {
|
||||
const ft = detail.feeTypeForm ?? {};
|
||||
const position = index + 1;
|
||||
const label = `明细 #${ft.detailNo ?? position}`;
|
||||
|
||||
if (ft.detailStatus === "draft") {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_DRAFT_STATUS",
|
||||
`details[${index}].feeTypeForm.detailStatus`,
|
||||
`${label} 仍处于草稿状态(detailStatus=draft),提交前必须保存该明细`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof ft.detailNo === "number") {
|
||||
const previous = seenDetailNos.get(ft.detailNo);
|
||||
if (previous !== undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DUPLICATE_DETAIL_NO",
|
||||
`details[${index}].feeTypeForm.detailNo`,
|
||||
`明细序号 ${ft.detailNo} 重复(第 ${previous + 1} 条与第 ${position} 条)`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
seenDetailNos.set(ft.detailNo, index);
|
||||
}
|
||||
}
|
||||
|
||||
const amount = ft.amount;
|
||||
const standard = moneyStandard(amount);
|
||||
if (standard === undefined) {
|
||||
hasValidDetailAmounts = false;
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_AMOUNT_INVALID",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的本位币金额缺失或不是合法数字`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
detailAmountSum += standard;
|
||||
if (standard <= 0) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_AMOUNT_NOT_POSITIVE",
|
||||
`details[${index}].feeTypeForm.amount.standard`,
|
||||
`${label} 的金额为 ${standard},应大于 0`,
|
||||
"warning"
|
||||
)
|
||||
);
|
||||
}
|
||||
if (billCurrency && amount?.standardStrCode && amount.standardStrCode !== billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
"CURRENCY_MISMATCH",
|
||||
`details[${index}].feeTypeForm.amount.standardStrCode`,
|
||||
`${label} 的本位币币种为 ${amount.standardStrCode},与单据本位币 ${billCurrency} 不一致` +
|
||||
`(合思服务端会直接相加不同币种,必须由 CLI 拦截)`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 外币明细:foreign × rate 必须能还原 standard
|
||||
const foreign = toNumber(amount?.foreign);
|
||||
const rate = toNumber(amount?.rate);
|
||||
if (foreign !== undefined && rate !== undefined) {
|
||||
if (rate <= 0) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_RATE_INVALID",
|
||||
`details[${index}].feeTypeForm.amount.rate`,
|
||||
`${label} 的汇率为 ${rate},应大于 0`
|
||||
)
|
||||
);
|
||||
} else if (standard !== undefined && !nearlyEqual(standard, foreign * rate, rateTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_RATE_MISMATCH",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的本位币金额 ${standard} 与外币 ${foreign} × 汇率 ${rate} = ${(foreign * rate).toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
if (!amount?.foreignStrCode) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_FIELDS_INCOMPLETE",
|
||||
`details[${index}].feeTypeForm.amount.foreignStrCode`,
|
||||
`${label} 有外资金额但缺少 foreignStrCode`
|
||||
)
|
||||
);
|
||||
} else if (billCurrency && amount.foreignStrCode === billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_SAME_CURRENCY",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的外币币种与本位币相同(${billCurrency}),不应同时设置外币字段`,
|
||||
"warning"
|
||||
)
|
||||
);
|
||||
}
|
||||
} else if (foreign !== undefined || rate !== undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"FOREIGN_FIELDS_INCOMPLETE",
|
||||
`details[${index}].feeTypeForm.amount`,
|
||||
`${label} 的外币金额与汇率必须成对出现`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 明细发票总额
|
||||
const detailInvoiceTotal = moneyStandard(ft.u_发票总金额);
|
||||
if (detailInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DETAIL_INVOICE_TOTAL_INVALID",
|
||||
`details[${index}].feeTypeForm.u_发票总金额`,
|
||||
`${label} 的发票总金额缺失或不是合法数字`
|
||||
)
|
||||
);
|
||||
} else {
|
||||
detailInvoiceSum += detailInvoiceTotal;
|
||||
if (billCurrency && ft.u_发票总金额?.standardStrCode && ft.u_发票总金额.standardStrCode !== billCurrency) {
|
||||
issues.push(
|
||||
issue(
|
||||
"INVOICE_CURRENCY_MISMATCH",
|
||||
`details[${index}].feeTypeForm.u_发票总金额.standardStrCode`,
|
||||
`${label} 的发票总金额币种 ${ft.u_发票总金额.standardStrCode} 与单据本位币 ${billCurrency} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 发票去重
|
||||
const invoices = ft.invoiceForm?.invoices ?? [];
|
||||
for (const invoice of invoices) {
|
||||
const invoiceId = typeof invoice.invoiceId === "string" ? invoice.invoiceId : undefined;
|
||||
if (!invoiceId) continue;
|
||||
const previous = seenInvoiceIds.get(invoiceId);
|
||||
if (previous !== undefined) {
|
||||
issues.push(
|
||||
issue(
|
||||
"DUPLICATE_INVOICE",
|
||||
`details[${index}].feeTypeForm.invoiceForm.invoices`,
|
||||
`发票 ${invoiceId} 同时绑定在明细 #${previous + 1} 与 ${label}`,
|
||||
"warning"
|
||||
)
|
||||
);
|
||||
} else {
|
||||
seenInvoiceIds.set(invoiceId, index);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 6. 表头派生金额
|
||||
const expenseMoney = moneyStandard(form.expenseMoney);
|
||||
if (expenseMoney === undefined) {
|
||||
issues.push(
|
||||
issue("EXPENSE_MONEY_INVALID", "expenseMoney", "单据报销金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (hasValidDetailAmounts && !nearlyEqual(expenseMoney, detailAmountSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"EXPENSE_TOTAL_MISMATCH",
|
||||
"expenseMoney.standard",
|
||||
`报销金额 ${expenseMoney} 与明细金额合计 ${detailAmountSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const payMoney = moneyStandard(form.payMoney);
|
||||
if (payMoney === undefined) {
|
||||
issues.push(issue("PAY_MONEY_INVALID", "payMoney", "单据支付金额缺失或不是合法数字"));
|
||||
} else if (expenseMoney !== undefined) {
|
||||
const writtenOff = moneyStandard(form.writtenOffMoney) ?? 0;
|
||||
const expectedPay = expenseMoney - writtenOff;
|
||||
if (!nearlyEqual(payMoney, expectedPay, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"PAY_TOTAL_MISMATCH",
|
||||
"payMoney.standard",
|
||||
`支付金额 ${payMoney} 与报销金额 ${expenseMoney} - 核销借款 ${writtenOff} = ${expectedPay.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const billInvoiceTotal = moneyStandard(form.u_发票总金额);
|
||||
if (billInvoiceTotal === undefined) {
|
||||
issues.push(
|
||||
issue("BILL_INVOICE_TOTAL_INVALID", "u_发票总金额", "单据发票总金额缺失或不是合法数字")
|
||||
);
|
||||
} else if (!nearlyEqual(billInvoiceTotal, detailInvoiceSum, moneyTolerance)) {
|
||||
issues.push(
|
||||
issue(
|
||||
"INVOICE_TOTAL_MISMATCH",
|
||||
"u_发票总金额.standard",
|
||||
`单据发票总金额 ${billInvoiceTotal} 与各明细发票合计 ${detailInvoiceSum.toFixed(2)} 不一致`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 7. 日期
|
||||
const submitAt = toNumber(form.expenseDate);
|
||||
const payBy = toNumber(form.u_最晚付款日期);
|
||||
if (submitAt !== undefined && payBy !== undefined && payBy < submitAt) {
|
||||
issues.push(
|
||||
issue(
|
||||
"PAY_DATE_BEFORE_SUBMIT",
|
||||
"u_最晚付款日期",
|
||||
`最晚付款日期 ${new Date(payBy).toLocaleDateString("zh-CN")} 早于提交日期 ${new Date(submitAt).toLocaleDateString("zh-CN")}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return issues;
|
||||
}
|
||||
|
||||
/** 存在 error 级别的校验问题时抛出 ValidationError。 */
|
||||
export function assertBillDraftValid(
|
||||
form: BillDraftForm | undefined,
|
||||
options: ValidateOptions = {}
|
||||
): void {
|
||||
const issues = validateBillDraft(form, options);
|
||||
const errors = issues.filter((item) => item.severity === "error");
|
||||
if (errors.length === 0) return;
|
||||
throw new ValidationError(
|
||||
`单据校验未通过(${errors.length} 项错误):\n` +
|
||||
errors.map((item) => ` - [${item.field}] ${item.message}`).join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
/** 文本输出格式化,供 CLI 复用。 */
|
||||
export function formatValidationIssues(issues: ValidationIssue[]): string {
|
||||
if (issues.length === 0) return "✅ 单据校验通过:派生字段与必填项一致";
|
||||
return issues
|
||||
.map((item) => `${item.severity === "error" ? "❌" : "⚠️"} [${item.field}] ${item.message}`)
|
||||
.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { NotFoundError, ValidationError } from "../../core/errors.js";
|
||||
import { getFormSpecification, getRawBillFlow } from "./api.js";
|
||||
|
||||
/**
|
||||
* 纯接口提交单据草稿。
|
||||
*
|
||||
* 流程(实测):
|
||||
* 1. `POST /api/v1/flow/plans/computed` 计算审批计划(nodes)
|
||||
* 2. `POST /api/flow/v1/flows/$<flowId>?pushMessageCode=debug`
|
||||
* body: { name: "freeflow.submit", formType, form, nodes }
|
||||
*
|
||||
* 未指派审批人的节点必须由调用方通过 `--approver` 指定,绝不自动编造。
|
||||
*/
|
||||
|
||||
export interface SubmitBillOptions {
|
||||
/** 用于补齐未指派节点的审批人(员工 ID) */
|
||||
approverId?: string;
|
||||
}
|
||||
|
||||
export interface SubmitBillResult {
|
||||
flowId: string;
|
||||
code: string;
|
||||
nodeCount: number;
|
||||
response: unknown;
|
||||
}
|
||||
|
||||
interface PlanNode {
|
||||
id?: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
approverId?: unknown;
|
||||
approverIds?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export async function submitBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string,
|
||||
options: SubmitBillOptions = {}
|
||||
): Promise<SubmitBillResult> {
|
||||
const raw = await getRawBillFlow(client, corpId, target);
|
||||
const flow = raw && typeof raw.flowId === "object" ? (raw.flowId as Record<string, unknown>) : undefined;
|
||||
const form = flow && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : undefined;
|
||||
if (!flow || !form) {
|
||||
throw new NotFoundError(`未找到单号或 ID 为 [${target}] 的单据`);
|
||||
}
|
||||
|
||||
const flowId = String(flow.id ?? "");
|
||||
if (!flowId) throw new NotFoundError("单据缺少流程 ID");
|
||||
if (flow.state !== "draft") {
|
||||
throw new ValidationError(`单据当前状态为 ${String(flow.state)},仅 draft 可提交`);
|
||||
}
|
||||
|
||||
const specificationId = form.specificationId;
|
||||
const spec = specificationId
|
||||
? await getFormSpecification(client, corpId, String(specificationId))
|
||||
: undefined;
|
||||
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 planResponse = await client.post("api/v1/flow/plans/computed", {
|
||||
searchParams: { corpId },
|
||||
json: { flowId, flowPlanConfigId, form, formType, params: {} },
|
||||
});
|
||||
const planJson = (await planResponse.json()) as { value?: { nodes?: PlanNode[] } };
|
||||
const nodes = planJson.value?.nodes ?? [];
|
||||
if (nodes.length === 0) {
|
||||
throw new ValidationError("审批计划为空,无法提交");
|
||||
}
|
||||
|
||||
const unassigned: string[] = [];
|
||||
for (const node of nodes) {
|
||||
if (node.type === "ebot") continue;
|
||||
const hasApprover =
|
||||
Boolean(node.approverId) || (Array.isArray(node.approverIds) && node.approverIds.length > 0);
|
||||
if (hasApprover) continue;
|
||||
if (options.approverId) {
|
||||
if (node.type === "countersign") node.approverIds = [options.approverId];
|
||||
else node.approverId = options.approverId;
|
||||
} else {
|
||||
unassigned.push(String(node.name ?? node.id ?? "unknown"));
|
||||
}
|
||||
}
|
||||
if (unassigned.length > 0) {
|
||||
throw new ValidationError(
|
||||
`以下审批节点未指派审批人:${unassigned.join("、")};请通过 --approver 指定员工`
|
||||
);
|
||||
}
|
||||
|
||||
const response = await client.post(`api/flow/v1/flows/$${flowId}`, {
|
||||
searchParams: { corpId, pushMessageCode: "debug" },
|
||||
json: { id: flowId, name: "freeflow.submit", formType, form, nodes },
|
||||
});
|
||||
|
||||
return {
|
||||
flowId,
|
||||
code: String(form.code ?? target),
|
||||
nodeCount: nodes.length,
|
||||
response: await response.json(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { normalizeTemplateGroups } from "./templates.js";
|
||||
|
||||
const raw = [
|
||||
{
|
||||
name: "报销单拆单",
|
||||
active: true,
|
||||
specifications: [
|
||||
{ id: "a:1", originalId: "a", name: "AI合同审批单", type: "custom", active: true },
|
||||
{ id: "a:2", originalId: "a", name: "报销单-汇总", type: "expense", active: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "历史模板",
|
||||
active: true,
|
||||
specifications: [
|
||||
{ id: "b:1", originalId: "b", name: "旧报销单", type: "expense", active: false },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "空分组",
|
||||
active: true,
|
||||
specifications: [],
|
||||
},
|
||||
{
|
||||
name: "停用分组",
|
||||
active: false,
|
||||
specifications: [
|
||||
{ id: "c:1", originalId: "c", name: "隐藏模板", type: "expense", active: true },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe("normalizeTemplateGroups", () => {
|
||||
it("默认只返回启用模板,并跳过空分组/停用分组", () => {
|
||||
const result = normalizeTemplateGroups(raw);
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.inactive).toBe(1);
|
||||
expect(result.groups.map((g) => g.name)).toEqual(["报销单拆单"]);
|
||||
expect(result.groups[0].specifications.map((s) => s.name)).toEqual([
|
||||
"AI合同审批单",
|
||||
"报销单-汇总",
|
||||
]);
|
||||
});
|
||||
|
||||
it("includeInactive 返回停用模板与停用分组", () => {
|
||||
const result = normalizeTemplateGroups(raw, { includeInactive: true });
|
||||
expect(result.total).toBe(4);
|
||||
expect(result.groups.map((g) => g.name)).toEqual(["报销单拆单", "历史模板", "停用分组"]);
|
||||
const inactiveSpecs = result.groups.flatMap((g) => g.specifications).filter((s) => !s.active);
|
||||
expect(inactiveSpecs.map((s) => s.name)).toEqual(["旧报销单"]);
|
||||
});
|
||||
|
||||
it("优先使用 originalId,兼容含冒号的原始 ID", () => {
|
||||
const result = normalizeTemplateGroups([
|
||||
{
|
||||
name: "系统模板",
|
||||
active: true,
|
||||
specifications: [
|
||||
{
|
||||
id: "ID01ofWoOC1wiX:system:预算调整申请单:d3ac4cb25935090ab684d3fa4537b3517a849646",
|
||||
originalId: "ID01ofWoOC1wiX:system:预算调整申请单",
|
||||
name: "预算调整申请单",
|
||||
type: "custom",
|
||||
active: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(result.groups[0].specifications[0].id).toBe("ID01ofWoOC1wiX:system:预算调整申请单");
|
||||
expect(result.groups[0].specifications[0].versionedId).toContain(":d3ac4cb");
|
||||
});
|
||||
|
||||
it("保留分组名与模板类型", () => {
|
||||
const result = normalizeTemplateGroups(raw);
|
||||
expect(result.groups[0].specifications[0]).toMatchObject({
|
||||
id: "a",
|
||||
versionedId: "a:1",
|
||||
name: "AI合同审批单",
|
||||
type: "custom",
|
||||
group: "报销单拆单",
|
||||
active: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { KyInstance } from "ky";
|
||||
|
||||
/**
|
||||
* 单据模板(表单规格)列表。
|
||||
*
|
||||
* 页面「快速新建单据」读的是同一个接口:
|
||||
* GET /api/form/v2/specificationGroups/withSpecificationVersioned?corpId=
|
||||
* 响应按“规格分组 → 规格”组织,且已按当前身份做过可见性过滤。
|
||||
*
|
||||
* 默认只返回启用中的模板;`includeInactive` 用于排查/管理场景。
|
||||
*/
|
||||
|
||||
export interface BillTemplateSpec {
|
||||
/** 规格组 ID(可直接用于 `bill spec <id>` / 创建单据) */
|
||||
id: string;
|
||||
/** 服务端返回的版本化 ID(`<groupId>:<versionHash>`) */
|
||||
versionedId: string;
|
||||
name: string;
|
||||
type: string;
|
||||
active: boolean;
|
||||
group: string;
|
||||
}
|
||||
|
||||
export interface BillTemplateGroup {
|
||||
name: string;
|
||||
specifications: BillTemplateSpec[];
|
||||
}
|
||||
|
||||
export interface BillTemplateList {
|
||||
groups: BillTemplateGroup[];
|
||||
total: number;
|
||||
inactive: number;
|
||||
}
|
||||
|
||||
interface RawSpecification {
|
||||
id?: string;
|
||||
originalId?: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
/** 去掉版本化 ID 末尾的 `:<hash>`,保留可被 `bill spec` 使用的原始 ID。 */
|
||||
function stripVersionHash(id: string): string {
|
||||
return id.replace(/:[0-9a-f]{32,64}$/i, "");
|
||||
}
|
||||
|
||||
interface RawGroup {
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
specifications?: RawSpecification[];
|
||||
}
|
||||
|
||||
export interface ListBillTemplatesOptions {
|
||||
includeInactive?: boolean;
|
||||
}
|
||||
|
||||
export function normalizeTemplateGroups(
|
||||
items: RawGroup[],
|
||||
options: ListBillTemplatesOptions = {}
|
||||
): BillTemplateList {
|
||||
const includeInactive = options.includeInactive === true;
|
||||
const groups: BillTemplateGroup[] = [];
|
||||
let total = 0;
|
||||
let inactive = 0;
|
||||
|
||||
for (const item of items) {
|
||||
if (!includeInactive && item.active === false) continue;
|
||||
const specs: BillTemplateSpec[] = [];
|
||||
for (const spec of item.specifications ?? []) {
|
||||
if (!spec.id || !spec.name) continue;
|
||||
const active = spec.active !== false;
|
||||
if (!active) {
|
||||
inactive += 1;
|
||||
if (!includeInactive) continue;
|
||||
}
|
||||
const versionedId = spec.id;
|
||||
const originalId = typeof spec.originalId === "string" && spec.originalId.trim()
|
||||
? spec.originalId
|
||||
: stripVersionHash(versionedId);
|
||||
specs.push({
|
||||
id: originalId,
|
||||
versionedId,
|
||||
name: spec.name,
|
||||
type: spec.type ?? "unknown",
|
||||
active,
|
||||
group: item.name ?? "",
|
||||
});
|
||||
total += 1;
|
||||
}
|
||||
if (specs.length > 0) {
|
||||
groups.push({ name: item.name ?? "", specifications: specs });
|
||||
}
|
||||
}
|
||||
|
||||
return { groups, total, inactive };
|
||||
}
|
||||
|
||||
export async function listBillTemplates(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: ListBillTemplatesOptions = {}
|
||||
): Promise<BillTemplateList> {
|
||||
// 服务端/CDN 会缓存该 GET 响应,改名后可能读到旧名称;带时间戳强制回源。
|
||||
const response = await client.get("api/form/v2/specificationGroups/withSpecificationVersioned", {
|
||||
searchParams: { corpId, _t: String(Date.now()) },
|
||||
headers: { "cache-control": "no-cache", pragma: "no-cache" },
|
||||
});
|
||||
const json = (await response.json()) as { items?: RawGroup[]; value?: { items?: RawGroup[] } };
|
||||
const items = json.items ?? json.value?.items ?? [];
|
||||
return normalizeTemplateGroups(items, options);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import { EkbApiError } from "../../core/errors.js";
|
||||
|
||||
/**
|
||||
* 单据草稿写入动作(均通过 `POST /api/flow/v1/flows/$<flowId>` + `name` 区分)。
|
||||
*
|
||||
* 合思把「保存 / 提交 / 删除」都收敛在同一个端点,靠 action 名区分:
|
||||
* - `freeflow.edit` —— 保存草稿
|
||||
* - `freeflow.submit` —— 提交送审(需先计算审批计划并把 nodes 带回)
|
||||
* - `freeflow.delete` —— 删除草稿
|
||||
*
|
||||
* 本文件目前只实现风险最低、已在生产草稿上验证过的删除动作。
|
||||
*/
|
||||
|
||||
async function postFlowAction(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
flowId: string,
|
||||
name: string,
|
||||
extra: Record<string, unknown> = {},
|
||||
searchParams: Record<string, string> = {}
|
||||
): Promise<Record<string, unknown> | undefined> {
|
||||
const response = await client.post(`api/flow/v1/flows/$${flowId}`, {
|
||||
searchParams: { corpId, ...searchParams },
|
||||
json: { id: flowId, name, ...extra },
|
||||
});
|
||||
const text = await response.text();
|
||||
if (!text) return undefined;
|
||||
const json = JSON.parse(text) as { flow?: Record<string, unknown> };
|
||||
if (json.flow) return json.flow;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除草稿单据及其费用明细(`freeflow.delete`)。
|
||||
* 仅允许对 `draft` 状态单据调用——调用方需自行校验状态。
|
||||
*/
|
||||
export async function deleteBillDraft(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
flowId: string
|
||||
): Promise<void> {
|
||||
const flow = await postFlowAction(client, corpId, flowId, "freeflow.delete");
|
||||
if (!flow) {
|
||||
throw new EkbApiError("删除单据失败:服务端未返回流程对象", "BILL_DELETE_FAILED", 500);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user