diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 6bdcc7a..c11747f 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -33,6 +33,7 @@ metadata: | 代客协助凭证导入 / 探针连通性诊断 | `hose auth import`, `hose probe` | [references/auth.md](references/auth.md) | | 企业租户切换 / 查看当前企业 | `hose corps list`, `hose corps switch ` | [references/auth.md](references/auth.md) | | 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) | +| 单据审批动作(同意/驳回/转交/加签/评论) | `hose bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) | | 单据审批历史 / 当前节点 / 后续流程 | `hose bill flow <单号|ID>` | [references/bill.md](references/bill.md) | | 单据风控预警 / 预算状态 / 发票风险 | `hose bill risk <单号|ID>` | [references/bill.md](references/bill.md) | | 单据引用 ID 二级解析(人员/部门/费用类型) | `hose bill refs <单号|ID>` | [references/bill.md](references/bill.md) | @@ -83,6 +84,11 @@ hose bill link CL20260901001 # 生成官方 Web 详情 hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘 hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射) hose bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照 +hose bill approve S26000001 --yes # 同意当前待办 +hose bill reject S26000001 --comment "金额不符" --yes # 驳回并写明原因 +hose bill transfer S26000001 --approver-id 111 --yes # 转交给工号/员工 ID/唯一姓名 +hose bill add-node S26000001 --approver-id 111 --mode pre --yes # 前加签;--mode post 为后加签 +hose bill comment S26000001 --comment "请补充发票" --yes # 追加单据评论 hose bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型 hose bill relations S26000001 # 追溯冲借款、事前申请和合同关联 hose bill budget S26000001 # 查看单据预算超限和预算接口状态 diff --git a/skills/hose-use/references/bill.md b/skills/hose-use/references/bill.md index 5eabfa5..3196818 100644 --- a/skills/hose-use/references/bill.md +++ b/skills/hose-use/references/bill.md @@ -68,6 +68,29 @@ hose-use bill risk CL20260903001 `bill risk` 聚合审批页“审查”面板的风控预警、信用规则、预算状态与发票风险接口;默认只输出摘要,`--json` 保留结构化原始结果。 +## 4. 单据审批动作套件 + +审批动作直接复用合思 Web 点击时的业务接口。写操作必须显式带 `--yes`;交互终端未带该参数时会进行二次确认,非交互终端会直接拒绝,避免脚本误写业务状态。 + +```bash +# 同意:可附带纯文本审批意见 +hose bill approve S26000001 --comment "同意" --yes + +# 驳回:原因是必填项;默认退回提交人,可用 --reject-to 指定目标 +hose bill reject S26000001 --comment "请补充发票" --yes + +# 转交:--approver-id 支持完整员工 ID、工号或唯一姓名 +hose bill transfer S26000001 --approver-id 111 --yes + +# 加签:默认前加签,--mode post 表示后加签 +hose bill add-node S26000001 --approver-id 111 --mode pre --comment "请协助复核" --yes + +# 评论:支持 --participants 传入逗号分隔的人员 ID +hose bill comment S26000001 --comment "补充说明" --participants --yes +``` + +动作解析流程会先通过审批 backlog 详情定位 `backlogId`、`flowId` 和当前节点 ID;当响应包含 `flow.actions` 时,会校验当前登录员工是否拥有对应的 `freeflow.*` 动作。底层请求对应:`freeflow.agree`、`freeflow.reject`、`freeflow.addnode` 和 `freeflow.comment`。 + ### 单据引用 ID 二级解析 (`bill refs`) 读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID: @@ -115,7 +138,7 @@ hose bill download S26000001 --output-dir ./downloads hose bill download S26000001 --file-id ID01THIU98FNyT --output-dir ./downloads --json ``` -## 4. 单据实体元数据字典 (`bill schema`) +## 5. 单据实体元数据字典 (`bill schema`) 用于探查当前企业所有单据实体、字段类型与扩展属性定义: @@ -126,7 +149,7 @@ hose-use bill schema --json --- -## 5. 上下文防爆保护与安全转储 +## 6. 上下文防爆保护与安全转储 合思复杂的报销单通常携带大量明细行、发票 OCR 原生报文与附件列表,查询结果动辄数万行(几百 KB 到数 MB)。 diff --git a/src/cli/commands/bill.ts b/src/cli/commands/bill.ts index 82c6162..0c01e34 100644 --- a/src/cli/commands/bill.ts +++ b/src/cli/commands/bill.ts @@ -12,6 +12,12 @@ import { getBillAttachments, downloadBillAttachments, getFieldDictionary, + approveBill, + rejectBill, + transferBill, + addNodeBill, + commentBill, + resolveBillStaffIds, } from "../../domains/bill/tools.js"; export async function handleBillCommand( @@ -29,7 +35,98 @@ export async function handleBillCommand( const action = parsed.action?.toLowerCase(); const corpId = corp.corpId || corp.id; + const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]); + const requireWriteConfirmation = async () => { + if (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return; + if (!process.stdin.isTTY || !process.stdout.isTTY) { + throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。"); + } + const { prompt } = await import("../helpers.js"); + const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: "); + if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作"); + }; + const listOption = (keys: string[]): string[] | undefined => { + const value = stringOption(parsed.options, keys); + if (!value) return undefined; + const values = value.split(",").map((item) => item.trim()).filter(Boolean); + return values.length ? values : undefined; + }; + const actionOptions = () => ({ + currentStaffId: corp.staffId || corp.credentials.staffId, + reminder: booleanOption(parsed.options, ["reminder", "remind"]), + keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]), + comment: stringOption(parsed.options, ["comment", "message", "opinion"]), + participants: listOption(["participant", "participants"]), + approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]), + rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]), + resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START", + addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => { + const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase(); + return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE"; + })(), + }); + const resolveApproverIds = async (values: string[] | undefined): Promise => { + if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名"); + return resolveBillStaffIds(client, corpId, values); + }; + switch (action) { + case "approve": + case "agree": { + await requireWriteConfirmation(); + const target = actionTarget(); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill approve <单号|ID> --yes"); + const result = await approveBill(client, corpId, target, actionOptions()); + if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; + return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; + } + + case "reject": + case "deny": { + await requireWriteConfirmation(); + const target = actionTarget(); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill reject <单号|ID> --comment <原因> --yes"); + const options = actionOptions(); + if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因"); + const result = await rejectBill(client, corpId, target, options); + if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; + return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; + } + + case "transfer": + case "shift": { + await requireWriteConfirmation(); + const target = actionTarget(); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill transfer <单号|ID> --approver-id <员工ID> --yes"); + const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) }; + const result = await transferBill(client, corpId, target, options); + if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; + return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; + } + + case "add-node": + case "addnode": + case "countersign": + case "counter-sign": { + await requireWriteConfirmation(); + const target = actionTarget(); + if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose bill add-node <单号|ID> --approver-id <员工ID> --yes"); + const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) }; + const result = await addNodeBill(client, corpId, target, options); + if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; + return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 }; + } + + case "comment": + case "remark": { + await requireWriteConfirmation(); + const target = actionTarget(); + if (!target) throw new Error("请提供单号或单据 ID: hose bill comment <单号|ID> --comment <内容> --yes"); + const result = await commentBill(client, corpId, target, actionOptions()); + if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; + return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 }; + } + case "list": case "search": case undefined: { diff --git a/src/cli/parser.ts b/src/cli/parser.ts index a9c9ba8..05fefd9 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -23,6 +23,9 @@ const KNOWN_BOOLEAN_FLAGS = new Set([ "allow-full", "allowFull", "summary", + "yes", + "confirm", + "force-write", ]); export function parseArgs(rawArgs: string[]): CliParsedArgs { diff --git a/src/cli/printer.ts b/src/cli/printer.ts index 79cfee3..726638a 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -119,7 +119,7 @@ export function printHelp(): string { corps 多企业租户管理 (list, switch, current) config 全局运行模式与路径诊断 (show, paths, mode , set) workflow 工作流管理 (list, get, find, analyze, toggle) - bill 单据与费用明细检索 (list, get <单号|ID> [--risk], refs <单号|ID>, relations <单号|ID>, attachments <单号|ID>, download <单号|ID>, flow <单号|ID>, risk <单号|ID>, budget <单号|ID>, schema, link <单号|ID>) + bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link) contact 企业通讯录与人员检索 (list, search <关键词>, get ) task 待办中心与审批任务 (todo, approved, records, submitted, cc) message 消息中心与通知管理 (list, count, read, read-all) @@ -143,6 +143,7 @@ export function printHelp(): string { --full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截) --stateless 单次强制以无状态模式执行 --stateful 单次强制以有状态模式执行 + --yes, -y 确认执行会改变单据状态的审批动作 --help, -h 查看帮助信息 常用示例: @@ -181,6 +182,11 @@ export function printHelp(): string { hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆 hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情 hose-use bill get S26000001 --risk # 在详情中附加费控风控与发票风险快照 + hose-use bill approve S26000001 --yes # 同意待审批单据 + hose-use bill reject S26000001 --comment "金额不符" --yes # 驳回并填写原因 + hose-use bill transfer S26000001 --approver-id <员工ID> --yes # 转交审批 + hose-use bill add-node S26000001 --approver-id <员工ID> --mode pre --yes # 前加签 + hose-use bill comment S26000001 --comment "请补充发票" --yes # 添加单据评论 hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档 hose-use service start # 后台启动常驻守护进程服务 hose-use service status # 查看守护进程运行状态与接口地址 diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index aa61d0a..655e364 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -1,13 +1,13 @@ # Bill 域说明 -本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票、关联引用与数据实体元数据字典的检索与格式化。 +本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票、关联引用、审批动作与数据实体元数据字典的检索、执行与格式化。 ## 文件结构 ```text src/domains/bill/ -├── api.ts # 传输层:调用单据、审批详情、组织架构和费用类型目录 API -├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与 MCP tools +├── api.ts # 传输层:调用单据、审批详情、审批动作、组织架构和费用类型目录 API +├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与动作编排 ├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义 ├── bill.test.ts # 单元测试 └── README.bill.md # 本说明文件 @@ -29,3 +29,11 @@ src/domains/bill/ - 从审批详情中的 `expenseLink`、`loan`、`requisition`、`contract` 等关系字段抽取前置单据树,保留原始对象供 JSON 下钻。 6. **附件标准化 (`getBillAttachments`)**: - 递归识别表单中的 `attachments`、`fileId`、`fileName`、`key` 与原件 URL,统一输出附件清单并去重。 +7. **审批动作套件**: + - `approveBill` 调用 `POST /api/flow/v2/backlogs/$`,使用 `freeflow.agree` 节点报文; + - `rejectBill` 调用 `POST /api/flow/v2/backlogs/approveListWithNode`,使用 `freeflow.reject` 批量报文,评论会转为 `

