Files
seal-use/src/domains/hose/flow.ts
T

1231 lines
42 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, "\"")
.replace(/&#39;/g, "'")
.replace(/&nbsp;/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.action === "抄送单据" ||
ev.action === "抄送通知"
) {
continue;
}
if (
(ev.rawAction === "freeflow.print" || ev.action === "打印提醒" || ev.action === "打印单据") &&
!ev.comment
) {
continue;
}
const opName = ev.operator?.name || ev.operator?.id || "未知";
// freeflow.retract has no nodeName in Hose; the actor is always the submitter
const isRetractAction = ev.rawAction === "freeflow.retract" || ev.action === "单据撤回";
const nodePrefix = ev.nodeName?.trim()
? `${ev.nodeName.trim()}(${opName})`
: isRetractAction
? `提交人(${opName})`
: opName;
let comment = ev.comment;
if (!comment) {
if (ev.rawAction === "freeflow.agree" || ev.action === "审批同意") {
comment = "同意";
} else if (ev.rawAction === "freeflow.autoAgree") {
comment = "自动同意";
} else if (ev.rawAction === "freeflow.pay" || ev.action === "支付成功" || ev.action === "支付完成") {
comment = "支付成功";
} else if (ev.rawAction === "freeflow.paying" || ev.action === "发起支付" || ev.action === "支付中") {
comment = "发起支付";
} else if (ev.rawAction === "freeflow.reject" || ev.action === "审批驳回") {
comment = "驳回";
} else if (ev.rawAction === "freeflow.back" || ev.action === "审批退回") {
comment = "退回修改";
} else if (ev.rawAction === "freeflow.retract" || ev.action === "单据撤回") {
comment = "单据撤回";
} else {
comment = ev.action || "-";
}
}
const line = `${nodePrefix}: ${comment}`;
if (lines.length === 0 || lines[lines.length - 1] !== line) {
lines.push(line);
}
}
return lines;
}
export function formatNumberedHumanOpinions(
historyLines: string[],
pendingLines: string[] = [],
mode: "forward" | "reverse" = "forward"
): string {
if (historyLines.length === 0 && pendingLines.length === 0) {
return "-";
}
if (mode === "forward") {
const all = [...historyLines, ...pendingLines];
return all.map((line, idx) => `${idx + 1}. ${line}`).join("\n");
}
// Reverse chronological order for in-progress approvals:
// Pending node(s) appear at the top with badge (e.g. ⏳ 7. 出纳支付(高思琦): 待支付),
// followed by history approvals in reverse order (e.g. 6. CFO, 5. 财务经理...)
const result: string[] = [];
pendingLines.forEach((line, idx) => {
const seq = historyLines.length + idx + 1;
const badge = idx === 0 ? "⏳ " : "";
result.push(`${badge}${seq}. ${line}`);
});
for (let i = historyLines.length - 1; i >= 0; i--) {
const seq = i + 1;
result.push(`${seq}. ${historyLines[i]}`);
}
return result.join("\n");
}
export function formatRejectionComment(
rejectEvent?: HoseFlowTimelineEntry,
rejectionDetail?: HoseRejectionDetail,
mar?: Record<string, unknown>,
history?: HoseFlowTimelineEntry[]
): { comment: string; operator?: FlowPerson } {
const op = rejectEvent?.operator || rejectionDetail?.operator || (mar as any)?.operator;
const opName = op?.name || op?.id || (mar as any)?.operatorName || "";
let rawNodeName = (
rejectEvent?.nodeName ||
rejectionDetail?.nodeName ||
(mar as any)?.nodeName ||
""
).trim();
// Strip Seal's synthetic wrapper node names (never output "合思审批节点" to user)
if (
rawNodeName === "合思审批节点" ||
rawNodeName === "外部审批节点" ||
rawNodeName.includes("合思审批") ||
rawNodeName.includes("外部审批")
) {
rawNodeName = "";
}
// In Hose, freeflow.reject often records target node "提交人" (meaning rejected back to submitter)
// If we have an operator name, lookup their actual approval nodeName in history
if ((!rawNodeName || rawNodeName === "提交人") && opName && history) {
const matchedLog = history.find(
(h) =>
h.operator?.name === opName &&
h.nodeName &&
h.nodeName.trim() !== "提交人" &&
!h.isEbot
);
if (matchedLog?.nodeName) {
rawNodeName = matchedLog.nodeName.trim();
} else if (rawNodeName === "提交人") {
rawNodeName = "驳回至提交人";
}
}
const rawComment =
rejectEvent?.comment ||
rejectionDetail?.reason ||
(mar as any)?.rejectComment ||
"审批驳回";
let commentStr = rawComment;
if (rawNodeName && opName) {
if (!rawComment.startsWith(`${rawNodeName}(${opName}):`)) {
commentStr = `${rawNodeName}(${opName}): ${rawComment}`;
}
} else if (opName) {
if (!rawComment.startsWith(`${opName}:`)) {
commentStr = `${opName}: ${rawComment}`;
}
} else if (rawNodeName) {
if (!rawComment.startsWith(`${rawNodeName}:`)) {
commentStr = `${rawNodeName}: ${rawComment}`;
}
}
return {
comment: commentStr,
operator: op
};
}
export function extractPendingLines(flow?: HoseFlowDetail): string[] {
if (!flow) return [];
const pendingNodes = flow.pending || [];
const rawStateUpper = String(flow.rawState || "").toUpperCase();
const stateUpper = String(flow.state || "").toUpperCase();
const lines: string[] = [];
if (pendingNodes.length > 0) {
for (const p of pendingNodes) {
const pApprover = p.approver?.name || p.approver?.id || "待定";
const pNodeName = (p.name || flow.currentNode || "").trim();
const pPrefix = pNodeName ? `${pNodeName}(${pApprover})` : pApprover;
const isPayment =
p.type?.toUpperCase() === "PAYING" ||
pNodeName.includes("支付") ||
rawStateUpper === "PAYING" ||
stateUpper === "支付中";
const actionText = isPayment ? "待支付" : "待审批";
lines.push(`${pPrefix}: ${actionText}`);
}
} else if (flow.currentNode?.trim()) {
const isPayment =
flow.currentNode.includes("支付") ||
rawStateUpper === "PAYING" ||
stateUpper === "支付中";
const actionText = isPayment ? "待支付" : "待审批";
lines.push(`${flow.currentNode.trim()}: ${actionText}`);
}
return lines;
}
export function alignApprovalRunsWithHoseFlow(
runs: ApprovalRun[],
flow?: HoseFlowDetail
): 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 isFlowRetractedOrCancelled =
rawStateUpper === "DRAFT" ||
rawStateUpper === "REVOKED" ||
rawStateUpper === "CANCELED" ||
rawStateUpper === "CANCELLED" ||
stateUpper === "草稿" ||
stateUpper === "已撤回" ||
stateUpper === "已取消";
const isFlowRejected =
rawStateUpper === "REJECTED" ||
rawStateUpper === "TERMINATED" ||
stateUpper === "审批驳回" ||
stateUpper === "已驳回";
const isFlowPaid =
!isFlowRetractedOrCancelled &&
!isFlowRejected &&
(rawStateUpper === "PAID" ||
stateUpper === "已支付" ||
history.some(
(e) =>
!e.isEbot &&
(e.rawAction === "freeflow.pay" || e.action === "支付成功" || e.action === "支付完成")
));
const isFlowPaying =
!isFlowRetractedOrCancelled &&
!isFlowRejected &&
!isFlowPaid &&
(rawStateUpper === "PAYING" ||
stateUpper === "支付中" ||
(flow.pending || []).some(
(p) =>
p.isCurrent &&
(p.type?.toUpperCase() === "PAYING" || p.name?.includes("支付"))
) ||
flow.currentNode?.includes("支付") === true);
const isFlowApproved =
!isFlowRetractedOrCancelled &&
!isFlowRejected &&
!isFlowPaying &&
(rawStateUpper === "COMPLETED" ||
rawStateUpper === "APPROVED" ||
stateUpper === "已完成" ||
stateUpper === "审批通过");
const isFlowCompleted = isFlowPaid || isFlowApproved;
for (let i = 0; i < sortedRuns.length; i++) {
const run = sortedRuns[i];
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 mar =
((run as Record<string, unknown>).manualApprovalRecord as Record<string, unknown> | undefined) ||
(res.manualApprovalRecord as Record<string, unknown> | undefined) ||
((doc as Record<string, unknown>).manualApprovalRecord as Record<string, unknown> | undefined) ||
{};
const marStatus =
typeof mar.status === "object" && mar.status !== null
? String((mar.status as Record<string, unknown>).type || (mar.status as Record<string, unknown>).label || "").toUpperCase()
: "";
const marSourceStatus =
typeof mar.status === "object" && mar.status !== null
? String((mar.status as Record<string, unknown>).sourceStatus || "")
: "";
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" ||
marStatus === "CANCELLED" ||
marStatus === "CANCELED" ||
marSourceStatus.includes("撤回") ||
marSourceStatus.includes("取消");
const isRunApprovedInSeal =
normManual === "APPROVED" ||
normManual === "已支付/审批完成" ||
normManual === "已通过" ||
normManual === "已完成" ||
normManual === "已支付" ||
marStatus === "APPROVED";
const isRunCompensation =
marSourceStatus.includes("补偿") || marSourceStatus.includes("已支付");
const isRunRejectedInSeal =
!isRunCompensation &&
(normManual === "TERMINATED" ||
normManual === "REJECTED" ||
normManual === "REJECT" ||
normManual === "已驳回" ||
normManual === "被驳回" ||
marStatus === "TERMINATED" ||
marStatus === "REJECTED" ||
marStatus === "已驳回" ||
marStatus === "被驳回");
// 5-second clock skew tolerance window [runTime - 5000, nextRunTime)
const windowEvents = history.filter((e) => {
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 === "审批驳回"
);
if (!isLatestRun) {
// Historical run that has been superseded by a newer run
if (rejectEvent || (!flow && isRunRejectedInSeal)) {
eHumanAction = "审批驳回";
auditDrift = false;
auditDriftReason = undefined;
const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history);
eHumanComment = rejInfo.comment;
operator = rejInfo.operator;
} else if (retractEvent || isRunCancelledInSeal || (!rejectEvent && marSourceStatus.includes("单据撤回"))) {
eHumanAction = "已撤回";
operator = retractEvent?.operator;
// Events belonging to this run only occur up to the retract event
const runEvents = retractEvent
? subsequentHumanEvents.filter((e) => (e.time ?? 0) <= (retractEvent.time ?? Infinity))
: subsequentHumanEvents;
const opinionLines = formatHumanOpinionLines(runEvents);
for (const ev of runEvents) {
if (!operator && ev.operator) operator = ev.operator;
}
if (retractEvent && !opinionLines.some((l) => l.includes("单据撤回"))) {
opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回`);
}
eHumanComment =
opinionLines.length > 1
? formatNumberedHumanOpinions(opinionLines, [], "forward")
: opinionLines.length === 1
? opinionLines[0]!
: (retractEvent ? `提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回` : "单据已撤回");
} else {
eHumanAction = "已修改重提";
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
for (const ev of subsequentHumanEvents) {
if (!operator && ev.operator) operator = ev.operator;
}
eHumanComment =
opinionLines.length > 1
? formatNumberedHumanOpinions(opinionLines, [], "forward")
: opinionLines.length === 1
? opinionLines[0]!
: "-";
}
} else {
// Latest run for this document
if (
rejectEvent ||
isFlowRejected ||
(flow && flow.rejections && flow.rejections.length > 0) ||
(!flow && isRunRejectedInSeal)
) {
eHumanAction = "审批驳回";
auditDrift = false;
auditDriftReason = undefined;
const rejInfo = formatRejectionComment(rejectEvent, flow?.rejections?.[0], mar, history);
eHumanComment = rejInfo.comment;
operator = rejInfo.operator;
} else if (isFlowCompleted || (!flow && isRunApprovedInSeal)) {
eHumanAction = isFlowPaid ? "已支付" : "审批通过";
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
for (const ev of subsequentHumanEvents) {
if (!operator && ev.operator) operator = ev.operator;
}
if (opinionLines.length > 0) {
eHumanComment = formatNumberedHumanOpinions(opinionLines, [], "forward");
} else {
const lastHumanApproval = [...windowEvents]
.reverse()
.find(
(e) =>
!e.isEbot &&
(e.rawAction === "freeflow.agree" ||
e.action === "审批同意" ||
e.rawAction === "freeflow.pay")
);
eHumanComment = lastHumanApproval?.comment ? `1. ${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.some((l) => l.includes("单据撤回"))) {
opinionLines.push(`提交人(${retractEvent.operator?.name || "提交人"}): 单据撤回`);
}
eHumanComment =
opinionLines.length > 1
? formatNumberedHumanOpinions(opinionLines, [], "forward")
: opinionLines.length === 1
? opinionLines[0]!
: "单据已撤回";
} else if (isFlowPaying) {
eHumanAction = "⏳ 支付中";
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
for (const ev of subsequentHumanEvents) {
if (!operator && ev.operator) operator = ev.operator;
}
const pendingLines = extractPendingLines(flow);
eHumanComment = formatNumberedHumanOpinions(opinionLines, pendingLines, "reverse");
} else {
// Flow is actively approving
eHumanAction = "⏳ 审批中";
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
for (const ev of subsequentHumanEvents) {
if (!operator && ev.operator) operator = ev.operator;
}
const pendingLines = extractPendingLines(flow);
eHumanComment = formatNumberedHumanOpinions(opinionLines, pendingLines, "reverse");
}
}
}
result.set(run.id, {
recordId: run.id,
sourceDocumentSN: run.sourceDocumentSN,
taskMode: run.taskMode,
aiDecision: formatAiDecision(aiDecisionStr),
aiAction,
eHumanAction,
eHumanComment,
auditDrift,
auditDriftReason,
operator
});
}
return result;
}