1012 lines
35 KiB
TypeScript
1012 lines
35 KiB
TypeScript
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) => {
|
||
const stateUpper = String(item.state || "").toUpperCase();
|
||
if (
|
||
stateUpper === "CANCELED" ||
|
||
stateUpper === "CANCELLED" ||
|
||
stateUpper === "PROCESSED" ||
|
||
stateUpper === "COMPLETED" ||
|
||
stateUpper === "PAID"
|
||
) {
|
||
return false;
|
||
}
|
||
return (
|
||
item.logId === -1 ||
|
||
stateUpper === "APPROVING" ||
|
||
stateUpper === "PROCESSING" ||
|
||
stateUpper === "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 rawState = flowDetails.state;
|
||
const state = translateFlowState(rawState);
|
||
const rawStateUpper = String(rawState || "").toUpperCase();
|
||
const isFlowInEndState = [
|
||
"COMPLETED",
|
||
"APPROVED",
|
||
"PAID",
|
||
"REVOKED",
|
||
"CANCELED",
|
||
"CANCELLED",
|
||
"REJECTED"
|
||
].includes(rawStateUpper);
|
||
const pending = isFlowInEndState ? [] : parseHoseOpenPending(allLogs, staffMap);
|
||
|
||
const currentNode = pending.find((p) => p.isCurrent)?.name;
|
||
const metrics = calculateFlowMetrics(
|
||
flowDetails as unknown as Record<string, unknown>,
|
||
history,
|
||
undefined,
|
||
versions
|
||
);
|
||
const staffOpinions = extractStaffOpinions(history);
|
||
const rejections = extractRejections(history);
|
||
|
||
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 rawState =
|
||
typeof raw.state === "string"
|
||
? raw.state
|
||
: typeof flow.state === "string"
|
||
? flow.state
|
||
: undefined;
|
||
const state = translateFlowState(rawState);
|
||
const rawStateUpper = String(rawState || "").toUpperCase();
|
||
const isFlowInEndState = [
|
||
"COMPLETED",
|
||
"APPROVED",
|
||
"PAID",
|
||
"REVOKED",
|
||
"CANCELED",
|
||
"CANCELLED",
|
||
"REJECTED"
|
||
].includes(rawStateUpper);
|
||
const pending = isFlowInEndState ? [] : parseHosePending(plan, currentNode, currentNodeId);
|
||
const metrics = calculateFlowMetrics(flow, history, raw);
|
||
const staffOpinions = extractStaffOpinions(history);
|
||
const rejections = extractRejections(history);
|
||
|
||
const lastAttributes =
|
||
history.at(-1)?.nodeName ??
|
||
(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 formatAiDecision(decision?: string): string {
|
||
if (!decision) return "-";
|
||
const norm = decision.toUpperCase();
|
||
if (norm === "APPROVE" || norm === "通过") return "通过";
|
||
if (norm === "EXEMPT_APPROVE" || norm === "免审通过" || norm === "备注通过") return "备注通过";
|
||
if (norm === "REVIEW" || norm === "转交复核") return "转交复核";
|
||
if (norm === "REJECT" || norm === "驳回") return "驳回";
|
||
if (norm === "ERROR" || norm === "错误") return "错误";
|
||
return decision;
|
||
}
|
||
|
||
export function formatHumanOpinionLines(events: HoseFlowTimelineEntry[]): string[] {
|
||
const lines: string[] = [];
|
||
for (const ev of events) {
|
||
if (
|
||
(ev.rawAction === "freeflow.carbonCopy" ||
|
||
ev.rawAction === "freeflow.cc" ||
|
||
ev.rawAction === "freeflow.print" ||
|
||
ev.action === "打印提醒" ||
|
||
ev.action === "抄送通知") &&
|
||
!ev.comment
|
||
) {
|
||
continue;
|
||
}
|
||
|
||
const opName = ev.operator?.name || ev.operator?.id || "未知";
|
||
const nodePrefix = ev.nodeName?.trim() ? `${ev.nodeName.trim()}(${opName})` : opName;
|
||
let comment = ev.comment;
|
||
if (!comment) {
|
||
if (ev.rawAction === "freeflow.agree" || ev.action === "审批同意") {
|
||
comment = "同意";
|
||
} else if (ev.rawAction === "freeflow.autoAgree") {
|
||
comment = "自动同意";
|
||
} else if (ev.rawAction === "freeflow.pay" || ev.action === "支付完成") {
|
||
comment = "支付完成";
|
||
} else if (ev.rawAction === "freeflow.paying" || ev.action === "支付中") {
|
||
comment = "支付中";
|
||
} else if (ev.rawAction === "freeflow.reject" || ev.action === "审批驳回") {
|
||
comment = "驳回";
|
||
} else if (ev.rawAction === "freeflow.retract" || ev.action === "单据撤回") {
|
||
comment = "单据撤回";
|
||
} else {
|
||
comment = ev.action || "-";
|
||
}
|
||
}
|
||
|
||
const line = `${nodePrefix}: ${comment}`;
|
||
if (lines.length === 0 || lines[lines.length - 1] !== line) {
|
||
lines.push(line);
|
||
}
|
||
}
|
||
return lines;
|
||
}
|
||
|
||
export function alignApprovalRunsWithHoseFlow(
|
||
runs: ApprovalRun[],
|
||
flow?: HoseFlowDetail
|
||
): 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: formatAiDecision(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 rawStateUpper = String(flow.rawState || "").toUpperCase();
|
||
const stateUpper = String(flow.state || "").toUpperCase();
|
||
const isFlowCompleted =
|
||
rawStateUpper === "COMPLETED" ||
|
||
rawStateUpper === "APPROVED" ||
|
||
rawStateUpper === "PAID" ||
|
||
rawStateUpper === "PAYING" ||
|
||
stateUpper === "已完成" ||
|
||
stateUpper === "审批通过" ||
|
||
stateUpper === "已支付" ||
|
||
stateUpper === "支付中";
|
||
|
||
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 isExemptApprove =
|
||
normDecision === "EXEMPT_APPROVE" ||
|
||
normDecision === "免审通过" ||
|
||
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 || isExemptApprove) aiAction = "添加评论";
|
||
else if (isReject) aiAction = isAutomatic ? "驳回" : "添加评论";
|
||
else if (normDecision === "REVIEW" || normDecision === "转交复核") aiAction = "转交复核";
|
||
|
||
const doc = (run.document as Record<string, unknown> | undefined) || {};
|
||
const rawManual =
|
||
(doc.manualApprovalStatus as string | undefined) ||
|
||
(res.manualApprovalStatus as string | undefined) ||
|
||
((run as Record<string, unknown>).manualApprovalStatus as string | undefined);
|
||
const normManual = typeof rawManual === "string" ? rawManual.toUpperCase() : "";
|
||
const isRunCancelledInSeal =
|
||
normManual === "CANCELLED" ||
|
||
normManual === "CANCELED" ||
|
||
normManual === "已取消" ||
|
||
normManual === "已撤回" ||
|
||
normManual === "REVOKED";
|
||
const isRunApprovedInSeal =
|
||
normManual === "APPROVED" ||
|
||
normManual === "已支付/审批完成" ||
|
||
normManual === "已通过" ||
|
||
normManual === "已完成" ||
|
||
normManual === "已支付";
|
||
|
||
// 5-second clock skew tolerance window [runTime - 5000, nextRunTime)
|
||
const windowEvents = history.filter((e) => {
|
||
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 isAiApproved = isApprove || isExemptApprove;
|
||
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 (isAiApproved && 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 in this run's window
|
||
const subsequentHumanEvents = windowEvents.filter(
|
||
(e) =>
|
||
(e.time ?? 0) >= runTime - 1000 &&
|
||
!e.isEbot &&
|
||
e.rawAction !== "freeflow.submit" &&
|
||
e.action !== "提交送审" &&
|
||
!((e.rawAction === "freeflow.comment" || e.action === "发表评论") && !e.comment) &&
|
||
!((e.rawAction === "freeflow.print" || e.action === "打印提醒") && !e.comment) &&
|
||
!(e.rawAction === "freeflow.carbonCopy" || e.rawAction === "freeflow.cc" || e.action === "抄送通知")
|
||
);
|
||
|
||
const retractEvent = subsequentHumanEvents.find(
|
||
(e) => e.rawAction === "freeflow.retract" || e.action === "单据撤回"
|
||
);
|
||
const rejectEvent = subsequentHumanEvents.find(
|
||
(e) => e.rawAction === "freeflow.reject" || e.action === "审批驳回"
|
||
);
|
||
|
||
const isFlowRetractedOrCancelled =
|
||
rawStateUpper === "DRAFT" ||
|
||
rawStateUpper === "REVOKED" ||
|
||
rawStateUpper === "CANCELED" ||
|
||
rawStateUpper === "CANCELLED" ||
|
||
stateUpper === "草稿" ||
|
||
stateUpper === "已撤回" ||
|
||
stateUpper === "已取消";
|
||
|
||
const isFlowRejected =
|
||
rawStateUpper === "REJECTED" ||
|
||
rawStateUpper === "TERMINATED" ||
|
||
stateUpper === "审批驳回" ||
|
||
stateUpper === "已驳回";
|
||
|
||
if (!isLatestRun) {
|
||
// Historical run that has been superseded by a newer run
|
||
if (retractEvent || isRunCancelledInSeal) {
|
||
eHumanAction = "已撤回";
|
||
operator = retractEvent?.operator;
|
||
eHumanComment =
|
||
retractEvent?.comment ||
|
||
(retractEvent ? `${retractEvent.operator?.name || "提交人"}: 单据撤回` : "单据已撤回/取消");
|
||
} else if (rejectEvent) {
|
||
eHumanAction = "驳回";
|
||
operator = rejectEvent.operator;
|
||
eHumanComment = rejectEvent.comment || "驳回";
|
||
} else {
|
||
eHumanAction = "已修改重提";
|
||
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
|
||
for (const ev of subsequentHumanEvents) {
|
||
if (!operator && ev.operator) operator = ev.operator;
|
||
}
|
||
eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "-";
|
||
}
|
||
} else {
|
||
// Latest run for this document
|
||
if (isFlowCompleted || isRunApprovedInSeal) {
|
||
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 = formatHumanOpinionLines(subsequentHumanEvents);
|
||
for (const ev of subsequentHumanEvents) {
|
||
if (!operator && ev.operator) operator = ev.operator;
|
||
}
|
||
|
||
if (opinionLines.length > 0) {
|
||
eHumanComment = opinionLines.join("\n");
|
||
} else {
|
||
const lastHumanApproval = [...windowEvents]
|
||
.reverse()
|
||
.find(
|
||
(e) =>
|
||
!e.isEbot &&
|
||
(e.rawAction === "freeflow.agree" || e.action === "审批同意" || e.rawAction === "freeflow.pay")
|
||
);
|
||
eHumanComment = lastHumanApproval?.comment || "-";
|
||
if (!operator) operator = lastHumanApproval?.operator;
|
||
}
|
||
}
|
||
} else if (isFlowRetractedOrCancelled || (retractEvent && !hasPostAiResubmit) || isRunCancelledInSeal) {
|
||
eHumanAction = "已撤回";
|
||
operator = retractEvent?.operator;
|
||
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
|
||
for (const ev of subsequentHumanEvents) {
|
||
if (!operator && ev.operator) operator = ev.operator;
|
||
}
|
||
if (retractEvent && opinionLines.length === 0) {
|
||
opinionLines.push(`${retractEvent.operator?.name || "提交人"}: 单据撤回`);
|
||
}
|
||
eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "单据已撤回";
|
||
} else if (isFlowRejected || rejectEvent) {
|
||
eHumanAction = "驳回";
|
||
operator = rejectEvent?.operator;
|
||
const rej = flow.rejections?.[0];
|
||
eHumanComment = rejectEvent?.comment || rej?.reason || rej?.nodeName || "审批驳回";
|
||
} else {
|
||
// Flow is still actively approving
|
||
eHumanAction = auditDrift ? "审核中 (⚠️ AI通过后被修改重提)" : "审核中";
|
||
|
||
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
|
||
for (const ev of subsequentHumanEvents) {
|
||
if (!operator && ev.operator) operator = ev.operator;
|
||
}
|
||
|
||
const pendingNodes = flow.pending || [];
|
||
const currentPending = pendingNodes.find((p) => p.isCurrent) || pendingNodes[0];
|
||
if (currentPending) {
|
||
const pApprover =
|
||
currentPending.approver?.name || currentPending.approver?.id || "待定";
|
||
const pNodeName = (currentPending.name || flow.currentNode || "").trim();
|
||
const pPrefix = pNodeName ? `${pNodeName}(${pApprover})` : pApprover;
|
||
opinionLines.push(`${pPrefix}:当前审核节点`);
|
||
} else if (flow.currentNode?.trim()) {
|
||
opinionLines.push(`${flow.currentNode.trim()}:当前审核节点`);
|
||
}
|
||
|
||
eHumanComment = opinionLines.length > 0 ? opinionLines.join("\n") : "当前审核节点";
|
||
}
|
||
}
|
||
}
|
||
|
||
result.set(run.id, {
|
||
recordId: run.id,
|
||
sourceDocumentSN: run.sourceDocumentSN,
|
||
taskMode: run.taskMode,
|
||
aiDecision: formatAiDecision(aiDecisionStr),
|
||
aiAction,
|
||
eHumanAction,
|
||
eHumanComment,
|
||
auditDrift,
|
||
auditDriftReason,
|
||
operator
|
||
});
|
||
}
|
||
|
||
return result;
|
||
}
|