import { describe, expect, test } from "bun:test"; import ky from "ky"; import { cleanCommentText, translateFlowAction, translateFlowState, extractFlowPerson, isEbotOperator, formatOperator, parseHoseTimeline, parseHosePending, parseHoseOpenPending, calculateFlowMetrics, extractStaffOpinions, extractRejections, parseHoseFlow, parseHoseOpenComposite, getHoseFlow, getHoseOpenFlow, getHoseCloseFlow, alignApprovalRunsWithHoseFlow, formatAiDecision, formatHumanOpinionLines, formatNumberedHumanOpinions, formatRejectionComment } from "./flow.js"; import { searchCloseBacklogs, getCloseBacklogDetailById, resolveCloseBacklogId, fetchRawCloseHoseFlow, HOSE_CLOSE_LOOKUP_SELECT, HOSE_CLOSE_DETAIL_SELECT, HOSE_CLOSE_JOINS } from "./close/index.js"; import { fetchHoseOpenFlowDetails, fetchHoseOpenAllLogs, fetchHoseOpenVersioned, fetchHoseOpenCompositeFlow } from "./open/index.js"; import { createHoseClientWithCredentials, createHoseClient, createHoseOpenClient, createHoseCloseClient, getHoseHeaders, getHoseCloseHeaders } from "./client.js"; import type { CorpConfig } from "../../core/config/types.js"; describe("Hose Flow Domain", () => { describe("Text cleaning and formatting", () => { test("cleanCommentText strips HTML and decodes entities", () => { expect(cleanCommentText("

发票缺失,请补充餐饮发票原件后重提

")).toBe( "发票缺失,请补充餐饮发票原件后重提" ); expect( cleanCommentText("

意见:"同意" & 抄送<财务>'s 部门 

") ).toBe("意见:\"同意\" & 抄送<财务>'s 部门"); expect(cleanCommentText("")).toBeUndefined(); expect(cleanCommentText("

")).toBeUndefined(); expect(cleanCommentText(undefined)).toBeUndefined(); }); test("translateFlowAction and translateFlowState translate known codes", () => { expect(translateFlowAction("freeflow.submit")).toBe("提交送审"); expect(translateFlowAction("freeflow.agree")).toBe("审批同意"); expect(translateFlowAction("freeflow.autoAgree")).toBe("自动同意"); expect(translateFlowAction("freeflow.reject")).toBe("审批驳回"); expect(translateFlowAction("freeflow.retract")).toBe("单据撤回"); expect(translateFlowAction("unknown_action")).toBe("unknown_action"); expect(translateFlowState("APPROVING")).toBe("审批中"); expect(translateFlowState("APPROVED")).toBe("审批通过"); expect(translateFlowState("REJECTED")).toBe("审批驳回"); expect(translateFlowState("REVOKED")).toBe("已撤回"); expect(translateFlowState("unknown_state")).toBe("unknown_state"); }); test("extractFlowPerson extracts person from string or object", () => { expect(extractFlowPerson("staff-123")).toEqual({ id: "staff-123" }); expect(extractFlowPerson({ id: "staff-456", name: "李四", code: "E001" })).toEqual({ id: "staff-456", name: "李四", code: "E001" }); expect(extractFlowPerson({ id: "staff-789", nickName: "张三" })).toEqual({ id: "staff-789", name: "张三", code: undefined }); expect( extractFlowPerson({ signerId: { id: "signer-1", name: "王五", code: "S01" } }) ).toEqual({ id: "signer-1", name: "王五", code: "S01" }); expect(extractFlowPerson(null)).toBeUndefined(); expect(extractFlowPerson({})).toBeUndefined(); }); }); describe("Ebot identification", () => { test("detects Ebot via attributes.isEbotNode", () => { const isEbot = isEbotOperator( { id: "staff-bot", name: "系统助手" }, { isEbotNode: true } ); expect(isEbot).toBe(true); }); test("detects Ebot via operator name or id containing ebot", () => { expect(isEbotOperator({ id: "ebot:rule-engine", name: "智能审核" })).toBe(true); expect(isEbotOperator({ id: "user-1", name: "合思Ebot智能审核助手" })).toBe(true); expect(isEbotOperator({ id: "user-2", name: "AI智能审批机器人" })).toBe(true); }); test("formats operator display name for Ebot", () => { const formatted = formatOperator({ id: "ebot-1", name: "bot" }, true, true); expect(formatted).toEqual({ id: "ebot-1", name: "Ebot (智能审批)", code: undefined }); }); test("formats operator for system automatic steps", () => { const formatted = formatOperator(undefined, true, false); expect(formatted).toEqual({ id: "system", name: "系统自动" }); }); }); describe("Multi-node flow timeline & pending parsing", () => { const multiNodeRaw = { id: "backlog-001", state: "APPROVING", nodeName: "财务初审", nodeId: "node-finance", flowId: { id: "flow-001", state: "APPROVING", form: { code: "BX20260901001", title: "市场部差旅报销", submitDate: 1788200000000, submitterId: { id: "staff-alice", name: "Alice", code: "A01" }, ownerId: { id: "staff-alice", name: "Alice" }, specificationId: { id: "spec-bx", name: "费用报销单", code: "EXP" }, submitCount: 1, rejectionNum: 0, version: 1 }, logs: [ { id: "log-1", time: 1788200000000, action: "freeflow.submit", state: "SUBMITTED", operatorId: { id: "staff-alice", name: "Alice", code: "A01" }, attributes: { nodeName: "单据提交", comment: "

申请出差报销

" } }, { id: "log-2", time: 1788201000000, action: "freeflow.agree", state: "APPROVED", operatorId: { id: "staff-bob", name: "Bob", code: "B01" }, attributes: { nodeName: "主管审批", comment: "

同意报销

" } }, { id: "log-3", time: 1788201500000, action: "freeflow.agree", state: "APPROVED", operatorId: { id: "staff-ebot", name: "Ebot" }, attributes: { isEbotNode: true, nodeName: "AI发票风控", comment: "

发票合规通过

" } } ], plan: { nextNodeId: "node-finance", nodes: [ { id: "node-dept", name: "主管审批", type: "APPROVE", approverId: { id: "staff-bob", name: "Bob" } }, { id: "node-finance", name: "财务初审", type: "APPROVE", approverId: { id: "staff-carol", name: "Carol", code: "C01" }, counterSigners: [{ signerId: { id: "staff-david", name: "David" } }] }, { id: "node-director", name: "总监审批", type: "APPROVE", approverId: { id: "staff-eva", name: "Eva" } } ] } } }; test("parses timeline entries with chronological duration and clean text", () => { const flow = parseHoseFlow(multiNodeRaw); expect(flow.backlogId).toBe("backlog-001"); expect(flow.flowId).toBe("flow-001"); expect(flow.billCode).toBe("BX20260901001"); expect(flow.title).toBe("市场部差旅报销"); expect(flow.state).toBe("审批中"); expect(flow.submitter?.name).toBe("Alice"); expect(flow.specification?.name).toBe("费用报销单"); expect(flow.history).toHaveLength(3); expect(flow.history[0]!.action).toBe("提交送审"); expect(flow.history[0]!.nodeName).toBe("单据提交"); expect(flow.history[0]!.comment).toBe("申请出差报销"); expect(flow.history[0]!.durationMs).toBe(1000000); // 1788201000000 - 1788200000000 expect(flow.history[1]!.action).toBe("审批同意"); expect(flow.history[1]!.operator?.name).toBe("Bob"); expect(flow.history[1]!.durationMs).toBe(500000); // 1788201500000 - 1788201000000 expect(flow.history[2]!.isEbot).toBe(true); expect(flow.history[2]!.automatic).toBe(true); expect(flow.history[2]!.operator?.name).toBe("Ebot (智能审批)"); expect(flow.history[2]!.durationMs).toBeUndefined(); // last log has no nextLog }); test("parses pending plan nodes and identifies current node", () => { const flow = parseHoseFlow(multiNodeRaw); expect(flow.pending).toHaveLength(3); expect(flow.pending[0]!.name).toBe("主管审批"); expect(flow.pending[0]!.isCurrent).toBe(false); expect(flow.pending[0]!.state).toBe("后续"); expect(flow.pending[1]!.name).toBe("财务初审"); expect(flow.pending[1]!.isCurrent).toBe(true); expect(flow.pending[1]!.state).toBe("当前"); expect(flow.pending[1]!.approver?.name).toBe("Carol"); expect(flow.pending[1]!.approvers).toHaveLength(1); expect(flow.pending[1]!.approvers[0]!.name).toBe("David"); expect(flow.pending[2]!.name).toBe("总监审批"); expect(flow.pending[2]!.isCurrent).toBe(false); }); test("extracts staff opinions separating Ebot from human staff", () => { const flow = parseHoseFlow(multiNodeRaw); expect(flow.staffOpinions).toHaveLength(3); expect(flow.staffOpinions[0]!.operator?.name).toBe("Alice"); expect(flow.staffOpinions[0]!.comment).toBe("申请出差报销"); expect(flow.staffOpinions[0]!.isEbot).toBe(false); expect(flow.staffOpinions[1]!.operator?.name).toBe("Bob"); expect(flow.staffOpinions[1]!.comment).toBe("同意报销"); expect(flow.staffOpinions[1]!.isEbot).toBe(false); expect(flow.staffOpinions[2]!.isEbot).toBe(true); expect(flow.staffOpinions[2]!.comment).toBe("发票合规通过"); }); }); describe("Rejection and Resubmission (驳回重提)", () => { test("calculates rejection metrics when bill was rejected and resubmitted", () => { const rejectAndResubmitRaw = { id: "backlog-reject-01", state: "APPROVING", flowId: { id: "flow-reject-01", state: "APPROVING", form: { code: "BX-REJECT-01", rejectionNum: 1, submitCount: 2, sourceFlowVersion: "v1.2", submitDate: 1788302000000 }, logs: [ { id: "log-1", time: 1788300000000, action: "freeflow.submit", state: "SUBMITTED", operatorId: { id: "user-1", name: "张三" }, attributes: { nodeName: "初次提交" } }, { id: "log-2", time: 1788301000000, action: "freeflow.reject", state: "REJECTED", operatorId: { id: "manager-1", name: "王经理" }, attributes: { nodeName: "主管审批", comment: "

金额超标,缺少招待人员清单,请补充后重提

" } }, { id: "log-3", time: 1788302000000, action: "freeflow.submit", state: "SUBMITTED", operatorId: { id: "user-1", name: "张三" }, attributes: { nodeName: "补充重提", comment: "

已补充招待名单

" } }, { id: "log-4", time: 1788303000000, action: "freeflow.agree", state: "APPROVED", operatorId: { id: "manager-1", name: "王经理" }, attributes: { nodeName: "主管审批", comment: "

复核无误,通过

" } } ] } }; const flow = parseHoseFlow(rejectAndResubmitRaw); expect(flow.metrics.rejectionNum).toBe(1); expect(flow.metrics.submitCount).toBe(2); expect(flow.metrics.sourceFlowVersion).toBe("v1.2"); expect(flow.metrics.isModifiedAfterReject).toBe(true); expect(flow.rejections).toHaveLength(1); expect(flow.rejections[0]!.nodeName).toBe("主管审批"); expect(flow.rejections[0]!.operator?.name).toBe("王经理"); expect(flow.rejections[0]!.reason).toBe("金额超标,缺少招待人员清单,请补充后重提"); expect(flow.rejections[0]!.rawComment).toBe( "

金额超标,缺少招待人员清单,请补充后重提

" ); expect(flow.rejections[0]!.isEbot).toBe(false); }); test("detects bill currently in REJECTED state (not yet resubmitted)", () => { const stillRejectedRaw = { id: "backlog-still-reject", state: "REJECTED", flowId: { id: "flow-still-reject", state: "REJECTED", form: { code: "BX-STILL-REJECT", rejectionNum: 1, submitCount: 1, submitDate: 1788300000000 }, logs: [ { id: "log-1", time: 1788300000000, action: "freeflow.submit", state: "SUBMITTED", operatorId: { id: "user-1", name: "张三" }, attributes: { nodeName: "初次提交" } }, { id: "log-2", time: 1788301000000, action: "freeflow.reject", state: "REJECTED", operatorId: { id: "manager-1", name: "王经理" }, attributes: { nodeName: "主管审批", comment: "

发票模糊无法查验,驳回

" } } ] } }; const flow = parseHoseFlow(stillRejectedRaw); expect(flow.metrics.rejectionNum).toBe(1); expect(flow.metrics.submitCount).toBe(1); expect(flow.metrics.isModifiedAfterReject).toBe(false); expect(flow.rejections).toHaveLength(1); expect(flow.rejections[0]!.reason).toBe("发票模糊无法查验,驳回"); }); }); describe("Active Retract and Resubmission (主动撤回重提)", () => { test("detects active retract and subsequent resubmission", () => { const retractAndResubmitRaw = { id: "backlog-retract-01", state: "APPROVING", flowId: { id: "flow-retract-01", state: "APPROVING", form: { code: "BX-RETRACT-01", submitCount: 2, submitDate: 1788402000000 }, logs: [ { id: "log-1", time: 1788400000000, action: "freeflow.submit", state: "SUBMITTED", operatorId: { id: "user-1", name: "李雷" }, attributes: { nodeName: "单据提交" } }, { id: "log-2", time: 1788401000000, action: "freeflow.retract", state: "REVOKED", operatorId: { id: "user-1", name: "李雷" }, attributes: { nodeName: "单据撤回", comment: "

发现报销费用归属部门选错,撤回修改

" } }, { id: "log-3", time: 1788402000000, action: "freeflow.submit", state: "SUBMITTED", operatorId: { id: "user-1", name: "李雷" }, attributes: { nodeName: "重新提交", comment: "

已修改部门,重新提交

" } } ] } }; const flow = parseHoseFlow(retractAndResubmitRaw); expect(flow.metrics.retractCount).toBe(1); expect(flow.metrics.isResubmittedAfterRetract).toBe(true); expect(flow.metrics.submitCount).toBe(2); expect(flow.metrics.rejectionNum).toBe(0); const retractLog = flow.history.find((h) => h.action === "单据撤回"); expect(retractLog).toBeDefined(); expect(retractLog?.comment).toBe("发现报销费用归属部门选错,撤回修改"); }); }); describe("API Client & Read-Only Endpoint Contract", () => { test("getHoseHeaders formats lowercase credentials", () => { const headers = getHoseHeaders({ domain: "https://app.ekuaibao.com", corpId: "corp-xyz", staffId: "staff-abc", accessToken: "token-123" }); expect(headers).toEqual({ accesstoken: "token-123", corpid: "corp-xyz", staffid: "staff-abc" }); }); test("createHoseClient throws for non-hose source", async () => { const nonHoseCorp: CorpConfig = { id: "direct-corp", name: "Direct Corp", environment: "production", source: { type: "direct", token: "tok", sealUrl: "https://test.sealai.cc", expiresIn: 3600, staffId: "direct" }, seal: { endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } }, auth: { refreshTtl: 300 } }; expect(createHoseClient(nonHoseCorp)).rejects.toThrow("Expected 'hose'"); }); test("searchBacklogs calls POST api/flow/v2/backlogs/search with minimal projection", async () => { let recordedUrl = ""; let recordedMethod = ""; let recordedBody: Record | undefined; let recordedSearchParams: URLSearchParams | undefined; const mockClient = ky.create({ fetch: async (input, init) => { const req = input instanceof Request ? input : new Request(input, init); recordedUrl = req.url; recordedMethod = req.method; const text = await req.clone().text(); if (text) { recordedBody = JSON.parse(text); } recordedSearchParams = new URL(recordedUrl).searchParams; return new Response( JSON.stringify({ count: 1, items: [ { id: "backlog-matched", flowId: { id: "flow-123", form: { code: "BX001" } } } ] }), { status: 200, headers: { "content-type": "application/json" } } ); }, prefix: "https://app.ekuaibao.com" }); const items = await searchCloseBacklogs(mockClient, "corp-test", { filterBy: `(flowId.form.code=="BX001")` }); expect(items).toHaveLength(1); expect(items[0]!.id).toBe("backlog-matched"); expect(recordedUrl).toContain("api/flow/v2/backlogs/search"); expect(recordedMethod).toBe("POST"); expect(recordedSearchParams?.get("corpId")).toBe("corp-test"); expect(recordedBody?.filterBy).toBe(`(flowId.form.code=="BX001")`); expect(recordedBody?.select).toBe(HOSE_CLOSE_LOOKUP_SELECT); }); test("getCloseBacklogDetailById calls POST api/flow/v2/backlogs/id with the 7 joins", async () => { let recordedUrl = ""; let recordedMethod = ""; let recordedBody: Record | undefined; let recordedJoins: string[] = []; const mockClient = ky.create({ fetch: async (input, init) => { const req = input instanceof Request ? input : new Request(input, init); recordedUrl = req.url; recordedMethod = req.method; const text = await req.clone().text(); if (text) { recordedBody = JSON.parse(text); } const url = new URL(recordedUrl); recordedJoins = url.searchParams.getAll("join"); return new Response( JSON.stringify({ value: { id: "backlog-detail-1", flowId: { id: "flow-detail-1", form: { code: "BX999", title: "差旅" }, logs: [], plan: { nodes: [] } } } }), { status: 200, headers: { "content-type": "application/json" } } ); }, prefix: "https://app.ekuaibao.com" }); const detail = await getCloseBacklogDetailById(mockClient, "corp-test", "backlog-detail-1"); expect(detail).toBeDefined(); expect(detail?.id).toBe("backlog-detail-1"); expect(recordedUrl).toContain("api/flow/v2/backlogs/id"); expect(recordedMethod).toBe("POST"); expect(recordedBody?.filterBy).toBe(`(id=="backlog-detail-1")`); expect(recordedBody?.select).toBe(HOSE_CLOSE_DETAIL_SELECT); expect(recordedJoins).toEqual([...HOSE_CLOSE_JOINS]); }); test("getHoseCloseFlow resolves target and parses CloseAPI flow end-to-end", async () => { const mockClient = ky.create({ fetch: async (input, init) => { const req = input instanceof Request ? input : new Request(input, init); const url = req.url; if (url.includes("api/flow/v2/backlogs/search")) { return new Response( JSON.stringify({ count: 1, items: [ { id: "backlog-found", flowId: { id: "flow-found", form: { code: "TARGET-CODE" } } } ] }), { status: 200, headers: { "content-type": "application/json" } } ); } if (url.includes("api/flow/v2/backlogs/id")) { return new Response( JSON.stringify({ value: { id: "backlog-found", flowId: { id: "flow-found", form: { code: "TARGET-CODE", title: "终端测试单据", rejectionNum: 0, submitCount: 1 }, logs: [ { id: "log-1", time: 1788500000000, action: "freeflow.submit", operatorId: { id: "user-1", name: "张三" }, attributes: { nodeName: "提交" } } ], plan: { nextNodeId: "node-1", nodes: [{ id: "node-1", name: "审批节点" }] } } } }), { status: 200, headers: { "content-type": "application/json" } } ); } return new Response("Not found", { status: 404 }); }, prefix: "https://app.ekuaibao.com" }); const flow = await getHoseCloseFlow(mockClient, "corp-test", "TARGET-CODE"); expect(flow).toBeDefined(); expect(flow?.backlogId).toBe("backlog-found"); expect(flow?.billCode).toBe("TARGET-CODE"); expect(flow?.history).toHaveLength(1); expect(flow?.pending).toHaveLength(1); expect(flow?.pending[0]!.isCurrent).toBe(true); expect(flow?.metrics.submitCount).toBe(1); expect(flow?.metrics.isModifiedAfterReject).toBe(false); }); test("getHoseOpenFlow calls OpenAPI endpoints (flowDetails, allLogs, versioned) and parses composite flow", async () => { const mockOpenClient = ky.create({ fetch: async (input, init) => { const req = input instanceof Request ? input : new Request(input, init); const url = req.url; if (url.includes("api/openapi/v1.1/flowDetails/allLogs")) { return new Response( JSON.stringify({ count: 2, items: [ { id: "task-1", nodeName: "主管审批", ownerId: "user-mgr", state: "PROCESSED", logId: 1, action: "freeflow.agree" }, { id: "task-2", nodeName: "财务复核", ownerId: "user-finance", state: "APPROVING", logId: -1, action: null } ] }), { status: 200, headers: { "content-type": "application/json" } } ); } if (url.includes("api/openapi/v1.1/flowDetails")) { return new Response( JSON.stringify({ value: { id: "flow-open-1", state: "approving", form: { code: "B26009999", title: "OpenAPI测试报销", rejectionNum: 1 }, logs: [ { id: "l1", action: "freeflow.submit", operatorId: "user-submit", time: 1789000000000, attributes: { nodeName: "费用标准检查", comment: "" } }, { id: "l2", action: "freeflow.agree", operatorId: "user-mgr", time: 1789001000000, attributes: { nodeName: "主管审批", comment: "同意" } } ] } }), { status: 200, headers: { "content-type": "application/json" } } ); } if (url.includes("api/openapi/v1/flow/versioned")) { return new Response( JSON.stringify({ count: 2, items: [ { version: 2, state: "approving", logs: [] }, { version: 1, state: "draft", logs: [] } ] }), { status: 200, headers: { "content-type": "application/json" } } ); } return new Response("Not found", { status: 404 }); }, prefix: "https://app.ekuaibao.com" }); const flow = await getHoseOpenFlow(mockOpenClient, "flow-open-1"); expect(flow).toBeDefined(); expect(flow?.flowId).toBe("flow-open-1"); expect(flow?.billCode).toBe("B26009999"); expect(flow?.history).toHaveLength(2); expect(flow?.history[1]?.comment).toBe("同意"); expect(flow?.staffOpinions).toHaveLength(1); expect(flow?.staffOpinions[0]?.comment).toBe("同意"); expect(flow?.pending).toHaveLength(1); expect(flow?.pending[0]?.name).toBe("财务复核"); expect(flow?.pending[0]?.isCurrent).toBe(true); expect(flow?.currentNode).toBe("财务复核"); expect(flow?.metrics.rejectionNum).toBe(1); expect(flow?.metrics.submitCount).toBe(2); }); }); describe("Approval Runs & Hose Flow Alignment (E人工行为 / E人工意见 对齐引擎)", () => { test("aligns multi-round approval scenario: assisted reject -> automatic reject -> completed", () => { const runs = [ { id: "run-1", sourceDocumentSN: "B26000001", taskMode: "assisted", createdAt: 10000, result: { decision: "REJECT" } }, { id: "run-2", sourceDocumentSN: "B26000001", taskMode: "fully_automatic", createdAt: 20000, result: { decision: "REJECT" } }, { id: "run-3", sourceDocumentSN: "B26000001", taskMode: "fully_automatic", createdAt: 30000, result: { decision: "APPROVE" } } ] as any[]; const flow = { state: "审批通过", rawState: "COMPLETED", history: [ { time: 5000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "提交人" } }, { time: 8000, action: "审批同意", rawAction: "freeflow.agree", operator: { name: "主管A" } }, { time: 12000, action: "审批驳回", rawAction: "freeflow.reject", operator: { name: "主管B" }, comment: "发票不全缺少总经理审批,退回修改" }, { time: 15000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "提交人" } }, { time: 18000, action: "审批同意", rawAction: "freeflow.agree", operator: { name: "主管B" } }, { time: 21000, action: "审批驳回", rawAction: "freeflow.reject", isEbot: true, operator: { name: "Ebot" }, comment: "规则驳回" }, { time: 25000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "提交人" } }, { time: 31000, action: "自动同意", rawAction: "freeflow.autoAgree", isEbot: true }, { time: 35000, action: "审批同意", rawAction: "freeflow.agree", operator: { name: "财务C" }, comment: "核销通过" } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r1 = aligned.get("run-1")!; expect(r1.eHumanAction).toBe("审批驳回"); expect(r1.eHumanComment).toBe( "主管B ❌: 发票不全缺少总经理审批,退回修改\n↳ 驳回至: 提交人\n↳ 重新提交后由主管B继续审批" ); expect(r1.operator?.name).toBe("主管B"); expect(r1.auditDrift).toBe(false); const r2 = aligned.get("run-2")!; expect(r2.eHumanAction).toBe("无操作"); expect(r2.eHumanComment).toBe("-"); expect(r2.auditDrift).toBe(false); const r3 = aligned.get("run-3")!; expect(r3.eHumanAction).toBe("审批通过"); expect(r3.eHumanComment).toBe("1. 财务C: 核销通过"); expect(r3.operator?.name).toBe("财务C"); expect(r3.auditDrift).toBe(false); }); test("handles unfinished flow: pending on human node with reverse order and badge", () => { const runs = [ { id: "run-3", sourceDocumentSN: "B26000001", taskMode: "fully_automatic", createdAt: 30000, result: { decision: "APPROVE" } } ] as any[]; const flow = { state: "审批中", rawState: "APPROVING", currentNode: "财务C审核", history: [ { time: 31000, action: "自动同意", rawAction: "freeflow.autoAgree", isEbot: true } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r3 = aligned.get("run-3")!; expect(r3.eHumanAction).toBe("⏳ 审批中"); expect(r3.eHumanComment).toBe("⏳ 1. 财务C审核: 待审批"); }); test("detects Post-AI Mutation (审计漂移 / 过审后中途被修改)", () => { const runs = [ { id: "run-1", sourceDocumentSN: "B26000001", taskMode: "fully_automatic", createdAt: 10000, result: { decision: "APPROVE" } } ] as any[]; const flow = { state: "已完成", rawState: "COMPLETED", history: [ { time: 8000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "提交人" } }, { time: 16000, action: "单据撤回", rawAction: "freeflow.retract", operator: { name: "提交人" } }, { time: 20000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "提交人" } }, { time: 25000, action: "审批同意", rawAction: "freeflow.agree", operator: { name: "财务主管" } } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r1 = aligned.get("run-1")!; expect(r1.eHumanAction).toBe("审批通过"); expect(r1.auditDrift).toBe(true); expect(r1.auditDriftReason).toContain("AI通过后单据发生撤回/修改重提"); }); test("handles multi-round retraction and resubmission: retracted run vs active approving run", () => { const runs = [ { id: "run-retracted", sourceDocumentSN: "B26002390", taskMode: "assisted", createdAt: 10000, status: "failed", manualApprovalStatus: "CANCELLED", result: { decision: "ERROR" } }, { id: "run-active", sourceDocumentSN: "B26002390", taskMode: "assisted", createdAt: 20000, status: "completed", result: { decision: "REJECT" } } ] as any[]; const flow = { state: "审批中", rawState: "APPROVING", currentNode: "上级主管", history: [ { time: 8000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "刘佳琼" } }, { time: 9000, action: "审批同意", rawAction: "freeflow.agree", isEbot: true, operator: { name: "Ebot" } }, { time: 15000, action: "单据撤回", rawAction: "freeflow.retract", operator: { name: "刘佳琼" } }, { time: 18000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "刘佳琼" } }, { time: 22000, action: "审批同意", rawAction: "freeflow.agree", isEbot: true, operator: { name: "Ebot" } } ], pending: [ { id: "node-mgr", name: "上级主管", isCurrent: true, approver: { name: "张舒" } } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r1 = aligned.get("run-retracted")!; expect(r1.eHumanAction).toBe("已撤回"); expect(r1.eHumanComment).toBe("提交人(刘佳琼) ↩️: 单据撤回"); expect(r1.auditDrift).toBe(false); const r2 = aligned.get("run-active")!; expect(r2.eHumanAction).toBe("⏳ 审批中"); expect(r2.eHumanComment).toBe("⏳ 1. 上级主管(张舒): 待审批"); expect(r2.auditDrift).toBe(false); }); test("handles completed paid flow: resolves through, deduplicates opinions, omits cc, and clears pending", () => { const runs = [ { id: "run-paid", sourceDocumentSN: "B26002324", taskMode: "assisted", createdAt: 10000, status: "completed", manualApprovalStatus: "APPROVED", result: { decision: "EXEMPT_APPROVE" } } ] as any[]; const flow = { state: "已支付", rawState: "paid", history: [ { time: 8000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "高思琦" } }, { time: 11000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "上级主管", operator: { name: "张舒" } }, { time: 12000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" } }, { time: 13000, action: "自动同意", rawAction: "freeflow.autoAgree", nodeName: "部门主管", operator: { name: "张舒" } }, { time: 14000, action: "发表评论", rawAction: "freeflow.comment", comment: "ETA2026年家庭日费用报销", operator: { name: "高思琦" } }, { time: 14500, action: "发表评论", rawAction: "freeflow.comment", comment: "ETA2026年家庭日费用报销", operator: { name: "高思琦" } }, { time: 15000, action: "支付完成", rawAction: "freeflow.pay", operator: { name: "高思琦" } }, { time: 16000, action: "抄送通知", rawAction: "freeflow.carbonCopy", operator: { name: "高思琦" } } ], pending: [] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r = aligned.get("run-paid")!; expect(r.aiDecision).toBe("备注通过"); expect(r.eHumanAction).toBe("已支付"); expect(r.auditDrift).toBe(false); // Verify opinions: // 1. Agree nodes present with sequence numbers expect(r.eHumanComment).toContain("1. 上级主管(张舒): 同意"); expect(r.eHumanComment).toContain("2. 财务助理(熊雪倩): 同意"); expect(r.eHumanComment).toContain("3. 部门主管(张舒) 🤖: 自动同意"); // 2. Duplicate comment deduplicated (appears only once) const matches = r.eHumanComment.match(/高思琦 💬: ETA2026年家庭日费用报销/g); expect(matches?.length).toBe(1); // 3. freeflow.pay mapped to 支付成功 expect(r.eHumanComment).toContain("5. 高思琦 💰: 支付成功"); // 4. freeflow.carbonCopy omitted expect(r.eHumanComment).not.toContain("freeflow.carbonCopy"); expect(r.eHumanComment).not.toContain("抄送单据"); expect(r.eHumanComment).not.toContain("抄送通知"); // 5. No pending node appended expect(r.eHumanComment).not.toContain("当前审核节点"); expect(r.eHumanComment).not.toContain("待支付"); }); test("handles cashier paying document (B26002283 scenario): resolves to ⏳ 支付中 with reverse order opinions", () => { const runs = [ { id: "run-paying", sourceDocumentSN: "B26002283", taskMode: "assisted", createdAt: 10000, status: "completed", manualApprovalRecord: { status: { type: "PROCESSING", label: "处理中" } }, result: { decision: "REJECT" } } ] as any[]; const flow = { state: "支付中", rawState: "paying", currentNode: "出纳支付", history: [ { time: 8000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "侯旭鹏" } }, { time: 11000, action: "审批同意", rawAction: "freeflow.agree", nodeName: ".上级主管", operator: { name: "江辉华" }, comment: "同意" }, { time: 12000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" }, comment: "同意" }, { time: 13000, action: "自动同意", rawAction: "freeflow.autoAgree", nodeName: "部门主管", operator: { name: "江辉华" } }, { time: 13001, action: "自动同意", rawAction: "freeflow.autoAgree", nodeName: "部门领导", operator: { name: "江辉华" } }, { time: 14000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务经理", operator: { name: "周晚容" }, comment: "同意" }, { time: 15000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "CFO", operator: { name: "张舒" }, comment: "同意" }, { time: 16000, action: "打印单据", rawAction: "freeflow.print", nodeName: "打印提醒", operator: { name: "高思琦" } } ], pending: [ { name: "出纳支付", type: "PAYING", isCurrent: true, approver: { name: "高思琦" } } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r = aligned.get("run-paying")!; expect(r.eHumanAction).toBe("⏳ 支付中"); // Verify reverse order: // Line 1 is the pending cashier node with badge ⏳ and seq 7 const lines = r.eHumanComment.split("\n"); expect(lines[0]).toBe("⏳ 7. 出纳支付(高思琦): 待支付"); // Line 2 is the most recent approval: CFO (seq 6) expect(lines[1]).toBe("6. CFO(张舒): 同意"); // Line 3 is 财务经理 (seq 5) expect(lines[2]).toBe("5. 财务经理(周晚容): 同意"); // Line 7 is .上级主管 (seq 1) expect(lines[6]).toBe("1. .上级主管(江辉华): 同意"); }); test("handles AI approved run rejected by human operator before resubmission and payment: resolves to 审批驳回 with node and operator prefix", () => { const runs = [ { id: "run-rejected-then-paid", sourceDocumentSN: "B26002305", taskMode: "assisted", createdAt: 10000, status: "completed", manualApprovalRecord: { status: { type: "TERMINATED", label: "被驳回" }, rejectComment: "修改附件" }, result: { decision: "EXEMPT_APPROVE" } } ] as any[]; const flow = { state: "已支付", rawState: "paid", history: [ { time: 8000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "张晶丰" } }, { time: 11000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "上级主管", operator: { name: "刘苏宁" } }, { time: 15000, action: "审批驳回", rawAction: "freeflow.reject", nodeName: "提交人", comment: "修改附件", operator: { name: "熊雪倩" } }, { time: 20000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "张晶丰" } }, { time: 25000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" } }, { time: 30000, action: "支付完成", rawAction: "freeflow.pay", operator: { name: "高思琦" } } ], pending: [] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r = aligned.get("run-rejected-then-paid")!; expect(r.aiDecision).toBe("备注通过"); expect(r.eHumanAction).toBe("审批驳回"); // Node prefix resolved from熊雪倩's approval node in history: 财务助理(熊雪倩): 修改附件 expect(r.eHumanComment).toBe( "财务助理(熊雪倩) ❌: 修改附件\n↳ 驳回至: 提交人\n↳ 重新提交后由熊雪倩继续审批" ); expect(r.auditDrift).toBe(false); expect(r.operator?.name).toBe("熊雪倩"); }); test("B26002307 scenario: rejected to intermediate node with 样式 2-B format", () => { const runs = [ { id: "run-2307", sourceDocumentSN: "B26002307", taskMode: "assisted", createdAt: 100000, manualApprovalRecord: { nodeName: "合思审批节点", status: { type: "TERMINATED", label: "已驳回" } }, result: { decision: "APPROVE" } } ] as any[]; const flow = { state: "已支付", rawState: "paid", history: [ { time: 90000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "郭宝" } }, { time: 95000, action: "自动同意", rawAction: "freeflow.autoAgree", isEbot: true, operator: { name: "Ebot" } }, { time: 98000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "上级主管", operator: { name: "孙麓" }, comment: "同意" }, { time: 101000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" }, comment: "同意" }, { time: 110000, action: "审批驳回", rawAction: "freeflow.reject", nodeName: "财务经理", operator: { name: "周晚容" }, comment: "修改", rejectTargetNodeName: "财务助理", rejectTargetOperator: { name: "熊雪倩" }, resubmitRuleText: "重新提交后由周晚容继续审批" }, { time: 120000, action: "修改了单据", rawAction: "flow.modify", isModification: true, nodeName: "财务助理", operator: { name: "熊雪倩" } }, { time: 130000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" }, comment: "同意" }, { time: 140000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "董事长", operator: { name: "甘戈" }, comment: "同意" }, { time: 150000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务经理", operator: { name: "周晚容" }, comment: "同意" }, { time: 160000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "CFO", operator: { name: "张舒" }, comment: "同意" }, { time: 170000, action: "支付成功", rawAction: "freeflow.pay", operator: { name: "高思琦" } } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r = aligned.get("run-2307")!; expect(r.eHumanAction).toBe("审批驳回"); expect(r.eHumanComment).toBe( "财务经理(周晚容) ❌: 修改\n↳ 驳回至: 财务助理(熊雪倩)\n↳ 重新提交后由周晚容继续审批" ); expect(r.operator?.name).toBe("周晚容"); }); test("B26002144 scenario: mid-flow document modification yields 已支付 (中途修改) with modification at top", () => { const runs = [ { id: "run-2144", sourceDocumentSN: "B26002144", taskMode: "automatic", createdAt: 92000, manualApprovalRecord: { status: { type: "APPROVED", label: "已支付/审批完成" } }, result: { decision: "APPROVE" } } ] as any[]; const flow = { state: "已支付", rawState: "paid", history: [ { time: 90000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "郭宝" } }, { time: 95000, action: "自动同意", rawAction: "freeflow.autoAgree", isEbot: true, operator: { name: "费用标准检查" } }, { time: 98000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "上级主管", operator: { name: "孙麓" }, comment: "同意" }, { time: 105000, action: "修改了单据", rawAction: "flow.modify", isModification: true, nodeName: "财务助理", operator: { name: "熊雪倩" } }, { time: 110000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" }, comment: "同意" }, { time: 120000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "董事长", operator: { name: "甘戈" }, comment: "同意" }, { time: 130000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务经理", operator: { name: "周晚容" }, comment: "同意" }, { time: 140000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "CFO", operator: { name: "张舒" }, comment: "同意" }, { time: 150000, action: "支付成功", rawAction: "freeflow.pay", operator: { name: "高思琦" } } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r = aligned.get("run-2144")!; expect(r.eHumanAction).toBe("已支付 (中途修改)"); expect(r.eHumanComment).toBe( "2. 财务助理(熊雪倩) ✏️: 修改了单据\n1. 上级主管(孙麓): 同意\n3. 财务助理(熊雪倩): 同意\n4. 董事长(甘戈): 同意\n5. 财务经理(周晚容): 同意\n6. CFO(张舒): 同意\n7. 高思琦 💰: 支付成功" ); }); }); describe("Pending and end-state handling", () => { test("parseHoseOpenPending filters out CANCELED / PROCESSED nodes even with logId -1", () => { const allLogs = [ { id: "1", logId: -1, state: "CANCELED", nodeName: "已取消节点", ownerId: "user-1" }, { id: "2", logId: -1, state: "APPROVING", nodeName: "当前待审节点", ownerId: "user-2" } ] as any[]; const pending = parseHoseOpenPending(allLogs); expect(pending.length).toBe(1); expect(pending[0]?.name).toBe("当前待审节点"); }); test("parseHoseOpenComposite clears pending nodes when flow is paid or completed", () => { const composite = { flowDetails: { id: "flow-1", state: "paid", logs: [] }, allLogs: [ { id: "1", logId: -1, state: "APPROVING", nodeName: "残留待审节点", ownerId: "user-1" } ] } as any; const detail = parseHoseOpenComposite(composite); expect(detail?.state).toBe("已支付"); expect(detail?.pending).toEqual([]); }); test("formatAiDecision maps codes to Chinese labels", () => { expect(formatAiDecision("EXEMPT_APPROVE")).toBe("备注通过"); expect(formatAiDecision("ERROR")).toBe("错误"); expect(formatAiDecision("APPROVE")).toBe("通过"); expect(formatAiDecision("REJECT")).toBe("驳回"); expect(formatAiDecision("REVIEW")).toBe("转交复核"); }); test("formatNumberedHumanOpinions formats forward order for completed flows", () => { const history = ["上级主管(张舒): 同意", "财务助理(熊雪倩): 同意", "CFO(张舒): 自动同意"]; const formatted = formatNumberedHumanOpinions(history, [], "forward"); expect(formatted).toBe( "1. 上级主管(张舒): 同意\n2. 财务助理(熊雪倩): 同意\n3. CFO(张舒): 自动同意" ); }); test("formatNumberedHumanOpinions formats reverse order with pending badge for in-progress flows", () => { const history = ["上级主管(江辉华): 同意", "财务助理(熊雪倩): 同意"]; const pending = ["财务经理(周晚容): 待审批", "CFO(张舒): 待审批"]; const formatted = formatNumberedHumanOpinions(history, pending, "reverse"); const lines = formatted.split("\n"); // Pending nodes first, starting from seq 3, then 4. First pending has ⏳ badge. expect(lines[0]).toBe("⏳ 3. 财务经理(周晚容): 待审批"); expect(lines[1]).toBe("4. CFO(张舒): 待审批"); // History approvals in reverse order expect(lines[2]).toBe("2. 财务助理(熊雪倩): 同意"); expect(lines[3]).toBe("1. 上级主管(江辉华): 同意"); }); test("formatRejectionComment prepends node and operator name", () => { const res1 = formatRejectionComment( { rawAction: "freeflow.reject", action: "审批驳回", nodeName: "提交人", operator: { name: "熊雪倩" }, comment: "修改附件" } as any, undefined, undefined, [ { rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" } } as any ] ); expect(res1.comment).toBe( "财务助理(熊雪倩) ❌: 修改附件\n↳ 驳回至: 提交人\n↳ 重新提交后由熊雪倩继续审批" ); expect(res1.operator?.name).toBe("熊雪倩"); const res2 = formatRejectionComment( undefined, { nodeName: "财务经理", operator: { name: "周晚容" }, reason: "单据超标缺少说明" } as any ); expect(res2.comment).toBe( "财务经理(周晚容) ❌: 单据超标缺少说明\n↳ 驳回至: 提交人\n↳ 重新提交后由周晚容继续审批" ); const res3 = formatRejectionComment( undefined, undefined, { nodeName: "合思审批节点", rejectComment: "超额报销" } ); expect(res3.comment).toBe( "超额报销\n↳ 驳回至: 提交人\n↳ 重新提交后继续审批" ); expect(res3.comment).not.toContain("合思审批节点"); }); test("handles historical retracted run superseded by paid run (B26002100 case)", () => { const runs = [ { id: "run-round-1", sourceDocumentSN: "B26002100", taskMode: "assisted", createdAt: 100000, manualApprovalRecord: { nodeName: "合思审批节点", status: { type: "TERMINATED", label: "已驳回", sourceStatus: "已支付回调补偿驳回" } }, result: { decision: "APPROVE" } }, { id: "run-round-2", sourceDocumentSN: "B26002100", taskMode: "assisted", createdAt: 200000, manualApprovalRecord: { status: { type: "APPROVED", label: "已支付/审批完成", sourceStatus: "已支付/审批完成" } }, result: { decision: "APPROVE" } } ] as any[]; const flow = { state: "已支付", rawState: "paid", history: [ { time: 99000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "袁锦" } }, { time: 101000, action: "审批同意", rawAction: "freeflow.agree", isEbot: true, operator: { name: "Ebot" } }, { time: 105000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "费用类型是研发费", operator: { name: "宁艳楠" }, comment: "同意" }, { time: 150000, action: "单据撤回", rawAction: "freeflow.retract", operator: { name: "袁锦" } }, { time: 199000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "袁锦" } }, { time: 201000, action: "审批同意", rawAction: "freeflow.agree", isEbot: true, operator: { name: "Ebot" } }, { time: 205000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "费用类型是研发费", operator: { name: "宁艳楠" }, comment: "同意" }, { time: 210000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务经理", operator: { name: "周晚容" }, comment: "同意" }, { time: 220000, action: "支付成功", rawAction: "freeflow.pay", operator: { name: "高思琦" } } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r1 = aligned.get("run-round-1")!; expect(r1.eHumanAction).toBe("已撤回"); expect(r1.eHumanComment).toBe( "1. 费用类型是研发费(宁艳楠): 同意\n2. 提交人(袁锦) ↩️: 单据撤回" ); expect(r1.eHumanComment).not.toContain("合思审批节点"); expect(r1.eHumanComment).not.toContain("审批驳回"); const r2 = aligned.get("run-round-2")!; expect(r2.eHumanAction).toBe("已支付"); expect(r2.eHumanComment).toBe( "1. 费用类型是研发费(宁艳楠): 同意\n2. 财务经理(周晚容): 同意\n3. 高思琦 💰: 支付成功" ); }); test("cross-period partial query: identifies historical rejected run even if queried in isolation without subsequent runs in batch", () => { // User only queried June (so Seal batch only contains Run 1). // But Hose document later had Run 2 in July and was paid in August. const singleIsolatedRun = [ { id: "run-june-round1", sourceDocumentSN: "B26009999", taskMode: "assisted", createdAt: 100000, status: "completed", manualApprovalRecord: { status: { type: "TERMINATED", label: "已驳回" }, rejectComment: "发票模糊" }, result: { decision: "REJECT" } } ] as any[]; const fullLifetimeHoseFlow = { state: "已支付", rawState: "paid", history: [ // June round (Run 1) { time: 90000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "张三" } }, { time: 101000, action: "审批同意", rawAction: "freeflow.agree", isEbot: true, operator: { name: "Ebot" } }, { time: 110000, action: "审批驳回", rawAction: "freeflow.reject", nodeName: "财务审批", comment: "发票模糊", operator: { name: "李四" } }, // July round (Run 2, not in current query batch) { time: 200000, action: "提交送审", rawAction: "freeflow.submit", operator: { name: "张三" } }, { time: 201000, action: "审批同意", rawAction: "freeflow.agree", isEbot: true, operator: { name: "Ebot" } }, { time: 210000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务审批", comment: "同意", operator: { name: "李四" } }, { time: 220000, action: "支付成功", rawAction: "freeflow.pay", operator: { name: "王五" } } ] } as any; const aligned = alignApprovalRunsWithHoseFlow(singleIsolatedRun, fullLifetimeHoseFlow); const r = aligned.get("run-june-round1")!; // Must NOT be falsely labeled as "已支付" just because Hose is currently paid! expect(r.eHumanAction).toBe("审批驳回"); expect(r.eHumanComment).toBe( "财务审批(李四) ❌: 发票模糊\n↳ 驳回至: 提交人\n↳ 重新提交后由李四继续审批" ); expect(r.auditDrift).toBe(false); }); }); });