From ffec604ed98fba7c0a0913cb2e63d986c5299b68 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 14 Oct 2026 22:00:55 +0800 Subject: [PATCH] feat(bill,flow): add unified bill trace and flow get diagnostic engine (Phase 2) --- src/cli/commands/bill/index.ts | 9 +- src/cli/commands/bill/search.ts | 103 ++++++++++++- src/cli/commands/flow.test.ts | 248 +++++++++++++++++++++++++++++++ src/cli/commands/flow.ts | 99 +++++++++++++ src/cli/registry.ts | 6 + src/domains/bill/README.bill.md | 8 +- src/domains/bill/api.ts | 100 +++++++++---- src/domains/bill/bill.test.ts | 126 ++++++++++++++++ src/domains/bill/tools.ts | 254 ++++++++++++++++++++++++++++++++ src/domains/bill/types.ts | 49 ++++++ 10 files changed, 970 insertions(+), 32 deletions(-) create mode 100644 src/cli/commands/flow.test.ts create mode 100644 src/cli/commands/flow.ts diff --git a/src/cli/commands/bill/index.ts b/src/cli/commands/bill/index.ts index a0cff76..fa5f46d 100644 --- a/src/cli/commands/bill/index.ts +++ b/src/cli/commands/bill/index.ts @@ -1,7 +1,7 @@ import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { createBillActionContext } from "./context.js"; import { handleApprove, handleReject, handleTransfer, handleAddNode, handleComment } from "./approve.js"; -import { handleList, handleGet } from "./search.js"; +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"; @@ -53,6 +53,11 @@ export async function handleBillCommand( case "find": return handleGet(ctx); + case "trace": + case "inspect": + case "diagnose": + return handleTrace(ctx); + case "schema": case "schemas": case "entities": @@ -100,6 +105,6 @@ export async function handleBillCommand( return handleSpec(ctx); default: - throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec , refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`); + throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], trace <单号|ID>, spec , refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`); } } diff --git a/src/cli/commands/bill/search.ts b/src/cli/commands/bill/search.ts index d3d737c..9804ff3 100644 --- a/src/cli/commands/bill/search.ts +++ b/src/cli/commands/bill/search.ts @@ -1,6 +1,6 @@ -import { getBillByCodeOrId, getBillRisk, searchAndFormatBills } from "../../../domains/bill/tools.js"; +import { getBillByCodeOrId, getBillRisk, searchAndFormatBills, traceBillFlowDetail } from "../../../domains/bill/tools.js"; import { booleanOption, numberOption, stringOption } from "../../parser.js"; -import { printJson, printTable } from "../../printer.js"; +import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliResult } from "../../types.js"; import type { BillActionContext } from "./context.js"; @@ -198,3 +198,102 @@ export async function handleGet(ctx: BillActionContext): Promise { exitCode: 0, }; } + +export async function handleTrace(ctx: BillActionContext): Promise { + const { parsed, runtime, corp, corpId } = ctx; + const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "target", "flowId"]); + if (!target) { + throw new Error("请提供要穿透诊断的单号或单据/流程 ID: hose-use bill trace <单号|ID> 或 hose-use flow get <单号|ID>"); + } + + const client = await ctx.getClient(); + const report = await traceBillFlowDetail(client, corpId, target); + + if (!report.found) { + if (runtime.jsonMode) { + return { + stdout: printJson(report, runtime.outputOptions), + stderr: "", + exitCode: 1, + }; + } + return { + stdout: "", + stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到匹配 [${target}] 的单据或审批流实例\n 诊断提示: ${report.diagnostic.advice}\n`, + exitCode: 1, + }; + } + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + corpId, + corpName: corp.name, + ...report, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + const approverNames = report.pendingApprovers + .map((p) => (p.name ? `${p.name}${p.code ? ` (${p.code})` : ""}` : p.id)) + .filter(Boolean) + .join("、"); + + const lines: string[] = [ + `====== 单据全域穿透诊断 [${report.billCode || report.target}] ======`, + printKeyValue({ + "单据编号": report.billCode || "-", + "单据 ID": report.billId || "-", + "流程实例 (flowId)": report.flowId || "-", + "单据类型": report.specificationName + ? `${report.specificationName}${report.specificationId ? ` (${report.specificationId})` : ""}` + : "-", + "单据标题": report.title || "-", + "提报人员": report.submitter + ? `${report.submitter.name || "-"}${report.submitter.id ? ` (${report.submitter.id})` : ""}` + : "-", + "归属部门": report.department || "-", + "提报时间": report.submitDate || "-", + "单据金额": report.amount || "-", + "全局流转状态": `${report.state || "-"} (${report.rawState || "-"})`, + }), + "", + "── 🩺 待办与审批诊断 ──", + ` 阶段判定 : ${report.diagnostic.stageLabel}`, + ` 当前驻留节点: ${report.currentNode?.name || "-"}${report.currentNode?.id ? ` (${report.currentNode.id})` : ""}`, + ` 待办处理人: ${approverNames || "(当前无待办审批人)"}`, + ` 是否可审批: ${report.diagnostic.canApprove ? "✅ 是 (支持执行同意/驳回)" : "❌ 否 (当前不可审批)"}`, + ` 诊断结论 : ${report.diagnostic.summary}`, + ` 排障建议 : ${report.diagnostic.advice}`, + ]; + + if (report.timeline.length > 0) { + lines.push(""); + lines.push("── ⏱️ 审批流转历史轨迹 (Timeline) ──"); + const timelineRows = report.timeline.map((item) => [ + `#${item.index}`, + item.time || "-", + item.nodeName || "-", + item.operator?.name || item.operator?.id || (item.automatic ? "自动执行" : "-"), + item.action || item.state || "-", + item.comment ? (item.comment.length > 30 ? item.comment.slice(0, 30) + "..." : item.comment) : "-", + ]); + lines.push( + printTable( + ["#", "时间", "节点名称", "操作人", "动作", "审批意见"], + timelineRows + ) + ); + } + + return { + stdout: `${lines.join("\n")}\n`, + stderr: "", + exitCode: 0, + }; +} diff --git a/src/cli/commands/flow.test.ts b/src/cli/commands/flow.test.ts new file mode 100644 index 0000000..3d24b90 --- /dev/null +++ b/src/cli/commands/flow.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, it, spyOn, afterEach } from "bun:test"; +import { handleFlowCommand } from "./flow.js"; +import { handleBillCommand } from "./bill/index.js"; +import { findCommandByArea } from "../registry.js"; +import * as sessionModule from "../../core/http/session-client.js"; +import type { CliRuntime } from "../types.js"; +import type { CorpConfig } from "../../core/config/types.js"; + +const mockCorp: CorpConfig = { + id: "corp-test-1", + name: "测试企业", + baseUrl: "https://app.ekuaibao.com", + source: "openapi", + credentials: { + accessToken: "mock-token", + corpId: "corp-test-1", + staffId: "corp-test-1:STAFF_TEST", + }, +}; + +const mockRuntime: CliRuntime = { + corpContext: { + listCorps: () => [mockCorp], + getCurrent: () => mockCorp, + switchCorp: () => true, + resolve: () => mockCorp, + } as any, + selectedCorp: mockCorp, + jsonMode: false, + outputOptions: {}, +}; + +describe("CLI - flow & trace 全域透视与穿透诊断命令族", () => { + let spies: ReturnType[] = []; + + afterEach(() => { + for (const spy of spies) { + spy.mockRestore(); + } + spies = []; + }); + + it("registry 正确注册 flow 命令与 trace 别名", () => { + const flowDef = findCommandByArea("flow"); + expect(flowDef).toBeDefined(); + expect(flowDef?.area).toBe("flow"); + expect(flowDef?.aliases).toContain("trace"); + + const traceDef = findCommandByArea("trace"); + expect(traceDef).toBeDefined(); + expect(traceDef?.area).toBe("flow"); + }); + + it("未选中企业时返回错误并提示切换企业", async () => { + const res = await handleFlowCommand( + { + area: "flow", + action: "get", + args: ["ZJ-001"], + options: {}, + raw: ["flow", "get", "ZJ-001"], + }, + { ...mockRuntime, selectedCorp: null } + ); + expect(res.exitCode).toBe(1); + expect(res.stderr).toContain("未选中企业"); + }); + + it("hose-use flow --help 输出帮助信息", async () => { + const res = await handleFlowCommand( + { + area: "flow", + action: undefined, + args: [], + options: { help: true }, + raw: ["flow", "--help"], + }, + mockRuntime + ); + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("hose-use flow - 审批流全域透视与穿透诊断命令族"); + expect(res.stdout).toContain("hose-use flow get <单号|ID>"); + }); + + it("hose-use flow <单号> (位置参数) 自动识别并穿透诊断", async () => { + const mockRawFlow = { + id: "backlog-1", + state: "APPROVING", + flowId: { + id: "flow-1", + state: "APPROVING", + form: { + code: "ZJ-20261014-001", + title: "转转合同付款", + payMoney: "12500.00", + submitterId: { id: "u1", name: "张敏" }, + expenseDepartment: { name: "财务部" }, + }, + plan: { + nodes: [ + { id: "n1", name: "出纳打款", state: "APPROVING", approverId: { id: "u2", name: "李出纳" } }, + ], + }, + logs: [], + }, + }; + + const mockClient = { + post: async () => new Response(JSON.stringify({ value: mockRawFlow })), + } as any; + + spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient)); + + const res = await handleFlowCommand( + { + area: "flow", + action: "zj-20261014-001", + args: [], + positional: ["flow", "ZJ-20261014-001"], + options: {}, + raw: ["flow", "ZJ-20261014-001"], + }, + mockRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("单据全域穿透诊断 [ZJ-20261014-001]"); + expect(res.stdout).toContain("提报人员"); + expect(res.stdout).toContain("张敏"); + expect(res.stdout).toContain("待办处理人: 李出纳"); + expect(res.stdout).toContain("出纳打款"); + }); + + it("hose-use flow get <单号> --json 结构化输出", async () => { + const mockRawFlow = { + id: "backlog-2", + state: "PAYING", + flowId: { + id: "flow-2", + state: "PAYING", + form: { + code: "ZJ-20261014-002", + title: "资金调拨", + }, + plan: { + nodes: [ + { id: "n1", name: "出纳打款", state: "APPROVING" }, + ], + }, + logs: [], + }, + }; + + const mockClient = { + post: async () => new Response(JSON.stringify({ value: mockRawFlow })), + } as any; + + spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient)); + + const res = await handleFlowCommand( + { + area: "flow", + action: "get", + args: ["ZJ-20261014-002"], + positional: ["flow", "get", "ZJ-20261014-002"], + options: { json: true }, + raw: ["flow", "get", "ZJ-20261014-002", "--json"], + }, + { ...mockRuntime, jsonMode: true } + ); + + expect(res.exitCode).toBe(0); + const parsed = JSON.parse(res.stdout); + expect(parsed.found).toBe(true); + expect(parsed.billCode).toBe("ZJ-20261014-002"); + expect(parsed.diagnostic.stage).toBe("PAYING"); + expect(parsed.diagnostic.canApprove).toBe(false); + expect(parsed.diagnostic.advice).toContain("400"); + }); + + it("hose-use bill trace <单号> 平滑集成并完成诊断", async () => { + const mockRawFlow = { + id: "backlog-3", + state: "APPROVING", + flowId: { + id: "flow-3", + state: "APPROVING", + form: { + code: "BX-999", + title: "日常差旅报销", + }, + plan: { + nodes: [ + { id: "n1", name: "总监审批", state: "APPROVING" }, + ], + }, + logs: [], + }, + }; + + const mockClient = { + post: async () => new Response(JSON.stringify({ value: mockRawFlow })), + } as any; + + spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient)); + + const res = await handleBillCommand( + { + area: "bill", + action: "trace", + args: ["BX-999"], + positional: ["bill", "trace", "BX-999"], + options: {}, + raw: ["bill", "trace", "BX-999"], + }, + mockRuntime + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("单据全域穿透诊断 [BX-999]"); + expect(res.stdout).toContain("总监审批"); + expect(res.stdout).toContain("是否可审批: ✅ 是"); + }); + + it("未找到单据时返回 exitCode 1 与排障建议", async () => { + const mockClient = { + post: async () => new Response(JSON.stringify({ items: [] })), + } as any; + + spies.push(spyOn(sessionModule, "createSessionClient").mockResolvedValue(mockClient)); + + const res = await handleFlowCommand( + { + area: "flow", + action: "get", + args: ["UNKNOWN-BILL"], + positional: ["flow", "get", "UNKNOWN-BILL"], + options: {}, + raw: ["flow", "get", "UNKNOWN-BILL"], + }, + mockRuntime + ); + + expect(res.exitCode).toBe(1); + expect(res.stderr).toContain("[NOT FOUND]"); + expect(res.stderr).toContain("诊断提示"); + }); +}); diff --git a/src/cli/commands/flow.ts b/src/cli/commands/flow.ts new file mode 100644 index 0000000..3766766 --- /dev/null +++ b/src/cli/commands/flow.ts @@ -0,0 +1,99 @@ +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; +import { createBillActionContext } from "./bill/context.js"; +import { handleTrace, handleList } from "./bill/search.js"; +import { handleFlow, handleRisk } from "./bill/flow.js"; +import { handleApprove, handleReject } from "./bill/approve.js"; + +function printFlowHelp(): string { + return [ + "hose-use flow - 审批流全域透视与穿透诊断命令族", + "", + "用法:", + " hose-use flow <单号|ID> 等价于 flow get/trace,快速透视单据流转与诊断待办", + " hose-use flow get <单号|ID> 深度穿透单据全貌、当前驻留节点与 400 待办根因诊断", + " hose-use flow trace <单号|ID> (别名) 同 flow get", + " hose-use flow history <单号|ID> 查看审批历史流转时间线与后续节点", + " hose-use flow risk <单号|ID> 查看费控与合规风控诊断", + " hose-use flow list [options] 列出当前待审批/已审批单据流", + " hose-use flow approve <单号|ID> 执行审批同意 (受 --dry-run 与 --yes 约束)", + " hose-use flow reject <单号|ID> 执行审批驳回 (受 --dry-run 与 --yes 约束)", + "", + "选项:", + " --corp= 指定操作企业 (默认激活企业)", + " --json 以 JSON 结构化格式输出诊断数据", + " --verbose 显示完整调试信息", + " -h, --help 显示帮助信息", + ].join("\n"); +} + +export async function handleFlowCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + if (parsed.options.help || parsed.action === "help") { + return { + stdout: printFlowHelp() + "\n", + stderr: "", + exitCode: 0, + }; + } + + const corp = runtime.selectedCorp; + if (!corp) { + return { + stdout: "", + stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", + exitCode: 1, + }; + } + + const action = parsed.action?.toLowerCase(); + const args = [...parsed.args]; + + // 1. 无动作无参数且无 --code/--id 选项时,默认展示列表 + if (!action && args.length === 0 && !parsed.options.code && !parsed.options.id) { + const ctx = createBillActionContext(parsed, runtime); + return handleList(ctx); + } + + // 2. 识别透视与穿透类动词 + const flowTraceActions = new Set(["get", "trace", "inspect", "diagnose", "show", "find"]); + if (action && flowTraceActions.has(action)) { + const ctx = createBillActionContext(parsed, runtime); + return handleTrace(ctx); + } + + // 3. 识别其他常用审批流动作 + const flowOtherActions = new Set(["history", "records", "timeline", "risk", "list", "search", "approve", "agree", "reject", "deny"]); + if (action && flowOtherActions.has(action)) { + const ctx = createBillActionContext(parsed, runtime); + switch (action) { + case "history": + case "records": + case "timeline": + return handleFlow(ctx); + case "risk": + return handleRisk(ctx); + case "list": + case "search": + return handleList(ctx); + case "approve": + case "agree": + return handleApprove(ctx); + case "reject": + case "deny": + return handleReject(ctx); + } + } + + // 4. 用户直接输入单号:hose-use flow <单号|ID> + // 从原始 positional[1] 获取未经 lowercase 转换的原始单号/ID + const rawTarget = parsed.positional?.[1] || parsed.action; + const rewrittenParsed: CliParsedArgs = { + ...parsed, + action: "trace", + args: [rawTarget!, ...args], + }; + const ctx = createBillActionContext(rewrittenParsed, runtime); + return handleTrace(ctx); +} diff --git a/src/cli/registry.ts b/src/cli/registry.ts index d7c53b1..8f85012 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -11,6 +11,7 @@ import { handleMcpCommand } from "./commands/mcp.js"; import { handleUpdateCommand } from "./commands/update/index.js"; import { handleOpenApiCommand } from "./commands/openapi.js"; import { handleBillCommand } from "./commands/bill/index.js"; +import { handleFlowCommand } from "./commands/flow.js"; import { handleContactCommand } from "./commands/contact.js"; import { handleServiceCommand } from "./commands/service.js"; import { handleHttpCommand } from "./commands/http.js"; @@ -81,6 +82,11 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [ aliases: ["bills", "fee", "fees", "invoice", "invoices"], handler: (parsed, runtime) => handleBillCommand(parsed, runtime), }, + { + area: "flow", + aliases: ["flows", "trace"], + handler: (parsed, runtime) => handleFlowCommand(parsed, runtime), + }, { area: "contact", aliases: ["contacts", "staff", "staffs"], diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index 2682f6e..3a07284 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -41,5 +41,11 @@ src/domains/bill/ - `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` 校验当前身份是否具备该动作权限。 +8. **全域单据穿透与待办诊断 (`traceBillFlowDetail`)**: + - 跨 `backlogs/search`、`flows/my`、`flows/approved`、`carbonCopy/search` 与 `backlogs/id` 多通道穿透检索单据流程实例; + - 智能提取单据金额、提报人、提报时间、归属部门、当前驻留节点与待办审批人列表; + - 内置待办根因诊断引擎,智能判定流转阶段(`DRAFT`、`APPROVING`、`PAYING`、`PAID`、`REJECTED`): + - 识别“待出纳支付/打款”节点(如 `PAYING` 或节点名包含“打款/出纳/支付”),精准提示不可审批及自动化工作流调用报错 400(无待办审批事项)的根本原因与排障建议; + - 结构化还原流转时间线轨迹(Timeline),自动标记 Ebot 智能审批与自动跳过节点。 -CLI 入口为 `hose-use bill approve|reject|transfer|add-node|comment <单号|ID>`。所有会改变状态的动作都要求 `--yes`(交互终端未提供时会拒绝执行);转交和加签的 `--approver-id` 支持完整员工 ID、工号或唯一姓名匹配,驳回强制要求 `--comment`。 +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`。 diff --git a/src/domains/bill/api.ts b/src/domains/bill/api.ts index 7325a12..6bd8e6c 100644 --- a/src/domains/bill/api.ts +++ b/src/domains/bill/api.ts @@ -63,12 +63,16 @@ export async function getRawBillFlow( corpId: string, target: string ): Promise | undefined> { + const cleanTarget = target.trim(); let match: Record | undefined; - const filters = [ - `(id==${quoted(target)})||((flowId.id==${quoted(target)})||(flowId.form.code==${quoted(target)}))`, + + // 通道 1: api/flow/v2/backlogs/search 精准单号与 ID 匹配 + const searchFilters = [ + `(id==${quoted(cleanTarget)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`, + `(flowId.form.code==${quoted(cleanTarget)})`, `(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))`, ]; - for (const filterBy of filters) { + for (const filterBy of searchFilters) { try { const lookup = await client.post("api/flow/v2/backlogs/search", { searchParams: { corpId }, @@ -82,36 +86,78 @@ export async function getRawBillFlow( match = (lookupJson.items ?? []).find((item) => { const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record : {}; const form = flow.form && typeof flow.form === "object" ? flow.form as Record : {}; - return item.id === target || flow.id === target || form.code === target; + return item.id === cleanTarget || flow.id === cleanTarget || form.code === cleanTarget; }); if (match) break; } catch { - // Fall through to the broad status lookup or direct detail request. + // 继续尝试其他检索 } } - const backlogId = typeof match?.id === "string" ? match.id : target; - const detail = await client.post("api/flow/v2/backlogs/id", { - searchParams: (() => { - const params = new URLSearchParams({ corpId }); - for (const join of [ - "flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments", - "flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code", - "flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments", - "flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code", - "flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code", - "flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code", - "flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code", - ]) params.append("join", join); - return params; - })(), - json: { - filterBy: `(id==${quoted(backlogId)})`, - select: flowDetailSelect(), - }, - }); - const json = (await detail.json()) as { value?: Record; items?: Record[] }; - return json.value ?? json.items?.[0]; + // 通道 2: 尝试从我发起的流程与已审批单据中检索 (flows/my & flows/approved) + if (!match) { + const endpoints = ["api/flow/v1/flows/my", "api/flow/v1/flows/approved", "api/flow/v2/carbonCopy/search"]; + for (const ep of endpoints) { + try { + const res = await client.post(ep, { + searchParams: { corpId }, + json: { + limit: { start: 0, count: 50 }, + filterBy: `(form.code==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)})`, + }, + }); + const json = (await res.json()) as { items?: Record[] }; + const found = (json.items ?? []).find((item) => { + const flow = item.flowId && typeof item.flowId === "object" ? item.flowId as Record : {}; + const form = (flow.form ?? item.form) as Record | undefined; + return item.id === cleanTarget || flow.id === cleanTarget || form?.code === cleanTarget; + }); + if (found) { + match = found; + break; + } + } catch { + // 忽略通道异常 + } + } + } + + 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 + : undefined; + + // 通道 3: 调用 api/flow/v2/backlogs/id 获取完整结构化详情 + try { + const filterByCond = flowIdFromMatch + ? `(id==${quoted(backlogId)})||(flowId.id==${quoted(flowIdFromMatch)})` + : `(id==${quoted(backlogId)})||((flowId.id==${quoted(cleanTarget)})||(flowId.form.code==${quoted(cleanTarget)}))`; + + const detail = await client.post("api/flow/v2/backlogs/id", { + searchParams: (() => { + const params = new URLSearchParams({ corpId }); + for (const join of [ + "flowId.form.submitterId,submitterId,/v1/organization/staffs?join=defaultDepartment,defaultDepartment,/v1/organization/departments", + "flowId.form.ownerId,ownerId,/v1/organization/staffs?select=id,name,code", + "flowId.form.expenseDepartment,expenseDepartment,/v1/organization/departments", + "flowId.logs.operatorId,operatorId,/v1/organization/staffs?select=id,name,code", + "flowId.logs.nextOperatorId,nextOperatorId,/v1/organization/staffs?select=id,name,code", + "flowId.plan.nodes.approverId,approverId,/v1/organization/staffs?select=id,name,code", + "flowId.plan.nodes.counterSigners.signerId,signerId,/v1/organization/staffs?select=id,name,code", + ]) params.append("join", join); + return params; + })(), + json: { + filterBy: filterByCond, + select: flowDetailSelect(), + }, + }); + const json = (await detail.json()) as { value?: Record; items?: Record[] }; + return json.value ?? json.items?.[0] ?? match; + } catch (err) { + if (match) return match; + throw err; + } } export interface BillActionTarget { diff --git a/src/domains/bill/bill.test.ts b/src/domains/bill/bill.test.ts index e94fd31..431392e 100644 --- a/src/domains/bill/bill.test.ts +++ b/src/domains/bill/bill.test.ts @@ -17,6 +17,7 @@ import { normalizeSearchFields, buildServerBillFilterBy, searchAndFormatBills, + traceBillFlowDetail, } from "./tools.js"; import { RawBillItemSchema, EntitySchema } from "./types.js"; @@ -712,5 +713,130 @@ describe("Bill Domain", () => { expect(resDefault.items.map((b) => b.billId)).toEqual(["bill-2", "bill-3"]); }); }); + + describe("traceBillFlowDetail 全域穿透诊断与待办根因分析", () => { + it("待审批状态:精准解析提报人、金额、当前节点与待办审批人,判定可审批", async () => { + const mockRawFlow = { + id: "backlog-101", + state: "APPROVING", + flowId: { + id: "flow-101", + state: "APPROVING", + form: { + code: "BX-20261014-001", + title: "差旅费用报销单", + expenseMoney: { amount: "1280.50" }, + submitDate: 1781682826000, + submitterId: { id: "staff-1", name: "张三", code: "ZS01" }, + expenseDepartment: { name: "研发部" }, + specificationId: { id: "spec-bx", name: "日常报销单" }, + }, + plan: { + nextNodeId: "node-2", + nodes: [ + { id: "node-1", name: "提单", state: "PROCESSED" }, + { id: "node-2", name: "直属主管审批", state: "APPROVING", approverId: { id: "staff-2", name: "李主管", code: "LZ01" } }, + ], + }, + logs: [ + { + action: "SUBMIT", + time: 1781682826000, + operatorId: { id: "staff-1", name: "张三" }, + attributes: { nodeName: "提单", comment: "请领导审批" }, + }, + ], + }, + }; + + const client = { + post: async (path: string) => { + if (path.includes("backlogs/search")) { + return new Response(JSON.stringify({ items: [mockRawFlow] })); + } + if (path.includes("backlogs/id")) { + return new Response(JSON.stringify({ value: mockRawFlow })); + } + return new Response(JSON.stringify({ items: [] })); + }, + } as any; + + const report = await traceBillFlowDetail(client, "test-corp", "BX-20261014-001"); + expect(report.found).toBe(true); + expect(report.billCode).toBe("BX-20261014-001"); + expect(report.amount).toBe("¥ 1280.50"); + expect(report.submitter?.name).toBe("张三"); + expect(report.department).toBe("研发部"); + expect(report.state).toBe("审批中"); + expect(report.currentNode?.name).toBe("直属主管审批"); + expect(report.pendingApprovers).toHaveLength(1); + expect(report.pendingApprovers[0].name).toBe("李主管"); + expect(report.diagnostic.stage).toBe("APPROVING"); + expect(report.diagnostic.canApprove).toBe(true); + expect(report.diagnostic.summary).toContain("待办审批人: 李主管"); + expect(report.timeline).toHaveLength(1); + expect(report.timeline[0].action).toBe("SUBMIT"); + }); + + it("待出纳打款节点 (PAYING):精准识别并诊断 400 根因与排障建议", async () => { + const mockRawFlow = { + id: "backlog-paying-01", + state: "APPROVING", + nodeName: "出纳打款", + flowId: { + id: "flow-paying-01", + state: "PAYING", + form: { + code: "ZJ-20261014-999", + title: "对公转账调拨", + payMoney: "50000.00", + specificationId: { id: "spec-zj", name: "资金调拨单" }, + }, + plan: { + nodes: [ + { id: "n1", name: "财务复核", state: "PROCESSED" }, + { id: "n2", name: "出纳打款", state: "APPROVING" }, + ], + }, + logs: [ + { + action: "AGREE", + time: 1781683000000, + operatorId: { id: "ebot_system", name: "ebot" }, + attributes: { isEbotNode: true, nodeName: "智能审核", comment: "风控核验通过" }, + }, + ], + }, + }; + + const client = { + post: async () => new Response(JSON.stringify({ value: mockRawFlow })), + } as any; + + const report = await traceBillFlowDetail(client, "test-corp", "ZJ-20261014-999"); + expect(report.found).toBe(true); + expect(report.diagnostic.stage).toBe("PAYING"); + expect(report.diagnostic.canApprove).toBe(false); + expect(report.diagnostic.stageLabel).toBe("待支付 / 出纳打款"); + expect(report.diagnostic.summary).toContain("出纳打款"); + expect(report.diagnostic.advice).toContain("400"); + expect(report.timeline[0].operator?.name).toBe("Ebot (智能审批)"); + expect(report.timeline[0].automatic).toBe(true); + }); + + it("单据不存在时返回友好未找到诊断报告", async () => { + const client = { + post: async () => new Response(JSON.stringify({ items: [] })), + } as any; + + const report = await traceBillFlowDetail(client, "test-corp", "NOT-EXIST-999"); + expect(report.found).toBe(false); + expect(report.target).toBe("NOT-EXIST-999"); + expect(report.diagnostic.canApprove).toBe(false); + expect(report.diagnostic.stage).toBe("UNKNOWN"); + expect(report.diagnostic.advice).toContain("请核对单号是否准确"); + }); + }); }); + diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index 35cf788..a00a018 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -55,6 +55,8 @@ import { type BillRelationsReport, type BillAttachment, type BillAttachmentReport, + type BillFlowTimelineItem, + type BillFlowTraceDiagnostic, type FormSpecification, type FormSpecificationComponent, type FormPriorityItem, @@ -960,6 +962,258 @@ export async function getBillFlow( }; } +function resolveFlowStage( + rawState: string, + nodeName?: string +): "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN" { + const s = rawState.toUpperCase(); + const n = (nodeName || "").toLowerCase(); + + if (s.includes("REJECT") || s === "TERMINATED") return "REJECTED"; + if (s === "PAID" || s === "COMPLETED" || s === "PROCESSED") return "PAID"; + if (s.includes("PAY") || n.includes("打款") || n.includes("出纳") || n.includes("支付")) return "PAYING"; + if (s.includes("APPROV") || s === "PENDING" || s === "SENDING") return "APPROVING"; + if (s.includes("DRAFT")) return "DRAFT"; + return "UNKNOWN"; +} + +function buildDiagnosticReport( + stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN", + rawState: string, + currentNodeName?: string, + pendingApprovers: { id?: string; name?: string; code?: string }[] = [] +): { + canApprove: boolean; + stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN"; + stageLabel: string; + summary: string; + advice: string; +} { + const approverNames = pendingApprovers.map((p) => p.name || p.id).filter(Boolean).join("、"); + + switch (stage) { + case "PAYING": + return { + canApprove: false, + stage, + stageLabel: "待支付 / 出纳打款", + summary: `单据已通过全部分级审批流转,当前停留在【${currentNodeName || "出纳打款"}】环节`, + advice: "该单据当前无待办审批任务,若调用自动审批接口必报 400(无待办审批事项)。出纳打款后单据即闭环;若属于自动化打款流水,请检查工作流触发器是否误推了待支付单据,建议增加条件【审批状态 等于 APPROVING】进行拦截。", + }; + case "APPROVING": + return { + canApprove: true, + stage, + stageLabel: "审批中 (待办审批)", + summary: `单据当前停留在【${currentNodeName || "审批"}】节点${approverNames ? `,待办审批人: ${approverNames}` : ""}`, + advice: "单据处于正常待办审批状态,当前待办人员或工作流自动化可正常执行同意 (agree) 或驳回 (reject) 操作。", + }; + case "REJECTED": + return { + canApprove: false, + stage, + stageLabel: "已驳回 / 已终止", + summary: "单据已流转至驳回或终止状态", + advice: "单据已终止流转,无法执行审批同意。请联系提报人员根据驳回意见重新修改并提交新单据。", + }; + case "PAID": + return { + canApprove: false, + stage, + stageLabel: "已闭环 / 已打款", + summary: "单据全流程已审批并通过出纳打款闭环", + advice: "单据已结束流转,无需任何人工或自动化操作。", + }; + case "DRAFT": + return { + canApprove: false, + stage, + stageLabel: "草稿未提交", + summary: "单据尚未正式提交进入审批流", + advice: "请提报人完成单据填写后点击提交。", + }; + default: + return { + canApprove: false, + stage, + stageLabel: rawState || "未知状态", + summary: `单据当前处于状态: ${rawState || "未知"}`, + advice: "请通过 Web 后台或联系管理员核对单据流转配置。", + }; + } +} + +/** + * 全域单据穿透诊断与待办全貌洞察 + */ +export async function traceBillFlowDetail( + client: KyInstance, + corpId: string, + targetQuery: string +): Promise { + const cleanTarget = targetQuery.trim(); + if (!cleanTarget) { + throw new ValidationError("请提供要穿透查询的单号或单据 ID"); + } + + // 1. 尝试直接获取流程全貌 + let rawFlow = await getRawBillFlow(client, corpId, cleanTarget); + + // 2. 如果直接流程未命中,尝试通过传统单据索引反查 + if (!rawFlow) { + try { + const bills = await getBillByCodeOrId(client, corpId, cleanTarget); + if (bills.length > 0) { + const firstBill = bills[0]; + const candidateId = firstBill.billId || firstBill.billCode; + if (candidateId) { + rawFlow = await getRawBillFlow(client, corpId, candidateId); + } + } + } catch { + // 容错并继续 + } + } + + if (!rawFlow) { + return { + found: false, + target: cleanTarget, + pendingApprovers: [], + diagnostic: { + canApprove: false, + stage: "UNKNOWN", + stageLabel: "未找到", + summary: `在当前企业下未找到匹配 "${cleanTarget}" 的单据或流程实例`, + advice: "请核对单号是否准确,或确认当前账号是否具备该业务流程的查看权限。", + }, + timeline: [], + }; + } + + const flow = rawFlow.flowId && typeof rawFlow.flowId === "object" ? (rawFlow.flowId as Record) : {}; + const form = flow.form && typeof flow.form === "object" ? (flow.form as Record) : ((rawFlow.form as Record) || {}); + const spec = form.specificationId && typeof form.specificationId === "object" ? (form.specificationId as Record) : {}; + const nodeState = rawFlow.nodeState && typeof rawFlow.nodeState === "object" ? (rawFlow.nodeState as Record) : {}; + const plan = flow.plan && typeof flow.plan === "object" ? (flow.plan as Record) : {}; + const nodes = Array.isArray(plan.nodes) ? (plan.nodes as Record[]) : []; + const logs = Array.isArray(flow.logs) ? (flow.logs as Record[]) : []; + + // 基础信息提取 + const billCode = typeof form.code === "string" ? form.code : typeof rawFlow.code === "string" ? rawFlow.code : undefined; + const billId = typeof rawFlow.id === "string" ? rawFlow.id : typeof form.id === "string" ? form.id : undefined; + const flowId = typeof flow.id === "string" ? flow.id : undefined; + const backlogId = typeof rawFlow.id === "string" ? rawFlow.id : undefined; + const specificationName = typeof spec.name === "string" ? spec.name : undefined; + const specificationId = typeof spec.id === "string" ? spec.id : undefined; + const title = typeof form.title === "string" ? form.title : typeof form.name === "string" ? form.name : undefined; + + // 金额提取 + let amountStr: string | undefined; + const rawMoney = form.expenseMoney || form.payMoney || form.loanMoney || form.requisitionMoney || form.amount; + if (rawMoney && typeof rawMoney === "object") { + const std = (rawMoney as any).standard ?? (rawMoney as any).amount; + if (std !== undefined) amountStr = `¥ ${std}`; + } else if (typeof rawMoney === "string" || typeof rawMoney === "number") { + amountStr = `¥ ${rawMoney}`; + } + + // 提交人与部门 + const submitter = flowPerson(form.submitterId || flow.ownerId); + const deptObj = form.expenseDepartment || form.defaultDepartment; + const department = deptObj && typeof deptObj === "object" ? (deptObj as any).name : undefined; + const submitDate = typeof form.submitDate === "number" ? new Date(form.submitDate).toLocaleString("zh-CN", { hour12: false }) : undefined; + + // 状态提取 + const rawState = String(rawFlow.state || flow.state || form.state || "").toUpperCase(); + const stateLabel = translateBillFlowState(rawState); + + // 当前驻留节点提取 + const nextNodeId = typeof plan.nextNodeId === "string" ? plan.nextNodeId : undefined; + const currentNodeName = typeof rawFlow.nodeName === "string" ? rawFlow.nodeName : typeof nodeState.nodeName === "string" ? nodeState.nodeName : undefined; + + let activeNode = nodes.find((n) => (nextNodeId && n.id === nextNodeId) || (currentNodeName && n.name === currentNodeName)); + if (!activeNode && nodes.length > 0) { + activeNode = nodes.find((n) => n.state === "APPROVING" || n.state === "approving" || n.status === "ACTIVE"); + } + + const currentNode = activeNode + ? { + id: typeof activeNode.id === "string" ? activeNode.id : undefined, + name: typeof activeNode.name === "string" ? activeNode.name : currentNodeName, + type: typeof activeNode.type === "string" ? activeNode.type : undefined, + } + : currentNodeName + ? { name: currentNodeName } + : undefined; + + // 待办审批人提取 + const pendingApprovers: { id?: string; name?: string; code?: string }[] = []; + if (activeNode) { + if (activeNode.approverId) { + const p = flowPerson(activeNode.approverId); + if (p) pendingApprovers.push(p); + } + if (Array.isArray(activeNode.counterSigners)) { + for (const signer of activeNode.counterSigners) { + const p = flowPerson(signer); + if (p) pendingApprovers.push(p); + } + } + } + + // 诊断规则引擎 + const stage = resolveFlowStage(rawState, currentNode?.name); + const diagnostic = buildDiagnosticReport(stage, rawState, currentNode?.name, pendingApprovers); + + // 流转时间线 + const timeline: BillFlowTimelineItem[] = logs.map((log, index) => { + const attrs = (log.attributes as Record) || {}; + const op = flowPerson(log.operatorId); + const isEbot = attrs.isEbotNode === true || `${op?.id || ""} ${op?.name || ""}`.toLowerCase().includes("ebot"); + const labeledOp = isEbot ? { ...(op || { id: "ebot" }), name: "Ebot (智能审批)" } : op; + const timeNum = typeof log.time === "number" ? log.time : undefined; + + return { + index: index + 1, + time: timeNum ? new Date(timeNum).toLocaleString("zh-CN", { hour12: false }) : undefined, + timestamp: timeNum, + action: translateBillFlowAction(typeof log.action === "string" ? log.action : undefined), + rawAction: typeof log.action === "string" ? log.action : undefined, + state: translateBillFlowState(typeof log.state === "string" ? log.state : undefined), + rawState: typeof log.state === "string" ? log.state : undefined, + nodeName: typeof attrs.nodeName === "string" ? attrs.nodeName : typeof attrs.nextName === "string" ? attrs.nextName : undefined, + operator: labeledOp, + comment: typeof attrs.comment === "string" ? attrs.comment.replace(/<[^>]+>/g, "").trim() : undefined, + automatic: attrs.isEbotNode === true || attrs.isAuto === true || !log.operatorId, + skipped: attrs.isSkip === true || attrs.skipped === true || log.state === "SKIPPED", + }; + }); + + return { + found: true, + target: cleanTarget, + billCode, + billId, + flowId, + backlogId, + specificationName, + specificationId, + title, + amount: amountStr, + submitter, + department, + submitDate, + state: stateLabel, + rawState, + currentNode, + pendingApprovers, + diagnostic, + timeline, + raw: rawFlow, + }; +} + 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 : {}; diff --git a/src/domains/bill/types.ts b/src/domains/bill/types.ts index e687164..6ee885b 100644 --- a/src/domains/bill/types.ts +++ b/src/domains/bill/types.ts @@ -290,3 +290,52 @@ export interface BillAttachmentReport { attachments: BillAttachment[]; raw: Record; } + +// ── 流程单据全貌穿透与待办诊断模型 ────────────────────────────────────────── + +export interface BillFlowTimelineItem { + index: number; + time?: string; + timestamp?: number; + durationMs?: number; + action?: string; + rawAction?: string; + state?: string; + rawState?: string; + nodeName?: string; + operator?: { id?: string; name?: string; code?: string }; + nextOperators?: { id?: string; name?: string; code?: string }[]; + comment?: string; + automatic?: boolean; + skipped?: boolean; +} + +export interface BillFlowTraceDiagnostic { + found: boolean; + target: string; + billCode?: string; + billId?: string; + flowId?: string; + backlogId?: string; + specificationName?: string; + specificationId?: string; + title?: string; + amount?: string; + submitter?: { id?: string; name?: string; code?: string }; + department?: string; + submitDate?: string; + state?: string; + rawState?: string; + currentNode?: { id?: string; name?: string; type?: string }; + pendingApprovers: { id?: string; name?: string; code?: string }[]; + diagnostic: { + canApprove: boolean; + stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN"; + stageLabel: string; + summary: string; + advice: string; + }; + timeline: BillFlowTimelineItem[]; + raw?: Record; +} +