import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/workflow/services.js"; import { DEFAULT_CHOOSE_SERIALIZATION, normalizeChooseTags, type ChooseSerialization, } from "../../../domains/platform/workflow/models/choose-serialization.js"; import { loadGlobalConfig } from "../../../core/config/loader.js"; import { matchAppRequirement } from "../../../domains/platform/workflow/analysis/openapi-app-requirements.js"; import { fetchOpenedPowerCodes } from "../../../domains/store/tools.js"; import { stringOption } from "../../parser.js"; import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js"; import type { CliParsedArgs, CliRuntime } from "../../types.js"; export const PLATFORM_ID_OPTION_KEYS = ["platform", "platform-id", "platformId", "app", "app-id", "appId"]; export function formatWorkflowVersion(workflow: { version?: string | null; tasksVersion?: number | null; updateTime?: string | null; }): string { const version = workflow.version || "-"; const tasksVersion = workflow.tasksVersion ?? "-"; const updateTime = workflow.updateTime ? `,更新时间 ${workflow.updateTime}` : ""; return `版本 ${version}(tasksVersion ${tasksVersion})${updateTime}`; } export async function createWorkflowDetailClient( parsed: CliParsedArgs, runtime: CliRuntime, pipelineId: string, ): Promise<{ client: Awaited>; clients: Awaited>; platformId?: string; }> { const clients = await createClientsForCorp(runtime.selectedCorp!); const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS); let platformId = explicit; if (!platformId) { try { const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id; const { listBasicPlatforms: listPlatforms } = await import("../../../domains/platform/applications/services.js"); const platforms = await listPlatforms(clients.ekbClient, corpId); const firstActive = platforms.find((p) => p.active) ?? platforms[0]; platformId = firstActive?.id; } catch { // Fall back to easoClient } } return { client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient, clients, platformId, }; } export async function createJobPiperClient( parsed: CliParsedArgs, runtime: CliRuntime ): Promise>> { const corp = runtime.selectedCorp!; const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS); if (explicit) { return createPiperClientForCorp(corp, explicit); } const clients = await createClientsForCorp(corp); try { const corpId = corp.corpId || corp.id; const { listBasicPlatforms: listPlatforms } = await import("../../../domains/platform/applications/services.js"); const platforms = await listPlatforms(clients.ekbClient, corpId); const firstActive = platforms.find((p) => p.active) ?? platforms[0]; if (firstActive?.id) { return await createPiperClientForCorp(corp, firstActive.id); } } catch { // Fall back to default easoClient } return clients.easoClient; } export interface CodeNodeSummary { id: string; name: string; label: string; type: string; status: string; rawOutput: unknown; summaryLines: string[]; } export function extractCodeNodeSummaries( nodes: Array, flattenExecutionTreeFn?: (nodes: any[]) => any[] ): CodeNodeSummary[] { const flattened = (flattenExecutionTreeFn ?? flattenExecutionTree)(nodes); const summaries: CodeNodeSummary[] = []; for (const node of flattened) { if (!node) continue; const type = String(node.type || ""); if (type !== "code" && type !== "code-js2") continue; const rawOutput = node.output ?? node.outputs ?? node.details; const summaryLines: string[] = []; if (rawOutput === undefined || rawOutput === null) { summaryLines.push(" 出参: (无返回值或 null)"); } else if (Array.isArray(rawOutput)) { summaryLines.push(` 出参类型: Array (${rawOutput.length} 项)`); if (rawOutput.length > 0) { const first = rawOutput[0]; if (first && typeof first === "object") { const keys = ["planCode", "code", "id", "name", "title", "totalAmount", "amount"]; const matchedKey = keys.find((k) => (first as Record)[k] !== undefined); if (matchedKey) { summaryLines.push(` 首项 ${matchedKey}: ${String((first as Record)[matchedKey])}`); } if ((first as any).amount !== undefined && matchedKey !== "amount") { summaryLines.push(` 首项金额: ${String((first as any).amount)}`); } } else { summaryLines.push(` 首项值: ${String(first)}`); } } } else if (typeof rawOutput === "object") { const obj = rawOutput as Record; summaryLines.push(" 出参类型: Object"); if (Array.isArray(obj.items)) { summaryLines.push(` items.length: ${obj.items.length}`); } for (const k of ["planCode", "totalAmount", "count", "code", "total", "amount", "success"]) { if (obj[k] !== undefined) { summaryLines.push(` ${k}: ${String(obj[k])}`); } } const allKeys = Object.keys(obj); if (summaryLines.length === 1 && allKeys.length > 0) { summaryLines.push(` 字段列表 (${allKeys.length} 个): ${allKeys.slice(0, 5).join(", ")}${allKeys.length > 5 ? "..." : ""}`); } } else { summaryLines.push(` 出参值: ${String(rawOutput)}`); } summaries.push({ id: node.id || "-", name: node.name || "-", label: node.label || node.displayName || (type === "code" ? "MVEL代码节点" : "JS代码节点"), type, status: node.status || "UNKNOWN", rawOutput, summaryLines, }); } return summaries; } export function formatCodeNodeSummariesCard( summaries: CodeNodeSummary[], jobId?: string ): string[] { if (summaries.length === 0) return []; const lines: string[] = [ "", "── 🧮 核心代码节点出参即时摘要 (Code Return Values) ──", ]; for (const s of summaries) { const statusIcon = s.status === "COMPLETED" || s.status === "SUCCESS" ? "✅" : s.status === "FAILED" ? "❌" : "⏳"; lines.push(` ${statusIcon} [${s.name}] ${s.label} (${s.type}, 状态: ${s.status})`); for (const l of s.summaryLines) { lines.push(` ${l}`); } if (jobId) { lines.push(` ↳ 完整出参查看: hose-use workflow job ${jobId} --node=${s.name} --full`); } } return lines; } // ── choose 表达式序列化模式 ──────────────────────────────────────────────────── /** * 解析本轮写入使用的 choose 序列化模式。 * * 优先级:命令行 --choose-serialization > 全局配置 chooseSerialization > 默认 frontend。 * * 说明:该模式只影响 CLI 往服务端写入的字节形态,读取侧永远同时容忍两种形态。 * 详细背景见 src/domains/platform/workflow/models/choose-serialization.ts 顶部注释。 */ export function resolveChooseSerialization(parsed: CliParsedArgs): ChooseSerialization { const explicit = stringOption(parsed.options, ["choose-serialization"]); if (explicit === "frontend" || explicit === "pure") { return explicit; } return loadGlobalConfig().chooseSerialization ?? DEFAULT_CHOOSE_SERIALIZATION; } /** * 归一化对象中所有形如 `url` 的字段(目前只有 http 节点的 `url`), * 让 CLI 写出的结果与设计器保持一致。 */ export function normalizeNodeExpressionFields( target: Record, mode: ChooseSerialization ): { changed: boolean; before?: string; after?: string } { if (!target || typeof target.url !== "string") return { changed: false }; const normalized = normalizeChooseTags(target.url, mode); if (normalized === target.url) return { changed: false }; const before = target.url; target.url = normalized; return { changed: true, before, after: normalized }; } // ── 保存期:接口所需企业应用的自动开通状态预检 ────────────────────────────── export interface NodeAppRequirementAlert { taskName: string; taskLabel: string; /** 接口的人类可读名称 */ apiName: string; /** 所需应用名称 */ appName: string; powerCode: string; productId?: string; /** 静态路径(判断依据) */ staticPath: string; /** 是否真的读到了企业应用清单 */ verified: boolean; /** 已核对且确认未开通 */ unlicensed: boolean; message: string; } /** * 保存节点时的权限预检:只看**本次写入的节点**,命中已知「接口 → 应用」映射时 * 去应用商店核对企业是否已开通。 * * 边界(与静态分析保持一致): * - 只处理 http 节点; * - URL 读不出静态路径(整体由上游节点变量拼接)时直接跳过,不猜测; * - 读不到企业应用清单时降级为「无法确认」,不阻断保存。 * * 读清单失败不会抛错,也不会卡住写入 —— 这是提示性检查,不是门禁。 */ export async function preflightNodeAppRequirements( runtime: CliRuntime, tasks: Array | undefined | null> ): Promise<{ alerts: NodeAppRequirementAlert[]; verifyError?: string }> { const candidates: Array<{ task: Record; matched: NonNullable>; }> = []; for (const task of tasks) { if (!task || typeof task !== "object") continue; if (String(task.type || "").trim().toLowerCase() !== "http") continue; const matched = matchAppRequirement(task.url, task.method); if (matched) candidates.push({ task, matched }); } if (!candidates.length) return { alerts: [] }; let opened: Set | undefined; let verifyError: string | undefined; try { const corp = runtime.selectedCorp; if (!corp) throw new Error("当前未选择企业"); opened = await fetchOpenedPowerCodes(corp); } catch (error) { verifyError = error instanceof Error ? error.message : String(error); } const alerts = candidates.map(({ task, matched }) => { const { requirement, staticPath } = matched; const verified = opened !== undefined; const unlicensed = verified && !opened!.has(requirement.powerCode.trim().toLowerCase()); const taskName = String(task.name || ""); const taskLabel = String(task.label || task.displayName || ""); const where = requirement.productId ? `「${requirement.appName}」(productId=${requirement.productId})` : `「${requirement.appName}」`; const head = `节点 [${taskLabel || taskName}] (${taskName}) 调用 ${requirement.apiName},需要应用${where},powerCode=${requirement.powerCode}`; const message = !verified ? `${head};未能读取企业应用清单(${verifyError}),请自行到应用商店确认已开通,否则运行时会返回 403。` : unlicensed ? `${head},但当前企业尚未开通该应用。流程跑到这个节点必然返回 403「未开通功能,无权访问」,请先到应用商店开通再发布。` : `${head},企业已开通 ✅`; return { taskName, taskLabel, apiName: requirement.apiName, appName: requirement.appName, powerCode: requirement.powerCode, productId: requirement.productId, staticPath, verified, unlicensed, message, }; }); return { alerts, verifyError }; } /** 把预检结果渲染成命令行提示块;无告警时返回空串。 */ export function renderAppRequirementAlerts(alerts: NodeAppRequirementAlert[]): string { if (!alerts.length) return ""; const lines: string[] = []; const blocked = alerts.filter((a) => a.unlicensed); if (blocked.length) { lines.push(""); lines.push("⛔ 应用权限预检未通过(发布后运行到这里必然 403):"); for (const alert of blocked) { lines.push(` • ${alert.message}`); lines.push(` 判定依据: URL 静态路径 '${alert.staticPath}'`); } } const unknown = alerts.filter((a) => !a.verified); for (const alert of unknown) { lines.push(""); lines.push(`⚠️ 应用权限未能核对:${alert.message}`); lines.push(` 判定依据: URL 静态路径 '${alert.staticPath}'`); } return lines.join("\n"); }