1547 lines
55 KiB
TypeScript
1547 lines
55 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>,
|
||
allLogs?: unknown[],
|
||
submitterId?: string
|
||
): 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));
|
||
|
||
const resolveStaff = (personId?: string): FlowPerson | undefined => {
|
||
if (!personId) return undefined;
|
||
const base = extractFlowPerson(personId);
|
||
if (!base) return undefined;
|
||
if (!base.name && staffMap && base.id) {
|
||
const idParts = base.id.split(":");
|
||
const staff =
|
||
staffMap.get(base.id) ||
|
||
(idParts.length > 1 && idParts[1] ? staffMap.get(idParts[1]) : undefined);
|
||
if (staff?.name) {
|
||
return {
|
||
...base,
|
||
name: staff.name,
|
||
code: staff.code || base.code
|
||
};
|
||
}
|
||
}
|
||
return base;
|
||
};
|
||
|
||
const entries: HoseFlowTimelineEntry[] = [];
|
||
|
||
for (let index = 0; index < sortedLogs.length; index++) {
|
||
const log = sortedLogs[index]!;
|
||
const attributes =
|
||
log.attributes && typeof log.attributes === "object"
|
||
? (log.attributes as Record<string, unknown>)
|
||
: {};
|
||
const currentTime = typeof log.time === "number" ? log.time : undefined;
|
||
|
||
// Check for inline document modification log (modifyFlowLog)
|
||
if (Array.isArray(log.modifyFlowLog)) {
|
||
for (const m of log.modifyFlowLog as Array<Record<string, unknown>>) {
|
||
if (m && typeof m === "object" && m.operatorState === "UPDATE") {
|
||
const modTime = typeof m.operatorTime === "number" ? m.operatorTime : currentTime;
|
||
const modOpId = typeof m.operatorId === "string" ? m.operatorId : undefined;
|
||
const modPerson = resolveStaff(modOpId);
|
||
|
||
let modNodeName = "单据修改";
|
||
if (modOpId && modOpId === submitterId) {
|
||
modNodeName = "提交人";
|
||
} else if (Array.isArray(allLogs) && modOpId) {
|
||
const matchedAllLog: any = allLogs.find(
|
||
(a: any) =>
|
||
a &&
|
||
typeof a === "object" &&
|
||
a.ownerId === modOpId &&
|
||
typeof a.nodeName === "string"
|
||
);
|
||
if (matchedAllLog?.nodeName) {
|
||
modNodeName = String(matchedAllLog.nodeName).trim();
|
||
}
|
||
}
|
||
|
||
entries.push({
|
||
id: typeof m.flowVersionedId === "string" ? `modify-${m.flowVersionedId}` : undefined,
|
||
time: modTime,
|
||
state: "审批中",
|
||
rawState: "MODIFY",
|
||
action: "修改了单据",
|
||
rawAction: "flow.modify",
|
||
nodeName: modNodeName,
|
||
comment: "修改了单据",
|
||
rawComment: "修改了单据",
|
||
automatic: false,
|
||
isEbot: false,
|
||
skipped: false,
|
||
isModification: true,
|
||
operator: modPerson,
|
||
nextOperators: []
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
const rawOperator = extractFlowPerson(log.operatorId);
|
||
const isEbot = isEbotOperator(rawOperator, attributes);
|
||
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 resolved = resolveStaff(operator.id);
|
||
if (resolved?.name) operator = resolved;
|
||
}
|
||
|
||
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);
|
||
|
||
// Node name & Rejection-specific metadata handling
|
||
let nodeName: string | undefined;
|
||
let rejectTargetNodeName: string | undefined;
|
||
let rejectTargetOperator: FlowPerson | undefined;
|
||
let resubmitRuleText: string | undefined;
|
||
|
||
if (rawAction === "freeflow.reject") {
|
||
// 1. Originating node name
|
||
let originNode: string | undefined;
|
||
if (Array.isArray(allLogs)) {
|
||
const match = allLogs.find(
|
||
(a: any) =>
|
||
a &&
|
||
typeof a === "object" &&
|
||
a.action === "freeflow.reject" &&
|
||
(a.ownerId === log.operatorId ||
|
||
Math.abs((Number(a.updateTime) || 0) - (currentTime || 0)) < 2000)
|
||
);
|
||
if (match && typeof (match as any).nodeName === "string") {
|
||
originNode = (match as any).nodeName.trim();
|
||
}
|
||
}
|
||
if (!originNode && attributes.nodeId) {
|
||
const match = sortedLogs.find(
|
||
(l: any) =>
|
||
l &&
|
||
typeof l === "object" &&
|
||
l.attributes?.nodeId === attributes.nodeId &&
|
||
l.action !== "freeflow.reject" &&
|
||
l.attributes?.nodeName
|
||
);
|
||
if (match) originNode = String((match as any).attributes.nodeName).trim();
|
||
}
|
||
if (!originNode) {
|
||
const opId = typeof log.operatorId === "object" ? (log.operatorId as any)?.id : log.operatorId;
|
||
const match = sortedLogs.find((l: any) => {
|
||
const lOpId = typeof l.operatorId === "object" ? (l.operatorId as any)?.id : l.operatorId;
|
||
return lOpId === opId && l.action !== "freeflow.reject" && l.attributes?.nodeName;
|
||
});
|
||
if (match) {
|
||
originNode = String((match as any).attributes.nodeName).trim();
|
||
} else if (attributes.nodeName && attributes.nodeName !== "提交人") {
|
||
originNode = String(attributes.nodeName).trim();
|
||
}
|
||
}
|
||
nodeName = originNode || "审批节点";
|
||
|
||
// 2. Target node name
|
||
rejectTargetNodeName =
|
||
typeof attributes.nodeName === "string" && attributes.nodeName
|
||
? attributes.nodeName.trim()
|
||
: typeof attributes.nextName === "string" && attributes.nextName
|
||
? attributes.nextName.trim()
|
||
: "提交人";
|
||
|
||
// 3. Target operator person
|
||
const nextOpId = typeof log.nextOperatorId === "string" ? log.nextOperatorId : undefined;
|
||
if (nextOpId) {
|
||
rejectTargetOperator = resolveStaff(nextOpId);
|
||
}
|
||
if (
|
||
(!rejectTargetOperator || !rejectTargetOperator.name) &&
|
||
(rejectTargetNodeName === "提交人" || rejectTargetNodeName.includes("提交")) &&
|
||
submitterId
|
||
) {
|
||
rejectTargetOperator = resolveStaff(submitterId);
|
||
}
|
||
|
||
// 4. Resubmit rule text
|
||
const method = String(attributes.resubmitMethod || "").toUpperCase();
|
||
const opDisplayName = operator?.name || "原审批人";
|
||
if (method === "TO_REJECTOR") {
|
||
resubmitRuleText = `重新提交后由${opDisplayName}继续审批`;
|
||
} else if (
|
||
method === "START_OVER" ||
|
||
method === "TO_START" ||
|
||
method === "ALL" ||
|
||
method === "RE_START"
|
||
) {
|
||
resubmitRuleText = "重新提交后重新全流程审批";
|
||
} else if (method === "NEXT_NODE") {
|
||
resubmitRuleText = "重新提交后流转至下一节点";
|
||
} else {
|
||
resubmitRuleText = `重新提交后由${opDisplayName}继续审批`;
|
||
}
|
||
} else {
|
||
nodeName =
|
||
typeof attributes.nodeName === "string" && attributes.nodeName
|
||
? attributes.nodeName
|
||
: typeof attributes.nextName === "string" && attributes.nextName
|
||
? attributes.nextName
|
||
: action === "打印单据"
|
||
? "打印提醒"
|
||
: undefined;
|
||
}
|
||
|
||
const rawComment = typeof attributes.comment === "string" ? attributes.comment : undefined;
|
||
const comment = cleanCommentText(rawComment);
|
||
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(resolveStaff)
|
||
.filter((p): p is FlowPerson => Boolean(p));
|
||
|
||
const nodeId =
|
||
typeof attributes.nodeId === "string" && attributes.nodeId
|
||
? attributes.nodeId
|
||
: typeof log.nodeId === "string" && log.nodeId
|
||
? log.nodeId
|
||
: undefined;
|
||
|
||
entries.push({
|
||
id: typeof log.id === "string" ? log.id : undefined,
|
||
nodeId,
|
||
time: currentTime,
|
||
state,
|
||
rawState,
|
||
action,
|
||
rawAction,
|
||
nodeName,
|
||
comment,
|
||
rawComment,
|
||
automatic,
|
||
isEbot,
|
||
skipped,
|
||
operator,
|
||
nextOperators,
|
||
rejectTargetNodeName,
|
||
rejectTargetOperator,
|
||
resubmitRuleText,
|
||
isModification: false
|
||
});
|
||
}
|
||
|
||
// Sort all entries (including modification entries) chronologically and compute durations
|
||
entries.sort((a, b) => (Number(a.time) || 0) - (Number(b.time) || 0));
|
||
for (let i = 0; i < entries.length; i++) {
|
||
const cur = entries[i]!;
|
||
const next = entries[i + 1];
|
||
if (cur.time !== undefined && next?.time !== undefined && next.time >= cur.time) {
|
||
cur.durationMs = next.time - cur.time;
|
||
}
|
||
}
|
||
|
||
return entries;
|
||
}
|
||
|
||
export function parseHosePending(
|
||
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,
|
||
fromNodeName: entry.nodeName,
|
||
targetNodeName: entry.rejectTargetNodeName,
|
||
targetOperator: entry.rejectTargetOperator,
|
||
resubmitRuleText: entry.resubmitRuleText
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* 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 submitterId =
|
||
typeof form.submitterId === "string"
|
||
? form.submitterId
|
||
: typeof flowDetails.ownerId === "string"
|
||
? flowDetails.ownerId
|
||
: undefined;
|
||
const history = parseHoseTimeline(flowDetails.logs || [], staffMap, allLogs, submitterId);
|
||
const rawState = flowDetails.state;
|
||
const state = translateFlowState(rawState);
|
||
const rawStateUpper = String(rawState || "").toUpperCase();
|
||
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 === "flow.modify" || ev.action === "修改了单据" || ev.isModification) {
|
||
comment = "修改了单据";
|
||
} else 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 || "-";
|
||
}
|
||
}
|
||
|
||
let emoji = "";
|
||
if (ev.rawAction === "flow.modify" || ev.action === "修改了单据" || ev.isModification || comment === "修改了单据") {
|
||
emoji = "✏️";
|
||
} else if (
|
||
ev.rawAction === "freeflow.autoAgree" ||
|
||
ev.action === "自动同意" ||
|
||
comment === "自动同意" ||
|
||
ev.automatic
|
||
) {
|
||
emoji = "🤖";
|
||
} else if (ev.rawAction === "freeflow.retract" || ev.action === "单据撤回" || comment === "单据撤回") {
|
||
emoji = "↩️";
|
||
} else if (
|
||
ev.rawAction === "freeflow.reject" ||
|
||
ev.action === "审批驳回" ||
|
||
ev.rawAction === "freeflow.back" ||
|
||
ev.action === "审批退回" ||
|
||
comment === "驳回" ||
|
||
comment === "退回修改"
|
||
) {
|
||
emoji = "❌";
|
||
} else if (
|
||
(ev.rawAction === "freeflow.pay" || ev.action === "支付成功" || ev.action === "支付完成") &&
|
||
(comment === "支付成功" || comment === "支付完成" || !comment)
|
||
) {
|
||
emoji = "💰";
|
||
} else if (
|
||
ev.rawAction === "freeflow.addnode" ||
|
||
ev.action?.includes("加签") ||
|
||
ev.action?.includes("转交") ||
|
||
ev.action?.includes("转办") ||
|
||
comment?.includes("转交") ||
|
||
comment?.includes("加签")
|
||
) {
|
||
emoji = "🔀";
|
||
} else if (
|
||
ev.rawAction === "freeflow.paying" ||
|
||
ev.rawAction === "freeflow.comment" ||
|
||
ev.action === "发表评论" ||
|
||
ev.action === "添加评论" ||
|
||
(ev.rawAction === "freeflow.pay" && comment !== "支付成功")
|
||
) {
|
||
emoji = "💬";
|
||
}
|
||
|
||
const emojiPrefix = emoji ? ` ${emoji}` : "";
|
||
const line = `${nodePrefix}${emojiPrefix}: ${comment}`;
|
||
if (lines.length === 0 || lines[lines.length - 1] !== line) {
|
||
lines.push(line);
|
||
}
|
||
}
|
||
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];
|
||
const numbered = all.map((line, idx) => `${idx + 1}. ${line}`);
|
||
// If any history line records document modification ("修改了单据"), hoist all modification lines to the top
|
||
// while strictly preserving each item's true chronological sequence number from the flow
|
||
const modLines = numbered.filter((l) => l.includes("修改了单据"));
|
||
const normalLines = numbered.filter((l) => !l.includes("修改了单据"));
|
||
return [...modLines, ...normalLines].join("\n");
|
||
}
|
||
|
||
// Reverse chronological order for in-progress approvals:
|
||
// 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[],
|
||
flow?: HoseFlowDetail
|
||
): { comment: string; operator?: FlowPerson } {
|
||
const op = rejectEvent?.operator || rejectionDetail?.operator || (mar as any)?.operator;
|
||
const opName = op?.name || op?.id || (mar as any)?.operatorName || "";
|
||
|
||
let rawNodeName = (
|
||
rejectEvent?.nodeName ||
|
||
rejectionDetail?.fromNodeName ||
|
||
rejectionDetail?.nodeName ||
|
||
(mar as any)?.nodeName ||
|
||
""
|
||
).trim();
|
||
|
||
// Strip Seal's synthetic wrapper node names (never output "合思审批节点" to user)
|
||
if (
|
||
rawNodeName === "合思审批节点" ||
|
||
rawNodeName === "外部审批节点" ||
|
||
rawNodeName.includes("合思审批") ||
|
||
rawNodeName.includes("外部审批")
|
||
) {
|
||
rawNodeName = "";
|
||
}
|
||
|
||
// If nodeName is still missing or default, lookup their actual approval nodeName in history
|
||
if ((!rawNodeName || rawNodeName === "提交人" || rawNodeName === "审批节点") && opName && history) {
|
||
const matchedLog = history.find(
|
||
(h) =>
|
||
h.operator?.name === opName &&
|
||
h.nodeName &&
|
||
h.nodeName.trim() !== "提交人" &&
|
||
!h.isEbot &&
|
||
h.rawAction !== "freeflow.reject"
|
||
);
|
||
if (matchedLog?.nodeName) {
|
||
rawNodeName = matchedLog.nodeName.trim();
|
||
}
|
||
}
|
||
|
||
const rawComment =
|
||
rejectEvent?.comment ||
|
||
rejectionDetail?.reason ||
|
||
(mar as any)?.rejectComment ||
|
||
"修改";
|
||
|
||
let cleanComment = rawComment;
|
||
if (cleanComment.includes(":")) {
|
||
const parts = cleanComment.split(":");
|
||
if (parts.length > 1) {
|
||
cleanComment = parts.slice(1).join(":").trim();
|
||
}
|
||
}
|
||
|
||
let mainLine = cleanComment;
|
||
if (rawNodeName && opName) {
|
||
mainLine = `${rawNodeName}(${opName}) ❌: ${cleanComment}`;
|
||
} else if (opName) {
|
||
mainLine = `${opName} ❌: ${cleanComment}`;
|
||
} else if (rawNodeName) {
|
||
mainLine = `${rawNodeName} ❌: ${cleanComment}`;
|
||
} else {
|
||
mainLine = cleanComment;
|
||
}
|
||
|
||
// Target node & operator
|
||
const targetNode =
|
||
rejectEvent?.rejectTargetNodeName ||
|
||
rejectionDetail?.targetNodeName ||
|
||
"提交人";
|
||
const targetOpName =
|
||
rejectEvent?.rejectTargetOperator?.name ||
|
||
rejectionDetail?.targetOperator?.name ||
|
||
flow?.submitter?.name;
|
||
const targetStr = targetOpName ? `${targetNode}(${targetOpName})` : targetNode;
|
||
|
||
// Resubmit rule text
|
||
const ruleStr =
|
||
rejectEvent?.resubmitRuleText ||
|
||
rejectionDetail?.resubmitRuleText ||
|
||
(opName ? `重新提交后由${opName}继续审批` : "重新提交后继续审批");
|
||
|
||
// 样式 2-B(三行展开式,驳回目标与重审规则各占一行)
|
||
const commentStr = `${mainLine}\n↳ 驳回至: ${targetStr}\n↳ ${ruleStr}`;
|
||
|
||
return {
|
||
comment: commentStr,
|
||
operator: op
|
||
};
|
||
}
|
||
|
||
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 doc = (run.document as Record<string, unknown> | undefined) || {};
|
||
const mar =
|
||
((run as Record<string, unknown>).manualApprovalRecord as Record<string, unknown> | undefined) ||
|
||
((run.result as Record<string, unknown> | undefined)?.manualApprovalRecord as Record<string, unknown> | undefined) ||
|
||
((doc as Record<string, unknown>).manualApprovalRecord as Record<string, unknown> | undefined) ||
|
||
{};
|
||
|
||
// 1. 强特征 Node ID 锚定:优先从 sourceExtendData.nodeId 或 manualApprovalRecord.nodeId 反查合思真实节点
|
||
const sourceNodeId =
|
||
typeof (run.sourceExtendData as Record<string, unknown> | undefined)?.nodeId === "string"
|
||
? String((run.sourceExtendData as Record<string, unknown>).nodeId)
|
||
: undefined;
|
||
const rawMarNodeId = typeof mar.nodeId === "string" ? String(mar.nodeId) : undefined;
|
||
const decodedMarNodeId = rawMarNodeId
|
||
? decodeURIComponent(rawMarNodeId).replace(/^hcnode_/, "").replace(/_r\d+$/, "")
|
||
: undefined;
|
||
const targetNodeId = sourceNodeId || decodedMarNodeId;
|
||
|
||
const matchedNodeEvent = targetNodeId
|
||
? history.find((e) => e.nodeId && (e.nodeId === targetNodeId || targetNodeId.includes(e.nodeId)))
|
||
: undefined;
|
||
|
||
// 锚定基准时间:优先采用合思对应节点的真实执行时刻;若无对应节点,放宽多系统排队容差至 60 秒
|
||
const effectiveRunTime = matchedNodeEvent?.time ?? runTime;
|
||
|
||
const nextRun = sortedRuns[i + 1];
|
||
let nextRunTime = nextRun ? Number(nextRun.createdAt) || Infinity : Infinity;
|
||
let isLatestRun = i === sortedRuns.length - 1;
|
||
|
||
// 跨期/分段切片安全防线:
|
||
// 若导出时只圈选了局部时间范围(例如横跨3个月的单据只导出了中间某个月),Seal 内存中可能只有单条历史 Run。
|
||
// 我们利用合思全生命周期流水 (flow.history) 反向校验:如果在当前 Run 之后存在后续新的 AI 审批 (isEbot),
|
||
// 则直接证明当前 Run 已被后续更新的 AI 轮次所替代,绝非最新终态轮次!
|
||
const subsequentEbot = history.find(
|
||
(e) =>
|
||
(e.time ?? 0) > effectiveRunTime + 5000 &&
|
||
e.isEbot &&
|
||
(e.nodeName?.includes("智能") ||
|
||
e.nodeName?.includes("AI") ||
|
||
e.action?.includes("智能") ||
|
||
e.comment?.includes("AI") ||
|
||
e.comment?.includes("approval-result")) &&
|
||
!e.nodeName?.includes("费用标准检查") &&
|
||
!e.nodeName?.includes("标准检查") &&
|
||
!e.nodeName?.includes("预算")
|
||
);
|
||
|
||
if (subsequentEbot) {
|
||
isLatestRun = false;
|
||
if ((subsequentEbot.time ?? Infinity) < nextRunTime) {
|
||
nextRunTime = subsequentEbot.time!;
|
||
}
|
||
}
|
||
|
||
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 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 === "被驳回");
|
||
|
||
// 容差窗口:若已通过 nodeId 准确锚定,前后仅需 1 秒同步边沿;若未锚定,提供 60 秒跨系统排队与处理缓冲
|
||
const skewToleranceMs = matchedNodeEvent ? 1000 : 60000;
|
||
const windowEvents = history.filter((e) => {
|
||
const t = e.time ?? 0;
|
||
return t >= effectiveRunTime - skewToleranceMs && 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) > effectiveRunTime + 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) >= effectiveRunTime - 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, flow);
|
||
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.
|
||
// Rule: rejectEvent is scoped to THIS run's time window — if it exists, this run was
|
||
// definitively rejected regardless of what the overall flow state is now (the flow may
|
||
// have been paid via a subsequent re-submission).
|
||
// flow.rejections.length alone is NOT reliable — it can contain rejections from earlier
|
||
// rounds. Only use it as a fallback when isFlowRejected (current state) is also true.
|
||
if (rejectEvent) {
|
||
// A rejection event occurred inside this run's time window → this run was rejected.
|
||
eHumanAction = "审批驳回";
|
||
auditDrift = false;
|
||
auditDriftReason = undefined;
|
||
const rejInfo = formatRejectionComment(rejectEvent, undefined, mar, history, flow);
|
||
eHumanComment = rejInfo.comment;
|
||
operator = rejInfo.operator;
|
||
} else if (isFlowCompleted || (!flow && isRunApprovedInSeal)) {
|
||
const hasModification = windowEvents.some(
|
||
(e) => e.rawAction === "flow.modify" || e.isModification || e.action === "修改了单据"
|
||
);
|
||
eHumanAction = isFlowPaid
|
||
? hasModification
|
||
? "已支付 (中途修改)"
|
||
: "已支付"
|
||
: hasModification
|
||
? "审批通过 (中途修改)"
|
||
: "审批通过";
|
||
|
||
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
|
||
for (const ev of subsequentHumanEvents) {
|
||
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 (isFlowPaying) {
|
||
eHumanAction = "⏳ 支付中";
|
||
|
||
const opinionLines = formatHumanOpinionLines(subsequentHumanEvents);
|
||
for (const ev of subsequentHumanEvents) {
|
||
if (!operator && ev.operator) operator = ev.operator;
|
||
}
|
||
const pendingLines = extractPendingLines(flow);
|
||
eHumanComment = formatNumberedHumanOpinions(opinionLines, pendingLines, "reverse");
|
||
} else if (isFlowRetractedOrCancelled || (retractEvent && !hasPostAiResubmit) || isRunCancelledInSeal) {
|
||
eHumanAction = "已撤回";
|
||
operator = retractEvent?.operator;
|
||
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]!
|
||
: (retractEvent ? `提交人(${retractEvent.operator?.name || "提交人"}) ↩️: 单据撤回` : "单据已撤回");
|
||
} else if (isFlowRejected || (!flow && isRunRejectedInSeal)) {
|
||
// No rejectEvent in this run's window, but the current Hose flow state is rejected.
|
||
eHumanAction = "审批驳回";
|
||
auditDrift = false;
|
||
auditDriftReason = undefined;
|
||
const rejInfo = formatRejectionComment(undefined, flow?.rejections?.[0], mar, history, flow);
|
||
eHumanComment = rejInfo.comment;
|
||
operator = rejInfo.operator;
|
||
} 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;
|
||
}
|