Add Hose approval flow alignment for approval runs export
- 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
This commit is contained in:
1 parent
19c04df1bb
commit
b9ea04adc6
20 files changed
+3088
-11
No files matched your search
@@ -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 <recordId|SN>");
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
+6
-1
@@ -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 <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--out <file>] [--corp <corpId>]"]
|
||||
usage: ["seal-use approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads|--to-downloads] [--with-flow|--no-flow] [--out <file>] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "flow",
|
||||
summary: "Get Hose approval flow timeline, staff opinions, and align with AI runs",
|
||||
usage: ["seal-use approval-runs flow <recordId|SN> [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "list",
|
||||
|
||||
@@ -357,7 +357,7 @@ export async function fetchHoseCloseApiToken(
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
|
||||
export async function ensureHoseCloseApiToken(corp: CorpConfig): Promise<TokenEntry> {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -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<string, string>
|
||||
): Promise<KyInstance> {
|
||||
return createHoseOpenClient(corp, customHeaders);
|
||||
}
|
||||
@@ -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<RawHoseBacklogItem[]> {
|
||||
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<Record<string, unknown> | 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<string> {
|
||||
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<string, unknown>) : {};
|
||||
const form = flow.form && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : {};
|
||||
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<Record<string, unknown> | undefined> {
|
||||
const backlogId = await resolveCloseBacklogId(client, corpId, target);
|
||||
return getCloseBacklogDetailById(client, corpId, backlogId);
|
||||
}
|
||||
@@ -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<string, string> {
|
||||
return {
|
||||
accesstoken: credentials.accessToken,
|
||||
corpid: credentials.corpId,
|
||||
staffid: credentials.staffId
|
||||
};
|
||||
}
|
||||
|
||||
export function createHoseCloseClientWithCredentials(
|
||||
credentials: HoseCloseClientCredentials,
|
||||
customHeaders?: Record<string, string>
|
||||
): 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<string, string>
|
||||
): Promise<KyInstance> {
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./types.js";
|
||||
export * from "./client.js";
|
||||
export * from "./api.js";
|
||||
@@ -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<typeof RawHoseBacklogItemSchema>;
|
||||
|
||||
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<typeof RawHoseBacklogSearchResponseSchema>;
|
||||
|
||||
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<typeof RawHoseBacklogDetailResponseSchema>;
|
||||
@@ -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("<p>发票缺失,<strong>请补充餐饮发票原件</strong>后重提</p>")).toBe(
|
||||
"发票缺失,请补充餐饮发票原件后重提"
|
||||
);
|
||||
expect(
|
||||
cleanCommentText("<p>意见:"同意" & 抄送<财务>'s 部门 </p>")
|
||||
).toBe("意见:\"同意\" & 抄送<财务>'s 部门");
|
||||
expect(cleanCommentText("")).toBeUndefined();
|
||||
expect(cleanCommentText("<p> </p>")).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: "<p>申请出差报销</p>" }
|
||||
},
|
||||
{
|
||||
id: "log-2",
|
||||
time: 1788201000000,
|
||||
action: "freeflow.agree",
|
||||
state: "APPROVED",
|
||||
operatorId: { id: "staff-bob", name: "Bob", code: "B01" },
|
||||
attributes: { nodeName: "主管审批", comment: "<p>同意报销</p>" }
|
||||
},
|
||||
{
|
||||
id: "log-3",
|
||||
time: 1788201500000,
|
||||
action: "freeflow.agree",
|
||||
state: "APPROVED",
|
||||
operatorId: { id: "staff-ebot", name: "Ebot" },
|
||||
attributes: { isEbotNode: true, nodeName: "AI发票风控", comment: "<p>发票合规通过</p>" }
|
||||
}
|
||||
],
|
||||
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: "<p>金额超标,<strong>缺少招待人员清单</strong>,请补充后重提</p>"
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "log-3",
|
||||
time: 1788302000000,
|
||||
action: "freeflow.submit",
|
||||
state: "SUBMITTED",
|
||||
operatorId: { id: "user-1", name: "张三" },
|
||||
attributes: { nodeName: "补充重提", comment: "<p>已补充招待名单</p>" }
|
||||
},
|
||||
{
|
||||
id: "log-4",
|
||||
time: 1788303000000,
|
||||
action: "freeflow.agree",
|
||||
state: "APPROVED",
|
||||
operatorId: { id: "manager-1", name: "王经理" },
|
||||
attributes: { nodeName: "主管审批", comment: "<p>复核无误,通过</p>" }
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
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(
|
||||
"<p>金额超标,<strong>缺少招待人员清单</strong>,请补充后重提</p>"
|
||||
);
|
||||
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: "<p>发票模糊无法查验,驳回</p>"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
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: "<p>发现报销费用归属部门选错,撤回修改</p>" }
|
||||
},
|
||||
{
|
||||
id: "log-3",
|
||||
time: 1788402000000,
|
||||
action: "freeflow.submit",
|
||||
state: "SUBMITTED",
|
||||
operatorId: { id: "user-1", name: "李雷" },
|
||||
attributes: { nodeName: "重新提交", comment: "<p>已修改部门,重新提交</p>" }
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
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<string, unknown> | 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<string, unknown> | 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通过后单据发生撤回/修改重提");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
if (obj.signerId && typeof obj.signerId === "object") {
|
||||
obj = obj.signerId as Record<string, unknown>;
|
||||
}
|
||||
|
||||
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<string, unknown>
|
||||
): 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<string, HoseOpenStaffItem>
|
||||
): HoseFlowTimelineEntry[] {
|
||||
const logs = Array.isArray(rawLogs)
|
||||
? rawLogs.filter((l): l is Record<string, unknown> => 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<string, unknown>)
|
||||
: {};
|
||||
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<string, unknown>,
|
||||
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<string, unknown>) : {};
|
||||
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<string, HoseOpenStaffItem>
|
||||
): 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<string, unknown>,
|
||||
history: HoseFlowTimelineEntry[],
|
||||
rawBacklog?: Record<string, unknown>,
|
||||
versions?: HoseOpenVersionedItem[]
|
||||
): HoseFlowMetrics {
|
||||
const form =
|
||||
flow.form && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : {};
|
||||
|
||||
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<string, unknown>;
|
||||
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<string, unknown>,
|
||||
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<string, unknown>;
|
||||
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<string, unknown>
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses raw CloseAPI payload (hose-close) into unified HoseFlowDetail.
|
||||
*/
|
||||
export function parseHoseFlow(
|
||||
raw: Record<string, unknown>,
|
||||
fallbackTarget?: string
|
||||
): HoseFlowDetail {
|
||||
const flow =
|
||||
raw.flowId && typeof raw.flowId === "object"
|
||||
? (raw.flowId as Record<string, unknown>)
|
||||
: raw;
|
||||
const form =
|
||||
flow.form && typeof flow.form === "object"
|
||||
? (flow.form as Record<string, unknown>)
|
||||
: {};
|
||||
const nodeState =
|
||||
raw.nodeState && typeof raw.nodeState === "object"
|
||||
? (raw.nodeState as Record<string, unknown>)
|
||||
: {};
|
||||
const plan =
|
||||
flow.plan && typeof flow.plan === "object"
|
||||
? (flow.plan as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
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<string, unknown>)?.attributes
|
||||
: undefined);
|
||||
const resolvedCurrentNode =
|
||||
currentNode ??
|
||||
(lastAttributes && typeof lastAttributes === "object"
|
||||
? (lastAttributes as Record<string, unknown>).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<string, unknown>;
|
||||
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<string, HoseOpenStaffItem>
|
||||
): Promise<HoseFlowDetail | undefined> {
|
||||
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<HoseFlowDetail | undefined> {
|
||||
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<string, HoseOpenStaffItem>
|
||||
): Promise<HoseFlowDetail | undefined> {
|
||||
const flowId = targetOrFlowId ?? targetOrCorpId;
|
||||
return getHoseOpenFlow(client, flowId, staffCache);
|
||||
}
|
||||
|
||||
export function alignApprovalRunsWithHoseFlow(
|
||||
runs: ApprovalRun[],
|
||||
flow?: HoseFlowDetail
|
||||
): Map<string, HoseRunAlignment> {
|
||||
const result = new Map<string, HoseRunAlignment>();
|
||||
if (!runs || runs.length === 0) return result;
|
||||
|
||||
if (!flow) {
|
||||
for (const run of runs) {
|
||||
const res = (run.result as Record<string, unknown> | undefined) || {};
|
||||
const aiDecision = (res.decision as string | undefined) || (run as Record<string, unknown>).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<string, unknown> | undefined) || {};
|
||||
const rawAiDecision = (res.decision as string | undefined) || (run as Record<string, unknown>).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;
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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<HoseOpenFlowDetailsValue | undefined> {
|
||||
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<HoseOpenAllLogsItem[]> {
|
||||
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<HoseOpenVersionedItem[]> {
|
||||
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<HoseOpenStaffItem[]> {
|
||||
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<string, HoseOpenStaffItem>
|
||||
): Promise<HoseOpenCompositeData> {
|
||||
const [flowDetails, allLogs, versions] = await Promise.all([
|
||||
fetchHoseOpenFlowDetails(client, flowId),
|
||||
fetchHoseOpenAllLogs(client, flowId).catch(() => []),
|
||||
fetchHoseOpenVersioned(client, flowId).catch(() => [])
|
||||
]);
|
||||
|
||||
const staffMap = staffCache ?? new Map<string, HoseOpenStaffItem>();
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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<string, string>
|
||||
): 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<string, string>
|
||||
): Promise<KyInstance> {
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./types.js";
|
||||
export * from "./client.js";
|
||||
export * from "./api.js";
|
||||
@@ -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<typeof HoseOpenFlowLogAttributeSchema>;
|
||||
|
||||
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<typeof HoseOpenFlowLogSchema>;
|
||||
|
||||
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<typeof HoseOpenFormDetailSchema>;
|
||||
|
||||
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<typeof HoseOpenFlowDetailsValueSchema>;
|
||||
|
||||
export const HoseOpenFlowDetailsResponseSchema = z
|
||||
.object({
|
||||
value: z.preprocess((v) => (v === null ? undefined : v), HoseOpenFlowDetailsValueSchema.optional())
|
||||
})
|
||||
.passthrough();
|
||||
export type HoseOpenFlowDetailsResponse = z.infer<typeof HoseOpenFlowDetailsResponseSchema>;
|
||||
|
||||
// --- 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<typeof HoseOpenAllLogsItemSchema>;
|
||||
|
||||
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<typeof HoseOpenAllLogsResponseSchema>;
|
||||
|
||||
// --- 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<typeof HoseOpenVersionedItemSchema>;
|
||||
|
||||
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<typeof HoseOpenVersionedResponseSchema>;
|
||||
|
||||
// --- Hose OpenAPI Composite Result ---
|
||||
|
||||
export interface HoseOpenCompositeData {
|
||||
flowDetails?: HoseOpenFlowDetailsValue;
|
||||
allLogs: HoseOpenAllLogsItem[];
|
||||
versions: HoseOpenVersionedItem[];
|
||||
staffMap?: Map<string, HoseOpenStaffItem>;
|
||||
}
|
||||
|
||||
// --- 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<typeof HoseOpenStaffItemSchema>;
|
||||
|
||||
export const HoseOpenStaffResponseSchema = z
|
||||
.object({
|
||||
items: z.preprocess((v) => (Array.isArray(v) ? v : []), z.array(HoseOpenStaffItemSchema)).default([])
|
||||
})
|
||||
.passthrough();
|
||||
export type HoseOpenStaffResponse = z.infer<typeof HoseOpenStaffResponseSchema>;
|
||||
|
||||
export interface HoseOpenStaffQueryOptions {
|
||||
type: "STAFFID" | "CODE" | "CELLPHONE" | "MAIL" | "USERID";
|
||||
conditionIds: string[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const HOSE_FLOW_ACTION_LABELS: Record<string, string> = {
|
||||
"freeflow.submit": "提交送审",
|
||||
"freeflow.agree": "审批同意",
|
||||
"freeflow.autoAgree": "自动同意",
|
||||
"freeflow.reject": "审批驳回",
|
||||
"freeflow.print": "打印单据",
|
||||
"freeflow.retract": "单据撤回",
|
||||
"freeflow.addnode": "加签/转交",
|
||||
"freeflow.comment": "发表评论"
|
||||
};
|
||||
|
||||
export const HOSE_FLOW_STATE_LABELS: Record<string, string> = {
|
||||
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<typeof FlowPersonSchema>;
|
||||
|
||||
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<typeof HoseFlowTimelineEntrySchema>;
|
||||
|
||||
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<typeof HoseFlowPendingNodeSchema>;
|
||||
|
||||
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<typeof HoseFlowMetricsSchema>;
|
||||
|
||||
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<typeof HoseStaffOpinionSchema>;
|
||||
|
||||
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<typeof HoseRejectionDetailSchema>;
|
||||
|
||||
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<typeof HoseFlowDetailSchema>;
|
||||
|
||||
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<typeof RawHoseBacklogItemSchema>;
|
||||
|
||||
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<typeof RawHoseBacklogSearchResponseSchema>;
|
||||
|
||||
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<typeof RawHoseBacklogDetailResponseSchema>;
|
||||
|
||||
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<typeof HoseRunAlignmentSchema>;
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<string, number> = {};
|
||||
let rejectReasonCount = 0;
|
||||
let driftCount = 0;
|
||||
|
||||
// 3.5 如果是合思租户且未显式关闭 withFlow,获取原生审批流并对齐真实人工行为与意见
|
||||
const alignmentsByRecordId = new Map<string, HoseRunAlignment>();
|
||||
const deletedSNs = new Set<string>();
|
||||
const excludeDeleted = options.excludeDeleted ?? true;
|
||||
|
||||
if (options.withFlow !== false && corp.source.type === "hose") {
|
||||
try {
|
||||
const runsByDocKey = new Map<string, ApprovalRun[]>();
|
||||
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<string, HoseOpenStaffItem>();
|
||||
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<string, any> = {
|
||||
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
|
||||
};
|
||||
}
|
||||
@@ -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 引用或命中的规则及应用分析",
|
||||
|
||||
Reference in new issue
Block a user