import { existsSync, readFileSync } from "node:fs"; import { isCorpProd } from "../../../core/config/types.js"; import { classifyWorkflowTrigger, getWorkflowDebugSource, getWorkflowDetail, getWorkflowSampleData, runWorkflowDebugTest, updateWorkflow, refreshWorkflowChooses, flattenWorkflowTaskTree, type WorkflowTriggerCategory, } from "../../../domains/platform/workflow/services.js"; import { stringOption, booleanOption, numberOption } from "../../parser.js"; import { printJson, printTable, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { createWorkflowDetailClient, extractCodeNodeSummaries, formatCodeNodeSummariesCard } from "./shared.js"; import { buildConfirmedCommand, isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js"; import { hasProductionOverride, productionGuard, productionOverrideMeta } from "../../production.js"; export async function handleWorkflowTest( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { let pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]); let flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]); // 智能参数纠错:如果首参数疑似单号/台账记录(非纯数字长ID),且第二个位置参数为工作流ID(16~20位纯数字) if ( parsed.args[0] && parsed.args[1] && /^\d{16,20}$/.test(parsed.args[1]) && !/^\d{16,20}$/.test(parsed.args[0]) ) { flowCodeOrId = parsed.args[0]; pipelineId = parsed.args[1]; } if (!pipelineId) { return { stdout: "", stderr: [ "用法: hose-use workflow test [选项]", "", "不同触发器的调试参数分支:", " 1. 单据触发 (flowForm): --flow=<单号|ID> 指定单据", " 2. 台账触发 (dataLink): --record=<记录ID|编码> 指定业务对象数据", " 3. 定时触发 (clock): 无需业务参数,使用 --yes 确认执行", " 4. 外部调用 (webhook): --body='{...}' 或 --file= 传入事件请求体", "", "通用选项:", " --save-sample 调试通过后自动将执行节点的真实出参保存为样本数据 (sampleData)", " --timeout= 设置轮询超时时间 (默认 15000ms)", " --auto-publish 是否自动发布测试快照 (默认 false)", " --allow-prod 确认在正式生产环境 (env: prod) 下执行调试(--force 为兼容别名)", " --dry-run 只预览,不发起调试", " --yes/--confirm 确认执行真实工作流节点", "", "别名: hose-use workflow debug ", ].join("\n") + "\n", exitCode: 1, }; } const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]); const saveSample = booleanOption(parsed.options, ["save-sample", "saveSample", "save-samples", "saveSamples"]); const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000; const rawBody = stringOption(parsed.options, ["body", "data", "payload"]); const filePath = stringOption(parsed.options, ["file", "path"]); const isEmpty = booleanOption(parsed.options, ["empty", "none"]); const sampleOption = stringOption(parsed.options, ["sample", "sample-id", "sampleId"]); const allowProd = hasProductionOverride(parsed); const isProductionCorp = Boolean(runtime.selectedCorp && isCorpProd(runtime.selectedCorp)); const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"]; if (isProductionCorp) { warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --allow-prod。`); } const nextActionCmd = buildConfirmedCommand(parsed, isProductionCorp ? ["--allow-prod"] : []); const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", nextActionCmd); if (isDryRun(parsed, runtime)) { return mutationPreview( parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings, ...(isProductionCorp ? { productionOverride: allowProd, productionWarning: allowProd ? "生产环境覆盖已启用:实际执行会在正式生产企业产生真实业务变更。" : "当前为正式生产企业:实际执行需追加 --allow-prod 确认。", } : {}), }, { extraArgs: isProductionCorp && !allowProd ? ["--allow-prod"] : [] } ); } // 生产确认只要求“用户明确知道在操作生产企业”,不做功能禁止;预览已在上面放行。 const blocked = productionGuard(parsed, runtime, { operation: "执行工作流调试", operationCode: "workflow.test", risk: "调试会真实执行工作流节点,可能产生单据流转、第三方调用、通知与快照发布等不可逆业务变更。", nextAction: nextActionCmd, }); if (blocked) return blocked; if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution(); const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId); // 1. 获取工作流详情与触发器元数据 const detail = await getWorkflowDetail(client, pipelineId).catch(() => { warnings.push("未能读取工作流状态,启用状态未知。"); return null; }); const isEnabled = detail?.state === 1 || (detail as any)?.active === true; const triggerNode = detail?.tasks?.[0]; const triggerType = triggerNode?.type || "unknown"; const triggerLabel = triggerNode?.label || triggerNode?.name || "触发器"; const category: WorkflowTriggerCategory = classifyWorkflowTrigger(triggerType); let targetId = flowCodeOrId; let customPayload: Record | undefined; // 2. 根据触发器类型进行路径分支分发 (Path Branching) switch (category) { case "SCHEDULE": { // 分支 A: 定时任务触发器 (clock) ── 无需单据/台账,直接派发执行 targetId = ""; break; } case "WEBHOOK": { // 分支 B: Webhook / 外部事件触发器 ── 支持 flow/bill / sample / body / file / empty targetId = ""; if (flowCodeOrId && !rawBody && !filePath) { try { const { getBillByCodeOrId } = await import("../../../domains/bill/tools.js"); const { createSessionClient } = await import("../../../core/http/index.js"); const sessionClient = await createSessionClient(runtime.selectedCorp!); const corpId = runtime.selectedCorp?.corpId || runtime.selectedCorp?.id || ""; const bills = await getBillByCodeOrId(sessionClient, corpId, flowCodeOrId); const bill = bills[0]; if (bill) { customPayload = { code: bill.billCode, flowId: bill.billId, title: bill.title, data: bill, corporationId: corpId, }; } else { customPayload = { code: flowCodeOrId, flowId: flowCodeOrId, corporationId: corpId, }; } } catch { customPayload = { code: flowCodeOrId, flowId: flowCodeOrId, corporationId: runtime.selectedCorp?.corpId || runtime.selectedCorp?.id, }; } } else if (rawBody) { try { customPayload = JSON.parse(rawBody); } catch (e: any) { return { stdout: "", stderr: `❌ --body 参数不是合法的 JSON 字符串: ${e.message}\n`, exitCode: 1, }; } } else if (filePath) { if (!existsSync(filePath)) { return { stdout: "", stderr: `❌ 指定的 Payload 文件不存在: ${filePath}\n`, exitCode: 1, }; } try { customPayload = JSON.parse(readFileSync(filePath, "utf-8")); } catch (e: any) { return { stdout: "", stderr: `❌ 读取并解析文件 ${filePath} 失败: ${e.message}\n`, exitCode: 1, }; } } else if (sampleOption) { // 从服务器获取历史接收样本发起测试 try { const sampleResult = await getWorkflowSampleData(client, pipelineId); const records = sampleResult.records || []; let matched = records.find((r) => r.id === sampleOption); if (!matched) { const num = parseInt(sampleOption, 10); if (!isNaN(num) && num >= 1 && num <= records.length) { matched = records[num - 1]; } } if (!matched) { return { stdout: "", stderr: `❌ 未找到指定的数据样本 [${sampleOption}]。当前服务器保存了 ${records.length} 条样本。\n`, exitCode: 1, }; } customPayload = JSON.parse(matched.dataJson); } catch (e: any) { return { stdout: "", stderr: `❌ 获取或解析数据样本失败: ${e.message}\n`, exitCode: 1, }; } } else if (isEmpty) { customPayload = {}; } else { // 未提供 Payload 时,展示参数定义与服务器最近接收的数据样本 let sampleLines: string[] = []; try { const sampleResult = await getWorkflowSampleData(client, pipelineId); const records = sampleResult.records || []; if (records.length > 0) { const rows = records.map((r, idx) => { const timeStr = r.createTime ? new Date(r.createTime).toLocaleString("zh-CN", { hour12: false }) : "-"; let preview = r.dataJson || ""; if (preview.length > 55) preview = preview.slice(0, 52) + "..."; return [idx + 1, r.id, timeStr, preview]; }); sampleLines = [ "", `── 服务器最近接收的数据样本 (最近 ${records.length} 条) ──`, printTable(["#", "样本 ID", "接收时间", "数据摘要 (Payload Preview)"], rows), ]; } } catch {} // 解析触发器定义的请求参数与中文昵称映射 const triggerParams = Array.isArray((triggerNode as any)?.params) ? ((triggerNode as any).params as Array<{ key: string; value: string }>) : []; let paramLines: string[] = []; if (triggerParams.length > 0) { paramLines = [ "", "── 接收的请求参数定义 (Params) ──", printTable( ["参数名 (Key)", "中文昵称 (Label)"], triggerParams.map((p) => [p.key, p.value]) ), ]; } return { stdout: [ `📡 [外部事件触发器: ${triggerLabel} (${triggerType})]`, `该工作流由 Webhook / 外部系统事件驱动,需提供模拟请求体 (Payload) 进行测试。`, ...paramLines, ...sampleLines, "", "调试传参选项:", ...(sampleLines.length > 0 ? [` --sample=<1|2|3> 直接选用上述服务器最近接收的数据样本发起测试`] : []), ` --flow=<单号> 提取指定单据的编码与数据作为 Webhook Payload 发起测试`, ` --body='{"key": "value"}' 直接传入自定义 JSON 请求体`, ` --file= 从本地 JSON 文件读取请求体`, ` --empty 使用空对象 {} 直接发起测试`, "", `示例:`, ` hose-use workflow test ${pipelineId} ${ sampleLines.length > 0 ? "--sample=1" : `--flow=B26000148` }`, ` hose-use workflow webhook send ${pipelineId} --bill=B26000148 --yes`, ].join("\n") + "\n", stderr: "", exitCode: 1, }; } break; } case "DATALINK": { // 分支 C: 业务对象台账变更触发器 ── 需要台账数据记录 ID (ID01...) if (!targetId) { try { const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 }); if (runtime.jsonMode) { return { stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions), stderr: "", exitCode: 0, }; } // 动态解析数据源列字段 (Fields) const hasFields = Array.isArray(source.fields) && source.fields.length > 0; const headers = hasFields ? ["#", "记录 ID", ...source.fields.map((f) => f.label)] : ["#", "记录 ID", "编码 (Code)", "名称 (Name)", "负责人 (Owner)"]; const rows = source.items.map((it, idx) => { if (hasFields) { return [ idx + 1, it.id, ...source.fields.map((f) => (it as any)[f.key] || "-"), ]; } return [ idx + 1, it.id, (it as any).code || "-", (it as any).name || it.title || "-", (it as any).owner || "-", ]; }); const out = [ `⚠️ 未指定台账记录,请通过 --record=<记录ID|编码> 传入测试台账。`, ...(isEnabled ? [ `💡 [启用态提示] 该工作流当前处于【🟢 生产启用中】(state = 1)。`, ` 合思前端已置灰调试按钮,CLI 支持直接调测;请注意后端缺乏沙箱,执行将产生真实副作用并自增版本。`, ] : []), "", `── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "业务对象台账"}) ──`, rows.length ? printTable(headers, rows) : "暂无可用台账记录", "", `示例: hose-use workflow test ${pipelineId} --record=${source.items[0]?.id || "ID01..."}`, ].join("\n"); return { stdout: `${out}\n`, stderr: "", exitCode: 1 }; } catch (err: any) { return { stdout: "", stderr: `未指定台账记录 (--record=),且拉取候选台账失败: ${err.message || String(err)}\n`, exitCode: 1, }; } } break; } case "FLOW_FORM": default: { // 分支 D: 单据审批事件触发器 ── 需要单据编号 (ZJ-xxx / flowId) if (!targetId) { try { const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 }); if (runtime.jsonMode) { return { stdout: printJson({ ...source, productionEnabled: detail ? isEnabled : null, warnings }, runtime.outputOptions), stderr: "", exitCode: 0, }; } const rows = source.items.map((it, idx) => [ idx + 1, it.id, it.title || "-", it.flowState || "-", ]); const out = [ `⚠️ 未指定测试单号,请通过 --flow=<单号> 传入测试单据。`, ...(isEnabled ? [ `💡 [启用态提示] 该工作流当前处于【🟢 生产启用中】(state = 1)。`, ` 合思前端已置灰调试按钮,CLI 支持直接调测;请注意后端缺乏沙箱,执行将产生真实副作用并自增版本。`, ] : []), "", `── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "我的单据"}) ──`, rows.length ? printTable(["#", "单据编号 (ID)", "单据名称 (Title)", "状态 (Status)"], rows) : "暂无可用测试单据", "", `示例: hose-use workflow test ${pipelineId} --flow=${source.items[0]?.id || "ZJ-xxxx"}`, ].join("\n"); return { stdout: `${out}\n`, stderr: "", exitCode: 1 }; } catch (err: any) { const errMsg = err.message || String(err); const notFoundHint = errMsg.includes("expected 1 result. got 0") ? `\n💡 提示: 云端未查询到工作流 [${pipelineId}] 的调试数据源,请检查工作流 ID 是否有效,或工作流类型是否需要 --flow / --body 等参数。` : ""; return { stdout: "", stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${errMsg}${notFoundHint}\n`, exitCode: 1, }; } } break; } } // 3. 执行端到端调试测试 confirmExecution(); const execution = await runWorkflowDebugTest(client, pipelineId, { flowCodeOrId: targetId, data: customPayload, triggerCategory: category, triggerType, triggerLabel, autoPublish, timeoutMs, }); const savedSampleNodes: Array<{ name: string; label: string; fieldCount: number }> = []; if (saveSample && execution.outcome === "completed" && execution.executionTree?.length > 0) { try { const latestDetail = await getWorkflowDetail(client, pipelineId); const flattened = flattenWorkflowTaskTree(latestDetail.tasks || []); let updatedCount = 0; for (const execNode of execution.executionTree) { if (!execNode.name || execNode.output === undefined || execNode.output === null) continue; if (typeof execNode.output !== "object" || Object.keys(execNode.output).length === 0) continue; const matched = flattened.find((f) => f.task.name === execNode.name); if (matched) { (matched.task as any).sampleData = execNode.output; savedSampleNodes.push({ name: matched.task.name, label: (matched.task as any).displayName || matched.task.label || matched.task.type, fieldCount: Object.keys(execNode.output).length, }); updatedCount++; } } if (updatedCount > 0) { await updateWorkflow(client, latestDetail, { platformId, expectedVersion: { version: latestDetail.version, tasksVersion: latestDetail.tasksVersion }, }); try { await refreshWorkflowChooses(client, pipelineId); } catch {} } } catch (sampleErr: any) { warnings.push(`自动固化样本数据警告: ${sampleErr.message || String(sampleErr)}`); } } const report = { ...execution, productionEnabled: detail ? isEnabled : null, savedSampleNodes: savedSampleNodes.length > 0 ? savedSampleNodes : undefined, warnings, ...productionOverrideMeta( parsed, runtime, "生产环境覆盖已启用 (--allow-prod):本次调试在正式生产企业真实执行。" ), }; const exitCode = report.outcome === "completed" ? 0 : 1; if (runtime.jsonMode) { return { stdout: printJson(report, runtime.outputOptions), stderr: "", exitCode, }; } const treeRows = report.executionTree.map((node, idx) => [ idx + 1, node.id, node.name || "-", node.label || (node as any).displayName || "-", node.type || "-", node.status || "-", String((node as any).durationTime ?? node.executionTime ?? "-"), node.error?.message || "-", ]); const targetDescription = category === "SCHEDULE" ? "(定时调度模拟触发)" : category === "WEBHOOK" ? `(Webhook Payload: ${customPayload ? Object.keys(customPayload).join(", ") || "{}" : "-"})` : report.targetEntityId || "-"; const outLines = [ ...(isEnabled ? [ "⚠️ [生产启用态调试安全提醒]", `• 目标工作流 [${pipelineId}] 当前处于【🟢 生产启用中】(state = 1);`, "• 特权调测通道:合思 Web 控制台已置灰【调试】按钮,CLI 为您打通了此直接调测通道;", "• 风险提示:合思后端缺乏沙箱隔离,真实写节点(如自动审批、HTTP请求)将直接在生产生效,且服务端已自动生成新快照版本。", "", ] : []), `====== 工作流自动化调测报告 [${pipelineId}] ======`, printKeyValue({ "工作流 ID (pipelineId)": pipelineId, "触发器类型": `[${category}] ${triggerLabel} (${triggerType})`, "生成 Job ID": report.jobId, "测试目标对象": targetDescription, "执行结果状态": report.status, "测试结果": report.outcome, "是否超时": String(report.timedOut), "诊断完整": String(report.diagnosticsComplete), "运行模式": report.runType, "总耗时(ms)": String(report.durationTime ?? "-"), "节点执行总数": report.executionTree.length, "异常/跳过节点数": report.failedExecutions.length, }), "", "── 顶层节点执行树 ──", treeRows.length ? printTable( ["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"], treeRows ) : "暂无顶层节点执行记录", ]; outLines.push(...warnings.map(warning => `⚠️ ${warning}`)); outLines.push(...report.diagnosticsErrors.map(error => `诊断读取失败 [${error.source}]: ${error.message}`)); if (report.conditionDiagnoses.length > 0) { outLines.push(""); outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──"); for (const diag of report.conditionDiagnoses) { outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`); outLines.push(` • 判定结论: ${diag.summary}`); outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`); if (diag.rules.length > 0) { outLines.push(" • 规则比对明细:"); for (const r of diag.rules) { const statusIcon = r.matched === null ? "?" : r.matched ? "✅" : "❌"; const missTag = r.isMissing ? " [⚠️ 属性缺失]" : ""; outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`); outLines.push(` ↳ ${r.detail}`); } } } } const codeSummaries = extractCodeNodeSummaries(report.executionTree); if (codeSummaries.length > 0) { outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId)); } if (savedSampleNodes.length > 0) { outLines.push(""); outLines.push("── ✨ 样本数据自动固化 (Sample Data Saved) ──"); outLines.push(`已自动将 ${savedSampleNodes.length} 个节点的真实调试出参固化为 sampleData 并刷新设计器选择树:`); for (const sn of savedSampleNodes) { outLines.push(` • [${sn.name}] (${sn.label}): 固化 ${sn.fieldCount} 个属性`); } } if (category === "WEBHOOK" && report.outcome !== "completed") { outLines.push(""); outLines.push("💡 [Webhook 流程调试提示]"); outLines.push(" 工作流首节点为 Webhook 触发器。若需向合思云端发起真实的 Webhook 事件调度流转,可直接运行:"); outLines.push(` hose-use workflow webhook send ${pipelineId}${flowCodeOrId ? ` --bill=${flowCodeOrId}` : ""} --yes`); } return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode, }; }