feat(bill): add pure-API create and submit commands
- bill create: 按模板创建草稿(最小表单 + 一条费用明细,版本化 specificationId) - bill submit: plans/computed 计算审批计划 → freeflow.submit(未指派节点需显式 --approver) - 文档与 Skill 路由同步
This commit is contained in:
1 parent
1de9e3f552
commit
3c00a0c0a6
9 files changed
+920
-442
No files matched your search
Vendored
+465
-439
File diff suppressed because it is too large.
Load diff
@@ -116,6 +116,8 @@ metadata:
|
||||
| 单据实体模型与字段元数据查询 / 单据模板联动规格 | `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) |
|
||||
@@ -181,6 +183,8 @@ hose-use bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签
|
||||
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 # 复制为新草稿(不提交)
|
||||
|
||||
@@ -299,7 +299,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"validate": "校验单据派生字段一致性(金额/币种/发票总额/草稿状态)",
|
||||
"copy": "复制单据为新草稿(清空发票绑定,不提交)",
|
||||
"delete": "删除草稿单据(仅 draft,需 --yes)",
|
||||
"templates": "查看单据模板(默认仅启用,--all 含停用)"
|
||||
"templates": "查看单据模板(默认仅启用,--all 含停用)",
|
||||
"create": "按模板创建单据草稿(不提交)",
|
||||
"submit": "提交单据送审(会进入审批流)"
|
||||
},
|
||||
"options": [
|
||||
"--dry-run 只预览审批动作",
|
||||
@@ -343,7 +345,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"url": "link",
|
||||
"specification": "spec"
|
||||
},
|
||||
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 title 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,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,
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,8 @@ 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,
|
||||
@@ -129,7 +131,15 @@ export async function handleBillCommand(
|
||||
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 <单号>, validate <单号>, copy <单号> --yes, delete <单号> --yes, templates [--all]`);
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -12,6 +12,8 @@ src/domains/bill/
|
||||
├── 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 # 复制转换单测
|
||||
@@ -73,6 +75,14 @@ src/domains/bill/
|
||||
- 响应按「规格分组 → 规格」组织,且已由服务端按当前身份做可见性过滤;
|
||||
- 默认只返回启用中的模板,`--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
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
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 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 detail = {
|
||||
feeTypeId: feeType.id,
|
||||
specificationId: feeType.expenseSpecificationId,
|
||||
feeTypeForm: {
|
||||
amount: {
|
||||
standard: amount,
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
standardSymbol: "¥",
|
||||
standardNumCode: "156",
|
||||
standardStrCode: "CNY",
|
||||
},
|
||||
feeDate: expenseDate,
|
||||
},
|
||||
};
|
||||
|
||||
const form = {
|
||||
specificationId: versionedSpecificationId,
|
||||
title,
|
||||
submitterId,
|
||||
expenseDate,
|
||||
expenseDepartment,
|
||||
...(options.reason?.trim() ? { description: options.reason.trim() } : {}),
|
||||
details: [detail],
|
||||
};
|
||||
|
||||
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,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(),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user