/** * commands/workflow/create.ts — 新建流程模板 (6 步 webapi 路径) * 修复 Bug 3 (流程编辑页无节点 + 提交报"系统异常") * 6 步 webapi 路径 (镜像 web 浏览器 AiCreateModal.vue 完整流程, 端到端可用): * 1. loadWorkflow.getAiInfo(keyword) → 走 web 端, prompt/parse/format 跟 web 一致 * 2. loadWorkflow.create(template) → 创建空模板 (走 /api/workflow/template) * 3. getVersionList(templateId) → 拿 versionId (走 /api/workflow/template/Version/{id}) * 4. buildFlowNodes(flowXml, formId) → 构造完整 flowNodes (含 global + 解析节点) * 5. loadWorkflow.save({type:1, ...}) → 真正发布 + 部署 (走 /api/workflow/template/Save) * 6. (caller 后续) /workflow/task 发起 * 镜像原型: * - web/apps/jnpf-web-apps-main/src/onlineDev/flowEngine/components/AiCreateModal.vue (AI 弹窗 + form 配置 + create) * - web/apps/jnpf-web-apps-main/src/onlineDev/flowEngine/DesignForm.vue:130-150 (handleRequest + saveFlow) * - web/apps/jnpf-web-apps-main/src/api/workFlow/template.ts: getAiInfo + create + saveFlow * - web/apps/jnpf-web-apps-main/src/FlowProcess/src/helper/config.ts:13-58 (defaultGlobalForm 模板) * - jnpf/.../flowable/util/FlowUtil.java:2134 (后端 launch 必查 global.getTitleType) * 简化 (app 2026-07-01): * - 移除老路径 (--no-ai-path / --auto-enable / 单独 PUT enabledMark) - 都是没用的中间步骤 * - --ai 默认走 6 步 webapi, --flowXml 用户直传也走 webapi 路径 * - 必填: --fullName + --category, --enCode 可选 (缺时从 fullName 自动生成 snake_case) */ import { Command } from 'commander' import { JnpfClient } from '../../core/client.ts' import { installHelpHookWithPatterns } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { setupOutputFilter, wrapCommand } from '../_output_filter.ts' // v2.2+ (2026-07-21): wrapCommand 收口 5c (9 process.exit + step machine throw) import { callAiWorkflow, detectTrivialFlowXml } from '../form/_ai.ts' import { buildFlowNodes, validateFlowNodeStructure } from './_webapi_helpers.ts' import { autoLayoutFlowXml, isLayoutNeeded } from './_autoLayout.ts' import { initWebapi, loadWorkflow } from '../../webapi/workflow.ts' import { getUserInfoApi } from '../../webapi/user.ts' import { validateWorkflowCreate, semanticLint } from './_validate.ts' import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): enCode/fullName strip 已统一到 runCommandAutoFix (commands/_auto_fix.ts), 不再 inline 调 autoStripEnCode/autoStripFullName (替代原 line 96-112 的 inline 调用 + warn log, BS-新38/BS-新52). interface CreateOpts { fullName?: string enCode?: string category?: string /** 流程类型 (0=标准 1=简流, 默认 0) */ type?: string /** start node 绑定的 formId (镜像 web 选表单步骤) */ startFormId?: string /** 用户直传 BPMN XML (跳过 AI, 也走 6 步路径) */ flowXml?: string flowConfig?: string iconBackground?: string showType?: string icon?: string /** 手动设 sortCode (默认 0, baseline 拖拽排序丢失) */ sortCode?: string /** (Round 8 P2): isLayoutNeeded 阈值 (默认 0.8 = 80% 重叠触发) */ layoutThreshold?: string json?: boolean verbose?: boolean /** 5.10.3 AI 创建流程 (--ai "<描述>") - 调 web 端 getAiInfo 拿 flowXml */ ai?: string /** 自动授权给当前角色 (镜像 web 流创建后行为) */ autoAuthorize?: boolean } /** 从 fullName 生成 enCode (snake_case) - 镜像 web form validate: 字母数字小数点, 不能放首尾 */ function autoEnCode(fullName: string): string { // 只保留 ASCII 字母数字和小数点; 其余 (中文/标点/下划线) 全删 (因为正则不允许 _) const cleaned = fullName.replace(/[^a-zA-Z0-9.]/g, '').toLowerCase() if (!cleaned) return 'workflow' // 中文开头, fallback // 首字符不能是数字或 . (enCode 正则要求首字母是字母) if (/^[0-9.]/.test(cleaned)) return `wf${cleaned}` return cleaned } export function buildWorkflowCreateCommand(): Command { const cmd = new Command('create') .description('新建流程模板 (6 步 webapi 路径: AI → create → version → buildFlowNodes(含global) → save(type=1 部署))') .option('--fullName ', '中文名 (必填)') .option('--enCode ', '英文编码 (必填或 auto: 从 fullName 生成 snake_case)') .option('--category ', '分类 id (必填, 跑 `dacli workflow selector` 看真实值, 或直接传中文 "项目管理")') .option('--type ', '流程类型 (0=标准 1=简流, 默认 0)', '0') .option('--flowXml ', 'BPMN xml (--ai 自动填; 用户直传跳过 AI)') .option('--flowConfig ', 'flowConfig JSON 字符串') .option('--iconBackground ', '图标背景色 (默认 #108ee9)', '#108ee9') .option('--icon ', '流程图标 (默认 icon-ym icon-ym-flow)', 'icon-ym icon-ym-flow') // 手动设 sortCode (默认 0) .option('--sortCode ', 'sortCode 排序 (默认 0)', '0') .option('--showType ', '显示位置 (0=全局 1=流程 2=菜单, 默认 0)', '0') .option('--startFormId ', '绑定的 formId (绑到 start 节点 formId, 镜像 web 选表单步骤)') .option('--layoutThreshold ', 'isLayoutNeeded 重叠阈值 (0-1, 默认 0.8 = 80% 触发 autoLayout)', '0.8') .option('--ai ', 'AI 创建流程 — 自然语言描述, 走 web 端 getAiInfo 拿 flowXml') .option('--auto-authorize', '创建后自动给当前角色授权', false) .option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false) .option('--json', '原始 JSON 输出', false) .action(async (opts: CreateOpts) => { // 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON // 复用 form 的输出过滤模式 (见 _output.ts) setupOutputFilter(opts) const c = await JnpfClient.fromToken() const startTime = Date.now() // v2.1+ (2026-07-21): 命令级 auto-fix pipeline (跨命令通用) // S-X1 enCode strip silent (BS-新38) // S-X2 fullName soften silent (BS-新52) // G-X1 BS-47 重名 suggest (含 appCode 前缀建议, 启用 G-X1 需 fetchExistingLists) // 替代原 line 96-112 的 inline autoStripEnCode/autoStripFullName + WARN 日志 // (Round 12-13 drift loop fix, 详见 commands/_auto_fix.ts:runCommandAutoFix + ADR-0010 §3) const fixCtx = await fetchExistingLists(c, c.appCode) const cmdFix = runCommandAutoFix(opts as unknown as Record, fixCtx) if (cmdFix.silent.length > 0) { Object.assign(opts, cmdFix.opts) } await wrapCommand({ command: 'workflow create', appCode: c.appCode, startTime, verbose: opts.verbose, json: opts.json, fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions], }, async (ctx) => { try { // (Round 8 P0): workflow 没绑 startFormId → 浏览器报 "workFlowForm/undefined.vue" // step 1 拦截: 提示用户传 --startFormId (web NodeFormParser.vue:59-64) if (!opts.startFormId) { log.warn(`BS-E3: workflow 未传 --startFormId, 浏览器流程设计器点击节点时会报 'workFlowForm/undefined.vue'`) log.warn(` 建议: dacli workflow create --startFormId= ... (参考 web NodeFormParser.vue:59-64 动态 import)`) } // (Round 8 P0): --ai 描述过短 → AI 返回乱流程 if (opts.ai && opts.ai.trim().length < 10) { log.warn(`BS-E4: --ai 描述过短 (${opts.ai.trim().length} 字符), AI 可能返回不完整流程`) log.warn(` 建议: 描述至少 10 字符, 含完整审批环节 (例: "员工提交 → 主管审批 → 财务付款")`) } // (Round 8 P0): workflow --category= 不存在 → 后端 400 模糊 // step 0 拦截: 跑 selector 查表, 不存在直接 exit 2 // v2.4+ (BS-E5-加强, tdd2 2026-07-25): category 不传时自动从已有 workflow 派生 if (!opts.category) { try { await initWebapi(c) const resp = (await loadWorkflow.getFlowSelector({})) as unknown const list = Array.isArray(resp) ? resp : ((resp as { list?: unknown[] })?.list || []) const firstWithCategory = (list as Array>).find((it) => it.category) if (firstWithCategory?.category) { opts.category = String(firstWithCategory.category) log.info(`BS-E5-加强: workflow category 自动派生: ${opts.category}`) } else { // 无任何 workflow 可参考, fallback 到固定 hex (跨 app 共享) opts.category = '802fb04ab5b84aa5bcc5dc53372a271d' log.warn(`BS-E5-加强: 无 workflow 可参考, fallback 到共享 category: ${opts.category}`) } } catch (e) { log.warn(`BS-E5-加强: 自动派生失败 (${(e as Error).message?.slice(0, 60)}), 使用共享 fallback`) opts.category = '802fb04ab5b84aa5bcc5dc53372a271d' } } if (opts.category) { try { await initWebapi(c) // 用 selector 不带 category 过滤拿全集 (返回所有可见 category id) const resp = (await loadWorkflow.getFlowSelector({})) as unknown const list = Array.isArray(resp) ? resp : ((resp as { list?: unknown[] })?.list || []) const allCategories = new Set() for (const item of list as Array>) { if (item.category) allCategories.add(String(item.category)) } // v0.22+ (2026-07-28 tdd5 实战): 中文分类名 (项目管理/费用相关) 在全新 app selector 里查不到 // 因为 selector 只返回本 app 已有 workflow 的 category。允许: // ① 32 位 hex hash (baseline 数据, 跨 app 通用, 如 802fb04ab5b84aa5bcc5dc53372a271d) // ② 已知 6 个 JNPF 平台内置中文分类 (项目管理/费用相关/人事管理/仓库管理/车辆管理/日常工作) // 这些是 JNPF 后端硬编码全局 category, 任何 app 都可使用 (后端二次转换显示) // 修复: 中文名不再报 BS-E5, 直接放行 (后端会落库并显示) const KNOWN_ZH_CATEGORIES = new Set(['项目管理', '费用相关', '人事管理', '仓库管理', '车辆管理', '日常工作']) const is32Hex = /^[a-f0-9]{32}$/.test(opts.category) const isKnownZh = KNOWN_ZH_CATEGORIES.has(opts.category) if (!allCategories.has(opts.category) && !is32Hex && !isKnownZh) { log.error(`BS-E5: workflow --category="${opts.category}" 不存在`) log.error(` 跑 'dacli workflow selector' 看真实分类 id (32 位 hash 或中文)`) return ctx.fail(`BS-E5: workflow --category="${opts.category}" 不存在`, { enCode: opts.enCode }) } } catch (e) { log.warn(`BS-E5: 查 workflow category 失败 (${(e as Error).message?.slice(0, 80)}), 跳过预校验`) } } // ========== 1. 解析 flowXml 来源 (AI 或 直传) ========== let flowXml: string | undefined = opts.flowXml if (!flowXml && opts.ai) { // 用户反馈 (2026-07-27): "form --ai 用输入框兜底可以接受, 但不能前两轮上来就用" // → LLM 是主路径, 拒绝太短/太模糊的输入走 LLM (浪费 5-15s token, 必返 trivial/坏结构) // → 短输入直接走后续 buildFormData 默认空 schema (web 默认), 行为跟 --enCode 透传一样 // 阈值: 10 字符 (中文 "请假流程" 4 字也低于 10) + 至少含 1 个名词性关键词 (请假/审批/设备…) const MIN_AI_CHARS = 10 if (opts.ai.trim().length < MIN_AI_CHARS) { log.warn(`--ai 描述过短 (${opts.ai.trim().length} 字符, 最低 ${MIN_AI_CHARS}), 跳过 LLM 走默认 schema`) log.warn(` 提示: 写清楚业务 + 关键字段, 例: "请假流程:员工提交→直属领导审批→HR 备案"`) log.warn(` 或先用 'dacli form optimize "..."' 改写 (P0-2), 或直接传 --flowXml `) opts.ai = '' // 触发下方"AI 失败/缺 enCode"路径 → 走 web buildFormData 默认空 schema } } if (!flowXml && opts.ai) { // P1-6 fix (2026-07-25): --ai 路径加载 web FlowProcess 全模块 + 5 节点递归, 默认 256MB 不够 // 检测 NODE_OPTIONS 是否设置, 缺则 WARN 提示重跑 (dacli 进程已启动, 不能 retroactively 设) if (!process.env.NODE_OPTIONS || !/max-old-space-size/.test(process.env.NODE_OPTIONS)) { log.warn(`P1-6: --ai 路径会 load web FlowProcess 全模块, 256MB 默认值不够, 易 OOM`) log.warn(` 建议重跑: NODE_OPTIONS="--max-old-space-size=4096" dacli workflow create --ai "..." ...`) log.warn(` (或传 --flowXml 跳过 AI 路径, 已知 tdd3 workflow --ai 实测 4GB 也爆)`) } log.info(`[step 1/6] --ai "${opts.ai.slice(0, 50)}${opts.ai.length > 50 ? '...' : ''}" — 调 web 端 getAiInfo`) let data = await callAiWorkflow(opts.ai) if (!data.flowXml) { log.error('AI 响应缺 flowXml, 无法自动建建') if (opts.json) printJson(data) return ctx.fail('AI 响应缺 flowXml, 无法自动建流程', { enCode: opts.enCode }) } flowXml = data.flowXml log.info(` ↳ AI 返回 flowXml 长度 ${flowXml.length} 字符`) // P1-5 (v0.23+ 修订): BPMN lint 检测 + 不重试 LLM, 走 dacli 兜底 // // 修订原因 (用户反馈 2026-07-27): "form --ai 用输入框兜底可以接受, 但不能前两轮上来就用" // → 含义: LLM 才是主路径; 输入框兜底仅在 LLM 不可用/产出不可用 时启用, 不能 ① 一上来就用 ② lint 失败就重试 LLM (浪费 5-15s token, 实测两次产出几乎一样) // // 现行设计: // ① 短/模糊输入 (≤10 字符) → 拒绝走 LLM, 直接走兜底 (dacli/buildFormData 默认空 schema) // 实测: "请假流程" (4 字符) 这种就属于 "用户没真写描述", 问 LLM 也是浪费 // ② 正常输入 → 走 LLM (主路径), 跑 lint // ③ lint 失败 → 不重试, 警告 + 继续 (后续 autoLayout + dacli 兜底会合成 DI 修复画布, 流程仍可用) // ④ LLM Login expired/token 失效 → 透明 fallback 到 web buildFormData (已有 P1-7 兜底) { const { parseFlowXml, validateFlowNodeStructure } = await import('./_webapi_helpers.ts') const lint = validateFlowNodeStructure(parseFlowXml(flowXml)) if (lint.errorList.length > 0) { log.warn(` ↳ P1-5 BPMN lint 不通过 (${lint.errorList.length} 项, 不重试 LLM, 走兜底):`) for (const e of lint.errorList) log.warn(` - ${e.error} (${e.webSource})`) log.info(` ↳ 兜底策略: autoLayout + _webapi_helpers.synthesizeDiagram 会补齐 BPMNDI 节点, 流程仍可保存运行`) } else { log.info(` ↳ P1-5 BPMN lint ✓: ${lint.nodeTypeCounts.start || 0} start + ${lint.nodeTypeCounts.approver || 0} approver + ${lint.nodeTypeCounts.end || 0} end + ${lint.nodeTypeCounts.exclusive || 0} exclusiveGateway`) } } // (Round 12 检测 AI 返回是否 trivial (≤1 userTask). // Round 12: 5/5 workflow --ai 都生 "Start → 审批 → End" 3-node trivial, baseline 节点全丢. // JNPF 后端 LLM prompt 缺节点规格, dacli 端不可修. // 客户端侦测 + WARN 推荐用 --flowXml 直传 baseline const trivial = detectTrivialFlowXml(flowXml) if (trivial.isTrivial) { log.warn(trivial.warning) log.warn(` --flowXml 用法: 拷贝 baseline 的 f_configuration.flowXml (Round 12: ${trivial.taskCount}/baseline 4-10 节点)`) } // C方案: 自动布局 (镜像 web handleAutoLayoutByHorizontal 思路) // AI 返回的 XML 所有节点 bounds=(400,300) 完全重叠, 不自动布局浏览器打开会全挤在一起 // bpmn-moddle 纯 XML 解析 (无 DOM 依赖), Node 端跑 BFS 水平布局 // (Round 8 P2): --layout-threshold 参数, 默认 0.8 (80% 重叠触发) const layoutThreshold = parseFloat(opts.layoutThreshold || '0.8') if (await isLayoutNeeded(flowXml, layoutThreshold)) { log.info(` ↳ 检测到 AI XML 节点/waypoint 坐标重叠 (阈值 ${layoutThreshold * 100}%), 触发自动布局 (B方案: 镜像 web bpmn-js handleAutoLayoutByHorizontal)`) flowXml = await autoLayoutFlowXml(flowXml) } } if (!flowXml) { log.error('必须传 --flowXml 或 --ai "<描述>" 之一') return ctx.fail('必须传 --flowXml 或 --ai "<描述>" 之一', { enCode: opts.enCode }) } // enCode 兜底: 缺时从 fullName 生成 const enCode = opts.enCode || (opts.fullName ? autoEnCode(opts.fullName) : 'workflow') // ========== 2. step machine 校验 (聚合错误一次报) ========== await runWorkflowStepMachine(c, { fullName: opts.fullName, enCode, category: opts.category, icon: opts.icon, showType: opts.showType, flowXml, }) // ========== 3. create template (空 flowNodes, 跟 web 一致) ========== log.info(`[step 2/6] POST /workflow/template (空 flowNodes, 跟 web AiCreateModal 一致)`) const createBody: Record = { fullName: opts.fullName, enCode, category: opts.category || null, type: Number(opts.type ?? '0'), flowXml, flowNodes: {}, flowConfig: opts.flowConfig || '{}', // --sortCode 透传 (默认 0) sortCode: parseInt(opts.sortCode || '0', 10), showType: Number(opts.showType ?? '0'), iconBackground: opts.iconBackground ?? '#108ee9', icon: opts.icon ?? 'icon-ym icon-ym-flow', } const createResp = await c.postJson('/workflow/template', createBody) if (createResp.code !== 200) { log.error(`创建失败 (code=${createResp.code}): ${createResp.msg}`) const enhanced = enhanceFromBackend(createResp.msg || '', 'workflow', { entity: 'workflow' }) log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: 'create template' })}`) // fix (stale pre-validate "已存在 SU001" cleanup + retry ONCE // 现象: 前次失败留的 partial workflow (templateId 已知 or enCode 已注册) 阻塞 retry. // 修法: 检测 "已存在/SU001/预校验" → 找 stale id → 删除 → 重试一次. const isStalePreValidate = /已存在|SU001|预校验|already exists/i.test(String(createResp.msg || '')) if (isStalePreValidate) { log.warn(`BS-新43b: stale pre-validate detected, 尝试清理 + retry`) let cleaned = false try { const list = (await c.get(`/workflow/template`, { keyword: enCode })) as | { data?: { list?: Array<{ id?: string }> } } | { list?: Array<{ id?: string }> } | Array<{ id?: string }> | undefined const arr = Array.isArray(list) ? list : ((list as { data?: { list?: any[] } })?.data?.list || (list as { list?: any[] })?.list || []) // templateId 还未声明 (line 224), 用 createResp.data 替代 const justCreatedId = typeof createResp.data === 'string' ? createResp.data : (createResp.data as { id?: string } | undefined)?.id || '' for (const stale of arr) { if (stale?.id && String(stale.id) !== String(justCreatedId)) { await initWebapi(c) await loadWorkflow.delFlow(String(stale.id)) log.warn(`BS-新43b: 清理 stale workflow id=${stale.id}`) cleaned = true } } } catch (e) { log.warn(`BS-新43b: stale cleanup 失败 (${(e as Error).message?.slice(0, 100)})`) } if (cleaned) { log.info(`BS-新43b: retry create ONCE after cleanup`) const retryResp = await c.postJson('/workflow/template', createBody) if (retryResp.code === 200) { log.ok(`BS-新43b: retry 成功`) Object.assign(createResp, retryResp) } else { log.error(`BS-新43b: retry 仍失败 (code=${retryResp.code}): ${retryResp.msg}`) return ctx.fail(`workflow create retry 仍失败 (code=${retryResp.code}): ${retryResp.msg}`, { enCode: opts.enCode }) } } else { return ctx.fail('workflow create 失败 (stale cleanup 未清理任何残留)', { enCode: opts.enCode }) } } else { return ctx.fail(`workflow create 失败 (code=${createResp.code}): ${createResp.msg}`, { enCode: opts.enCode }) } } const templateId = (typeof createResp.data === 'string' ? createResp.data : (createResp.data as { id?: string })?.id) || '' log.ok(` ↳ templateId = ${templateId}`) // ========== 4. getVersionList 拿 versionId ========== log.info(`[step 3/6] GET /workflow/template/Version/${templateId}`) const verResp = await c.get>(`/workflow/template/Version/${templateId}`) const versions = (verResp.data as unknown) as Array<{ id: string; state?: number }> || [] if (versions.length === 0) { log.error(`创建后没有 version 记录, templateId=${templateId}, 数据异常`) return ctx.fail(`创建后没有 version 记录, templateId=${templateId}, 数据异常`, { enCode: opts.enCode }) } const versionId = versions[0].id log.ok(` ↳ versionId (flowId) = ${versionId}`) // ========== 5. 构造完整 flowNodes (含 global 节点) ========== log.info(`[step 4/6] buildFlowNodes — 镜像 web FlowProcess.getData() 注入 defaultGlobalForm`) const flowNodes = buildFlowNodes(flowXml, { formId: opts.startFormId, category: opts.category }) const nodeCount = Object.keys(flowNodes).length const hasGlobal = 'global' in flowNodes log.ok(` ↳ ${nodeCount} 个节点 (含 global=${hasGlobal}, start.formId=${opts.startFormId || '(none)'})`) // 镜像 web bpmnLintUtil.ts 结构校验 (不创角色/节点数校验) const structCheck = validateFlowNodeStructure(flowNodes) if (structCheck.errorList.length > 0) { // 镜像 web 端 DesignForm.vue:130-134 (setErrorList + validatePopoverRef 弹窗) // dacli 走 log.warn + exit code 1 镜像 web "保存失败" 行为 for (const err of structCheck.errorList) { log.warn(` ↳ BS-drift-W-3 [${err.nodeType}]: ${err.error}`) log.warn(` (镜像 web ${err.webSource})`) } } else if (structCheck.okMessage) { log.ok(` ↳ ${structCheck.okMessage}`) } // 语义 lint — 阻断坏 BPMN 进后端 Flowable 部署. // 与 _webapi_helpers.validateFlowNodeStructure 互补: // - validateFlowNodeStructure 检查 flowNodes Map 形态 (数量/类型) // - semanticLint 检查原始 flowXml BPMN 语义 (assignee 解析, 多结束无合并) // 注入真实 webapi: getCurrentUser 调 JNPF /api/oauth/CurrentUser (src/webapi/user.ts getUserInfoApi). // getUserListByRole / getDeptManager 暂未在 web 端暴露, 保留 undefined → 解析时会 'api error' 阻断. const webapi = { getCurrentUser: async () => { try { return await getUserInfoApi(c, { systemCode: c.appCode, isBackend: 1 }) } catch { return null } }, } const semantic = await semanticLint(flowXml, { webapi }) if (!semantic.ok) { log.error(`✗ workflow 语义 lint 失败 (${semantic.errors.length} 个错误):`) for (const e of semantic.errors) { log.error(` - ${e}`) } for (const d of semantic.diagnostics) { log.error(` [${d.nodeId}] ${d.message}`) } // v2.2+ (2026-07-21): throw 替代 process.exit(1), wrapCommand handler catch → ctx.fail throw new Error( `WORKFLOW_SEMANTIC_INVALID: ${semantic.errors.length} errors. ` + `Fix BPMN userTask assignee / candidate before Save. ` + `Diagnostics: ${JSON.stringify(semantic.diagnostics)}`, ) } // ========== 6. save(type=1) 真正发布 + 部署 ========== log.info(`[step 5/6] POST /workflow/template/Save type=1 (关键: 真正发布+部署)`) const saveBody = { id: templateId, flowId: versionId, flowXml, flowConfig: opts.flowConfig || '{"visibleType":1}', type: 1, flowNodes, isAddVersion: false, } const saveResp = await c.postJson('/workflow/template/Save', saveBody) if (saveResp.code !== 200) { log.error(`Save 失败 (code=${saveResp.code}): ${saveResp.msg}`) const enhanced = enhanceFromBackend(saveResp.msg || '', 'workflow', { entity: 'workflow' }) log.error(` ${formatErrorLine(enhanced, { step: 5, stepName: 'save type=1' })}`) return ctx.fail(`Save 失败 (code=${saveResp.code}): ${saveResp.msg}`, { enCode: opts.enCode }) } log.ok(` ↳ Save 成功 (workflow 已部署到 Flowable)`) // ========== 7. 验证发布状态 ========== log.info(`[step 6/6] 验证发布状态`) const checkResp = await c.get<{ list?: Array<{ id: string; enabledMark?: number; status?: number; flowId?: string; enCode?: string }> }>('/workflow/template', { keyword: enCode, currentPage: 1, pageSize: 5, }) const list = (checkResp.data as { list?: Array<{ id: string; enabledMark?: number; status?: number; flowId?: string; enCode?: string }> } | undefined)?.list || [] const item = list[0] if (!item) { log.warn(` ↳ ⚠️ 发布后未找到流程, 请手动检查 (templateId=${templateId})`) } else { const enabled = item.enabledMark === 1 ? '✓' : '✗' const status = item.status === 1 ? '上架' : item.status === 0 ? '未上架' : item.status log.ok(` ↳ enabledMark=${enabled} (1=启用) status=${item.status} (${status}) flowId=${item.flowId || versionId}`) } // enCode 可能被 JNPF 流水号改 const actualEnCode = item?.enCode || enCode if (actualEnCode !== enCode) { log.warn(` ↳ JNPF 后端未采用用户传的 enCode, 实际 = ${actualEnCode} (JNPF 流水号机制)`) } // auto-authorize if (opts.autoAuthorize) { log.info(`--auto-authorize: 给当前角色授权 workflow (id=${templateId})`) try { const ar = await c.postJson('/permission/authorize', { objectType: 'flow', objectId: templateId }) if (ar.code === 200) log.ok(` ↳ ✓ 已授权给当前角色`) else log.warn(` ↳ --auto-authorize 部分失败: ${ar.msg}`) } catch (e) { log.warn(` ↳ --auto-authorize 异常: ${(e as Error).message?.slice(0, 100)}`) } } // 输出 log.ok(`\n✅ 6 步 webapi 路径完成`) log.info(` templateId: ${templateId}`) log.info(` enCode: ${actualEnCode}`) log.info(` flowId: ${item?.flowId || versionId} (← 可直接用于 dacli workflow launch)`) log.info(` 后续:`) log.info(` - 发起: dacli workflow launch --flowId=${item?.flowId || versionId} --formId={startFormId} --data='{...}'`) log.info(` - 详情: dacli workflow info --id=${templateId}`) if (opts.json) { printJson({ id: templateId, enCode: actualEnCode, fullName: opts.fullName, flowId: item?.flowId || versionId, versionId, flowXml, flowNodes, enabledMark: item?.enabledMark || 1, status: item?.status || 1, }) } // 输出过滤: 命令结束, 落 CommandLog (L3) + 打印摘要 + "详情: dacli log last" (L1) // v2.1+ (2026-07-21): 走新签名 { command, appCode, summary, fixes, duration_ms, verbose, json } ctx.success({ id: templateId, enCode: actualEnCode, flowId: item?.flowId || versionId, }) } catch (e) { ctx.fail(`workflow create 失败: ${(e as Error).message?.slice(0, 200)}`, { enCode: opts.enCode }) } }) }) installHelpHookWithPatterns(cmd, 'workflow create', { purpose: '新建流程模板 (v0.12+ BS-新27: 6 步 webapi 路径, 镜像 web AiCreateModal 端到端可用)', required: { '--fullName': '中文名', '--category': '分类 id 或中文' }, optional: { '--enCode': '英文编码 (缺时从 fullName 生成 snake_case)', '--type': '0=标准 1=简流 (默认 0)', '--flowXml': 'BPMN xml (--ai 自动填; 用户直传跳过 AI)', '--startFormId': '绑定的 formId (绑到 start 节点, 镜像 web 选表单步骤)', '--ai': 'AI 创建流程 — 自然语言描述, 走 web 端 getAiInfo 拿 flowXml', '--auto-authorize': '创建后自动给当前角色授权', }, example: [ 'dacli workflow create --fullName="请假流程" --category="项目管理" --ai "员工请假, 直属领导审批, HR 备案"', 'dacli workflow create --fullName="出差申请" --category="项目管理" --ai "出差申请:申请→部门经理→总经理→结束" --startFormId=841768605497428101', 'dacli workflow create --fullName="数据申请" --category="项目管理" --flowXml=\'\'', ], source: { web: 'web/apps/jnpf-web-apps-main/src/views/onlineDev/flowEngine/components/AiCreateModal.vue + web/apps/jnpf-web-apps-main/src/views/onlineDev/flowEngine/DesignForm.vue', api: 'POST /api/workflow/ai | POST /api/workflow/template | POST /api/workflow/template/Save', ref: 'web/apps/jnpf-web-apps-main/src/components/FlowProcess/src/helper/config.ts:13-58 defaultGlobalForm + web/apps/jnpf-web-apps-main/src/components/FlowProcess/src/index.vue:73-200 getData', }, notes: [ 'v0.12+ BS-新27 关键修复 (jxcj 2026-07-01 验证 LC20260701000003):', ' 1. --ai → web getAiInfo 拿 flowXml (避免 dacli 自写 LLM prompt 漂移)', ' 2. POST /workflow/template (空 flowNodes)', ' 3. GET /workflow/template/Version/{id} 拿 versionId', ' 4. buildFlowNodes 注入 defaultGlobalForm (镜像 web FlowProcess.getData())', ' 5. POST /workflow/template/Save type=1 (关键: 真正发布+部署, 不是 UpDownShelf)', ' 6. 验证 status + enabledMark', '关键: Save type=1 才会设 flowableId + flowId, UpDownShelf 只改 status', '关键: flowNodes 必须含 global 节点, 后端 FlowUtil:2134 必查 global.getTitleType', 'enCode 缺时自动从 fullName 生成 snake_case (中文 → 拼音待 v0.13+, 暂用 _ 替换)', ], }) return cmd } /** * step machine 校验 (3 步镜像 web flowEngine/Form.vue + 后端 TemplateController.create) */ async function runWorkflowStepMachine( c: JnpfClient, opts: { fullName?: string enCode?: string category?: string icon?: string showType?: string flowXml?: string }, ): Promise { let existingEnCodes: string[] = [] try { const r = await c.get<{ data?: { list?: Array<{ enCode: string }> } }>('/workflow/template', { currentPage: 1, pageSize: 1000, }) const list = (r.data as { list?: Array<{ enCode: string }> })?.list || [] existingEnCodes = list.map((t) => t.enCode).filter(Boolean) } catch { /* skip */ } const result = validateWorkflowCreate({ fullName: opts.fullName, enCode: opts.enCode, category: opts.category, icon: opts.icon, showType: opts.showType ? Number(opts.showType) : undefined, flowXml: opts.flowXml, existingEnCodes, }) if (!result.ok) { const allErrors = result.steps.flatMap((s) => s.errors.map((e) => ({ step: s.step, stepName: s.stepName, ...e })), ) log.error(`✗ step machine 校验失败 (${allErrors.length} 个错误):`) for (const e of allErrors) { log.error(` [step ${e.step} ${e.stepName}] ${e.field || '?'}: ${e.message}`) } // v2.2+ (2026-07-21): throw 替代 process.exit(1), wrapCommand handler catch → ctx.fail throw new Error(`step machine 校验失败 (${allErrors.length} 个错误)`) } log.info(`✓ step machine 校验通过 (3/3): enCode=${opts.enCode}`) }