...

`; + - `transferBill` 与 `addNodeBill` 共用 backlog 动作接口,分别使用 `SHIFT_NODE`、`PRE_ADD_NODE`/`AFT_ADD_NODE`; + - `commentBill` 调用 `POST /api/flow/v1/flows/comment/$`,使用 `freeflow.comment`,保留参与人和私密评论参数; + - 动作执行前从审批详情解析 backlog ID、流程 ID、当前节点 ID,并可依据 `flow.actions` 校验当前身份是否具备该动作权限。 + +CLI 入口为 `hose bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。 diff --git a/src/domains/bill/api.ts b/src/domains/bill/api.ts index a264176..d1f4af7 100644 --- a/src/domains/bill/api.ts +++ b/src/domains/bill/api.ts @@ -112,6 +112,171 @@ export async function getRawBillFlow( return json.value ?? json.items?.[0]; } +export interface BillActionTarget { + backlogId: string; + flowId: string; + billId?: string; + billCode?: string; + nodeId?: string; + nodeName?: string; + raw: Record; +} + +export interface BillActionOptions { + currentStaffId?: string; + reminder?: boolean; + keepItSecret?: boolean; + comment?: string; + participants?: string[]; + approverIds?: string[]; + rejectTo?: string | null; + resubmitMethod?: string; + addNodeType?: "PRE_ADD_NODE" | "AFT_ADD_NODE"; +} + +async function readActionResponse(response: Response): Promise { + if (response.status === 204) return undefined; + const text = await response.text(); + if (!text) return undefined; + try { + return JSON.parse(text) as unknown; + } catch { + return text; + } +} + +function htmlComment(comment: string | undefined): string { + const value = comment ?? ""; + return `

${value + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'")}

`; +} + +function backlogSearchParams(corpId: string): Record { + return { messageCode: "debug", corpId }; +} + +export async function approveBillAction( + client: KyInstance, + corpId: string, + target: BillActionTarget, + options: BillActionOptions = {}, +): Promise { + const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, { + searchParams: backlogSearchParams(corpId), + json: { + node: { + flowId: target.flowId, + id: target.nodeId, + name: "freeflow.agree", + }, + reminder: options.reminder ?? false, + keepItSecret: options.keepItSecret ?? false, + comment: options.comment ?? "", + participants: options.participants ?? [], + isSingle: true, + id: target.backlogId, + name: "freeflow.agree", + }, + }); + return readActionResponse(response); +} + +export async function rejectBillAction( + client: KyInstance, + corpId: string, + target: BillActionTarget, + options: BillActionOptions = {}, +): Promise { + const response = await client.post("api/flow/v2/backlogs/approveListWithNode", { + searchParams: backlogSearchParams(corpId), + json: { + data: [{ + id: target.backlogId, + resubmitMethod: options.resubmitMethod ?? "TO_REJECTOR", + reminder: options.reminder ?? false, + keepItSecret: options.keepItSecret ?? false, + rejectTo: options.rejectTo ?? null, + comment: htmlComment(options.comment), + participants: options.participants ?? [], + name: "freeflow.reject", + }], + }, + }); + return readActionResponse(response); +} + +export async function transferBillAction( + client: KyInstance, + corpId: string, + target: BillActionTarget, + options: BillActionOptions = {}, +): Promise { + const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, { + searchParams: backlogSearchParams(corpId), + json: { + reminder: options.reminder ?? false, + keepItSecret: options.keepItSecret ?? false, + approverId: options.approverIds ?? [], + type: "SHIFT_NODE", + autographImageId: "", + comment: options.comment ? htmlComment(options.comment) : "", + participants: options.participants ?? [], + id: target.backlogId, + name: "freeflow.addnode", + }, + }); + return readActionResponse(response); +} + +export async function addNodeBillAction( + client: KyInstance, + corpId: string, + target: BillActionTarget, + options: BillActionOptions = {}, +): Promise { + const response = await client.post(`api/flow/v2/backlogs/$${target.backlogId}`, { + searchParams: backlogSearchParams(corpId), + json: { + reminder: options.reminder ?? false, + keepItSecret: options.keepItSecret ?? false, + approverId: options.approverIds ?? [], + type: options.addNodeType ?? "PRE_ADD_NODE", + autographImageId: "", + comment: htmlComment(options.comment), + participants: options.participants ?? [], + id: target.backlogId, + name: "freeflow.addnode", + }, + }); + return readActionResponse(response); +} + +export async function commentBillAction( + client: KyInstance, + corpId: string, + target: BillActionTarget, + options: BillActionOptions = {}, +): Promise { + const response = await client.post(`api/flow/v1/flows/comment/$${target.flowId}`, { + searchParams: { messageCode: "debug", corpId }, + json: { + id: target.flowId, + params: { + comment: htmlComment(options.comment), + participants: options.participants ?? [], + attachments: [], + keepItSecret: options.keepItSecret ?? false, + }, + name: "freeflow.comment", + }, + }); + return readActionResponse(response); +} + export async function getRawBillRisk( client: KyInstance, corpId: string, diff --git a/src/domains/bill/bill.test.ts b/src/domains/bill/bill.test.ts index 6989344..5db4221 100644 --- a/src/domains/bill/bill.test.ts +++ b/src/domains/bill/bill.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "bun:test"; -import { formatSingleBill, getBillReferences, getBillRelations, getBillAttachments, getBillRisk, getBillFlow } from "./tools.js"; +import { formatSingleBill, getBillReferences, getBillRelations, getBillAttachments, getBillRisk, getBillFlow, approveBill, rejectBill, transferBill, addNodeBill, commentBill, resolveBillStaffIds } from "./tools.js"; import { RawBillItemSchema, EntitySchema } from "./types.js"; describe("Bill Domain", () => { @@ -209,4 +209,76 @@ describe("Bill Domain", () => { expect(result?.history[1]?.automatic).toBe(true); expect(result?.history[1]?.skipped).toBe(true); }); + + it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => { + const calls: Array<{ path: string; options: any }> = []; + const client = { + post: async (path: string, options: any) => { + calls.push({ path, options }); + if (path.includes("backlogs/search")) { + return new Response(JSON.stringify({ items: [{ id: "backlog-action", flowId: { id: "flow-action", form: { code: "E26000007" } } }] })); + } + if (path.includes("backlogs/id")) { + return new Response(JSON.stringify({ value: { + id: "backlog-action", + nodeId: "FLOW:node-action", + nodeName: "直接领导审批", + state: "APPROVING", + flowId: { id: "flow-action", form: { code: "E26000007" }, plan: { nodes: [] } }, + } })); + } + return new Response(null, { status: 204 }); + }, + } as any; + + await approveBill(client, "corp-action", "E26000007", { comment: "同意" }); + const approveCall = calls.at(-1); + expect(approveCall?.path).toBe("api/flow/v2/backlogs/$backlog-action"); + expect(approveCall?.options.json).toMatchObject({ + node: { flowId: "flow-action", id: "FLOW:node-action", name: "freeflow.agree" }, + comment: "同意", + name: "freeflow.agree", + }); + + await rejectBill(client, "corp-action", "E26000007", { comment: "金额 < 不符" }); + expect(calls.at(-1)?.path).toBe("api/flow/v2/backlogs/approveListWithNode"); + expect(calls.at(-1)?.options.json.data[0]).toMatchObject({ + id: "backlog-action", + comment: "

金额 < 不符

", + name: "freeflow.reject", + }); + + await transferBill(client, "corp-action", "E26000007", { approverIds: ["staff-2"] }); + expect(calls.at(-1)?.options.json).toMatchObject({ + approverId: ["staff-2"], + type: "SHIFT_NODE", + name: "freeflow.addnode", + }); + + await addNodeBill(client, "corp-action", "E26000007", { approverIds: ["staff-3"], comment: "请协助", addNodeType: "AFT_ADD_NODE" }); + expect(calls.at(-1)?.options.json).toMatchObject({ + approverId: ["staff-3"], + type: "AFT_ADD_NODE", + comment: "

请协助

", + name: "freeflow.addnode", + }); + + await commentBill(client, "corp-action", "E26000007", { comment: "补充说明" }); + expect(calls.at(-1)?.path).toBe("api/flow/v1/flows/comment/$flow-action"); + expect(calls.at(-1)?.options.json).toMatchObject({ + id: "flow-action", + params: { comment: "

补充说明

", participants: [], attachments: [], keepItSecret: false }, + name: "freeflow.comment", + }); + }); + + it("resolves transfer and add-node people by full ID, employee code or unique name", async () => { + const client = { + get: async () => new Response(JSON.stringify({ items: [ + { id: "corp:staff-1", userId: "user-1", code: "101", name: "谢子豪" }, + { id: "corp:staff-2", userId: "user-2", code: "111", name: "沈玥妍" }, + ] })), + } as any; + await expect(resolveBillStaffIds(client, "corp-action", ["111", "谢子豪"])).resolves.toEqual(["corp:staff-2", "corp:staff-1"]); + }); }); diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index a1db62e..8c29b31 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -13,6 +13,13 @@ import { getDepartmentTree, getFeeTypeTree, resolveAttachmentFiles, + approveBillAction, + rejectBillAction, + transferBillAction, + addNodeBillAction, + commentBillAction, + type BillActionOptions, + type BillActionTarget, } from "./api.js"; import { type RawBillItem, @@ -768,6 +775,150 @@ export async function getBillFlow( }; } +function actionTarget(raw: Record, fallback: string): BillActionTarget { + const flow = raw.flowId && typeof raw.flowId === "object" ? raw.flowId as Record : {}; + const form = flow.form && typeof flow.form === "object" ? flow.form as Record : {}; + const backlogId = typeof raw.id === "string" ? raw.id : fallback; + const flowId = typeof flow.id === "string" ? flow.id : undefined; + if (!flowId) throw new Error(`未找到单据流程 ID: ${fallback}`); + const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record : {}; + const nodes = Array.isArray(plan.nodes) ? plan.nodes : []; + const nodeName = typeof raw.nodeName === "string" ? raw.nodeName : undefined; + const currentNode = nodes.find((value) => { + const node = value && typeof value === "object" ? value as Record : {}; + return typeof raw.nodeId === "string" && node.id === raw.nodeId || nodeName && node.name === nodeName; + }); + return { + backlogId, + flowId, + billId: flowId, + billCode: typeof form.code === "string" ? form.code : undefined, + nodeId: typeof raw.nodeId === "string" ? raw.nodeId : currentNode && typeof currentNode === "object" && typeof (currentNode as Record).id === "string" ? (currentNode as Record).id as string : undefined, + nodeName, + raw, + }; +} + +async function resolveActionTarget(client: KyInstance, corpId: string, target: string): Promise { + const raw = await getRawBillFlow(client, corpId, target); + if (!raw) throw new Error(`未找到单据或审批任务: ${target}`); + return actionTarget(raw, target); +} + +export interface BillActionResult { + action: "approve" | "reject" | "transfer" | "add-node" | "comment"; + corpId: string; + target: string; + backlogId: string; + flowId: string; + billId?: string; + billCode?: string; + nodeId?: string; + response?: unknown; +} + +export async function resolveBillStaffIds( + client: KyInstance, + corpId: string, + values: string[], +): Promise { + const catalog = await listActiveStaffCatalog(client, corpId); + const normalized = (value: string) => value.trim().toLowerCase(); + const matchesFor = (value: string) => { + const target = normalized(value); + return catalog.filter((staff) => { + const id = typeof staff.id === "string" ? staff.id : ""; + const userId = typeof staff.userId === "string" ? staff.userId : ""; + const name = typeof staff.name === "string" ? staff.name : ""; + const code = typeof staff.code === "string" ? staff.code : ""; + return [id, userId, name, code].some((candidate) => { + const lowered = normalized(candidate); + return lowered === target || lowered.endsWith(`:${target}`); + }); + }); + }; + const result: string[] = []; + for (const value of values) { + const matches = matchesFor(value); + if (matches.length !== 1) { + if (matches.length > 1) throw new Error(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`); + throw new Error(`未找到员工 [${value}]`); + } + const id = typeof matches[0]?.id === "string" ? matches[0].id : undefined; + if (!id) throw new Error(`员工 [${value}] 缺少可用 ID`); + result.push(id); + } + return result; +} + +async function runBillAction( + client: KyInstance, + corpId: string, + target: string, + action: BillActionResult["action"], + options: BillActionOptions = {}, +): Promise { + const resolved = await resolveActionTarget(client, corpId, target); + if (options.currentStaffId && action !== "comment") { + const flow = resolved.raw.flowId && typeof resolved.raw.flowId === "object" ? resolved.raw.flowId as Record : {}; + const actions = flow.actions && typeof flow.actions === "object" ? flow.actions as Record : undefined; + if (actions && Object.keys(actions).length > 0) { + const current = options.currentStaffId; + const currentTail = current.split(":").at(-1) || current; + const entry = Object.entries(actions).find(([staffId]) => { + const staffTail = staffId.split(":").at(-1) || staffId; + return staffId === current || staffId.endsWith(`:${current}`) || current.endsWith(`:${staffId}`) || staffTail === currentTail; + }); + const allowed = entry?.[1]; + const requiredAction = action === "approve" ? "freeflow.agree" : action === "reject" ? "freeflow.reject" : "freeflow.addnode"; + if (!Array.isArray(allowed) || !allowed.includes(requiredAction)) { + throw new Error(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`); + } + } + } + let response: unknown; + if (action === "approve") response = await approveBillAction(client, corpId, resolved, options); + else if (action === "reject") response = await rejectBillAction(client, corpId, resolved, options); + else if (action === "transfer") response = await transferBillAction(client, corpId, resolved, options); + else if (action === "add-node") response = await addNodeBillAction(client, corpId, resolved, options); + else response = await commentBillAction(client, corpId, resolved, options); + return { + action, + corpId, + target, + backlogId: resolved.backlogId, + flowId: resolved.flowId, + billId: resolved.billId, + billCode: resolved.billCode, + nodeId: resolved.nodeId, + response, + }; +} + +export function approveBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { + return runBillAction(client, corpId, target, "approve", options); +} + +export function rejectBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { + if (!options.comment?.trim()) throw new Error("驳回原因不能为空"); + return runBillAction(client, corpId, target, "reject", options); +} + +export function transferBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { + if (!options.approverIds?.length) throw new Error("转交审批至少需要一个 approverId"); + return runBillAction(client, corpId, target, "transfer", options); +} + +export function addNodeBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { + if (!options.approverIds?.length) throw new Error("加签审批至少需要一个 approverId"); + return runBillAction(client, corpId, target, "add-node", options); +} + +export function commentBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) { + if (!options.comment?.trim()) throw new Error("评论内容不能为空"); + return runBillAction(client, corpId, target, "comment", options); +} + export async function getBillRisk( client: KyInstance, corpId: string,