From b9ea04adc60becb44ae6956da79d0ad9b1b7ac60 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 17:20:19 +0800 Subject: [PATCH 01/19] Add Hose approval flow alignment for approval runs export MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add Hose flow domain with OpenAPI & CloseAPI timeline and staff opinion parsing - Add E人工行为 and E人工意见 columns in approval runs Excel export - Add pre-flight scale/duration warning and smooth concurrency throttling (default concurrency 3, batch delay 150ms) - Add seal-use approval-runs flow diagnostic CLI command and tool - Support --to-downloads and --flow-concurrency CLI flags --- src/cli/commands/approval-runs.ts | 58 +- src/cli/help.ts | 7 +- src/core/auth/hose.ts | 2 +- src/domains/hose/api.ts | 44 + src/domains/hose/client.ts | 43 + src/domains/hose/close/api.ts | 118 +++ src/domains/hose/close/client.ts | 64 ++ src/domains/hose/close/index.ts | 3 + src/domains/hose/close/types.ts | 28 + src/domains/hose/flow.test.ts | 860 ++++++++++++++++++ src/domains/hose/flow.ts | 859 +++++++++++++++++ src/domains/hose/index.ts | 7 + src/domains/hose/open/api.ts | 179 ++++ src/domains/hose/open/client.ts | 55 ++ src/domains/hose/open/index.ts | 3 + src/domains/hose/open/types.ts | 173 ++++ src/domains/hose/types.ts | 157 ++++ src/domains/seal/approval-runs-export.test.ts | 73 ++ src/domains/seal/approval-runs-export.ts | 212 ++++- src/domains/seal/tools.ts | 154 ++++ 20 files changed, 3088 insertions(+), 11 deletions(-) create mode 100644 src/domains/hose/api.ts create mode 100644 src/domains/hose/client.ts create mode 100644 src/domains/hose/close/api.ts create mode 100644 src/domains/hose/close/client.ts create mode 100644 src/domains/hose/close/index.ts create mode 100644 src/domains/hose/close/types.ts create mode 100644 src/domains/hose/flow.test.ts create mode 100644 src/domains/hose/flow.ts create mode 100644 src/domains/hose/index.ts create mode 100644 src/domains/hose/open/api.ts create mode 100644 src/domains/hose/open/client.ts create mode 100644 src/domains/hose/open/index.ts create mode 100644 src/domains/hose/open/types.ts create mode 100644 src/domains/hose/types.ts diff --git a/src/cli/commands/approval-runs.ts b/src/cli/commands/approval-runs.ts index 41e7beb..3a6ad19 100644 --- a/src/cli/commands/approval-runs.ts +++ b/src/cli/commands/approval-runs.ts @@ -166,6 +166,16 @@ export async function handleApprovalRunsCommand( if (action === "get") { const recordId = args.command[2]; if (!recordId) throw new Error("Missing approval run recordId"); + if (booleanOption(args.options.flow)) { + await runTool( + "seal_approval_run_flow_get", + client, + corp, + { recordId }, + outputOptions(args.options) + ); + return; + } await runTool( "seal_approval_run_get", client, @@ -313,14 +323,40 @@ export async function handleApprovalRunsCommand( return; } + if (action === "flow") { + const target = + maybeName ?? + args.command[2] ?? + stringOption(args.options.sn) ?? + stringOption(args.options.id) ?? + stringOption(args.options.recordId); + if (!target) { + throw new Error("Usage: seal-use approval-runs flow "); + } + + await runTool( + "seal_approval_run_flow_get", + client, + corp, + { target }, + outputOptions(args.options) + ); + return; + } + if (action === "export") { const result = await exportApprovalRunsToExcel(client, corp, { limit: numberOption(args.options.limit), startDate: - stringOption(args.options.start) ?? + stringOption(args.options["start-date"]) ?? stringOption(args.options.startDate) ?? + stringOption(args.options.start) ?? stringOption(args.options.since), - endDate: stringOption(args.options.end) ?? stringOption(args.options.endDate), + endDate: + stringOption(args.options["end-date"]) ?? + stringOption(args.options.endDate) ?? + stringOption(args.options.end) ?? + stringOption(args.options.until), status: stringOption(args.options.status), manualApprovalStatus: stringOption(args.options["manual-status"]) ?? @@ -332,8 +368,22 @@ export async function handleApprovalRunsCommand( stringOption(args.options.out) ?? stringOption(args.options.output) ?? stringOption(args.options.file), - toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options.download), - force: booleanOption(args.options.force) + toDownloads: + booleanOption(args.options["to-downloads"]) ?? + booleanOption(args.options.downloads) ?? + booleanOption(args.options.download), + force: booleanOption(args.options.force), + withFlow: + booleanOption(args.options["with-flow"]) ?? + (booleanOption(args.options["no-flow"]) ? false : undefined), + flowConcurrency: + numberOption(args.options["flow-concurrency"]) ?? + numberOption(args.options.concurrency), + excludeDeleted: + booleanOption(args.options["exclude-deleted"]) ?? + (booleanOption(args.options["include-deleted"]) ? false : undefined), + taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]), + sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"]) }); printJson(result, outputOptions(args.options)); return; diff --git a/src/cli/help.ts b/src/cli/help.ts index 4551eb2..9526c7e 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -351,7 +351,12 @@ export const HELP_REGISTRY: AreaHelp[] = [ { name: "export", summary: "Export approval run audit records to Excel workbook", - usage: ["seal-use approval-runs export [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads] [--out ] [--corp ]"] + usage: ["seal-use approval-runs export [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads|--to-downloads] [--with-flow|--no-flow] [--out ] [--corp ]"] + }, + { + name: "flow", + summary: "Get Hose approval flow timeline, staff opinions, and align with AI runs", + usage: ["seal-use approval-runs flow [--corp ]"] }, { name: "list", diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts index 5f96493..5fb6148 100644 --- a/src/core/auth/hose.ts +++ b/src/core/auth/hose.ts @@ -357,7 +357,7 @@ export async function fetchHoseCloseApiToken( }; } -async function ensureHoseCloseApiToken(corp: CorpConfig): Promise { +export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); } diff --git a/src/domains/hose/api.ts b/src/domains/hose/api.ts new file mode 100644 index 0000000..93cd342 --- /dev/null +++ b/src/domains/hose/api.ts @@ -0,0 +1,44 @@ +// --- Hose OpenAPI (hose-open) --- +export { + fetchHoseOpenFlowDetails, + fetchHoseOpenAllLogs, + fetchHoseOpenVersioned, + fetchHoseOpenCompositeFlow, + type FetchHoseOpenVersionedOptions +} from "./open/api.js"; + +// --- Hose CloseAPI (hose-close) --- +export { + searchCloseBacklogs, + getCloseBacklogDetailById, + resolveCloseBacklogId, + fetchRawCloseHoseFlow, + HOSE_CLOSE_LOOKUP_SELECT, + HOSE_CLOSE_DETAIL_SELECT, + HOSE_CLOSE_JOINS, + type SearchCloseBacklogsOptions, + type CloseBacklogDetailOptions +} from "./close/api.js"; + +// Legacy aliases for backward compatibility +import { + searchCloseBacklogs, + getCloseBacklogDetailById, + resolveCloseBacklogId, + fetchRawCloseHoseFlow, + HOSE_CLOSE_LOOKUP_SELECT, + HOSE_CLOSE_DETAIL_SELECT, + HOSE_CLOSE_JOINS, + type SearchCloseBacklogsOptions, + type CloseBacklogDetailOptions +} from "./close/api.js"; + +export const HOSE_FLOW_LOOKUP_SELECT = HOSE_CLOSE_LOOKUP_SELECT; +export const HOSE_FLOW_DETAIL_SELECT = HOSE_CLOSE_DETAIL_SELECT; +export const HOSE_FLOW_JOINS = HOSE_CLOSE_JOINS; +export type SearchBacklogsOptions = SearchCloseBacklogsOptions; +export type BacklogDetailOptions = CloseBacklogDetailOptions; +export const searchBacklogs = searchCloseBacklogs; +export const getBacklogDetailById = getCloseBacklogDetailById; +export const resolveBacklogId = resolveCloseBacklogId; +export const fetchRawHoseFlow = fetchRawCloseHoseFlow; diff --git a/src/domains/hose/client.ts b/src/domains/hose/client.ts new file mode 100644 index 0000000..c19718c --- /dev/null +++ b/src/domains/hose/client.ts @@ -0,0 +1,43 @@ +import type { KyInstance } from "ky"; +import type { CorpConfig } from "../../core/config/types.js"; +import { + createHoseOpenClient, + createHoseOpenClientWithCredentials, + type HoseOpenClientCredentials +} from "./open/client.js"; +import { + createHoseCloseClient, + createHoseCloseClientWithCredentials, + getHoseCloseHeaders, + type HoseCloseClientCredentials +} from "./close/client.js"; + +// Re-exports with explicit open vs close distinction +export { + createHoseOpenClient, + createHoseOpenClientWithCredentials, + type HoseOpenClientCredentials +} from "./open/client.js"; + +export { + createHoseCloseClient, + createHoseCloseClientWithCredentials, + getHoseCloseHeaders, + type HoseCloseClientCredentials +} from "./close/client.js"; + +// Legacy aliases for backward compatibility +export type HoseClientCredentials = HoseCloseClientCredentials; +export const getHoseHeaders = getHoseCloseHeaders; +export const createHoseClientWithCredentials = createHoseCloseClientWithCredentials; + +/** + * Default Hose client creator: uses Hose OpenAPI (hose-open). + * Bypasses row-level permission fences and requires no proxy staff ID. + */ +export async function createHoseClient( + corp: CorpConfig, + customHeaders?: Record +): Promise { + return createHoseOpenClient(corp, customHeaders); +} diff --git a/src/domains/hose/close/api.ts b/src/domains/hose/close/api.ts new file mode 100644 index 0000000..094958d --- /dev/null +++ b/src/domains/hose/close/api.ts @@ -0,0 +1,118 @@ +import type { KyInstance } from "ky"; +import { + RawHoseBacklogItemSchema, + type RawHoseBacklogDetailResponse, + type RawHoseBacklogItem, + type RawHoseBacklogSearchResponse +} from "./types.js"; + +export const HOSE_CLOSE_LOOKUP_SELECT = "flowId(form(code,title),`...`),`...`"; + +export const HOSE_CLOSE_DETAIL_SELECT = + "flowId(form(specificationId(id,name,code),`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`"; + +export const HOSE_CLOSE_JOINS = [ + "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" +] as const; + +export interface SearchCloseBacklogsOptions { + filterBy: string; + limit?: { start: number; count: number }; + select?: string; +} + +export interface CloseBacklogDetailOptions { + select?: string; + joins?: readonly string[] | string[]; +} + +export async function searchCloseBacklogs( + client: KyInstance, + corpId: string, + options: SearchCloseBacklogsOptions +): Promise { + const response = await client.post("api/flow/v2/backlogs/search", { + searchParams: { corpId }, + json: { + filterBy: options.filterBy, + limit: options.limit ?? { start: 0, count: 100 }, + select: options.select ?? HOSE_CLOSE_LOOKUP_SELECT + } + }); + const data = (await response.json()) as RawHoseBacklogSearchResponse; + return (data.items ?? []).map((item) => RawHoseBacklogItemSchema.parse(item)); +} + +export async function getCloseBacklogDetailById( + client: KyInstance, + corpId: string, + backlogId: string, + options?: CloseBacklogDetailOptions +): Promise | undefined> { + const params = new URLSearchParams({ corpId }); + const joins = options?.joins ?? HOSE_CLOSE_JOINS; + for (const join of joins) { + params.append("join", join); + } + + const response = await client.post("api/flow/v2/backlogs/id", { + searchParams: params, + json: { + filterBy: `(id==${JSON.stringify(backlogId)})`, + select: options?.select ?? HOSE_CLOSE_DETAIL_SELECT + } + }); + const data = (await response.json()) as RawHoseBacklogDetailResponse; + return data.value ?? data.items?.[0]; +} + +export async function resolveCloseBacklogId( + client: KyInstance, + corpId: string, + target: string +): Promise { + const cleanTarget = target.trim(); + if (!cleanTarget) return target; + + const filters = [ + `(id==${JSON.stringify(cleanTarget)})||((flowId.id==${JSON.stringify(cleanTarget)})||(flowId.form.code==${JSON.stringify(cleanTarget)}))`, + `(state.in("APPROVING","PROCESSED","REJECTED","DRAFT"))` + ]; + + for (const filterBy of filters) { + try { + const items = await searchCloseBacklogs(client, corpId, { + filterBy, + limit: { start: 0, count: 100 }, + select: HOSE_CLOSE_LOOKUP_SELECT + }); + const match = 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 === cleanTarget || flow.id === cleanTarget || form.code === cleanTarget; + }); + if (match && typeof match.id === "string") { + return match.id; + } + } catch { + // Fall through to next filter or return raw target + } + } + + return cleanTarget; +} + +export async function fetchRawCloseHoseFlow( + client: KyInstance, + corpId: string, + target: string +): Promise | undefined> { + const backlogId = await resolveCloseBacklogId(client, corpId, target); + return getCloseBacklogDetailById(client, corpId, backlogId); +} diff --git a/src/domains/hose/close/client.ts b/src/domains/hose/close/client.ts new file mode 100644 index 0000000..a708e06 --- /dev/null +++ b/src/domains/hose/close/client.ts @@ -0,0 +1,64 @@ +import ky, { HTTPError, type KyInstance } from "ky"; +import { ensureHoseCloseApiToken, normalizeBaseUrl } from "../../../core/auth/hose.js"; +import type { CorpConfig } from "../../../core/config/types.js"; + +export interface HoseCloseClientCredentials { + domain: string; + corpId: string; + staffId: string; + accessToken: string; +} + +export function getHoseCloseHeaders(credentials: HoseCloseClientCredentials): Record { + return { + accesstoken: credentials.accessToken, + corpid: credentials.corpId, + staffid: credentials.staffId + }; +} + +export function createHoseCloseClientWithCredentials( + credentials: HoseCloseClientCredentials, + customHeaders?: Record +): KyInstance { + return ky.create({ + prefix: normalizeBaseUrl(credentials.domain), + timeout: 30000, + headers: { + ...getHoseCloseHeaders(credentials), + ...customHeaders + }, + hooks: { + beforeError: [ + async ({ error }) => { + const body = + error instanceof HTTPError + ? await error.response.text().catch(() => "") + : ""; + error.message = `${error.message}${body ? `: ${body}` : ""}`; + return error; + } + ] + } + }); +} + +export async function createHoseCloseClient( + corp: CorpConfig, + customHeaders?: Record +): Promise { + if (corp.source.type !== "hose") { + throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`); + } + + const tokenEntry = await ensureHoseCloseApiToken(corp); + return createHoseCloseClientWithCredentials( + { + domain: corp.source.domain, + corpId: corp.source.corpId, + staffId: corp.source.staffId, + accessToken: tokenEntry.token + }, + customHeaders + ); +} diff --git a/src/domains/hose/close/index.ts b/src/domains/hose/close/index.ts new file mode 100644 index 0000000..498d3bc --- /dev/null +++ b/src/domains/hose/close/index.ts @@ -0,0 +1,3 @@ +export * from "./types.js"; +export * from "./client.js"; +export * from "./api.js"; diff --git a/src/domains/hose/close/types.ts b/src/domains/hose/close/types.ts new file mode 100644 index 0000000..6d2c473 --- /dev/null +++ b/src/domains/hose/close/types.ts @@ -0,0 +1,28 @@ +import { z } from "zod"; + +export const RawHoseBacklogItemSchema = z + .object({ + id: z.string(), + state: z.string().optional(), + nodeName: z.string().optional(), + flowId: z.record(z.string(), z.unknown()).optional(), + nodeState: z.record(z.string(), z.unknown()).optional() + }) + .passthrough(); +export type RawHoseBacklogItem = z.infer; + +export const RawHoseBacklogSearchResponseSchema = z + .object({ + count: z.number().optional(), + items: z.array(z.record(z.string(), z.unknown())).default([]) + }) + .passthrough(); +export type RawHoseBacklogSearchResponse = z.infer; + +export const RawHoseBacklogDetailResponseSchema = z + .object({ + value: z.record(z.string(), z.unknown()).optional(), + items: z.array(z.record(z.string(), z.unknown())).optional() + }) + .passthrough(); +export type RawHoseBacklogDetailResponse = z.infer; diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts new file mode 100644 index 0000000..9c11976 --- /dev/null +++ b/src/domains/hose/flow.test.ts @@ -0,0 +1,860 @@ +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 +} 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("发票不全缺少总经理审批,退回修改"); + 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("财务C: 核销通过"); + expect(r3.operator?.name).toBe("财务C"); + expect(r3.auditDrift).toBe(false); + }); + + test("handles unfinished flow: pending on human node", () => { + 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("财务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("通过 (⚠️ AI通过后被中途修改)"); + expect(r1.auditDrift).toBe(true); + expect(r1.auditDriftReason).toContain("AI通过后单据发生撤回/修改重提"); + }); + }); +}); + diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts new file mode 100644 index 0000000..e962802 --- /dev/null +++ b/src/domains/hose/flow.ts @@ -0,0 +1,859 @@ +import type { KyInstance } from "ky"; +import type { ApprovalRun } from "../seal/types.js"; +import { + fetchHoseOpenCompositeFlow, + type HoseOpenAllLogsItem, + type HoseOpenCompositeData, + type HoseOpenFlowLog, + type HoseOpenStaffItem, + type HoseOpenVersionedItem +} from "./open/index.js"; +export type { HoseOpenStaffItem } from "./open/index.js"; +import { + fetchRawCloseHoseFlow +} from "./close/index.js"; +import { + HOSE_FLOW_ACTION_LABELS, + HOSE_FLOW_STATE_LABELS, + type FlowPerson, + type HoseFlowDetail, + type HoseFlowMetrics, + type HoseFlowPendingNode, + type HoseFlowTimelineEntry, + type HoseRejectionDetail, + type HoseRunAlignment, + type HoseStaffOpinion +} from "./types.js"; + +export function cleanCommentText(comment?: string): string | undefined { + if (!comment || typeof comment !== "string") return undefined; + const stripped = comment + .replace(/<[^>]*>/g, "") + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/"/g, "\"") + .replace(/'/g, "'") + .replace(/ /g, " ") + .trim(); + return stripped.length > 0 ? stripped : undefined; +} + +export function translateFlowAction(action?: string): string | undefined { + if (!action) return undefined; + return HOSE_FLOW_ACTION_LABELS[action] || action; +} + +export function translateFlowState(state?: string): string | undefined { + if (!state) return undefined; + return HOSE_FLOW_STATE_LABELS[state.toUpperCase()] || state; +} + +export function extractFlowPerson(value: unknown): FlowPerson | undefined { + if (typeof value === "string") { + const trimmed = value.trim(); + return trimmed ? { id: trimmed } : undefined; + } + if (!value || typeof value !== "object") return undefined; + + let obj = value as Record; + if (obj.signerId && typeof obj.signerId === "object") { + obj = obj.signerId as Record; + } + + const id = typeof obj.id === "string" ? obj.id.trim() : undefined; + const name = + typeof obj.name === "string" && obj.name.trim() + ? obj.name.trim() + : typeof obj.nickName === "string" && obj.nickName.trim() + ? obj.nickName.trim() + : undefined; + const code = typeof obj.code === "string" && obj.code.trim() ? obj.code.trim() : undefined; + + if (!id && !name && !code) return undefined; + return { id, name, code }; +} + +export function isEbotOperator( + operator?: FlowPerson, + attributes?: Record +): boolean { + if (attributes?.isEbotNode === true) return true; + const combined = `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase(); + if (combined.includes("ebot")) return true; + if (operator?.name?.includes("智能审批") || operator?.name?.includes("AI审批")) return true; + if ( + typeof attributes?.nodeName === "string" && + (attributes.nodeName.toLowerCase().includes("ebot") || + attributes.nodeName.includes("智能审批")) + ) { + return true; + } + return false; +} + +export function formatOperator( + operator?: FlowPerson, + automatic = false, + isEbot = false +): FlowPerson | undefined { + if (isEbot) { + return { + id: operator?.id || "ebot", + name: "Ebot (智能审批)", + code: operator?.code + }; + } + if (!operator && automatic) { + return { + id: "system", + name: "系统自动" + }; + } + return operator; +} + +export function parseHoseTimeline( + rawLogs: unknown[], + staffMap?: Map +): HoseFlowTimelineEntry[] { + const logs = Array.isArray(rawLogs) + ? rawLogs.filter((l): l is Record => Boolean(l && typeof l === "object")) + : []; + + const sortedLogs = [...logs].sort((a, b) => (Number(a.time) || 0) - (Number(b.time) || 0)); + + return sortedLogs.map((log, index) => { + const attributes = + log.attributes && typeof log.attributes === "object" + ? (log.attributes as Record) + : {}; + const currentTime = typeof log.time === "number" ? log.time : undefined; + const nextLog = sortedLogs[index + 1]; + const nextTime = typeof nextLog?.time === "number" ? nextLog.time : undefined; + const durationMs = + currentTime !== undefined && nextTime !== undefined && nextTime >= currentTime + ? nextTime - currentTime + : undefined; + + const rawOperator = extractFlowPerson(log.operatorId); + const isEbot = isEbotOperator(rawOperator, attributes); + const automatic = Boolean( + attributes.isEbotNode === true || + attributes.isAuto === true || + log.action === "freeflow.autoAgree" || + !log.operatorId || + isEbot + ); + let operator = formatOperator(rawOperator, automatic, isEbot); + if (operator && !operator.name && staffMap && operator.id) { + const idParts = operator.id.split(":"); + const staff = + staffMap.get(operator.id) || + (idParts.length > 1 && idParts[1] ? staffMap.get(idParts[1]) : undefined); + if (staff?.name) { + operator = { + ...operator, + name: staff.name, + code: staff.code || operator.code + }; + } + } + + const rawAction = typeof log.action === "string" ? log.action : undefined; + const action = translateFlowAction(rawAction); + const rawState = typeof log.state === "string" ? log.state : undefined; + const state = translateFlowState(rawState); + + const nodeName = + typeof attributes.nodeName === "string" && attributes.nodeName + ? attributes.nodeName + : typeof attributes.nextName === "string" && attributes.nextName + ? attributes.nextName + : action === "打印单据" + ? "打印提醒" + : undefined; + + const rawComment = typeof attributes.comment === "string" ? attributes.comment : undefined; + const comment = cleanCommentText(rawComment); + const skipped = Boolean( + attributes.isSkip === true || attributes.skipped === true || rawState === "SKIPPED" + ); + + const nextIds = Array.isArray(log.nextOperatorIds) + ? log.nextOperatorIds + : log.nextOperatorId + ? [log.nextOperatorId] + : []; + const nextOperators = nextIds + .map(extractFlowPerson) + .filter((p): p is FlowPerson => Boolean(p)); + + return { + id: typeof log.id === "string" ? log.id : undefined, + time: currentTime, + durationMs, + state, + rawState, + action, + rawAction, + nodeName, + comment, + rawComment, + automatic, + isEbot, + skipped, + operator, + nextOperators + }; + }); +} + +export function parseHosePending( + plan: Record, + currentNodeName?: string, + currentNodeId?: string +): HoseFlowPendingNode[] { + const nextNodeId = typeof plan.nextNodeId === "string" ? plan.nextNodeId : undefined; + const nodes = Array.isArray(plan.nodes) ? plan.nodes : []; + + return nodes.map((value) => { + const node = value && typeof value === "object" ? (value as Record) : {}; + const id = typeof node.id === "string" ? node.id : undefined; + const name = typeof node.name === "string" ? node.name : undefined; + const type = typeof node.type === "string" ? node.type : undefined; + + const isCurrent = Boolean( + (id && id === nextNodeId) || + (currentNodeName && name === currentNodeName) || + (currentNodeId && id === currentNodeId) + ); + + const approver = extractFlowPerson(node.approverId); + const approvers = Array.isArray(node.counterSigners) + ? node.counterSigners.map(extractFlowPerson).filter((p): p is FlowPerson => Boolean(p)) + : []; + + return { + id, + name, + type, + state: isCurrent ? "当前" : "后续", + isCurrent, + approver, + approvers + }; + }); +} + +export function parseHoseOpenPending( + allLogs: HoseOpenAllLogsItem[], + staffMap?: Map +): HoseFlowPendingNode[] { + const pendingItems = allLogs.filter( + (item) => + item.logId === -1 || + item.state === "APPROVING" || + item.state === "PROCESSING" || + item.state === "PAYING" + ); + + return pendingItems.map((item, index) => { + let approver = extractFlowPerson(item.ownerId); + if (approver && !approver.name && staffMap && item.ownerId) { + const ownerParts = item.ownerId.split(":"); + const staff = + staffMap.get(item.ownerId) || + (ownerParts.length > 1 && ownerParts[1] ? staffMap.get(ownerParts[1]) : undefined); + if (staff?.name) { + approver = { + ...approver, + name: staff.name, + code: staff.code || approver.code + }; + } + } + return { + id: item.nodeId || item.id, + name: item.nodeName, + type: item.state, + state: index === 0 ? "当前" : "后续", + isCurrent: index === 0, + approver, + approvers: approver ? [approver] : [] + }; + }); +} + +export function calculateFlowMetrics( + flow: Record, + history: HoseFlowTimelineEntry[], + rawBacklog?: Record, + versions?: HoseOpenVersionedItem[] +): HoseFlowMetrics { + const form = + flow.form && typeof flow.form === "object" ? (flow.form as Record) : {}; + + const rejectionLogs = history.filter( + (e) => + e.rawAction === "freeflow.reject" || e.rawState === "REJECTED" || e.action === "审批驳回" + ); + const formRejectionNum = + typeof form.rejectionNum === "number" + ? form.rejectionNum + : typeof form.rejectionNum === "string" + ? parseInt(form.rejectionNum, 10) || undefined + : undefined; + const rejectionNum = + formRejectionNum !== undefined ? formRejectionNum : rejectionLogs.length; + + const submitLogs = history.filter( + (e) => + e.rawAction === "freeflow.submit" || e.rawState === "SUBMITTED" || e.action === "提交送审" + ); + const formSubmitCount = + typeof form.submitCount === "number" ? form.submitCount : undefined; + const versionCount = versions && versions.length > 0 ? versions.length : undefined; + const submitCount = + formSubmitCount !== undefined + ? formSubmitCount + : versionCount !== undefined + ? Math.max(versionCount, submitLogs.length, 1) + : Math.max(1, submitLogs.length); + + const retractLogs = history.filter( + (e) => + e.rawAction === "freeflow.retract" || e.rawState === "REVOKED" || e.action === "单据撤回" + ); + const retractCount = retractLogs.length; + + const sourceFlowVersion = + form.sourceFlowVersion ?? flow.sourceFlowVersion ?? form.version ?? flow.version; + + let isModifiedAfterReject = false; + if (rejectionNum > 0 || rejectionLogs.length > 0) { + const lastRejectTime = Math.max(...rejectionLogs.map((e) => e.time ?? 0), 0); + const hasSubsequentSubmit = history.some( + (e) => + (e.time ?? 0) > lastRejectTime && + (e.rawAction === "freeflow.submit" || + e.rawState === "SUBMITTED" || + e.action === "提交送审") + ); + const hasSubsequentActivity = history.some( + (e) => + (e.time ?? 0) > lastRejectTime && + e.rawAction !== "freeflow.reject" && + e.rawAction !== "freeflow.print" + ); + const currentState = String(rawBacklog?.state ?? flow.state ?? "").toUpperCase(); + const isCurrentlyRejected = + currentState === "REJECTED" || + (rejectionLogs.length > 0 && history.at(-1)?.rawAction === "freeflow.reject"); + const submitDate = typeof form.submitDate === "number" ? form.submitDate : 0; + const updateTime = + typeof form.updateTime === "number" + ? form.updateTime + : typeof flow.updateTime === "number" + ? flow.updateTime + : 0; + + isModifiedAfterReject = + hasSubsequentSubmit || + (!isCurrentlyRejected && + (hasSubsequentActivity || + submitDate > lastRejectTime || + updateTime > lastRejectTime || + submitCount > rejectionNum)); + } + + let isResubmittedAfterRetract = false; + if (retractCount > 0) { + const lastRetractTime = Math.max(...retractLogs.map((e) => e.time ?? 0), 0); + const hasSubsequentSubmit = history.some( + (e) => + (e.time ?? 0) > lastRetractTime && + (e.rawAction === "freeflow.submit" || + e.rawState === "SUBMITTED" || + e.action === "提交送审") + ); + const currentState = String(rawBacklog?.state ?? flow.state ?? "").toUpperCase(); + const isCurrentlyRevoked = + currentState === "REVOKED" || + (retractLogs.length > 0 && history.at(-1)?.rawAction === "freeflow.retract"); + const updateTime = + typeof form.updateTime === "number" + ? form.updateTime + : typeof flow.updateTime === "number" + ? flow.updateTime + : 0; + + isResubmittedAfterRetract = + hasSubsequentSubmit || + (!isCurrentlyRevoked && (submitCount > 1 || updateTime > lastRetractTime)); + } + + return { + rejectionNum, + submitCount, + sourceFlowVersion: + typeof sourceFlowVersion === "string" || typeof sourceFlowVersion === "number" + ? sourceFlowVersion + : undefined, + isModifiedAfterReject, + retractCount, + isResubmittedAfterRetract + }; +} + +export function extractStaffOpinions(history: HoseFlowTimelineEntry[]): HoseStaffOpinion[] { + return history + .filter((entry) => Boolean(entry.comment && entry.comment.trim())) + .map((entry) => ({ + nodeName: entry.nodeName, + operator: entry.operator, + action: entry.action, + rawAction: entry.rawAction, + time: entry.time, + comment: entry.comment!, + isEbot: entry.isEbot + })); +} + +export function extractRejections(history: HoseFlowTimelineEntry[]): HoseRejectionDetail[] { + return history + .filter( + (entry) => + entry.rawAction === "freeflow.reject" || + entry.rawState === "REJECTED" || + entry.action === "审批驳回" + ) + .map((entry) => ({ + time: entry.time, + nodeName: entry.nodeName, + operator: entry.operator, + isEbot: entry.isEbot, + reason: entry.comment || "未填写驳回原因", + rawComment: entry.rawComment + })); +} + +/** + * Parses Hose OpenAPI composite data (hose-open) into unified HoseFlowDetail. + */ +export function parseHoseOpenComposite( + composite: HoseOpenCompositeData, + fallbackTarget?: string +): HoseFlowDetail | undefined { + const { flowDetails, allLogs, versions, staffMap } = composite; + if (!flowDetails) return undefined; + + const form = (flowDetails.form || {}) as Record; + const history = parseHoseTimeline(flowDetails.logs || [], staffMap); + const pending = parseHoseOpenPending(allLogs, staffMap); + + const currentNode = pending.find((p) => p.isCurrent)?.name; + const metrics = calculateFlowMetrics( + flowDetails as unknown as Record, + history, + undefined, + versions + ); + const staffOpinions = extractStaffOpinions(history); + const rejections = extractRejections(history); + + const rawState = flowDetails.state; + const state = translateFlowState(rawState); + + let specification: { id?: string; name?: string; code?: string } | undefined; + if (form.specificationId && typeof form.specificationId === "object") { + const specObj = form.specificationId as Record; + specification = { + id: typeof specObj.id === "string" ? specObj.id : undefined, + name: typeof specObj.name === "string" ? specObj.name : undefined, + code: typeof specObj.code === "string" ? specObj.code : undefined + }; + } else if (typeof form.specificationId === "string") { + specification = { id: form.specificationId }; + } + + return { + backlogId: flowDetails.id || fallbackTarget || "", + flowId: flowDetails.id, + billCode: typeof form.code === "string" ? form.code : undefined, + title: typeof form.title === "string" ? form.title : undefined, + state, + rawState, + currentNode, + specification, + submitter: extractFlowPerson(form.submitterId), + owner: extractFlowPerson(flowDetails.ownerId || form.ownerId), + submitDate: typeof form.submitDate === "number" ? form.submitDate : undefined, + updateTime: + typeof form.updateTime === "number" + ? form.updateTime + : typeof flowDetails.updateTime === "number" + ? flowDetails.updateTime + : undefined, + history, + pending, + metrics, + staffOpinions, + rejections, + raw: flowDetails as unknown as Record + }; +} + +/** + * Parses raw CloseAPI payload (hose-close) into unified HoseFlowDetail. + */ +export function parseHoseFlow( + raw: Record, + fallbackTarget?: string +): HoseFlowDetail { + const flow = + raw.flowId && typeof raw.flowId === "object" + ? (raw.flowId as Record) + : raw; + const form = + flow.form && typeof flow.form === "object" + ? (flow.form as Record) + : {}; + const nodeState = + raw.nodeState && typeof raw.nodeState === "object" + ? (raw.nodeState as Record) + : {}; + const plan = + flow.plan && typeof flow.plan === "object" + ? (flow.plan as Record) + : {}; + + const history = parseHoseTimeline(Array.isArray(flow.logs) ? flow.logs : []); + const currentNode = + typeof raw.nodeName === "string" + ? raw.nodeName + : typeof nodeState.nodeName === "string" + ? nodeState.nodeName + : undefined; + const currentNodeId = + typeof raw.nodeId === "string" + ? raw.nodeId + : typeof nodeState.nodeId === "string" + ? nodeState.nodeId + : undefined; + + const pending = parseHosePending(plan, currentNode, currentNodeId); + const metrics = calculateFlowMetrics(flow, history, raw); + const staffOpinions = extractStaffOpinions(history); + const rejections = extractRejections(history); + + const rawState = + typeof raw.state === "string" + ? raw.state + : typeof flow.state === "string" + ? flow.state + : undefined; + const state = translateFlowState(rawState); + + const lastAttributes = + history.at(-1)?.nodeName ?? + (flow.logs && Array.isArray(flow.logs) && flow.logs.length > 0 + ? (flow.logs.at(-1) as Record)?.attributes + : undefined); + const resolvedCurrentNode = + currentNode ?? + (lastAttributes && typeof lastAttributes === "object" + ? (lastAttributes as Record).nextName + : typeof lastAttributes === "string" + ? lastAttributes + : undefined); + + let specification: { id?: string; name?: string; code?: string } | undefined; + if (form.specificationId && typeof form.specificationId === "object") { + const specObj = form.specificationId as Record; + specification = { + id: typeof specObj.id === "string" ? specObj.id : undefined, + name: typeof specObj.name === "string" ? specObj.name : undefined, + code: typeof specObj.code === "string" ? specObj.code : undefined + }; + } else if (typeof form.specificationId === "string") { + specification = { id: form.specificationId }; + } + + return { + backlogId: typeof raw.id === "string" ? raw.id : fallbackTarget || "", + flowId: typeof flow.id === "string" ? flow.id : undefined, + billCode: typeof form.code === "string" ? form.code : undefined, + title: typeof form.title === "string" ? form.title : undefined, + state, + rawState, + currentNode: typeof resolvedCurrentNode === "string" ? resolvedCurrentNode : undefined, + specification, + submitter: extractFlowPerson(form.submitterId), + owner: extractFlowPerson(flow.ownerId ?? form.ownerId), + submitDate: typeof form.submitDate === "number" ? form.submitDate : undefined, + updateTime: + typeof form.updateTime === "number" + ? form.updateTime + : typeof flow.updateTime === "number" + ? flow.updateTime + : undefined, + history, + pending, + metrics, + staffOpinions, + rejections, + raw + }; +} + +/** + * Primary OpenAPI implementation: fetch unified Hose flow details via hose-open. + * Bypasses row-level staff isolation and requires no proxy staff ID. + */ +export async function getHoseOpenFlow( + client: KyInstance, + flowId: string, + staffCache?: Map +): Promise { + const composite = await fetchHoseOpenCompositeFlow(client, flowId, staffCache); + return parseHoseOpenComposite(composite, flowId); +} + +/** + * Legacy CloseAPI implementation: fetch raw Hose flow via hose-close. + * Subject to staff row-level permission isolation. + */ +export async function getHoseCloseFlow( + client: KyInstance, + corpId: string, + target: string +): Promise { + const raw = await fetchRawCloseHoseFlow(client, corpId, target); + if (!raw) return undefined; + return parseHoseFlow(raw, target); +} + +/** + * Unified flow getter: defaults to OpenAPI (hose-open) when flowId is provided, + * with fallback to CloseAPI if explicitly needed. + */ +export async function getHoseFlow( + client: KyInstance, + targetOrCorpId: string, + targetOrFlowId?: string, + staffCache?: Map +): Promise { + const flowId = targetOrFlowId ?? targetOrCorpId; + return getHoseOpenFlow(client, flowId, staffCache); +} + +export function alignApprovalRunsWithHoseFlow( + runs: ApprovalRun[], + flow?: HoseFlowDetail +): Map { + const result = new Map(); + if (!runs || runs.length === 0) return result; + + if (!flow) { + for (const run of runs) { + const res = (run.result as Record | undefined) || {}; + const aiDecision = (res.decision as string | undefined) || (run as Record).aiDecision || "-"; + result.set(run.id, { + recordId: run.id, + sourceDocumentSN: run.sourceDocumentSN, + taskMode: run.taskMode, + aiDecision: typeof aiDecision === "string" ? aiDecision : "-", + aiAction: "-", + eHumanAction: "-", + eHumanComment: "-", + auditDrift: false + }); + } + return result; + } + + const sortedRuns = [...runs].sort( + (a, b) => (Number(a.createdAt) || 0) - (Number(b.createdAt) || 0) + ); + + const history = flow.history || []; + const isFlowCompleted = + flow.rawState === "COMPLETED" || + flow.rawState === "APPROVED" || + flow.state === "已完成" || + flow.state === "审批通过"; + + for (let i = 0; i < sortedRuns.length; i++) { + const run = sortedRuns[i]; + if (!run) continue; + const runTime = Number(run.createdAt) || 0; + const nextRun = sortedRuns[i + 1]; + const nextRunTime = nextRun ? Number(nextRun.createdAt) || Infinity : Infinity; + const isLatestRun = i === sortedRuns.length - 1; + + const res = (run.result as Record | undefined) || {}; + const rawAiDecision = (res.decision as string | undefined) || (run as Record).aiDecision || "-"; + const aiDecisionStr = typeof rawAiDecision === "string" ? rawAiDecision : "-"; + const normDecision = aiDecisionStr.toUpperCase(); + const isReject = normDecision === "REJECT" || normDecision === "驳回"; + const isApprove = normDecision === "APPROVE" || normDecision === "通过"; + + const taskMode = run.taskMode || run.finalExecutionMode || ""; + const normMode = String(taskMode).toLowerCase(); + const isAutomatic = + normMode.includes("auto") || + run.finalExecutionMode === "automatic" || + taskMode === "automatic" || + taskMode === "fully_automatic"; + + let aiAction = "-"; + if (isApprove) aiAction = "添加评论"; + else if (isReject) aiAction = isAutomatic ? "驳回" : "添加评论"; + else if (normDecision === "REVIEW" || normDecision === "转交复核") aiAction = "转交复核"; + + // 5-second clock skew tolerance window [runTime - 5000, nextRunTime) + const windowEvents = history.filter((e) => { + const t = e.time ?? 0; + return t >= runTime - 5000 && t < nextRunTime; + }); + + let eHumanAction = "-"; + let eHumanComment = "-"; + let auditDrift = false; + let auditDriftReason: string | undefined; + let operator: FlowPerson | undefined; + + // Check for Post-AI Mutation / Audit Drift + const postAiEvents = history.filter((e) => (e.time ?? 0) > runTime + 5000); + const hasPostAiRetract = postAiEvents.some( + (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" + ); + const hasPostAiResubmit = postAiEvents.some( + (e) => e.rawAction === "freeflow.submit" || e.action === "提交送审" + ); + + if (isLatestRun && (hasPostAiRetract || hasPostAiResubmit)) { + auditDrift = true; + auditDriftReason = "AI通过后单据发生撤回/修改重提,后续未经AI复审"; + } + + if (isAutomatic && isReject) { + // AI in automatic mode hard-rejected directly on Hose as Ebot. + // No human operator acted in this round (AI took full control). + eHumanAction = "无操作"; + eHumanComment = "-"; + } else { + // Subsequent human events after current AI run + const subsequentHumanEvents = windowEvents.filter( + (e) => + (e.time ?? 0) >= runTime - 1000 && + !e.isEbot && + e.rawAction !== "freeflow.submit" && + e.action !== "提交送审" && + e.rawAction !== "freeflow.print" && + e.action !== "打印提醒" && + e.rawAction !== "freeflow.comment" + ); + + const rejectEvent = subsequentHumanEvents.find( + (e) => e.rawAction === "freeflow.reject" || e.action === "审批驳回" + ); + + const pendingNodes = flow.pending || []; + const currentPending = pendingNodes.find((p) => p.isCurrent) || pendingNodes[0]; + + if (!isFlowCompleted) { + // Flow is still approving / in progress + eHumanAction = auditDrift ? "审核中 (⚠️ AI通过后被修改重提)" : "审核中"; + + const opinionLines: string[] = []; + for (const ev of subsequentHumanEvents) { + const opName = ev.operator?.name || ev.operator?.id || "未知"; + const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; + const comment = + ev.comment || + (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" + ? "同意" + : ev.action || "-"); + opinionLines.push(`${nodePrefix}: ${comment}`); + if (!operator) operator = ev.operator; + } + + if (currentPending) { + const pApprover = + currentPending.approver?.name || currentPending.approver?.id || "待定"; + const pNodeName = (currentPending.name || flow.currentNode || "").trim(); + const pPrefix = pNodeName ? `${pNodeName}(${pApprover})` : pApprover; + opinionLines.push(`${pPrefix}:当前审核节点`); + } else if (flow.currentNode?.trim()) { + opinionLines.push(`${flow.currentNode.trim()}:当前审核节点`); + } + + eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "当前审核节点"; + } else { + // Flow is completed + const hasRetract = subsequentHumanEvents.some( + (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" + ); + + if (auditDrift) { + eHumanAction = "通过 (⚠️ AI通过后被中途修改)"; + } else if (rejectEvent) { + eHumanAction = "驳回"; + } else if (hasRetract) { + eHumanAction = "已撤回"; + } else { + eHumanAction = "通过"; + } + + if (rejectEvent) { + eHumanComment = rejectEvent.comment || "驳回"; + operator = rejectEvent.operator; + } else { + const opinionLines: string[] = []; + for (const ev of subsequentHumanEvents) { + const opName = ev.operator?.name || ev.operator?.id || "未知"; + const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; + const comment = + ev.comment || + (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" + ? "同意" + : ev.action || "-"); + opinionLines.push(`${nodePrefix}: ${comment}`); + if (!operator) operator = ev.operator; + } + + if (opinionLines.length > 0) { + eHumanComment = opinionLines.join("\n"); + } else { + const lastHumanApproval = [...windowEvents] + .reverse() + .find( + (e) => + !e.isEbot && + (e.rawAction === "freeflow.agree" || e.action === "审批同意") + ); + eHumanComment = lastHumanApproval?.comment || "-"; + if (!operator) operator = lastHumanApproval?.operator; + } + } + } + } + + result.set(run.id, { + recordId: run.id, + sourceDocumentSN: run.sourceDocumentSN, + taskMode: run.taskMode, + aiDecision: aiDecisionStr, + aiAction, + eHumanAction, + eHumanComment, + auditDrift, + auditDriftReason, + operator + }); + } + + return result; +} diff --git a/src/domains/hose/index.ts b/src/domains/hose/index.ts new file mode 100644 index 0000000..af1db81 --- /dev/null +++ b/src/domains/hose/index.ts @@ -0,0 +1,7 @@ +export * from "./types.js"; +export * from "./client.js"; +export * from "./api.js"; +export * from "./flow.js"; + +export * as hoseOpen from "./open/index.js"; +export * as hoseClose from "./close/index.js"; diff --git a/src/domains/hose/open/api.ts b/src/domains/hose/open/api.ts new file mode 100644 index 0000000..70e30d5 --- /dev/null +++ b/src/domains/hose/open/api.ts @@ -0,0 +1,179 @@ +import type { KyInstance } from "ky"; +import { HTTPError } from "ky"; +import { + HoseOpenAllLogsResponseSchema, + HoseOpenFlowDetailsResponseSchema, + HoseOpenStaffResponseSchema, + HoseOpenVersionedResponseSchema, + type HoseOpenAllLogsItem, + type HoseOpenCompositeData, + type HoseOpenFlowDetailsValue, + type HoseOpenStaffItem, + type HoseOpenStaffQueryOptions, + type HoseOpenVersionedItem +} from "./types.js"; + +export async function fetchHoseOpenFlowDetails( + client: KyInstance, + flowId: string +): Promise { + try { + const response = await client + .get("api/openapi/v1.1/flowDetails", { + searchParams: { flowId } + }) + .json(); + const parsed = HoseOpenFlowDetailsResponseSchema.parse(response); + return parsed.value; + } catch (error) { + if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) { + return undefined; + } + throw error; + } +} + +export async function fetchHoseOpenAllLogs( + client: KyInstance, + flowId: string +): Promise { + try { + const response = await client + .get("api/openapi/v1.1/flowDetails/allLogs", { + searchParams: { flowId } + }) + .json(); + const parsed = HoseOpenAllLogsResponseSchema.parse(response); + return parsed.items; + } catch (error) { + if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) { + return []; + } + throw error; + } +} + +export interface FetchHoseOpenVersionedOptions { + pageNum?: number; + pageSize?: number; + convertFeeType?: boolean; +} + +export async function fetchHoseOpenVersioned( + client: KyInstance, + flowId: string, + options?: FetchHoseOpenVersionedOptions +): Promise { + try { + const response = await client + .get("api/openapi/v1/flow/versioned", { + searchParams: { + flow_id: flowId, + pageNum: options?.pageNum ?? 1, + pageSize: options?.pageSize ?? 20, + convertFeeType: options?.convertFeeType ?? true + } + }) + .json(); + const parsed = HoseOpenVersionedResponseSchema.parse(response); + return parsed.items; + } catch (error) { + if (error instanceof HTTPError && (error.response.status === 404 || error.response.status === 412)) { + return []; + } + throw error; + } +} + +export async function fetchHoseOpenStaffs( + client: KyInstance, + options: HoseOpenStaffQueryOptions +): Promise { + if (!options.conditionIds || options.conditionIds.length === 0) { + return []; + } + try { + const response = await client + .post("api/openapi/v1/staffs/getStaffIds", { + json: { + type: options.type, + conditionIds: options.conditionIds.slice(0, 100) + } + }) + .json(); + const parsed = HoseOpenStaffResponseSchema.parse(response); + return parsed.items; + } catch (error) { + if (options.conditionIds.length > 1) { + const items: HoseOpenStaffItem[] = []; + for (const id of options.conditionIds) { + try { + const res = await client + .post("api/openapi/v1/staffs/getStaffIds", { + json: { type: options.type, conditionIds: [id] } + }) + .json(); + const p = HoseOpenStaffResponseSchema.parse(res); + items.push(...p.items); + } catch { + // Gracefully continue on individual failure + } + } + return items; + } + return []; + } +} + +export async function fetchHoseOpenCompositeFlow( + client: KyInstance, + flowId: string, + staffCache?: Map +): Promise { + const [flowDetails, allLogs, versions] = await Promise.all([ + fetchHoseOpenFlowDetails(client, flowId), + fetchHoseOpenAllLogs(client, flowId).catch(() => []), + fetchHoseOpenVersioned(client, flowId).catch(() => []) + ]); + + const staffMap = staffCache ?? new Map(); + const missingStaffIds: string[] = []; + + const addId = (id?: string | null) => { + if (id && typeof id === "string" && id !== "ebot" && !staffMap.has(id)) { + missingStaffIds.push(id); + } + }; + + for (const item of allLogs) { + addId(item.ownerId); + } + for (const log of flowDetails?.logs || []) { + addId(log.operatorId); + addId(log.nextOperatorId); + } + + const uniqueIds = [...new Set(missingStaffIds)]; + if (uniqueIds.length > 0) { + try { + const staffs = await fetchHoseOpenStaffs(client, { + type: "STAFFID", + conditionIds: uniqueIds + }); + for (const s of staffs) { + if (s.id) staffMap.set(s.id, s); + if (s.cellphone) staffMap.set(s.cellphone, s); + } + } catch { + // Gracefully continue if staff lookup fails + } + } + + return { + flowDetails, + allLogs, + versions, + staffMap + }; +} + diff --git a/src/domains/hose/open/client.ts b/src/domains/hose/open/client.ts new file mode 100644 index 0000000..650468d --- /dev/null +++ b/src/domains/hose/open/client.ts @@ -0,0 +1,55 @@ +import ky, { HTTPError, type KyInstance } from "ky"; +import { ensureHoseOpenapiToken, normalizeBaseUrl } from "../../../core/auth/hose.js"; +import type { CorpConfig } from "../../../core/config/types.js"; + +export interface HoseOpenClientCredentials { + domain?: string; + accessToken: string; +} + +export function createHoseOpenClientWithCredentials( + credentials: HoseOpenClientCredentials, + customHeaders?: Record +): KyInstance { + const baseUrl = normalizeBaseUrl(credentials.domain || "https://app.ekuaibao.com"); + return ky.create({ + prefix: baseUrl, + timeout: 30000, + searchParams: { + accessToken: credentials.accessToken + }, + headers: { + ...customHeaders + }, + hooks: { + beforeError: [ + async ({ error }) => { + const body = + error instanceof HTTPError + ? await error.response.text().catch(() => "") + : ""; + error.message = `${error.message}${body ? `: ${body}` : ""}`; + return error; + } + ] + } + }); +} + +export async function createHoseOpenClient( + corp: CorpConfig, + customHeaders?: Record +): Promise { + if (corp.source.type !== "hose") { + throw new Error(`Unsupported Hose source type: ${corp.source.type}. Expected 'hose'.`); + } + + const token = await ensureHoseOpenapiToken(corp); + return createHoseOpenClientWithCredentials( + { + domain: corp.source.domain, + accessToken: token + }, + customHeaders + ); +} diff --git a/src/domains/hose/open/index.ts b/src/domains/hose/open/index.ts new file mode 100644 index 0000000..498d3bc --- /dev/null +++ b/src/domains/hose/open/index.ts @@ -0,0 +1,3 @@ +export * from "./types.js"; +export * from "./client.js"; +export * from "./api.js"; diff --git a/src/domains/hose/open/types.ts b/src/domains/hose/open/types.ts new file mode 100644 index 0000000..d221dce --- /dev/null +++ b/src/domains/hose/open/types.ts @@ -0,0 +1,173 @@ +import { z } from "zod"; + +const nullableString = z.preprocess((v) => (v === null ? undefined : v), z.string().optional()); +const nullableBoolean = z.preprocess((v) => (v === null ? undefined : v), z.boolean().optional()); +const nullableNumber = z.preprocess((v) => (v === null ? undefined : v), z.number().optional()); + +// --- Hose OpenAPI: flowDetails --- + +export const HoseOpenFlowLogAttributeSchema = z + .object({ + nodeId: nullableString, + nodeName: nullableString, + nextId: nullableString, + nextName: nullableString, + comment: nullableString, + isUrgent: nullableBoolean, + isEbotNode: nullableBoolean, + isAuto: nullableBoolean, + isSkip: nullableBoolean, + skipped: nullableBoolean, + counterSign: nullableBoolean, + nextCounterSign: nullableBoolean, + complete: nullableBoolean + }) + .passthrough(); +export type HoseOpenFlowLogAttribute = z.infer; + +export const HoseOpenFlowLogSchema = z + .object({ + id: nullableString, + action: nullableString, + state: nullableString, + operatorId: nullableString, + nextOperatorId: nullableString, + nextOperatorIds: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(z.string())).default([]), + time: nullableNumber, + attributes: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFlowLogAttributeSchema.optional()) + }) + .passthrough(); +export type HoseOpenFlowLog = z.infer; + +export const HoseOpenFormDetailSchema = z + .object({ + code: nullableString, + title: nullableString, + submitterId: nullableString, + submitDate: nullableNumber, + expenseDate: nullableNumber, + rejectionNum: z.preprocess((v) => (v === null ? undefined : v), z.union([z.number(), z.string()]).optional()), + reviewStatus: nullableString, + specificationId: nullableString, + payMoney: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.unknown()).optional()), + expenseMoney: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.unknown()).optional()), + details: z.preprocess((v) => (v === null ? undefined : v), z.array(z.record(z.string(), z.unknown())).optional()) + }) + .passthrough(); +export type HoseOpenFormDetail = z.infer; + +export const HoseOpenFlowDetailsValueSchema = z + .object({ + id: z.string(), + version: nullableNumber, + state: nullableString, + flowType: nullableString, + formType: nullableString, + ownerId: nullableString, + createTime: nullableNumber, + updateTime: nullableNumber, + form: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFormDetailSchema.optional()), + logs: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenFlowLogSchema)).default([]), + actions: z.preprocess((v) => (v === null ? undefined : v), z.record(z.string(), z.array(z.string())).optional()) + }) + .passthrough(); +export type HoseOpenFlowDetailsValue = z.infer; + +export const HoseOpenFlowDetailsResponseSchema = z + .object({ + value: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFlowDetailsValueSchema.optional()) + }) + .passthrough(); +export type HoseOpenFlowDetailsResponse = z.infer; + +// --- Hose OpenAPI: flowDetails/allLogs --- + +export const HoseOpenAllLogsItemSchema = z + .object({ + id: z.string(), + flowId: nullableString, + nodeId: nullableString, + nodeName: nullableString, + ownerId: nullableString, + state: nullableString, + logId: nullableNumber, + action: nullableString, + createTime: nullableNumber, + updateTime: nullableNumber, + isUrgent: nullableBoolean + }) + .passthrough(); +export type HoseOpenAllLogsItem = z.infer; + +export const HoseOpenAllLogsResponseSchema = z + .object({ + count: z.preprocess((v) => (typeof v === "number" ? v : 0), z.number()).default(0), + items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenAllLogsItemSchema)).default([]) + }) + .passthrough(); +export type HoseOpenAllLogsResponse = z.infer; + +// --- Hose OpenAPI: flow/versioned --- + +export const HoseOpenVersionedItemSchema = z + .object({ + id: nullableString, + flowId: nullableString, + version: nullableNumber, + state: nullableString, + createTime: nullableNumber, + updateTime: nullableNumber, + form: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFormDetailSchema.optional()), + logs: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenFlowLogSchema)).default([]), + modifyFlowLog: z.preprocess((v) => (Array.isArray(v) ? v : undefined), z.array(z.record(z.string(), z.unknown())).optional()) + }) + .passthrough(); +export type HoseOpenVersionedItem = z.infer; + +export const HoseOpenVersionedResponseSchema = z + .object({ + count: z.preprocess((v) => (typeof v === "number" ? v : 0), z.number()).default(0), + items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenVersionedItemSchema)).default([]) + }) + .passthrough(); +export type HoseOpenVersionedResponse = z.infer; + +// --- Hose OpenAPI Composite Result --- + +export interface HoseOpenCompositeData { + flowDetails?: HoseOpenFlowDetailsValue; + allLogs: HoseOpenAllLogsItem[]; + versions: HoseOpenVersionedItem[]; + staffMap?: Map; +} + +// --- Hose OpenAPI: staffs/getStaffIds --- + +export const HoseOpenStaffItemSchema = z + .object({ + id: z.string(), + name: nullableString, + enName: nullableString, + nickName: nullableString, + code: nullableString, + cellphone: nullableString, + email: nullableString, + active: nullableBoolean, + userId: nullableString, + defaultDepartment: nullableString + }) + .passthrough(); +export type HoseOpenStaffItem = z.infer; + +export const HoseOpenStaffResponseSchema = z + .object({ + items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenStaffItemSchema)).default([]) + }) + .passthrough(); +export type HoseOpenStaffResponse = z.infer; + +export interface HoseOpenStaffQueryOptions { + type: "STAFFID" | "CODE" | "CELLPHONE" | "MAIL" | "USERID"; + conditionIds: string[]; +} + diff --git a/src/domains/hose/types.ts b/src/domains/hose/types.ts new file mode 100644 index 0000000..f0e5923 --- /dev/null +++ b/src/domains/hose/types.ts @@ -0,0 +1,157 @@ +import { z } from "zod"; + +export const HOSE_FLOW_ACTION_LABELS: Record = { + "freeflow.submit": "提交送审", + "freeflow.agree": "审批同意", + "freeflow.autoAgree": "自动同意", + "freeflow.reject": "审批驳回", + "freeflow.print": "打印单据", + "freeflow.retract": "单据撤回", + "freeflow.addnode": "加签/转交", + "freeflow.comment": "发表评论" +}; + +export const HOSE_FLOW_STATE_LABELS: Record = { + APPROVING: "审批中", + APPROVED: "审批通过", + REJECTED: "审批驳回", + REVOKED: "已撤回", + CANCELED: "已取消", + CANCELLED: "已取消", + SKIPPED: "已跳过", + SUBMITTED: "已提交", + PENDING: "待审批", + WAITING: "待处理", + COMPLETED: "已完成", + DRAFT: "草稿" +}; + +export const FlowPersonSchema = z.object({ + id: z.string().optional(), + name: z.string().optional(), + code: z.string().optional() +}); +export type FlowPerson = z.infer; + +export const HoseFlowTimelineEntrySchema = z.object({ + id: z.string().optional(), + time: z.number().optional(), + durationMs: z.number().optional(), + state: z.string().optional(), + rawState: z.string().optional(), + action: z.string().optional(), + rawAction: z.string().optional(), + nodeName: z.string().optional(), + comment: z.string().optional(), + rawComment: z.string().optional(), + automatic: z.boolean().default(false), + isEbot: z.boolean().default(false), + skipped: z.boolean().default(false), + operator: FlowPersonSchema.optional(), + nextOperators: z.array(FlowPersonSchema).default([]) +}); +export type HoseFlowTimelineEntry = z.infer; + +export const HoseFlowPendingNodeSchema = z.object({ + id: z.string().optional(), + name: z.string().optional(), + type: z.string().optional(), + state: z.enum(["当前", "后续", "已完成"]).default("后续"), + isCurrent: z.boolean().default(false), + approver: FlowPersonSchema.optional(), + approvers: z.array(FlowPersonSchema).default([]) +}); +export type HoseFlowPendingNode = z.infer; + +export const HoseFlowMetricsSchema = z.object({ + rejectionNum: z.number().int().nonnegative().default(0), + submitCount: z.number().int().positive().default(1), + sourceFlowVersion: z.union([z.string(), z.number()]).optional(), + isModifiedAfterReject: z.boolean().default(false), + retractCount: z.number().int().nonnegative().default(0), + isResubmittedAfterRetract: z.boolean().default(false) +}); +export type HoseFlowMetrics = z.infer; + +export const HoseStaffOpinionSchema = z.object({ + nodeName: z.string().optional(), + operator: FlowPersonSchema.optional(), + action: z.string().optional(), + rawAction: z.string().optional(), + time: z.number().optional(), + comment: z.string(), + isEbot: z.boolean().default(false) +}); +export type HoseStaffOpinion = z.infer; + +export const HoseRejectionDetailSchema = z.object({ + time: z.number().optional(), + nodeName: z.string().optional(), + operator: FlowPersonSchema.optional(), + isEbot: z.boolean().default(false), + reason: z.string(), + rawComment: z.string().optional() +}); +export type HoseRejectionDetail = z.infer; + +export const HoseFlowDetailSchema = z.object({ + backlogId: z.string(), + flowId: z.string().optional(), + billCode: z.string().optional(), + title: z.string().optional(), + state: z.string().optional(), + rawState: z.string().optional(), + currentNode: z.string().optional(), + specification: z.object({ + id: z.string().optional(), + name: z.string().optional(), + code: z.string().optional() + }).optional(), + submitter: FlowPersonSchema.optional(), + owner: FlowPersonSchema.optional(), + submitDate: z.number().optional(), + updateTime: z.number().optional(), + history: z.array(HoseFlowTimelineEntrySchema), + pending: z.array(HoseFlowPendingNodeSchema), + metrics: HoseFlowMetricsSchema, + staffOpinions: z.array(HoseStaffOpinionSchema), + rejections: z.array(HoseRejectionDetailSchema), + raw: z.record(z.string(), z.unknown()).optional() +}); +export type HoseFlowDetail = z.infer; + +export const RawHoseBacklogItemSchema = z.object({ + id: z.string(), + state: z.string().optional(), + nodeName: z.string().optional(), + flowId: z.record(z.string(), z.unknown()).optional(), + nodeState: z.record(z.string(), z.unknown()).optional() +}).passthrough(); +export type RawHoseBacklogItem = z.infer; + +export const RawHoseBacklogSearchResponseSchema = z.object({ + count: z.number().optional(), + items: z.array(z.record(z.string(), z.unknown())).default([]) +}).passthrough(); +export type RawHoseBacklogSearchResponse = z.infer; + +export const RawHoseBacklogDetailResponseSchema = z.object({ + value: z.record(z.string(), z.unknown()).optional(), + items: z.array(z.record(z.string(), z.unknown())).optional() +}).passthrough(); +export type RawHoseBacklogDetailResponse = z.infer; + +export const HoseRunAlignmentSchema = z.object({ + recordId: z.string(), + sourceDocumentSN: z.string().optional(), + taskMode: z.string().optional(), + aiDecision: z.string().optional(), + aiAction: z.string().optional(), + eHumanAction: z.string(), + eHumanComment: z.string(), + auditDrift: z.boolean().default(false), + auditDriftReason: z.string().optional(), + operator: FlowPersonSchema.optional() +}); +export type HoseRunAlignment = z.infer; + diff --git a/src/domains/seal/approval-runs-export.test.ts b/src/domains/seal/approval-runs-export.test.ts index a7ccc8e..cf9a47a 100644 --- a/src/domains/seal/approval-runs-export.test.ts +++ b/src/domains/seal/approval-runs-export.test.ts @@ -273,11 +273,22 @@ describe("exportApprovalRunsToExcel integration", () => { const ws = wb.worksheets[0]!; expect(ws.rowCount).toBe(3); // 1 header + 2 rows expect(ws.getRow(1).getCell(1).value).toBe("单据编号"); + expect(ws.getRow(1).getCell(9).value).toBe("人工审核"); + expect(ws.getRow(1).getCell(10).value).toBe("人工驳回原因"); + expect(ws.getRow(1).getCell(11).value).toBe("E人工行为"); + expect(ws.getRow(1).getCell(12).value).toBe("E人工意见"); + expect(ws.getRow(2).getCell(1).value).toBe("B26001"); expect(ws.getRow(2).getCell(9).value).toBe("已支付/审批完成"); + expect(ws.getRow(2).getCell(10).value).toBe("-"); + expect(ws.getRow(2).getCell(11).value).toBe("-"); + expect(ws.getRow(2).getCell(12).value).toBe("-"); + expect(ws.getRow(3).getCell(1).value).toBe("B26002"); expect(ws.getRow(3).getCell(9).value).toBe("被驳回"); expect(ws.getRow(3).getCell(10).value).toBe("请上传正确的行程单凭据"); + expect(ws.getRow(3).getCell(11).value).toBe("-"); + expect(ws.getRow(3).getCell(12).value).toBe("-"); } finally { if (existsSync(tmpOut)) { rmSync(tmpOut, { force: true }); @@ -304,4 +315,66 @@ describe("exportApprovalRunsToExcel integration", () => { }) ).rejects.toThrow("起始时间 (2026-09-15) 不能晚于结束时间 (2026-09-13)"); }); + + test("automatically excludes simulation tasks and records excludedSimulationCount", async () => { + const mockClient = { + get: (url: string) => { + if (url.includes("api/v1/rules")) { + return { json: async () => ({ rules: [] }) }; + } + if (url.includes("api/v1/approvals")) { + return { + json: async () => ({ + total: 3, + records: [ + { + id: "run-sim-1", + sourceDocumentSN: "SIM001", + status: "completed", + taskMode: "simulation", + createdAt: 1788760000000 + }, + { + id: "run-real-1", + sourceDocumentSN: "REAL001", + status: "completed", + taskMode: "assisted", + createdAt: 1788760010000 + }, + { + id: "run-sim-2", + sourceDocumentSN: "SIM002", + status: "completed", + taskMode: "simulation", + createdAt: 1788760020000 + } + ] + }) + }; + } + throw new Error(`Unexpected url: ${url}`); + } + } as any; + + const tmpOut = join(tmpdir(), `test-export-sim-${Date.now()}.xlsx`); + try { + const result = await exportApprovalRunsToExcel(mockClient, testCorp, { + outputFile: tmpOut, + pageDelayMs: 0 + }); + + expect(result.recordCount).toBe(1); + expect(result.excludedSimulationCount).toBe(2); + + const wb = new ExcelJS.Workbook(); + await wb.xlsx.readFile(tmpOut); + const ws = wb.worksheets[0]!; + expect(ws.rowCount).toBe(2); // 1 header + 1 real row + expect(ws.getRow(2).getCell(1).value).toBe("REAL001"); + } finally { + if (existsSync(tmpOut)) { + rmSync(tmpOut, { force: true }); + } + } + }); }); diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index f2c7aa9..05c804b 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -5,6 +5,13 @@ import ExcelJS from "exceljs"; import type { KyInstance } from "ky"; import type { CorpConfig } from "../../core/config/types.js"; import * as api from "./api.js"; +import { + alignApprovalRunsWithHoseFlow, + createHoseOpenClient, + getHoseOpenFlow, + type HoseOpenStaffItem, + type HoseRunAlignment +} from "../hose/index.js"; import type { ApprovalRun, ApprovalRunListData } from "./types.js"; export interface ApprovalRunsExportOptions { @@ -19,6 +26,12 @@ export interface ApprovalRunsExportOptions { pageSize?: number; pageDelayMs?: number; force?: boolean; + withFlow?: boolean; + flowConcurrency?: number; + flowBatchDelayMs?: number; + excludeDeleted?: boolean; + taskMode?: string; + sourceSystem?: string; } export interface ApprovalRunsExportResult { @@ -31,6 +44,9 @@ export interface ApprovalRunsExportResult { rejectReasonCount: number; fileSizeBytes: number; exportedAt: string; + driftCount?: number; + excludedDeletedCount?: number; + excludedSimulationCount?: number; } export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined { @@ -331,10 +347,37 @@ export async function exportApprovalRunsToExcel( console.error(`已就绪 ${sortedRuleKeys.length} 个规则列。开始拉取单据...`); + // 1.5 如果是合思企业且开启审批流对齐,先探测单据规模并做耗时与频控提示 + if (options.withFlow !== false && corp.source.type === "hose") { + try { + const probeData = await api.listApprovalRuns(client, { + limit: 1, + startDate: startDateTs, + endDate: endDateTs, + status: options.status, + sourceSystem: options.sourceSystem, + taskMode: options.taskMode, + manualApprovalStatus: manualStatusFilter + }); + const probeTotal = probeData.total ?? probeData.records?.length ?? 0; + const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5)); + const estSeconds = Math.max(1, Math.ceil((probeTotal / concurrency) * 0.4)); + if (probeTotal > 50) { + console.error( + `⚠️ [审批流对齐提示] 目标区间内单据规模约为 ${probeTotal} 笔。系统已启用合思 Open API 保护限流(并发 ${concurrency}),预计审批流拉取耗时约 ${estSeconds} 秒。若无需原生人工流转行为与意见,可追加 --no-flow 快速导出。` + ); + } + } catch { + // ignore probe error + } + } + // 2. 温和分页拉取单据记录 const fetchedRecords: ApprovalRun[] = []; let offset = 0; let totalAvailable = 0; + let excludedSimulationCount = 0; + let excludedOtherSourceCount = 0; while (fetchedRecords.length < limit) { let batch: ApprovalRunListData | undefined; @@ -348,6 +391,8 @@ export async function exportApprovalRunsToExcel( startDate: startDateTs, endDate: endDateTs, status: options.status, + sourceSystem: options.sourceSystem, + taskMode: options.taskMode, manualApprovalStatus: manualStatusFilter }); break; @@ -363,6 +408,22 @@ export async function exportApprovalRunsToExcel( totalAvailable = batch.total ?? totalAvailable; for (const r of batch.records) { + // 过滤测试任务(仅保留真实审批任务) + if (r.taskMode === "simulation") { + excludedSimulationCount++; + continue; + } + + if (options.taskMode && r.taskMode !== options.taskMode) { + continue; + } + + // 如果企业是合思来源,仅拉取合思来源单据 + if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) { + excludedOtherSourceCount++; + continue; + } + if (options.includeCompletedOnly && r.status !== "completed") { continue; } @@ -399,6 +460,17 @@ export async function exportApprovalRunsToExcel( } } + if (excludedSimulationCount > 0) { + console.error( + `ℹ️ 已自动排除 ${excludedSimulationCount} 条模拟测试任务 (taskMode="simulation"),仅保留真实审批任务。` + ); + } + if (excludedOtherSourceCount > 0) { + console.error( + `ℹ️ 已自动排除 ${excludedOtherSourceCount} 条非合思来源单据,仅保留合思业务单据。` + ); + } + console.error(`成功拉取 ${fetchedRecords.length} 条单据数据,正在生成高保真 Excel...`); // 3. 构建 Excel 工作簿 @@ -421,6 +493,8 @@ export async function exportApprovalRunsToExcel( { header: "思考深度", key: "thinkingDepth", width: 12 }, { header: "人工审核", key: "manualStatus", width: 16 }, { header: "人工驳回原因", key: "humanRejectReason", width: 36 }, + { header: "E人工行为", key: "eHumanAction", width: 18 }, + { header: "E人工意见", key: "eHumanComment", width: 36 }, { header: "创建时间", key: "createdAt", width: 20 }, { header: "任务耗时", key: "duration", width: 12 }, { header: "关联规则数", key: "hitRuleCount", width: 12 }, @@ -464,9 +538,104 @@ export async function exportApprovalRunsToExcel( const statusCounts: Record = {}; let rejectReasonCount = 0; + let driftCount = 0; + + // 3.5 如果是合思租户且未显式关闭 withFlow,获取原生审批流并对齐真实人工行为与意见 + const alignmentsByRecordId = new Map(); + const deletedSNs = new Set(); + const excludeDeleted = options.excludeDeleted ?? true; + + if (options.withFlow !== false && corp.source.type === "hose") { + try { + const runsByDocKey = new Map(); + for (const record of fetchedRecords) { + const docKey = record.sourceDocumentId || record.sourceDocumentSN; + if (docKey) { + const list = runsByDocKey.get(docKey) || []; + list.push(record); + runsByDocKey.set(docKey, list); + } + } + + const uniqueDocKeys = Array.from(runsByDocKey.keys()); + if (uniqueDocKeys.length > 0) { + const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5)); + const batchDelayMs = options.flowBatchDelayMs ?? 150; + const estSeconds = Math.max(1, Math.ceil((uniqueDocKeys.length / concurrency) * (0.25 + batchDelayMs / 1000))); + + console.error( + `正在拉取合思原生审批流以对齐人工行为与意见 (共 ${uniqueDocKeys.length} 个单据,并发限制: ${concurrency},批次间隔: ${batchDelayMs}ms,预计耗时约 ${estSeconds}s)...` + ); + const openClient = await createHoseOpenClient(corp); + const staffCache = new Map(); + for (let i = 0; i < uniqueDocKeys.length; i += concurrency) { + const batchKeys = uniqueDocKeys.slice(i, i + concurrency); + await Promise.all( + batchKeys.map(async (docKey) => { + const runsForDoc = runsByDocKey.get(docKey)!; + const displaySN = runsForDoc[0]?.sourceDocumentSN || docKey; + try { + const flow = await getHoseOpenFlow(openClient, docKey, staffCache); + if (!flow) { + deletedSNs.add(displaySN); + const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined); + for (const [recordId, align] of aligned.entries()) { + align.eHumanAction = "单据已删除"; + align.eHumanComment = "合思系统中未找到该单据流转记录(可能已在合思端删除或作废)"; + alignmentsByRecordId.set(recordId, align); + } + return; + } + const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, flow); + for (const [recordId, align] of aligned.entries()) { + alignmentsByRecordId.set(recordId, align); + if (align.auditDrift) driftCount++; + } + } catch (err: any) { + console.error(`⚠️ 拉取单据 ${displaySN} 审批流失败: ${err.message},使用降级对齐。`); + const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined); + for (const [recordId, align] of aligned.entries()) { + alignmentsByRecordId.set(recordId, align); + } + } + }) + ); + + if (batchDelayMs > 0 && i + concurrency < uniqueDocKeys.length) { + await new Promise((r) => setTimeout(r, batchDelayMs)); + } + + if ((i + concurrency) % 20 < concurrency || i + concurrency >= uniqueDocKeys.length) { + const completed = Math.min(i + batchKeys.length, uniqueDocKeys.length); + const pct = Math.round((completed / uniqueDocKeys.length) * 100); + console.error(`[审批流进度] 已对齐: ${completed}/${uniqueDocKeys.length} (${pct}%)...`); + } + } + } + } catch (err: any) { + console.error(`⚠️ 对齐合思审批流失败: ${err.message},E人工行为与意见将使用默认值。`); + } + + if (deletedSNs.size > 0) { + console.error( + `ℹ️ 检测到 ${deletedSNs.size} 个单据在合思端已删除或不存在(如: ${Array.from(deletedSNs).slice(0, 3).join(", ")}...)${ + excludeDeleted ? ",已按要求自动排除。" : ",已在报表中标记为「单据已删除」。" + }` + ); + } + } + + let exportedRecordCount = 0; + let excludedDeletedCount = 0; // 填充数据行 for (const record of fetchedRecords) { + const sn = record.sourceDocumentSN || record.sourceDocumentId; + if (excludeDeleted && sn && deletedSNs.has(sn)) { + excludedDeletedCount++; + continue; + } + exportedRecordCount++; const res = (record.result as any) || {}; const doc = (record.document as any) || {}; @@ -575,6 +744,10 @@ export async function exportApprovalRunsToExcel( createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false }); } + const align = alignmentsByRecordId.get(record.id); + const eHumanAction = align ? align.eHumanAction : "-"; + const eHumanComment = align ? align.eHumanComment : "-"; + const rowData: Record = { sn: record.sourceDocumentSN || record.sourceDocumentId || "-", templateName, @@ -586,6 +759,8 @@ export async function exportApprovalRunsToExcel( thinkingDepth: "标准", manualStatus, humanRejectReason, + eHumanAction, + eHumanComment, createdAt: createdAtStr, duration: durationStr, hitRuleCount: hitRuleIds.length, @@ -621,8 +796,8 @@ export async function exportApprovalRunsToExcel( if (colNumber <= baseColumns.length) { cell.alignment = { vertical: "middle", - horizontal: [1, 2, 10, 14, 15].includes(colNumber) ? "left" : "center", - wrapText: [10, 14, 15].includes(colNumber) + horizontal: [1, 2, 10, 12, 16, 17].includes(colNumber) ? "left" : "center", + wrapText: [10, 12, 16, 17].includes(colNumber) }; // AI 决策颜色区分 @@ -650,6 +825,30 @@ export async function exportApprovalRunsToExcel( if (colNumber === 10 && val !== "-") { cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF991B1B" } }; } + + // E人工行为高亮 + if (colNumber === 11) { + if (val.includes("⚠️") || val.includes("修改")) { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFD97706" }, bold: true }; + cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } }; + } else if (val.includes("驳回")) { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true }; + cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } }; + } else if (val.includes("通过")) { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF16A34A" }, bold: true }; + cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } }; + } else if (val.includes("待处理") || val.includes("处理中") || val.includes("审核中")) { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" } }; + cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } }; + } else if (val === "无操作") { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF94A3B8" } }; + } + } + + // E人工意见字体 + if (colNumber === 12 && val !== "-") { + cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF334155" } }; + } } else { cell.alignment = { vertical: "middle", horizontal: "center" }; if (val.includes("不通过")) { @@ -676,7 +875,7 @@ export async function exportApprovalRunsToExcel( toDownloads: options.toDownloads, corpName, dateTag, - recordCount: fetchedRecords.length + recordCount: exportedRecordCount }); await workbook.xlsx.writeFile(targetPath); @@ -688,11 +887,14 @@ export async function exportApprovalRunsToExcel( filePath: targetPath, corpId: corp.id, corpName, - recordCount: fetchedRecords.length, + recordCount: exportedRecordCount, ruleColumnCount: sortedRuleKeys.length, statusCounts, rejectReasonCount, fileSizeBytes: stat.size, - exportedAt: new Date().toISOString() + exportedAt: new Date().toISOString(), + driftCount, + excludedDeletedCount, + excludedSimulationCount }; } diff --git a/src/domains/seal/tools.ts b/src/domains/seal/tools.ts index 5d25e6a..2199db4 100644 --- a/src/domains/seal/tools.ts +++ b/src/domains/seal/tools.ts @@ -29,6 +29,11 @@ import { extractApprovalRunAttachments } from "./attachments.js"; import { exportApprovalRunsToExcel, normalizeTimestamp } from "./approval-runs-export.js"; +import { + alignApprovalRunsWithHoseFlow, + createHoseOpenClient, + getHoseOpenFlow +} from "../hose/index.js"; import { exportInsightReportToExcel, type InsightExportOptions } from "./insight-export.js"; import { ThinkingPolicySchema, @@ -1521,6 +1526,155 @@ export const sealTools = [ return fields.length > 0 ? pickRunFields(full, fields) : full; } }, + { + name: "seal_approval_run_flow_get", + description: "获取合思原生审批流流转时间线、待办节点、员工意见、驳回原因及版本变更指标,并对齐 AI 运行记录与人工行为", + parameters: z.object({ + target: z.string().optional().describe("合思单号 (sourceDocumentSN) 或 Seal 运行记录 ID (recordId)"), + recordId: z.string().optional().describe("Seal 运行记录 ID"), + sourceDocumentSN: z.string().optional().describe("合思单号 (sourceDocumentSN)") + }), + handler: async ( + client: KyInstance, + params: { target?: string; recordId?: string; sourceDocumentSN?: string }, + context: ToolContext + ) => { + const corp = context.corp; + if (corp.source.type !== "hose") { + throw new Error( + `企业「${corp.name || corp.id}」非合思(hose)租户(来源类型: ${corp.source.type}),暂不支持合思原生审批流分析。` + ); + } + + const input = (params.target || params.sourceDocumentSN || params.recordId)?.trim(); + if (!input) { + throw new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。"); + } + + let sn = input; + let targetRecord: ApprovalRun | undefined; + + try { + targetRecord = await api.getApprovalRun(client, input); + if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) { + sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!; + } + } catch { + // Continue as SN + } + + let runs: ApprovalRun[] = []; + try { + const runsData = await api.listApprovalRuns(client, { + search: sn, + sourceDocumentSN: sn, + limit: 100 + }); + runs = (runsData.records || []).filter( + (r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input + ); + } catch { + // ignore + } + + if (runs.length === 0 && targetRecord) { + runs = [targetRecord]; + } + + const flowId = targetRecord?.sourceDocumentId || runs[0]?.sourceDocumentId || sn; + const hoseClient = await createHoseOpenClient(corp); + const flow = await getHoseOpenFlow(hoseClient, flowId); + if (!flow) { + console.error(`⚠️ 单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`); + const fallbackAlignments = alignApprovalRunsWithHoseFlow(runs, undefined); + const fallbackRuns = runs.map((run) => { + const align = fallbackAlignments.get(run.id); + return { + recordId: run.id, + createdAt: run.createdAt, + createdAtFormatted: run.createdAt + ? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }) + : undefined, + taskMode: run.taskMode, + status: run.status, + aiDecision: align?.aiDecision || "-", + aiAction: align?.aiAction || "-", + eHumanAction: "单据已删除", + eHumanComment: "合思系统中未找到该单据流转记录(已在合思端删除或作废)", + auditDrift: false, + auditDriftReason: undefined, + operator: undefined + }; + }); + + return { + sourceDocumentSN: sn, + corpId: corp.id, + corpName: corp.name, + sourceSystem: corp.source.type, + found: false, + deleted: true, + message: `单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`, + flow: undefined, + runsCount: runs.length, + runs: fallbackRuns, + auditDrift: false + }; + } + + const alignments = alignApprovalRunsWithHoseFlow(runs, flow); + const alignedRuns = runs.map((run) => { + const align = alignments.get(run.id); + return { + recordId: run.id, + createdAt: run.createdAt, + createdAtFormatted: run.createdAt + ? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }) + : undefined, + taskMode: run.taskMode, + status: run.status, + aiDecision: align?.aiDecision || "-", + aiAction: align?.aiAction || "-", + eHumanAction: align?.eHumanAction || "-", + eHumanComment: align?.eHumanComment || "-", + auditDrift: align?.auditDrift ?? false, + auditDriftReason: align?.auditDriftReason, + operator: align?.operator + }; + }); + + const hasAuditDrift = alignedRuns.some((r) => r.auditDrift); + + return { + sourceDocumentSN: sn, + corpId: corp.id, + corpName: corp.name, + sourceSystem: corp.source.type, + flow: { + backlogId: flow.backlogId, + flowId: flow.flowId, + billCode: flow.billCode, + title: flow.title, + state: flow.state, + rawState: flow.rawState, + currentNode: flow.currentNode, + specification: flow.specification, + submitter: flow.submitter, + owner: flow.owner, + metrics: flow.metrics, + rejections: flow.rejections, + staffOpinions: flow.staffOpinions, + timelineCount: flow.history.length, + pendingCount: flow.pending.length, + timeline: flow.history, + pending: flow.pending + }, + runsCount: runs.length, + runs: alignedRuns, + auditDrift: hasAuditDrift + }; + } + }, { name: "seal_approval_run_cited_rules_get", description: "从审批运行结果中抽取 AI 引用或命中的规则及应用分析", From 1a2c41c70c41df4bbd193bfb853f5bdbf0045d60 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 17:24:27 +0800 Subject: [PATCH 02/19] Fix flow alignment for retracted runs and add cancel cell styling --- src/domains/hose/flow.test.ts | 55 ++++++ src/domains/hose/flow.ts | 203 ++++++++++++++++------- src/domains/seal/approval-runs-export.ts | 6 + 3 files changed, 205 insertions(+), 59 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 9c11976..08a3295 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -855,6 +855,61 @@ describe("Hose Flow Domain", () => { 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("上级主管(张舒):当前审核节点"); + expect(r2.auditDrift).toBe(false); + }); }); }); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index e962802..d14251d 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -712,6 +712,19 @@ export function alignApprovalRunsWithHoseFlow( else if (isReject) aiAction = isAutomatic ? "驳回" : "添加评论"; else if (normDecision === "REVIEW" || normDecision === "转交复核") aiAction = "转交复核"; + const doc = (run.document as Record | undefined) || {}; + const rawManual = + (doc.manualApprovalStatus as string | undefined) || + (res.manualApprovalStatus as string | undefined) || + ((run as Record).manualApprovalStatus as string | undefined); + const normManual = typeof rawManual === "string" ? rawManual.toUpperCase() : ""; + const isRunCancelledInSeal = + normManual === "CANCELLED" || + normManual === "CANCELED" || + normManual === "已取消" || + normManual === "已撤回" || + normManual === "REVOKED"; + // 5-second clock skew tolerance window [runTime - 5000, nextRunTime) const windowEvents = history.filter((e) => { const t = e.time ?? 0; @@ -725,6 +738,7 @@ export function alignApprovalRunsWithHoseFlow( let operator: FlowPerson | undefined; // Check for Post-AI Mutation / Audit Drift + const isAiApproved = isApprove || normDecision === "EXEMPT_APPROVE" || normDecision === "免审通过"; const postAiEvents = history.filter((e) => (e.time ?? 0) > runTime + 5000); const hasPostAiRetract = postAiEvents.some( (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" @@ -733,7 +747,7 @@ export function alignApprovalRunsWithHoseFlow( (e) => e.rawAction === "freeflow.submit" || e.action === "提交送审" ); - if (isLatestRun && (hasPostAiRetract || hasPostAiResubmit)) { + if (isAiApproved && isLatestRun && (hasPostAiRetract || hasPostAiResubmit)) { auditDrift = true; auditDriftReason = "AI通过后单据发生撤回/修改重提,后续未经AI复审"; } @@ -744,7 +758,7 @@ export function alignApprovalRunsWithHoseFlow( eHumanAction = "无操作"; eHumanComment = "-"; } else { - // Subsequent human events after current AI run + // Subsequent human events after current AI run in this run's window const subsequentHumanEvents = windowEvents.filter( (e) => (e.time ?? 0) >= runTime - 1000 && @@ -756,61 +770,132 @@ export function alignApprovalRunsWithHoseFlow( e.rawAction !== "freeflow.comment" ); + const retractEvent = subsequentHumanEvents.find( + (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" + ); const rejectEvent = subsequentHumanEvents.find( (e) => e.rawAction === "freeflow.reject" || e.action === "审批驳回" ); - const pendingNodes = flow.pending || []; - const currentPending = pendingNodes.find((p) => p.isCurrent) || pendingNodes[0]; + const isFlowRetractedOrCancelled = + flow.rawState === "DRAFT" || + flow.rawState === "REVOKED" || + flow.rawState === "CANCELED" || + flow.rawState === "CANCELLED" || + flow.state === "草稿" || + flow.state === "已撤回" || + flow.state === "已取消"; - if (!isFlowCompleted) { - // Flow is still approving / in progress - eHumanAction = auditDrift ? "审核中 (⚠️ AI通过后被修改重提)" : "审核中"; + const isFlowRejected = + flow.rawState === "REJECTED" || + flow.rawState === "TERMINATED" || + flow.state === "审批驳回" || + flow.state === "已驳回"; - const opinionLines: string[] = []; - for (const ev of subsequentHumanEvents) { - const opName = ev.operator?.name || ev.operator?.id || "未知"; - const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; - const comment = - ev.comment || - (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" - ? "同意" - : ev.action || "-"); - opinionLines.push(`${nodePrefix}: ${comment}`); - if (!operator) operator = ev.operator; - } - - if (currentPending) { - const pApprover = - currentPending.approver?.name || currentPending.approver?.id || "待定"; - const pNodeName = (currentPending.name || flow.currentNode || "").trim(); - const pPrefix = pNodeName ? `${pNodeName}(${pApprover})` : pApprover; - opinionLines.push(`${pPrefix}:当前审核节点`); - } else if (flow.currentNode?.trim()) { - opinionLines.push(`${flow.currentNode.trim()}:当前审核节点`); - } - - eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "当前审核节点"; - } else { - // Flow is completed - const hasRetract = subsequentHumanEvents.some( - (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" - ); - - if (auditDrift) { - eHumanAction = "通过 (⚠️ AI通过后被中途修改)"; + if (!isLatestRun) { + // Historical run that has been superseded by a newer run + if (retractEvent || isRunCancelledInSeal) { + eHumanAction = "已撤回"; + operator = retractEvent?.operator; + eHumanComment = + retractEvent?.comment || + (retractEvent ? `${retractEvent.operator?.name || "提交人"}: 单据撤回` : "单据已撤回/取消"); } else if (rejectEvent) { eHumanAction = "驳回"; - } else if (hasRetract) { - eHumanAction = "已撤回"; - } else { - eHumanAction = "通过"; - } - - if (rejectEvent) { - eHumanComment = rejectEvent.comment || "驳回"; operator = rejectEvent.operator; + eHumanComment = rejectEvent.comment || "驳回"; } else { + eHumanAction = "已修改重提"; + const opinionLines: string[] = []; + for (const ev of subsequentHumanEvents) { + const opName = ev.operator?.name || ev.operator?.id || "未知"; + const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; + const comment = + ev.comment || + (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" + ? "同意" + : ev.action || "-"); + opinionLines.push(`${nodePrefix}: ${comment}`); + if (!operator) operator = ev.operator; + } + eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "-"; + } + } else { + // Latest run for this document + if (isFlowCompleted) { + const hasRetract = subsequentHumanEvents.some( + (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" + ); + + if (auditDrift) { + eHumanAction = "通过 (⚠️ AI通过后被中途修改)"; + } else if (rejectEvent) { + eHumanAction = "驳回"; + } else if (hasRetract) { + eHumanAction = "已撤回"; + } else { + eHumanAction = "通过"; + } + + if (rejectEvent) { + eHumanComment = rejectEvent.comment || "驳回"; + operator = rejectEvent.operator; + } else { + const opinionLines: string[] = []; + for (const ev of subsequentHumanEvents) { + const opName = ev.operator?.name || ev.operator?.id || "未知"; + const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; + const comment = + ev.comment || + (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" + ? "同意" + : ev.action || "-"); + opinionLines.push(`${nodePrefix}: ${comment}`); + if (!operator) operator = ev.operator; + } + + if (opinionLines.length > 0) { + eHumanComment = opinionLines.join("\n"); + } else { + const lastHumanApproval = [...windowEvents] + .reverse() + .find( + (e) => + !e.isEbot && + (e.rawAction === "freeflow.agree" || e.action === "审批同意") + ); + eHumanComment = lastHumanApproval?.comment || "-"; + if (!operator) operator = lastHumanApproval?.operator; + } + } + } else if (isFlowRetractedOrCancelled || (retractEvent && !hasPostAiResubmit) || isRunCancelledInSeal) { + eHumanAction = "已撤回"; + operator = retractEvent?.operator; + const opinionLines: string[] = []; + for (const ev of subsequentHumanEvents) { + const opName = ev.operator?.name || ev.operator?.id || "未知"; + const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; + const comment = + ev.comment || + (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" + ? "同意" + : ev.action || "-"); + opinionLines.push(`${nodePrefix}: ${comment}`); + if (!operator) operator = ev.operator; + } + if (retractEvent && opinionLines.length === 0) { + opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); + } + eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "单据已撤回"; + } else if (isFlowRejected || rejectEvent) { + eHumanAction = "驳回"; + operator = rejectEvent?.operator; + const rej = flow.rejections?.[0]; + eHumanComment = rejectEvent?.comment || rej?.reason || rej?.nodeName || "审批驳回"; + } else { + // Flow is still actively approving + eHumanAction = auditDrift ? "审核中 (⚠️ AI通过后被修改重提)" : "审核中"; + const opinionLines: string[] = []; for (const ev of subsequentHumanEvents) { const opName = ev.operator?.name || ev.operator?.id || "未知"; @@ -824,19 +909,19 @@ export function alignApprovalRunsWithHoseFlow( if (!operator) operator = ev.operator; } - if (opinionLines.length > 0) { - eHumanComment = opinionLines.join("\n"); - } else { - const lastHumanApproval = [...windowEvents] - .reverse() - .find( - (e) => - !e.isEbot && - (e.rawAction === "freeflow.agree" || e.action === "审批同意") - ); - eHumanComment = lastHumanApproval?.comment || "-"; - if (!operator) operator = lastHumanApproval?.operator; + const pendingNodes = flow.pending || []; + const currentPending = pendingNodes.find((p) => p.isCurrent) || pendingNodes[0]; + if (currentPending) { + const pApprover = + currentPending.approver?.name || currentPending.approver?.id || "待定"; + const pNodeName = (currentPending.name || flow.currentNode || "").trim(); + const pPrefix = pNodeName ? `${pNodeName}(${pApprover})` : pApprover; + opinionLines.push(`${pPrefix}:当前审核节点`); + } else if (flow.currentNode?.trim()) { + opinionLines.push(`${flow.currentNode.trim()}:当前审核节点`); } + + eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "当前审核节点"; } } } diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index 05c804b..b595afe 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -818,6 +818,9 @@ export async function exportApprovalRunsToExcel( } else if (val.includes("处理中") || val.includes("审批中")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" } }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } }; + } else if (val.includes("取消") || val.includes("撤回")) { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF64748B" } }; + cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF1F5F9" } }; } } @@ -840,6 +843,9 @@ export async function exportApprovalRunsToExcel( } else if (val.includes("待处理") || val.includes("处理中") || val.includes("审核中")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" } }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } }; + } else if (val.includes("撤回") || val.includes("取消")) { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF64748B" } }; + cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFF1F5F9" } }; } else if (val === "无操作") { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF94A3B8" } }; } From d5f68ea2f3723c9a0b41a9bddfd4ec3029d8d4d8 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 17:27:05 +0800 Subject: [PATCH 03/19] =?UTF-8?q?Map=20EXEMPT=5FAPPROVE=20to=20=E5=A4=87?= =?UTF-8?q?=E6=B3=A8=E9=80=9A=E8=BF=87=20and=20ERROR=20to=20=E9=94=99?= =?UTF-8?q?=E8=AF=AF=20in=20AI=20decision=20column?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domains/hose/flow.ts | 8 ++++++-- src/domains/seal/approval-runs-export.ts | 18 +++++++++++++----- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index d14251d..751dcf1 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -698,6 +698,10 @@ export function alignApprovalRunsWithHoseFlow( const normDecision = aiDecisionStr.toUpperCase(); const isReject = normDecision === "REJECT" || normDecision === "驳回"; const isApprove = normDecision === "APPROVE" || normDecision === "通过"; + const isExemptApprove = + normDecision === "EXEMPT_APPROVE" || + normDecision === "免审通过" || + normDecision === "备注通过"; const taskMode = run.taskMode || run.finalExecutionMode || ""; const normMode = String(taskMode).toLowerCase(); @@ -708,7 +712,7 @@ export function alignApprovalRunsWithHoseFlow( taskMode === "fully_automatic"; let aiAction = "-"; - if (isApprove) aiAction = "添加评论"; + if (isApprove || isExemptApprove) aiAction = "添加评论"; else if (isReject) aiAction = isAutomatic ? "驳回" : "添加评论"; else if (normDecision === "REVIEW" || normDecision === "转交复核") aiAction = "转交复核"; @@ -738,7 +742,7 @@ export function alignApprovalRunsWithHoseFlow( let operator: FlowPerson | undefined; // Check for Post-AI Mutation / Audit Drift - const isAiApproved = isApprove || normDecision === "EXEMPT_APPROVE" || normDecision === "免审通过"; + const isAiApproved = isApprove || isExemptApprove; const postAiEvents = history.filter((e) => (e.time ?? 0) > runTime + 5000); const hasPostAiRetract = postAiEvents.some( (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index b595afe..8da92e9 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -670,17 +670,24 @@ export async function exportApprovalRunsToExcel( // 4. AI 决策与行为 const aiDecision = res.decision || (record as any).aiDecision || "-"; - let aiDecisionDesc = aiDecision; + const normAiDec = String(aiDecision).toUpperCase(); + let aiDecisionDesc = String(aiDecision); let aiAction = "-"; - if (aiDecision === "APPROVE") { + if (normAiDec === "APPROVE" || normAiDec === "通过") { aiDecisionDesc = "通过"; aiAction = "添加评论"; - } else if (aiDecision === "REVIEW") { + } else if (normAiDec === "EXEMPT_APPROVE" || normAiDec === "免审通过" || normAiDec === "备注通过") { + aiDecisionDesc = "备注通过"; + aiAction = "添加评论"; + } else if (normAiDec === "REVIEW" || normAiDec === "转交复核") { aiDecisionDesc = "转交复核"; aiAction = "转交复核"; - } else if (aiDecision === "REJECT") { + } else if (normAiDec === "REJECT" || normAiDec === "驳回") { aiDecisionDesc = "驳回"; aiAction = "驳回"; + } else if (normAiDec === "ERROR" || normAiDec === "错误") { + aiDecisionDesc = "错误"; + aiAction = "-"; } // 5. 耗时计算 @@ -802,9 +809,10 @@ export async function exportApprovalRunsToExcel( // AI 决策颜色区分 if (colNumber === 7) { - if (val === "通过") cell.font = { color: { argb: "FF16A34A" }, bold: true }; + if (val === "通过" || val === "备注通过") cell.font = { color: { argb: "FF16A34A" }, bold: true }; else if (val === "转交复核") cell.font = { color: { argb: "FFD97706" }, bold: true }; else if (val === "驳回") cell.font = { color: { argb: "FFDC2626" }, bold: true }; + else if (val === "错误" || val === "ERROR") cell.font = { color: { argb: "FFDC2626" }, bold: true }; } // 人工审核高亮 From 6c6b3034a017cbbf2c39b98f2a8fc66f2d7fd2aa Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 17:34:35 +0800 Subject: [PATCH 04/19] Support paid flow states, freeflow pay actions, and clean pending nodes --- src/domains/hose/flow.test.ts | 93 ++++++++++++++- src/domains/hose/flow.ts | 217 ++++++++++++++++++++++------------ src/domains/hose/types.ts | 10 +- 3 files changed, 239 insertions(+), 81 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 08a3295..3143037 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -18,7 +18,9 @@ import { getHoseFlow, getHoseOpenFlow, getHoseCloseFlow, - alignApprovalRunsWithHoseFlow + alignApprovalRunsWithHoseFlow, + formatAiDecision, + formatHumanOpinionLines } from "./flow.js"; import { searchCloseBacklogs, @@ -910,6 +912,93 @@ describe("Hose Flow Domain", () => { expect(r2.eHumanComment).toBe("上级主管(张舒):当前审核节点"); 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 + expect(r.eHumanComment).toContain("上级主管(张舒): 同意"); + expect(r.eHumanComment).toContain("财务助理(熊雪倩): 同意"); + expect(r.eHumanComment).toContain("部门主管(张舒): 自动同意"); + // 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("高思琦: 支付完成"); + // 4. freeflow.carbonCopy omitted + expect(r.eHumanComment).not.toContain("freeflow.carbonCopy"); + expect(r.eHumanComment).not.toContain("抄送通知"); + // 5. No pending node appended + expect(r.eHumanComment).not.toContain("当前审核节点"); + }); + }); + + 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("转交复核"); + }); }); }); - diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 751dcf1..86630b2 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -250,13 +250,24 @@ export function parseHoseOpenPending( allLogs: HoseOpenAllLogsItem[], staffMap?: Map ): HoseFlowPendingNode[] { - const pendingItems = allLogs.filter( - (item) => + const pendingItems = allLogs.filter((item) => { + const stateUpper = String(item.state || "").toUpperCase(); + if ( + stateUpper === "CANCELED" || + stateUpper === "CANCELLED" || + stateUpper === "PROCESSED" || + stateUpper === "COMPLETED" || + stateUpper === "PAID" + ) { + return false; + } + return ( item.logId === -1 || - item.state === "APPROVING" || - item.state === "PROCESSING" || - item.state === "PAYING" - ); + stateUpper === "APPROVING" || + stateUpper === "PROCESSING" || + stateUpper === "PAYING" + ); + }); return pendingItems.map((item, index) => { let approver = extractFlowPerson(item.ownerId); @@ -450,7 +461,19 @@ export function parseHoseOpenComposite( const form = (flowDetails.form || {}) as Record; const history = parseHoseTimeline(flowDetails.logs || [], staffMap); - const pending = parseHoseOpenPending(allLogs, staffMap); + const rawState = flowDetails.state; + const state = translateFlowState(rawState); + const rawStateUpper = String(rawState || "").toUpperCase(); + const isFlowInEndState = [ + "COMPLETED", + "APPROVED", + "PAID", + "REVOKED", + "CANCELED", + "CANCELLED", + "REJECTED" + ].includes(rawStateUpper); + const pending = isFlowInEndState ? [] : parseHoseOpenPending(allLogs, staffMap); const currentNode = pending.find((p) => p.isCurrent)?.name; const metrics = calculateFlowMetrics( @@ -462,9 +485,6 @@ export function parseHoseOpenComposite( const staffOpinions = extractStaffOpinions(history); const rejections = extractRejections(history); - const rawState = flowDetails.state; - const state = translateFlowState(rawState); - let specification: { id?: string; name?: string; code?: string } | undefined; if (form.specificationId && typeof form.specificationId === "object") { const specObj = form.specificationId as Record; @@ -542,11 +562,6 @@ export function parseHoseFlow( ? nodeState.nodeId : undefined; - const pending = parseHosePending(plan, currentNode, currentNodeId); - const metrics = calculateFlowMetrics(flow, history, raw); - const staffOpinions = extractStaffOpinions(history); - const rejections = extractRejections(history); - const rawState = typeof raw.state === "string" ? raw.state @@ -554,6 +569,20 @@ export function parseHoseFlow( ? flow.state : undefined; const state = translateFlowState(rawState); + const rawStateUpper = String(rawState || "").toUpperCase(); + const isFlowInEndState = [ + "COMPLETED", + "APPROVED", + "PAID", + "REVOKED", + "CANCELED", + "CANCELLED", + "REJECTED" + ].includes(rawStateUpper); + const pending = isFlowInEndState ? [] : parseHosePending(plan, currentNode, currentNodeId); + const metrics = calculateFlowMetrics(flow, history, raw); + const staffOpinions = extractStaffOpinions(history); + const rejections = extractRejections(history); const lastAttributes = history.at(-1)?.nodeName ?? @@ -648,6 +677,60 @@ export async function getHoseFlow( return getHoseOpenFlow(client, flowId, staffCache); } +export function formatAiDecision(decision?: string): string { + if (!decision) return "-"; + const norm = decision.toUpperCase(); + if (norm === "APPROVE" || norm === "通过") return "通过"; + if (norm === "EXEMPT_APPROVE" || norm === "免审通过" || norm === "备注通过") return "备注通过"; + if (norm === "REVIEW" || norm === "转交复核") return "转交复核"; + if (norm === "REJECT" || norm === "驳回") return "驳回"; + if (norm === "ERROR" || norm === "错误") return "错误"; + return decision; +} + +export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string[] { + const lines: string[] = []; + for (const ev of events) { + if ( + (ev.rawAction === "freeflow.carbonCopy" || + ev.rawAction === "freeflow.cc" || + ev.rawAction === "freeflow.print" || + ev.action === "打印提醒" || + ev.action === "抄送通知") && + !ev.comment + ) { + continue; + } + + const opName = ev.operator?.name || ev.operator?.id || "未知"; + const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; + let comment = ev.comment; + if (!comment) { + if (ev.rawAction === "freeflow.agree" || ev.action === "审批同意") { + comment = "同意"; + } else if (ev.rawAction === "freeflow.autoAgree") { + comment = "自动同意"; + } else if (ev.rawAction === "freeflow.pay" || ev.action === "支付完成") { + comment = "支付完成"; + } else if (ev.rawAction === "freeflow.paying" || ev.action === "支付中") { + comment = "支付中"; + } else if (ev.rawAction === "freeflow.reject" || ev.action === "审批驳回") { + comment = "驳回"; + } else if (ev.rawAction === "freeflow.retract" || ev.action === "单据撤回") { + comment = "单据撤回"; + } else { + comment = ev.action || "-"; + } + } + + const line = `${nodePrefix}: ${comment}`; + if (lines.length === 0 || lines[lines.length - 1] !== line) { + lines.push(line); + } + } + return lines; +} + export function alignApprovalRunsWithHoseFlow( runs: ApprovalRun[], flow?: HoseFlowDetail @@ -663,7 +746,7 @@ export function alignApprovalRunsWithHoseFlow( recordId: run.id, sourceDocumentSN: run.sourceDocumentSN, taskMode: run.taskMode, - aiDecision: typeof aiDecision === "string" ? aiDecision : "-", + aiDecision: formatAiDecision(typeof aiDecision === "string" ? aiDecision : "-"), aiAction: "-", eHumanAction: "-", eHumanComment: "-", @@ -678,11 +761,17 @@ export function alignApprovalRunsWithHoseFlow( ); const history = flow.history || []; + const rawStateUpper = String(flow.rawState || "").toUpperCase(); + const stateUpper = String(flow.state || "").toUpperCase(); const isFlowCompleted = - flow.rawState === "COMPLETED" || - flow.rawState === "APPROVED" || - flow.state === "已完成" || - flow.state === "审批通过"; + rawStateUpper === "COMPLETED" || + rawStateUpper === "APPROVED" || + rawStateUpper === "PAID" || + rawStateUpper === "PAYING" || + stateUpper === "已完成" || + stateUpper === "审批通过" || + stateUpper === "已支付" || + stateUpper === "支付中"; for (let i = 0; i < sortedRuns.length; i++) { const run = sortedRuns[i]; @@ -728,6 +817,12 @@ export function alignApprovalRunsWithHoseFlow( normManual === "已取消" || normManual === "已撤回" || normManual === "REVOKED"; + const isRunApprovedInSeal = + normManual === "APPROVED" || + normManual === "已支付/审批完成" || + normManual === "已通过" || + normManual === "已完成" || + normManual === "已支付"; // 5-second clock skew tolerance window [runTime - 5000, nextRunTime) const windowEvents = history.filter((e) => { @@ -769,9 +864,9 @@ export function alignApprovalRunsWithHoseFlow( !e.isEbot && e.rawAction !== "freeflow.submit" && e.action !== "提交送审" && - e.rawAction !== "freeflow.print" && - e.action !== "打印提醒" && - e.rawAction !== "freeflow.comment" + !((e.rawAction === "freeflow.comment" || e.action === "发表评论") && !e.comment) && + !((e.rawAction === "freeflow.print" || e.action === "打印提醒") && !e.comment) && + !(e.rawAction === "freeflow.carbonCopy" || e.rawAction === "freeflow.cc" || e.action === "抄送通知") ); const retractEvent = subsequentHumanEvents.find( @@ -782,19 +877,19 @@ export function alignApprovalRunsWithHoseFlow( ); const isFlowRetractedOrCancelled = - flow.rawState === "DRAFT" || - flow.rawState === "REVOKED" || - flow.rawState === "CANCELED" || - flow.rawState === "CANCELLED" || - flow.state === "草稿" || - flow.state === "已撤回" || - flow.state === "已取消"; + rawStateUpper === "DRAFT" || + rawStateUpper === "REVOKED" || + rawStateUpper === "CANCELED" || + rawStateUpper === "CANCELLED" || + stateUpper === "草稿" || + stateUpper === "已撤回" || + stateUpper === "已取消"; const isFlowRejected = - flow.rawState === "REJECTED" || - flow.rawState === "TERMINATED" || - flow.state === "审批驳回" || - flow.state === "已驳回"; + rawStateUpper === "REJECTED" || + rawStateUpper === "TERMINATED" || + stateUpper === "审批驳回" || + stateUpper === "已驳回"; if (!isLatestRun) { // Historical run that has been superseded by a newer run @@ -810,23 +905,15 @@ export function alignApprovalRunsWithHoseFlow( eHumanComment = rejectEvent.comment || "驳回"; } else { eHumanAction = "已修改重提"; - const opinionLines: string[] = []; + const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { - const opName = ev.operator?.name || ev.operator?.id || "未知"; - const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; - const comment = - ev.comment || - (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" - ? "同意" - : ev.action || "-"); - opinionLines.push(`${nodePrefix}: ${comment}`); - if (!operator) operator = ev.operator; + if (!operator && ev.operator) operator = ev.operator; } eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "-"; } } else { // Latest run for this document - if (isFlowCompleted) { + if (isFlowCompleted || isRunApprovedInSeal) { const hasRetract = subsequentHumanEvents.some( (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" ); @@ -845,17 +932,9 @@ export function alignApprovalRunsWithHoseFlow( eHumanComment = rejectEvent.comment || "驳回"; operator = rejectEvent.operator; } else { - const opinionLines: string[] = []; + const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { - const opName = ev.operator?.name || ev.operator?.id || "未知"; - const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; - const comment = - ev.comment || - (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" - ? "同意" - : ev.action || "-"); - opinionLines.push(`${nodePrefix}: ${comment}`); - if (!operator) operator = ev.operator; + if (!operator && ev.operator) operator = ev.operator; } if (opinionLines.length > 0) { @@ -866,7 +945,7 @@ export function alignApprovalRunsWithHoseFlow( .find( (e) => !e.isEbot && - (e.rawAction === "freeflow.agree" || e.action === "审批同意") + (e.rawAction === "freeflow.agree" || e.action === "审批同意" || e.rawAction === "freeflow.pay") ); eHumanComment = lastHumanApproval?.comment || "-"; if (!operator) operator = lastHumanApproval?.operator; @@ -875,17 +954,9 @@ export function alignApprovalRunsWithHoseFlow( } else if (isFlowRetractedOrCancelled || (retractEvent && !hasPostAiResubmit) || isRunCancelledInSeal) { eHumanAction = "已撤回"; operator = retractEvent?.operator; - const opinionLines: string[] = []; + const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { - const opName = ev.operator?.name || ev.operator?.id || "未知"; - const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; - const comment = - ev.comment || - (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" - ? "同意" - : ev.action || "-"); - opinionLines.push(`${nodePrefix}: ${comment}`); - if (!operator) operator = ev.operator; + if (!operator && ev.operator) operator = ev.operator; } if (retractEvent && opinionLines.length === 0) { opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); @@ -900,17 +971,9 @@ export function alignApprovalRunsWithHoseFlow( // Flow is still actively approving eHumanAction = auditDrift ? "审核中 (⚠️ AI通过后被修改重提)" : "审核中"; - const opinionLines: string[] = []; + const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { - const opName = ev.operator?.name || ev.operator?.id || "未知"; - const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; - const comment = - ev.comment || - (ev.rawAction === "freeflow.agree" || ev.action === "审批同意" - ? "同意" - : ev.action || "-"); - opinionLines.push(`${nodePrefix}: ${comment}`); - if (!operator) operator = ev.operator; + if (!operator && ev.operator) operator = ev.operator; } const pendingNodes = flow.pending || []; @@ -934,7 +997,7 @@ export function alignApprovalRunsWithHoseFlow( recordId: run.id, sourceDocumentSN: run.sourceDocumentSN, taskMode: run.taskMode, - aiDecision: aiDecisionStr, + aiDecision: formatAiDecision(aiDecisionStr), aiAction, eHumanAction, eHumanComment, diff --git a/src/domains/hose/types.ts b/src/domains/hose/types.ts index f0e5923..0d06f1c 100644 --- a/src/domains/hose/types.ts +++ b/src/domains/hose/types.ts @@ -8,7 +8,11 @@ export const HOSE_FLOW_ACTION_LABELS: Record = { "freeflow.print": "打印单据", "freeflow.retract": "单据撤回", "freeflow.addnode": "加签/转交", - "freeflow.comment": "发表评论" + "freeflow.comment": "发表评论", + "freeflow.pay": "支付完成", + "freeflow.paying": "支付中", + "freeflow.carbonCopy": "抄送通知", + "freeflow.cc": "抄送通知" }; export const HOSE_FLOW_STATE_LABELS: Record = { @@ -23,7 +27,9 @@ export const HOSE_FLOW_STATE_LABELS: Record = { PENDING: "待审批", WAITING: "待处理", COMPLETED: "已完成", - DRAFT: "草稿" + DRAFT: "草稿", + PAID: "已支付", + PAYING: "支付中" }; export const FlowPersonSchema = z.object({ From 6c351b34dfddaaf29f0aff3f5e52701af7e6dfab Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 17:39:06 +0800 Subject: [PATCH 05/19] Prioritize reject event and Seal rejection over post-AI mutation --- src/domains/hose/flow.test.ts | 39 +++++++++++++++ src/domains/hose/flow.ts | 93 ++++++++++++++++++++--------------- 2 files changed, 93 insertions(+), 39 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 3143037..3d7ca83 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -964,6 +964,45 @@ describe("Hose Flow Domain", () => { // 5. No pending node appended expect(r.eHumanComment).not.toContain("当前审核节点"); }); + + test("handles AI approved run rejected by human operator before resubmission and payment: resolves to 驳回", () => { + 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", 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("驳回"); + expect(r.eHumanComment).toBe("修改附件"); + expect(r.auditDrift).toBe(false); + expect(r.operator?.name).toBe("熊雪倩"); + }); }); describe("Pending and end-state handling", () => { diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 86630b2..cef2b38 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -806,6 +806,15 @@ export function alignApprovalRunsWithHoseFlow( else if (normDecision === "REVIEW" || normDecision === "转交复核") aiAction = "转交复核"; const doc = (run.document as Record | undefined) || {}; + const mar = + ((run as Record).manualApprovalRecord as Record | undefined) || + (res.manualApprovalRecord as Record | undefined) || + ((doc as Record).manualApprovalRecord as Record | undefined) || + {}; + const marStatus = + typeof mar.status === "object" && mar.status !== null + ? String((mar.status as Record).type || (mar.status as Record).label || "").toUpperCase() + : ""; const rawManual = (doc.manualApprovalStatus as string | undefined) || (res.manualApprovalStatus as string | undefined) || @@ -822,7 +831,18 @@ export function alignApprovalRunsWithHoseFlow( normManual === "已支付/审批完成" || normManual === "已通过" || normManual === "已完成" || - normManual === "已支付"; + normManual === "已支付" || + marStatus === "APPROVED"; + const isRunRejectedInSeal = + normManual === "TERMINATED" || + normManual === "REJECTED" || + normManual === "REJECT" || + normManual === "已驳回" || + normManual === "被驳回" || + marStatus === "TERMINATED" || + marStatus === "REJECTED" || + marStatus === "已驳回" || + marStatus === "被驳回"; // 5-second clock skew tolerance window [runTime - 5000, nextRunTime) const windowEvents = history.filter((e) => { @@ -893,16 +913,18 @@ export function alignApprovalRunsWithHoseFlow( if (!isLatestRun) { // Historical run that has been superseded by a newer run - if (retractEvent || isRunCancelledInSeal) { + if (rejectEvent || isRunRejectedInSeal) { + eHumanAction = "驳回"; + auditDrift = false; + auditDriftReason = undefined; + eHumanComment = rejectEvent?.comment || (mar as any)?.rejectComment || "驳回"; + operator = rejectEvent?.operator; + } else if (retractEvent || isRunCancelledInSeal) { eHumanAction = "已撤回"; operator = retractEvent?.operator; eHumanComment = retractEvent?.comment || (retractEvent ? `${retractEvent.operator?.name || "提交人"}: 单据撤回` : "单据已撤回/取消"); - } else if (rejectEvent) { - eHumanAction = "驳回"; - operator = rejectEvent.operator; - eHumanComment = rejectEvent.comment || "驳回"; } else { eHumanAction = "已修改重提"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); @@ -913,43 +935,36 @@ export function alignApprovalRunsWithHoseFlow( } } else { // Latest run for this document - if (isFlowCompleted || isRunApprovedInSeal) { - const hasRetract = subsequentHumanEvents.some( - (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" - ); - + if (rejectEvent || isRunRejectedInSeal) { + eHumanAction = "驳回"; + auditDrift = false; + auditDriftReason = undefined; + eHumanComment = rejectEvent?.comment || (mar as any)?.rejectComment || "驳回"; + operator = rejectEvent?.operator; + } else if (isFlowCompleted || isRunApprovedInSeal) { if (auditDrift) { eHumanAction = "通过 (⚠️ AI通过后被中途修改)"; - } else if (rejectEvent) { - eHumanAction = "驳回"; - } else if (hasRetract) { - eHumanAction = "已撤回"; } else { eHumanAction = "通过"; } - if (rejectEvent) { - eHumanComment = rejectEvent.comment || "驳回"; - operator = rejectEvent.operator; - } else { - const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); - for (const ev of subsequentHumanEvents) { - if (!operator && ev.operator) operator = ev.operator; - } + const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); + for (const ev of subsequentHumanEvents) { + if (!operator && ev.operator) operator = ev.operator; + } - if (opinionLines.length > 0) { - eHumanComment = opinionLines.join("\n"); - } else { - const lastHumanApproval = [...windowEvents] - .reverse() - .find( - (e) => - !e.isEbot && - (e.rawAction === "freeflow.agree" || e.action === "审批同意" || e.rawAction === "freeflow.pay") - ); - eHumanComment = lastHumanApproval?.comment || "-"; - if (!operator) operator = lastHumanApproval?.operator; - } + if (opinionLines.length > 0) { + eHumanComment = opinionLines.join("\n"); + } else { + const lastHumanApproval = [...windowEvents] + .reverse() + .find( + (e) => + !e.isEbot && + (e.rawAction === "freeflow.agree" || e.action === "审批同意" || e.rawAction === "freeflow.pay") + ); + eHumanComment = lastHumanApproval?.comment || "-"; + if (!operator) operator = lastHumanApproval?.operator; } } else if (isFlowRetractedOrCancelled || (retractEvent && !hasPostAiResubmit) || isRunCancelledInSeal) { eHumanAction = "已撤回"; @@ -962,11 +977,11 @@ export function alignApprovalRunsWithHoseFlow( opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); } eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "单据已撤回"; - } else if (isFlowRejected || rejectEvent) { + } else if (isFlowRejected) { eHumanAction = "驳回"; - operator = rejectEvent?.operator; const rej = flow.rejections?.[0]; - eHumanComment = rejectEvent?.comment || rej?.reason || rej?.nodeName || "审批驳回"; + operator = rej?.operator; + eHumanComment = rej?.reason || rej?.nodeName || "审批驳回"; } else { // Flow is still actively approving eHumanAction = auditDrift ? "审核中 (⚠️ AI通过后被修改重提)" : "审核中"; From 2d4b0b1d361a95f2e84a3ed0c1a2fbdbe5843a6a Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 17:42:09 +0800 Subject: [PATCH 06/19] Translate freeflow.back and refine payment and CC actions --- src/domains/hose/flow.test.ts | 5 +++-- src/domains/hose/flow.ts | 24 +++++++++++++++--------- src/domains/hose/types.ts | 9 +++++---- 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 3d7ca83..4184574 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -956,10 +956,11 @@ describe("Hose Flow Domain", () => { // 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("高思琦: 支付完成"); + // 3. freeflow.pay mapped to 支付成功 + expect(r.eHumanComment).toContain("高思琦: 支付成功"); // 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("当前审核节点"); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index cef2b38..08d6901 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -692,11 +692,15 @@ export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string const lines: string[] = []; for (const ev of events) { if ( - (ev.rawAction === "freeflow.carbonCopy" || - ev.rawAction === "freeflow.cc" || - ev.rawAction === "freeflow.print" || - ev.action === "打印提醒" || - ev.action === "抄送通知") && + ev.rawAction === "freeflow.carbonCopy" || + ev.rawAction === "freeflow.cc" || + ev.action === "抄送单据" || + ev.action === "抄送通知" + ) { + continue; + } + if ( + (ev.rawAction === "freeflow.print" || ev.action === "打印提醒" || ev.action === "打印单据") && !ev.comment ) { continue; @@ -710,12 +714,14 @@ export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string comment = "同意"; } else if (ev.rawAction === "freeflow.autoAgree") { comment = "自动同意"; - } else if (ev.rawAction === "freeflow.pay" || ev.action === "支付完成") { - comment = "支付完成"; - } else if (ev.rawAction === "freeflow.paying" || ev.action === "支付中") { - comment = "支付中"; + } else if (ev.rawAction === "freeflow.pay" || ev.action === "支付成功" || ev.action === "支付完成") { + comment = "支付成功"; + } else if (ev.rawAction === "freeflow.paying" || ev.action === "发起支付" || ev.action === "支付中") { + comment = "发起支付"; } else if (ev.rawAction === "freeflow.reject" || ev.action === "审批驳回") { comment = "驳回"; + } else if (ev.rawAction === "freeflow.back" || ev.action === "审批退回") { + comment = "退回修改"; } else if (ev.rawAction === "freeflow.retract" || ev.action === "单据撤回") { comment = "单据撤回"; } else { diff --git a/src/domains/hose/types.ts b/src/domains/hose/types.ts index 0d06f1c..233bab1 100644 --- a/src/domains/hose/types.ts +++ b/src/domains/hose/types.ts @@ -5,14 +5,15 @@ export const HOSE_FLOW_ACTION_LABELS: Record = { "freeflow.agree": "审批同意", "freeflow.autoAgree": "自动同意", "freeflow.reject": "审批驳回", + "freeflow.back": "审批退回", "freeflow.print": "打印单据", "freeflow.retract": "单据撤回", "freeflow.addnode": "加签/转交", "freeflow.comment": "发表评论", - "freeflow.pay": "支付完成", - "freeflow.paying": "支付中", - "freeflow.carbonCopy": "抄送通知", - "freeflow.cc": "抄送通知" + "freeflow.pay": "支付成功", + "freeflow.paying": "发起支付", + "freeflow.carbonCopy": "抄送单据", + "freeflow.cc": "抄送单据" }; export const HOSE_FLOW_STATE_LABELS: Record = { From 86ac075c488a1c2efab657de9411a1bca1b990df Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 17:55:52 +0800 Subject: [PATCH 07/19] Refine flow alignment with native Hose states, numbering, and prefix --- src/domains/hose/flow.test.ts | 151 +++++++++++-- src/domains/hose/flow.ts | 262 +++++++++++++++++------ src/domains/seal/approval-runs-export.ts | 14 +- 3 files changed, 342 insertions(+), 85 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 4184574..eb5f0be 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -20,7 +20,9 @@ import { getHoseCloseFlow, alignApprovalRunsWithHoseFlow, formatAiDecision, - formatHumanOpinionLines + formatHumanOpinionLines, + formatNumberedHumanOpinions, + formatRejectionComment } from "./flow.js"; import { searchCloseBacklogs, @@ -786,8 +788,8 @@ describe("Hose Flow Domain", () => { const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r1 = aligned.get("run-1")!; - expect(r1.eHumanAction).toBe("驳回"); - expect(r1.eHumanComment).toBe("发票不全缺少总经理审批,退回修改"); + expect(r1.eHumanAction).toBe("审批驳回"); + expect(r1.eHumanComment).toBe("主管B: 发票不全缺少总经理审批,退回修改"); expect(r1.operator?.name).toBe("主管B"); expect(r1.auditDrift).toBe(false); @@ -797,13 +799,13 @@ describe("Hose Flow Domain", () => { expect(r2.auditDrift).toBe(false); const r3 = aligned.get("run-3")!; - expect(r3.eHumanAction).toBe("通过"); - expect(r3.eHumanComment).toBe("财务C: 核销通过"); + 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", () => { + test("handles unfinished flow: pending on human node with reverse order and badge", () => { const runs = [ { id: "run-3", @@ -825,8 +827,8 @@ describe("Hose Flow Domain", () => { const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r3 = aligned.get("run-3")!; - expect(r3.eHumanAction).toBe("审核中"); - expect(r3.eHumanComment).toBe("财务C审核:当前审核节点"); + expect(r3.eHumanAction).toBe("⏳ 审批中"); + expect(r3.eHumanComment).toBe("⏳ 1. 财务C审核: 待审批"); }); test("detects Post-AI Mutation (审计漂移 / 过审后中途被修改)", () => { @@ -853,7 +855,7 @@ describe("Hose Flow Domain", () => { const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r1 = aligned.get("run-1")!; - expect(r1.eHumanAction).toBe("通过 (⚠️ AI通过后被中途修改)"); + expect(r1.eHumanAction).toBe("审批通过"); expect(r1.auditDrift).toBe(true); expect(r1.auditDriftReason).toContain("AI通过后单据发生撤回/修改重提"); }); @@ -908,8 +910,8 @@ describe("Hose Flow Domain", () => { expect(r1.auditDrift).toBe(false); const r2 = aligned.get("run-active")!; - expect(r2.eHumanAction).toBe("审核中"); - expect(r2.eHumanComment).toBe("上级主管(张舒):当前审核节点"); + expect(r2.eHumanAction).toBe("⏳ 审批中"); + expect(r2.eHumanComment).toBe("⏳ 1. 上级主管(张舒): 待审批"); expect(r2.auditDrift).toBe(false); }); @@ -945,28 +947,84 @@ describe("Hose Flow Domain", () => { const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r = aligned.get("run-paid")!; expect(r.aiDecision).toBe("备注通过"); - expect(r.eHumanAction).toBe("通过"); + expect(r.eHumanAction).toBe("已支付"); expect(r.auditDrift).toBe(false); // Verify opinions: - // 1. Agree nodes present - expect(r.eHumanComment).toContain("上级主管(张舒): 同意"); - expect(r.eHumanComment).toContain("财务助理(熊雪倩): 同意"); - expect(r.eHumanComment).toContain("部门主管(张舒): 自动同意"); + // 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("高思琦: 支付成功"); + 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 AI approved run rejected by human operator before resubmission and payment: resolves to 驳回", () => { + 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", @@ -990,7 +1048,7 @@ describe("Hose Flow Domain", () => { { 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", operator: { name: "熊雪倩" } }, + { time: 25000, action: "审批同意", rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" } }, { time: 30000, action: "支付完成", rawAction: "freeflow.pay", operator: { name: "高思琦" } } ], pending: [] @@ -999,8 +1057,9 @@ describe("Hose Flow Domain", () => { const aligned = alignApprovalRunsWithHoseFlow(runs, flow); const r = aligned.get("run-rejected-then-paid")!; expect(r.aiDecision).toBe("备注通过"); - expect(r.eHumanAction).toBe("驳回"); - expect(r.eHumanComment).toBe("修改附件"); + expect(r.eHumanAction).toBe("审批驳回"); + // Node prefix resolved from熊雪倩's approval node in history: 财务助理(熊雪倩): 修改附件 + expect(r.eHumanComment).toBe("财务助理(熊雪倩): 修改附件"); expect(r.auditDrift).toBe(false); expect(r.operator?.name).toBe("熊雪倩"); }); @@ -1040,5 +1099,55 @@ describe("Hose Flow Domain", () => { 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("财务助理(熊雪倩): 修改附件"); + expect(res1.operator?.name).toBe("熊雪倩"); + + const res2 = formatRejectionComment( + undefined, + { + nodeName: "财务经理", + operator: { name: "周晚容" }, + reason: "单据超标缺少说明" + } as any + ); + expect(res2.comment).toBe("财务经理(周晚容): 单据超标缺少说明"); + }); }); }); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 08d6901..8bd5cf2 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -737,6 +737,130 @@ export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string return lines; } +export function formatNumberedHumanOpinions( + historyLines: string[], + pendingLines: string[] = [], + mode: "forward" | "reverse" = "forward" +): string { + if (historyLines.length === 0 && pendingLines.length === 0) { + return "-"; + } + + if (mode === "forward") { + const all = [...historyLines, ...pendingLines]; + return all.map((line, idx) => `${idx + 1}. ${line}`).join("\n"); + } + + // Reverse chronological order for in-progress approvals: + // Pending node(s) appear at the top with badge (e.g. ⏳ 7. 出纳支付(高思琦): 待支付), + // followed by history approvals in reverse order (e.g. 6. CFO, 5. 财务经理...) + const result: string[] = []; + + pendingLines.forEach((line, idx) => { + const seq = historyLines.length + idx + 1; + const badge = idx === 0 ? "⏳ " : ""; + result.push(`${badge}${seq}. ${line}`); + }); + + for (let i = historyLines.length - 1; i >= 0; i--) { + const seq = i + 1; + result.push(`${seq}. ${historyLines[i]}`); + } + + return result.join("\n"); +} + +export function formatRejectionComment( + rejectEvent?: HoseFlowTimelineEntry, + rejectionDetail?: HoseRejectionDetail, + mar?: Record, + history?: HoseFlowTimelineEntry[] +): { comment: string; operator?: FlowPerson } { + const op = rejectEvent?.operator || rejectionDetail?.operator || (mar as any)?.operator; + const opName = op?.name || op?.id || (mar as any)?.operatorName || ""; + + let rawNodeName = ( + rejectEvent?.nodeName || + rejectionDetail?.nodeName || + (mar as any)?.nodeName || + "" + ).trim(); + + // In Hose, freeflow.reject often records target node "提交人" (meaning rejected back to submitter) + // If we have an operator name, lookup their actual approval nodeName in history + if ((!rawNodeName || rawNodeName === "提交人") && opName && history) { + const matchedLog = history.find( + (h) => + h.operator?.name === opName && + h.nodeName && + h.nodeName.trim() !== "提交人" && + !h.isEbot + ); + if (matchedLog?.nodeName) { + rawNodeName = matchedLog.nodeName.trim(); + } else if (rawNodeName === "提交人") { + rawNodeName = "驳回至提交人"; + } + } + + const rawComment = + rejectEvent?.comment || + rejectionDetail?.reason || + (mar as any)?.rejectComment || + "审批驳回"; + + let commentStr = rawComment; + if (rawNodeName && opName) { + if (!rawComment.startsWith(`${rawNodeName}(${opName}):`)) { + commentStr = `${rawNodeName}(${opName}): ${rawComment}`; + } + } else if (opName) { + if (!rawComment.startsWith(`${opName}:`)) { + commentStr = `${opName}: ${rawComment}`; + } + } else if (rawNodeName) { + if (!rawComment.startsWith(`${rawNodeName}:`)) { + commentStr = `${rawNodeName}: ${rawComment}`; + } + } + + return { + comment: commentStr, + operator: op + }; +} + +export function extractPendingLines(flow?: HoseFlowDetail): string[] { + if (!flow) return []; + const pendingNodes = flow.pending || []; + const rawStateUpper = String(flow.rawState || "").toUpperCase(); + const stateUpper = String(flow.state || "").toUpperCase(); + + const lines: string[] = []; + if (pendingNodes.length > 0) { + for (const p of pendingNodes) { + const pApprover = p.approver?.name || p.approver?.id || "待定"; + const pNodeName = (p.name || flow.currentNode || "").trim(); + const pPrefix = pNodeName ? `${pNodeName}(${pApprover})` : pApprover; + const isPayment = + p.type?.toUpperCase() === "PAYING" || + pNodeName.includes("支付") || + rawStateUpper === "PAYING" || + stateUpper === "支付中"; + const actionText = isPayment ? "待支付" : "待审批"; + lines.push(`${pPrefix}: ${actionText}`); + } + } else if (flow.currentNode?.trim()) { + const isPayment = + flow.currentNode.includes("支付") || + rawStateUpper === "PAYING" || + stateUpper === "支付中"; + const actionText = isPayment ? "待支付" : "待审批"; + lines.push(`${flow.currentNode.trim()}: ${actionText}`); + } + return lines; +} + export function alignApprovalRunsWithHoseFlow( runs: ApprovalRun[], flow?: HoseFlowDetail @@ -769,15 +893,56 @@ export function alignApprovalRunsWithHoseFlow( const history = flow.history || []; const rawStateUpper = String(flow.rawState || "").toUpperCase(); const stateUpper = String(flow.state || "").toUpperCase(); - const isFlowCompleted = - rawStateUpper === "COMPLETED" || - rawStateUpper === "APPROVED" || - rawStateUpper === "PAID" || - rawStateUpper === "PAYING" || - stateUpper === "已完成" || - stateUpper === "审批通过" || - stateUpper === "已支付" || - stateUpper === "支付中"; + + const isFlowRetractedOrCancelled = + rawStateUpper === "DRAFT" || + rawStateUpper === "REVOKED" || + rawStateUpper === "CANCELED" || + rawStateUpper === "CANCELLED" || + stateUpper === "草稿" || + stateUpper === "已撤回" || + stateUpper === "已取消"; + + const isFlowRejected = + rawStateUpper === "REJECTED" || + rawStateUpper === "TERMINATED" || + stateUpper === "审批驳回" || + stateUpper === "已驳回"; + + const isFlowPaid = + !isFlowRetractedOrCancelled && + !isFlowRejected && + (rawStateUpper === "PAID" || + stateUpper === "已支付" || + history.some( + (e) => + !e.isEbot && + (e.rawAction === "freeflow.pay" || e.action === "支付成功" || e.action === "支付完成") + )); + + const isFlowPaying = + !isFlowRetractedOrCancelled && + !isFlowRejected && + !isFlowPaid && + (rawStateUpper === "PAYING" || + stateUpper === "支付中" || + (flow.pending || []).some( + (p) => + p.isCurrent && + (p.type?.toUpperCase() === "PAYING" || p.name?.includes("支付")) + ) || + flow.currentNode?.includes("支付") === true); + + const isFlowApproved = + !isFlowRetractedOrCancelled && + !isFlowRejected && + !isFlowPaying && + (rawStateUpper === "COMPLETED" || + rawStateUpper === "APPROVED" || + stateUpper === "已完成" || + stateUpper === "审批通过"); + + const isFlowCompleted = isFlowPaid || isFlowApproved; for (let i = 0; i < sortedRuns.length; i++) { const run = sortedRuns[i]; @@ -902,29 +1067,15 @@ export function alignApprovalRunsWithHoseFlow( (e) => e.rawAction === "freeflow.reject" || e.action === "审批驳回" ); - const isFlowRetractedOrCancelled = - rawStateUpper === "DRAFT" || - rawStateUpper === "REVOKED" || - rawStateUpper === "CANCELED" || - rawStateUpper === "CANCELLED" || - stateUpper === "草稿" || - stateUpper === "已撤回" || - stateUpper === "已取消"; - - const isFlowRejected = - rawStateUpper === "REJECTED" || - rawStateUpper === "TERMINATED" || - stateUpper === "审批驳回" || - stateUpper === "已驳回"; - if (!isLatestRun) { // Historical run that has been superseded by a newer run if (rejectEvent || isRunRejectedInSeal) { - eHumanAction = "驳回"; + eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; - eHumanComment = rejectEvent?.comment || (mar as any)?.rejectComment || "驳回"; - operator = rejectEvent?.operator; + const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history); + eHumanComment = rejInfo.comment; + operator = rejInfo.operator; } else if (retractEvent || isRunCancelledInSeal) { eHumanAction = "已撤回"; operator = retractEvent?.operator; @@ -937,22 +1088,19 @@ export function alignApprovalRunsWithHoseFlow( for (const ev of subsequentHumanEvents) { if (!operator && ev.operator) operator = ev.operator; } - eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "-"; + eHumanComment = formatNumberedHumanOpinions(opinionLines, [], "forward"); } } else { // Latest run for this document - if (rejectEvent || isRunRejectedInSeal) { - eHumanAction = "驳回"; + if (rejectEvent || isRunRejectedInSeal || isFlowRejected) { + eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; - eHumanComment = rejectEvent?.comment || (mar as any)?.rejectComment || "驳回"; - operator = rejectEvent?.operator; + const rejInfo = formatRejectionComment(rejectEvent, flow.rejections?.[0], mar, history); + eHumanComment = rejInfo.comment; + operator = rejInfo.operator; } else if (isFlowCompleted || isRunApprovedInSeal) { - if (auditDrift) { - eHumanAction = "通过 (⚠️ AI通过后被中途修改)"; - } else { - eHumanAction = "通过"; - } + eHumanAction = isFlowPaid ? "已支付" : "审批通过"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { @@ -960,16 +1108,18 @@ export function alignApprovalRunsWithHoseFlow( } if (opinionLines.length > 0) { - eHumanComment = opinionLines.join("\n"); + eHumanComment = formatNumberedHumanOpinions(opinionLines, [], "forward"); } else { const lastHumanApproval = [...windowEvents] .reverse() .find( (e) => !e.isEbot && - (e.rawAction === "freeflow.agree" || e.action === "审批同意" || e.rawAction === "freeflow.pay") + (e.rawAction === "freeflow.agree" || + e.action === "审批同意" || + e.rawAction === "freeflow.pay") ); - eHumanComment = lastHumanApproval?.comment || "-"; + eHumanComment = lastHumanApproval?.comment ? `1. ${lastHumanApproval.comment}` : "-"; if (!operator) operator = lastHumanApproval?.operator; } } else if (isFlowRetractedOrCancelled || (retractEvent && !hasPostAiResubmit) || isRunCancelledInSeal) { @@ -983,33 +1133,25 @@ export function alignApprovalRunsWithHoseFlow( opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); } eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "单据已撤回"; - } else if (isFlowRejected) { - eHumanAction = "驳回"; - const rej = flow.rejections?.[0]; - operator = rej?.operator; - eHumanComment = rej?.reason || rej?.nodeName || "审批驳回"; - } else { - // Flow is still actively approving - eHumanAction = auditDrift ? "审核中 (⚠️ AI通过后被修改重提)" : "审核中"; + } else if (isFlowPaying) { + eHumanAction = "⏳ 支付中"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { if (!operator && ev.operator) operator = ev.operator; } + const pendingLines = extractPendingLines(flow); + eHumanComment = formatNumberedHumanOpinions(opinionLines, pendingLines, "reverse"); + } else { + // Flow is actively approving + eHumanAction = "⏳ 审批中"; - const pendingNodes = flow.pending || []; - const currentPending = pendingNodes.find((p) => p.isCurrent) || pendingNodes[0]; - if (currentPending) { - const pApprover = - currentPending.approver?.name || currentPending.approver?.id || "待定"; - const pNodeName = (currentPending.name || flow.currentNode || "").trim(); - const pPrefix = pNodeName ? `${pNodeName}(${pApprover})` : pApprover; - opinionLines.push(`${pPrefix}:当前审核节点`); - } else if (flow.currentNode?.trim()) { - opinionLines.push(`${flow.currentNode.trim()}:当前审核节点`); + const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); + for (const ev of subsequentHumanEvents) { + if (!operator && ev.operator) operator = ev.operator; } - - eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "当前审核节点"; + const pendingLines = extractPendingLines(flow); + eHumanComment = formatNumberedHumanOpinions(opinionLines, pendingLines, "reverse"); } } } diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index 8da92e9..5b8e152 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -842,14 +842,20 @@ export async function exportApprovalRunsToExcel( if (val.includes("⚠️") || val.includes("修改")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFD97706" }, bold: true }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } }; - } else if (val.includes("驳回")) { + } else if (val.includes("驳回") || val.includes("退回")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } }; - } else if (val.includes("通过")) { + } else if (val.includes("通过") || val.includes("已支付") || val.includes("已完成")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF16A34A" }, bold: true }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } }; - } else if (val.includes("待处理") || val.includes("处理中") || val.includes("审核中")) { - cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" } }; + } else if ( + val.includes("待处理") || + val.includes("处理中") || + val.includes("审核中") || + val.includes("审批中") || + val.includes("支付中") + ) { + cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" }, bold: true }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } }; } else if (val.includes("撤回") || val.includes("取消")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF64748B" } }; From 047c877c1f445fd3947cd03b914419f8bd5b5532 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 18:11:21 +0800 Subject: [PATCH 08/19] Fix retracted run status and eliminate synthetic node leakage --- src/domains/hose/flow.test.ts | 66 +++++++++++++++++ src/domains/hose/flow.ts | 90 ++++++++++++++++++------ src/domains/seal/approval-runs-export.ts | 5 +- 3 files changed, 140 insertions(+), 21 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index eb5f0be..6eb3891 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -1148,6 +1148,72 @@ describe("Hose Flow Domain", () => { } as any ); expect(res2.comment).toBe("财务经理(周晚容): 单据超标缺少说明"); + + const res3 = formatRejectionComment( + undefined, + undefined, + { nodeName: "合思审批节点", rejectComment: "超额报销" } + ); + expect(res3.comment).toBe("超额报销"); + 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. 高思琦: 支付成功" + ); }); }); }); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 8bd5cf2..9463358 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -786,6 +786,16 @@ export function formatRejectionComment( "" ).trim(); + // Strip Seal's synthetic wrapper node names (never output "合思审批节点" to user) + if ( + rawNodeName === "合思审批节点" || + rawNodeName === "外部审批节点" || + rawNodeName.includes("合思审批") || + rawNodeName.includes("外部审批") + ) { + rawNodeName = ""; + } + // In Hose, freeflow.reject often records target node "提交人" (meaning rejected back to submitter) // If we have an operator name, lookup their actual approval nodeName in history if ((!rawNodeName || rawNodeName === "提交人") && opName && history) { @@ -986,6 +996,10 @@ export function alignApprovalRunsWithHoseFlow( typeof mar.status === "object" && mar.status !== null ? String((mar.status as Record).type || (mar.status as Record).label || "").toUpperCase() : ""; + const marSourceStatus = + typeof mar.status === "object" && mar.status !== null + ? String((mar.status as Record).sourceStatus || "") + : ""; const rawManual = (doc.manualApprovalStatus as string | undefined) || (res.manualApprovalStatus as string | undefined) || @@ -996,7 +1010,11 @@ export function alignApprovalRunsWithHoseFlow( normManual === "CANCELED" || normManual === "已取消" || normManual === "已撤回" || - normManual === "REVOKED"; + normManual === "REVOKED" || + marStatus === "CANCELLED" || + marStatus === "CANCELED" || + marSourceStatus.includes("撤回") || + marSourceStatus.includes("取消"); const isRunApprovedInSeal = normManual === "APPROVED" || normManual === "已支付/审批完成" || @@ -1004,16 +1022,19 @@ export function alignApprovalRunsWithHoseFlow( normManual === "已完成" || normManual === "已支付" || marStatus === "APPROVED"; + const isRunCompensation = + marSourceStatus.includes("补偿") || marSourceStatus.includes("已支付"); const isRunRejectedInSeal = - normManual === "TERMINATED" || - normManual === "REJECTED" || - normManual === "REJECT" || - normManual === "已驳回" || - normManual === "被驳回" || - marStatus === "TERMINATED" || - marStatus === "REJECTED" || - marStatus === "已驳回" || - marStatus === "被驳回"; + !isRunCompensation && + (normManual === "TERMINATED" || + normManual === "REJECTED" || + normManual === "REJECT" || + normManual === "已驳回" || + normManual === "被驳回" || + marStatus === "TERMINATED" || + marStatus === "REJECTED" || + marStatus === "已驳回" || + marStatus === "被驳回"); // 5-second clock skew tolerance window [runTime - 5000, nextRunTime) const windowEvents = history.filter((e) => { @@ -1069,37 +1090,61 @@ export function alignApprovalRunsWithHoseFlow( if (!isLatestRun) { // Historical run that has been superseded by a newer run - if (rejectEvent || isRunRejectedInSeal) { + if (rejectEvent || (!flow && isRunRejectedInSeal)) { eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history); eHumanComment = rejInfo.comment; operator = rejInfo.operator; - } else if (retractEvent || isRunCancelledInSeal) { + } else if (retractEvent || isRunCancelledInSeal || (!rejectEvent && marSourceStatus.includes("单据撤回"))) { eHumanAction = "已撤回"; operator = retractEvent?.operator; + // Events belonging to this run only occur up to the retract event + const runEvents = retractEvent + ? subsequentHumanEvents.filter((e) => (e.time ?? 0) <= (retractEvent.time ?? Infinity)) + : subsequentHumanEvents; + const opinionLines = formatHumanOpinionLines(runEvents); + for (const ev of runEvents) { + if (!operator && ev.operator) operator = ev.operator; + } + if (retractEvent && !opinionLines.some((l) => l.includes("单据撤回"))) { + opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); + } eHumanComment = - retractEvent?.comment || - (retractEvent ? `${retractEvent.operator?.name || "提交人"}: 单据撤回` : "单据已撤回/取消"); + opinionLines.length > 1 + ? formatNumberedHumanOpinions(opinionLines, [], "forward") + : opinionLines.length === 1 + ? opinionLines[0]! + : (retractEvent ? `${retractEvent.operator?.name || "提交人"}: 单据撤回` : "单据已撤回"); } else { eHumanAction = "已修改重提"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { if (!operator && ev.operator) operator = ev.operator; } - eHumanComment = formatNumberedHumanOpinions(opinionLines, [], "forward"); + eHumanComment = + opinionLines.length > 1 + ? formatNumberedHumanOpinions(opinionLines, [], "forward") + : opinionLines.length === 1 + ? opinionLines[0]! + : "-"; } } else { // Latest run for this document - if (rejectEvent || isRunRejectedInSeal || isFlowRejected) { + if ( + rejectEvent || + isFlowRejected || + (flow && flow.rejections && flow.rejections.length > 0) || + (!flow && isRunRejectedInSeal) + ) { eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; - const rejInfo = formatRejectionComment(rejectEvent, flow.rejections?.[0], mar, history); + const rejInfo = formatRejectionComment(rejectEvent, flow?.rejections?.[0], mar, history); eHumanComment = rejInfo.comment; operator = rejInfo.operator; - } else if (isFlowCompleted || isRunApprovedInSeal) { + } else if (isFlowCompleted || (!flow && isRunApprovedInSeal)) { eHumanAction = isFlowPaid ? "已支付" : "审批通过"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); @@ -1129,10 +1174,15 @@ export function alignApprovalRunsWithHoseFlow( for (const ev of subsequentHumanEvents) { if (!operator && ev.operator) operator = ev.operator; } - if (retractEvent && opinionLines.length === 0) { + if (retractEvent && !opinionLines.some((l) => l.includes("单据撤回"))) { opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); } - eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "单据已撤回"; + eHumanComment = + opinionLines.length > 1 + ? formatNumberedHumanOpinions(opinionLines, [], "forward") + : opinionLines.length === 1 + ? opinionLines[0]! + : "单据已撤回"; } else if (isFlowPaying) { eHumanAction = "⏳ 支付中"; diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index 5b8e152..728f544 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -703,8 +703,11 @@ export async function exportApprovalRunsToExcel( // 6. 人工审核状态与驳回原因 const mar = (record as any).manualApprovalRecord || {}; + const marSourceStatus = String(mar.status?.sourceStatus || ""); let manualStatus = "-"; - if (mar.status?.label) { + if (marSourceStatus === "已支付回调补偿驳回" || marSourceStatus.includes("补偿驳回")) { + manualStatus = "已撤回"; + } else if (mar.status?.label) { manualStatus = String(mar.status.label); } else if (mar.status?.type) { const t = String(mar.status.type); From 870975b5f707e68683e68c0575711ebfdaf7a2fb Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 18:18:25 +0800 Subject: [PATCH 09/19] =?UTF-8?q?Use=20=E6=8F=90=E4=BA=A4=E4=BA=BA?= =?UTF-8?q?=EF=BC=88xxx=EF=BC=89:=20=E5=8D=95=E6=8D=AE=E6=92=A4=E5=9B=9E?= =?UTF-8?q?=20prefix=20for=20retract=20events=20(no=20Hose=20nodeName)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domains/hose/flow.test.ts | 4 ++-- src/domains/hose/flow.ts | 14 ++++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 6eb3891..6e3f1f7 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -906,7 +906,7 @@ describe("Hose Flow Domain", () => { const r1 = aligned.get("run-retracted")!; expect(r1.eHumanAction).toBe("已撤回"); - expect(r1.eHumanComment).toBe("刘佳琼: 单据撤回"); + expect(r1.eHumanComment).toBe("提交人(刘佳琼): 单据撤回"); expect(r1.auditDrift).toBe(false); const r2 = aligned.get("run-active")!; @@ -1204,7 +1204,7 @@ describe("Hose Flow Domain", () => { const r1 = aligned.get("run-round-1")!; expect(r1.eHumanAction).toBe("已撤回"); expect(r1.eHumanComment).toBe( - "1. 费用类型是研发费(宁艳楠): 同意\n2. 袁锦: 单据撤回" + "1. 费用类型是研发费(宁艳楠): 同意\n2. 提交人(袁锦): 单据撤回" ); expect(r1.eHumanComment).not.toContain("合思审批节点"); expect(r1.eHumanComment).not.toContain("审批驳回"); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 9463358..992c4a6 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -707,7 +707,13 @@ export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string } const opName = ev.operator?.name || ev.operator?.id || "未知"; - const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName; + // freeflow.retract has no nodeName in Hose; the actor is always the submitter + const isRetractAction = ev.rawAction === "freeflow.retract" || ev.action === "单据撤回"; + const nodePrefix = ev.nodeName?.trim() + ? `${ev.nodeName.trim()}(${opName})` + : isRetractAction + ? `提交人(${opName})` + : opName; let comment = ev.comment; if (!comment) { if (ev.rawAction === "freeflow.agree" || ev.action === "审批同意") { @@ -1109,14 +1115,14 @@ export function alignApprovalRunsWithHoseFlow( if (!operator && ev.operator) operator = ev.operator; } if (retractEvent && !opinionLines.some((l) => l.includes("单据撤回"))) { - opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); + opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回`); } eHumanComment = opinionLines.length > 1 ? formatNumberedHumanOpinions(opinionLines, [], "forward") : opinionLines.length === 1 ? opinionLines[0]! - : (retractEvent ? `${retractEvent.operator?.name || "提交人"}: 单据撤回` : "单据已撤回"); + : (retractEvent ? `提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回` : "单据已撤回"); } else { eHumanAction = "已修改重提"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); @@ -1175,7 +1181,7 @@ export function alignApprovalRunsWithHoseFlow( if (!operator && ev.operator) operator = ev.operator; } if (retractEvent && !opinionLines.some((l) => l.includes("单据撤回"))) { - opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`); + opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回`); } eHumanComment = opinionLines.length > 1 From de79e9735b4ca9b3bb741f323396fbe16c20b354 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 14 Sep 2026 18:28:38 +0800 Subject: [PATCH 10/19] =?UTF-8?q?Make=20--with-flow=20opt-in:=20E=E4=BA=BA?= =?UTF-8?q?=E5=B7=A5=E8=A1=8C=E4=B8=BA/E=E4=BA=BA=E5=B7=A5=E6=84=8F?= =?UTF-8?q?=E8=A7=81=20columns=20require=20explicit=20--with-flow=20flag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/seal-use/SKILL.md | 4 +++- src/cli/help.ts | 4 ++-- src/domains/seal/approval-runs-export.ts | 10 +++++----- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index b464b64..8b1203e 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -88,7 +88,7 @@ seal-use corps list - 规则本地工作流: `seal-use rules pull` 导出草稿规则,`rules lint` 做质量检查,`rules push --dry-run` 预览增量更新,确认后用 `--yes` 写入;`rules map` 查询 `corps sync-test` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 `references/rule-lightweight.md` 和 `references/cli.md`。 - Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud --corp `; read `references/hose-enterprise-deploy.md`. - 审核决策偏好与思考深度: `seal-use preference get --corp `, `preference decision update --json '...' --corp `, `preference thinking-depth set --default --corp `, `preference thinking-depth policies --corp `. -- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp `, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表);需要追踪单据时再使用 `url` 或 `bridge`。 +- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp `, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表,默认仅含 Seal 系统字段;追加 `--with-flow` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,需调用合思 Open API,200 条以上单据约增加 30 秒);需要追踪单据时再使用 `url` 或 `bridge`。 - User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. - Delegation links management: `seal-use delegation list --corp `, `create [--note ...] --corp `, `create --from-link [--note ...]`, `revoke --corp `. - User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-use users search [keyword] --corp `, `users delegation --corp ` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate --corp `, `users create --name ... --phone ... --corp `, `users reset-password --corp `, `users get --corp `, `users delete --corp `. @@ -159,6 +159,8 @@ seal-use simulation batch-records --corp seal-use simulation status --corp seal-use simulation approval-definitions --corp seal-use approval-runs export --corp --downloads --completed-only +# Add --with-flow to also populate E人工行为 / E人工意见 columns (Hose Open API, adds ~30s): +seal-use approval-runs export --corp --downloads --with-flow seal-use analytics insight --corp seal-use contacts departments --corp seal-use data invoices --corp --limit 20 diff --git a/src/cli/help.ts b/src/cli/help.ts index 9526c7e..e600bf1 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -350,8 +350,8 @@ export const HELP_REGISTRY: AreaHelp[] = [ }, { name: "export", - summary: "Export approval run audit records to Excel workbook", - usage: ["seal-use approval-runs export [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads|--to-downloads] [--with-flow|--no-flow] [--out ] [--corp ]"] + summary: "Export approval run audit records to Excel workbook. Add --with-flow to include E人工行为 / E人工意见 columns (requires Hose Open API; adds ~30s for large batches).", + usage: ["seal-use approval-runs export [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads|--to-downloads] [--with-flow] [--out ] [--corp ]"] }, { name: "flow", diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index 728f544..d0429c7 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -347,8 +347,8 @@ export async function exportApprovalRunsToExcel( console.error(`已就绪 ${sortedRuleKeys.length} 个规则列。开始拉取单据...`); - // 1.5 如果是合思企业且开启审批流对齐,先探测单据规模并做耗时与频控提示 - if (options.withFlow !== false && corp.source.type === "hose") { + // 1.5 如果是合思企业且显式启用 withFlow,先探测单据规模并做耗时与频控提示 + if (options.withFlow === true && corp.source.type === "hose") { try { const probeData = await api.listApprovalRuns(client, { limit: 1, @@ -364,7 +364,7 @@ export async function exportApprovalRunsToExcel( const estSeconds = Math.max(1, Math.ceil((probeTotal / concurrency) * 0.4)); if (probeTotal > 50) { console.error( - `⚠️ [审批流对齐提示] 目标区间内单据规模约为 ${probeTotal} 笔。系统已启用合思 Open API 保护限流(并发 ${concurrency}),预计审批流拉取耗时约 ${estSeconds} 秒。若无需原生人工流转行为与意见,可追加 --no-flow 快速导出。` + `⚠️ [审批流对齐提示] 目标区间内单据规模约为 ${probeTotal} 笔。系统已启用合思 Open API 保护限流(并发 ${concurrency}),预计审批流拉取耗时约 ${estSeconds} 秒。` ); } } catch { @@ -540,12 +540,12 @@ export async function exportApprovalRunsToExcel( let rejectReasonCount = 0; let driftCount = 0; - // 3.5 如果是合思租户且未显式关闭 withFlow,获取原生审批流并对齐真实人工行为与意见 + // 3.5 如果是合思租户且显式启用 withFlow(--with-flow),获取原生审批流并对齐 E人工行为 / E人工意见 const alignmentsByRecordId = new Map(); const deletedSNs = new Set(); const excludeDeleted = options.excludeDeleted ?? true; - if (options.withFlow !== false && corp.source.type === "hose") { + if (options.withFlow === true && corp.source.type === "hose") { try { const runsByDocKey = new Map(); for (const record of fetchedRecords) { From 577ad0415c59a18564aa6209dcb07c9e29008908 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 09:23:06 +0800 Subject: [PATCH 11/19] Fix time-windowed rejection scoping, revert synthetic mapping on system fields, and make E columns strictly opt-in via --with-flow --- skills/seal-use/references/cli.md | 3 +- src/domains/hose/flow.ts | 43 ++++++---- src/domains/seal/approval-runs-export.test.ts | 79 +++++++++++++++++-- src/domains/seal/approval-runs-export.ts | 55 +++++++++---- 4 files changed, 141 insertions(+), 39 deletions(-) diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 4bf5f63..3aa1fef 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -147,7 +147,8 @@ seal-use analytics performance --corp [--start-date ] [--end-da seal-use analytics analyze --corp seal-use analytics export --corp [--downloads] [--out ] [--start-date ] [--end-date ] [--force] seal-use approval-runs count --corp [--status APPROVED] [--start ] [--end ] -seal-use approval-runs export --corp [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads] [--out ] +seal-use approval-runs export --corp [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads] [--out ] [--with-flow] +# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(默认关闭以节省合思 API 调用) seal-use approval-runs search --corp [--query text] [--limit 20] [--includeBridge true] seal-use approval-runs get --corp [--fields metadata|document.fields,result.summary] [--output-file file.json] seal-use approval-runs attachments --corp diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 992c4a6..a1bb8a0 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -1137,17 +1137,18 @@ export function alignApprovalRunsWithHoseFlow( : "-"; } } else { - // Latest run for this document - if ( - rejectEvent || - isFlowRejected || - (flow && flow.rejections && flow.rejections.length > 0) || - (!flow && isRunRejectedInSeal) - ) { + // Latest run for this document. + // Rule: rejectEvent is scoped to THIS run's time window — if it exists, this run was + // definitively rejected regardless of what the overall flow state is now (the flow may + // have been paid via a subsequent re-submission). + // flow.rejections.length alone is NOT reliable — it can contain rejections from earlier + // rounds. Only use it as a fallback when isFlowRejected (current state) is also true. + if (rejectEvent) { + // A rejection event occurred inside this run's time window → this run was rejected. eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; - const rejInfo = formatRejectionComment(rejectEvent, flow?.rejections?.[0], mar, history); + const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history); eHumanComment = rejInfo.comment; operator = rejInfo.operator; } else if (isFlowCompleted || (!flow && isRunApprovedInSeal)) { @@ -1173,6 +1174,15 @@ export function alignApprovalRunsWithHoseFlow( eHumanComment = lastHumanApproval?.comment ? `1. ${lastHumanApproval.comment}` : "-"; if (!operator) operator = lastHumanApproval?.operator; } + } else if (isFlowPaying) { + eHumanAction = "⏳ 支付中"; + + const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); + for (const ev of subsequentHumanEvents) { + if (!operator && ev.operator) operator = ev.operator; + } + const pendingLines = extractPendingLines(flow); + eHumanComment = formatNumberedHumanOpinions(opinionLines, pendingLines, "reverse"); } else if (isFlowRetractedOrCancelled || (retractEvent && !hasPostAiResubmit) || isRunCancelledInSeal) { eHumanAction = "已撤回"; operator = retractEvent?.operator; @@ -1189,15 +1199,14 @@ export function alignApprovalRunsWithHoseFlow( : opinionLines.length === 1 ? opinionLines[0]! : "单据已撤回"; - } else if (isFlowPaying) { - eHumanAction = "⏳ 支付中"; - - const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); - for (const ev of subsequentHumanEvents) { - if (!operator && ev.operator) operator = ev.operator; - } - const pendingLines = extractPendingLines(flow); - eHumanComment = formatNumberedHumanOpinions(opinionLines, pendingLines, "reverse"); + } else if (isFlowRejected || (!flow && isRunRejectedInSeal)) { + // No rejectEvent in this run's window, but the current Hose flow state is rejected. + eHumanAction = "审批驳回"; + auditDrift = false; + auditDriftReason = undefined; + const rejInfo = formatRejectionComment(undefined, flow?.rejections?.[0], mar, history); + eHumanComment = rejInfo.comment; + operator = rejInfo.operator; } else { // Flow is actively approving eHumanAction = "⏳ 审批中"; diff --git a/src/domains/seal/approval-runs-export.test.ts b/src/domains/seal/approval-runs-export.test.ts index cf9a47a..b196636 100644 --- a/src/domains/seal/approval-runs-export.test.ts +++ b/src/domains/seal/approval-runs-export.test.ts @@ -267,7 +267,7 @@ describe("exportApprovalRunsToExcel integration", () => { expect(result.rejectReasonCount).toBe(1); expect(existsSync(tmpOut)).toBe(true); - // Verify Excel contents with ExcelJS + // Verify Excel contents with ExcelJS: default export does NOT include E columns (Hose resource optimization) const wb = new ExcelJS.Workbook(); await wb.xlsx.readFile(tmpOut); const ws = wb.worksheets[0]!; @@ -275,20 +275,85 @@ describe("exportApprovalRunsToExcel integration", () => { expect(ws.getRow(1).getCell(1).value).toBe("单据编号"); expect(ws.getRow(1).getCell(9).value).toBe("人工审核"); expect(ws.getRow(1).getCell(10).value).toBe("人工驳回原因"); - expect(ws.getRow(1).getCell(11).value).toBe("E人工行为"); - expect(ws.getRow(1).getCell(12).value).toBe("E人工意见"); + expect(ws.getRow(1).getCell(11).value).toBe("创建时间"); + expect(ws.getRow(1).getCell(12).value).toBe("任务耗时"); expect(ws.getRow(2).getCell(1).value).toBe("B26001"); expect(ws.getRow(2).getCell(9).value).toBe("已支付/审批完成"); expect(ws.getRow(2).getCell(10).value).toBe("-"); - expect(ws.getRow(2).getCell(11).value).toBe("-"); - expect(ws.getRow(2).getCell(12).value).toBe("-"); expect(ws.getRow(3).getCell(1).value).toBe("B26002"); expect(ws.getRow(3).getCell(9).value).toBe("被驳回"); expect(ws.getRow(3).getCell(10).value).toBe("请上传正确的行程单凭据"); - expect(ws.getRow(3).getCell(11).value).toBe("-"); - expect(ws.getRow(3).getCell(12).value).toBe("-"); + } finally { + if (existsSync(tmpOut)) { + rmSync(tmpOut, { force: true }); + } + } + }); + + test("generates excel workbook with E columns when withFlow is true for hose corp", async () => { + const hoseCorp: CorpConfig = { + ...testCorp, + source: { type: "hose", corpId: "corp-hose-1" } as any + }; + + const mockClient = { + get: (url: string) => { + if (url.includes("api/v1/rules")) { + return { + json: async () => ({ + rules: [{ id: "r1", code: 0, description: "发票真实性核验", scope: "全局", strictness: "SHOULD_FOLLOW" }] + }) + }; + } + if (url.includes("api/v1/approvals")) { + return { + json: async () => ({ + total: 1, + records: [ + { + id: "run-h1", + sourceDocumentSN: "B26001", + status: "completed", + taskMode: "assisted", + sourceSystem: "hosecloud", + document: { fields: [] }, + result: { decision: "APPROVE", rulesResult: [] }, + manualApprovalRecord: { + status: { label: "已通过", type: "APPROVED" } + }, + createdAt: 1788760000000, + updatedAt: 1788760030000 + } + ] + }) + }; + } + throw new Error(`Unexpected url: ${url}`); + } + } as any; + + const tmpOut = join(tmpdir(), `test-export-flow-${Date.now()}.xlsx`); + + try { + const result = await exportApprovalRunsToExcel(mockClient, hoseCorp, { + outputFile: tmpOut, + limit: 10, + pageDelayMs: 0, + withFlow: true + }); + + expect(result.recordCount).toBe(1); + const wb = new ExcelJS.Workbook(); + await wb.xlsx.readFile(tmpOut); + const ws = wb.worksheets[0]!; + expect(ws.getRow(1).getCell(1).value).toBe("单据编号"); + expect(ws.getRow(1).getCell(9).value).toBe("人工审核"); + expect(ws.getRow(1).getCell(10).value).toBe("人工驳回原因"); + expect(ws.getRow(1).getCell(11).value).toBe("E人工行为"); + expect(ws.getRow(1).getCell(12).value).toBe("E人工意见"); + expect(ws.getRow(1).getCell(13).value).toBe("创建时间"); } finally { if (existsSync(tmpOut)) { rmSync(tmpOut, { force: true }); diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index d0429c7..8b186ad 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -482,6 +482,8 @@ export async function exportApprovalRunsToExcel( views: [{ state: "frozen", ySplit: 1, xSplit: 2 }] }); + const withFlow = options.withFlow === true && corp.source.type === "hose"; + const baseColumns: Array<{ header: string; key: string; width: number }> = [ { header: "单据编号", key: "sn", width: 16 }, { header: "单据模板名称", key: "templateName", width: 26 }, @@ -493,8 +495,12 @@ export async function exportApprovalRunsToExcel( { header: "思考深度", key: "thinkingDepth", width: 12 }, { header: "人工审核", key: "manualStatus", width: 16 }, { header: "人工驳回原因", key: "humanRejectReason", width: 36 }, - { header: "E人工行为", key: "eHumanAction", width: 18 }, - { header: "E人工意见", key: "eHumanComment", width: 36 }, + ...(withFlow + ? [ + { header: "E人工行为", key: "eHumanAction", width: 18 }, + { header: "E人工意见", key: "eHumanComment", width: 36 } + ] + : []), { header: "创建时间", key: "createdAt", width: 20 }, { header: "任务耗时", key: "duration", width: 12 }, { header: "关联规则数", key: "hitRuleCount", width: 12 }, @@ -705,9 +711,7 @@ export async function exportApprovalRunsToExcel( const mar = (record as any).manualApprovalRecord || {}; const marSourceStatus = String(mar.status?.sourceStatus || ""); let manualStatus = "-"; - if (marSourceStatus === "已支付回调补偿驳回" || marSourceStatus.includes("补偿驳回")) { - manualStatus = "已撤回"; - } else if (mar.status?.label) { + if (mar.status?.label) { manualStatus = String(mar.status.label); } else if (mar.status?.type) { const t = String(mar.status.type); @@ -769,8 +773,12 @@ export async function exportApprovalRunsToExcel( thinkingDepth: "标准", manualStatus, humanRejectReason, - eHumanAction, - eHumanComment, + ...(withFlow + ? { + eHumanAction, + eHumanComment + } + : {}), createdAt: createdAtStr, duration: durationStr, hitRuleCount: hitRuleIds.length, @@ -804,14 +812,33 @@ export async function exportApprovalRunsToExcel( }; if (colNumber <= baseColumns.length) { + const colDef = baseColumns[colNumber - 1]; + const colKey = colDef?.key || ""; + + const isLeftAligned = [ + "sn", + "templateName", + "humanRejectReason", + "eHumanComment", + "hitRulesSummary", + "aiSummary" + ].includes(colKey); + + const isWrapText = [ + "humanRejectReason", + "eHumanComment", + "hitRulesSummary", + "aiSummary" + ].includes(colKey); + cell.alignment = { vertical: "middle", - horizontal: [1, 2, 10, 12, 16, 17].includes(colNumber) ? "left" : "center", - wrapText: [10, 12, 16, 17].includes(colNumber) + horizontal: isLeftAligned ? "left" : "center", + wrapText: isWrapText }; // AI 决策颜色区分 - if (colNumber === 7) { + if (colKey === "aiDecision") { if (val === "通过" || val === "备注通过") cell.font = { color: { argb: "FF16A34A" }, bold: true }; else if (val === "转交复核") cell.font = { color: { argb: "FFD97706" }, bold: true }; else if (val === "驳回") cell.font = { color: { argb: "FFDC2626" }, bold: true }; @@ -819,7 +846,7 @@ export async function exportApprovalRunsToExcel( } // 人工审核高亮 - if (colNumber === 9) { + if (colKey === "manualStatus") { if (val.includes("驳回")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } }; @@ -836,12 +863,12 @@ export async function exportApprovalRunsToExcel( } // 人工驳回原因字体 - if (colNumber === 10 && val !== "-") { + if (colKey === "humanRejectReason" && val !== "-") { cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF991B1B" } }; } // E人工行为高亮 - if (colNumber === 11) { + if (colKey === "eHumanAction") { if (val.includes("⚠️") || val.includes("修改")) { cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFD97706" }, bold: true }; cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } }; @@ -869,7 +896,7 @@ export async function exportApprovalRunsToExcel( } // E人工意见字体 - if (colNumber === 12 && val !== "-") { + if (colKey === "eHumanComment" && val !== "-") { cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF334155" } }; } } else { From 8264865aec2961b50cbf8a947ee8b83f04c13b93 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 09:37:51 +0800 Subject: [PATCH 12/19] Fix isLatestRun cross-period blindspot: detect subsequent ebot/AI runs in Hose history --- src/domains/hose/flow.test.ts | 42 +++++++++++++++++++++++++++++++++++ src/domains/hose/flow.ts | 22 ++++++++++++++++-- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 6e3f1f7..1d74bca 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -1215,5 +1215,47 @@ describe("Hose Flow Domain", () => { "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("财务审批(李四): 发票模糊"); + expect(r.auditDrift).toBe(false); + }); }); }); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index a1bb8a0..90ccfa6 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -965,8 +965,26 @@ export function alignApprovalRunsWithHoseFlow( if (!run) continue; const runTime = Number(run.createdAt) || 0; const nextRun = sortedRuns[i + 1]; - const nextRunTime = nextRun ? Number(nextRun.createdAt) || Infinity : Infinity; - const isLatestRun = i === sortedRuns.length - 1; + let nextRunTime = nextRun ? Number(nextRun.createdAt) || Infinity : Infinity; + let isLatestRun = i === sortedRuns.length - 1; + + // 跨期/分段切片安全防线: + // 若导出时只圈选了局部时间范围(例如横跨3个月的单据只导出了中间某个月),Seal 内存中可能只有单条历史 Run。 + // 我们利用合思全生命周期流水 (flow.history) 反向校验:如果在当前 Run 之后存在后续新的 AI 审批 (isEbot), + // 则直接证明当前 Run 已被后续更新的 AI 轮次所替代,绝非最新终态轮次! + const subsequentEbot = history.find( + (e) => + (e.time ?? 0) > runTime + 5000 && + e.isEbot && + (e.rawAction === "freeflow.agree" || e.action === "智能审批" || e.nodeName?.includes("智能")) + ); + + if (subsequentEbot) { + isLatestRun = false; + if ((subsequentEbot.time ?? Infinity) < nextRunTime) { + nextRunTime = subsequentEbot.time!; + } + } const res = (run.result as Record | undefined) || {}; const rawAiDecision = (res.decision as string | undefined) || (run as Record).aiDecision || "-"; From cfc6ff3b8830d0cc1e81155c1bc20aa31798fc52 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 09:48:26 +0800 Subject: [PATCH 13/19] Anchor AI runs to Hose flow via exact nodeId with 60s queue delay fallback --- src/domains/hose/flow.ts | 49 +++++++++++++++++++++++++++++++-------- src/domains/hose/types.ts | 1 + 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 90ccfa6..70e71c8 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -189,8 +189,16 @@ export function parseHoseTimeline( .map(extractFlowPerson) .filter((p): p is FlowPerson => Boolean(p)); + const nodeId = + typeof attributes.nodeId === "string" && attributes.nodeId + ? attributes.nodeId + : typeof log.nodeId === "string" && log.nodeId + ? log.nodeId + : undefined; + return { id: typeof log.id === "string" ? log.id : undefined, + nodeId, time: currentTime, durationMs, state, @@ -964,6 +972,32 @@ export function alignApprovalRunsWithHoseFlow( const run = sortedRuns[i]; if (!run) continue; const runTime = Number(run.createdAt) || 0; + + const doc = (run.document as Record | undefined) || {}; + const mar = + ((run as Record).manualApprovalRecord as Record | undefined) || + ((run.result as Record | undefined)?.manualApprovalRecord as Record | undefined) || + ((doc as Record).manualApprovalRecord as Record | undefined) || + {}; + + // 1. 强特征 Node ID 锚定:优先从 sourceExtendData.nodeId 或 manualApprovalRecord.nodeId 反查合思真实节点 + const sourceNodeId = + typeof (run.sourceExtendData as Record | undefined)?.nodeId === "string" + ? String((run.sourceExtendData as Record).nodeId) + : undefined; + const rawMarNodeId = typeof mar.nodeId === "string" ? String(mar.nodeId) : undefined; + const decodedMarNodeId = rawMarNodeId + ? decodeURIComponent(rawMarNodeId).replace(/^hcnode_/, "").replace(/_r\d+$/, "") + : undefined; + const targetNodeId = sourceNodeId || decodedMarNodeId; + + const matchedNodeEvent = targetNodeId + ? history.find((e) => e.nodeId && (e.nodeId === targetNodeId || targetNodeId.includes(e.nodeId))) + : undefined; + + // 锚定基准时间:优先采用合思对应节点的真实执行时刻;若无对应节点,放宽多系统排队容差至 60 秒 + const effectiveRunTime = matchedNodeEvent?.time ?? runTime; + const nextRun = sortedRuns[i + 1]; let nextRunTime = nextRun ? Number(nextRun.createdAt) || Infinity : Infinity; let isLatestRun = i === sortedRuns.length - 1; @@ -974,7 +1008,7 @@ export function alignApprovalRunsWithHoseFlow( // 则直接证明当前 Run 已被后续更新的 AI 轮次所替代,绝非最新终态轮次! const subsequentEbot = history.find( (e) => - (e.time ?? 0) > runTime + 5000 && + (e.time ?? 0) > effectiveRunTime + 5000 && e.isEbot && (e.rawAction === "freeflow.agree" || e.action === "智能审批" || e.nodeName?.includes("智能")) ); @@ -1010,12 +1044,6 @@ export function alignApprovalRunsWithHoseFlow( else if (isReject) aiAction = isAutomatic ? "驳回" : "添加评论"; else if (normDecision === "REVIEW" || normDecision === "转交复核") aiAction = "转交复核"; - const doc = (run.document as Record | undefined) || {}; - const mar = - ((run as Record).manualApprovalRecord as Record | undefined) || - (res.manualApprovalRecord as Record | undefined) || - ((doc as Record).manualApprovalRecord as Record | undefined) || - {}; const marStatus = typeof mar.status === "object" && mar.status !== null ? String((mar.status as Record).type || (mar.status as Record).label || "").toUpperCase() @@ -1060,10 +1088,11 @@ export function alignApprovalRunsWithHoseFlow( marStatus === "已驳回" || marStatus === "被驳回"); - // 5-second clock skew tolerance window [runTime - 5000, nextRunTime) + // 容差窗口:若已通过 nodeId 准确锚定,前后仅需 1 秒同步边沿;若未锚定,提供 60 秒跨系统排队与处理缓冲 + const skewToleranceMs = matchedNodeEvent ? 1000 : 60000; const windowEvents = history.filter((e) => { const t = e.time ?? 0; - return t >= runTime - 5000 && t < nextRunTime; + return t >= effectiveRunTime - skewToleranceMs && t < nextRunTime; }); let eHumanAction = "-"; @@ -1074,7 +1103,7 @@ export function alignApprovalRunsWithHoseFlow( // Check for Post-AI Mutation / Audit Drift const isAiApproved = isApprove || isExemptApprove; - const postAiEvents = history.filter((e) => (e.time ?? 0) > runTime + 5000); + const postAiEvents = history.filter((e) => (e.time ?? 0) > effectiveRunTime + 5000); const hasPostAiRetract = postAiEvents.some( (e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回" ); diff --git a/src/domains/hose/types.ts b/src/domains/hose/types.ts index 233bab1..35f5185 100644 --- a/src/domains/hose/types.ts +++ b/src/domains/hose/types.ts @@ -42,6 +42,7 @@ export type FlowPerson = z.infer; export const HoseFlowTimelineEntrySchema = z.object({ id: z.string().optional(), + nodeId: z.string().optional(), time: z.number().optional(), durationMs: z.number().optional(), state: z.string().optional(), From f493d5911b8a7d2e9909ec3d6140b1892b960378 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 09:50:41 +0800 Subject: [PATCH 14/19] Refine subsequent human event filtering to use effectiveRunTime --- src/domains/hose/flow.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 70e71c8..c7a03f6 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -1125,7 +1125,7 @@ export function alignApprovalRunsWithHoseFlow( // Subsequent human events after current AI run in this run's window const subsequentHumanEvents = windowEvents.filter( (e) => - (e.time ?? 0) >= runTime - 1000 && + (e.time ?? 0) >= effectiveRunTime - 1000 && !e.isEbot && e.rawAction !== "freeflow.submit" && e.action !== "提交送审" && From a91f4b5f25a77bfb8d2eaa58bbd8cb47a6353b97 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 10:19:20 +0800 Subject: [PATCH 15/19] Refine Hose flow alignment for rejection targets and mid-flow modifications --- src/domains/hose/flow.test.ts | 128 +++++++++++++- src/domains/hose/flow.ts | 316 ++++++++++++++++++++++++++++------ src/domains/hose/types.ts | 12 +- 3 files changed, 394 insertions(+), 62 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index 1d74bca..aebf63a 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -789,7 +789,9 @@ describe("Hose Flow Domain", () => { const r1 = aligned.get("run-1")!; expect(r1.eHumanAction).toBe("审批驳回"); - expect(r1.eHumanComment).toBe("主管B: 发票不全缺少总经理审批,退回修改"); + expect(r1.eHumanComment).toBe( + "主管B: 发票不全缺少总经理审批,退回修改\n↳ 驳回至: 提交人\n↳ 重新提交后由主管B继续审批" + ); expect(r1.operator?.name).toBe("主管B"); expect(r1.auditDrift).toBe(false); @@ -1059,10 +1061,116 @@ describe("Hose Flow Domain", () => { expect(r.aiDecision).toBe("备注通过"); expect(r.eHumanAction).toBe("审批驳回"); // Node prefix resolved from熊雪倩's approval node in history: 财务助理(熊雪倩): 修改附件 - expect(r.eHumanComment).toBe("财务助理(熊雪倩): 修改附件"); + 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( + "1. 财务助理(熊雪倩): 修改了单据\n2. 上级主管(孙麓): 同意\n3. 财务助理(熊雪倩): 同意\n4. 董事长(甘戈): 同意\n5. 财务经理(周晚容): 同意\n6. CFO(张舒): 同意\n7. 高思琦: 支付成功" + ); + }); }); describe("Pending and end-state handling", () => { @@ -1136,7 +1244,9 @@ describe("Hose Flow Domain", () => { { rawAction: "freeflow.agree", nodeName: "财务助理", operator: { name: "熊雪倩" } } as any ] ); - expect(res1.comment).toBe("财务助理(熊雪倩): 修改附件"); + expect(res1.comment).toBe( + "财务助理(熊雪倩): 修改附件\n↳ 驳回至: 提交人\n↳ 重新提交后由熊雪倩继续审批" + ); expect(res1.operator?.name).toBe("熊雪倩"); const res2 = formatRejectionComment( @@ -1147,14 +1257,18 @@ describe("Hose Flow Domain", () => { reason: "单据超标缺少说明" } as any ); - expect(res2.comment).toBe("财务经理(周晚容): 单据超标缺少说明"); + expect(res2.comment).toBe( + "财务经理(周晚容): 单据超标缺少说明\n↳ 驳回至: 提交人\n↳ 重新提交后由周晚容继续审批" + ); const res3 = formatRejectionComment( undefined, undefined, { nodeName: "合思审批节点", rejectComment: "超额报销" } ); - expect(res3.comment).toBe("超额报销"); + expect(res3.comment).toBe( + "超额报销\n↳ 驳回至: 提交人\n↳ 重新提交后继续审批" + ); expect(res3.comment).not.toContain("合思审批节点"); }); @@ -1254,7 +1368,9 @@ describe("Hose Flow Domain", () => { 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("财务审批(李四): 发票模糊"); + expect(r.eHumanComment).toBe( + "财务审批(李四): 发票模糊\n↳ 驳回至: 提交人\n↳ 重新提交后由李四继续审批" + ); expect(r.auditDrift).toBe(false); }); }); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index c7a03f6..2dfc20b 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -115,7 +115,9 @@ export function formatOperator( export function parseHoseTimeline( rawLogs: unknown[], - staffMap?: Map + staffMap?: Map, + allLogs?: unknown[], + submitterId?: string ): HoseFlowTimelineEntry[] { const logs = Array.isArray(rawLogs) ? rawLogs.filter((l): l is Record => Boolean(l && typeof l === "object")) @@ -123,18 +125,80 @@ export function parseHoseTimeline( const sortedLogs = [...logs].sort((a, b) => (Number(a.time) || 0) - (Number(b.time) || 0)); - return sortedLogs.map((log, index) => { + const resolveStaff = (personId?: string): FlowPerson | undefined => { + if (!personId) return undefined; + const base = extractFlowPerson(personId); + if (!base) return undefined; + if (!base.name && staffMap && base.id) { + const idParts = base.id.split(":"); + const staff = + staffMap.get(base.id) || + (idParts.length > 1 && idParts[1] ? staffMap.get(idParts[1]) : undefined); + if (staff?.name) { + return { + ...base, + name: staff.name, + code: staff.code || base.code + }; + } + } + return base; + }; + + const entries: HoseFlowTimelineEntry[] = []; + + for (let index = 0; index < sortedLogs.length; index++) { + const log = sortedLogs[index]!; const attributes = log.attributes && typeof log.attributes === "object" ? (log.attributes as Record) : {}; const currentTime = typeof log.time === "number" ? log.time : undefined; - const nextLog = sortedLogs[index + 1]; - const nextTime = typeof nextLog?.time === "number" ? nextLog.time : undefined; - const durationMs = - currentTime !== undefined && nextTime !== undefined && nextTime >= currentTime - ? nextTime - currentTime - : undefined; + + // Check for inline document modification log (modifyFlowLog) + if (Array.isArray(log.modifyFlowLog)) { + for (const m of log.modifyFlowLog as Array>) { + if (m && typeof m === "object" && m.operatorState === "UPDATE") { + const modTime = typeof m.operatorTime === "number" ? m.operatorTime : currentTime; + const modOpId = typeof m.operatorId === "string" ? m.operatorId : undefined; + const modPerson = resolveStaff(modOpId); + + let modNodeName = "单据修改"; + if (modOpId && modOpId === submitterId) { + modNodeName = "提交人"; + } else if (Array.isArray(allLogs) && modOpId) { + const matchedAllLog: any = allLogs.find( + (a: any) => + a && + typeof a === "object" && + a.ownerId === modOpId && + typeof a.nodeName === "string" + ); + if (matchedAllLog?.nodeName) { + modNodeName = String(matchedAllLog.nodeName).trim(); + } + } + + entries.push({ + id: typeof m.flowVersionedId === "string" ? `modify-${m.flowVersionedId}` : undefined, + time: modTime, + state: "审批中", + rawState: "MODIFY", + action: "修改了单据", + rawAction: "flow.modify", + nodeName: modNodeName, + comment: "修改了单据", + rawComment: "修改了单据", + automatic: false, + isEbot: false, + skipped: false, + isModification: true, + operator: modPerson, + nextOperators: [] + }); + } + } + } const rawOperator = extractFlowPerson(log.operatorId); const isEbot = isEbotOperator(rawOperator, attributes); @@ -147,17 +211,8 @@ export function parseHoseTimeline( ); let operator = formatOperator(rawOperator, automatic, isEbot); if (operator && !operator.name && staffMap && operator.id) { - const idParts = operator.id.split(":"); - const staff = - staffMap.get(operator.id) || - (idParts.length > 1 && idParts[1] ? staffMap.get(idParts[1]) : undefined); - if (staff?.name) { - operator = { - ...operator, - name: staff.name, - code: staff.code || operator.code - }; - } + const resolved = resolveStaff(operator.id); + if (resolved?.name) operator = resolved; } const rawAction = typeof log.action === "string" ? log.action : undefined; @@ -165,14 +220,101 @@ export function parseHoseTimeline( const rawState = typeof log.state === "string" ? log.state : undefined; const state = translateFlowState(rawState); - const nodeName = - typeof attributes.nodeName === "string" && attributes.nodeName - ? attributes.nodeName - : typeof attributes.nextName === "string" && attributes.nextName - ? attributes.nextName - : action === "打印单据" - ? "打印提醒" - : undefined; + // Node name & Rejection-specific metadata handling + let nodeName: string | undefined; + let rejectTargetNodeName: string | undefined; + let rejectTargetOperator: FlowPerson | undefined; + let resubmitRuleText: string | undefined; + + if (rawAction === "freeflow.reject") { + // 1. Originating node name + let originNode: string | undefined; + if (Array.isArray(allLogs)) { + const match = allLogs.find( + (a: any) => + a && + typeof a === "object" && + a.action === "freeflow.reject" && + (a.ownerId === log.operatorId || + Math.abs((Number(a.updateTime) || 0) - (currentTime || 0)) < 2000) + ); + if (match && typeof (match as any).nodeName === "string") { + originNode = (match as any).nodeName.trim(); + } + } + if (!originNode && attributes.nodeId) { + const match = sortedLogs.find( + (l: any) => + l && + typeof l === "object" && + l.attributes?.nodeId === attributes.nodeId && + l.action !== "freeflow.reject" && + l.attributes?.nodeName + ); + if (match) originNode = String((match as any).attributes.nodeName).trim(); + } + if (!originNode) { + const opId = typeof log.operatorId === "object" ? (log.operatorId as any)?.id : log.operatorId; + const match = sortedLogs.find((l: any) => { + const lOpId = typeof l.operatorId === "object" ? (l.operatorId as any)?.id : l.operatorId; + return lOpId === opId && l.action !== "freeflow.reject" && l.attributes?.nodeName; + }); + if (match) { + originNode = String((match as any).attributes.nodeName).trim(); + } else if (attributes.nodeName && attributes.nodeName !== "提交人") { + originNode = String(attributes.nodeName).trim(); + } + } + nodeName = originNode || "审批节点"; + + // 2. Target node name + rejectTargetNodeName = + typeof attributes.nodeName === "string" && attributes.nodeName + ? attributes.nodeName.trim() + : typeof attributes.nextName === "string" && attributes.nextName + ? attributes.nextName.trim() + : "提交人"; + + // 3. Target operator person + const nextOpId = typeof log.nextOperatorId === "string" ? log.nextOperatorId : undefined; + if (nextOpId) { + rejectTargetOperator = resolveStaff(nextOpId); + } + if ( + (!rejectTargetOperator || !rejectTargetOperator.name) && + (rejectTargetNodeName === "提交人" || rejectTargetNodeName.includes("提交")) && + submitterId + ) { + rejectTargetOperator = resolveStaff(submitterId); + } + + // 4. Resubmit rule text + const method = String(attributes.resubmitMethod || "").toUpperCase(); + const opDisplayName = operator?.name || "原审批人"; + if (method === "TO_REJECTOR") { + resubmitRuleText = `重新提交后由${opDisplayName}继续审批`; + } else if ( + method === "START_OVER" || + method === "TO_START" || + method === "ALL" || + method === "RE_START" + ) { + resubmitRuleText = "重新提交后重新全流程审批"; + } else if (method === "NEXT_NODE") { + resubmitRuleText = "重新提交后流转至下一节点"; + } else { + resubmitRuleText = `重新提交后由${opDisplayName}继续审批`; + } + } else { + nodeName = + typeof attributes.nodeName === "string" && attributes.nodeName + ? attributes.nodeName + : typeof attributes.nextName === "string" && attributes.nextName + ? attributes.nextName + : action === "打印单据" + ? "打印提醒" + : undefined; + } const rawComment = typeof attributes.comment === "string" ? attributes.comment : undefined; const comment = cleanCommentText(rawComment); @@ -186,7 +328,7 @@ export function parseHoseTimeline( ? [log.nextOperatorId] : []; const nextOperators = nextIds - .map(extractFlowPerson) + .map(resolveStaff) .filter((p): p is FlowPerson => Boolean(p)); const nodeId = @@ -196,11 +338,10 @@ export function parseHoseTimeline( ? log.nodeId : undefined; - return { + entries.push({ id: typeof log.id === "string" ? log.id : undefined, nodeId, time: currentTime, - durationMs, state, rawState, action, @@ -212,9 +353,25 @@ export function parseHoseTimeline( isEbot, skipped, operator, - nextOperators - }; - }); + nextOperators, + rejectTargetNodeName, + rejectTargetOperator, + resubmitRuleText, + isModification: false + }); + } + + // Sort all entries (including modification entries) chronologically and compute durations + entries.sort((a, b) => (Number(a.time) || 0) - (Number(b.time) || 0)); + for (let i = 0; i < entries.length; i++) { + const cur = entries[i]!; + const next = entries[i + 1]; + if (cur.time !== undefined && next?.time !== undefined && next.time >= cur.time) { + cur.durationMs = next.time - cur.time; + } + } + + return entries; } export function parseHosePending( @@ -453,7 +610,11 @@ export function extractRejections(history: HoseFlowTimelineEntry[]): HoseRejecti operator: entry.operator, isEbot: entry.isEbot, reason: entry.comment || "未填写驳回原因", - rawComment: entry.rawComment + rawComment: entry.rawComment, + fromNodeName: entry.nodeName, + targetNodeName: entry.rejectTargetNodeName, + targetOperator: entry.rejectTargetOperator, + resubmitRuleText: entry.resubmitRuleText })); } @@ -468,7 +629,13 @@ export function parseHoseOpenComposite( if (!flowDetails) return undefined; const form = (flowDetails.form || {}) as Record; - const history = parseHoseTimeline(flowDetails.logs || [], staffMap); + const submitterId = + typeof form.submitterId === "string" + ? form.submitterId + : typeof flowDetails.ownerId === "string" + ? flowDetails.ownerId + : undefined; + const history = parseHoseTimeline(flowDetails.logs || [], staffMap, allLogs, submitterId); const rawState = flowDetails.state; const state = translateFlowState(rawState); const rawStateUpper = String(rawState || "").toUpperCase(); @@ -724,7 +891,9 @@ export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string : opName; let comment = ev.comment; if (!comment) { - if (ev.rawAction === "freeflow.agree" || ev.action === "审批同意") { + if (ev.rawAction === "flow.modify" || ev.action === "修改了单据" || ev.isModification) { + comment = "修改了单据"; + } else if (ev.rawAction === "freeflow.agree" || ev.action === "审批同意") { comment = "同意"; } else if (ev.rawAction === "freeflow.autoAgree") { comment = "自动同意"; @@ -761,7 +930,10 @@ export function formatNumberedHumanOpinions( } if (mode === "forward") { - const all = [...historyLines, ...pendingLines]; + // If any history line records document modification ("修改了单据"), place all modification lines at the top + const modLines = historyLines.filter((l) => l.includes("修改了单据")); + const normalHistory = historyLines.filter((l) => !l.includes("修改了单据")); + const all = [...modLines, ...normalHistory, ...pendingLines]; return all.map((line, idx) => `${idx + 1}. ${line}`).join("\n"); } @@ -788,13 +960,15 @@ export function formatRejectionComment( rejectEvent?: HoseFlowTimelineEntry, rejectionDetail?: HoseRejectionDetail, mar?: Record, - history?: HoseFlowTimelineEntry[] + history?: HoseFlowTimelineEntry[], + flow?: HoseFlowDetail ): { comment: string; operator?: FlowPerson } { const op = rejectEvent?.operator || rejectionDetail?.operator || (mar as any)?.operator; const opName = op?.name || op?.id || (mar as any)?.operatorName || ""; let rawNodeName = ( rejectEvent?.nodeName || + rejectionDetail?.fromNodeName || rejectionDetail?.nodeName || (mar as any)?.nodeName || "" @@ -810,20 +984,18 @@ export function formatRejectionComment( rawNodeName = ""; } - // In Hose, freeflow.reject often records target node "提交人" (meaning rejected back to submitter) - // If we have an operator name, lookup their actual approval nodeName in history - if ((!rawNodeName || rawNodeName === "提交人") && opName && history) { + // If nodeName is still missing or default, lookup their actual approval nodeName in history + if ((!rawNodeName || rawNodeName === "提交人" || rawNodeName === "审批节点") && opName && history) { const matchedLog = history.find( (h) => h.operator?.name === opName && h.nodeName && h.nodeName.trim() !== "提交人" && - !h.isEbot + !h.isEbot && + h.rawAction !== "freeflow.reject" ); if (matchedLog?.nodeName) { rawNodeName = matchedLog.nodeName.trim(); - } else if (rawNodeName === "提交人") { - rawNodeName = "驳回至提交人"; } } @@ -831,23 +1003,43 @@ export function formatRejectionComment( rejectEvent?.comment || rejectionDetail?.reason || (mar as any)?.rejectComment || - "审批驳回"; + "修改"; - let commentStr = rawComment; + let mainLine = rawComment; if (rawNodeName && opName) { if (!rawComment.startsWith(`${rawNodeName}(${opName}):`)) { - commentStr = `${rawNodeName}(${opName}): ${rawComment}`; + mainLine = `${rawNodeName}(${opName}): ${rawComment}`; } } else if (opName) { if (!rawComment.startsWith(`${opName}:`)) { - commentStr = `${opName}: ${rawComment}`; + mainLine = `${opName}: ${rawComment}`; } } else if (rawNodeName) { if (!rawComment.startsWith(`${rawNodeName}:`)) { - commentStr = `${rawNodeName}: ${rawComment}`; + mainLine = `${rawNodeName}: ${rawComment}`; } } + // Target node & operator + const targetNode = + rejectEvent?.rejectTargetNodeName || + rejectionDetail?.targetNodeName || + "提交人"; + const targetOpName = + rejectEvent?.rejectTargetOperator?.name || + rejectionDetail?.targetOperator?.name || + flow?.submitter?.name; + const targetStr = targetOpName ? `${targetNode}(${targetOpName})` : targetNode; + + // Resubmit rule text + const ruleStr = + rejectEvent?.resubmitRuleText || + rejectionDetail?.resubmitRuleText || + (opName ? `重新提交后由${opName}继续审批` : "重新提交后继续审批"); + + // 样式 2-B(三行展开式,驳回目标与重审规则各占一行) + const commentStr = `${mainLine}\n↳ 驳回至: ${targetStr}\n↳ ${ruleStr}`; + return { comment: commentStr, operator: op @@ -1010,7 +1202,14 @@ export function alignApprovalRunsWithHoseFlow( (e) => (e.time ?? 0) > effectiveRunTime + 5000 && e.isEbot && - (e.rawAction === "freeflow.agree" || e.action === "智能审批" || e.nodeName?.includes("智能")) + (e.nodeName?.includes("智能") || + e.nodeName?.includes("AI") || + e.action?.includes("智能") || + e.comment?.includes("AI") || + e.comment?.includes("approval-result")) && + !e.nodeName?.includes("费用标准检查") && + !e.nodeName?.includes("标准检查") && + !e.nodeName?.includes("预算") ); if (subsequentEbot) { @@ -1147,7 +1346,7 @@ export function alignApprovalRunsWithHoseFlow( eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; - const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history); + const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history, flow); eHumanComment = rejInfo.comment; operator = rejInfo.operator; } else if (retractEvent || isRunCancelledInSeal || (!rejectEvent && marSourceStatus.includes("单据撤回"))) { @@ -1195,11 +1394,20 @@ export function alignApprovalRunsWithHoseFlow( eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; - const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history); + const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history, flow); eHumanComment = rejInfo.comment; operator = rejInfo.operator; } else if (isFlowCompleted || (!flow && isRunApprovedInSeal)) { - eHumanAction = isFlowPaid ? "已支付" : "审批通过"; + const hasModification = windowEvents.some( + (e) => e.rawAction === "flow.modify" || e.isModification || e.action === "修改了单据" + ); + eHumanAction = isFlowPaid + ? hasModification + ? "已支付 (中途修改)" + : "已支付" + : hasModification + ? "审批通过 (中途修改)" + : "审批通过"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); for (const ev of subsequentHumanEvents) { @@ -1251,7 +1459,7 @@ export function alignApprovalRunsWithHoseFlow( eHumanAction = "审批驳回"; auditDrift = false; auditDriftReason = undefined; - const rejInfo = formatRejectionComment(undefined, flow?.rejections?.[0], mar, history); + const rejInfo = formatRejectionComment(undefined, flow?.rejections?.[0], mar, history, flow); eHumanComment = rejInfo.comment; operator = rejInfo.operator; } else { diff --git a/src/domains/hose/types.ts b/src/domains/hose/types.ts index 35f5185..2102002 100644 --- a/src/domains/hose/types.ts +++ b/src/domains/hose/types.ts @@ -56,7 +56,11 @@ export const HoseFlowTimelineEntrySchema = z.object({ isEbot: z.boolean().default(false), skipped: z.boolean().default(false), operator: FlowPersonSchema.optional(), - nextOperators: z.array(FlowPersonSchema).default([]) + nextOperators: z.array(FlowPersonSchema).default([]), + rejectTargetNodeName: z.string().optional(), + rejectTargetOperator: FlowPersonSchema.optional(), + resubmitRuleText: z.string().optional(), + isModification: z.boolean().default(false) }); export type HoseFlowTimelineEntry = z.infer; @@ -98,7 +102,11 @@ export const HoseRejectionDetailSchema = z.object({ operator: FlowPersonSchema.optional(), isEbot: z.boolean().default(false), reason: z.string(), - rawComment: z.string().optional() + rawComment: z.string().optional(), + fromNodeName: z.string().optional(), + targetNodeName: z.string().optional(), + targetOperator: FlowPersonSchema.optional(), + resubmitRuleText: z.string().optional() }); export type HoseRejectionDetail = z.infer; From e3c7f93dd971dd1e945933a3b2417f305ad4faa2 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 10:22:13 +0800 Subject: [PATCH 16/19] Preserve strict flow sequence numbers when hoisting mid-flow modifications --- src/domains/hose/flow.test.ts | 2 +- src/domains/hose/flow.ts | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index aebf63a..c161b13 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -1168,7 +1168,7 @@ describe("Hose Flow Domain", () => { const r = aligned.get("run-2144")!; expect(r.eHumanAction).toBe("已支付 (中途修改)"); expect(r.eHumanComment).toBe( - "1. 财务助理(熊雪倩): 修改了单据\n2. 上级主管(孙麓): 同意\n3. 财务助理(熊雪倩): 同意\n4. 董事长(甘戈): 同意\n5. 财务经理(周晚容): 同意\n6. CFO(张舒): 同意\n7. 高思琦: 支付成功" + "2. 财务助理(熊雪倩): 修改了单据\n1. 上级主管(孙麓): 同意\n3. 财务助理(熊雪倩): 同意\n4. 董事长(甘戈): 同意\n5. 财务经理(周晚容): 同意\n6. CFO(张舒): 同意\n7. 高思琦: 支付成功" ); }); }); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 2dfc20b..79664bc 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -930,11 +930,13 @@ export function formatNumberedHumanOpinions( } if (mode === "forward") { - // If any history line records document modification ("修改了单据"), place all modification lines at the top - const modLines = historyLines.filter((l) => l.includes("修改了单据")); - const normalHistory = historyLines.filter((l) => !l.includes("修改了单据")); - const all = [...modLines, ...normalHistory, ...pendingLines]; - return all.map((line, idx) => `${idx + 1}. ${line}`).join("\n"); + const all = [...historyLines, ...pendingLines]; + const numbered = all.map((line, idx) => `${idx + 1}. ${line}`); + // If any history line records document modification ("修改了单据"), hoist all modification lines to the top + // while strictly preserving each item's true chronological sequence number from the flow + const modLines = numbered.filter((l) => l.includes("修改了单据")); + const normalLines = numbered.filter((l) => !l.includes("修改了单据")); + return [...modLines, ...normalLines].join("\n"); } // Reverse chronological order for in-progress approvals: From 643676afd98dc540af22c2e51bceab3e1e1f65a5 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 10:28:24 +0800 Subject: [PATCH 17/19] Add distinctive emojis for special actions in Hose human opinions --- src/domains/hose/flow.test.ts | 26 ++++++------ src/domains/hose/flow.ts | 80 ++++++++++++++++++++++++++++------- 2 files changed, 78 insertions(+), 28 deletions(-) diff --git a/src/domains/hose/flow.test.ts b/src/domains/hose/flow.test.ts index c161b13..23e1414 100644 --- a/src/domains/hose/flow.test.ts +++ b/src/domains/hose/flow.test.ts @@ -790,7 +790,7 @@ describe("Hose Flow Domain", () => { const r1 = aligned.get("run-1")!; expect(r1.eHumanAction).toBe("审批驳回"); expect(r1.eHumanComment).toBe( - "主管B: 发票不全缺少总经理审批,退回修改\n↳ 驳回至: 提交人\n↳ 重新提交后由主管B继续审批" + "主管B ❌: 发票不全缺少总经理审批,退回修改\n↳ 驳回至: 提交人\n↳ 重新提交后由主管B继续审批" ); expect(r1.operator?.name).toBe("主管B"); expect(r1.auditDrift).toBe(false); @@ -908,7 +908,7 @@ describe("Hose Flow Domain", () => { const r1 = aligned.get("run-retracted")!; expect(r1.eHumanAction).toBe("已撤回"); - expect(r1.eHumanComment).toBe("提交人(刘佳琼): 单据撤回"); + expect(r1.eHumanComment).toBe("提交人(刘佳琼) ↩️: 单据撤回"); expect(r1.auditDrift).toBe(false); const r2 = aligned.get("run-active")!; @@ -956,12 +956,12 @@ describe("Hose Flow Domain", () => { // 1. Agree nodes present with sequence numbers expect(r.eHumanComment).toContain("1. 上级主管(张舒): 同意"); expect(r.eHumanComment).toContain("2. 财务助理(熊雪倩): 同意"); - expect(r.eHumanComment).toContain("3. 部门主管(张舒): 自动同意"); + expect(r.eHumanComment).toContain("3. 部门主管(张舒) 🤖: 自动同意"); // 2. Duplicate comment deduplicated (appears only once) - const matches = r.eHumanComment.match(/高思琦: ETA2026年家庭日费用报销/g); + const matches = r.eHumanComment.match(/高思琦 💬: ETA2026年家庭日费用报销/g); expect(matches?.length).toBe(1); // 3. freeflow.pay mapped to 支付成功 - expect(r.eHumanComment).toContain("5. 高思琦: 支付成功"); + expect(r.eHumanComment).toContain("5. 高思琦 💰: 支付成功"); // 4. freeflow.carbonCopy omitted expect(r.eHumanComment).not.toContain("freeflow.carbonCopy"); expect(r.eHumanComment).not.toContain("抄送单据"); @@ -1062,7 +1062,7 @@ describe("Hose Flow Domain", () => { expect(r.eHumanAction).toBe("审批驳回"); // Node prefix resolved from熊雪倩's approval node in history: 财务助理(熊雪倩): 修改附件 expect(r.eHumanComment).toBe( - "财务助理(熊雪倩): 修改附件\n↳ 驳回至: 提交人\n↳ 重新提交后由熊雪倩继续审批" + "财务助理(熊雪倩) ❌: 修改附件\n↳ 驳回至: 提交人\n↳ 重新提交后由熊雪倩继续审批" ); expect(r.auditDrift).toBe(false); expect(r.operator?.name).toBe("熊雪倩"); @@ -1122,7 +1122,7 @@ describe("Hose Flow Domain", () => { const r = aligned.get("run-2307")!; expect(r.eHumanAction).toBe("审批驳回"); expect(r.eHumanComment).toBe( - "财务经理(周晚容): 修改\n↳ 驳回至: 财务助理(熊雪倩)\n↳ 重新提交后由周晚容继续审批" + "财务经理(周晚容) ❌: 修改\n↳ 驳回至: 财务助理(熊雪倩)\n↳ 重新提交后由周晚容继续审批" ); expect(r.operator?.name).toBe("周晚容"); }); @@ -1168,7 +1168,7 @@ describe("Hose Flow Domain", () => { const r = aligned.get("run-2144")!; expect(r.eHumanAction).toBe("已支付 (中途修改)"); expect(r.eHumanComment).toBe( - "2. 财务助理(熊雪倩): 修改了单据\n1. 上级主管(孙麓): 同意\n3. 财务助理(熊雪倩): 同意\n4. 董事长(甘戈): 同意\n5. 财务经理(周晚容): 同意\n6. CFO(张舒): 同意\n7. 高思琦: 支付成功" + "2. 财务助理(熊雪倩) ✏️: 修改了单据\n1. 上级主管(孙麓): 同意\n3. 财务助理(熊雪倩): 同意\n4. 董事长(甘戈): 同意\n5. 财务经理(周晚容): 同意\n6. CFO(张舒): 同意\n7. 高思琦 💰: 支付成功" ); }); }); @@ -1245,7 +1245,7 @@ describe("Hose Flow Domain", () => { ] ); expect(res1.comment).toBe( - "财务助理(熊雪倩): 修改附件\n↳ 驳回至: 提交人\n↳ 重新提交后由熊雪倩继续审批" + "财务助理(熊雪倩) ❌: 修改附件\n↳ 驳回至: 提交人\n↳ 重新提交后由熊雪倩继续审批" ); expect(res1.operator?.name).toBe("熊雪倩"); @@ -1258,7 +1258,7 @@ describe("Hose Flow Domain", () => { } as any ); expect(res2.comment).toBe( - "财务经理(周晚容): 单据超标缺少说明\n↳ 驳回至: 提交人\n↳ 重新提交后由周晚容继续审批" + "财务经理(周晚容) ❌: 单据超标缺少说明\n↳ 驳回至: 提交人\n↳ 重新提交后由周晚容继续审批" ); const res3 = formatRejectionComment( @@ -1318,7 +1318,7 @@ describe("Hose Flow Domain", () => { const r1 = aligned.get("run-round-1")!; expect(r1.eHumanAction).toBe("已撤回"); expect(r1.eHumanComment).toBe( - "1. 费用类型是研发费(宁艳楠): 同意\n2. 提交人(袁锦): 单据撤回" + "1. 费用类型是研发费(宁艳楠): 同意\n2. 提交人(袁锦) ↩️: 单据撤回" ); expect(r1.eHumanComment).not.toContain("合思审批节点"); expect(r1.eHumanComment).not.toContain("审批驳回"); @@ -1326,7 +1326,7 @@ describe("Hose Flow Domain", () => { const r2 = aligned.get("run-round-2")!; expect(r2.eHumanAction).toBe("已支付"); expect(r2.eHumanComment).toBe( - "1. 费用类型是研发费(宁艳楠): 同意\n2. 财务经理(周晚容): 同意\n3. 高思琦: 支付成功" + "1. 费用类型是研发费(宁艳楠): 同意\n2. 财务经理(周晚容): 同意\n3. 高思琦 💰: 支付成功" ); }); @@ -1369,7 +1369,7 @@ describe("Hose Flow Domain", () => { // Must NOT be falsely labeled as "已支付" just because Hose is currently paid! expect(r.eHumanAction).toBe("审批驳回"); expect(r.eHumanComment).toBe( - "财务审批(李四): 发票模糊\n↳ 驳回至: 提交人\n↳ 重新提交后由李四继续审批" + "财务审批(李四) ❌: 发票模糊\n↳ 驳回至: 提交人\n↳ 重新提交后由李四继续审批" ); expect(r.auditDrift).toBe(false); }); diff --git a/src/domains/hose/flow.ts b/src/domains/hose/flow.ts index 79664bc..6aaef8b 100644 --- a/src/domains/hose/flow.ts +++ b/src/domains/hose/flow.ts @@ -912,7 +912,53 @@ export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string } } - const line = `${nodePrefix}: ${comment}`; + let emoji = ""; + if (ev.rawAction === "flow.modify" || ev.action === "修改了单据" || ev.isModification || comment === "修改了单据") { + emoji = "✏️"; + } else if ( + ev.rawAction === "freeflow.autoAgree" || + ev.action === "自动同意" || + comment === "自动同意" || + ev.automatic + ) { + emoji = "🤖"; + } else if (ev.rawAction === "freeflow.retract" || ev.action === "单据撤回" || comment === "单据撤回") { + emoji = "↩️"; + } else if ( + ev.rawAction === "freeflow.reject" || + ev.action === "审批驳回" || + ev.rawAction === "freeflow.back" || + ev.action === "审批退回" || + comment === "驳回" || + comment === "退回修改" + ) { + emoji = "❌"; + } else if ( + (ev.rawAction === "freeflow.pay" || ev.action === "支付成功" || ev.action === "支付完成") && + (comment === "支付成功" || comment === "支付完成" || !comment) + ) { + emoji = "💰"; + } else if ( + ev.rawAction === "freeflow.addnode" || + ev.action?.includes("加签") || + ev.action?.includes("转交") || + ev.action?.includes("转办") || + comment?.includes("转交") || + comment?.includes("加签") + ) { + emoji = "🔀"; + } else if ( + ev.rawAction === "freeflow.paying" || + ev.rawAction === "freeflow.comment" || + ev.action === "发表评论" || + ev.action === "添加评论" || + (ev.rawAction === "freeflow.pay" && comment !== "支付成功") + ) { + emoji = "💬"; + } + + const emojiPrefix = emoji ? ` ${emoji}` : ""; + const line = `${nodePrefix}${emojiPrefix}: ${comment}`; if (lines.length === 0 || lines[lines.length - 1] !== line) { lines.push(line); } @@ -1007,19 +1053,23 @@ export function formatRejectionComment( (mar as any)?.rejectComment || "修改"; - let mainLine = rawComment; + let cleanComment = rawComment; + if (cleanComment.includes(":")) { + const parts = cleanComment.split(":"); + if (parts.length > 1) { + cleanComment = parts.slice(1).join(":").trim(); + } + } + + let mainLine = cleanComment; if (rawNodeName && opName) { - if (!rawComment.startsWith(`${rawNodeName}(${opName}):`)) { - mainLine = `${rawNodeName}(${opName}): ${rawComment}`; - } + mainLine = `${rawNodeName}(${opName}) ❌: ${cleanComment}`; } else if (opName) { - if (!rawComment.startsWith(`${opName}:`)) { - mainLine = `${opName}: ${rawComment}`; - } + mainLine = `${opName} ❌: ${cleanComment}`; } else if (rawNodeName) { - if (!rawComment.startsWith(`${rawNodeName}:`)) { - mainLine = `${rawNodeName}: ${rawComment}`; - } + mainLine = `${rawNodeName} ❌: ${cleanComment}`; + } else { + mainLine = cleanComment; } // Target node & operator @@ -1363,14 +1413,14 @@ export function alignApprovalRunsWithHoseFlow( if (!operator && ev.operator) operator = ev.operator; } if (retractEvent && !opinionLines.some((l) => l.includes("单据撤回"))) { - opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回`); + opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}) ↩️: 单据撤回`); } eHumanComment = opinionLines.length > 1 ? formatNumberedHumanOpinions(opinionLines, [], "forward") : opinionLines.length === 1 ? opinionLines[0]! - : (retractEvent ? `提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回` : "单据已撤回"); + : (retractEvent ? `提交人(${retractEvent.operator?.name || "提交人"}) ↩️: 单据撤回` : "单据已撤回"); } else { eHumanAction = "已修改重提"; const opinionLines = formatHumanOpinionLines(subsequentHumanEvents); @@ -1448,14 +1498,14 @@ export function alignApprovalRunsWithHoseFlow( if (!operator && ev.operator) operator = ev.operator; } if (retractEvent && !opinionLines.some((l) => l.includes("单据撤回"))) { - opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回`); + opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}) ↩️: 单据撤回`); } eHumanComment = opinionLines.length > 1 ? formatNumberedHumanOpinions(opinionLines, [], "forward") : opinionLines.length === 1 ? opinionLines[0]! - : "单据已撤回"; + : (retractEvent ? `提交人(${retractEvent.operator?.name || "提交人"}) ↩️: 单据撤回` : "单据已撤回"); } else if (isFlowRejected || (!flow && isRunRejectedInSeal)) { // No rejectEvent in this run's window, but the current Hose flow state is rejected. eHumanAction = "审批驳回"; From a7c7ecb0c7886ab5364af77f56d554e87ccc4d98 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 10:36:31 +0800 Subject: [PATCH 18/19] Add target SN export filter and minute timestamp suffix --- src/cli/commands/approval-runs.ts | 12 + src/cli/help.test.ts | 2 +- src/cli/help.ts | 2 +- src/domains/seal/approval-runs-export.test.ts | 17 +- src/domains/seal/approval-runs-export.ts | 290 ++++++++++++------ 5 files changed, 222 insertions(+), 101 deletions(-) diff --git a/src/cli/commands/approval-runs.ts b/src/cli/commands/approval-runs.ts index 3a6ad19..fec4bec 100644 --- a/src/cli/commands/approval-runs.ts +++ b/src/cli/commands/approval-runs.ts @@ -345,7 +345,19 @@ export async function handleApprovalRunsCommand( } if (action === "export") { + const rawSn = + stringOption(args.options.sn) ?? + stringOption(args.options.sns) ?? + stringOption(args.options.sourceDocumentSN); + const snList = rawSn + ? rawSn + .split(/[,;\s]+/) + .map((s) => s.trim()) + .filter(Boolean) + : undefined; + const result = await exportApprovalRunsToExcel(client, corp, { + sns: snList, limit: numberOption(args.options.limit), startDate: stringOption(args.options["start-date"]) ?? diff --git a/src/cli/help.test.ts b/src/cli/help.test.ts index 85bf51e..63e6f61 100644 --- a/src/cli/help.test.ts +++ b/src/cli/help.test.ts @@ -226,7 +226,7 @@ describe("CLI help execution for lifecycle commands", () => { expect(result.exitCode).toBe(0); expect(result.isError).toBe(false); expect(result.stdout).toContain("approval-runs count [--status APPROVED] [--start ] [--end ]"); - expect(result.stdout).toContain("approval-runs export [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only]"); + expect(result.stdout).toContain("approval-runs export [--sn ] [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only]"); }); test("analytics export --help prints force parameter usage", async () => { diff --git a/src/cli/help.ts b/src/cli/help.ts index e600bf1..cffcb7e 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -351,7 +351,7 @@ export const HELP_REGISTRY: AreaHelp[] = [ { name: "export", summary: "Export approval run audit records to Excel workbook. Add --with-flow to include E人工行为 / E人工意见 columns (requires Hose Open API; adds ~30s for large batches).", - usage: ["seal-use approval-runs export [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads|--to-downloads] [--with-flow] [--out ] [--corp ]"] + usage: ["seal-use approval-runs export [--sn ] [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads|--to-downloads] [--with-flow] [--out ] [--corp ]"] }, { name: "flow", diff --git a/src/domains/seal/approval-runs-export.test.ts b/src/domains/seal/approval-runs-export.test.ts index b196636..8a25ef8 100644 --- a/src/domains/seal/approval-runs-export.test.ts +++ b/src/domains/seal/approval-runs-export.test.ts @@ -6,6 +6,7 @@ import ExcelJS from "exceljs"; import { formatDate, formatExportDateTag, + formatExportMinuteTag, getBeijingDate, getBeijingDateFrom, getRuleBriefTitle, @@ -64,21 +65,29 @@ describe("approval-runs-export helpers", () => { }); expect(custom).toBe("/tmp/custom-export.xlsx"); + const fixedTime = new Date("2026-09-15T10:26:00+08:00"); const dl = resolveOutputFilePath({ toDownloads: true, corpName: "大黄蜂", dateTag: "2026-08-07至2026-09-14", - recordCount: 50 + recordCount: 50, + exportTime: fixedTime }); - expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至2026-09-14_50条.xlsx"); + expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至2026-09-14_50条_20260915_1026.xlsx"); const rangeDl = resolveOutputFilePath({ toDownloads: true, corpName: "华铁大黄蜂", dateTag: "2026-08-07至2026-09-13", - recordCount: 9780 + recordCount: 9780, + exportTime: fixedTime }); - expect(rangeDl).toContain("Downloads/华铁大黄蜂_审核记录_2026-08-07至2026-09-13_9780条.xlsx"); + expect(rangeDl).toContain("Downloads/华铁大黄蜂_审核记录_2026-08-07至2026-09-13_9780条_20260915_1026.xlsx"); + }); + + test("formatExportMinuteTag formats in Asia/Shanghai correctly", () => { + const fixedTime = new Date("2026-09-15T10:26:00+08:00"); + expect(formatExportMinuteTag(fixedTime)).toBe("20260915_1026"); }); test("formatDate formats dates, epoch timestamps, and strings cleanly in Asia/Shanghai", () => { diff --git a/src/domains/seal/approval-runs-export.ts b/src/domains/seal/approval-runs-export.ts index 8b186ad..6f8a94b 100644 --- a/src/domains/seal/approval-runs-export.ts +++ b/src/domains/seal/approval-runs-export.ts @@ -32,6 +32,8 @@ export interface ApprovalRunsExportOptions { excludeDeleted?: boolean; taskMode?: string; sourceSystem?: string; + sns?: string[]; + exportTime?: Date; } export interface ApprovalRunsExportResult { @@ -265,12 +267,32 @@ export function getRuleBriefTitle(ruleId: string, desc?: string, scope?: string) return clean.slice(0, 22); } +export function formatExportMinuteTag(date: Date = new Date()): string { + const parts = new Intl.DateTimeFormat("en-CA", { + timeZone: "Asia/Shanghai", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hour12: false + }).formatToParts(date); + const find = (type: string) => parts.find((p) => p.type === type)?.value || ""; + const year = find("year"); + const month = find("month"); + const day = find("day"); + const hour = find("hour"); + const minute = find("minute"); + return `${year}${month}${day}_${hour}${minute}`; +} + export function resolveOutputFilePath(options: { outputFile?: string; toDownloads?: boolean; corpName: string; dateTag?: string; recordCount: number; + exportTime?: Date; }): string { if (options.outputFile) { const p = resolve(options.outputFile); @@ -284,7 +306,8 @@ export function resolveOutputFilePath(options: { const safeCorpName = options.corpName.replace(/[/\\?%*:|"<>]/g, "_").trim() || "审批记录"; const dateTag = options.dateTag || new Date().toISOString().slice(0, 10); const countTag = options.recordCount > 0 ? `${options.recordCount}条` : "空数据"; - const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}.xlsx`; + const timeTag = formatExportMinuteTag(options.exportTime || new Date()); + const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}_${timeTag}.xlsx`; let targetDir: string; if (options.toDownloads) { @@ -310,13 +333,21 @@ export async function exportApprovalRunsToExcel( const pageDelayMs = options.pageDelayMs ?? 250; const limit = options.limit ?? 100000; + const hasExplicitDate = Boolean(options.startDate || options.endDate); + const targetSns = Array.isArray(options.sns) + ? options.sns.map((s) => s.trim()).filter(Boolean) + : []; + const hasTargetSns = targetSns.length > 0; + const targetSnsSet = new Set(targetSns); + const dateRange = resolveExportDateRange({ startDate: options.startDate, endDate: options.endDate, - force: options.force + force: options.force, + silent: !hasExplicitDate && hasTargetSns }); - const startDateTs = dateRange.startDateTs; - const endDateTs = dateRange.endDateTs; + const { startDateTs, endDateTs } = dateRange; + let dateTag = dateRange.dateTag; const manualStatusFilter = normalizeManualApprovalStatus(options.manualApprovalStatus); // 1. 动态加载企业规则集,生成列定义 @@ -349,45 +380,14 @@ export async function exportApprovalRunsToExcel( // 1.5 如果是合思企业且显式启用 withFlow,先探测单据规模并做耗时与频控提示 if (options.withFlow === true && corp.source.type === "hose") { - try { - const probeData = await api.listApprovalRuns(client, { - limit: 1, - startDate: startDateTs, - endDate: endDateTs, - status: options.status, - sourceSystem: options.sourceSystem, - taskMode: options.taskMode, - manualApprovalStatus: manualStatusFilter - }); - const probeTotal = probeData.total ?? probeData.records?.length ?? 0; - const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5)); - const estSeconds = Math.max(1, Math.ceil((probeTotal / concurrency) * 0.4)); - if (probeTotal > 50) { - console.error( - `⚠️ [审批流对齐提示] 目标区间内单据规模约为 ${probeTotal} 笔。系统已启用合思 Open API 保护限流(并发 ${concurrency}),预计审批流拉取耗时约 ${estSeconds} 秒。` - ); - } - } catch { - // ignore probe error - } - } - - // 2. 温和分页拉取单据记录 - const fetchedRecords: ApprovalRun[] = []; - let offset = 0; - let totalAvailable = 0; - let excludedSimulationCount = 0; - let excludedOtherSourceCount = 0; - - while (fetchedRecords.length < limit) { - let batch: ApprovalRunListData | undefined; - let retries = 3; - - while (retries > 0) { + if (hasTargetSns) { + console.error( + `🎯 [单据筛选] 已指定定向筛选单号: [${targetSns.join(", ")}] (共 ${targetSns.length} 个)。` + ); + } else { try { - batch = await api.listApprovalRuns(client, { - limit: pageSize, - offset, + const probeData = await api.listApprovalRuns(client, { + limit: 1, startDate: startDateTs, endDate: endDateTs, status: options.status, @@ -395,68 +395,157 @@ export async function exportApprovalRunsToExcel( taskMode: options.taskMode, manualApprovalStatus: manualStatusFilter }); - break; - } catch (e: any) { - retries--; - console.error(`分页拉取失败 (offset=${offset}): ${e.message},剩余重试 ${retries} 次...`); - if (retries === 0) throw e; - await new Promise((r) => setTimeout(r, 1000)); + const probeTotal = probeData.total ?? probeData.records?.length ?? 0; + const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5)); + const estSeconds = Math.max(1, Math.ceil((probeTotal / concurrency) * 0.4)); + if (probeTotal > 50) { + console.error( + `⚠️ [审批流对齐提示] 目标区间内单据规模约为 ${probeTotal} 笔。系统已启用合思 Open API 保护限流(并发 ${concurrency}),预计审批流拉取耗时约 ${estSeconds} 秒。` + ); + } + } catch { + // ignore probe error } } + } - if (!batch || !batch.records || batch.records.length === 0) break; - totalAvailable = batch.total ?? totalAvailable; + // 2. 温和分页拉取单据记录 + const fetchedRecords: ApprovalRun[] = []; + let excludedSimulationCount = 0; + let excludedOtherSourceCount = 0; - for (const r of batch.records) { - // 过滤测试任务(仅保留真实审批任务) - if (r.taskMode === "simulation") { - excludedSimulationCount++; - continue; - } + if (hasTargetSns && targetSns.length <= 50) { + console.error(`正在定向检索 ${targetSns.length} 个指定单号...`); + for (const sn of targetSns) { + try { + const batch = await api.listApprovalRuns(client, { + search: sn, + limit: 50, + startDate: hasExplicitDate ? startDateTs : undefined, + endDate: hasExplicitDate ? endDateTs : undefined, + status: options.status, + sourceSystem: options.sourceSystem, + taskMode: options.taskMode, + manualApprovalStatus: manualStatusFilter + }); + const matched = (batch.records || []).filter((r) => r.sourceDocumentSN === sn); + for (const r of matched) { + if (r.taskMode === "simulation") { + excludedSimulationCount++; + continue; + } + if (options.taskMode && r.taskMode !== options.taskMode) continue; + if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) { + excludedOtherSourceCount++; + continue; + } + if (options.includeCompletedOnly && r.status !== "completed") continue; - if (options.taskMode && r.taskMode !== options.taskMode) { - continue; - } - - // 如果企业是合思来源,仅拉取合思来源单据 - if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) { - excludedOtherSourceCount++; - continue; - } - - if (options.includeCompletedOnly && r.status !== "completed") { - continue; - } - - // 如果是已完成单据但列表未附带规则结果,做安全补查 - if (r.status === "completed" && (!r.result || !(r.result as any).rulesResult)) { - try { - const full = await api.getApprovalRun(client, r.id); - fetchedRecords.push(full); - } catch { - fetchedRecords.push(r); + if (r.status === "completed" && (!r.result || !(r.result as any).rulesResult)) { + try { + const full = await api.getApprovalRun(client, r.id); + fetchedRecords.push(full); + } catch { + fetchedRecords.push(r); + } + } else { + fetchedRecords.push(r); + } + if (fetchedRecords.length >= limit) break; } - } else { - fetchedRecords.push(r); + } catch (e: any) { + console.error(`⚠️ 定向检索单号 [${sn}] 失败: ${e.message}`); } - if (fetchedRecords.length >= limit) break; } + console.error(`定向检索完成,成功匹配 ${fetchedRecords.length} 条记录。`); + } else { + let offset = 0; + let totalAvailable = 0; - offset += batch.records.length; - const currentProgress = totalAvailable > 0 ? ((offset / totalAvailable) * 100).toFixed(1) : "-"; - if (offset % 500 === 0 || offset >= totalAvailable || fetchedRecords.length >= limit) { - console.error( - `[进度] 已读取单据: ${offset}/${totalAvailable} (${currentProgress}%),有效加入: ${fetchedRecords.length} 条` - ); - } + while (fetchedRecords.length < limit) { + let batch: ApprovalRunListData | undefined; + let retries = 3; - if (batch.records.length < pageSize || offset >= totalAvailable) { - break; - } + while (retries > 0) { + try { + batch = await api.listApprovalRuns(client, { + limit: pageSize, + offset, + startDate: startDateTs, + endDate: endDateTs, + status: options.status, + sourceSystem: options.sourceSystem, + taskMode: options.taskMode, + manualApprovalStatus: manualStatusFilter + }); + break; + } catch (e: any) { + retries--; + console.error(`分页拉取失败 (offset=${offset}): ${e.message},剩余重试 ${retries} 次...`); + if (retries === 0) throw e; + await new Promise((r) => setTimeout(r, 1000)); + } + } - if (pageDelayMs > 0) { - await new Promise((r) => setTimeout(r, pageDelayMs)); + if (!batch || !batch.records || batch.records.length === 0) break; + totalAvailable = batch.total ?? totalAvailable; + + for (const r of batch.records) { + if (hasTargetSns && (!r.sourceDocumentSN || !targetSnsSet.has(r.sourceDocumentSN))) { + continue; + } + + // 过滤测试任务(仅保留真实审批任务) + if (r.taskMode === "simulation") { + excludedSimulationCount++; + continue; + } + + if (options.taskMode && r.taskMode !== options.taskMode) { + continue; + } + + // 如果企业是合思来源,仅拉取合思来源单据 + if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) { + excludedOtherSourceCount++; + continue; + } + + if (options.includeCompletedOnly && r.status !== "completed") { + continue; + } + + // 如果是已完成单据但列表未附带规则结果,做安全补查 + if (r.status === "completed" && (!r.result || !(r.result as any).rulesResult)) { + try { + const full = await api.getApprovalRun(client, r.id); + fetchedRecords.push(full); + } catch { + fetchedRecords.push(r); + } + } else { + fetchedRecords.push(r); + } + + if (fetchedRecords.length >= limit) break; + } + + offset += batch.records.length; + const currentProgress = totalAvailable > 0 ? ((offset / totalAvailable) * 100).toFixed(1) : "-"; + if (offset % 500 === 0 || offset >= totalAvailable || fetchedRecords.length >= limit) { + console.error( + `[进度] 已读取单据: ${offset}/${totalAvailable} (${currentProgress}%),有效加入: ${fetchedRecords.length} 条` + ); + } + + if (batch.records.length < pageSize || offset >= totalAvailable) { + break; + } + + if (pageDelayMs > 0) { + await new Promise((r) => setTimeout(r, pageDelayMs)); + } } } @@ -471,6 +560,18 @@ export async function exportApprovalRunsToExcel( ); } + if (!hasExplicitDate && hasTargetSns && fetchedRecords.length > 0) { + const dates = fetchedRecords + .map((r) => formatDate(r.createdAt || r.updatedAt)) + .filter(Boolean) as string[]; + if (dates.length > 0) { + dates.sort(); + const minDate = dates[0]!; + const maxDate = dates[dates.length - 1]!; + dateTag = minDate === maxDate ? minDate : `${minDate}至${maxDate}`; + } + } + console.error(`成功拉取 ${fetchedRecords.length} 条单据数据,正在生成高保真 Excel...`); // 3. 构建 Excel 工作簿 @@ -918,14 +1019,13 @@ export async function exportApprovalRunsToExcel( } // 4. 保存文件落地 - const dateTag = dateRange.dateTag; - const targetPath = resolveOutputFilePath({ outputFile: options.outputFile, toDownloads: options.toDownloads, corpName, dateTag, - recordCount: exportedRecordCount + recordCount: exportedRecordCount, + exportTime: options.exportTime }); await workbook.xlsx.writeFile(targetPath); From 9e853050985b8c40e128871a0faaf781bd1f6571 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 15 Sep 2026 10:38:54 +0800 Subject: [PATCH 19/19] Update CLI help, skill documentation, and next-step stderr guidance --- skills/seal-use/SKILL.md | 4 +++- skills/seal-use/references/cli.md | 6 ++++-- src/cli/commands/approval-runs.ts | 4 ++++ src/cli/help.ts | 15 ++++++++++++++- 4 files changed, 25 insertions(+), 4 deletions(-) diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 8b1203e..c0a771e 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -88,7 +88,7 @@ seal-use corps list - 规则本地工作流: `seal-use rules pull` 导出草稿规则,`rules lint` 做质量检查,`rules push --dry-run` 预览增量更新,确认后用 `--yes` 写入;`rules map` 查询 `corps sync-test` 生成的跨企业规则映射。规则版本与草稿/发布 code 空间的区别详见 `references/rule-lightweight.md` 和 `references/cli.md`。 - Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud --corp `; read `references/hose-enterprise-deploy.md`. - 审核决策偏好与思考深度: `seal-use preference get --corp `, `preference decision update --json '...' --corp `, `preference thinking-depth set --default --corp `, `preference thinking-depth policies --corp `. -- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp `, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表,默认仅含 Seal 系统字段;追加 `--with-flow` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,需调用合思 Open API,200 条以上单据约增加 30 秒);需要追踪单据时再使用 `url` 或 `bridge`。 +- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] --corp `, `approval-runs count`, `analytics insight|risks|performance|analyze`, 以及 `approval-runs export`(Excel 报表,文件名强制追加精确到分钟的 `_YYYYMMDD_HHmm` 时间戳后缀防止覆盖;支持 `--sn ` 定向筛选极速导出并跳过全量分页;追加 `--with-flow` 可额外输出 **E人工行为** / **E人工意见** 两列——基于合思原生审批流对齐,含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,200 条以上单据约增加 30 秒);需要追踪单据时再使用 `url` 或 `bridge`。 - User-facing 合思 authorization link (合思/易快报授权): `seal-use auth hose-link --corp --expire 7200`; read `references/hose-enterprise-auth.md`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. - Delegation links management: `seal-use delegation list --corp `, `create [--note ...] --corp `, `create --from-link [--note ...]`, `revoke --corp `. - User & Contacts Management (用户搜索、激活与一键代生成授权): `seal-use users search [keyword] --corp `, `users delegation --corp ` (仅适用于 Seal 本地创建的账号 `provider: local`;对合思同步账号系统拒绝重置密码,需改用 `auth hose-link`), `users activate --corp `, `users create --name ... --phone ... --corp `, `users reset-password --corp `, `users get --corp `, `users delete --corp `. @@ -161,6 +161,8 @@ seal-use simulation approval-definitions --corp seal-use approval-runs export --corp --downloads --completed-only # Add --with-flow to also populate E人工行为 / E人工意见 columns (Hose Open API, adds ~30s): seal-use approval-runs export --corp --downloads --with-flow +# Target specific document SNs for instant export without full pagination: +seal-use approval-runs export --corp --sn B26002307,B26002144 --with-flow --downloads seal-use analytics insight --corp seal-use contacts departments --corp seal-use data invoices --corp --limit 20 diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 3aa1fef..23a754b 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -147,8 +147,10 @@ seal-use analytics performance --corp [--start-date ] [--end-da seal-use analytics analyze --corp seal-use analytics export --corp [--downloads] [--out ] [--start-date ] [--end-date ] [--force] seal-use approval-runs count --corp [--status APPROVED] [--start ] [--end ] -seal-use approval-runs export --corp [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads] [--out ] [--with-flow] -# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(默认关闭以节省合思 API 调用) +seal-use approval-runs export --corp [--sn ] [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads] [--out ] [--with-flow] +# --sn / --sns: 定向筛选单据编号(支持逗号/分号/空格分隔,跳过全量分页,秒级定向导出特定单据) +# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,默认关闭以节省合思 API 调用) +# 导出文件名自动追加精确到分钟的 _YYYYMMDD_HHmm 时间戳后缀防止文件覆盖,格式:${企业名称}_审核记录_${时间区间}_${条数}_${导出时间戳}.xlsx seal-use approval-runs search --corp [--query text] [--limit 20] [--includeBridge true] seal-use approval-runs get --corp [--fields metadata|document.fields,result.summary] [--output-file file.json] seal-use approval-runs attachments --corp diff --git a/src/cli/commands/approval-runs.ts b/src/cli/commands/approval-runs.ts index fec4bec..1bfd0a8 100644 --- a/src/cli/commands/approval-runs.ts +++ b/src/cli/commands/approval-runs.ts @@ -397,6 +397,10 @@ export async function handleApprovalRunsCommand( taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]), sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"]) }); + console.error(`👉 查看导出文件: open "${result.filePath}"`); + if (!args.options["with-flow"] && corp.source.type === "hose") { + console.error(`👉 提示: 追加 --with-flow 可额外拉取合思原生审批流,输出 E人工行为 / E人工意见。`); + } printJson(result, outputOptions(args.options)); return; } diff --git a/src/cli/help.ts b/src/cli/help.ts index cffcb7e..855e559 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -351,7 +351,20 @@ export const HELP_REGISTRY: AreaHelp[] = [ { name: "export", summary: "Export approval run audit records to Excel workbook. Add --with-flow to include E人工行为 / E人工意见 columns (requires Hose Open API; adds ~30s for large batches).", - usage: ["seal-use approval-runs export [--sn ] [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads|--to-downloads] [--with-flow] [--out ] [--corp ]"] + usage: ["seal-use approval-runs export [--sn ] [--start ] [--end ] [--force] [--status ] [--manual-status ] [--completed-only] [--limit ] [--downloads|--to-downloads] [--with-flow] [--out ] [--corp ]"], + options: [ + { flag: "--sn, --sns ", description: "Target specific document SNs (comma-separated, e.g. B26002307,B26002144); fast indexed search bypassing full pagination" }, + { flag: "--with-flow", description: "Enrich export with Hose human actions and opinions in E人工行为 / E人工意见 columns (rejection 2-B, mid-flow modifications, action emojis)" }, + { flag: "--start ", description: "Filter records by start date (YYYY-MM-DD or ms timestamp)" }, + { flag: "--end ", description: "Filter records by end date (YYYY-MM-DD or ms timestamp)" }, + { flag: "--force", description: "Force export when time range exceeds 180 days" }, + { flag: "--status ", description: "Filter by system status (e.g. completed, processing)" }, + { flag: "--manual-status ", description: "Filter by manual approval status (e.g. APPROVED, TERMINATED)" }, + { flag: "--completed-only", description: "Only export completed approval runs" }, + { flag: "--limit ", description: "Maximum number of records to export" }, + { flag: "--downloads, --to-downloads", description: "Save exported workbook directly to user's ~/Downloads directory" }, + { flag: "--out ", description: "Custom output file path" } + ] }, { name: "flow",