Compare commits

..

30 Commits

Author SHA1 Message Date
821b79c9d8 Merge feat/process-modeler 阶段4: 模板新建流程 + Playwright e2e
Some checks failed
ci / build-test (push) Has been cancelled
- 4 模板(空白/单人/两级/会签,全小写元素名+isExecutable+DI,__PROCESS_ID__占位)+NewProcessDialog
  +中文key净化idMap发布restore;模板办理人表达式与codec逐字对齐回归断言
- Playwright live e2e 三场景(改存量全链/新建全链/走查+权限)对真8093/8089/5173真部署真起实例3绿

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 16:16:04 +08:00
3808011c8c test(modeler): Playwright live e2e 三场景(改存量/新建/走查+权限)
三场景对真实 8093 网关 + 8089 flowable-service + 真库 eip4 全程点穿:
- 场景A 改存量:/process-modeler?procKey=总包合同交底 → 点会签 userTask「编写交底」
  → EIP4 侧板会签控件读回勾选 → 存草稿(URL 回填 modelId) → 发布(PublishConfirm
  断言 key/版本/运行实例) → 确认 → 起实例 → trace 断言 current userTask。
- 场景B 新建:会签模板新建 → 选 task_cosign 填办理人 content=ADMIN → 存草稿 → 发布
  → 起实例 → trace 断言 current userTask「会签审批」。
- 场景C 走查+权限:中文节点渲染 / palette 齐 / 标准面板+EIP4 侧板同屏 / 超管门 403。

config 复用运行中的 5173 vite(默认 proxy /api→8093),apiJson 直连 8093 同一后端。
数据纪律:afterAll 删本次草稿(净零);发布产生的流程版本无下架端点属固有副作用。
场景C④ alice/123456 dev 库缺席 → 降级为无 token 打 deploy/models 断言 403(同
requireSuperAdmin 拒绝分支) + admin 打 models 200 对照。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 16:12:14 +08:00
54b0200ac0 test(modeler): 模板办理人表达式与codec逐字对齐回归断言(守命根)
I-1:模板里的 activiti:candidateUsers/collection 是硬编码字符串,与 candidateExpression
codec build 输出的逐字对齐此前只是实测、无测试守护。新增断言:从各模板 fromXML 解出属性值
(moddle 已解码 &quot;→真引号、保留全角【】,即 codec 处理的 businessObject 值层),
断言 === buildCandidateExpression(标准 item, 变体)(单人/两级 candidate、会签 multiInstance)。
模板 JSON 键序/转义漂移或 codec 改契约会被单测立即抓到,而非等 live 部署解析即断。

M-1:sanitizedId 加注释说明前端无碰撞去重的前提(新建模板仅 process key 一个非 ASCII id、
节点 id 全 ASCII → 碰撞不可达;未来引入中文节点 id 须对齐后端 -2/-3 去重)。

全量 vitest 273 绿、tsc -b exit 0。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 16:00:28 +08:00
2477f67afe feat(modeler): 新建流程(空白/单人/两级/会签4模板+NewProcessDialog)
模板库 src/modeler/templates/:4 个 BPMN 模板以真实流程为骨架抽形,全小写
元素名 + isExecutable="true" + 完整 BPMNDiagram DI;单人/两级带 activiti:candidateUsers
示例(全角【】+type:user),会签带 multiInstanceLoopCharacteristics+elementVariable+完成条件。
占位符 __PROCESS_ID__/__PROCESS_NAME__ 由 buildNewProcessXml 按用户 key/名称实例化:
ASCII key 直作 process id;中文 key 净化为 ASCII 并记 idMap(发布 restore 回中文 process key)。

NewProcessDialog:名称/key(可中文)/模板下拉,确认产实例化 XML 交父页 importXML。
ProcessModelerPage:新建流程按钮由 disabled 变可用→开对话框→pending newDraft 挂 Modeler+
import 模板(首存前不落草稿,走 createDraft 首存路径,展示名进草稿 name,diff 基线清空)。

模板正确性测试(fromXML 无警告/真序列化后全小写/isExecutable/会签含 multiInstance)+
NewProcessDialog+页面接线测试;全量 vitest 270 绿、tsc -b、build 通过。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:49:16 +08:00
ad8f63cf93 Merge feat/process-modeler 阶段3: 同人确认发布+diff+CRITICAL修复
Some checks failed
ci / build-test (push) Has been cancelled
- 节点级 diffSummary(命名空间感知按userTask id对齐,办理人codec比对/assignee/formKey/multiInstance)
- PublishConfirm(影响摘要key/版本/运行实例+变更节点清单+422结构化错误清单+同人确认)
- 发布 gating(无modelId提示先存)+原始源基线不被首存重置+发布前持久化(预览==部署)
- CRITICAL修复:activiti.json/flowable.json加tagAlias:lowerCase+自定义类型名PascalCase——
  修 bpmn-js Modeler.saveXML输出大写<Process>/<UserTask>致Flowable断部署;真Modeler序列化回归测试
- 全量 vitest 231+tsc+build 绿;live 验收发布 v9 中文key+起实例真userTask全通过

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:31:00 +08:00
8ea0ef2f1e fix(modeler): activiti.json 修 Modeler.saveXML 大写元素名(断部署)+真Modeler序列化回归测试
CRITICAL:bpmn-js Modeler.saveXML 把被 activiti.json `extends` 的 bpmn 类型序列化成
PascalCase 元素名(<Process>/<UserTask>/<StartEvent>…),未扩展的 <sequenceFlow>/<endEvent>
仍小写。Flowable 大小写敏感 → <Process> 不被识别为流程,ProcessValidator 报
flowable-process-definition-not-executable,部署完全失败。

根因:moddle 把「被扩展类型」的合并描述符 $pkg 设为**最后一个 trait 的包**(moddle
index.esm.js:577)。activiti 包缺 `xml.tagAlias:"lowerCase"`,故 moddle-xml 写元素名时不做
首字母小写 → PascalCase。且 tagAlias 是**双向**的(也驱动 fromXML 解析),要求自定义元素类型名
用 activiti/camunda 惯例的 PascalCase,否则解析 <activiti:taskListener> 找不到类型而丢弃。

修法(对齐 activiti/camunda-bpmn-moddle 标准):
- activiti.json + flowable.json 加 `"xml": { "tagAlias": "lowerCase" }`;
- 自定义元素类型名改 PascalCase:taskListener→TaskListener / executionListener→ExecutionListener
  / field→Field / formProperty→FormProperty / value→Value / in→In / out→Out(属性 type 引用同步)。
  XML 元素名仍小写(tagAlias),故 fixture 与「toContain('activiti:taskListener')」类 XML 断言不变。
- Eip4Panel.tsx:moddle.create/$type 用 'activiti:TaskListener';测试 fake 类型名同步。

为何旧测试没抓到:T1.1/T1.2 只断言 activiti 扩展属性/元素多重集,从不断言基础 BPMN 元素名大小写;
fromXML→toXML 与 create 都走同一 moddle-xml Writer 且都产 PascalCase(本 commit 实证)。

新增 serialization.test.ts(4 例,RED→GREEN):以 BpmnModdle(= Modeler.saveXML 的 moddle 层,
jsdom 跑不动 diagram-js SVG)驱动 fromXML→toXML 与 create→toXML,断言基础元素名全小写、无 PascalCase、
isExecutable 保留、扩展元素/属性不丢;flowable 隔离同验。

serialization 4 + fidelity 12 + Eip4Panel 37;全量 231 单测绿,tsc -b rc=0 + build 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 15:23:51 +08:00
0428a5c9d1 fix(modeler): 发布收口——原始源基线不被首存重置+发布前持久化(预览==部署)+跨命名空间diff测试
I1+I2 联锁修(同一根因:预览/diff 的两侧要对齐"打开时原始源"与"实际部署内容"):
- I1:新增 baselineTargetRef,openSourceRef 只在首次打开某目标时捕获原始源;存量首存
  setParams(modelId) 触发的 reload 因归属已预置为新 modelId 而保留基线,不再被冲成「已存版」
  →「打开存量→改办理人→存→发布」的 diff 恢复非空。
- I2:handlePublishClick 在开确认弹窗前先 saveDraft(currentXml) 持久化编辑器态,使
  后端 deploy 读到的服务端草稿 == 预览 == diff 的 current 侧(草稿改未存直接发布不再预览≠部署)。

Minor:
- M1:diffSummary 比 content 前做全角【】↔半角{} normWidth 归一(含 RAW 兜底路径),防宽度变体误报。
- M2:completionBody 折叠全部空白后比较,防 bpmn-js 重排空白误报完成条件变更。
- M3:PublishConfirm 发布中 guardedClose 拦截遮罩/X 关闭。

I3 测试:diffSummary 跨命名空间(默认 ns 源 vs bpmn: 前缀当前)对齐命中/前缀不误报 + M1 宽度变体;
页面 I1 锁(存量 save→publish 后 diff 基线仍原始源→清单非空,已 red-check 证伪防呆)+ I2(发布前 saveDraft)。

diffSummary 16 + PublishConfirm 9 + 页面 22;全量 227 单测绿,tsc -b rc=0 + build 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 14:39:52 +08:00
406f053ec2 feat(modeler): 同人确认发布(影响摘要+节点级diff+422校验错误清单)
- diffSummary.ts:DOMParser 命名空间感知的节点级 diff,按 userTask id 对齐比较
  办理人(candidateUsers,走 codec 比 items)/指派(assignee)/表单(formKey)/会签(有无·
  collection·completionCondition)四类,含新增/删除节点;坏 XML 返 []。
- processModeler.ts:deployModel(id)/fetchImpact(id),422 校验清单与通用失败归一进
  DeployOutcome(errors 兼容 flowable 对象式与网关字符串式两形态),impact 防御性 found。
- PublishConfirm.tsx:Dialog 展示流程 key/当前版本→新版本/运行中实例数(旧版本不受影响)
  + 变更节点清单;确认→deployModel 成功 toast「已发布 vN」并关闭,422→节点错误清单不关窗。
- ProcessModelerPage:顶栏发布按钮启用+gating(无 modelId 提示先存草稿),打开时存源 XML
  作 diff 基线。

diffSummary 13 + PublishConfirm 9 + 页面 21;全量 223 单测绿,tsc -b + build 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 14:10:46 +08:00
ac5ab12574 Merge feat/process-modeler 阶段2: 表达式codec+EIP4侧板+存草稿闭环
Some checks failed
ci / build-test (push) Has been cancelled
- 办理人/会签表达式 codec(与 BasePropertiesConverter 逐字对齐+stringToJson引号映射防截断JUEL;
  全库4794真实表达式往返实证零破坏)
- EIP4 侧板五控件(办理人meta透传/会签保真读回isSequential+elementVariable+自定义完成条件/
  formKey过滤/扩展属性/监听器field保留;切换节点无串台)
- 存草稿闭环(三路径保eip4IdMap+首存回填modelId防刷新重复+草稿列表/删除/formKey过滤输入)
- 全量 vitest 198+tsc+build 绿;live 验收总包合同交底存草稿→重开侧板忠实回显

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 13:18:10 +08:00
eba1704a55 fix(modeler): 首存回填modelId(防刷新重复草稿)+DELETE注释订正+placeholder保值测试
I-2:handleSaveDraft 在 createDraft/draftFromProcDef 成功后 setParams({modelId},{replace:true})
回填 ?modelId=,令刷新幂等(不再对同一 procKey 重复建草稿)、二次保存恒走 PUT。
测试:首存后按 modelId 重载(getModel('NEW-1'))证明回填生效;二次保存走 PUT NEW-1。

Minor:
- createDraft 的 metaInfo 补 sourceProcDefId 键,结构与 from-procdef 对齐(restore 只读
  eip4IdMap,但一致性利于 T3.x 影响摘要/审计)。
- deleteDraft 注释订正:后端 DELETE 已实现(impl-t21 f0d704d 网关同门转发),非「待补」。
- formKey placeholder 保值直测:过滤掉当前值后 select 仍保留该值(占位「(当前)」)。

测试 ProcessModelerPage 17→18、Eip4Panel 36→37;全量 vitest 198 绿 / tsc -b 干净 /
npm run build 成功。仅动自己文件。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 12:46:55 +08:00
5c2c0d95f6 feat(modeler): 存草稿闭环+草稿列表打开+formKey过滤输入
api/processModeler:新增 listModels/getModel/createDraft/saveDraft(PUT)/draftFromProcDef/
deleteDraft;fetchWfTemplates 改返 {templates,degraded} 透传数据源降级标记。

ProcessModelerPage:
- 顶栏「保存草稿」可用:saveXML({format:true})→有 modelId 走 PUT saveDraft(不重发 metaInfo,
  靠后端「不带 metaInfo 不覆盖」保住 eip4IdMap);无 modelId:存量按 procDefId 走 from-procdef
  (后端写 metaInfo)再 PUT 覆盖为编辑源,存量按 key/新建走 createDraft(前端把 source 载入的
  eip4IdMap 写进 metaInfo)。saving 态防重入。
- 打开器加「草稿」tab:listModels 列草稿→「打开」setParams(?modelId=)→getModel→importXML;
  载入草稿时从 metaInfo 解 eip4IdMap 存 ref(发布还原用)。
- 草稿删除按钮+confirm(deleteDraft;后端 DELETE 端点待补,前端契约先落)。

Eip4Panel formKey:1016 项加过滤输入(名称/id 实时 filter);未命名项(name 回落为 id)显示
「<uuid前8>…(未命名)」;degraded 显示「模板列表暂不可用」提示。

测试:Eip4Panel 33→36(formKey 过滤/未命名/degraded)、ProcessModelerPage 10→17
(存草稿 create/put/from-procdef 三路径 + ?modelId= 载入 + 草稿 tab 打开 + 删除确认/取消);
全量 vitest 196 绿 / tsc -b 干净 / npm run build 成功。仅动自己文件。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 12:14:37 +08:00
a9a304ab3d fix(modeler): 侧板评审收口——会签保真读回/切换节点回归测试/meta可见性+清除确认
I-1 会签保真:isSequential/elementVariable/completionCondition 原值读进 CosignState、
写回用读到的值(真实库 isSequential=true×2 / elementVariable=assign|loop_assign / 完成条件
>0.6×7 原强写会静默改坏派任);完成条件 body 不匹配预设→「自定义(保留)」态,仅主动选预设才
改写;elementVariable 缺省态与原本无 completionCondition 写回时省略,不凭空写空。parseCompletion
改精确匹配预设串(修 >0.55 误判过半的子串 bug)。新增串行开关+循环变量输入。

I-2 双节点回归:A(meta X)→B(meta Y)→编辑 B→写回 meta===Y≠X,防串台。

I-3 meta 可见性:顶部只读徽标显示非空业务 meta(如任务后置服务 PM_XXX);删光 items 且含非空
业务 meta 时 window.confirm 确认才写 undefined(取消则本地态与引擎均不变)。

顺手:扩展属性强制 activiti:/flowable: 前缀 + 拉黑有专用控件的键(candidateUsers/formKey/
collection/elementVariable);非标准办理人表达式(parse→null)显示「编辑将覆盖」警示;订阅
commandStack.changed,非自身写入时对当前选中重灌本地态(undo/redo 脱同步防线)。

测试 Eip4Panel 21→33;全量 vitest 186 绿 / tsc -b 干净 / npm run build 成功。仅动自己文件。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 12:01:26 +08:00
6fceff784d test(modeler): 侧板办理人补撇号转义用例(消费 codec 引号转义,防截断 JUEL)
新增 1 例:content 含撇号 O'Brien → 写回载荷内容段(剥离 JUEL 前后缀定界引号)
无裸 ASCII 单引号、含全角‘,验证侧板经 codec build 受引号转义保护。
Eip4Panel 测试 20→21;仅提交本测试文件,codec 由并行 T2.3 收口。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:38:08 +08:00
11632b4801 fix(modeler): codec 评审收口——stringToJson引号映射+半角content变体+item未知键透传+形状守卫
评审者跑全库 4794 条真实表达式往返对照原版序列化器,四项收口:
- I-1 build 补 stringToJson 引号契约(BasePropertiesConverter.java:235-280):字符串叶子值
  '→‘、"→“(经 JSON.stringify replacer,{}→【】由 halfToFull、\\与控制字符由 stringify 覆盖)。
  否则用户输入含 ' 截断外层 JUEL 单引号字面量 / 含 " 截断内层 JSON,部署后表达式解析即断。
  语料 ‘/“ 均 0 命中→对存量为 no-op,不破逐字往返。
- I-2 头注释纠偏:「content 不含花括号」被 20 条真实 ${users}(半角)证伪;改为事实——
  4774/4794 逐字,20 条半角 content 变体 build 归一为全角,引擎 :54 全局【→{ 还原后运行期等价。
- M-1 item 未知键 known-first 重排+按原序透传(与 meta 全量保留对称,不静默丢未来扩展键)。
- M-2 items 元素形状守卫:元素非对象或 type 非字符串→整体返 null 不抛。

加分:tools/codec-corpus-sweep.mjs(照 modeler-fidelity-sweep 风格,内联镜像 codec 跑全语料):
1512 文档 / 4794 表达式 → 逐字 4774 + 引擎运行期等价 20 + 解析失败 0 + 硬不匹配 0(门禁绿)。

测试 29 例(原 20 + 引号映射/幂等/meta 引号/半角变体运行期等价/未知键透传/形状守卫 9 例);
modeler 全量 66 例绿;tsc -b 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:36:53 +08:00
6dc9075648 feat(modeler): EIP4 侧板五控件(办理人meta透传/会签/formKey/扩展属性/监听器)
选中 userTask 时在标准属性面板上方叠加 React 侧板(§0.5 P5),全部写操作经
modeling.updateProperties(element,{...}),undo/redo 天然生效:
- 办理人:activiti:candidateUsers 经 codec parse→items 表格→build 写回,
  🔴 codec 外层业务 meta(taskSuccessService 等)存 ref、写回原样带回(硬要求用例覆盖)
- 会签:loopCharacteristics 开关(moddle.create MultiInstanceLoopCharacteristics,
  activiti:collection multiInstance 变体+elementVariable=assignee+completionCondition
  全票/过半/指定数 N 三预设);关→undefined
- formKey:GET /api/workflow/wftemplates 下拉写 activiti:formKey(裸 UUID),「无」清除
- 扩展属性:长尾 $attrs(activiti:/flowable:)增删改
- 任务监听器:activiti:taskListener event+class/delegateExpression 互斥;已有 field
  子元素显示徽标并原样保留(moddle 元素引用不动)

新增 useSelectedElement hook(订阅 selection.changed,单选返 element/多选空选 null/卸载解绑)。
ProcessModelerPage 右栏上方挂 Eip4Panel(modeler 入 state 驱动订阅)。
📌 红线回归:ProcessModelerPage 断言 moddleExtensions 键恰 ['activiti']、
additionalModules 长度 2(防双包冲突静默丢 userTask)。

测试:Eip4Panel 20 + useSelectedElement 5 + ProcessModelerPage 10(+1 红线);
全量 vitest 164 绿 / tsc -b 干净 / npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:35:13 +08:00
3dfb90f59b feat(modeler): 办理人/会签表达式编解码器(与 BasePropertiesConverter 逐字对齐)
纯前端纯函数 codec,parse/build 处理 businessObject 属性值层的办理人表达式。
前后缀常量逐字对齐 BasePropertiesConverter:34-35(candidate/multiInstance 两变体);
内容段全角【】↔{} 双向映射(build 恒全角,parse 兼容半角);外层 meta
(messageTemplate/taskSuccessService/isSkip* 等运行期业务字段)原样保留,侧板只改
items 也逐字往返不丢。content 逗号多值与 CHAR 尾部补白空格原样保留。

TDD:先红后绿。测试运行时从 synthetic-full-surface fixture 抽真实表达式锚定逐字形态。
20 例(真实 candidate/multiInstance 往返逐字 / 尾部空格保留 / 各 type 不丢字段 /
isSendMessage 可选往返 / 半角输入兼容 build 恒全角 / 非法输入返 null 不抛)全绿;
modeler 全量 32 例绿;tsc -b 干净。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:16:51 +08:00
d08a35fbbb Merge feat/process-modeler 阶段1: Modeler 前端骨架(moddle保真+/process-modeler页)
Some checks failed
ci / build-test (push) Has been cancelled
- vendored activiti/flowable moddle 描述符+语料双门测试(1512/1512 零丢失扫描工具,加固版回归门)
- /process-modeler 页:bpmn-js Modeler+标准属性面板(显式attachTo)+admin门+存量打开器(by-id/by-key双参)
- 设计中心「流程设计」入口;红线守住(只载activiti/无Camunda provider)
- 全量 vitest 118 例+tsc+build 绿;live 验收「总包合同交底」画布/palette/Multi-instance面板全渲染

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:08:27 +08:00
dffd1f32ef fix(modeler): 属性面板显式 attachTo 修挂载时序(live 实证)+canvas 分支错误提示
live 复验:画布/palette/选中/context pad 正常,但标准属性面板从不挂载
(document 中 .bio-properties-panel 为 0,容器 children=0)。

根因(本次修时 attachTo 测试逼出):属性面板宿主 <div data-testid=process-modeler-props>
**从未挂 ref={panelRef}** → 构造参数 propertiesPanel.parent 恒为 null,面板无处渲染。
- 补 ref={panelRef} 到 props 容器 div(真根因)。
- 构造后显式 (modeler.get('propertiesPanel')).attachTo(panelRef.current)——
  bpmn-js-properties-panel 规范补救,放 importXML 前、alive 检查内、panelRef 存在时。
- 顺带修 T1.5 评审 M-2:canvasRef 为 null 分支改为 setError(原停 loading 无提示)。

测试:ProcessModelerPage.test.tsx +1(Modeler stub get('propertiesPanel')→{attachTo},
断言 attachTo 恰调一次且实参是 props 容器 DOM)。stub get 改按 service 分派
(propertiesPanel/canvas)。全量 vitest 22 文件 118 例绿;tsc -b 干净;npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:05:23 +08:00
ae097f2a9c fix(modeler): 打开器改 by-key 载入(修 options source=model 语义缺口)
live 验收发现:本库 /api/process-select/options 的 143 个选项 source 全为 'model',
option.id 是 act_re_model id(非 procDefId)→ 按 id 载入永远 found:false;option.key 才是流程 key。

- processModeler.ts:加 fetchProcDefSourceByKey(key) → GET
  /api/workflow/process-definitions/by-key/{key}/source(key 常纯中文,encodeURIComponent;
  返回形状同 fetchProcDefSource,共用 normalizeProcDefSource:found:false 不解构 bpmnXml/idMap)。
  ProcessOption 加 source 字段。
- ProcessModelerPage:打开器双参分派——source==='processDefinition' 用 ?procDefId=<id>,
  其余(model/history)用 ?procKey=<key>;loadEffect 按参数派 by-id / by-key;
  过滤规则 !!o.id 改为 source==='processDefinition' ? !!o.id : !!o.key;
  选择器用索引取回选项对象避免路由二义。

测试:processModeler.test.ts +2(纯中文 key 编码 / by-key found:false)+ source 映射断言;
ProcessModelerPage.test.tsx +3(?procKey= 走 by-key 并 importXML / 选 model 选项派 by-key /
选 processDefinition 选项派 by-id)。全量 vitest 22 文件 117 例绿;tsc -b 干净;npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:59:24 +08:00
e131b8dee9 feat(modeler): /process-modeler 页骨架(Modeler+标准属性面板+存量载入+设计中心入口)
阶段1 T1.5:admin 门 + 三栏布局(左画布/右上 EIP4 侧板占位/右下标准属性面板)
+ bpmn-js lib/Modeler 挂载(只载 activiti moddle、只引标准 BpmnPropertiesProvider,
严禁 Camunda provider)+ ?procDefId= 时 fetchProcDefSource→importXML(idMap 存 ref)
+ 无参时 process-select 存量流程选择器 + 设计中心「流程设计」入口。

api: processModeler.ts(fetchProcDefSource / fetchProcessOptions,裸 JSON 防御性默认)。
- procDefId 用 encodeURIComponent 进 path(真实库 id 形如「总包合同交底:3:<uuid>」中文+冒号)。
- found:false 先判后返,不解构 bpmnXml/idMap(后端此分支省略这些键)。
tsconfig.app.json 开 resolveJsonModule(首个 app 代码 import json)。
bpmn-js-properties-panel 补 ambient d.ts(包未发布类型)。

测试:ProcessModelerPage.test.tsx 5 例 + processModeler.test.ts 6 例(含中文+冒号
procDefId 断言 URL 已编码 / found:false 只返 found 键 / amis 信封解包);
DesignCenterPage.entrances 加 dc-process-modeler admin-only 断言。
全量 vitest 22 文件 112 例绿;tsc -b 干净;npm run build 成功(bpmn-js 进主 bundle)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:37:36 +08:00
b391ee9f16 fix(modeler): 保真扫描回归加固——refs袋+unresolved入门+规模门+stderr(评审I1/M1/M2/M5)
- I1 引用回归盲区:surface() 新增 refs 袋(sourceRef/targetRef/bpmnElement/
  processRef/attachedToRef/default,与 sanitizeIds 同覆盖面)并入比对键;normWarn
  的 unresolved reference 类 warning 计入硬门 failures(净化/往返破坏连线的直接信号)。
- M1:删除未使用的 realFail。
- M2:新增 EXPECTED_TOTAL 环境变量(默认 1512),实际语料数不符即判失败;
  decodeFailures.length 并入硬门(过滤集内本应 100% 干净 UTF8)。
- M5:崩溃分支透出子进程 e.stderr。
- M3/M4:命名空间字面前缀识别的语料前提、extElemText trim 口径各加注释声明。

重跑实测(node tools/modeler-fidelity-sweep.mjs):匹配 1512/1512 零丢失,
解析异常 0,解码失败 0,warnings=0,exit 0;EXPECTED_TOTAL=9999 时 exit 1
(规模门生效)。npx vitest run src/modeler 12/12 绿;npx tsc -b 干净(exit 0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:15:49 +08:00
bd7c7fc697 fix(modeler): 描述符补 formProperty.value(sweep 0-warning 收口)
activiti.json formProperty 补 value isAttr(对齐 D6 完整描述符)。此前 4 例
unknown attribute <value> warning(均 Activiti 自带 demo 流程的 formProperty
value= 属性,如 VacationRequest)靠 lax $attrs 保留、本无数据丢失,补声明后消除。

重跑实测(node tools/modeler-fidelity-sweep.mjs,5433/eip4/eip3):
- 匹配 1512/1512 零丢失,解析异常 0,解码失败 0,warnings=0。
- 命名空间 activiti 1509 / flowable 3。
- npx vitest run src/modeler 12/12 绿;npx tsc -b 干净(exit 0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 10:02:09 +08:00
6eb856bb75 feat(modeler): 全量真实流程 moddle round-trip 保真扫描工具(实测 1512/1512 零丢失)
对本地 eip4 库(5433,search_path=eip3) act_ge_bytearray 全部真实 BPMN
(name_ like %.bpmn%/%.xml,共 1512)逐条 bpmn-moddle fromXML→toXML,
数据级(实体解码归一后)校验「activiti/flowable 扩展属性+扩展元素结构
+全部 bpmn 元素 id 集合」多重集往返一致。

- psql 子进程取数(不引 pg 依赖);命名空间嗅探后单载 activiti 或 flowable
  (T1.1 实证双载丢 userTask);进 moddle 前净化非法 id(镜像后端
  sanitizeBpmnIds,1445/1512 文档 process id 为中文,moddle 拒非 ASCII-NCName)。
- 实测: 匹配 1512/1512 零丢失(activiti 1509 / flowable 3);解析异常 0;
  解码失败 0。warnings 仅 4 例 unknown attribute <value>(formProperty
  value= 属性未声明,均 Activiti 自带 demo 流程,lax $attrs 保留,零丢失)。
- 解码守卫: 校验 base64→UTF8 无损,单列非 UTF8 文档。全表探明解码失败仅
  出现在非 BPMN 二进制资源(.png 1504 / var-* 87524),被 name 过滤器正确排除;
  真实 BPMN 语料 0 解码失败。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:59:54 +08:00
a2aeeba296 fix(modeler): T1.1 评审收口——bpmn-moddle 显式devDep+$attrs断言+类型声明
评审 I-1 / M-1 / TS7016 收口(承接 8fdfe68):
- I-1 幻影依赖:devDependencies 显式声明 bpmn-moddle ^8.1.0(npm dedupe 到与
  bpmn-js 同一份 8.1.0),保真测试不再依赖传递提升、与 Modeler 运行时同版本。
- M-1 断言意图纠偏:fidelity.test.ts 原注释「未声明时 .get() 返 undefined」实证有误——
  moddle .get() 对未声明属性会回落 $attrs 返原值(已实证:flowable:assignee 未声明时
  .get() 返 "X")。改注释 + 增 `expect($attrs?.['activiti:candidateUsers']).toBeUndefined()`
  直接断言值未落 lax $attrs(=真 typed 化,声明属性确不在 $attrs)。
- TS7016:新增 src/modeler/moddle/bpmn-moddle.d.ts(最小 ambient 声明)消编辑器诊断。

验证:npx vitest run src/modeler 12/12 绿;npx tsc -b 干净(exit 0)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:47:02 +08:00
8fdfe688f8 feat(modeler): activiti/flowable moddle 描述符 + 语料覆盖/round-trip 保真测试
在线流程 Modeler 阶段1 Task 1.1(P1 双门验收)。为 bpmn-js Modeler 载入
存量 activiti BPMN 提供 vendored moddle 描述符,并以合成 fixture 验证零丢失。

依赖(与 bpmn-js 17.11.1 兼容,实际解析版本):
- bpmn-js-properties-panel 5.60.0(package.json ^5.23.0)
- @bpmn-io/properties-panel 3.47.0(package.json ^3.23.0)
- bpmn-moddle 8.1.0(bpmn-js 传递依赖,直接 import)

交付:
- src/modeler/moddle/activiti.json:完整 activiti 命名空间描述符,覆盖 §0 实测
  全集——属性 formKey/candidateUsers/exclusive/assignee/collection/elementVariable/
  candidateGroups/autoStoreVariables/initiator/dueDate(按宿主 extends 到 UserTask/
  StartEvent/Process/ScriptTask/MultiInstanceLoopCharacteristics 等)+ 元素
  taskListener/formProperty/field/string/value/executionListener/in/out。
- src/modeler/moddle/flowable.json:flowable 命名空间镜像描述符(覆盖 flowable:assignee 等)。
- src/modeler/moddle/fixtures/synthetic-full-surface.bpmn.ts:合成 fixture,形态逐字
  对照真实流程「总包合同交底」——含全角【】办理人 JSON、多实例、taskListener+field/
  string、formProperty+value、boundaryEvent+timer、conditionExpression、完整 DI。
- src/modeler/moddle/fidelity.test.ts:12 用例(语料覆盖 + round-trip 零丢失)。

fixture 关键形态发现(实证):
- 办理人/会签 JSON 用**全角【】**包裹对象,方括号 [] 半角,引号在属性内以 &quot; 转义;
  content 尾部有 CHAR 补白空格(如 "4028...0f7d    ")——均需零丢失。
- candidateUsers 表达式解析后 byte-exact 等于原文;moddle 序列化把 '/" 输出为
  数字实体 &#39;/&#34;,全角【】原样保留(XML 语义等价、模型层零丢失)。

勘探实证并固化为回归测试的两条 moddle 约束:
- moddle-xml 拒绝中文 id(illegal ID,须 NCName ASCII)→ 这正是 D7 BpmnIdSanitizer
  在进 moddle 前净化、发布时还原的根本原因;fixture 用 ASCII id、中文仅留在 name。
- activiti+flowable 双包同载会因跨包同名 extends 属性(如 exclusive)冲突而丢弃 userTask
  → 按命名空间隔离加载;已验证 Modeler 单载 activiti 时 flowable 属性经 lax $attrs 零丢失
  往返(Task 1.5 Modeler 应单载 activiti)。

验证:npx vitest run src/modeler 12/12 绿;全量 101/101 绿;tsc -b 干净;npm run build 成功。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 09:35:23 +08:00
a807078595 Merge docs/readme-dev-fix-0702: README 联调指引修正
Some checks failed
ci / build-test (push) Has been cancelled
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 08:15:33 +08:00
7d4f26edd3 docs(readme): 修正过时联调指引(JDK17→21/8084→8093/账号/自举→build_devdb)
- 后端联调改走 scripts/run-dev.sh(dev :8093,JDK 21 守卫),删 JDK17 毒指引(项目必须 21,17 连编译都过不了)
- 账号分口径:dev 库 admin/111111(日常)/ local 自举 alice/123456(CI/对拍)
- .env 表 VITE_BACKEND_TARGET 默认对齐实际 8093
- 本地库指引:日常 eip4dev 用 build_devdb.sh,自举集仅 CI/对拍
- 页面 schema 契约行删「开发期静态 mock」过时表述;设计器行改「已闭环」

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 08:15:33 +08:00
d406a1629b Merge: 报表导出文件名/扩展名修复(受控 blob 下载)
Some checks failed
ci / build-test (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 14:01:16 +08:00
d80ea76974 fix(report): 导出 PDF/Excel 用受控下载,文件名/扩展名正确
导出按钮(actionType:url)默认 window.open 一个 attachment 响应,部分浏览器丢失 Content-Disposition 文件名 → 下载成 UUID、无扩展名、打不开。新增 reportDownload:自定义 amis env.jumpTo 拦截报表导出 URL,显式 fetch 成 blob 并用 <a download="<CD文件名>"> 落盘。filenameFromContentDisposition 优先取 filename*(UTF-8 真实报表名)而非前面的 UUID 兜底。前端改动,无需重转重导,覆盖全部报表导出。6 单测 + 浏览器实测 办公用品采购申请单.pdf/.xls。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 14:01:16 +08:00
8301db1f88 Merge feat/approval-closure: 审批抽屉协办/转阅多选人 + BPMN流程图(bpmn-js) + 会签进度横幅
Some checks failed
ci / build-test (push) Has been cancelled
2026-06-26 08:29:47 +08:00
43 changed files with 7185 additions and 14 deletions

View File

@@ -21,28 +21,33 @@ SDK 产物来自 C5 构建预演(eip4-poc 的 `sdk-local/`),整套渲染器(图
## 启动 ## 启动
前置:Node v22+,后端 platform-app(端口 8084),本地 PG(`localhost:5433/eip4m0`,已自举)。 前置:Node v22+、后端 **JDK 21**(严禁 26,Groovy 红线,见 `../eip4-platform/README.md`)、
本地 PG(`localhost:5433`,日常开发库 `eip4dev`,构建见下)。
```bash ```bash
npm install npm install
npm run dev # dev server :5173,/api 反代到后端(默认 8084) npm run dev # dev server :5173,/api 反代到后端(dev profile 默认 8093)
``` ```
浏览器开 http://localhost:5173/login,默认账号 `alice` / `123456`。 浏览器开 http://localhost:5173/login:
- **dev 库(eip4dev,日常开发)**:账号 `admin` / `111111`
- local 自举库(eip4m0,CI/对拍用):账号 `alice` / `123456`
### 后端联调(单独终端) ### 后端联调(单独终端)
```bash ```bash
cd ../eip4-platform cd ../eip4-platform
JAVA_HOME=/opt/homebrew/opt/openjdk@17 \ mvn -pl platform-app,flowable-service -am package -DskipTests # 先出 jar
mvn spring-boot:run -pl platform-app -Dspring-boot.run.profiles=local bash scripts/run-dev.sh platform # dev profile :8093(内置 JDK 21 守卫,自动关旧实例)
# 端口 8084;若被占,加 -Dspring-boot.run.arguments="--server.port=8090" # 审批流联调用: bash scripts/run-dev.sh both (再起 flowable-service :8089)
# 并把前端 .env 的 VITE_BACKEND_TARGET 同步改为 http://localhost:8090 # 日志 /tmp/eip4-platform.log;健康判定 curl :8093/v3/api-docs
# 前端反代端口冲突:复制 .env 为 .env.local 改 VITE_BACKEND_TARGET(已 gitignore)
``` ```
本地库自举(首次):依次灌入 `../eip4-platform/platform-parity/src/main/resources/bootstrap/` 日常开发库 `eip4dev` 构建:`bash tools/local-devdb/build_devdb.sh --drop-target`
的 `bootstrap-sys.sql` → `bootstrap-privilege.sql` → `bootstrap-auth.sql`, (约 6 分钟,需内网可达客户库副本 192.168.20.68:5435)。
再灌 `platform-flow-gateway/.../bootstrap-datastatus.sql`(详见 P4 报告附录)。 CI/对拍走 local profile + `eip4m0` 极简自举集(bootstrap SQL 见
`platform-parity/src/main/resources/bootstrap/`,含 alice 测试账号)。
## 构建 ## 构建
@@ -62,7 +67,7 @@ Nginx 关键配置:SPA 路由回退 `try_files $uri /index.html`;`/api` 反代
| 变量 | 默认 | 说明 | | 变量 | 默认 | 说明 |
|------|------|------| |------|------|------|
| `VITE_BACKEND_TARGET` | `http://localhost:8084` | dev server 的 `/api` 反代目标;8084 被占改 8090 | | `VITE_BACKEND_TARGET` | `http://localhost:8093` | dev server 的 `/api` 反代目标(dev profile 后端);冲突用 `.env.local` 覆盖 |
| `VITE_SCHEMA_SOURCE` | `mock` | `mock`=读 `public/schemas/`;`backend`=读后端 schema 接口 | | `VITE_SCHEMA_SOURCE` | `mock` | `mock`=读 `public/schemas/`;`backend`=读后端 schema 接口 |
## 与后端契约清单 ## 与后端契约清单
@@ -72,7 +77,7 @@ Nginx 关键配置:SPA 路由回退 `try_files $uri /index.html`;`/api` 反代
| 登录签发 JWT | `POST /api/auth/login` | platform-auth/P2认证实测报告.md | `src/api/auth.ts` | | 登录签发 JWT | `POST /api/auth/login` | platform-auth/P2认证实测报告.md | `src/api/auth.ts` |
| 实体 amis CRUD 列表 | `GET /api/entity/{t}/list` | EntityController(amis 格式 `{status,msg,data:{items,total}}`) | `src/components/AmisRenderer.tsx`(fetcher) | | 实体 amis CRUD 列表 | `GET /api/entity/{t}/list` | EntityController(amis 格式 `{status,msg,data:{items,total}}`) | `src/components/AmisRenderer.tsx`(fetcher) |
| 待办聚合 | `GET /api/todo` | platform-flow-gateway/P3网关实测报告.md(503 熔断降级) | `src/api/todo.ts` | | 待办聚合 | `GET /api/todo` | platform-flow-gateway/P3网关实测报告.md(503 熔断降级) | `src/api/todo.ts` |
| 页面 schema(生产期) | `GET /api/page/schema/{templateId}` | **本期设计契约**(P5 后端落地),开发期用静态 mock 替代 | `src/api/schema.ts` | | 页面 schema | `GET /api/page/schema/{templateId}` | PageSchemaController(`sys_page_schema` 唯一真相,已落地) | `src/api/schema.ts` |
JWT 经 `src/api/http.ts` 拦截器注入 `Authorization: Bearer`;401(非登录端点)自动清会话 + 跳 `/login`。 JWT 经 `src/api/http.ts` 拦截器注入 `Authorization: Bearer`;401(非登录端点)自动清会话 + 跳 `/login`。
@@ -89,7 +94,7 @@ JWT 经 `src/api/http.ts` 拦截器注入 `Authorization: Bearer`;401(非登录
- amis 锁 6.13.0 本地化部署,不依赖 CDN(SDK 在 `public/sdk-local/`,来源见 C5 构建预演)✅ - amis 锁 6.13.0 本地化部署,不依赖 CDN(SDK 在 `public/sdk-local/`,来源见 C5 构建预演)✅
- 渲染宿主参照 PoC `amis-local.html`(本地 SDK 引用方式)✅ - 渲染宿主参照 PoC `amis-local.html`(本地 SDK 引用方式)✅
- 页面 schema 双闸:官方 schema.json 校验闸 + 运行时渲染冒烟闸(迁移手册 §8)✅ - 页面 schema 双闸:官方 schema.json 校验闸 + 运行时渲染冒烟闸(迁移手册 §8)✅
- 设计器(amis-editor 二开)排 P4 后半,本期未做(装配点见 P4 报告遗留)✅ - 设计器:amis-editor 已接入并闭环(`src/editor/DesignerPage.tsx` + `editor.html`,设计中心独立 tab)✅
- 渲染层备选(amis fork 失败时):lowcode-engine / ProComponents(架构设计第七节)✅ - 渲染层备选(amis fork 失败时):lowcode-engine / ProComponents(架构设计第七节)✅
## 目录 ## 目录

264
e2e/process-modeler.spec.ts Normal file
View File

@@ -0,0 +1,264 @@
/**
* 在线流程 Modeler(B3)· 浏览器全程点穿 live e2e(实施计划 Task 4.2)。
*
* 三场景(真部署真起实例真验收,不 mock):
* A 改存量全链:登录 admin → /process-modeler?procKey=总包合同交底 → 画布渲染 → 点会签 userTask「编写交底」
* → EIP4 侧板会签控件可见且「启用会签」勾选(保真读回)→ 保存草稿(URL 回填 ?modelId=)→ 发布
* (PublishConfirm 断言含流程 key「总包合同交底」+ 版本 + 运行中实例数)→ 确认 → apiJson 起实例
* → trace 断言有 current userTask(证部署的存量流程经 moddle 往返后小写元素仍被引擎识别、可派任)。
* B 新建全链:新建流程 → 选「会签」模板 + 填名称/key → 进编辑器(画布非空)→ 选 task_cosign 填会签办理人
* content=ADMIN(否则空集合运行期被跳过、不生成任务)→ 保存草稿 → 发布 → 确认 → apiJson 起实例
* → trace 断言 current userTask「会签审批」(证 bpmn-js 新建的小写 BPMN 部署后真产任务)。
* C 走查 + 权限:①中文节点名渲染正常 ②palette 元素齐 ③标准属性面板 + EIP4 侧板同屏
* ④超管门:非超管访问 deploy/models 网关端点断言 403(见下方 alice 降级说明)。
*
* 依赖:8093 网关/后端 + 8089 flowable-service + 5173 vite dev 均在线(见 playwright.process-modeler.config.ts)。
* 自检:curl -s -o /dev/null -w '%{http_code}' localhost:8093/v3/api-docs(200)、curl localhost:5173(200)。
* 跑法:npx playwright test -c playwright.process-modeler.config.ts
*
* 数据纪律:afterAll 删本次建的草稿(act_re_model,DELETE /api/workflow/models/{id})。发布产生的流程新版本
* 无运行时下架端点(同 §F net-new),属 live 验收固有副作用——每跑一次「总包合同交底」版本 +1、B 新建一个净新 key。
*
* ⚠️ 场景 C④ alice 降级:dev 库无 alice/123456 账号(登录返 success:false),无法用真实非超管 token 打 deploy。
* 降级为等价断言:非超管凭据(无 token)打 deploy/models → 403(走的正是 ProcessModelerController.requireSuperAdmin
* 的 principal==null → 非 isSystemAdmin → 403 分支,与「合法非超管 token → 403」同一段代码),并用 admin token
* 打 models → 200 作对照,证超管门确在按身份区分放行/拒绝。alice 登录失败一并断言以记录账号缺席事实。
*/
import { expect, test } from '@playwright/test';
import http from 'node:http';
// apiJson 直连后端 8093(与 UI 经 5173 vite 代理的目标同一后端,故 UI 建的草稿 apiJson 可见)。
const BACKEND_PORT = 8093;
const ZONGBAO_KEY = '总包合同交底';
// 存量会签流程「总包合同交底」的会签 userTask id(净化源里 sid- 前缀为 ASCII 不被改写,即 bpmn-js data-element-id)。
const COSIGN_TASK_ID = 'sid-2AB0790B-7C9B-4872-8753-BC3DB644568C';
// 本次运行建的草稿 id,afterAll 清理。
const createdModelIds: string[] = [];
function apiJson(
method: string,
path: string,
token?: string,
body?: unknown,
): Promise<{ status: number; json: any }> {
return new Promise((resolve, reject) => {
const data = body ? JSON.stringify(body) : undefined;
const req = http.request(
{
hostname: 'localhost',
port: BACKEND_PORT,
path,
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(data ? { 'Content-Length': Buffer.byteLength(data) } : {}),
},
},
(res) => {
let buf = '';
res.on('data', (c) => (buf += c));
res.on('end', () => {
try {
resolve({ status: res.statusCode ?? 0, json: buf ? JSON.parse(buf) : null });
} catch {
resolve({ status: res.statusCode ?? 0, json: buf });
}
});
},
);
req.on('error', reject);
if (data) req.write(data);
req.end();
});
}
async function adminToken(): Promise<string> {
const r = await apiJson('POST', '/api/auth/login', undefined, { account: 'admin', password: '111111' });
return r.json.token as string;
}
// 真实 React 登录表单(复用 five-ring 惯例:第一个 textbox=账号、type=password=密码、按钮「登录」)。
async function loginAdmin(page: import('@playwright/test').Page) {
await page.goto('/login');
await page.getByRole('textbox').first().fill('admin');
await page.locator('input[type="password"]').fill('111111');
await page.getByRole('button', { name: '登录' }).click();
await page.waitForURL((u) => !u.pathname.endsWith('/login'), { timeout: 15_000 });
}
// 点击画布上指定 BPMN 元素(bpmn-js 在 shape g 上挂 data-element-id)。
async function selectBpmnElement(page: import('@playwright/test').Page, elementId: string) {
const el = page.locator(`[data-testid="process-modeler-canvas"] [data-element-id="${elementId}"]`);
await expect(el).toBeVisible({ timeout: 15_000 });
await el.click();
}
// 记住 URL 里回填的 ?modelId=,供 afterAll 清理。
function rememberModelId(page: import('@playwright/test').Page): string {
const id = new URL(page.url()).searchParams.get('modelId') ?? '';
if (id && !createdModelIds.includes(id)) createdModelIds.push(id);
return id;
}
// 起实例 + trace 断言:部署的流程 start 后必有 current userTask(证小写元素被引擎识别并派任)。
async function assertTaskGenerated(key: string, businessKey: string, token: string): Promise<void> {
const started = await apiJson('POST', '/api/process/start', token, {
processDefinitionKey: key,
businessKey,
});
expect(started.status, 'start 应 200').toBe(200);
const iid = started.json?.id;
expect(iid, 'start 应返回流程实例 id').toBeTruthy();
await expect
.poll(
async () => {
const t = await apiJson('GET', `/api/flow/process/${iid}/trace`, token);
const rows = Array.isArray(t.json) ? t.json : (t.json?.data ?? []);
return (rows as any[]).filter((r) => r && r.current && r.taskId).length;
},
{ timeout: 15_000, message: `${key} start 后应有 current userTask(证部署流程含真 userTask)` },
)
.toBeGreaterThan(0);
}
test.afterAll(async () => {
try {
const tok = await adminToken();
for (const id of createdModelIds) {
await apiJson('DELETE', `/api/workflow/models/${id}`, tok);
}
} catch {
/* 清理尽力而为 */
}
});
// ────────────────────────────────────────────────────────────────────────────
// 场景 A:改存量全链(打开→会签保真读回→存草稿→发布→起实例→任务生成)
// ────────────────────────────────────────────────────────────────────────────
test('场景A 改存量全链:总包合同交底 打开→会签读回→存草稿→发布→起实例生成任务', async ({ page }) => {
test.setTimeout(150_000);
await loginAdmin(page);
// 打开存量会签流程(中文 key 必须 encodeURIComponent 进 URL)。
await page.goto(`/process-modeler?procKey=${encodeURIComponent(ZONGBAO_KEY)}`);
// 画布渲染完成:出现 bpmn 元素(.djs-element)。
await expect(page.locator('[data-testid="process-modeler-canvas"] .djs-element').first()).toBeVisible({
timeout: 30_000,
});
// 点会签 userTask「编写交底」→ EIP4 侧板会签控件可见 + 「启用会签」勾选(保真读回存量会签配置)。
await selectBpmnElement(page, COSIGN_TASK_ID);
await expect(page.getByTestId('process-modeler-eip4-panel')).toBeVisible();
await expect(page.getByTestId('eip4-cosign-toggle')).toBeChecked();
// 保存草稿 → URL 回填 ?modelId=(存量按 key 打开走 createDraft)。
await page.getByTestId('process-modeler-save-draft').click();
await page.waitForURL(/[?&]modelId=/, { timeout: 20_000 });
const modelId = rememberModelId(page);
expect(modelId, '存草稿后 URL 应回填 modelId').toBeTruthy();
// 存草稿会以 modelId 重载画布——等发布按钮重新可用(modelerReady)再点发布。
await expect(page.getByTestId('process-modeler-publish')).toBeEnabled({ timeout: 20_000 });
await page.getByTestId('process-modeler-publish').click();
// 同人确认弹窗:断言影响摘要含流程 key「总包合同交底」+ 版本迁移 + 运行中实例数。
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeVisible({ timeout: 20_000 });
await expect(page.getByTestId('publish-impact-key')).toContainText(ZONGBAO_KEY);
await expect(page.getByTestId('publish-impact-version')).toContainText(/首次发布|v\d+\s*→\s*v\d+/);
await expect(page.getByTestId('publish-impact-instances')).toHaveText(/\d/);
// 确认发布 → 成功后弹窗关闭(onPublished→onClose)。
await page.getByTestId('publish-confirm-btn').click();
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeHidden({ timeout: 30_000 });
// 起实例 + trace 断言:部署的新版本 start 后有 current userTask。
const tok = await adminToken();
await assertTaskGenerated(ZONGBAO_KEY, `E2E-A-${Date.now()}`, tok);
});
// ────────────────────────────────────────────────────────────────────────────
// 场景 B:新建全链(会签模板→填办理人→存草稿→发布→起实例→任务生成)
// ────────────────────────────────────────────────────────────────────────────
test('场景B 新建全链:会签模板新建→填办理人→存草稿→发布→起实例生成任务', async ({ page }) => {
test.setTimeout(150_000);
const newKey = `e2anew${Date.now()}`; // ASCII NCName → 直接作 process id,无需 idMap 还原
await loginAdmin(page);
await page.goto('/process-modeler');
// 打开器「+ 新建流程」→ NewProcessDialog。
await page.getByTestId('process-modeler-new').click();
await page.getByTestId('new-process-name').fill('会签E2E演示');
await page.getByTestId('new-process-key').fill(newKey);
await page.getByTestId('new-process-template').selectOption('cosign');
await page.getByTestId('new-process-confirm').click();
// 进编辑器:画布非空(模板实例化)。
await expect(page.locator('[data-testid="process-modeler-canvas"] .djs-element').first()).toBeVisible({
timeout: 20_000,
});
// 选会签 userTask(模板 id=task_cosign)→ 会签已启用(保真)→ 填办理人 content=ADMIN
//(会签集合非空,运行期才真产任务;空 content 会被 MI 跳过导致流程直接结束、无任务)。
await selectBpmnElement(page, 'task_cosign');
await expect(page.getByTestId('eip4-cosign-toggle')).toBeChecked();
await page.getByTestId('eip4-cosign-content-0').fill('ADMIN');
// 保存草稿 → URL 回填 modelId。
await page.getByTestId('process-modeler-save-draft').click();
await page.waitForURL(/[?&]modelId=/, { timeout: 20_000 });
rememberModelId(page);
// 发布。
await expect(page.getByTestId('process-modeler-publish')).toBeEnabled({ timeout: 20_000 });
await page.getByTestId('process-modeler-publish').click();
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeVisible({ timeout: 20_000 });
await expect(page.getByTestId('publish-impact-key')).toContainText(newKey);
await page.getByTestId('publish-confirm-btn').click();
await expect(page.getByTestId('process-modeler-publish-confirm')).toBeHidden({ timeout: 30_000 });
// 起实例 + trace 断言:新建部署的会签流程 start 后有 current userTask。
const tok = await adminToken();
await assertTaskGenerated(newKey, `E2E-B-${Date.now()}`, tok);
});
// ────────────────────────────────────────────────────────────────────────────
// 场景 C:走查(中文节点/palette/双面板同屏)+ 权限(超管门 403)
// ────────────────────────────────────────────────────────────────────────────
test('场景C 走查+权限:中文节点/palette/标准面板+EIP4侧板同屏 + 超管门403', async ({ page }) => {
test.setTimeout(120_000);
await loginAdmin(page);
await page.goto(`/process-modeler?procKey=${encodeURIComponent(ZONGBAO_KEY)}`);
const canvas = page.locator('[data-testid="process-modeler-canvas"]');
await expect(canvas.locator('.djs-element').first()).toBeVisible({ timeout: 30_000 });
// ① 中文节点名渲染正常(存量会签流程节点「编写交底」「接收交底」)。
await expect(canvas.getByText('编写交底')).toBeVisible();
await expect(canvas.getByText('接收交底')).toBeVisible();
// ② palette 元素齐(bpmn-js Modeler 左侧工具箱有多个可拖建条目)。
await expect(page.locator('[data-testid="process-modeler-root"] .djs-palette').first()).toBeVisible();
expect(await page.locator('[data-testid="process-modeler-root"] .djs-palette .entry').count()).toBeGreaterThan(4);
// ③ 标准属性面板 + EIP4 侧板同屏(选中会签 userTask 后 EIP4 侧板出真控件,与标准面板宿主并存)。
await selectBpmnElement(page, COSIGN_TASK_ID);
await expect(page.getByTestId('process-modeler-eip4-panel')).toBeVisible();
await expect(page.getByTestId('eip4-cosign-toggle')).toBeVisible();
await expect(page.getByTestId('process-modeler-props')).toBeVisible();
// ④ 超管门 403:dev 库无 alice/123456 → 降级为「非超管凭据打 deploy/models → 403」等价断言。
const alice = await apiJson('POST', '/api/auth/login', undefined, { account: 'alice', password: '123456' });
expect(alice.json?.success, 'dev 库无 alice 账号(记录账号缺席)').toBeFalsy();
// 无 token(非超管)打 Modeler 网关端点 → requireSuperAdmin 拒 403(与合法非超管 token 同一拒绝分支)。
const denyDeploy = await apiJson('POST', '/api/workflow/models/nonexistent/deploy');
expect(denyDeploy.status, '非超管访问 deploy 端点应 403').toBe(403);
const denyModels = await apiJson('GET', '/api/workflow/models');
expect(denyModels.status, '非超管访问 models 列表应 403').toBe(403);
// 对照:admin(超管)打 models → 200,证超管门按身份区分放行,非一律拒。
const tok = await adminToken();
const allowModels = await apiJson('GET', '/api/workflow/models', tok);
expect(allowModels.status, 'admin 超管访问 models 应 200').toBe(200);
});

627
package-lock.json generated
View File

@@ -8,8 +8,10 @@
"name": "eip4-web", "name": "eip4-web",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@bpmn-io/properties-panel": "^3.47.0",
"axios": "1.7.9", "axios": "1.7.9",
"bpmn-js": "^17.11.1", "bpmn-js": "^17.11.1",
"bpmn-js-properties-panel": "^5.60.0",
"react": "18.3.1", "react": "18.3.1",
"react-dom": "18.3.1", "react-dom": "18.3.1",
"react-router-dom": "6.28.0" "react-router-dom": "6.28.0"
@@ -29,6 +31,7 @@
"amis-formula": "^6.13.0", "amis-formula": "^6.13.0",
"amis-theme-editor-helper": "^6.12.0-ab.1", "amis-theme-editor-helper": "^6.12.0-ab.1",
"amis-ui": "^6.13.0", "amis-ui": "^6.13.0",
"bpmn-moddle": "^8.1.0",
"i18n-runtime": "^1.0.13", "i18n-runtime": "^1.0.13",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"typescript": "5.6.3", "typescript": "5.6.3",
@@ -386,6 +389,24 @@
"node": ">=6.9.0" "node": ">=6.9.0"
} }
}, },
"node_modules/@bpmn-io/cm-theme": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/@bpmn-io/cm-theme/-/cm-theme-0.2.2.tgz",
"integrity": "sha512-9mD7fzzNDNBgseOUC6iRX4mi17LIO2es4zkcHt4e4owQC2Q3YPvqJTJaXqc7kkItloSFsqG2j/1iMJkpvjLv2A==",
"license": "MIT",
"peer": true,
"dependencies": {
"@codemirror/language": "^6.12.3",
"@lezer/highlight": "^1.2.3"
},
"engines": {
"node": ">= 20.12.0"
},
"peerDependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0"
}
},
"node_modules/@bpmn-io/diagram-js-ui": { "node_modules/@bpmn-io/diagram-js-ui": {
"version": "0.2.4", "version": "0.2.4",
"resolved": "https://registry.npmjs.org/@bpmn-io/diagram-js-ui/-/diagram-js-ui-0.2.4.tgz", "resolved": "https://registry.npmjs.org/@bpmn-io/diagram-js-ui/-/diagram-js-ui-0.2.4.tgz",
@@ -396,6 +417,307 @@
"preact": "^10.29.2" "preact": "^10.29.2"
} }
}, },
"node_modules/@bpmn-io/extract-process-variables": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/@bpmn-io/extract-process-variables/-/extract-process-variables-2.2.1.tgz",
"integrity": "sha512-1E5ydNzTqgx513NxA1nxk2CqDb9OkusfU9Tf6WejD1BiY+5u130XnZOFE/FQX0JB6ZmPOeFMx4IDEuHjrGhOzw==",
"license": "MIT",
"dependencies": {
"min-dash": "^5.0.0"
}
},
"node_modules/@bpmn-io/extract-process-variables/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/@bpmn-io/feel-editor": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@bpmn-io/feel-editor/-/feel-editor-2.6.0.tgz",
"integrity": "sha512-rI7vFBATeKJVi/KpkfxnclTObAvQGYda0l5eKhNwGIJ8D3+aPQlgdNtxJATX1keXVkqsA1Q/+Yn8Ih+dnC0NMw==",
"license": "MIT",
"dependencies": {
"@bpmn-io/feel-lint": "^3.1.0",
"@bpmn-io/lang-feel": "^4.0.2",
"@camunda/feel-builtins": "^1.2.0",
"@codemirror/autocomplete": "^6.20.0",
"@codemirror/commands": "^6.10.3",
"@codemirror/language": "^6.11.3",
"@codemirror/lint": "^6.9.7",
"@codemirror/state": "^6.6.0",
"@codemirror/view": "^6.43.1",
"@lezer/highlight": "^1.2.3",
"min-dom": "^5.3.0",
"mitt": "^3.0.1"
},
"engines": {
"node": ">= 20"
},
"peerDependencies": {
"@bpmn-io/cm-theme": "^0.2.0"
}
},
"node_modules/@bpmn-io/feel-editor/node_modules/domify": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domify/-/domify-3.0.0.tgz",
"integrity": "sha512-bs2yO68JDFOm6rKv8f0EnrM2cENduhRkpqOtt/s5l5JBA/eqGBZCzLPmdYoHtJ6utgLGgcBajFsEQbl12pT0lQ==",
"license": "MIT",
"engines": {
"node": ">=20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@bpmn-io/feel-editor/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/@bpmn-io/feel-editor/node_modules/min-dom": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/min-dom/-/min-dom-5.3.0.tgz",
"integrity": "sha512-0w5FEBgPAyHhmFojW3zxd7we3D+m5XYS3E/06OyvxmbHJoiQVa4Nagj6RWvoAKYRw5xth6cP5TMePc5cR1M9hA==",
"license": "MIT",
"dependencies": {
"domify": "^3.0.0",
"min-dash": "^5.0.0"
}
},
"node_modules/@bpmn-io/feel-lint": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@bpmn-io/feel-lint/-/feel-lint-3.1.0.tgz",
"integrity": "sha512-nOCYWMXgwR0joU4XKhu4f3P5f4/AsmuyiV1e+fzcXTCh7iMLU8VYdHXSIzZuJ0zxz3Gsnp7A8S8lt+HJ43H6IA==",
"license": "MIT",
"dependencies": {
"@bpmn-io/lezer-feel": "^2.1.0",
"@codemirror/language": "^6.12.1"
},
"engines": {
"node": "*"
}
},
"node_modules/@bpmn-io/feelers-editor": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@bpmn-io/feelers-editor/-/feelers-editor-1.1.1.tgz",
"integrity": "sha512-HNvssf1nb/OohOgFxxR0hWIpIb8JBvmr2CQ28GD/5WLPKe3uvu9mpItIjNTCpLxLuVHlsJLNDtLkf2B6tvmt9Q==",
"license": "MIT",
"dependencies": {
"@bpmn-io/feelers-lint": "^1.0.0",
"@bpmn-io/lang-feelers": "^1.0.0",
"@codemirror/autocomplete": "^6.20.0",
"@codemirror/commands": "^6.10.1",
"@codemirror/language": "^6.12.1",
"@codemirror/lint": "^6.9.3",
"@codemirror/state": "^6.5.4",
"@codemirror/view": "^6.39.12",
"@lezer/common": "^1.5.1",
"@lezer/html": "^1.3.13",
"@lezer/markdown": "^1.6.3",
"min-dom": "^5.2.0",
"mitt": "^3.0.1"
},
"peerDependencies": {
"@bpmn-io/cm-theme": "^0.2.1"
}
},
"node_modules/@bpmn-io/feelers-editor/node_modules/domify": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domify/-/domify-3.0.0.tgz",
"integrity": "sha512-bs2yO68JDFOm6rKv8f0EnrM2cENduhRkpqOtt/s5l5JBA/eqGBZCzLPmdYoHtJ6utgLGgcBajFsEQbl12pT0lQ==",
"license": "MIT",
"engines": {
"node": ">=20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@bpmn-io/feelers-editor/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/@bpmn-io/feelers-editor/node_modules/min-dom": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/min-dom/-/min-dom-5.3.0.tgz",
"integrity": "sha512-0w5FEBgPAyHhmFojW3zxd7we3D+m5XYS3E/06OyvxmbHJoiQVa4Nagj6RWvoAKYRw5xth6cP5TMePc5cR1M9hA==",
"license": "MIT",
"dependencies": {
"domify": "^3.0.0",
"min-dash": "^5.0.0"
}
},
"node_modules/@bpmn-io/feelers-lint": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@bpmn-io/feelers-lint/-/feelers-lint-1.0.0.tgz",
"integrity": "sha512-9McPCub8NBSD3gbAM9fu6laGVvb6U/D8Y5Ar/GGvOaAuJ6W34yP5jaV/on4MALTwmmXTDadZjO2RJJNub3JmwQ==",
"license": "MIT",
"dependencies": {
"@bpmn-io/feel-lint": "^3.1.0",
"@codemirror/language": "^6.12.1",
"@codemirror/lint": "^6.9.3"
}
},
"node_modules/@bpmn-io/lang-feel": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@bpmn-io/lang-feel/-/lang-feel-4.0.2.tgz",
"integrity": "sha512-rTPeJ77/2nYKbJXpvDmrNXy+opoIpD3Rsch0grCUZAO6xF68r41QeV8SqOdr2yZxD/4gI6YXlQhqh4rqFRDJXA==",
"license": "MIT",
"dependencies": {
"@bpmn-io/lezer-feel": "^3.0.1",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/language": "^6.12.3",
"@lezer/common": "^1.5.2"
},
"engines": {
"node": ">= 20.12.0"
}
},
"node_modules/@bpmn-io/lang-feel/node_modules/@bpmn-io/lezer-feel": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@bpmn-io/lezer-feel/-/lezer-feel-3.0.1.tgz",
"integrity": "sha512-+wWg4DP2h8WOEQx2Bz51blsw9dCqKj3kIDKYccABuoAEhzZeDhmm0A2k4ANmm9lf0w5pJmVSYz2djtrbzOvzzA==",
"license": "MIT",
"dependencies": {
"@lezer/highlight": "^1.2.3",
"@lezer/lr": "^1.4.10",
"min-dash": "^5.0.0"
},
"engines": {
"node": ">= 20.12.0"
}
},
"node_modules/@bpmn-io/lang-feel/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/@bpmn-io/lang-feelers": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@bpmn-io/lang-feelers/-/lang-feelers-1.0.0.tgz",
"integrity": "sha512-VgBDw9cXr62e6Qs6LixQyLiBxxv7Kh8fxKFkYCmHPf/cO8beLQGjnF789wRlhK05yh/CuHi7oN7EYChrFQOHwg==",
"license": "MIT",
"dependencies": {
"@bpmn-io/lezer-feel": "^3.0.0",
"@bpmn-io/lezer-feelers": "^1.0.0",
"@codemirror/language": "^6.12.1",
"@lezer/common": "^1.5.1"
}
},
"node_modules/@bpmn-io/lang-feelers/node_modules/@bpmn-io/lezer-feel": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@bpmn-io/lezer-feel/-/lezer-feel-3.0.1.tgz",
"integrity": "sha512-+wWg4DP2h8WOEQx2Bz51blsw9dCqKj3kIDKYccABuoAEhzZeDhmm0A2k4ANmm9lf0w5pJmVSYz2djtrbzOvzzA==",
"license": "MIT",
"dependencies": {
"@lezer/highlight": "^1.2.3",
"@lezer/lr": "^1.4.10",
"min-dash": "^5.0.0"
},
"engines": {
"node": ">= 20.12.0"
}
},
"node_modules/@bpmn-io/lang-feelers/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/@bpmn-io/lezer-feel": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/@bpmn-io/lezer-feel/-/lezer-feel-2.5.0.tgz",
"integrity": "sha512-09JlwNYeD5YYeFrl0dIFfgQKEL+NNiTyUwEtdcPhfftz1mYa7z+ylOPCv/8Z0GqG7X81uyMFvRZDFCRBFTiUPg==",
"license": "MIT",
"dependencies": {
"@lezer/highlight": "^1.2.3",
"@lezer/lr": "^1.4.10",
"min-dash": "^5.0.0"
},
"engines": {
"node": ">= 20.12.0"
}
},
"node_modules/@bpmn-io/lezer-feel/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/@bpmn-io/lezer-feelers": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@bpmn-io/lezer-feelers/-/lezer-feelers-1.0.0.tgz",
"integrity": "sha512-P0znH2SY85O7RmOr/FgveFiTREet9DSCf3nH3J/StkI5i7Q384o+GEeTmv58n91FlUknS20KE3T8Yk5Qmab+hg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.5.1",
"@lezer/highlight": "^1.1.6",
"@lezer/lr": "^1.4.8"
}
},
"node_modules/@bpmn-io/properties-panel": {
"version": "3.47.0",
"resolved": "https://registry.npmjs.org/@bpmn-io/properties-panel/-/properties-panel-3.47.0.tgz",
"integrity": "sha512-tZQRM0x9KLUEFU2FyHCwnYjSq1lbxpY8oCwABFA00IcuyeEDQFDV5DFg7ytTv2qOyWgncZ2xNXPRQ9pydkN2gg==",
"license": "MIT",
"dependencies": {
"@bpmn-io/feel-editor": "^2.6.0",
"@bpmn-io/feelers-editor": "^1.0.0",
"@codemirror/autocomplete": "^6.18.6",
"@codemirror/commands": "^6.10.3",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/language": "^6.11.0",
"@codemirror/lint": "^6.9.5",
"@codemirror/state": "^6.6.0",
"@codemirror/view": "^6.28.1",
"classnames": "^2.5.1",
"focus-trap": "^8.0.0",
"min-dash": "^5.0.0",
"min-dom": "^5.3.0"
},
"engines": {
"node": "*"
}
},
"node_modules/@bpmn-io/properties-panel/node_modules/classnames": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
"integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",
"license": "MIT"
},
"node_modules/@bpmn-io/properties-panel/node_modules/domify": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domify/-/domify-3.0.0.tgz",
"integrity": "sha512-bs2yO68JDFOm6rKv8f0EnrM2cENduhRkpqOtt/s5l5JBA/eqGBZCzLPmdYoHtJ6utgLGgcBajFsEQbl12pT0lQ==",
"license": "MIT",
"engines": {
"node": ">=20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@bpmn-io/properties-panel/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/@bpmn-io/properties-panel/node_modules/min-dom": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/min-dom/-/min-dom-5.3.0.tgz",
"integrity": "sha512-0w5FEBgPAyHhmFojW3zxd7we3D+m5XYS3E/06OyvxmbHJoiQVa4Nagj6RWvoAKYRw5xth6cP5TMePc5cR1M9hA==",
"license": "MIT",
"dependencies": {
"domify": "^3.0.0",
"min-dash": "^5.0.0"
}
},
"node_modules/@bramus/specificity": { "node_modules/@bramus/specificity": {
"version": "2.4.2", "version": "2.4.2",
"resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz", "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",
@@ -409,6 +731,92 @@
"specificity": "bin/cli.js" "specificity": "bin/cli.js"
} }
}, },
"node_modules/@camunda/feel-builtins": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@camunda/feel-builtins/-/feel-builtins-1.3.0.tgz",
"integrity": "sha512-ZahpLTeBUjnZEMI6Hu/n9e/oTPcJ8DpWmIyJ00tgVNWM1kqAEcMhARK0GthSrD5NXiSVICNHZ7VRTERMq2FmnA==",
"license": "MIT"
},
"node_modules/@codemirror/autocomplete": {
"version": "6.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
"integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.10.4",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.4.tgz",
"integrity": "sha512-Ryk9y9T0FFVF0cUGhAknveAyUOl/A1qReTFi+qPKtOh2Z9F4AUBz3XOrYD4ZEgZirdugVzHvd/2/Wcwy5OliTg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-json": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz",
"integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@lezer/json": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.12.4",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",
"integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.7",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.0",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.0.tgz",
"integrity": "sha512-Zbl9NyscLMZkfXPQnNAIIAFftidrA1UbcJEIMp24C0Bukc2I5T8wJS0wsXYsnDOqCFJUeJ1BITGNs5CqPDSmSg==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/view": {
"version": "6.43.4",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.4.tgz",
"integrity": "sha512-YImu23iyKfncJzT7sRy+rEqEhSc8RhOHqDxwy4WzXRKJwYm6iwf/9OJk5ctCAdZ6yi2ZqaGEvmf55fSVqMDrgg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@csstools/color-helpers": { "node_modules/@csstools/color-helpers": {
"version": "6.0.2", "version": "6.0.2",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.2.tgz", "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.2.tgz",
@@ -1063,6 +1471,62 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@lezer/common": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz",
"integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
"license": "MIT"
},
"node_modules/@lezer/highlight": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/json": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz",
"integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.10",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
"integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@lezer/markdown": {
"version": "1.6.4",
"resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.6.4.tgz",
"integrity": "sha512-N0SxazMj4k65DBfaf1azqtMZd6u7MqluP84/NZnB/io8Td9aleFmAhz9hcbvSfsxT5tdYlJ5qgv5aMJGY4zEtA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@mapbox/node-pre-gyp": { "node_modules/@mapbox/node-pre-gyp": {
"version": "1.0.11", "version": "1.0.11",
"resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
@@ -1099,6 +1563,12 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz",
"integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==",
"license": "MIT"
},
"node_modules/@playwright/test": { "node_modules/@playwright/test": {
"version": "1.60.0", "version": "1.60.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
@@ -2298,6 +2768,18 @@
"dequal": "^2.0.3" "dequal": "^2.0.3"
} }
}, },
"node_modules/array-move": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/array-move/-/array-move-4.0.0.tgz",
"integrity": "sha512-+RY54S8OuVvg94THpneQvFRmqWdAHeqtMzgMW6JNurHxe8rsS07cHQdfGkXnTUXiBcyZ0j3SiDIxxj0RPiqCkQ==",
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/asap": { "node_modules/asap": {
"version": "2.0.6", "version": "2.0.6",
"resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
@@ -2475,6 +2957,65 @@
"node": "*" "node": "*"
} }
}, },
"node_modules/bpmn-js-properties-panel": {
"version": "5.60.0",
"resolved": "https://registry.npmjs.org/bpmn-js-properties-panel/-/bpmn-js-properties-panel-5.60.0.tgz",
"integrity": "sha512-/+bi7pYR/aLUFS4VpCP96oDtWcMk+2dAjmHUYLbuk91/Cpn+6RYSzvXrl5USQRUH43Ng1xKfXyLYDTcr0P6e/Q==",
"license": "MIT",
"dependencies": {
"@bpmn-io/extract-process-variables": "^2.2.1",
"array-move": "^4.0.0",
"ids": "^3.0.2",
"min-dash": "^5.0.0",
"min-dom": "^5.3.0"
},
"engines": {
"node": "*"
},
"peerDependencies": {
"@bpmn-io/properties-panel": ">= 3.40.6",
"bpmn-js": ">= 11.5",
"camunda-bpmn-js-behaviors": ">= 0.4",
"diagram-js": ">= 11.9"
}
},
"node_modules/bpmn-js-properties-panel/node_modules/domify": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/domify/-/domify-3.0.0.tgz",
"integrity": "sha512-bs2yO68JDFOm6rKv8f0EnrM2cENduhRkpqOtt/s5l5JBA/eqGBZCzLPmdYoHtJ6utgLGgcBajFsEQbl12pT0lQ==",
"license": "MIT",
"engines": {
"node": ">=20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/bpmn-js-properties-panel/node_modules/ids": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/ids/-/ids-3.0.2.tgz",
"integrity": "sha512-t6YJP4mdC+GHF96Nbis/4FEANhP/8VWmYMvUuYpXvSdrhg5hpIVbq2XZlOA3UWTbtdwPCi0q7jEXOdHkAnqOnw==",
"license": "MIT",
"engines": {
"node": ">= 20.12"
}
},
"node_modules/bpmn-js-properties-panel/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT"
},
"node_modules/bpmn-js-properties-panel/node_modules/min-dom": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/min-dom/-/min-dom-5.3.0.tgz",
"integrity": "sha512-0w5FEBgPAyHhmFojW3zxd7we3D+m5XYS3E/06OyvxmbHJoiQVa4Nagj6RWvoAKYRw5xth6cP5TMePc5cR1M9hA==",
"license": "MIT",
"dependencies": {
"domify": "^3.0.0",
"min-dash": "^5.0.0"
}
},
"node_modules/bpmn-moddle": { "node_modules/bpmn-moddle": {
"version": "8.1.0", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/bpmn-moddle/-/bpmn-moddle-8.1.0.tgz", "resolved": "https://registry.npmjs.org/bpmn-moddle/-/bpmn-moddle-8.1.0.tgz",
@@ -2608,6 +3149,46 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/camunda-bpmn-js-behaviors": {
"version": "1.18.0",
"resolved": "https://registry.npmjs.org/camunda-bpmn-js-behaviors/-/camunda-bpmn-js-behaviors-1.18.0.tgz",
"integrity": "sha512-ozmC9Btz7l6x0edBZaRxCUxF28mVbnTHO+v8ve8xGfhVRI0y8fFN/enAAILGk/eT2e+87BMx7uIUHGaxQBzbjQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"ids": "^3.0.1",
"min-dash": "^5.0.0"
},
"peerDependencies": {
"bpmn-js": ">= 9",
"camunda-bpmn-moddle": ">= 7",
"zeebe-bpmn-moddle": ">= 0.18"
}
},
"node_modules/camunda-bpmn-js-behaviors/node_modules/ids": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/ids/-/ids-3.0.2.tgz",
"integrity": "sha512-t6YJP4mdC+GHF96Nbis/4FEANhP/8VWmYMvUuYpXvSdrhg5hpIVbq2XZlOA3UWTbtdwPCi0q7jEXOdHkAnqOnw==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">= 20.12"
}
},
"node_modules/camunda-bpmn-js-behaviors/node_modules/min-dash": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/min-dash/-/min-dash-5.0.0.tgz",
"integrity": "sha512-EGuoBnVL7/Fnv2sqakpX5WGmZehZ3YMmLayT7sM8E9DRU74kkeyMg4Rik1lsOkR2GbFNeBca4/L+UfU6gF0Edw==",
"license": "MIT",
"peer": true
},
"node_modules/camunda-bpmn-moddle": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/camunda-bpmn-moddle/-/camunda-bpmn-moddle-7.0.1.tgz",
"integrity": "sha512-Br8Diu6roMpziHdpl66Dhnm0DTnCFMrSD9zwLV08LpD52QA0UsXxU87XfHf08HjuB7ly0Hd1bvajZRpf9hbmYQ==",
"license": "MIT",
"peer": true
},
"node_modules/caniuse-lite": { "node_modules/caniuse-lite": {
"version": "1.0.30001797", "version": "1.0.30001797",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001797.tgz", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001797.tgz",
@@ -2850,6 +3431,12 @@
"node": ">= 10" "node": ">= 10"
} }
}, },
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/cropperjs": { "node_modules/cropperjs": {
"version": "1.6.2", "version": "1.6.2",
"resolved": "https://registry.npmjs.org/cropperjs/-/cropperjs-1.6.2.tgz", "resolved": "https://registry.npmjs.org/cropperjs/-/cropperjs-1.6.2.tgz",
@@ -3573,6 +4160,15 @@
"react": "^15.0.2 || ^16.0.0 || ^17.0.0" "react": "^15.0.2 || ^16.0.0 || ^17.0.0"
} }
}, },
"node_modules/focus-trap": {
"version": "8.2.2",
"resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-8.2.2.tgz",
"integrity": "sha512-qV0g8hRYBqgACcFOH3f9wXc4zPKhr/0z9RI2a6ZijZ72EeBi4g8oBy8zAWuUR1TsMpOzwpUMFvjdasrC41Joug==",
"license": "MIT",
"dependencies": {
"tabbable": "^6.5.0"
}
},
"node_modules/follow-redirects": { "node_modules/follow-redirects": {
"version": "1.16.0", "version": "1.16.0",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
@@ -4786,6 +5382,12 @@
"license": "ISC", "license": "ISC",
"optional": true "optional": true
}, },
"node_modules/mitt": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
"license": "MIT"
},
"node_modules/mkdirp": { "node_modules/mkdirp": {
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
@@ -6469,6 +7071,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/style-mod": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
"integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
"license": "MIT"
},
"node_modules/symbol-tree": { "node_modules/symbol-tree": {
"version": "3.2.4", "version": "3.2.4",
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
@@ -6476,6 +7084,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/tabbable": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.5.0.tgz",
"integrity": "sha512-wieBHXygIm7OyQOu5hQlkk62/WyCFYGlWg7L6/ZCUZwx0o398Zkn4pVmMyfYhfMG8kGrj/Krt8eIk6UKC6VzwA==",
"license": "MIT"
},
"node_modules/tar": { "node_modules/tar": {
"version": "6.2.1", "version": "6.2.1",
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
@@ -7103,6 +7717,12 @@
} }
} }
}, },
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
},
"node_modules/w3c-xmlserializer": { "node_modules/w3c-xmlserializer": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
@@ -7284,6 +7904,13 @@
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/zeebe-bpmn-moddle": {
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/zeebe-bpmn-moddle/-/zeebe-bpmn-moddle-1.16.0.tgz",
"integrity": "sha512-dsblK7DYgu4e3E4Vp9pSWjWpVrw+WtzLEMb82ak4FHL3FI7arWcTfIE/CviAS7iWD/UOl5YniQgee1LEJDdvaA==",
"license": "MIT",
"peer": true
},
"node_modules/zip-stream": { "node_modules/zip-stream": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz", "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz",

View File

@@ -11,8 +11,10 @@
"test": "vitest run" "test": "vitest run"
}, },
"dependencies": { "dependencies": {
"@bpmn-io/properties-panel": "^3.47.0",
"axios": "1.7.9", "axios": "1.7.9",
"bpmn-js": "^17.11.1", "bpmn-js": "^17.11.1",
"bpmn-js-properties-panel": "^5.60.0",
"react": "18.3.1", "react": "18.3.1",
"react-dom": "18.3.1", "react-dom": "18.3.1",
"react-router-dom": "6.28.0" "react-router-dom": "6.28.0"
@@ -32,6 +34,7 @@
"amis-formula": "^6.13.0", "amis-formula": "^6.13.0",
"amis-theme-editor-helper": "^6.12.0-ab.1", "amis-theme-editor-helper": "^6.12.0-ab.1",
"amis-ui": "^6.13.0", "amis-ui": "^6.13.0",
"bpmn-moddle": "^8.1.0",
"i18n-runtime": "^1.0.13", "i18n-runtime": "^1.0.13",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"typescript": "5.6.3", "typescript": "5.6.3",

View File

@@ -0,0 +1,36 @@
import { defineConfig, devices } from '@playwright/test';
// 在线流程 Modeler live e2e 专用配置(T4.2)。
//
// 复用主会话已在跑的 vite dev(5173,vite.config 默认 proxy /api → http://localhost:8093),
// 后端指向当前 live 的 8093 网关 + 8089 flowable-service + 真库 eip4(含 T3.1/T3.2/T4.1 全部新代码)。
// 与 fivering 配置(自起 vite 5174 → 8094)隔离:本配置 reuseExistingServer 复用 5173,不新起端口。
//
// 依赖(跑前须在线,spec 头注释有 curl 自检):
// - 8093 网关/后端(curl -s -o /dev/null -w '%{http_code}' localhost:8093/v3/api-docs → 200)
// - 8089 flowable-service(经 8093 转发;start/trace 走它)
// - 5173 vite dev(curl localhost:5173 → 200;apiJson 直连 8093,与 UI 经 5173 代理同一后端)
// 跑法:npx playwright test -c playwright.process-modeler.config.ts
export default defineConfig({
testDir: './e2e',
testMatch: /process-modeler\.spec\.ts/,
fullyParallel: false,
workers: 1,
timeout: 180_000,
reporter: [['list']],
use: {
baseURL: 'http://localhost:5173',
trace: 'off',
screenshot: 'only-on-failure',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
webServer: {
// reuseExistingServer:true → 5173 已在跑(主会话 npm run dev)则复用、不新起;
// 未跑时按 dev 同口径(VITE_BACKEND_TARGET=8093)拉起。
command:
'NODE_OPTIONS=--max-http-header-size=65536 VITE_BACKEND_TARGET=http://localhost:8093 npx vite --port 5173 --strictPort',
url: 'http://localhost:5173',
reuseExistingServer: true,
timeout: 120_000,
},
});

View File

@@ -11,6 +11,7 @@ import { DesignCenterPage } from './pages/DesignCenterPage';
import { NewFeatureShell } from './pages/NewFeatureShell'; import { NewFeatureShell } from './pages/NewFeatureShell';
import { AiFeatureForm } from './pages/AiFeatureForm'; import { AiFeatureForm } from './pages/AiFeatureForm';
import { ModelerPage } from './pages/ModelerPage'; import { ModelerPage } from './pages/ModelerPage';
import { ProcessModelerPage } from './pages/ProcessModelerPage';
// 把 401 跳登录的 handler 注入 http 层(在路由上下文内,可用 navigate) // 把 401 跳登录的 handler 注入 http 层(在路由上下文内,可用 navigate)
function UnauthorizedBridge() { function UnauthorizedBridge() {
@@ -48,6 +49,8 @@ export default function App() {
<Route path="/ai-feature" element={<AiFeatureForm />} /> <Route path="/ai-feature" element={<AiFeatureForm />} />
{/* 建模器(五环第①环·元数据→表,仅管理员)*/} {/* 建模器(五环第①环·元数据→表,仅管理员)*/}
<Route path="/modeler" element={<ModelerPage />} /> <Route path="/modeler" element={<ModelerPage />} />
{/* 在线流程 Modeler(可编辑 BPMN 设计器,仅管理员)*/}
<Route path="/process-modeler" element={<ProcessModelerPage />} />
{/* 根路径默认跳工作台 */} {/* 根路径默认跳工作台 */}
<Route index element={<Navigate to="/workbench" replace />} /> <Route index element={<Navigate to="/workbench" replace />} />
</Route> </Route>

View File

@@ -0,0 +1,101 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('./http', () => ({ http: { get: vi.fn() } }));
import { http } from './http';
import { fetchProcDefSource, fetchProcDefSourceByKey, fetchProcessOptions } from './processModeler';
const mGet = vi.mocked(http.get);
beforeEach(() => {
mGet.mockReset();
});
describe('fetchProcDefSource', () => {
it('中文+冒号 procDefId 必须 encodeURIComponent 进 path', async () => {
mGet.mockResolvedValue({
data: { found: true, bpmnXml: '<x/>', idMap: {}, procDefKey: '总包合同交底', version: 3 },
});
// 真实库形态:中文流程名 + 冒号 + uuid
await fetchProcDefSource('总包合同交底:3:9b2f-uuid');
expect(mGet).toHaveBeenCalledTimes(1);
const url = mGet.mock.calls[0][0] as string;
expect(url).toBe(
'/api/workflow/process-definitions/' + encodeURIComponent('总包合同交底:3:9b2f-uuid') + '/source',
);
// 未编码的中文与裸冒号不得出现在 path segment 里
expect(url).not.toContain('总包合同交底');
expect(url).toContain('%E6%80%BB'); // 「总」的编码
});
it('found:false(后端省略 bpmnXml/idMap 键)不抛,只返回 found:false', async () => {
mGet.mockResolvedValue({ data: { found: false } });
const r = await fetchProcDefSource('PD-x');
expect(r).toEqual({ found: false });
expect('bpmnXml' in r).toBe(false);
});
it('found:true 时解构五字段', async () => {
mGet.mockResolvedValue({
data: { found: true, bpmnXml: '<def/>', idMap: { '总包合同交底': 'Proc_zbht' }, procDefKey: '总包合同交底', version: 5 },
});
const r = await fetchProcDefSource('PD-1');
expect(r).toEqual({
found: true,
bpmnXml: '<def/>',
idMap: { '总包合同交底': 'Proc_zbht' },
procDefKey: '总包合同交底',
version: 5,
});
});
});
describe('fetchProcDefSourceByKey', () => {
it('纯中文 key 必须 encodeURIComponent 进 by-key path', async () => {
mGet.mockResolvedValue({
data: { found: true, bpmnXml: '<x/>', idMap: {}, procDefKey: '总包合同交底', version: 4 },
});
await fetchProcDefSourceByKey('总包合同交底');
expect(mGet).toHaveBeenCalledTimes(1);
const url = mGet.mock.calls[0][0] as string;
expect(url).toBe('/api/workflow/process-definitions/by-key/' + encodeURIComponent('总包合同交底') + '/source');
expect(url).not.toContain('总包合同交底');
expect(url).toContain('%E6%80%BB');
});
it('found:false(省略键)不抛,只返回 found:false', async () => {
mGet.mockResolvedValue({ data: { found: false } });
const r = await fetchProcDefSourceByKey('无此流程');
expect(r).toEqual({ found: false });
expect('bpmnXml' in r).toBe(false);
});
});
describe('fetchProcessOptions', () => {
it('解 amis 信封 data.options 并映射 source/id/key 字段', async () => {
mGet.mockResolvedValue({
data: {
status: 0,
msg: '',
data: {
options: [{ label: '总包合同交底', value: '总包合同交底', source: 'model', id: 'PD:3:u', key: 'zbht', type: 'process' }],
},
},
});
const opts = await fetchProcessOptions();
expect(opts).toEqual([{ label: '总包合同交底', value: '总包合同交底', source: 'model', id: 'PD:3:u', key: 'zbht' }]);
});
it('history 来源 id 为空时 id=undefined(前端据此过滤不可载入项)', async () => {
mGet.mockResolvedValue({
data: { data: { options: [{ label: '历史流程', value: '历史流程', id: null, key: null }] } },
});
const opts = await fetchProcessOptions();
expect(opts[0].id).toBeUndefined();
});
it('缺 options / 非数组时返回空数组不抛', async () => {
mGet.mockResolvedValue({ data: {} });
expect(await fetchProcessOptions()).toEqual([]);
});
});

384
src/api/processModeler.ts Normal file
View File

@@ -0,0 +1,384 @@
import { http } from './http';
/**
* 流程 Modeler(在线 BPMN 设计器)后端契约。
*
* 阶段 1 只用到「按 procDefId 取净化源 XML」。裸 JSON 派,防御性默认 found:false,
* 与 diagram.ts 同风格。网关端点由 T1.6 上线,本层照 design 契约先写。
*/
/** GET /api/workflow/process-definitions/{id}/source 的返回体。 */
export interface ProcDefSource {
/** 是否命中流程定义(无则 found:false,不抛)。 */
found: boolean;
/** BpmnIdSanitizer 净化后的 BPMN 2.0 XML(中文 id 已替换为 ASCII,供 moddle/Modeler 载入)。 */
bpmnXml?: string;
/** 净化映射 原id→净化id(发布时逆向还原用,本 task 仅存 ref,后续 task 用)。 */
idMap?: Record<string, string>;
/** 流程定义 key(存量多为中文,如「总包合同交底」)。 */
procDefKey?: string;
/** 流程定义版本号。 */
version?: number;
}
/**
* source 端点返回体归一:found:false 时后端省略 bpmnXml/idMap 键——先判 found 再解构,
* 不在 false 分支碰这些键。
*/
function normalizeProcDefSource(data: ProcDefSource | undefined): ProcDefSource {
if (!data?.found) {
return { found: false };
}
return {
found: true,
bpmnXml: data.bpmnXml ?? undefined,
idMap: data.idMap ?? undefined,
procDefKey: data.procDefKey ?? undefined,
version: data.version ?? undefined,
};
}
/**
* 按 procDefId 取净化后的存量流程源 XML(含可逆 idMap)。
*
* ⚠️ procDefId 必须编码进 path:真实库 1445 个流程的 id 形如「总包合同交底:3:<uuid>」
* (中文 + 冒号),不 encodeURIComponent 会破坏 path segment。
*/
export async function fetchProcDefSource(procDefId: string): Promise<ProcDefSource> {
const { data } = await http.get<ProcDefSource>(
`/api/workflow/process-definitions/${encodeURIComponent(procDefId)}/source`,
);
return normalizeProcDefSource(data);
}
/**
* 按流程 key 取净化后的最新版存量流程源 XML。
*
* ⚠️ 本库 process-select 选项 source 全为 'model'——option.id 是 act_re_model id(非
* procDefId,按 id 载入必 found:false),只有 option.key 是流程 key。故 model 来源的打开
* 走本端点按 key 载入。key 常为纯中文(如「总包合同交底」),必须 encodeURIComponent 进 path。
*/
export async function fetchProcDefSourceByKey(key: string): Promise<ProcDefSource> {
const { data } = await http.get<ProcDefSource>(
`/api/workflow/process-definitions/by-key/${encodeURIComponent(key)}/source`,
);
return normalizeProcDefSource(data);
}
/**
* 存量流程选择器的一条选项。复用旧 ProcessSelectDialog 的数据源
* `/api/process-select/options`(amis 信封 {status,data:{options}})。
*
* - {@link source} 决定用哪个参数打开:'processDefinition'→id 即 procDefId;'model'/'history'→用 key。
* - {@link id} 为 procDefId(仅 source=processDefinition 可信;source=model 时 id 是 act_re_model id,
* 非 procDefId,不能按 id 载入)。
* - {@link value}/{@link label} 均为流程名称(沿用旧口径 value==label==流程名)。
*/
export interface ProcessOption {
label: string;
value: string;
source?: string;
id?: string;
key?: string;
}
interface ProcessSelectEnvelope {
data?: { options?: unknown[] };
options?: unknown[];
}
interface RawOption {
label?: unknown;
value?: unknown;
source?: unknown;
id?: unknown;
key?: unknown;
}
/**
* formKey picker 的一条选项。数据源 `GET /api/workflow/wftemplates`(T2.2 网关端点),
* 契约 `{templates:[{id,name}],degraded?}`。id=view_wftemplate_id 裸 UUID(即 activiti:formKey
* 值,无前缀)。**T2.2 实证**:view_wftemplate 无名称列,网关按 entityid→sys_entity.name 解析,
* 1016 活动模板仅 ~339 有中文名,其余 name 回落为 id(uuid)——前端下拉需过滤 + 未命名展示。
*/
export interface WfTemplateOption {
id: string;
name: string;
}
/** wftemplates 结果:degraded=数据源读库异常(网关返 {templates:[],degraded:true})。 */
export interface WfTemplateResult {
templates: WfTemplateOption[];
degraded: boolean;
}
/** GET /api/workflow/wftemplates —— 取表单模板列表供 formKey 下拉(防御性;透传 degraded)。 */
export async function fetchWfTemplates(): Promise<WfTemplateResult> {
const { data } = await http.get<{ templates?: unknown[]; degraded?: boolean }>(
'/api/workflow/wftemplates',
);
const degraded = data?.degraded === true;
const raw = data?.templates ?? [];
if (!Array.isArray(raw)) return { templates: [], degraded };
const templates = raw
.map((t) => {
const o = (t ?? {}) as { id?: unknown; name?: unknown };
const id = o.id != null ? String(o.id) : '';
const name = o.name != null ? String(o.name) : id;
return { id, name };
})
.filter((t) => t.id !== '');
return { templates, degraded };
}
// ── 流程草稿(act_re_model)CRUD(T2.1 后端 + T2.2 网关,全走超管门;前端已登录 admin) ────
/** GET /api/workflow/models 列表项。 */
export interface ModelSummary {
id: string;
name: string;
key: string;
lastUpdateTime?: string;
}
/** GET /api/workflow/models/{id} 单条草稿(含编辑源 XML 与 metaInfo JSON 串)。 */
export interface DraftModel {
found: boolean;
id?: string;
name?: string;
key?: string;
bpmnXml?: string;
/** metaInfo JSON 串,含 eip4IdMap/sourceProcDefId/originalKey(from-procdef 建的草稿有)。 */
metaInfo?: string;
}
/** 新建草稿请求体。metaInfo 必带 eip4IdMap 以便发布还原中文 key(存量改造场景)。 */
export interface CreateDraftBody {
name: string;
key: string;
bpmnXml: string;
metaInfo?: string;
}
/** GET /api/workflow/models —— 草稿列表(防御性返回数组)。 */
export async function listModels(): Promise<ModelSummary[]> {
const { data } = await http.get<{ models?: unknown[] }>('/api/workflow/models');
const raw = data?.models ?? [];
if (!Array.isArray(raw)) return [];
return raw
.map((m) => {
const o = (m ?? {}) as { id?: unknown; name?: unknown; key?: unknown; lastUpdateTime?: unknown };
return {
id: o.id != null ? String(o.id) : '',
name: o.name != null ? String(o.name) : '',
key: o.key != null ? String(o.key) : '',
lastUpdateTime: o.lastUpdateTime != null ? String(o.lastUpdateTime) : undefined,
};
})
.filter((m) => m.id !== '');
}
/** GET /api/workflow/models/{id} —— 取单条草稿(防御性 found:false)。 */
export async function getModel(id: string): Promise<DraftModel> {
const { data } = await http.get<DraftModel>(`/api/workflow/models/${encodeURIComponent(id)}`);
if (!data?.found) return { found: false };
return {
found: true,
id: data.id != null ? String(data.id) : undefined,
name: data.name != null ? String(data.name) : undefined,
key: data.key != null ? String(data.key) : undefined,
bpmnXml: data.bpmnXml ?? undefined,
metaInfo: data.metaInfo ?? undefined,
};
}
/** POST /api/workflow/models —— 新建草稿,返回 modelId。 */
export async function createDraft(body: CreateDraftBody): Promise<string> {
const { data } = await http.post<{ modelId?: unknown }>('/api/workflow/models', body);
return data?.modelId != null ? String(data.modelId) : '';
}
/**
* PUT /api/workflow/models/{id} —— 保存草稿(更新 name/编辑源)。
* ⚠️ 刻意不传 metaInfo 键:后端 T2.1「不带 metaInfo 不覆盖」保住 from-procdef/create 时写入的
* eip4IdMap,避免二次保存打掉发布还原所需的映射。
*/
export async function saveDraft(id: string, body: { name?: string; bpmnXml: string }): Promise<void> {
await http.put(`/api/workflow/models/${encodeURIComponent(id)}`, body);
}
/** POST /api/workflow/models/from-procdef —— 由 procDefId 建草稿(后端净化+写 metaInfo),返回 modelId。 */
export async function draftFromProcDef(procDefId: string): Promise<string> {
const { data } = await http.post<{ modelId?: unknown }>('/api/workflow/models/from-procdef', {
procDefId,
});
return data?.modelId != null ? String(data.modelId) : '';
}
/**
* DELETE /api/workflow/models/{id} —— 删除草稿。
* 后端已实现(flowable-service DELETE /api/flow/models/{id} + 网关同超管门转发,f0d704d)。
*/
export async function deleteDraft(id: string): Promise<void> {
await http.delete(`/api/workflow/models/${encodeURIComponent(id)}`);
}
// ── 发布(deploy)+ 影响摘要(impact)(T3.1 后端 + T3.2 网关,超管门) ──────────
/**
* 一条发布校验错误。后端两种来源统一收进本形态(防御性——T3.1/T3.2 并行):
* - flowable ProcessValidator(T3.1 flowable-service):`{activityId,problem,defaultDescription}`。
* - 网关 EIP4 语义校验(T3.2):可能是字符串(或对象)→ 归一到 {message}。
*/
export interface DeployValidationError {
activityId?: string;
problem?: string;
defaultDescription?: string;
/** 字符串式错误(网关语义校验)或无结构错误的兜底展示文案。 */
message?: string;
}
/** deployModel 结果:ok=部署成功;否则 validationErrors(422 校验清单)或 message(通用失败)。 */
export interface DeployOutcome {
ok: boolean;
deploymentId?: string;
processKey?: string;
newVersion?: number;
/** 校验未通过(422 且带 errors)时的节点错误清单;发布弹窗按此渲染不关窗。 */
validationErrors?: DeployValidationError[];
/** 通用失败文案(404/无 errors 的 422/网络异常)。 */
message?: string;
}
/** GET /api/workflow/models/{id}/impact 归一结果。found=false 表示不可用(404/异常)。 */
export interface DeployImpact {
found: boolean;
processKey?: string;
/** 该 key 当前最新已部署版本(无则 0);发布后为 currentVersion+1。 */
currentVersion?: number;
/** 该 key 运行中实例数(留在旧版本不受影响)。 */
runningInstances?: number;
}
interface RawDeployError {
activityId?: unknown;
problem?: unknown;
defaultDescription?: unknown;
message?: unknown;
msg?: unknown;
}
/** errors 数组归一:元素可为字符串(→{message})或对象(→取标准字段),滤掉全空项。 */
function normalizeDeployErrors(raw: unknown): DeployValidationError[] {
if (!Array.isArray(raw)) return [];
return raw
.map((e): DeployValidationError => {
if (typeof e === 'string') return { message: e };
const o = (e ?? {}) as RawDeployError;
const err: DeployValidationError = {};
if (o.activityId != null) err.activityId = String(o.activityId);
if (o.problem != null) err.problem = String(o.problem);
if (o.defaultDescription != null) err.defaultDescription = String(o.defaultDescription);
const m = o.message ?? o.msg;
if (m != null) err.message = String(m);
return err;
})
.filter((e) => e.activityId || e.problem || e.defaultDescription || e.message);
}
/** axios 错误的响应体结构(防御性访问,不依赖 AxiosError 类型强绑定)。 */
interface HttpErrorLike {
response?: { status?: number; data?: unknown };
}
interface DeployRespBody {
status?: unknown;
deploymentId?: unknown;
processKey?: unknown;
newVersion?: unknown;
errors?: unknown;
msg?: unknown;
}
function successOutcome(d: DeployRespBody | undefined): DeployOutcome {
return {
ok: true,
deploymentId: d?.deploymentId != null ? String(d.deploymentId) : undefined,
processKey: d?.processKey != null ? String(d.processKey) : undefined,
newVersion: d?.newVersion != null ? Number(d.newVersion) : undefined,
};
}
/**
* POST /api/workflow/models/{id}/deploy —— 同人确认后发布草稿。
*
* 不向调用方抛异常:把 422(校验失败带 errors / 其他带 msg)与网络异常都归一进 {ok:false,...},
* 供发布弹窗区分「校验清单(不关窗让用户改)」与「通用失败 toast」。成功返 {ok:true,newVersion,...}。
*/
export async function deployModel(id: string): Promise<DeployOutcome> {
try {
const { data } = await http.post<DeployRespBody>(
`/api/workflow/models/${encodeURIComponent(id)}/deploy`,
);
// 2xx 但后端标 status:1(防御性——理论上 422 才失败,但双写路径下容错)。
if (data && data.status === 1) {
const errs = normalizeDeployErrors(data.errors);
return errs.length
? { ok: false, validationErrors: errs, message: data.msg != null ? String(data.msg) : undefined }
: { ok: false, message: data.msg != null ? String(data.msg) : '发布失败' };
}
return successOutcome(data);
} catch (e) {
const resp = (e as HttpErrorLike)?.response;
const d = resp?.data as DeployRespBody | undefined;
if (d) {
const errs = normalizeDeployErrors(d.errors);
if (errs.length) {
return { ok: false, validationErrors: errs, message: d.msg != null ? String(d.msg) : undefined };
}
return { ok: false, message: d.msg != null ? String(d.msg) : '发布失败' };
}
return { ok: false, message: '发布失败(服务不可用或网络异常)' };
}
}
/**
* GET /api/workflow/models/{id}/impact —— 发布影响摘要(流程 key/当前版本/运行中实例数)。
* 防御性:任何失败(404/异常)返 {found:false},弹窗降级提示而不阻断发布。
*/
export async function fetchImpact(id: string): Promise<DeployImpact> {
try {
const { data } = await http.get<{ status?: unknown; processKey?: unknown; currentVersion?: unknown; runningInstances?: unknown }>(
`/api/workflow/models/${encodeURIComponent(id)}/impact`,
);
if (!data || data.status === 1) return { found: false };
return {
found: true,
processKey: data.processKey != null ? String(data.processKey) : undefined,
currentVersion: data.currentVersion != null ? Number(data.currentVersion) : undefined,
runningInstances: data.runningInstances != null ? Number(data.runningInstances) : undefined,
};
} catch {
return { found: false };
}
}
/** GET /api/process-select/options —— 取存量流程选项(解 amis 信封,防御性返回数组)。 */
export async function fetchProcessOptions(q?: string): Promise<ProcessOption[]> {
const { data } = await http.get<ProcessSelectEnvelope>('/api/process-select/options', {
params: q ? { q } : undefined,
});
const raw = data?.data?.options ?? data?.options ?? [];
if (!Array.isArray(raw)) return [];
return raw.map((o) => {
const opt = (o ?? {}) as RawOption;
const label = opt.label != null ? String(opt.label) : opt.value != null ? String(opt.value) : '';
return {
label,
value: opt.value != null ? String(opt.value) : label,
source: opt.source != null ? String(opt.source) : undefined,
id: opt.id != null && String(opt.id) !== '' ? String(opt.id) : undefined,
key: opt.key != null && String(opt.key) !== '' ? String(opt.key) : undefined,
};
});
}

View File

@@ -18,6 +18,7 @@ import { registerMessageAction } from '../amis/registerMessageAction';
import { registerReplayAction } from '../amis/registerReplayAction'; import { registerReplayAction } from '../amis/registerReplayAction';
import { normalizeUserTransferSchemaTree, registerUserTransferPicker } from '../amis/registerUserTransferPicker'; import { normalizeUserTransferSchemaTree, registerUserTransferPicker } from '../amis/registerUserTransferPicker';
import { getProfile } from '../auth/token'; import { getProfile } from '../auth/token';
import { makeJumpTo } from './reportDownload';
interface AmisRendererProps { interface AmisRendererProps {
schema: Record<string, unknown>; schema: Record<string, unknown>;
@@ -141,6 +142,8 @@ export function AmisRenderer({ schema }: AmisRendererProps) {
fetcher, fetcher,
// 与后端 amis CRUD 约定对齐:status===0 为成功 // 与后端 amis CRUD 约定对齐:status===0 为成功
isCancel: (e: unknown) => (http as unknown as { isCancel?: (x: unknown) => boolean }).isCancel?.(e) ?? false, isCancel: (e: unknown) => (http as unknown as { isCancel?: (x: unknown) => boolean }).isCancel?.(e) ?? false,
// 报表导出(actionType:url)走受控 blob 下载,按 Content-Disposition 命名,修「文件名 UUID/无扩展名」。
jumpTo: makeJumpTo(),
}, },
); );
instanceRef.current = instance; instanceRef.current = instance;

View File

@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest';
import { filenameFromContentDisposition, isReportDownloadUrl } from './reportDownload';
describe('filenameFromContentDisposition', () => {
it('优先取 filename* 的 UTF-8 中文报表名(而非前面的 UUID 兜底)', () => {
// 后端真实响应头形态:ASCII filename 是 UUID 兜底,filename* 才是真实报表名
const cd =
'attachment; filename="0a47a300-f544-42fd-b523-f4ac9672e27b.xls"; '
+ "filename*=UTF-8''%E5%8A%9E%E5%85%AC%E7%94%A8%E5%93%81%E9%87%87%E8%B4%AD%E7%94%B3%E8%AF%B7%E5%8D%95.xls";
expect(filenameFromContentDisposition(cd)).toBe('办公用品采购申请单.xls');
});
it('无 filename* 时回退普通 filename', () => {
expect(filenameFromContentDisposition('attachment; filename="report.pdf"')).toBe('report.pdf');
});
it('filename* 中的 + 还原为空格', () => {
expect(filenameFromContentDisposition("attachment; filename*=UTF-8''a+b.xls")).toBe('a b.xls');
});
it('空/缺失返回空串', () => {
expect(filenameFromContentDisposition(undefined)).toBe('');
expect(filenameFromContentDisposition(null)).toBe('');
expect(filenameFromContentDisposition('')).toBe('');
});
});
describe('isReportDownloadUrl', () => {
it('匹配 report render 的 pdf/xls 导出 URL', () => {
expect(isReportDownloadUrl('/api/report/render/abc?format=pdf')).toBe(true);
expect(isReportDownloadUrl('/api/report/render/abc?format=xls&OA_X_ID=1')).toBe(true);
expect(isReportDownloadUrl('/api/report/render/abc?format=xlsx')).toBe(true);
});
it('不匹配 html(iframe 查看) 或非报表 URL', () => {
expect(isReportDownloadUrl('/api/report/render/abc?format=html')).toBe(false);
expect(isReportDownloadUrl('/api/report/frame/abc')).toBe(false);
expect(isReportDownloadUrl('/page/abc')).toBe(false);
});
});

View File

@@ -0,0 +1,90 @@
// ============================================================================
// 报表导出下载 —— 受控 blob 下载,按 Content-Disposition 正确命名
// ----------------------------------------------------------------------------
// 背景:报表导出按钮是 amis actionType:url(默认 window.open)。部分浏览器在
// window.open 一个 attachment 响应时会丢失 Content-Disposition 文件名,退化成
// blob/路径命名(UUID、无扩展名,双击打不开)。这里把报表导出 URL 拦下来,显式
// fetch 成 blob 并用 <a download="<CD文件名>"> 落盘,文件名/扩展名在所有浏览器都正确。
// ============================================================================
import { http } from '../api/http';
/**
* 解析 Content-Disposition 文件名。**优先 {@code filename*=UTF-8''…}**(RFC 5987,含中文报表名,
* URL 解码);否则回退普通 {@code filename="…"}(常是 UUID/ASCII 兜底)。
* 注意:CD 形如 {@code attachment; filename="UUID.xls"; filename*=UTF-8''办公用品采购申请单.xls},
* 必须先取 filename*,否则会取到前面的 UUID。
*/
export function filenameFromContentDisposition(cd: string | undefined | null): string {
if (!cd) return '';
// 1) 优先 filename*(UTF-8 编码的真实报表名)
const star = /filename\*=(?:UTF-8'')?([^;\n]*)/i.exec(cd);
if (star && star[1]) {
let f = star[1].trim().replace(/['"]/g, '');
try {
f = decodeURIComponent(f);
} catch {
/* 解码失败保留原值 */
}
return f.replace(/\+/g, ' ');
}
// 2) 回退普通 filename="…"(不匹配 filename*=,因其含 '*')
const plain = /filename=("?)([^";\n]*)\1/i.exec(cd);
let f = plain && plain[2] ? plain[2].trim() : '';
if (f && f.replace(/[^%]/g, '').length > 2) {
try {
f = decodeURIComponent(f);
} catch {
/* 保留原值 */
}
f = f.replace(/\+/g, ' ');
}
return f;
}
/** 报表导出下载 URL(format=pdf/xls/…)——应作为带正确文件名的附件落盘,而非 window.open。 */
export function isReportDownloadUrl(to: string): boolean {
return /\/api\/report\/render\//.test(to) && /[?&]format=(pdf|xls|xlsx|excel)(\b|&|$)/i.test(to);
}
/**
* 以 blob 拉取报表导出并按 Content-Disposition 文件名落盘({@code <a download>})。
* 显式取 CD 文件名并用 download 属性强制命名,规避 window.open 在部分浏览器丢失文件名的问题。
*/
export async function downloadReportFile(to: string): Promise<void> {
const resp = (await http.get(to, { responseType: 'blob' as never })) as {
headers?: Record<string, string>;
data?: unknown;
};
const headers = resp.headers ?? {};
const filename = filenameFromContentDisposition(headers['content-disposition']) || 'report';
const blob = resp.data instanceof Blob ? resp.data : new Blob([resp.data as BlobPart]);
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}
/** 自定义 jumpTo:报表导出 URL 走受控 blob 下载(文件名正确),其余沿用 amis 默认跳转语义。 */
export function makeJumpTo() {
return (to: string, action?: { actionType?: string; blank?: boolean }) => {
if (to && isReportDownloadUrl(to)) {
void downloadReportFile(to);
return;
}
if (to === 'goBack') {
window.history.back();
return;
}
if (action && action.actionType === 'url') {
if (action.blank === false) window.location.href = to;
else window.open(to);
return;
}
if (/^https?:\/\//.test(to)) window.location.replace(to);
else window.location.href = to;
};
}

View File

@@ -0,0 +1,629 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';
import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn';
import {
parseCandidateExpression,
buildCandidateExpression,
type UserPropertyItem,
} from './candidateExpression';
// formKey 下拉数据源:mock,其中一个 id 对齐 fixture 的 formKey 值;第三项 name===id(未命名)。
vi.mock('../api/processModeler', () => ({
fetchWfTemplates: vi.fn(() =>
Promise.resolve({
templates: [
{ id: '2098ce21-400b-4425-9c22-63e350974b98', name: '合同交底表单' },
{ id: 'aaaa-bbbb', name: '另一个表单' },
{ id: 'deadbeef-1111-2222', name: 'deadbeef-1111-2222' }, // 未命名(name 回落为 id)
],
degraded: false,
}),
),
}));
import { Eip4Panel } from './Eip4Panel';
import { fetchWfTemplates } from '../api/processModeler';
const mWfTemplates = vi.mocked(fetchWfTemplates);
// ── 真实办理人形态锚定(同 candidateExpression.test.ts:抽 fixture,做 XML 实体解码) ────
function xmlDecode(s: string): string {
return s.replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
}
function extractAttr(attr: string): string {
const m = SYNTHETIC_BPMN.match(new RegExp(attr + '="([^"]*)"'));
if (!m) throw new Error('fixture 缺属性 ' + attr);
return xmlDecode(m[1]);
}
const REAL_CANDIDATE = extractAttr('activiti:candidateUsers'); // type=position + 非空 taskSuccessService
// ── 假 modeler / element(vi.fn 捕获 updateProperties 载荷) ────────────────────
function makeModeler() {
let selHandler: ((e: unknown) => void) | null = null;
let cmdHandler: (() => void) | null = null;
const updateProperties = vi.fn();
const created: Array<Record<string, unknown>> = [];
const moddle = {
create: vi.fn((type: string, props: Record<string, unknown> = {}) => {
const o = { $type: type, ...props };
created.push(o);
return o;
}),
};
const modeling = { updateProperties };
const on = vi.fn((ev: string, cb: (e: unknown) => void) => {
if (ev === 'selection.changed') selHandler = cb;
if (ev === 'commandStack.changed') cmdHandler = cb as () => void;
});
const off = vi.fn();
const get = (svc: string) => (svc === 'modeling' ? modeling : svc === 'moddle' ? moddle : {});
const modeler = { on, off, get };
// 选中同时 flush 微任务队列:fetchWfTemplates(mock 已 resolve)的 setState 在 act 内落定,
// 避免「update not wrapped in act」告警。
const select = (element: unknown) =>
act(async () => {
selHandler?.({ newSelection: element ? [element] : [] });
await Promise.resolve();
await Promise.resolve();
});
// 模拟外部 undo/redo:commandStack.changed。
const fireCommandStack = () =>
act(async () => {
cmdHandler?.();
await Promise.resolve();
});
return { modeler, updateProperties, moddle, created, select, fireCommandStack };
}
/** 全项目 window.confirm 默认放行(具体测试可再 spy 覆盖);afterEach 复原。 */
let confirmSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
});
afterEach(() => {
confirmSpy.mockRestore();
});
/** 一个内容非空、meta 为空的合法办理人表达式(清空时不触发 confirm)。 */
function candidateNoMeta(content = 'u1'): string {
const item: UserPropertyItem = {
type: 'user',
content,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
};
return buildCandidateExpression([item], 'candidate', {});
}
/** 造一个 userTask element:map=businessObject.get(name) 源,$attrs=原始扩展属性袋。 */
function userTask(map: Record<string, unknown> = {}, $attrs?: Record<string, string>) {
return {
id: map.__id ? String(map.__id) : 't1',
type: 'bpmn:UserTask',
businessObject: { $type: 'bpmn:UserTask', $attrs, get: (n: string) => map[n] },
};
}
/** 造一个 moddle-ish 元素(taskListener/loop 等):$type + get(name) + 直读属性。 */
function moddleEl(type: string, props: Record<string, unknown>) {
return { $type: type, ...props, get: (n: string) => props[n] };
}
/** 取最后一次 updateProperties 载荷。 */
function lastPayload(updateProperties: ReturnType<typeof vi.fn>): Record<string, unknown> {
const calls = updateProperties.mock.calls;
return calls[calls.length - 1][1] as Record<string, unknown>;
}
beforeEach(() => {
vi.clearAllMocks();
});
describe('Eip4Panel — 选择状态', () => {
it('未选中任何节点时提示选择', async () => {
const { modeler } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
expect(screen.getByText(/请选择/)).toBeInTheDocument();
// flush 挂载期 fetchWfTemplates 的 setState(避免 act 告警)
await act(async () => {
await Promise.resolve();
});
});
it('选中非 userTask 显示简短提示,不渲染办理人控件', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select({ id: 'g1', type: 'bpmn:ExclusiveGateway', businessObject: { get: () => undefined } });
expect(screen.getByText(/不是用户任务|仅.*用户任务/)).toBeInTheDocument();
expect(screen.queryByTestId('eip4-candidate-add')).not.toBeInTheDocument();
});
});
describe('Eip4Panel — 办理人(candidateUsers)', () => {
it('顶部灰字提示:引擎以本控件为准', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
expect(screen.getByText(/引擎以本控件为准/)).toBeInTheDocument();
});
it('set:改 content 写回 activiti:candidateUsers(可被 codec 解析)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
const input = screen.getByTestId('eip4-candidate-content-0');
fireEvent.change(input, { target: { value: 'newUser1,newUser2' } });
const payload = lastPayload(updateProperties);
const written = payload['activiti:candidateUsers'] as string;
const parsed = parseCandidateExpression(written)!;
expect(parsed.items[0].content).toBe('newUser1,newUser2');
expect(parsed.items[0].type).toBe('position');
});
it('🔴 改 items 后 meta 逐字保留(taskSuccessService 等业务字段不丢)', async () => {
const { modeler, updateProperties, select } = makeModeler();
const original = parseCandidateExpression(REAL_CANDIDATE)!;
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), {
target: { value: 'changed' },
});
const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string;
const parsed = parseCandidateExpression(written)!;
// meta 逐字保留
expect(parsed.meta).toEqual(original.meta);
expect(parsed.meta.taskSuccessService).toBe('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS');
// items 确已改
expect(parsed.items[0].content).toBe('changed');
});
it('清空最后一行(meta 为空):无 confirm,直接写回 undefined', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': candidateNoMeta() }));
fireEvent.click(screen.getByTestId('eip4-candidate-remove-0'));
expect(confirmSpy).not.toHaveBeenCalled();
expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined();
expect('activiti:candidateUsers' in lastPayload(updateProperties)).toBe(true);
});
it('I-3 清空含非空业务 meta:confirm=确认 → 写回 undefined', async () => {
const { modeler, updateProperties, select } = makeModeler();
confirmSpy.mockReturnValue(true);
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
fireEvent.click(screen.getByTestId('eip4-candidate-remove-0'));
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(String(confirmSpy.mock.calls[0][0])).toContain('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS');
expect(lastPayload(updateProperties)['activiti:candidateUsers']).toBeUndefined();
});
it('I-3 清空含非空业务 meta:confirm=取消 → 不写回、行仍在', async () => {
const { modeler, updateProperties, select } = makeModeler();
confirmSpy.mockReturnValue(false);
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
fireEvent.click(screen.getByTestId('eip4-candidate-remove-0'));
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(updateProperties).not.toHaveBeenCalled(); // 引擎未变
expect(screen.getByTestId('eip4-candidate-content-0')).toBeInTheDocument(); // 行未删
});
it('I-3 非空业务 meta 顶部只读徽标显示任务后置服务', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
const badge = screen.getByTestId('eip4-candidate-meta-badge');
expect(badge.textContent).toContain('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS');
});
it('顺手:非标准办理人表达式显示「编辑将覆盖」警示', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': '${someOtherExpr(execution)}' }));
expect(screen.getByTestId('eip4-candidate-nonstandard')).toBeInTheDocument();
});
it('增行:改 type 下拉写回对应 type', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.click(screen.getByTestId('eip4-candidate-add'));
fireEvent.change(screen.getByTestId('eip4-candidate-type-0'), {
target: { value: 'scriptUser' },
});
fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), {
target: { value: '${APPLYUSERS}' },
});
const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string;
const parsed = parseCandidateExpression(written)!;
expect(parsed.items[0]).toMatchObject({ type: 'scriptUser', content: '${APPLYUSERS}' });
});
// codec build 对叶子值应用引擎 stringToJson 转义(' → ‘、" → “),防用户输入含撇号/双引号
// 截断外层 JUEL 单引号字面量或内层 JSON。侧板消费 codec 即受保护——断言写回载荷的内容段
// (剥离 JUEL 前后缀定界引号后)无裸 ASCII 撇号、有全角‘。
it("content 含撇号 O'Brien:写回载荷转义为‘、内容段无裸单引号(防截断 JUEL 字面量)", async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:candidateUsers': REAL_CANDIDATE }));
fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), {
target: { value: "O'Brien" },
});
const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string;
const PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'";
const SUFFIX = "')}";
const content = written.slice(PREFIX.length, written.length - SUFFIX.length);
expect(content).toContain('O‘Brien'); // U+2018 全角撇号
expect(content.includes("'")).toBe(false); // 内容段完全无裸 ASCII 单引号
});
});
describe('Eip4Panel — 会签(multiInstance)', () => {
it('开:载荷含 loopCharacteristics(collection multiInstance 前缀+elementVariable+completionCondition 全票预设)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.click(screen.getByTestId('eip4-cosign-toggle'));
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect(loop).toBeTruthy();
expect(String(loop['activiti:collection'])).toContain('multiInstanceUsersHandler.getUsers');
expect(loop['activiti:elementVariable']).toBe('assignee');
expect((loop.completionCondition as { body: string }).body).toBe(
'${nrOfCompletedInstances/nrOfInstances==1}',
);
expect(loop.isSequential).toBe(false);
});
it('关:已有会签 → 载荷 loopCharacteristics=undefined', async () => {
const { modeler, updateProperties, select } = makeModeler();
const loop = moddleEl('bpmn:MultiInstanceLoopCharacteristics', {
'activiti:collection': extractAttr('activiti:collection'),
'activiti:elementVariable': 'assignee',
completionCondition: { body: '${nrOfCompletedInstances/nrOfInstances==1}' },
});
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: loop }));
// 初始应为开
expect((screen.getByTestId('eip4-cosign-toggle') as HTMLInputElement).checked).toBe(true);
fireEvent.click(screen.getByTestId('eip4-cosign-toggle'));
const payload = lastPayload(updateProperties);
expect('loopCharacteristics' in payload).toBe(true);
expect(payload.loopCharacteristics).toBeUndefined();
});
it('指定数 N:completionCondition body 代入 N', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.click(screen.getByTestId('eip4-cosign-toggle'));
fireEvent.change(screen.getByTestId('eip4-cosign-completion-type'), {
target: { value: 'count' },
});
fireEvent.change(screen.getByTestId('eip4-cosign-completion-n'), { target: { value: '3' } });
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect((loop.completionCondition as { body: string }).body).toBe(
'${nrOfCompletedInstances>=3}',
);
});
it('过半预设:body 为 >0.5', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.click(screen.getByTestId('eip4-cosign-toggle'));
fireEvent.change(screen.getByTestId('eip4-cosign-completion-type'), {
target: { value: 'majority' },
});
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect((loop.completionCondition as { body: string }).body).toBe(
'${nrOfCompletedInstances/nrOfInstances>0.5}',
);
});
// ── I-1 会签保真:读回并原样保留 isSequential / elementVariable / 非预设完成条件 ──────
// 真实库存在 isSequential=true、elementVariable=assign、完成条件 >0.6 等形态;强写会静默改坏。
function cosignLoop() {
return moddleEl('bpmn:MultiInstanceLoopCharacteristics', {
isSequential: true,
'activiti:collection': extractAttr('activiti:collection'),
'activiti:elementVariable': 'assign',
completionCondition: { body: '${nrOfCompletedInstances/nrOfInstances>0.6}' },
});
}
it('I-1 串行会签往返保 isSequential=true(不被强写 false)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: cosignLoop() }));
expect((screen.getByTestId('eip4-cosign-sequential') as HTMLInputElement).checked).toBe(true);
// 触发一次写(编辑会签人员 content),断言 isSequential 保留 true
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect(loop.isSequential).toBe(true);
});
it('I-1 elementVariable=assign 往返保 assign(不被强写 assignee)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: cosignLoop() }));
expect((screen.getByTestId('eip4-cosign-element-variable') as HTMLInputElement).value).toBe('assign');
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect(loop['activiti:elementVariable']).toBe('assign');
});
it('I-1 非预设完成条件 >0.6 不被归一为全票(自定义态保留原 body)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: cosignLoop() }));
// 下拉显「自定义(保留)」+ 原 body 展示
expect(screen.getByText(/自定义(保留)/)).toBeInTheDocument();
expect(screen.getByTestId('eip4-cosign-completion-custom').textContent).toContain(
'${nrOfCompletedInstances/nrOfInstances>0.6}',
);
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect((loop.completionCondition as { body: string }).body).toBe(
'${nrOfCompletedInstances/nrOfInstances>0.6}',
);
});
it('I-1 缺 elementVariable 的会签:写回省略该属性(不凭空写空)', async () => {
const { modeler, updateProperties, select } = makeModeler();
const loop = moddleEl('bpmn:MultiInstanceLoopCharacteristics', {
isSequential: false,
'activiti:collection': extractAttr('activiti:collection'),
// 无 activiti:elementVariable、无 completionCondition
});
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ loopCharacteristics: loop }));
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
const written = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
expect('activiti:elementVariable' in written).toBe(false); // 缺省态不写
expect('completionCondition' in written).toBe(false); // 原本无完成条件不发出
});
});
describe('Eip4Panel — formKey', () => {
it('选择模板 → 写回 activiti:formKey=裸 UUID', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
const sel = await screen.findByTestId('eip4-formkey-select');
// 等待模板选项加载
await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(2));
fireEvent.change(sel, { target: { value: 'aaaa-bbbb' } });
expect(lastPayload(updateProperties)['activiti:formKey']).toBe('aaaa-bbbb');
});
it('选「无」→ 写回 undefined 清除', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:formKey': '2098ce21-400b-4425-9c22-63e350974b98' }));
const sel = await screen.findByTestId('eip4-formkey-select');
fireEvent.change(sel, { target: { value: '' } });
const payload = lastPayload(updateProperties);
expect('activiti:formKey' in payload).toBe(true);
expect(payload['activiti:formKey']).toBeUndefined();
});
it('过滤输入实时 filter 选项(名称匹配)', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
const sel = await screen.findByTestId('eip4-formkey-select');
await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(3)); // (无)+3
fireEvent.change(screen.getByTestId('eip4-formkey-filter'), { target: { value: '合同' } });
const opts = Array.from(sel.querySelectorAll('option')).map((o) => o.textContent);
expect(opts).toContain('合同交底表单');
expect(opts).not.toContain('另一个表单');
});
it('未命名项(name===id)显示「<uuid前8>…(未命名)」', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
const sel = await screen.findByTestId('eip4-formkey-select');
await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(3));
const opts = Array.from(sel.querySelectorAll('option')).map((o) => o.textContent);
expect(opts).toContain('deadbeef…(未命名)');
});
it('degraded:显示「模板列表暂不可用」提示', async () => {
mWfTemplates.mockResolvedValueOnce({ templates: [], degraded: true });
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
expect(await screen.findByTestId('eip4-formkey-degraded')).toBeInTheDocument();
});
it('过滤掉当前值后 select 仍保留该值(占位「(当前)」防丢值)', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ 'activiti:formKey': 'aaaa-bbbb' })); // 当前值=另一个表单
const sel = (await screen.findByTestId('eip4-formkey-select')) as HTMLSelectElement;
await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(3));
// 过滤到「合同」→ aaaa-bbbb(另一个表单)被过滤掉
fireEvent.change(screen.getByTestId('eip4-formkey-filter'), { target: { value: '合同' } });
expect(sel.value).toBe('aaaa-bbbb'); // 值未丢
const cur = Array.from(sel.querySelectorAll('option')).find(
(o) => (o as HTMLOptionElement).value === 'aaaa-bbbb',
);
expect(cur).toBeTruthy();
expect(cur!.textContent).toContain('(当前)');
});
});
describe('Eip4Panel — 扩展属性(长尾 $attrs)', () => {
it('增:填 key/value 后写回命名空间键', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), {
target: { value: 'activiti:custom' },
});
fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'v1' } });
fireEvent.click(screen.getByTestId('eip4-extattr-add'));
expect(lastPayload(updateProperties)).toEqual({ 'activiti:custom': 'v1' });
});
it('删:已有扩展属性写回 undefined', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({}, { 'activiti:custom': 'v1' }));
expect(screen.getByTestId('eip4-extattr-key-0')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('eip4-extattr-remove-0'));
const payload = lastPayload(updateProperties);
expect('activiti:custom' in payload).toBe(true);
expect(payload['activiti:custom']).toBeUndefined();
});
it('只列 activiti:/flowable: 前缀的 $attrs(其它前缀不显示)', async () => {
const { modeler, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask({}, { 'activiti:custom': 'v1', 'xmlns:foo': 'bar' }));
expect(screen.getByTestId('eip4-extattr-key-0')).toHaveValue('activiti:custom');
expect(screen.queryByTestId('eip4-extattr-key-1')).not.toBeInTheDocument();
});
it('顺手:无 activiti:/flowable: 前缀的新键被拒(不写回)', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), { target: { value: 'foo' } });
fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'v' } });
fireEvent.click(screen.getByTestId('eip4-extattr-add'));
expect(updateProperties).not.toHaveBeenCalled();
});
it('顺手:拉黑有专用控件的键(activiti:formKey)不允许从扩展属性写', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.change(screen.getByTestId('eip4-extattr-new-key'), {
target: { value: 'activiti:formKey' },
});
fireEvent.change(screen.getByTestId('eip4-extattr-new-value'), { target: { value: 'x' } });
fireEvent.click(screen.getByTestId('eip4-extattr-add'));
expect(updateProperties).not.toHaveBeenCalled();
});
});
describe('Eip4Panel — 任务监听器(taskListener)', () => {
it('增:新监听器写回 extensionElements,并保留已有监听器的 field(引用不动)', async () => {
const { modeler, updateProperties, moddle, select } = makeModeler();
const fieldObj = moddleEl('activiti:Field', { name: 'mailTemplate' });
const existing = moddleEl('activiti:TaskListener', {
event: 'complete',
class: 'com.dsasp.server.wf.user.listener.TaskCompleteListener',
fields: [fieldObj],
});
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ extensionElements: { values: [existing] } }));
// 已有监听器显示 field 徽标
expect(screen.getByText(/含 field 配置/)).toBeInTheDocument();
fireEvent.click(screen.getByTestId('eip4-listener-add'));
const ext = lastPayload(updateProperties).extensionElements as { values: Array<Record<string, unknown>> };
expect(ext.$type).toBe('bpmn:ExtensionElements');
expect(ext.values.length).toBe(2);
// 原监听器被重建但其 fields 数组引用与 field 元素引用原样保留
const withFields = ext.values.find((v) => Array.isArray(v.fields));
expect(withFields).toBeTruthy();
expect((withFields!.fields as unknown[])[0]).toBe(fieldObj);
// moddle.create 被用于构造 taskListener 与 ExtensionElements
expect(moddle.create).toHaveBeenCalledWith('bpmn:ExtensionElements', expect.anything());
});
it('编辑 event 下拉 + class 值写回', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.click(screen.getByTestId('eip4-listener-add'));
fireEvent.change(screen.getByTestId('eip4-listener-event-0'), { target: { value: 'assignment' } });
fireEvent.change(screen.getByTestId('eip4-listener-value-0'), { target: { value: 'com.X.Listener' } });
const ext = lastPayload(updateProperties).extensionElements as { values: Array<Record<string, unknown>> };
const listener = ext.values.find((v) => v.$type === 'activiti:TaskListener')!;
expect(listener.event).toBe('assignment');
expect(listener.class).toBe('com.X.Listener');
});
it('删:移除唯一监听器 → extensionElements=undefined', async () => {
const { modeler, updateProperties, select } = makeModeler();
const existing = moddleEl('activiti:TaskListener', { event: 'create', class: 'com.X' });
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ extensionElements: { values: [existing] } }));
fireEvent.click(screen.getByTestId('eip4-listener-remove-0'));
const payload = lastPayload(updateProperties);
expect('extensionElements' in payload).toBe(true);
expect(payload.extensionElements).toBeUndefined();
});
it('delegateExpression 模式:互斥写回 delegateExpression', async () => {
const { modeler, updateProperties, select } = makeModeler();
render(<Eip4Panel modeler={modeler} />);
await select(userTask());
fireEvent.click(screen.getByTestId('eip4-listener-add'));
fireEvent.change(screen.getByTestId('eip4-listener-mode-0'), {
target: { value: 'delegateExpression' },
});
fireEvent.change(screen.getByTestId('eip4-listener-value-0'), { target: { value: '${bean}' } });
const ext = lastPayload(updateProperties).extensionElements as { values: Array<Record<string, unknown>> };
const listener = ext.values.find((v) => v.$type === 'activiti:TaskListener')!;
expect(listener.delegateExpression).toBe('${bean}');
expect('class' in listener).toBe(false);
});
});
describe('Eip4Panel — 切换节点 / undo-redo 重灌(评审 I-2 + 顺手)', () => {
it('I-2 A(meta X)→B(meta Y)→编辑 B→写回 meta===Y 且 ≠X', async () => {
const { modeler, updateProperties, select } = makeModeler();
const item = (c: string): UserPropertyItem => ({
type: 'user',
content: c,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
});
const exprA = buildCandidateExpression([item('a')], 'candidate', { taskSuccessService: 'SVC_X' });
const exprB = buildCandidateExpression([item('b')], 'candidate', { taskSuccessService: 'SVC_Y' });
render(<Eip4Panel modeler={modeler} />);
await select(userTask({ __id: 'A', 'activiti:candidateUsers': exprA }));
await select(userTask({ __id: 'B', 'activiti:candidateUsers': exprB }));
// 编辑 B 的 content
fireEvent.change(screen.getByTestId('eip4-candidate-content-0'), { target: { value: 'b2' } });
const written = lastPayload(updateProperties)['activiti:candidateUsers'] as string;
const meta = parseCandidateExpression(written)!.meta;
expect(meta.taskSuccessService).toBe('SVC_Y'); // 用 B 的 meta
expect(meta.taskSuccessService).not.toBe('SVC_X'); // 不串到 A 的 meta
});
it('顺手:commandStack.changed(外部 undo)对当前选中重灌本地态', async () => {
const { modeler, select, fireCommandStack } = makeModeler();
const item = (c: string): UserPropertyItem => ({
type: 'user',
content: c,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
});
// 可变 map:模拟外部 undo 改写 businessObject。
const map: Record<string, unknown> = {
'activiti:candidateUsers': buildCandidateExpression([item('X')], 'candidate', {}),
};
const el = {
id: 't1',
type: 'bpmn:UserTask',
businessObject: { $type: 'bpmn:UserTask', get: (n: string) => map[n] },
};
render(<Eip4Panel modeler={modeler} />);
await select(el);
expect((screen.getByTestId('eip4-candidate-content-0') as HTMLInputElement).value).toBe('X');
// 外部 undo 改了 businessObject → commandStack.changed → 重灌
map['activiti:candidateUsers'] = buildCandidateExpression([item('Y')], 'candidate', {});
await fireCommandStack();
expect((screen.getByTestId('eip4-candidate-content-0') as HTMLInputElement).value).toBe('Y');
});
});

805
src/modeler/Eip4Panel.tsx Normal file
View File

@@ -0,0 +1,805 @@
// EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。
//
// 设计要点(计划 T2.4 + §0.5 P5 + 评审收口):
// - 全部写操作经 bpmn-js `modeling.updateProperties(element,{...})`,undo/redo 天然生效。
// - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。
// - 🔴 meta 透传硬要求:codec parse 出的外层业务字段(taskSuccessService 等)存入 state,
// 写回时原样带回 build,否则重新部署会打掉已部署流程的任务后置服务钩子。顶部只读徽标显示,
// 删光 items 时 confirm 确认才写 undefined(评审 I-3)。
// - 🔴 会签保真(评审 I-1):isSequential/elementVariable/completionCondition 原始值读进 state、
// 写回用读到的值(真实库有 isSequential=true / elementVariable=assign / 完成条件 >0.6 等
// 非预设形态,强写会静默改坏派任);完成条件 body 不匹配预设时置「自定义(保留)」态,
// 仅用户主动选预设才改写。
// - 扩展属性只列长尾 $attrs;新增强制 activiti:/flowable: 前缀并拉黑有专用控件的键。
// - taskListener 重建时原样保留其 field 子元素(moddle 元素引用不动)。
// - undo/redo:订阅 commandStack.changed,非自身写入时对当前选中重灌本地态。
import { useEffect, useRef, useState } from 'react';
import {
buildCandidateExpression,
parseCandidateExpression,
type CandidateVariant,
type UserPropertyItem,
} from './candidateExpression';
import { fetchWfTemplates, type WfTemplateOption } from '../api/processModeler';
import { toast } from '../components/ui';
import type { BpmnElement, SelectionModeler } from './useSelectedElement';
import { useSelectedElement } from './useSelectedElement';
// ── bpmn-js 服务契约(最小) ───────────────────────────────────────────────────
interface Modeling {
updateProperties(element: BpmnElement, props: Record<string, unknown>): void;
}
interface Moddle {
create(type: string, props?: Record<string, unknown>): Record<string, unknown>;
}
export interface PanelModeler extends SelectionModeler {
get(service: string): unknown;
}
// ── 办理人 type 取值(§0 实测 10 种)+ 中文标签 ────────────────────────────────
const CANDIDATE_TYPES: Array<{ value: string; label: string }> = [
{ value: 'user', label: '指定人员' },
{ value: 'depart', label: '指定部门' },
{ value: 'position', label: '指定岗位' },
{ value: 'formSpecifiedDimension', label: '表单指定维度' },
{ value: 'initiator', label: '流程发起人' },
{ value: 'sameToTask', label: '同某任务办理人' },
{ value: 'beforeTaskLeader', label: '上一办理人领导' },
{ value: 'beforeTaskDepartManager', label: '上一办理人部门经理' },
{ value: 'scriptUser', label: '脚本/表达式' },
{ value: 'projectRoleType', label: '项目角色' },
];
const LISTENER_EVENTS = ['create', 'assignment', 'complete', 'all'];
// 有专用控件的属性,禁止再从「扩展属性」兜底编辑器写入(去重、防冲突)。
const RESERVED_EXT_LOCALNAMES = new Set(['candidateUsers', 'formKey', 'collection', 'elementVariable']);
// ── 会签完成条件预设 ─────────────────────────────────────────────────────────
type CompletionType = 'all' | 'majority' | 'count' | 'custom';
const COMPLETION_ALL = '${nrOfCompletedInstances/nrOfInstances==1}';
const COMPLETION_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}';
function completionBodyFor(s: CosignState): string {
if (s.completionType === 'majority') return COMPLETION_MAJORITY;
if (s.completionType === 'count') return '${nrOfCompletedInstances>=' + s.completionN + '}';
if (s.completionType === 'custom') return s.completionCustomBody;
return COMPLETION_ALL;
}
// 精确匹配预设串(不用子串,否则 >0.55 会误判为过半);非预设/无 body → 自定义(保留)。
function parseCompletion(body: string | undefined): {
type: CompletionType;
n: number;
custom: string;
} {
if (body === COMPLETION_ALL) return { type: 'all', n: 2, custom: '' };
if (body === COMPLETION_MAJORITY) return { type: 'majority', n: 2, custom: '' };
const m = body ? body.match(/^\$\{nrOfCompletedInstances>=(\d+)\}$/) : null;
if (m) return { type: 'count', n: Number(m[1]), custom: '' };
return { type: 'custom', n: 2, custom: body ?? '' };
}
// ── moddle 读值(兼容 .get(name) 与直读属性) ──────────────────────────────────
function mget(obj: unknown, name: string): unknown {
if (!obj || typeof obj !== 'object') return undefined;
const o = obj as Record<string, unknown> & { get?: (n: string) => unknown };
if (typeof o.get === 'function') return o.get(name);
return o[name];
}
// 非空业务 meta → 只读徽标/确认文案(用于「删光办理人会一并移除 X」)。
function notableMeta(meta: Record<string, unknown>): string[] {
const out: string[] = [];
if (typeof meta.taskSuccessService === 'string' && meta.taskSuccessService)
out.push('任务后置服务:' + meta.taskSuccessService);
if (typeof meta.messageTemplate === 'string' && meta.messageTemplate) out.push('消息模板');
if (meta.isSkipInitiator === true) out.push('跳过发起人');
if (meta.isNoUserSkip === true) out.push('无办理人自动跳过');
if (meta.isSkipBeforeTask === true) out.push('跳过前置任务办理人');
return out;
}
// formKey 下拉展示名:网关无名称时 name 回落为 id(uuid),未命名项显示「<uuid前8>…(未命名)」。
function wfTemplateLabel(t: WfTemplateOption): string {
if (t.name && t.name !== t.id) return t.name;
return (t.id.length > 8 ? t.id.slice(0, 8) : t.id) + '…(未命名)';
}
function newCandidateItem(): UserPropertyItem {
return {
type: 'user',
content: '',
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
};
}
interface ListenerRow {
event: string;
mode: 'class' | 'delegateExpression';
value: string;
/** 原监听器的 field 子元素数组(编辑时原样保留,引用不动)。 */
fields?: unknown[];
}
interface CosignState {
enabled: boolean;
items: UserPropertyItem[];
/** 保真:串行/并行,读回原值(真实库有 isSequential=true)。 */
isSequential: boolean;
/** 保真:循环变量名,读回原值(真实库有 assign/loop_assign/缺省);为空则写回时省略该属性。 */
elementVariable: string;
completionType: CompletionType;
completionN: number;
/** completionType==='custom' 时保留的原始 body;'' 表示原本无 completionCondition。 */
completionCustomBody: string;
}
const FRESH_COSIGN: CosignState = {
enabled: false,
items: [],
isSequential: false,
elementVariable: 'assignee',
completionType: 'all',
completionN: 2,
completionCustomBody: '',
};
// ── items 编辑器(办理人 / 会签人员复用) ──────────────────────────────────────
function ItemsEditor({
idPrefix,
items,
onChange,
}: {
idPrefix: string;
items: UserPropertyItem[];
onChange: (next: UserPropertyItem[]) => void;
}) {
const patch = (i: number, p: Partial<UserPropertyItem>) =>
onChange(items.map((it, idx) => (idx === i ? { ...it, ...p } : it)));
const remove = (i: number) => onChange(items.filter((_, idx) => idx !== i));
const add = () => onChange([...items, newCandidateItem()]);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{items.map((it, i) => (
<div
key={i}
style={{
border: '1px solid var(--line)',
borderRadius: 4,
padding: 6,
display: 'flex',
flexDirection: 'column',
gap: 4,
}}
>
<div style={{ display: 'flex', gap: 4 }}>
<select
data-testid={`${idPrefix}-type-${i}`}
value={it.type}
onChange={(e) => patch(i, { type: e.target.value })}
style={{ flex: '0 0 120px' }}
>
{CANDIDATE_TYPES.map((t) => (
<option key={t.value} value={t.value}>
{t.label}
</option>
))}
</select>
<input
data-testid={`${idPrefix}-content-${i}`}
value={it.content}
placeholder="人员/部门/岗位 id 或表达式"
onChange={(e) => patch(i, { content: e.target.value })}
style={{ flex: 1, minWidth: 0 }}
/>
<button
className="btn btn-sm"
data-testid={`${idPrefix}-remove-${i}`}
onClick={() => remove(i)}
title="删除该行"
>
删
</button>
</div>
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', fontSize: 12 }}>
<label>
<input
type="checkbox"
data-testid={`${idPrefix}-iscandidate-${i}`}
checked={!!it.isCandidate}
onChange={(e) => patch(i, { isCandidate: e.target.checked })}
/>{' '}
候选
</label>
<label>
<input
type="checkbox"
data-testid={`${idPrefix}-mail-${i}`}
checked={!!it.isSendMail}
onChange={(e) => patch(i, { isSendMail: e.target.checked })}
/>{' '}
邮件
</label>
<label>
<input
type="checkbox"
data-testid={`${idPrefix}-phone-${i}`}
checked={!!it.isSendPhone}
onChange={(e) => patch(i, { isSendPhone: e.target.checked })}
/>{' '}
短信
</label>
<label>
<input
type="checkbox"
data-testid={`${idPrefix}-msg-${i}`}
checked={!!it.isSendMessage}
onChange={(e) => patch(i, { isSendMessage: e.target.checked })}
/>{' '}
站内
</label>
</div>
</div>
))}
<button className="btn btn-sm" data-testid={`${idPrefix}-add`} onClick={add}>
+ 添加办理人
</button>
</div>
);
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<div style={{ borderBottom: '1px solid var(--line)', padding: '10px 12px' }}>
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 8 }}>{title}</div>
{children}
</div>
);
}
export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
const element = useSelectedElement(modeler);
const modeling = modeler ? (modeler.get('modeling') as Modeling | undefined) : undefined;
const moddle = modeler ? (modeler.get('moddle') as Moddle | undefined) : undefined;
const isUserTask = element?.type === 'bpmn:UserTask';
// ── 本地编辑态(选中变更 / undo-redo 时从 businessObject 重新初始化) ─────────
const [candidateItems, setCandidateItems] = useState<UserPropertyItem[]>([]);
const [candidateMeta, setCandidateMeta] = useState<Record<string, unknown>>({});
const [candidateNonStandard, setCandidateNonStandard] = useState(false);
const [cosign, setCosign] = useState<CosignState>(FRESH_COSIGN);
const [cosignMeta, setCosignMeta] = useState<Record<string, unknown>>({});
const [formKey, setFormKey] = useState('');
const [extAttrs, setExtAttrs] = useState<Array<{ key: string; value: string }>>([]);
const [newAttr, setNewAttr] = useState<{ key: string; value: string }>({ key: '', value: '' });
const [listeners, setListeners] = useState<ListenerRow[]>([]);
const [templates, setTemplates] = useState<WfTemplateOption[]>([]);
const [templatesDegraded, setTemplatesDegraded] = useState(false);
const [formKeyFilter, setFormKeyFilter] = useState('');
// undo/redo 重灌计数:commandStack.changed(非自身写入)时自增,触发 init 重跑。
const [syncTick, setSyncTick] = useState(0);
// 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。
const otherExtRef = useRef<unknown[]>([]);
// 自身写入标记:updateProperties 会触发 commandStack.changed,借此跳过自触发重灌。
const selfWriteRef = useRef(false);
// formKey 数据源加载一次(透传 degraded;1016 项靠过滤输入,不裸滚动)。
useEffect(() => {
let alive = true;
Promise.resolve(fetchWfTemplates())
.then((r) => {
if (!alive) return;
setTemplates(Array.isArray(r?.templates) ? r.templates : []);
setTemplatesDegraded(!!r?.degraded);
})
.catch(() => {
if (!alive) return;
setTemplates([]);
setTemplatesDegraded(true);
});
return () => {
alive = false;
};
}, []);
// undo/redo 脱同步防线:非自身写入的 commandStack 变更 → 对当前选中重灌本地态。
useEffect(() => {
if (!modeler) return;
const handler = () => {
if (selfWriteRef.current) {
selfWriteRef.current = false; // 自身 updateProperties 触发,不重灌(避免规范化闪烁)
return;
}
setSyncTick((t) => t + 1);
};
modeler.on('commandStack.changed', handler);
return () => {
modeler.off?.('commandStack.changed', handler);
};
}, [modeler]);
// 选中变更 / 外部命令 → 从 businessObject 重新初始化本地态。
useEffect(() => {
if (!element || element.type !== 'bpmn:UserTask') {
setCandidateItems([]);
setCandidateMeta({});
setCandidateNonStandard(false);
setCosign(FRESH_COSIGN);
setCosignMeta({});
setFormKey('');
setExtAttrs([]);
setNewAttr({ key: '', value: '' });
setListeners([]);
otherExtRef.current = [];
return;
}
const bo = element.businessObject;
// 办理人
const rawCand = bo.get('activiti:candidateUsers') as string | undefined;
const cand = parseCandidateExpression(rawCand);
setCandidateItems(cand?.items ?? []);
setCandidateMeta(cand?.meta ?? {});
setCandidateNonStandard(!!rawCand && !cand); // 非空但解析失败=非标准表达式
// 会签(保真读回 isSequential/elementVariable/completionCondition 原值)
const loop = bo.get('loopCharacteristics');
if (loop) {
const parsed = parseCandidateExpression(mget(loop, 'activiti:collection') as string | undefined);
const cc = parseCompletion(
(mget(loop, 'completionCondition') as { body?: string } | undefined)?.body,
);
setCosign({
enabled: true,
items: parsed?.items ?? [],
isSequential: Boolean(mget(loop, 'isSequential')),
elementVariable: (mget(loop, 'activiti:elementVariable') as string) ?? '',
completionType: cc.type,
completionN: cc.n,
completionCustomBody: cc.custom,
});
setCosignMeta(parsed?.meta ?? {});
} else {
setCosign(FRESH_COSIGN);
setCosignMeta({});
}
// formKey
setFormKey((bo.get('activiti:formKey') as string) ?? '');
// 扩展属性(长尾 $attrs,只留 activiti:/flowable: 前缀)
const attrs = bo.$attrs ?? {};
setExtAttrs(
Object.entries(attrs)
.filter(([k]) => k.startsWith('activiti:') || k.startsWith('flowable:'))
.map(([key, value]) => ({ key, value: String(value) })),
);
setNewAttr({ key: '', value: '' });
// 任务监听器
const extEl = bo.get('extensionElements') as { values?: unknown[] } | undefined;
const values = (extEl?.values ?? []) as unknown[];
// moddle 类型名遵循 activiti/camunda 惯例=PascalCase(xml.tagAlias:lowerCase 令 XML 元素名仍小写
// <activiti:taskListener>),故按 $type 'activiti:TaskListener' 识别;小写名会致扩展类型 $pkg 串味、
// 断部署(见 moddle/serialization.test.ts)。
otherExtRef.current = values.filter((v) => (v as { $type?: string }).$type !== 'activiti:TaskListener');
setListeners(
values
.filter((v) => (v as { $type?: string }).$type === 'activiti:TaskListener')
.map((v) => {
const cls = mget(v, 'class') as string | undefined;
const del = mget(v, 'delegateExpression') as string | undefined;
const fields = ((v as { fields?: unknown[] }).fields ?? mget(v, 'fields')) as unknown[] | undefined;
return {
event: (mget(v, 'event') as string) ?? 'create',
mode: cls ? 'class' : del ? 'delegateExpression' : 'class',
value: cls ?? del ?? '',
fields: fields && fields.length ? fields : undefined,
} as ListenerRow;
}),
);
}, [element, syncTick]);
function update(props: Record<string, unknown>) {
if (element && modeling) {
selfWriteRef.current = true;
modeling.updateProperties(element, props);
}
}
// ── 办理人写回 ─────────────────────────────────────────────────────────────
function writeCandidate(items: UserPropertyItem[]) {
if (items.length === 0) {
// 删光 items:若外层含非空业务 meta,confirm 确认才写 undefined(否则连带清除业务字段)。
const notable = notableMeta(candidateMeta);
if (
notable.length > 0 &&
typeof window !== 'undefined' &&
!window.confirm('清空办理人将一并移除:' + notable.join('、') + '。确认清空?')
) {
return; // 取消:本地态与引擎均不变
}
setCandidateItems([]);
update({ 'activiti:candidateUsers': undefined });
return;
}
setCandidateItems(items);
update({ 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMeta) });
}
// ── 会签写回 ───────────────────────────────────────────────────────────────
function writeCosign(next: CosignState) {
setCosign(next);
if (!next.enabled) {
update({ loopCharacteristics: undefined });
return;
}
if (!moddle) return;
const collection = buildCandidateExpression(
next.items,
'multiInstance' as CandidateVariant,
cosignMeta,
);
const props: Record<string, unknown> = {
isSequential: next.isSequential,
'activiti:collection': collection,
};
// elementVariable 为空(真实库缺省态)则省略,不凭空写空属性。
if (next.elementVariable) props['activiti:elementVariable'] = next.elementVariable;
const body = completionBodyFor(next);
// body 为空(原本无 completionCondition)则不发出该子元素,保真。
if (body) props.completionCondition = moddle.create('bpmn:FormalExpression', { body });
const loop = moddle.create('bpmn:MultiInstanceLoopCharacteristics', props);
update({ loopCharacteristics: loop });
}
// ── formKey 写回 ───────────────────────────────────────────────────────────
function writeFormKey(value: string) {
setFormKey(value);
update({ 'activiti:formKey': value === '' ? undefined : value });
}
// ── 扩展属性写回 ───────────────────────────────────────────────────────────
function addExtAttr() {
const key = newAttr.key.trim();
if (!key) return;
if (!key.startsWith('activiti:') && !key.startsWith('flowable:')) {
toast('扩展属性键必须以 activiti: 或 flowable: 开头', 'warn');
return;
}
const local = key.slice(key.indexOf(':') + 1);
if (RESERVED_EXT_LOCALNAMES.has(local)) {
toast('该属性有专用控件,请用上方对应控件编辑', 'warn');
return;
}
setExtAttrs((prev) => {
const rest = prev.filter((a) => a.key !== key);
return [...rest, { key, value: newAttr.value }];
});
update({ [key]: newAttr.value });
setNewAttr({ key: '', value: '' });
}
function editExtAttr(key: string, value: string) {
setExtAttrs((prev) => prev.map((a) => (a.key === key ? { ...a, value } : a)));
update({ [key]: value });
}
function removeExtAttr(key: string) {
setExtAttrs((prev) => prev.filter((a) => a.key !== key));
update({ [key]: undefined });
}
// ── 任务监听器写回 ─────────────────────────────────────────────────────────
function writeListeners(next: ListenerRow[]) {
setListeners(next);
if (!moddle) return;
const listenerEls = next.map((l) => {
const props: Record<string, unknown> = { event: l.event };
props[l.mode] = l.value;
if (l.fields && l.fields.length) props.fields = l.fields;
return moddle.create('activiti:TaskListener', props);
});
const all = [...otherExtRef.current, ...listenerEls];
const extEl = all.length ? moddle.create('bpmn:ExtensionElements', { values: all }) : undefined;
update({ extensionElements: extEl });
}
function addListener() {
writeListeners([...listeners, { event: 'create', mode: 'class', value: '' }]);
}
function patchListener(i: number, p: Partial<ListenerRow>) {
writeListeners(listeners.map((l, idx) => (idx === i ? { ...l, ...p } : l)));
}
function removeListener(i: number) {
writeListeners(listeners.filter((_, idx) => idx !== i));
}
// ── 渲染 ───────────────────────────────────────────────────────────────────
if (!element) {
return (
<div data-testid="process-modeler-eip4-panel" style={hintStyle}>
请选择一个用户任务节点以编辑 EIP4 属性。
</div>
);
}
if (!isUserTask) {
return (
<div data-testid="process-modeler-eip4-panel" style={hintStyle}>
选中的不是用户任务节点。EIP4 定制控件仅对用户任务(办理人 / 会签 / formKey)可用。
</div>
);
}
const candidateBadges = notableMeta(candidateMeta);
const formKeyQuery = formKeyFilter.trim().toLowerCase();
const filteredTemplates = formKeyQuery
? templates.filter(
(t) => t.name.toLowerCase().includes(formKeyQuery) || t.id.toLowerCase().includes(formKeyQuery),
)
: templates;
return (
<div
data-testid="process-modeler-eip4-panel"
style={{ overflow: 'auto', maxHeight: '55%', borderBottom: '1px solid var(--line)' }}
>
<div style={{ padding: '8px 12px', fontSize: 12, color: 'var(--text-3)', background: 'var(--surface-2, #fafafa)' }}>
EIP4 引擎以本控件为准,下方标准面板原生字段仅供高级调试。
</div>
<Section title="办理人">
{candidateBadges.length > 0 ? (
<div
data-testid="eip4-candidate-meta-badge"
style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 8, lineHeight: 1.6 }}
>
含业务配置:{candidateBadges.join('、')}(清空办理人会一并移除)
</div>
) : null}
{candidateNonStandard ? (
<div
data-testid="eip4-candidate-nonstandard"
style={{ fontSize: 12, color: 'var(--warn, #d48806)', marginBottom: 8 }}
>
当前为非标准办理人表达式,编辑将覆盖原表达式。
</div>
) : null}
<ItemsEditor idPrefix="eip4-candidate" items={candidateItems} onChange={writeCandidate} />
</Section>
<Section title="会签(多实例)">
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, marginBottom: 8 }}>
<input
type="checkbox"
data-testid="eip4-cosign-toggle"
checked={cosign.enabled}
onChange={(e) => writeCosign({ ...cosign, enabled: e.target.checked })}
/>
启用会签
</label>
{cosign.enabled ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<input
type="checkbox"
data-testid="eip4-cosign-sequential"
checked={cosign.isSequential}
onChange={(e) => writeCosign({ ...cosign, isSequential: e.target.checked })}
/>
串行(顺序会签)
</label>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<span style={{ flex: '0 0 auto' }}>循环变量</span>
<input
data-testid="eip4-cosign-element-variable"
value={cosign.elementVariable}
placeholder="assignee"
onChange={(e) => writeCosign({ ...cosign, elementVariable: e.target.value })}
style={{ flex: 1, minWidth: 0 }}
/>
</label>
<ItemsEditor
idPrefix="eip4-cosign"
items={cosign.items}
onChange={(items) => writeCosign({ ...cosign, items })}
/>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, flexWrap: 'wrap' }}>
<span>完成条件</span>
<select
data-testid="eip4-cosign-completion-type"
value={cosign.completionType}
onChange={(e) =>
writeCosign({ ...cosign, completionType: e.target.value as CompletionType })
}
>
{/* 自定义(保留)仅在当前为自定义态时可选中——presets 不提供切到自定义,防误清 */}
{cosign.completionType === 'custom' ? (
<option value="custom">自定义(保留)</option>
) : null}
<option value="all">全票通过</option>
<option value="majority">过半通过</option>
<option value="count">指定数</option>
</select>
{cosign.completionType === 'count' ? (
<input
type="number"
min={1}
data-testid="eip4-cosign-completion-n"
value={cosign.completionN}
onChange={(e) =>
writeCosign({ ...cosign, completionN: Number(e.target.value) || 1 })
}
style={{ width: 64 }}
/>
) : null}
{cosign.completionType === 'custom' ? (
<span
data-testid="eip4-cosign-completion-custom"
style={{ fontSize: 12, color: 'var(--text-3)' }}
>
当前条件:<code>{cosign.completionCustomBody || '(无)'}</code>
</span>
) : null}
</div>
</div>
) : null}
</Section>
<Section title="表单(formKey)">
{templatesDegraded ? (
<div
data-testid="eip4-formkey-degraded"
style={{ fontSize: 12, color: 'var(--warn, #d48806)', marginBottom: 6 }}
>
模板列表暂不可用(数据源异常);可保留当前值或稍后重试。
</div>
) : null}
<input
data-testid="eip4-formkey-filter"
placeholder={`筛选表单(名称或 id,共 ${templates.length} 项)`}
value={formKeyFilter}
onChange={(e) => setFormKeyFilter(e.target.value)}
style={{ width: '100%', marginBottom: 6 }}
/>
<select
data-testid="eip4-formkey-select"
value={formKey}
onChange={(e) => writeFormKey(e.target.value)}
style={{ width: '100%' }}
>
<option value="">(无)</option>
{/* 当前值不在(过滤后的)模板列表时,补一条占位以免下拉丢值 */}
{formKey && !filteredTemplates.some((t) => t.id === formKey) ? (
<option value={formKey}>
{(() => {
const cur = templates.find((t) => t.id === formKey);
return (cur ? wfTemplateLabel(cur) : formKey) + '(当前)';
})()}
</option>
) : null}
{filteredTemplates.map((t) => (
<option key={t.id} value={t.id}>
{wfTemplateLabel(t)}
</option>
))}
</select>
</Section>
<Section title="扩展属性(activiti/flowable)">
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{extAttrs.map((a, i) => (
<div key={a.key} style={{ display: 'flex', gap: 4 }}>
<input
data-testid={`eip4-extattr-key-${i}`}
value={a.key}
readOnly
style={{ flex: '0 0 130px', minWidth: 0 }}
/>
<input
data-testid={`eip4-extattr-value-${i}`}
value={a.value}
onChange={(e) => editExtAttr(a.key, e.target.value)}
style={{ flex: 1, minWidth: 0 }}
/>
<button
className="btn btn-sm"
data-testid={`eip4-extattr-remove-${i}`}
onClick={() => removeExtAttr(a.key)}
>
删
</button>
</div>
))}
<div style={{ display: 'flex', gap: 4 }}>
<input
data-testid="eip4-extattr-new-key"
placeholder="activiti:key"
value={newAttr.key}
onChange={(e) => setNewAttr((s) => ({ ...s, key: e.target.value }))}
style={{ flex: '0 0 130px', minWidth: 0 }}
/>
<input
data-testid="eip4-extattr-new-value"
placeholder="value"
value={newAttr.value}
onChange={(e) => setNewAttr((s) => ({ ...s, value: e.target.value }))}
style={{ flex: 1, minWidth: 0 }}
/>
<button className="btn btn-sm" data-testid="eip4-extattr-add" onClick={addExtAttr}>
+ 增
</button>
</div>
</div>
</Section>
<Section title="任务监听器(taskListener)">
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{listeners.map((l, i) => (
<div
key={i}
style={{ border: '1px solid var(--line)', borderRadius: 4, padding: 6, display: 'flex', flexDirection: 'column', gap: 4 }}
>
<div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
<select
data-testid={`eip4-listener-event-${i}`}
value={l.event}
onChange={(e) => patchListener(i, { event: e.target.value })}
style={{ flex: '0 0 110px' }}
>
{LISTENER_EVENTS.map((ev) => (
<option key={ev} value={ev}>
{ev}
</option>
))}
</select>
<select
data-testid={`eip4-listener-mode-${i}`}
value={l.mode}
onChange={(e) =>
patchListener(i, { mode: e.target.value as ListenerRow['mode'] })
}
style={{ flex: '0 0 130px' }}
>
<option value="class">class</option>
<option value="delegateExpression">delegateExpression</option>
</select>
<button
className="btn btn-sm"
data-testid={`eip4-listener-remove-${i}`}
onClick={() => removeListener(i)}
>
删
</button>
</div>
<input
data-testid={`eip4-listener-value-${i}`}
value={l.value}
placeholder={l.mode === 'class' ? '全限定类名' : '${bean}'}
onChange={(e) => patchListener(i, { value: e.target.value })}
/>
{l.fields && l.fields.length ? (
<span style={{ fontSize: 11, color: 'var(--text-3)' }}>
含 field 配置({l.fields.length})· 编辑时原样保留
</span>
) : null}
</div>
))}
<button className="btn btn-sm" data-testid="eip4-listener-add" onClick={addListener}>
+ 添加监听器
</button>
</div>
</Section>
</div>
);
}
const hintStyle: React.CSSProperties = {
padding: 12,
color: 'var(--text-3)',
fontSize: 12,
borderBottom: '1px solid var(--line)',
};

View File

@@ -0,0 +1,94 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { NewProcessDialog, type NewProcessResult } from './NewProcessDialog';
function renderDialog() {
const onConfirm = vi.fn<[NewProcessResult], void>();
const onClose = vi.fn();
render(<NewProcessDialog onConfirm={onConfirm} onClose={onClose} />);
return { onConfirm, onClose };
}
describe('NewProcessDialog', () => {
it('渲染名称/key/模板三字段', () => {
renderDialog();
expect(screen.getByTestId('new-process-name')).toBeInTheDocument();
expect(screen.getByTestId('new-process-key')).toBeInTheDocument();
expect(screen.getByTestId('new-process-template')).toBeInTheDocument();
// 模板下拉含四个模板
expect(screen.getByText('空白流程')).toBeInTheDocument();
expect(screen.getByText('单人审批')).toBeInTheDocument();
expect(screen.getByText('两级审批')).toBeInTheDocument();
expect(screen.getByText('会签')).toBeInTheDocument();
});
it('name/key 任一为空 → 确认禁用且 onConfirm 不触发', () => {
const { onConfirm } = renderDialog();
const confirm = screen.getByTestId('new-process-confirm');
expect(confirm).toBeDisabled();
// 只填 name,key 仍空 → 仍禁用
fireEvent.change(screen.getByTestId('new-process-name'), { target: { value: '请假审批' } });
expect(confirm).toBeDisabled();
fireEvent.click(confirm);
expect(onConfirm).not.toHaveBeenCalled();
});
it('key 仅空白也判无效', () => {
renderDialog();
fireEvent.change(screen.getByTestId('new-process-name'), { target: { value: 'n' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: ' ' } });
expect(screen.getByTestId('new-process-confirm')).toBeDisabled();
});
it('填齐 + 选会签模板 → 确认,onConfirm 收到实例化 XML(含 multiInstance,占位符已替换)', () => {
const { onConfirm } = renderDialog();
fireEvent.change(screen.getByTestId('new-process-name'), { target: { value: '合同会签' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: 'contractCosign' } });
fireEvent.change(screen.getByTestId('new-process-template'), { target: { value: 'cosign' } });
fireEvent.click(screen.getByTestId('new-process-confirm'));
expect(onConfirm).toHaveBeenCalledTimes(1);
const r = onConfirm.mock.calls[0][0];
expect(r.name).toBe('合同会签');
expect(r.key).toBe('contractCosign');
// process id/key 已替换为用户输入(ASCII key),占位符无残留。
expect(r.xml).toContain('id="contractCosign"');
expect(r.xml).toContain('bpmnElement="contractCosign"');
expect(r.xml).not.toContain('__PROCESS_ID__');
expect(r.xml).not.toContain('__PROCESS_NAME__');
// 选中的是会签模板。
expect(r.xml).toContain('multiInstanceLoopCharacteristics');
expect(r.idMap).toEqual({});
});
it('默认模板为空白流程(不含 userTask)', () => {
const { onConfirm } = renderDialog();
fireEvent.change(screen.getByTestId('new-process-name'), { target: { value: '空白' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: 'blankProc' } });
fireEvent.click(screen.getByTestId('new-process-confirm'));
const r = onConfirm.mock.calls[0][0];
expect(r.xml).not.toContain('userTask');
expect(r.xml).toContain('id="blankProc"');
});
it('中文 key → onConfirm.idMap 记录 {中文 key→净化 ASCII id},XML 内 process id 为 ASCII', () => {
const { onConfirm } = renderDialog();
fireEvent.change(screen.getByTestId('new-process-name'), { target: { value: '总包合同交底' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: '总包合同交底' } });
fireEvent.change(screen.getByTestId('new-process-template'), { target: { value: 'single-approval' } });
fireEvent.click(screen.getByTestId('new-process-confirm'));
const r = onConfirm.mock.calls[0][0];
expect(r.key).toBe('总包合同交底');
expect(Object.keys(r.idMap)).toEqual(['总包合同交底']);
const asciiId = r.idMap['总包合同交底'];
expect(asciiId).toMatch(/^[A-Za-z_][A-Za-z0-9_.-]*$/); // ASCII NCName
expect(r.xml).toContain('id="' + asciiId + '"');
expect(r.xml).not.toContain('id="总包合同交底"'); // moddle 拒中文 id
});
it('取消 → onClose,不 onConfirm', () => {
const { onConfirm, onClose } = renderDialog();
fireEvent.click(screen.getByTestId('new-process-cancel'));
expect(onClose).toHaveBeenCalled();
expect(onConfirm).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,113 @@
// 新建流程对话框(T4.1)。
//
// 字段:名称(展示名)/ key(流程标识,允许中文——引擎 process key 既有中文事实)/ 模板下拉。
// 确认时按选中模板 + 用户输入实例化 XML(buildNewProcessXml 替换占位符、按 key 定 ASCII process id
// 并算发布还原 idMap),把结果交父页进入编辑态(父页 importXML,尚未存草稿)。
import { useState } from 'react';
import { Dialog } from '../components/ui';
import { PROCESS_TEMPLATES, getTemplate, buildNewProcessXml } from './templates';
/** 新建结果:交父页 importXML + 首存草稿用(name→草稿名/process name,key→草稿 key,idMap→metaInfo)。 */
export interface NewProcessResult {
name: string;
key: string;
/** 实例化后的 BPMN(占位符已替换,可直接 importXML)。 */
xml: string;
/** 发布还原映射(中文 key 时 {原 key→净化 id},ASCII key 时空)。 */
idMap: Record<string, string>;
}
interface NewProcessDialogProps {
onConfirm: (r: NewProcessResult) => void;
onClose: () => void;
}
export function NewProcessDialog({ onConfirm, onClose }: NewProcessDialogProps) {
const [name, setName] = useState('');
const [key, setKey] = useState('');
const [templateId, setTemplateId] = useState(PROCESS_TEMPLATES[0].id);
const nameOk = name.trim().length > 0;
const keyOk = key.trim().length > 0;
const valid = nameOk && keyOk;
function handleConfirm() {
if (!valid) return;
const tpl = getTemplate(templateId);
if (!tpl) return;
const built = buildNewProcessXml(tpl.xml, name, key);
onConfirm({ name: name.trim(), key: key.trim(), xml: built.xml, idMap: built.idMap });
}
const foot = (
<>
<button className="btn" data-testid="new-process-cancel" onClick={onClose}>
取消
</button>
<button
className="btn btn-primary"
data-testid="new-process-confirm"
onClick={handleConfirm}
disabled={!valid}
>
创建并编辑
</button>
</>
);
return (
<Dialog title="新建流程" width={480} onClose={onClose} foot={foot}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<Field label="流程名称" hint="展示名,可用中文">
<input
data-testid="new-process-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="如:请假审批"
style={inputStyle}
/>
</Field>
<Field label="流程标识(key)" hint="引擎 process key,可用中文;发布后作为流程唯一标识">
<input
data-testid="new-process-key"
value={key}
onChange={(e) => setKey(e.target.value)}
placeholder="如:leaveApply 或 请假审批"
style={inputStyle}
/>
</Field>
<Field label="起始模板">
<select
data-testid="new-process-template"
value={templateId}
onChange={(e) => setTemplateId(e.target.value)}
style={inputStyle}
>
{PROCESS_TEMPLATES.map((t) => (
<option key={t.id} value={t.id}>
{t.label}
</option>
))}
</select>
</Field>
{!valid ? (
<div data-testid="new-process-hint" style={{ fontSize: 12, color: 'var(--text-3)' }}>
请填写流程名称与 key。
</div>
) : null}
</div>
</Dialog>
);
}
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
<label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<span style={{ fontSize: 13, fontWeight: 600 }}>{label}</span>
{children}
{hint ? <span style={{ fontSize: 11, color: 'var(--text-3)' }}>{hint}</span> : null}
</label>
);
}
const inputStyle: React.CSSProperties = { width: '100%', padding: '6px 8px', boxSizing: 'border-box' };

View File

@@ -0,0 +1,139 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn';
vi.mock('../api/processModeler', () => ({
deployModel: vi.fn(),
fetchImpact: vi.fn(),
}));
const toastMock = vi.fn();
vi.mock('../components/ui', async (importOriginal) => ({
...(await importOriginal<typeof import('../components/ui')>()),
toast: (...args: unknown[]) => toastMock(...args),
}));
import { PublishConfirm } from './PublishConfirm';
import { deployModel, fetchImpact } from '../api/processModeler';
const mDeploy = vi.mocked(deployModel);
const mImpact = vi.mocked(fetchImpact);
// 办理人改一处 → diff 应识别「接收交底:办理人变更」。
const EDITED = SYNTHETIC_BPMN.replace(
'&quot;type&quot;:&quot;position&quot;',
'&quot;type&quot;:&quot;user&quot;',
);
function renderConfirm(overrides: Partial<React.ComponentProps<typeof PublishConfirm>> = {}) {
const onClose = vi.fn();
const onPublished = vi.fn();
render(
<PublishConfirm
modelId="MD-1"
openSourceXml={SYNTHETIC_BPMN}
currentXml={EDITED}
processKeyHint="总包合同交底"
onClose={onClose}
onPublished={onPublished}
{...overrides}
/>,
);
return { onClose, onPublished };
}
beforeEach(() => {
toastMock.mockReset();
mDeploy.mockReset().mockResolvedValue({ ok: true, deploymentId: 'D1', processKey: '总包合同交底', newVersion: 4 });
mImpact.mockReset().mockResolvedValue({ found: true, processKey: '总包合同交底', currentVersion: 3, runningInstances: 7 });
});
describe('PublishConfirm', () => {
it('展示影响摘要:流程 key、当前版本→新版本、运行中实例数', async () => {
renderConfirm();
await waitFor(() => expect(mImpact).toHaveBeenCalledWith('MD-1'));
expect(await screen.findByTestId('publish-impact-key')).toHaveTextContent('总包合同交底');
// currentVersion 3 → newVersion 4
expect(screen.getByTestId('publish-impact-version')).toHaveTextContent('v3');
expect(screen.getByTestId('publish-impact-version')).toHaveTextContent('v4');
expect(screen.getByTestId('publish-impact-instances')).toHaveTextContent('7');
// 灰字提示旧版本不受影响
expect(screen.getByTestId('publish-impact-instances')).toHaveTextContent(/不受.*影响/);
});
it('展示节点级 diff(办理人变更)', async () => {
renderConfirm();
await screen.findByTestId('publish-diff-list');
expect(screen.getByTestId('publish-diff-list')).toHaveTextContent('接收交底');
expect(screen.getByTestId('publish-diff-list')).toHaveTextContent('办理人变更');
});
it('无变化时提示未检测到关键属性变化', async () => {
renderConfirm({ currentXml: SYNTHETIC_BPMN });
await screen.findByTestId('publish-diff-empty');
expect(screen.getByTestId('publish-diff-empty')).toHaveTextContent(/未检测到|无/);
});
it('确认发布成功 → deployModel、toast「已发布 v4」、onPublished(4)、关闭', async () => {
const { onClose, onPublished } = renderConfirm();
await screen.findByTestId('publish-confirm-btn');
fireEvent.click(screen.getByTestId('publish-confirm-btn'));
await waitFor(() => expect(mDeploy).toHaveBeenCalledWith('MD-1'));
await waitFor(() => expect(toastMock).toHaveBeenCalledWith(expect.stringContaining('已发布 v4'), 'ok'));
expect(onPublished).toHaveBeenCalledWith(4);
expect(onClose).toHaveBeenCalled();
});
it('422 校验失败 → 按 errors 渲染节点错误清单,不关弹窗、不 onPublished', async () => {
mDeploy.mockResolvedValue({
ok: false,
validationErrors: [
{ activityId: 't_receive', problem: 'activiti-usertask-assignee', defaultDescription: '用户任务缺办理人' },
{ message: 'formKey 不存在于 view_wftemplate' },
],
});
const { onClose, onPublished } = renderConfirm();
await screen.findByTestId('publish-confirm-btn');
fireEvent.click(screen.getByTestId('publish-confirm-btn'));
await waitFor(() => expect(screen.getByTestId('publish-errors')).toBeInTheDocument());
expect(screen.getByTestId('publish-error-0')).toHaveTextContent('t_receive');
expect(screen.getByTestId('publish-error-0')).toHaveTextContent('用户任务缺办理人');
expect(screen.getByTestId('publish-error-1')).toHaveTextContent('formKey 不存在于 view_wftemplate');
expect(onClose).not.toHaveBeenCalled();
expect(onPublished).not.toHaveBeenCalled();
});
it('通用失败(无 errors)→ toast 报错,不关弹窗', async () => {
mDeploy.mockResolvedValue({ ok: false, message: '草稿不存在: MD-1' });
const { onClose } = renderConfirm();
await screen.findByTestId('publish-confirm-btn');
fireEvent.click(screen.getByTestId('publish-confirm-btn'));
await waitFor(() => expect(toastMock).toHaveBeenCalledWith(expect.stringContaining('草稿不存在'), 'err'));
expect(onClose).not.toHaveBeenCalled();
});
it('取消 → onClose,不发布', async () => {
const { onClose } = renderConfirm();
await screen.findByTestId('publish-cancel-btn');
fireEvent.click(screen.getByTestId('publish-cancel-btn'));
expect(onClose).toHaveBeenCalled();
expect(mDeploy).not.toHaveBeenCalled();
});
it('impact 不可用(found:false)→ 降级用 processKeyHint 显示 key,仍可发布', async () => {
mImpact.mockResolvedValue({ found: false });
renderConfirm();
await waitFor(() => expect(mImpact).toHaveBeenCalled());
expect(await screen.findByTestId('publish-impact-key')).toHaveTextContent('总包合同交底');
// 版本不可知时显示占位而非崩溃
expect(screen.getByTestId('publish-impact-version')).toBeInTheDocument();
expect(screen.getByTestId('publish-confirm-btn')).not.toBeDisabled();
});
it('首次发布(currentVersion 0)→ 显示「首次发布 → v1」', async () => {
mImpact.mockResolvedValue({ found: true, processKey: 'new_proc', currentVersion: 0, runningInstances: 0 });
renderConfirm();
await waitFor(() => expect(mImpact).toHaveBeenCalled());
await waitFor(() => expect(screen.getByTestId('publish-impact-version')).toHaveTextContent(/首次发布/));
expect(screen.getByTestId('publish-impact-version')).toHaveTextContent('v1');
});
});

View File

@@ -0,0 +1,188 @@
// 同人确认发布弹窗(T3.3)。
//
// 发布点击后打开本弹窗:并发拉「影响摘要」(fetchImpact) + 本地算「节点级 diff」(diffSummary,
// 打开时源 XML vs 当前 saveXML) → 展示流程 key / 当前版本→新版本 / 运行中实例数(灰字提示旧版本
// 不受影响)/ 办理人·会签等变更节点清单 → 用户确认 → deployModel。
// - 成功:toast「已发布 vN」(用后端返回的真实 newVersion) + onPublished + 关闭。
// - 422 校验失败:按 errors 渲染节点错误清单,**不关弹窗**让用户回去改。
// - 通用失败:toast 报错,不关弹窗。
import { useEffect, useState } from 'react';
import { Dialog } from '../components/ui';
import { toast } from '../components/ui';
import { deployModel, fetchImpact, type DeployImpact, type DeployValidationError } from '../api/processModeler';
import { diffSummary, type NodeDiff } from './diffSummary';
interface PublishConfirmProps {
/** 草稿 modelId(必须已存草稿才可发布)。 */
modelId: string;
/** 打开流程时保存的源 XML(diff 基线)。 */
openSourceXml: string;
/** 当前编辑器 saveXML 结果(diff 对比方;由父页在打开弹窗前算好)。 */
currentXml: string;
/** impact 未回来 / 不可用时兜底显示的流程 key(loadedKey)。 */
processKeyHint?: string;
onClose: () => void;
/** 发布成功回调(带后端返回的真实新版本号)。 */
onPublished: (newVersion?: number) => void;
}
/** 单条校验错误的展示文案:activityId + 问题描述(defaultDescription 优先,回退 problem/message)。 */
function errorText(e: DeployValidationError): string {
const desc = e.defaultDescription || e.problem || e.message || '校验未通过';
return e.activityId ? `[${e.activityId}] ${desc}` : desc;
}
export function PublishConfirm({
modelId,
openSourceXml,
currentXml,
processKeyHint,
onClose,
onPublished,
}: PublishConfirmProps) {
// 节点级 diff 是纯本地同步计算,初始化即得。
const [diff] = useState<NodeDiff[]>(() => diffSummary(openSourceXml, currentXml));
const [impact, setImpact] = useState<DeployImpact | null>(null);
const [impactLoaded, setImpactLoaded] = useState(false);
const [deploying, setDeploying] = useState(false);
const [errors, setErrors] = useState<DeployValidationError[] | null>(null);
useEffect(() => {
let alive = true;
fetchImpact(modelId)
.then((r) => {
if (!alive) return;
setImpact(r);
setImpactLoaded(true);
})
.catch(() => {
if (!alive) return;
setImpact({ found: false });
setImpactLoaded(true);
});
return () => {
alive = false;
};
}, [modelId]);
async function handleConfirm() {
if (deploying) return;
setDeploying(true);
setErrors(null);
try {
const r = await deployModel(modelId);
if (r.ok) {
toast('已发布 v' + (r.newVersion ?? '?'), 'ok');
onPublished(r.newVersion);
onClose();
return;
}
if (r.validationErrors && r.validationErrors.length) {
setErrors(r.validationErrors); // 校验清单 → 不关窗,让用户回去改
} else {
toast(r.message ?? '发布失败', 'err');
}
} finally {
setDeploying(false);
}
}
// M3:发布进行中拦截关闭(遮罩点击 / X 按钮),避免中途关窗留下不确定态。
const guardedClose = () => {
if (!deploying) onClose();
};
const key = impact?.processKey || processKeyHint || '(未知)';
const cur = impact?.currentVersion ?? 0;
const versionText = !impactLoaded
? '版本加载中…'
: impact?.found
? cur > 0
? `v${cur} → v${cur + 1}`
: `首次发布 → v1`
: '(版本信息暂不可用)';
const running = impact?.found ? (impact.runningInstances ?? 0) : undefined;
const foot = (
<>
<button className="btn" data-testid="publish-cancel-btn" onClick={guardedClose} disabled={deploying}>
取消
</button>
<button
className="btn btn-primary"
data-testid="publish-confirm-btn"
onClick={handleConfirm}
disabled={deploying}
>
{deploying ? '发布中…' : '确认发布'}
</button>
</>
);
return (
<Dialog title="发布流程" width={520} onClose={guardedClose} foot={foot}>
<div data-testid="process-modeler-publish-confirm" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{/* 影响摘要 */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13 }}>
<Row label="流程标识(key)">
<code data-testid="publish-impact-key">{key}</code>
</Row>
<Row label="版本">
<span data-testid="publish-impact-version">{versionText}</span>
</Row>
<Row label="运行中实例">
<span data-testid="publish-impact-instances">
{running === undefined ? '—' : running}
<span style={{ color: 'var(--text-3)', marginLeft: 8, fontSize: 12 }}>
(留在旧版本,不受本次发布影响)
</span>
</span>
</Row>
</div>
{/* 节点级变更清单 */}
<div>
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 6 }}>办理人 / 会签等变更节点</div>
{diff.length === 0 ? (
<div data-testid="publish-diff-empty" style={{ fontSize: 12, color: 'var(--text-3)' }}>
未检测到办理人 / 会签 / 表单等关键属性变化(可能仅调整了布局或其他节点)。
</div>
) : (
<ul data-testid="publish-diff-list" style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.7 }}>
{diff.map((d, i) => (
<li key={i} data-testid={`publish-diff-item-${i}`}>
<strong>{d.nodeName}</strong>:{d.changes.join('、')}
</li>
))}
</ul>
)}
</div>
{/* 校验错误清单(422,不关窗) */}
{errors && errors.length ? (
<div data-testid="publish-errors" style={{ border: '1px solid var(--err)', borderRadius: 4, padding: 10 }}>
<div style={{ color: 'var(--err)', fontWeight: 600, fontSize: 13, marginBottom: 6 }}>
校验未通过,请修正后重试:
</div>
<ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: 1.7 }}>
{errors.map((e, i) => (
<li key={i} data-testid={`publish-error-${i}`} style={{ color: 'var(--err)' }}>
{errorText(e)}
</li>
))}
</ul>
</div>
) : null}
</div>
</Dialog>
);
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div style={{ display: 'flex', gap: 8 }}>
<span style={{ flex: '0 0 120px', color: 'var(--text-3)' }}>{label}</span>
<span style={{ flex: 1, minWidth: 0 }}>{children}</span>
</div>
);
}

View File

@@ -0,0 +1,6 @@
// bpmn-js-properties-panel 未随包发布类型声明(无 dist/*.d.ts、无 package.json types 字段)。
// 只声明本项目用到的两个标准模块(severe: 严禁引 Camunda provider,见 ProcessModelerPage)。
declare module 'bpmn-js-properties-panel' {
export const BpmnPropertiesPanelModule: unknown;
export const BpmnPropertiesProviderModule: unknown;
}

View File

@@ -0,0 +1,305 @@
import { describe, it, expect } from 'vitest';
import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn';
import {
parseCandidateExpression,
buildCandidateExpression,
type UserPropertyItem,
} from './candidateExpression';
// ── 真实形态锚定 ────────────────────────────────────────────────────────────
// 不手抄表达式:直接从 T1.1 逐字对照「总包合同交底」写就的 synthetic-full-surface
// fixture 里,运行时抽出 activiti:candidateUsers / activiti:collection 的属性值,
// 做 XML 实体解码(&quot;→")得到 businessObject 属性值层的真实表达式。这样测试
// 与「真实形态的唯一真相」绑定,fixture 改则测试自动跟随,杜绝逐字漂移。
function xmlDecode(s: string): string {
return s
.replace(/&quot;/g, '"')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
}
function extractAttr(attr: string): string {
const m = SYNTHETIC_BPMN.match(new RegExp(attr + '="([^"]*)"'));
if (!m) throw new Error('fixture 缺属性 ' + attr);
return xmlDecode(m[1]);
}
// activiti:candidateUsers,单实例办理人,type=position,content 尾部 4 个 CHAR 补白空格,
// 外层 meta 含非空 taskSuccessService(真实服务钩子)。
const REAL_CANDIDATE = extractAttr('activiti:candidateUsers');
// activiti:collection,多实例(会签)办理人,type=projectRoleType,content 为逗号分隔的
// 11 个布尔维度串,外层 meta 全部为空/false。
const REAL_MULTI = extractAttr('activiti:collection');
describe('parseCandidateExpression — 真实形态解析', () => {
it('解析真实 candidate 表达式(全角【】,识别为 candidate 变体)', () => {
const r = parseCandidateExpression(REAL_CANDIDATE);
expect(r).not.toBeNull();
expect(r!.variant).toBe('candidate');
expect(r!.items).toHaveLength(1);
expect(r!.items[0]).toMatchObject({
type: 'position',
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
});
});
it('content 尾部 CHAR 补白空格原样保留(不 trim)', () => {
const r = parseCandidateExpression(REAL_CANDIDATE);
// 32 位十六进制 id + 4 个尾部空格
expect(r!.items[0].content).toBe('402881343cd50391013d62ccd0c20f7d ');
expect(r!.items[0].content).toHaveLength(36);
});
it('multiInstance 前缀变体 multiInstanceUsersHandler.getUsers 同套解析', () => {
const r = parseCandidateExpression(REAL_MULTI);
expect(r).not.toBeNull();
expect(r!.variant).toBe('multiInstance');
expect(r!.items[0].type).toBe('projectRoleType');
});
it('content 含逗号分隔多值原样保留', () => {
const r = parseCandidateExpression(REAL_MULTI);
expect(r!.items[0].content).toBe(
'true,false,false,false,false,false,false,false,false,false,false',
);
});
});
describe('buildCandidateExpression — 与引擎口径逐字往返', () => {
it('candidate 真实表达式 round-trip 逐字一致(全角【】+前后缀逐字+meta 不丢)', () => {
const r = parseCandidateExpression(REAL_CANDIDATE)!;
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(REAL_CANDIDATE);
});
it('multiInstance 真实表达式 round-trip 逐字一致', () => {
const r = parseCandidateExpression(REAL_MULTI)!;
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(REAL_MULTI);
});
it('外层 meta(messageTemplate/taskSuccessService/isSkip* 等)往返一字不丢', () => {
const r = parseCandidateExpression(REAL_CANDIDATE)!;
// 真实服务钩子:侧板只改 items 时,taskSuccessService 等业务字段必须原样带回,
// 否则重新部署会打掉已部署流程的任务后置服务。
expect(r.meta).toMatchObject({
messageTemplate: '',
taskSuccessService: 'PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS',
isSkipInitiator: false,
isNoUserSkip: false,
isSkipBeforeTask: true,
});
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toContain(
'PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS',
);
});
it('构建输出前缀/后缀逐字对齐 BasePropertiesConverter 常量', () => {
const r = parseCandidateExpression(REAL_CANDIDATE)!;
const built = buildCandidateExpression(r.items, r.variant, r.meta);
expect(built.startsWith("${candidateUsersHandler.getCandidateUsers(execution,'")).toBe(true);
expect(built.endsWith("')}")).toBe(true);
const rm = parseCandidateExpression(REAL_MULTI)!;
const builtM = buildCandidateExpression(rm.items, rm.variant, rm.meta);
expect(builtM.startsWith("${multiInstanceUsersHandler.getUsers(execution,'")).toBe(true);
});
});
describe('各 type 往返不丢字段(真实结构派生:同一真实外壳,仅换 type/content)', () => {
// 用真实 candidate 外壳(REAL_CANDIDATE 的 meta 与 item 键集),仅替换 type/content,
// 覆盖 §0 其余 type。结构逐字来自真实形态,值取真实业务样例。
function reshape(type: string, content: string): string {
const r = parseCandidateExpression(REAL_CANDIDATE)!;
const item: UserPropertyItem = { ...r.items[0], type, content };
return buildCandidateExpression([item], 'candidate', r.meta);
}
it('scriptUser(content=${APPLYUSERS},真实会签办理人形态)往返不丢', () => {
const expr = reshape('scriptUser', '${APPLYUSERS}');
const r = parseCandidateExpression(expr)!;
expect(r.items[0]).toMatchObject({ type: 'scriptUser', content: '${APPLYUSERS}' });
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(expr);
});
it('depart 往返不丢', () => {
const expr = reshape('depart', '402881343cd50391013d62ccd0c20f7d');
const r = parseCandidateExpression(expr)!;
expect(r.items[0].type).toBe('depart');
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(expr);
});
it('beforeTaskLeader 往返不丢', () => {
const expr = reshape('beforeTaskLeader', '');
const r = parseCandidateExpression(expr)!;
expect(r.items[0].type).toBe('beforeTaskLeader');
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(expr);
});
});
describe('isSendMessage 可选字段', () => {
it('含 isSendMessage 往返保留', () => {
const r = parseCandidateExpression(REAL_CANDIDATE)!;
expect(r.items[0].isSendMessage).toBe(false);
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(REAL_CANDIDATE);
});
it('缺 isSendMessage 的旧数据变体:parse 不填充,build 不凭空添加', () => {
// 引擎 BasePropertiesConverter:62-67 对 isCandidate/isSendMail/isSendPhone 无 null 守卫、
// 唯 isSendMessage 有(:63),故存在无 isSendMessage 的合法历史数据。此变体无 meta。
const NO_MSG =
"${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[【\"type\":\"user\",\"content\":\"u1,u2\",\"isCandidate\":true,\"isSendMail\":false,\"isSendPhone\":false】]】')}";
const r = parseCandidateExpression(NO_MSG)!;
expect(r.items[0].isSendMessage).toBeUndefined();
expect('isSendMessage' in r.items[0]).toBe(false);
expect(Object.keys(r.meta)).toHaveLength(0);
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(NO_MSG);
});
});
describe('半角输入兼容 + build 恒全角', () => {
it('半角{}输入可解析,build 输出恒全角【】,回到真实全角形态', () => {
const halfWidth = REAL_CANDIDATE.split('【').join('{').split('】').join('}');
expect(halfWidth).not.toBe(REAL_CANDIDATE); // 确认输入确是半角
const r = parseCandidateExpression(halfWidth);
expect(r).not.toBeNull();
expect(r!.items[0].type).toBe('position');
// build 输出恒全角 → 等于真实全角原文
expect(buildCandidateExpression(r!.items, r!.variant, r!.meta)).toBe(REAL_CANDIDATE);
});
});
describe('非法/空输入返回 null 不抛', () => {
it('undefined → null', () => {
expect(parseCandidateExpression(undefined)).toBeNull();
});
it('空串 → null', () => {
expect(parseCandidateExpression('')).toBeNull();
});
it('缺前缀(非办理人表达式)→ null', () => {
expect(parseCandidateExpression('${someOtherExpr(execution)}')).toBeNull();
});
it('有前缀但内容坏 JSON → null 不抛', () => {
const bad =
"${candidateUsersHandler.getCandidateUsers(execution,'【not a valid json】')}";
expect(() => parseCandidateExpression(bad)).not.toThrow();
expect(parseCandidateExpression(bad)).toBeNull();
});
it('有前缀但缺后缀 → null', () => {
const noSuffix = "${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[]】";
expect(parseCandidateExpression(noSuffix)).toBeNull();
});
it('JSON 合法但无 items 数组 → null', () => {
const noItems =
"${candidateUsersHandler.getCandidateUsers(execution,'【\"foo\":1】')}";
expect(parseCandidateExpression(noItems)).toBeNull();
});
// M-2 形状守卫
it('items 元素非对象(字符串)→ null 不抛', () => {
const bad =
"${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[\"notanobject\"]】')}";
expect(() => parseCandidateExpression(bad)).not.toThrow();
expect(parseCandidateExpression(bad)).toBeNull();
});
it('items 元素 type 非字符串(数字)→ null', () => {
const bad =
"${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[【\"type\":123,\"content\":\"x\"】]】')}";
expect(parseCandidateExpression(bad)).toBeNull();
});
it('items 元素为 null → null', () => {
const bad =
"${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[null]】')}";
expect(parseCandidateExpression(bad)).toBeNull();
});
});
describe('I-1 stringToJson 引号映射(T2.4 接用户输入前必须)', () => {
const CAND_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'";
function body(built: string): string {
return built.slice(CAND_PREFIX.length, built.length - "')}".length);
}
it("content 含 ' 和 \" → build 映射为 ‘/“,值层无裸 '/\"、外层 JUEL 定界符不被截断", () => {
const item: UserPropertyItem = {
type: 'user',
content: `O'Brien "Ann"`,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
};
const built = buildCandidateExpression([item], 'candidate');
// JUEL 单引号字面量安全:整个内容段不得出现裸 ASCII 单引号(否则截断 execution,'...')。
// 注意 " 是 JSON 结构定界符会合法出现于内容段,故只对 ' 断言整段无裸值。
expect(body(built)).not.toContain("'");
// JSON 结构安全:值里的 " 已映射走,build 产物仍是良构表达式,可无损 parse 回来。
const r = parseCandidateExpression(built);
expect(r).not.toBeNull();
const c = r!.items[0].content;
expect(c).toContain('‘'); // O‘Brien
expect(c).toContain('“'); // “Ann“(开闭同映射为左引号,与 stringToJson 逐字一致)
expect(c).not.toContain("'");
expect(c).not.toContain('"');
expect(built.startsWith(CAND_PREFIX)).toBe(true);
expect(built.endsWith("')}")).toBe(true);
});
it('引号映射幂等:build 产物再 parse→build 稳定不变', () => {
const built = buildCandidateExpression(
[{ type: 'user', content: `x'y"z`, isCandidate: true, isSendMail: false, isSendPhone: false }],
'candidate',
);
const r = parseCandidateExpression(built)!;
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(built);
});
it('meta 字符串叶子(messageTemplate)同样应用引号映射', () => {
const built = buildCandidateExpression(
[{ type: 'user', content: 'u1', isCandidate: true, isSendMail: false, isSendPhone: false }],
'candidate',
{ messageTemplate: `it's` },
);
expect(built).toContain('it‘s');
expect(body(built)).not.toContain("'");
});
});
describe('I-2 半角 content 变体(scriptUser ${users})——运行期等价', () => {
// 语料实测 20 条:content 用半角 ${users}(非 stringToJson 产物)。parse 保留原值,
// build 把结构性 {} 连同 content 里半角 {} 一并规范化为全角——非字节逐字,但引擎运行期
// 对整串全局 【→{ 还原后完全等价。
const HALF =
"${multiInstanceUsersHandler.getUsers(execution,'【\"items\":[【\"type\":\"scriptUser\",\"content\":\"${users}\",\"isCandidate\":true,\"isSendMail\":false,\"isSendPhone\":false】]】')}";
// 镜像引擎 CandidateUsersHandler:54 的全局字面替换
const engineRestore = (s: string): string => s.split('【').join('{').split('】').join('}');
it('半角 content 可解析,原值保留', () => {
const r = parseCandidateExpression(HALF)!;
expect(r.items[0]).toMatchObject({ type: 'scriptUser', content: '${users}' });
});
it('build 输出恒全角(content 半角{}被规范化),但引擎全局替换后与原文等价', () => {
const r = parseCandidateExpression(HALF)!;
const built = buildCandidateExpression(r.items, r.variant, r.meta);
expect(built).toContain('$【users】'); // 非字节逐字
expect(engineRestore(built)).toBe(engineRestore(HALF)); // 运行期等价
});
});
describe('M-1 item 未知键透传(不静默丢未来扩展键,与 meta 全量保留对称)', () => {
it('未知 item 键排在已知键之后,往返逐字不丢', () => {
const WITH_UNKNOWN =
"${candidateUsersHandler.getCandidateUsers(execution,'【\"items\":[【\"type\":\"user\",\"content\":\"u1\",\"isCandidate\":true,\"isSendMail\":false,\"isSendPhone\":false,\"futureFlag\":true】]】')}";
const r = parseCandidateExpression(WITH_UNKNOWN)!;
expect((r.items[0] as Record<string, unknown>).futureFlag).toBe(true);
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(WITH_UNKNOWN);
});
});

View File

@@ -0,0 +1,152 @@
// 办理人 / 会签(多实例)办理人表达式的编解码器(纯函数)。
//
// 处理的是 bpmn-js businessObject **属性值层**的表达式(XML 实体已解码:真引号、全角【】),
// 不是 XML 源码层(&quot;)。引擎侧唯一真相:
// - 前后缀常量逐字对齐 com.dsasp.server.wf.bean.BasePropertiesConverter:34-35
// CANDIDATESERVICE / MULTIINSTANCESERVICE(见下 PREFIX 常量)。
// - 存储态的对象花括号一律写作**全角【】**(方括号 [] 半角),运行期由
// CandidateUsersHandler:54 以 `.replace("【","{").replace("】","}")`(全局字面替换)
// 还原为合法 JSON 再交 Jackson 解析。本编解码器 build 输出恒全角、parse 兼容全角/半角。
// - 外层对象结构:{"items":[{...}],"messageTemplate","taskSuccessService",
// "isSkipInitiator","isNoUserSkip","isSkipBeforeTask"}(语料实测 meta 键集有多种子集)。
// 引擎运行期候选人解析(convertToUserProperties)只读 items,但 taskSuccessService 等是
// 任务后置服务钩子等运行期业务字段——侧板只改 items 时必须原样带回(meta),否则重新部署
// 会打掉这些字段。
// - 字符串叶子值(content/messageTemplate 等)的转义逐字对齐原版 stringToJson
// (BasePropertiesConverter.java:235-280):`'`→‘(U+2018)、`"`→“(U+201C)、
// `{`→【、`}`→】,反斜杠与控制字符走标准 JSON 转义。build 对新值应用此契约,防用户输入
// 含 `'`(截断外层 JUEL 单引号字面量)或 `"`(截断内层 JSON)导致部署后表达式解析即断。
//
// 逐字往返口径(全量 1512 流 4794 条真实表达式实测,见 tools/codec-corpus-sweep.mjs):
// - 4774/4794 build(parse(x))===x 逐字一致;`‘`/`“`/`\/` 在语料 0 命中,故新增引号
// 转义对存量表达式为 no-op(合法存量叶子值不含裸 ' / ",否则会截断 JUEL/JSON)。
// - 余 20 条 content 用**半角** `${users}`(scriptUser 会签变体,非 stringToJson 产物):
// parse 保留原值,build 把结构性 {} 连同 content 里的半角 {} 一并规范化为全角【】。此非字节
// 逐字,但**运行期等价**——引擎 :54 对整串做全局 【→{ 还原,`$【users】` 复原为 `${users}`。
// - content 里的逗号分隔多值与 CHAR 尾部补白空格原样保留。
const CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'";
const MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'";
const SUFFIX = "')}";
export type CandidateVariant = 'candidate' | 'multiInstance';
/** 单个办理人项。字段名逐字对齐 BasePropertiesConverter 常量(:21-27)。 */
export interface UserPropertyItem {
type: string;
content: string;
isCandidate?: boolean;
isSendMail?: boolean;
isSendPhone?: boolean;
isSendMessage?: boolean;
}
export interface ParsedCandidateExpression {
items: UserPropertyItem[];
variant: CandidateVariant;
/** items 之外的外层字段(messageTemplate/taskSuccessService/isSkip* 等),原样保留以逐字往返。 */
meta: Record<string, unknown>;
}
/** item 的规范键序;未知键在其后按原序透传(与 meta 全量保留对称,不静默丢未来扩展键)。 */
const KNOWN_ITEM_KEYS = ['type', 'content', 'isCandidate', 'isSendMail', 'isSendPhone', 'isSendMessage'];
const KNOWN_ITEM_KEY_SET = new Set(KNOWN_ITEM_KEYS);
function fullToHalf(s: string): string {
return s.split('【').join('{').split('】').join('}');
}
function halfToFull(s: string): string {
return s.split('{').join('【').split('}').join('】');
}
/**
* 字符串叶子值转义,逐字对齐原版 stringToJson 里 JSON.stringify **未覆盖**的两处值级映射:
* `'`→‘、`"`→“。(反斜杠/控制字符由 JSON.stringify 覆盖;`{`/`}`→【/】由 halfToFull 覆盖。)
* 对合法存量叶子值(不含裸 ' / ")为 no-op,故不破坏逐字往返;仅对面板新输入生效。
*/
function escapeLeaf(v: string): string {
return v.split("'").join('‘').split('"').join('“');
}
/** 按规范键序重建 item:已知键在前(存在才输出,不凭空增删),未知键按原序透传。 */
function reorderItem(src: Record<string, unknown>): Record<string, unknown> {
const o: Record<string, unknown> = {};
for (const k of KNOWN_ITEM_KEYS) {
if (src[k] !== undefined) o[k] = src[k];
}
for (const k of Object.keys(src)) {
if (!KNOWN_ITEM_KEY_SET.has(k) && src[k] !== undefined) o[k] = src[k];
}
return o;
}
/**
* 解析办理人/会签表达式。识别 candidate / multiInstance 两种前缀,内容段全角【】→{} 后 JSON.parse。
* 非办理人表达式、缺后缀、坏 JSON、无 items 数组、items 元素非对象或 type 非字符串、
* undefined/空串一律返回 null 不抛。
*/
export function parseCandidateExpression(
expr: string | undefined | null,
): ParsedCandidateExpression | null {
if (typeof expr !== 'string' || expr.length === 0) return null;
let variant: CandidateVariant;
let prefix: string;
if (expr.startsWith(CANDIDATE_PREFIX)) {
variant = 'candidate';
prefix = CANDIDATE_PREFIX;
} else if (expr.startsWith(MULTI_PREFIX)) {
variant = 'multiInstance';
prefix = MULTI_PREFIX;
} else {
return null;
}
if (!expr.endsWith(SUFFIX)) return null;
const content = expr.slice(prefix.length, expr.length - SUFFIX.length);
let obj: unknown;
try {
obj = JSON.parse(fullToHalf(content));
} catch {
return null;
}
if (obj === null || typeof obj !== 'object') return null;
const record = obj as Record<string, unknown>;
if (!Array.isArray(record.items)) return null;
// 形状守卫:元素必须是普通对象且 type 为字符串,否则整体返 null(对齐「非法返 null 不抛」)。
for (const el of record.items) {
if (el === null || typeof el !== 'object' || Array.isArray(el)) return null;
if (typeof (el as Record<string, unknown>).type !== 'string') return null;
}
const items = (record.items as Record<string, unknown>[]).map(
reorderItem,
) as unknown as UserPropertyItem[];
const meta: Record<string, unknown> = { ...record };
delete meta.items;
return { items, variant, meta };
}
/**
* 构建办理人/会签表达式:重建外层对象 {items, ...meta} → JSON.stringify(紧凑无空白,replacer
* 对字符串叶子应用 stringToJson 引号映射)→ 结构性 {} 换成全角【】(方括号保持半角)→ 套前后缀。
* round-trip 与真实表达式逐字一致(半角 content 变体除外,见文件头运行期等价说明)。
*/
export function buildCandidateExpression(
items: UserPropertyItem[],
variant: CandidateVariant,
meta?: Record<string, unknown>,
): string {
const prefix = variant === 'multiInstance' ? MULTI_PREFIX : CANDIDATE_PREFIX;
const outer = {
items: items.map((it) => reorderItem(it as unknown as Record<string, unknown>)),
...(meta ?? {}),
};
const json = JSON.stringify(outer, (_key, value) =>
typeof value === 'string' ? escapeLeaf(value) : value,
);
return prefix + halfToFull(json) + SUFFIX;
}

View File

@@ -0,0 +1,194 @@
import { describe, it, expect } from 'vitest';
import { SYNTHETIC_BPMN } from './moddle/fixtures/synthetic-full-surface.bpmn';
import { diffSummary } from './diffSummary';
import { buildCandidateExpression, type UserPropertyItem } from './candidateExpression';
// 节点级 diff(P2):以「总包合同交底」逐字对照的 synthetic fixture 为基线,
// 按 userTask id 对齐比较四类属性变化(办理人/指派/formKey/会签)。改动用**定点字符串替换**
// 从基线派生,确保只动被测那一处(其余节点无 diff),与真实存储态绑定不手抄表达式。
//
// fixture 关键锚点(见 synthetic-full-surface.bpmn):
// - t_write(编写交底):activiti:assignee=${assignee} + 多实例会签(collection type=projectRoleType,
// completionCondition 全票 ==1),无 candidateUsers。
// - t_receive(接收交底):activiti:candidateUsers(type=position)+ activiti:formKey=3eee7644-…,无会签。
/** 从基线移除 t_write 的会签块(多实例 loop)。 */
const NO_COSIGN = SYNTHETIC_BPMN.replace(
/<multiInstanceLoopCharacteristics[\s\S]*?<\/multiInstanceLoopCharacteristics>/,
'',
);
describe('diffSummary — 节点级四类属性 diff', () => {
it('完全相同 → 无变化节点', () => {
expect(diffSummary(SYNTHETIC_BPMN, SYNTHETIC_BPMN)).toEqual([]);
});
it('办理人变更(candidateUsers items type position→user)→ 只标接收交底「办理人变更」', () => {
const edited = SYNTHETIC_BPMN.replace(
'&quot;type&quot;:&quot;position&quot;',
'&quot;type&quot;:&quot;user&quot;',
);
const diff = diffSummary(SYNTHETIC_BPMN, edited);
expect(diff).toEqual([{ nodeName: '接收交底', changes: ['办理人变更'] }]);
});
it('指派人变更(activiti:assignee ${assignee}→${boss})→ 只标编写交底「指派人变更」', () => {
const edited = SYNTHETIC_BPMN.replace(
'activiti:assignee="${assignee}"',
'activiti:assignee="${boss}"',
);
const diff = diffSummary(SYNTHETIC_BPMN, edited);
expect(diff).toEqual([{ nodeName: '编写交底', changes: ['指派人变更'] }]);
});
it('formKey 变更 → 只标接收交底「表单变更」', () => {
const edited = SYNTHETIC_BPMN.replace(
'activiti:formKey="3eee7644-f51d-4755-9abb-aca7f4dd8516"',
'activiti:formKey="99999999-0000-0000-0000-000000000000"',
);
const diff = diffSummary(SYNTHETIC_BPMN, edited);
expect(diff).toEqual([{ nodeName: '接收交底', changes: ['表单变更'] }]);
});
it('会签开启(源无会签→当前有)→ 编写交底「会签开启」', () => {
const diff = diffSummary(NO_COSIGN, SYNTHETIC_BPMN);
expect(diff).toEqual([{ nodeName: '编写交底', changes: ['会签开启'] }]);
});
it('会签关闭(源有会签→当前无)→ 编写交底「会签关闭」', () => {
const diff = diffSummary(SYNTHETIC_BPMN, NO_COSIGN);
expect(diff).toEqual([{ nodeName: '编写交底', changes: ['会签关闭'] }]);
});
it('会签人员变更(collection items type projectRoleType→scriptUser)→ 编写交底「会签人员变更」', () => {
const edited = SYNTHETIC_BPMN.replace(
'&quot;type&quot;:&quot;projectRoleType&quot;',
'&quot;type&quot;:&quot;scriptUser&quot;',
);
const diff = diffSummary(SYNTHETIC_BPMN, edited);
expect(diff).toEqual([{ nodeName: '编写交底', changes: ['会签人员变更'] }]);
});
it('会签完成条件变更(全票 ==1 → 过半 >0.5)→ 编写交底「会签完成条件变更」', () => {
const edited = SYNTHETIC_BPMN.replace(
'/nrOfInstances==1}',
'/nrOfInstances>0.5}',
);
const diff = diffSummary(SYNTHETIC_BPMN, edited);
expect(diff).toEqual([{ nodeName: '编写交底', changes: ['会签完成条件变更'] }]);
});
it('一个节点多类同时变更 → changes 汇总多项', () => {
let edited = SYNTHETIC_BPMN.replace(
'activiti:formKey="3eee7644-f51d-4755-9abb-aca7f4dd8516"',
'activiti:formKey="99999999-0000-0000-0000-000000000000"',
);
edited = edited.replace(
'&quot;type&quot;:&quot;position&quot;',
'&quot;type&quot;:&quot;user&quot;',
);
const diff = diffSummary(SYNTHETIC_BPMN, edited);
expect(diff).toHaveLength(1);
expect(diff[0].nodeName).toBe('接收交底');
expect(diff[0].changes).toEqual(expect.arrayContaining(['办理人变更', '表单变更']));
expect(diff[0].changes).toHaveLength(2);
});
it('新增用户任务 → 标「新增用户任务」', () => {
const added = SYNTHETIC_BPMN.replace(
'<endEvent id="end_1"></endEvent>',
'<userTask id="t_new" name="新审批"></userTask><endEvent id="end_1"></endEvent>',
);
const diff = diffSummary(SYNTHETIC_BPMN, added);
expect(diff).toEqual([{ nodeName: '新审批', changes: ['新增用户任务'] }]);
});
it('删除用户任务 → 标「删除用户任务」', () => {
// 从当前移除 t_receive(用其带 boundaryEvent 的完整块不便,改用 name 回退验证:直接删 t_write 块)。
const removed = SYNTHETIC_BPMN.replace(
/<userTask id="t_write"[\s\S]*?<\/userTask>/,
'',
);
const diff = diffSummary(SYNTHETIC_BPMN, removed);
expect(diff).toEqual([{ nodeName: '编写交底', changes: ['删除用户任务'] }]);
});
it('无 name 的节点回退用 id 作 nodeName', () => {
const added = SYNTHETIC_BPMN.replace(
'<endEvent id="end_1"></endEvent>',
'<userTask id="t_noname"></userTask><endEvent id="end_1"></endEvent>',
);
const diff = diffSummary(SYNTHETIC_BPMN, added);
expect(diff).toEqual([{ nodeName: 't_noname', changes: ['新增用户任务'] }]);
});
it('坏 XML(任一侧解析失败)→ 返回空数组不抛', () => {
expect(() => diffSummary('<not xml', SYNTHETIC_BPMN)).not.toThrow();
expect(diffSummary('<not', SYNTHETIC_BPMN)).toEqual([]);
expect(diffSummary(SYNTHETIC_BPMN, '<<<')).toEqual([]);
});
});
// I3-①:跨命名空间对齐——源用默认命名空间(存量存储态),当前用 bpmn: 前缀(bpmn-js saveXML 输出)。
// diff 必须按命名空间 URI(而非字面前缀)对齐 userTask,否则「改存量→发布」全链的 diff 会漏。
describe('diffSummary — 跨命名空间(默认 ns vs bpmn: 前缀)对齐', () => {
const item = (type: string, content: string): UserPropertyItem => ({
type,
content,
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
});
// 办理人表达式属性值需把 " 转义成 &quot; 才能进 XML 属性。
const candAttr = (items: UserPropertyItem[]) =>
buildCandidateExpression(items, 'candidate').replace(/"/g, '&quot;');
// 默认命名空间(无前缀),activiti: 前缀属性——模拟存量源。
const defaultNs = (items: UserPropertyItem[]) =>
`<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" targetNamespace="x">
<process id="p1" name="流程" isExecutable="true">
<userTask id="t1" name="任务甲" activiti:candidateUsers="${candAttr(items)}"></userTask>
</process>
</definitions>`;
// bpmn: 前缀(BPMN 元素全部带前缀,namespaceURI 不变)——模拟 bpmn-js saveXML 输出。
const bpmnPrefixed = (items: UserPropertyItem[]) =>
`<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" targetNamespace="x">
<bpmn:process id="p1" name="流程" isExecutable="true">
<bpmn:userTask id="t1" name="任务甲" activiti:candidateUsers="${candAttr(items)}"></bpmn:userTask>
</bpmn:process>
</bpmn:definitions>`;
const ITEMS_A = [item('user', 'u1')];
const ITEMS_B = [item('depart', 'd1')];
it('前缀不同、语义相同 → 无变化(前缀本身不误报)', () => {
expect(diffSummary(defaultNs(ITEMS_A), bpmnPrefixed(ITEMS_A))).toEqual([]);
});
it('前缀不同、办理人改了 → 按 URI 对齐命中「办理人变更」', () => {
expect(diffSummary(defaultNs(ITEMS_A), bpmnPrefixed(ITEMS_B))).toEqual([
{ nodeName: '任务甲', changes: ['办理人变更'] },
]);
});
});
// M1:会签人员 content 的全角/半角宽度变体不应误报(parse 已 fullToHalf,diff 再兜一层 normWidth)。
describe('diffSummary — 人员 content 宽度变体不误报(M1)', () => {
it('collection content 仅全角【】↔半角{} 之差 → 无「会签人员变更」', () => {
// 两版仅 collection 人员 content 的括号宽度不同:${x}(半角)vs $【x】(全角),运行期等价。
const withHalf = SYNTHETIC_BPMN.replace(
'&quot;content&quot;:&quot;true,false,false,false,false,false,false,false,false,false,false&quot;',
'&quot;content&quot;:&quot;${x}&quot;',
);
const withFull = SYNTHETIC_BPMN.replace(
'&quot;content&quot;:&quot;true,false,false,false,false,false,false,false,false,false,false&quot;',
'&quot;content&quot;:&quot;$【x】&quot;',
);
expect(withHalf).not.toBe(withFull); // 两版确有字面差异
expect(diffSummary(withHalf, withFull)).toEqual([]);
});
});

175
src/modeler/diffSummary.ts Normal file
View File

@@ -0,0 +1,175 @@
// 发布影响摘要——节点级 diff(计划 §0.5 P2)。
//
// 纯函数:以打开流程时保存的**源 XML**(openSourceXml)对比当前编辑器 saveXML 的**当前 XML**
// (currentXml),按 userTask id 对齐,比较四类会真正影响运行期办理/派任的属性变化:
// ① 办理人 activiti:candidateUsers(用 candidateExpression.parse 比 items,忽略仅格式差异)
// ② 指派人 activiti:assignee
// ③ 表单 activiti:formKey
// ④ 会签 多实例(有无切换 / collection 人员 / completionCondition 完成条件)
// 以及新增 / 删除的用户任务。只返回有变化的节点。不做通用图 diff(YAGNI)。
//
// 实现要点:
// - 用 DOMParser 命名空间感知解析(getElementsByTagNameNS / getAttributeNS 按 URI 匹配),
// 故 bpmn-js 导出的 `bpmn:` 前缀 vs 存量源的默认命名空间不影响对齐(前缀无关,只认 URI)。
// - 办理人/会签人员的比较走 candidateExpression codec:解析出 items 做规范化签名对比,
// bpmn-js round-trip 产生的纯格式差异(半角{}→全角【】等)不误报为变更。
// - 防御性:任一侧 XML 解析失败 → 返回 [](影响摘要是补充信息,版本/实例数才是权威)。
import { parseCandidateExpression } from './candidateExpression';
const BPMN_NS = 'http://www.omg.org/spec/BPMN/20100524/MODEL';
const ACTIVITI_NS = 'http://activiti.org/bpmn';
const FLOWABLE_NS = 'http://flowable.org/bpmn';
/** 单个变化节点:节点名(name 回退 id)+ 变化类别中文清单。 */
export interface NodeDiff {
nodeName: string;
changes: string[];
}
/** activiti/flowable 扩展属性读值(命名空间 URI 匹配 + 限定名回退),缺失返 undefined。 */
function extAttr(el: Element, local: string): string | undefined {
const tryNs = (ns: string): string | undefined => {
const v = el.getAttributeNS(ns, local);
return v == null ? undefined : v;
};
let v = tryNs(ACTIVITI_NS);
if (v === undefined) v = tryNs(FLOWABLE_NS);
if (v === undefined) {
const q = el.getAttribute('activiti:' + local) ?? el.getAttribute('flowable:' + local);
v = q == null ? undefined : q;
}
return v;
}
/** 解析 XML → Document;坏 XML(parsererror / 无根 / 抛异常)返 null。 */
function parseDoc(xml: string): Document | null {
if (typeof xml !== 'string' || xml.length === 0) return null;
try {
const doc = new DOMParser().parseFromString(xml, 'application/xml');
if (doc.getElementsByTagName('parsererror').length > 0) return null;
if (!doc.documentElement) return null;
return doc;
} catch {
return null;
}
}
/** 文档内所有 userTask(按命名空间 URI),id→元素,保留文档顺序。 */
function userTasks(doc: Document): Map<string, Element> {
const map = new Map<string, Element>();
const list = doc.getElementsByTagNameNS(BPMN_NS, 'userTask');
for (let i = 0; i < list.length; i++) {
const el = list[i];
const id = el.getAttribute('id');
if (id) map.set(id, el);
}
return map;
}
function nameOf(el: Element, id: string): string {
const name = el.getAttribute('name');
return name && name.trim() ? name : id;
}
/** userTask 的多实例(会签)loop 元素,无则 null。 */
function miOf(el: Element): Element | null {
const list = el.getElementsByTagNameNS(BPMN_NS, 'multiInstanceLoopCharacteristics');
return list.length ? list[0] : null;
}
/** 多实例完成条件 body(折叠全部空白后比较,避免 bpmn-js 重排空白误报变更),无则空串。 */
function completionBody(mi: Element): string {
const list = mi.getElementsByTagNameNS(BPMN_NS, 'completionCondition');
return list.length ? (list[0].textContent ?? '').replace(/\s+/g, '') : '';
}
/** 全角【】↔半角{} 归一(与 codec parse 的 fullToHalf 同口径),防人员 content 宽度变体误报。 */
function normWidth(s: string): string {
return s.split('【').join('{').split('】').join('}');
}
/**
* 办理人/会签人员表达式的**语义签名**:能解析则取 items 的规范化投影(type/content/四通知开关),
* 忽略 meta 与格式差异;不能解析(非标准表达式)则回退原串比较;空则空串。
* 两侧签名不同即视为人员配置变化。
*/
function exprSig(raw: string | undefined): string {
if (!raw) return '';
const parsed = parseCandidateExpression(raw);
if (!parsed) return 'RAW:' + normWidth(raw);
return JSON.stringify(
parsed.items.map((i) => [
i.type,
normWidth(i.content),
!!i.isCandidate,
!!i.isSendMail,
!!i.isSendPhone,
!!i.isSendMessage,
]),
);
}
/** 比较同一 id 的两个 userTask,返回变化类别清单(无变化返 [])。 */
function nodeChanges(a: Element, b: Element): string[] {
const changes: string[] = [];
if (exprSig(extAttr(a, 'candidateUsers')) !== exprSig(extAttr(b, 'candidateUsers'))) {
changes.push('办理人变更');
}
if ((extAttr(a, 'assignee') ?? '') !== (extAttr(b, 'assignee') ?? '')) {
changes.push('指派人变更');
}
if ((extAttr(a, 'formKey') ?? '') !== (extAttr(b, 'formKey') ?? '')) {
changes.push('表单变更');
}
const miA = miOf(a);
const miB = miOf(b);
if (miA && !miB) {
changes.push('会签关闭');
} else if (!miA && miB) {
changes.push('会签开启');
} else if (miA && miB) {
if (exprSig(extAttr(miA, 'collection')) !== exprSig(extAttr(miB, 'collection'))) {
changes.push('会签人员变更');
}
if (completionBody(miA) !== completionBody(miB)) {
changes.push('会签完成条件变更');
}
}
return changes;
}
/**
* 节点级发布影响 diff。openSourceXml=打开时源,currentXml=当前 saveXML。
* 返回有变化的用户任务清单(含新增/删除);任一侧坏 XML → []。
*/
export function diffSummary(openSourceXml: string, currentXml: string): NodeDiff[] {
const srcDoc = parseDoc(openSourceXml);
const curDoc = parseDoc(currentXml);
if (!srcDoc || !curDoc) return [];
const src = userTasks(srcDoc);
const cur = userTasks(curDoc);
const out: NodeDiff[] = [];
// 当前文档顺序:匹配节点比属性;仅当前有 = 新增。
cur.forEach((curEl, id) => {
const srcEl = src.get(id);
if (!srcEl) {
out.push({ nodeName: nameOf(curEl, id), changes: ['新增用户任务'] });
return;
}
const changes = nodeChanges(srcEl, curEl);
if (changes.length) out.push({ nodeName: nameOf(curEl, id), changes });
});
// 仅源有 = 删除。
src.forEach((srcEl, id) => {
if (!cur.has(id)) out.push({ nodeName: nameOf(srcEl, id), changes: ['删除用户任务'] });
});
return out;
}

View File

@@ -0,0 +1,178 @@
{
"name": "Activiti",
"uri": "http://activiti.org/bpmn",
"prefix": "activiti",
"xml": { "tagAlias": "lowerCase" },
"associations": [],
"types": [
{
"name": "ActivityExtension",
"isAbstract": true,
"extends": ["bpmn:Activity"],
"properties": [
{ "name": "exclusive", "isAttr": true, "type": "String" },
{ "name": "async", "isAttr": true, "type": "String" },
{ "name": "asyncBefore", "isAttr": true, "type": "String" },
{ "name": "asyncAfter", "isAttr": true, "type": "String" }
]
},
{
"name": "UserTaskExtension",
"isAbstract": true,
"extends": ["bpmn:UserTask"],
"properties": [
{ "name": "assignee", "isAttr": true, "type": "String" },
{ "name": "candidateUsers", "isAttr": true, "type": "String" },
{ "name": "candidateGroups", "isAttr": true, "type": "String" },
{ "name": "formKey", "isAttr": true, "type": "String" },
{ "name": "dueDate", "isAttr": true, "type": "String" },
{ "name": "priority", "isAttr": true, "type": "String" },
{ "name": "category", "isAttr": true, "type": "String" },
{ "name": "skipExpression", "isAttr": true, "type": "String" }
]
},
{
"name": "StartEventExtension",
"isAbstract": true,
"extends": ["bpmn:StartEvent"],
"properties": [
{ "name": "formKey", "isAttr": true, "type": "String" },
{ "name": "initiator", "isAttr": true, "type": "String" }
]
},
{
"name": "ProcessExtension",
"isAbstract": true,
"extends": ["bpmn:Process"],
"properties": [
{ "name": "candidateStarterUsers", "isAttr": true, "type": "String" },
{ "name": "candidateStarterGroups", "isAttr": true, "type": "String" },
{ "name": "versionTag", "isAttr": true, "type": "String" },
{ "name": "historyTimeToLive", "isAttr": true, "type": "String" }
]
},
{
"name": "ScriptTaskExtension",
"isAbstract": true,
"extends": ["bpmn:ScriptTask"],
"properties": [
{ "name": "autoStoreVariables", "isAttr": true, "type": "String" },
{ "name": "resultVariable", "isAttr": true, "type": "String" }
]
},
{
"name": "ServiceTaskExtension",
"isAbstract": true,
"extends": ["bpmn:ServiceTask", "bpmn:SendTask", "bpmn:BusinessRuleTask"],
"properties": [
{ "name": "class", "isAttr": true, "type": "String" },
{ "name": "expression", "isAttr": true, "type": "String" },
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
{ "name": "resultVariableName", "isAttr": true, "type": "String" },
{ "name": "type", "isAttr": true, "type": "String" }
]
},
{
"name": "CallActivityExtension",
"isAbstract": true,
"extends": ["bpmn:CallActivity"],
"properties": [
{ "name": "calledElementBinding", "isAttr": true, "type": "String" },
{ "name": "calledElementVersion", "isAttr": true, "type": "String" }
]
},
{
"name": "MultiInstanceExtension",
"isAbstract": true,
"extends": ["bpmn:MultiInstanceLoopCharacteristics"],
"properties": [
{ "name": "collection", "isAttr": true, "type": "String" },
{ "name": "elementVariable", "isAttr": true, "type": "String" }
]
},
{
"name": "TaskListener",
"superClass": ["Element"],
"meta": { "allowedIn": ["bpmn:UserTask"] },
"properties": [
{ "name": "event", "isAttr": true, "type": "String" },
{ "name": "class", "isAttr": true, "type": "String" },
{ "name": "expression", "isAttr": true, "type": "String" },
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
{ "name": "fields", "type": "Field", "isMany": true }
]
},
{
"name": "ExecutionListener",
"superClass": ["Element"],
"meta": { "allowedIn": ["*"] },
"properties": [
{ "name": "event", "isAttr": true, "type": "String" },
{ "name": "class", "isAttr": true, "type": "String" },
{ "name": "expression", "isAttr": true, "type": "String" },
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
{ "name": "fields", "type": "Field", "isMany": true }
]
},
{
"name": "Field",
"superClass": ["Element"],
"meta": { "allowedIn": ["*"] },
"properties": [
{ "name": "name", "isAttr": true, "type": "String" },
{ "name": "stringValue", "isAttr": true, "type": "String" },
{ "name": "string", "type": "String" },
{ "name": "expression", "type": "String" }
]
},
{
"name": "FormProperty",
"superClass": ["Element"],
"meta": { "allowedIn": ["*"] },
"properties": [
{ "name": "id", "isAttr": true, "type": "String" },
{ "name": "name", "isAttr": true, "type": "String" },
{ "name": "type", "isAttr": true, "type": "String" },
{ "name": "required", "isAttr": true, "type": "String" },
{ "name": "readable", "isAttr": true, "type": "String" },
{ "name": "writable", "isAttr": true, "type": "String" },
{ "name": "variable", "isAttr": true, "type": "String" },
{ "name": "expression", "isAttr": true, "type": "String" },
{ "name": "datePattern", "isAttr": true, "type": "String" },
{ "name": "default", "isAttr": true, "type": "String" },
{ "name": "value", "isAttr": true, "type": "String" },
{ "name": "values", "type": "Value", "isMany": true }
]
},
{
"name": "Value",
"superClass": ["Element"],
"properties": [
{ "name": "id", "isAttr": true, "type": "String" },
{ "name": "name", "isAttr": true, "type": "String" }
]
},
{
"name": "In",
"superClass": ["Element"],
"meta": { "allowedIn": ["*"] },
"properties": [
{ "name": "source", "isAttr": true, "type": "String" },
{ "name": "sourceExpression", "isAttr": true, "type": "String" },
{ "name": "target", "isAttr": true, "type": "String" },
{ "name": "variables", "isAttr": true, "type": "String" }
]
},
{
"name": "Out",
"superClass": ["Element"],
"meta": { "allowedIn": ["*"] },
"properties": [
{ "name": "source", "isAttr": true, "type": "String" },
{ "name": "sourceExpression", "isAttr": true, "type": "String" },
{ "name": "target", "isAttr": true, "type": "String" },
{ "name": "variables", "isAttr": true, "type": "String" }
]
}
]
}

3
src/modeler/moddle/bpmn-moddle.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
// bpmn-moddle 8.x 无自带类型声明(TS7016)。最小 ambient 声明消编辑器诊断;
// 运行时行为以 fidelity.test.ts 的 round-trip 断言为准。
declare module 'bpmn-moddle';

View File

@@ -0,0 +1,211 @@
import { describe, it, expect } from 'vitest';
import BpmnModdle from 'bpmn-moddle';
import activiti from './activiti.json';
import flowable from './flowable.json';
import { SYNTHETIC_BPMN } from './fixtures/synthetic-full-surface.bpmn';
// §0 实测扩展面(本地 eip4 库 5433):11 属性 + 5 元素 + 命名空间 activiti/flowable。
const CORPUS_ATTRS = [
'formKey', 'candidateUsers', 'exclusive', 'assignee', 'collection',
'elementVariable', 'candidateGroups', 'autoStoreVariables', 'initiator', 'dueDate',
];
const CORPUS_ELEMENTS = ['taskListener', 'formProperty', 'value', 'field', 'string'];
// 接收交底 userTask 的 candidateUsers 表达式反转义后的真实态:真引号 + 全角【】+ content 尾 4 空格。
const EXPECTED_CANDIDATE_USERS =
`\${candidateUsersHandler.getCandidateUsers(execution,'【"items":[【"type":"position",` +
`"content":"402881343cd50391013d62ccd0c20f7d ","isCandidate":true,"isSendMail":false,` +
`"isSendPhone":false,"isSendMessage":false】],"messageTemplate":"",` +
`"taskSuccessService":"PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS",` +
`"isSkipInitiator":false,"isNoUserSkip":false,"isSkipBeforeTask":true】')}`;
// moddle 跨包同名 extends 属性冲突(activiti:exclusive vs flowable:exclusive 均挂 bpmn:Activity),
// 两包同载会丢元素。真实语料每文档只用一个命名空间(1509 activiti / 3 flowable,不混用),
// 故按命名空间隔离加载。见文末「moddle 约束」测试。
const newActiviti = () => new BpmnModdle({ activiti });
const newFlowable = () => new BpmnModdle({ flowable });
function proc(root: any): any {
return root.rootElements.find((e: any) => e.$type === 'bpmn:Process');
}
function findById(root: any, id: string): any {
return (proc(root).flowElements ?? []).find((e: any) => e.id === id);
}
function warns(res: any, re: RegExp): any[] {
return (res.warnings ?? []).filter((w: any) => re.test(String(w?.message ?? w)));
}
describe('activiti/flowable moddle 描述符 — 语料覆盖', () => {
it('§0 全部实测 activiti 属性/元素在 activiti.json 有声明', () => {
// 大小写不敏感:自定义元素类型名遵循 activiti/camunda 惯例=PascalCase(TaskListener/Field/…),
// xml.tagAlias:lowerCase 令 XML 元素名仍小写(<activiti:taskListener>)。见 serialization.test.ts。
const declared = JSON.stringify(activiti).toLowerCase();
[...CORPUS_ATTRS, ...CORPUS_ELEMENTS].forEach((n) =>
expect(declared, `activiti:${n} 未声明`).toContain(`"${n.toLowerCase()}"`));
});
it('flowable.json 声明命名空间与 flowable:assignee', () => {
expect(flowable.uri).toBe('http://flowable.org/bpmn');
expect(flowable.prefix).toBe('flowable');
expect(JSON.stringify(flowable)).toContain('"assignee"');
});
});
describe('activiti round-trip 零丢失(合成 fixture 覆盖全扩展面)', () => {
it('fromXML 干净:无 activiti 未知警告、无未解析引用(=描述符完整)', async () => {
const res = await newActiviti().fromXML(SYNTHETIC_BPMN);
expect(warns(res, /activiti|unparsable|unresolved/i)).toHaveLength(0);
// 全部流元素(含 userTask/scriptTask/boundaryEvent)都解析出来
const types = proc(res.rootElement).flowElements.map((e: any) => e.$type);
expect(types).toContain('bpmn:UserTask');
expect(types).toContain('bpmn:ScriptTask');
expect(types).toContain('bpmn:BoundaryEvent');
});
it('candidateUsers 被识别为 typed 属性且逐字保留(全角【】+ 尾空格 + JSON 原样)', async () => {
const { rootElement } = await newActiviti().fromXML(SYNTHETIC_BPMN);
const receive = findById(rootElement, 't_receive');
// 逐字保真:解析值 byte-exact 等于原文。
expect(receive.get('activiti:candidateUsers')).toBe(EXPECTED_CANDIDATE_USERS);
// typed 化的直接证据:值走声明属性、未回落 lax $attrs。
// (moddle .get() 对未声明属性也会回落 $attrs 返原值,故单看 .get() 不足以证明 typed 化。)
expect(receive.$attrs?.['activiti:candidateUsers']).toBeUndefined();
});
it('多实例 collection/elementVariable/completionCondition 解析为结构化模型', async () => {
const { rootElement } = await newActiviti().fromXML(SYNTHETIC_BPMN);
const write = findById(rootElement, 't_write');
const mi = write.loopCharacteristics;
expect(mi.$type).toBe('bpmn:MultiInstanceLoopCharacteristics');
expect(mi.get('activiti:elementVariable')).toBe('assignee');
expect(mi.get('activiti:collection')).toContain('multiInstanceUsersHandler.getUsers');
expect(mi.get('activiti:collection')).toContain('【"items":[');
expect(mi.completionCondition.body).toBe('${nrOfCompletedInstances/nrOfInstances==1}');
});
it('taskListener + field + string + formProperty/value 解析为结构化模型', async () => {
const { rootElement } = await newActiviti().fromXML(SYNTHETIC_BPMN);
const receive = findById(rootElement, 't_receive');
const listener = receive.extensionElements.values.find(
(v: any) => v.$type === 'activiti:TaskListener',
);
expect(listener.event).toBe('complete');
expect(listener.class).toBe('com.dsasp.server.wf.user.listener.TaskCompleteListener');
expect(listener.fields[0].name).toBe('mailTemplate');
expect(listener.fields[0].string).toBe('审批完成通知');
const formProp = receive.extensionElements.values.find(
(v: any) => v.$type === 'activiti:FormProperty',
);
expect(formProp.id).toBe('fp_remark');
expect(formProp.values.map((v: any) => v.name)).toEqual(['同意', '驳回']);
});
it('import→export 关键片段逐字保留(实体稳定:全角【】/中文 name/formKey/监听器/多实例/timer/条件)', async () => {
const moddle = newActiviti();
const { rootElement } = await moddle.fromXML(SYNTHETIC_BPMN);
const { xml } = await moddle.toXML(rootElement, { format: false });
// 中文 name(moddle 对 name 无 NCName 限制,与 id 不同)+ DI 引用(净化后的 ASCII id)
expect(xml).toContain('name="总包合同交底"');
expect(xml).toContain('bpmnElement="Proc_zbht"');
// 办理人 / 会签 handler 前缀(引号被 moddle 序列化为数字实体 &#39;/&#34;,故断言只取到括号前)
expect(xml).toContain('getCandidateUsers(execution,');
expect(xml).toContain('multiInstanceUsersHandler.getUsers');
// 全角【】原样出现在序列化字节里(不被转义)——JSON 包裹符零丢失的直接证据
expect(xml).toContain('【');
expect(xml).toContain('】');
// 内嵌 JSON 值原样(标识符不受实体化影响)+ content 尾 4 空格(CHAR 补白)
expect(xml).toContain('projectRoleType');
expect(xml).toContain('PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS');
expect(xml).toContain('402881343cd50391013d62ccd0c20f7d ');
// 扩展属性
expect(xml).toContain('activiti:formKey="2098ce21-400b-4425-9c22-63e350974b98"');
expect(xml).toContain('activiti:formKey="3eee7644-f51d-4755-9abb-aca7f4dd8516"');
expect(xml).toContain('activiti:exclusive="false"');
expect(xml).toContain('activiti:elementVariable="assignee"');
expect(xml).toContain('activiti:initiator="applyuser"');
expect(xml).toContain('activiti:autoStoreVariables="false"');
// 扩展元素
expect(xml).toContain('activiti:taskListener');
expect(xml).toContain('com.dsasp.server.wf.user.listener.TaskCompleteListener');
expect(xml).toContain('审批完成通知');
expect(xml).toContain('activiti:formProperty');
expect(xml).toContain('activiti:value');
// BPMN 特性:boundary+timer / conditionExpression
expect(xml).toContain('timerEventDefinition');
expect(xml).toContain('PT8H');
expect(xml).toContain('isSave==true');
expect(xml).toContain('completionCondition');
});
it('二次 round-trip 稳定:export 结果再 import,candidateUsers 仍逐字一致', async () => {
const m1 = newActiviti();
const first = await m1.fromXML(SYNTHETIC_BPMN);
const { xml } = await m1.toXML(first.rootElement, { format: true });
const m2 = newActiviti();
const { rootElement } = await m2.fromXML(xml);
expect(findById(rootElement, 't_receive').get('activiti:candidateUsers')).toBe(
EXPECTED_CANDIDATE_USERS,
);
});
});
describe('flowable 命名空间 round-trip', () => {
const FLOWABLE_BPMN = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:flowable="http://flowable.org/bpmn" targetNamespace="t">
<process id="p_flowable" isExecutable="true">
<userTask id="u1" name="审批" flowable:assignee="\${assignee}" flowable:formKey="k1"></userTask>
</process>
</definitions>`;
it('flowable-only 加载时 flowable:assignee typed 化并 round-trip 零丢失', async () => {
const moddle = newFlowable();
const res = await moddle.fromXML(FLOWABLE_BPMN);
const u1 = findById(res.rootElement, 'u1');
expect(u1.get('flowable:assignee')).toBe('${assignee}');
const { xml } = await moddle.toXML(res.rootElement, { format: false });
expect(xml).toContain('flowable:assignee="${assignee}"');
expect(warns(res, /flowable/i)).toHaveLength(0);
});
it('activiti-only 加载时 flowable 属性经 lax $attrs 零丢失往返(Task 1.5 Modeler 单载 activiti 的依据)', async () => {
const moddle = newActiviti();
const res = await moddle.fromXML(FLOWABLE_BPMN);
const u1 = findById(res.rootElement, 'u1');
expect(u1.$attrs['flowable:assignee']).toBe('${assignee}');
const { xml } = await moddle.toXML(res.rootElement, { format: false });
expect(xml).toContain('flowable:assignee="${assignee}"');
expect(xml).toContain('flowable:formKey="k1"');
expect(warns(res, /flowable|unparsable/i)).toHaveLength(0);
});
});
describe('moddle 约束(勘探实证,固化为回归事实)', () => {
it('D7 依据:moddle-xml 拒绝中文 id(illegal ID),故进 moddle 前必须 BpmnIdSanitizer 净化', async () => {
const CN_ID = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" targetNamespace="t">
<process id="总包合同交底" name="总包合同交底" isExecutable="true">
<startEvent id="s1"></startEvent>
</process>
</definitions>`;
const res = await newActiviti().fromXML(CN_ID);
// 中文 id 的 process 被判 unparsable → 整个 process 丢失(rootElements 无 bpmn:Process)
expect(warns(res, /illegal ID|总包合同交底/)).not.toHaveLength(0);
expect((res.rootElement.rootElements ?? []).some((e: any) => e.$type === 'bpmn:Process')).toBe(false);
});
it('Task 1.5 约束:activiti+flowable 双包同载会因跨包同名 extends 属性冲突丢弃 userTask', async () => {
const BOTH = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" xmlns:flowable="http://flowable.org/bpmn" targetNamespace="t">
<process id="p1" isExecutable="true">
<userTask id="u1" name="审批" activiti:exclusive="false" activiti:assignee="\${a}"></userTask>
</process>
</definitions>`;
const both = new BpmnModdle({ activiti, flowable });
const res = await both.fromXML(BOTH);
expect(warns(res, /redefines|already defined/)).not.toHaveLength(0);
// userTask 被判 unparsable 而丢失 —— 证明不可两包同载,必须按命名空间隔离(见本文件 newActiviti/newFlowable)
const types = proc(res.rootElement).flowElements?.map((e: any) => e.$type) ?? [];
expect(types).not.toContain('bpmn:UserTask');
});
});

View File

@@ -0,0 +1,103 @@
// 合成 fixture:复刻 §0 实测全扩展面 + 中文 name + 全角【】办理人 JSON。
//
// 形态逐字对照真实流程「总包合同交底」(本地 eip4 库 5433 抽取):
// - candidateUsers / multiInstance collection 的内嵌 JSON 用**全角【】**包裹对象,
// 方括号 [] 是半角,引号在 XML 属性里以 &quot; 转义(本文件即真实存储态)。
// - content 尾部的 4 个空格(CHAR 补白)原样保留,用于验证空白零丢失。
// - taskListener/formProperty/field/string、boundaryEvent+timer、conditionExpression、
// startEvent initiator/formKey、scriptTask autoStoreVariables、完整 BPMNDiagram DI。
//
// ⚠️ 关键约束(本任务勘探实证):bpmn-moddle / moddle-xml 会**拒绝中文 id**(报
// `illegal ID`,id 必须是 XSD NCName 的 ASCII 子集),故 moddle 层永远只处理**净化后的
// ASCII id**。真实流程的中文 id(=流程 key,如「总包合同交底」)由 BpmnIdSanitizer(Task 1.3)
// 在进 moddle 前净化、发布时还原——那才是 D7 id 可逆净化存在的根本原因。因此本 fixture 的
// process/节点 id 用 ASCII(模拟净化后态),中文只保留在 name 里(moddle 对 name 无限制)。
// 另有独立测试固化「moddle 拒绝中文 id」这一事实。
//
// 注意:TS 模板字符串里所有引擎表达式的 `${` 均转义为 `\${`,避免被当作插值。
// 不提交任何客户真实 BPMN(P6),仅此合成件覆盖全部扩展语义。
export const SYNTHETIC_BPMN = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/processdef">
<process id="Proc_zbht" name="总包合同交底" isExecutable="true" activiti:candidateStarterGroups="all">
<startEvent id="start_1" name="发起" activiti:initiator="applyuser" activiti:formKey="7c9b-start-form"></startEvent>
<userTask id="t_write" name="编写交底" activiti:exclusive="false" activiti:assignee="\${assignee}" activiti:formKey="2098ce21-400b-4425-9c22-63e350974b98" activiti:dueDate="\${dueDate}" activiti:candidateGroups="managers">
<multiInstanceLoopCharacteristics isSequential="false" activiti:collection="\${multiInstanceUsersHandler.getUsers(execution,'【&quot;items&quot;:[【&quot;type&quot;:&quot;projectRoleType&quot;,&quot;content&quot;:&quot;true,false,false,false,false,false,false,false,false,false,false&quot;,&quot;isCandidate&quot;:true,&quot;isSendMail&quot;:false,&quot;isSendPhone&quot;:false,&quot;isSendMessage&quot;:false】],&quot;messageTemplate&quot;:&quot;&quot;,&quot;taskSuccessService&quot;:&quot;&quot;,&quot;isSkipInitiator&quot;:false,&quot;isNoUserSkip&quot;:false,&quot;isSkipBeforeTask&quot;:false】')}" activiti:elementVariable="assignee">
<completionCondition>\${nrOfCompletedInstances/nrOfInstances==1}</completionCondition>
</multiInstanceLoopCharacteristics>
</userTask>
<userTask id="t_receive" name="接收交底" activiti:exclusive="false" activiti:candidateUsers="\${candidateUsersHandler.getCandidateUsers(execution,'【&quot;items&quot;:[【&quot;type&quot;:&quot;position&quot;,&quot;content&quot;:&quot;402881343cd50391013d62ccd0c20f7d &quot;,&quot;isCandidate&quot;:true,&quot;isSendMail&quot;:false,&quot;isSendPhone&quot;:false,&quot;isSendMessage&quot;:false】],&quot;messageTemplate&quot;:&quot;&quot;,&quot;taskSuccessService&quot;:&quot;PM_CONTRACTUALREGISTER_UPDATEPROJECTSTATUS&quot;,&quot;isSkipInitiator&quot;:false,&quot;isNoUserSkip&quot;:false,&quot;isSkipBeforeTask&quot;:true】')}" activiti:formKey="3eee7644-f51d-4755-9abb-aca7f4dd8516">
<extensionElements>
<activiti:taskListener event="complete" class="com.dsasp.server.wf.user.listener.TaskCompleteListener">
<activiti:field name="mailTemplate">
<activiti:string>审批完成通知</activiti:string>
</activiti:field>
</activiti:taskListener>
<activiti:formProperty id="fp_remark" name="备注" type="string" required="true">
<activiti:value id="v1" name="同意"></activiti:value>
<activiti:value id="v2" name="驳回"></activiti:value>
</activiti:formProperty>
</extensionElements>
</userTask>
<boundaryEvent id="boundary_1" name="超时" attachedToRef="t_receive" cancelActivity="true">
<timerEventDefinition>
<timeDuration>PT8H</timeDuration>
</timerEventDefinition>
</boundaryEvent>
<scriptTask id="script_1" name="自动登记" scriptFormat="juel" activiti:autoStoreVariables="false">
<script>\${execution.setVariable('done', true)}</script>
</scriptTask>
<endEvent id="end_1"></endEvent>
<sequenceFlow id="f1" sourceRef="start_1" targetRef="t_write"></sequenceFlow>
<sequenceFlow id="f2" sourceRef="t_write" targetRef="t_receive"></sequenceFlow>
<sequenceFlow id="f3" sourceRef="t_receive" targetRef="script_1">
<conditionExpression xsi:type="tFormalExpression">\${isSave==true}</conditionExpression>
</sequenceFlow>
<sequenceFlow id="f4" sourceRef="script_1" targetRef="end_1"></sequenceFlow>
<sequenceFlow id="f5" sourceRef="boundary_1" targetRef="end_1"></sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_Proc_zbht">
<bpmndi:BPMNPlane bpmnElement="Proc_zbht" id="BPMNPlane_Proc_zbht">
<bpmndi:BPMNShape bpmnElement="start_1" id="BPMNShape_start_1">
<omgdc:Bounds height="30.0" width="30.0" x="99.0" y="179.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="t_write" id="BPMNShape_t_write">
<omgdc:Bounds height="80.0" width="100.0" x="174.0" y="154.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="t_receive" id="BPMNShape_t_receive">
<omgdc:Bounds height="80.0" width="100.0" x="375.0" y="154.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="boundary_1" id="BPMNShape_boundary_1">
<omgdc:Bounds height="31.0" width="31.0" x="410.0" y="216.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="script_1" id="BPMNShape_script_1">
<omgdc:Bounds height="80.0" width="100.0" x="576.0" y="154.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="end_1" id="BPMNShape_end_1">
<omgdc:Bounds height="28.0" width="28.0" x="756.0" y="180.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="f1" id="BPMNEdge_f1">
<omgdi:waypoint x="129.0" y="194.0"></omgdi:waypoint>
<omgdi:waypoint x="174.0" y="194.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="f2" id="BPMNEdge_f2">
<omgdi:waypoint x="274.0" y="194.0"></omgdi:waypoint>
<omgdi:waypoint x="375.0" y="194.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="f3" id="BPMNEdge_f3">
<omgdi:waypoint x="475.0" y="194.0"></omgdi:waypoint>
<omgdi:waypoint x="576.0" y="194.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="f4" id="BPMNEdge_f4">
<omgdi:waypoint x="676.0" y="194.0"></omgdi:waypoint>
<omgdi:waypoint x="756.0" y="194.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="f5" id="BPMNEdge_f5">
<omgdi:waypoint x="425.0" y="247.0"></omgdi:waypoint>
<omgdi:waypoint x="425.0" y="320.0"></omgdi:waypoint>
<omgdi:waypoint x="770.0" y="320.0"></omgdi:waypoint>
<omgdi:waypoint x="770.0" y="208.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>`;

View File

@@ -0,0 +1,91 @@
{
"name": "Flowable",
"uri": "http://flowable.org/bpmn",
"prefix": "flowable",
"xml": { "tagAlias": "lowerCase" },
"associations": [],
"types": [
{
"name": "ActivityExtension",
"isAbstract": true,
"extends": ["bpmn:Activity"],
"properties": [
{ "name": "exclusive", "isAttr": true, "type": "String" },
{ "name": "async", "isAttr": true, "type": "String" }
]
},
{
"name": "UserTaskExtension",
"isAbstract": true,
"extends": ["bpmn:UserTask"],
"properties": [
{ "name": "assignee", "isAttr": true, "type": "String" },
{ "name": "candidateUsers", "isAttr": true, "type": "String" },
{ "name": "candidateGroups", "isAttr": true, "type": "String" },
{ "name": "formKey", "isAttr": true, "type": "String" },
{ "name": "dueDate", "isAttr": true, "type": "String" }
]
},
{
"name": "StartEventExtension",
"isAbstract": true,
"extends": ["bpmn:StartEvent"],
"properties": [
{ "name": "formKey", "isAttr": true, "type": "String" },
{ "name": "initiator", "isAttr": true, "type": "String" }
]
},
{
"name": "MultiInstanceExtension",
"isAbstract": true,
"extends": ["bpmn:MultiInstanceLoopCharacteristics"],
"properties": [
{ "name": "collection", "isAttr": true, "type": "String" },
{ "name": "elementVariable", "isAttr": true, "type": "String" }
]
},
{
"name": "TaskListener",
"superClass": ["Element"],
"meta": { "allowedIn": ["bpmn:UserTask"] },
"properties": [
{ "name": "event", "isAttr": true, "type": "String" },
{ "name": "class", "isAttr": true, "type": "String" },
{ "name": "expression", "isAttr": true, "type": "String" },
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
{ "name": "fields", "type": "Field", "isMany": true }
]
},
{
"name": "Field",
"superClass": ["Element"],
"meta": { "allowedIn": ["*"] },
"properties": [
{ "name": "name", "isAttr": true, "type": "String" },
{ "name": "stringValue", "isAttr": true, "type": "String" },
{ "name": "string", "type": "String" },
{ "name": "expression", "type": "String" }
]
},
{
"name": "FormProperty",
"superClass": ["Element"],
"meta": { "allowedIn": ["*"] },
"properties": [
{ "name": "id", "isAttr": true, "type": "String" },
{ "name": "name", "isAttr": true, "type": "String" },
{ "name": "type", "isAttr": true, "type": "String" },
{ "name": "required", "isAttr": true, "type": "String" },
{ "name": "values", "type": "Value", "isMany": true }
]
},
{
"name": "Value",
"superClass": ["Element"],
"properties": [
{ "name": "id", "isAttr": true, "type": "String" },
{ "name": "name", "isAttr": true, "type": "String" }
]
}
]
}

View File

@@ -0,0 +1,95 @@
import { describe, it, expect } from 'vitest';
import BpmnModdle from 'bpmn-moddle';
import activiti from './activiti.json';
import flowable from './flowable.json';
import { SYNTHETIC_BPMN } from './fixtures/synthetic-full-surface.bpmn';
// 元素名大小写回归(CRITICAL:断部署)。
//
// 根因:moddle 把「被扩展类型」的合并描述符 $pkg 设为**最后一个 trait 的包**
// (moddle index.esm.js:577)。activiti.json 用 `extends` 给 bpmn:Process/UserTask/StartEvent…
// 加属性 → 这些基础类型的 $pkg 变成 activiti 包;moddle-xml 序列化时按 $pkg 的
// `xml.tagAlias` 决定元素名首字母是否小写。bpmn 包有 `tagAlias:"lowerCase"`(Process→process),
// activiti 包若无此声明 → 写出 PascalCase `<Process>/<UserTask>/<StartEvent>`。
// **Flowable 大小写敏感**:`<Process>` 不被识别为流程 → 部署时 ProcessValidator 报
// flowable-process-definition-not-executable(看到 0 个可执行流程),部署完全失败。
//
// 为何 T1.1/T1.2 没抓到:它们只断言 activiti 扩展属性/元素多重集,**从不断言基础 BPMN 元素名的
// 大小写**;且 fromXML→toXML 与 create 都走同一 moddle-xml Writer,均产 PascalCase(本文件实证)。
//
// 为何用 BpmnModdle 而非真 Modeler:bpmn-js Modeler 依赖 diagram-js 的 SVG 布局(getBBox 等),
// jsdom 跑不动;而 Modeler.saveXML 在 moddle 层就是 `moddle.toXML(定义树)`,diagram-js 从不改元素名。
// 故 `new BpmnModdle({activiti})` 的 fromXML→toXML / create→toXML 忠实复现 saveXML 的元素命名路径。
const BASE_TYPES: Array<[create: string, lower: string, pascal: string]> = [
['bpmn:Process', 'process', 'Process'],
['bpmn:UserTask', 'userTask', 'UserTask'],
['bpmn:StartEvent', 'startEvent', 'StartEvent'],
['bpmn:ScriptTask', 'scriptTask', 'ScriptTask'],
['bpmn:EndEvent', 'endEvent', 'EndEvent'],
['bpmn:SequenceFlow', 'sequenceFlow', 'SequenceFlow'],
['bpmn:BoundaryEvent', 'boundaryEvent', 'BoundaryEvent'],
];
/** 元素名正则(可选 bpmn: 前缀 + 精确 token + 分隔符),大小写敏感。 */
const openTag = (name: string) => new RegExp('<(bpmn:)?' + name + '[\\s/>]');
describe('moddle 序列化——基础 BPMN 元素名小写(断部署回归)', () => {
it('打开存量再导出(fromXML→toXML):基础元素名全小写,无 PascalCase(Flowable 可识别)', async () => {
const moddle = new BpmnModdle({ activiti });
const { rootElement } = await moddle.fromXML(SYNTHETIC_BPMN);
const { xml } = await moddle.toXML(rootElement, { format: true });
for (const [, lower, pascal] of BASE_TYPES) {
expect(xml, `应含小写 <${lower}>`).toMatch(openTag(lower));
expect(xml, `不应含 PascalCase <${pascal}>(Flowable 大小写敏感)`).not.toMatch(openTag(pascal));
}
});
it('isExecutable 症状:process 元素小写且保留 isExecutable="true"', async () => {
const moddle = new BpmnModdle({ activiti });
const { rootElement } = await moddle.fromXML(SYNTHETIC_BPMN);
const { xml } = await moddle.toXML(rootElement, { format: true });
// 真正的 bug 是 <Process> 不被识别("isExecutable 丢失"只是症状)——断言 process 小写即可。
expect(xml).toMatch(/<(bpmn:)?process[\s][^>]*isExecutable="true"/);
expect(xml).not.toMatch(openTag('Process'));
});
it('新建元素(create→toXML):新建流程各基础节点名也全小写', async () => {
const moddle = new BpmnModdle({ activiti });
const defs = moddle.create('bpmn:Definitions', { targetNamespace: 'http://x' });
const proc = moddle.create('bpmn:Process', { id: 'p1', isExecutable: true });
const start = moddle.create('bpmn:StartEvent', { id: 's1' });
const ut = moddle.create('bpmn:UserTask', {
id: 't1',
'activiti:candidateUsers': 'X',
'activiti:formKey': 'K',
});
const flow = moddle.create('bpmn:SequenceFlow', { id: 'f1', sourceRef: start, targetRef: ut });
const end = moddle.create('bpmn:EndEvent', { id: 'e1' });
proc.flowElements = [start, ut, flow, end];
defs.rootElements = [proc];
const { xml } = await moddle.toXML(defs, { format: true });
for (const [, lower, pascal] of BASE_TYPES.filter(([, l]) => l !== 'scriptTask' && l !== 'boundaryEvent')) {
expect(xml, `应含小写 <${lower}>`).toMatch(openTag(lower));
expect(xml, `不应含 PascalCase <${pascal}>`).not.toMatch(openTag(pascal));
}
// 扩展属性 / 自定义元素不受影响
expect(xml).toContain('activiti:candidateUsers="X"');
expect(xml).toContain('activiti:formKey="K"');
});
it('flowable 描述符隔离同样小写(虽不进 Modeler,防同类潜伏 bug)', async () => {
const moddle = new BpmnModdle({ flowable });
const defs = moddle.create('bpmn:Definitions', { targetNamespace: 'http://x' });
const proc = moddle.create('bpmn:Process', { id: 'p1', isExecutable: true });
const ut = moddle.create('bpmn:UserTask', { id: 't1', 'flowable:assignee': 'u1' });
proc.flowElements = [ut];
defs.rootElements = [proc];
const { xml } = await moddle.toXML(defs, { format: true });
expect(xml).toMatch(openTag('process'));
expect(xml).toMatch(openTag('userTask'));
expect(xml).not.toMatch(openTag('Process'));
expect(xml).not.toMatch(openTag('UserTask'));
expect(xml).toContain('flowable:assignee="u1"');
});
});

View File

@@ -0,0 +1,35 @@
// 新建流程模板——空白(1 startEvent + 1 endEvent,供纯手绘)。
//
// ⚠️ CRITICAL(阶段 3 教训):元素名一律**全小写**(<definitions><process><startEvent/>…);
// 缺 isExecutable="true" 会被 Flowable ProcessValidator 拒(看到 0 个可执行流程);缺完整
// BPMNDiagram DI 则画布空白。故模板源字符串即含小写元素名 + isExecutable + 完整 DI。
//
// 占位符(由 templates/index.ts 的 buildNewProcessXml 实例化替换):
// __PROCESS_ID__ —— 进 <process id> 与 <bpmndi:BPMNPlane bpmnElement>(决定 process key)。
// 本身是合法 NCName(`_`+大写字母+`_`),故未替换的原模板也能过 moddle 校验。
// __PROCESS_NAME__ —— 进 <process name>(展示名,name 属性对 NCName 无限制)。
//
// 空白模板 start→end 直连即最小可部署流程,用户在流上插入节点或另起手绘。
export const BLANK_BPMN = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/processdef">
<process id="__PROCESS_ID__" name="__PROCESS_NAME__" isExecutable="true">
<startEvent id="start_1" name="开始"></startEvent>
<endEvent id="end_1" name="结束"></endEvent>
<sequenceFlow id="flow_1" sourceRef="start_1" targetRef="end_1"></sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane bpmnElement="__PROCESS_ID__" id="BPMNPlane_1">
<bpmndi:BPMNShape bpmnElement="start_1" id="BPMNShape_start_1">
<omgdc:Bounds height="30.0" width="30.0" x="180.0" y="85.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="end_1" id="BPMNShape_end_1">
<omgdc:Bounds height="28.0" width="28.0" x="320.0" y="86.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="flow_1" id="BPMNEdge_flow_1">
<omgdi:waypoint x="210.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="320.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>`;

View File

@@ -0,0 +1,46 @@
// 新建流程模板——会签(start → 多实例 userTask → end)。
//
// userTask 挂 multiInstanceLoopCharacteristics(并行):
// - activiti:collection = multiInstance 表达式(multiInstanceUsersHandler.getUsers,全角【】+
// items 一项 type:user;逐字对齐 candidateExpression codec 的 'multiInstance' 变体 build 输出)。
// - activiti:elementVariable="assignee" + userTask activiti:assignee="${assignee}":每个实例把
// 集合元素绑到 assignee 变量再据此派任(对照真实会签流「总包合同交底」结构)。
// - completionCondition ${nrOfCompletedInstances/nrOfInstances==1}(全票通过,对齐侧板 all 预设)。
//
// 约束同其余模板:全小写元素名 + isExecutable + 完整 DI + 占位符。
export const COSIGN_BPMN = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/processdef">
<process id="__PROCESS_ID__" name="__PROCESS_NAME__" isExecutable="true">
<startEvent id="start_1" name="发起"></startEvent>
<userTask id="task_cosign" name="会签审批" activiti:exclusive="false" activiti:assignee="\${assignee}">
<multiInstanceLoopCharacteristics isSequential="false" activiti:collection="\${multiInstanceUsersHandler.getUsers(execution,'【&quot;items&quot;:[【&quot;type&quot;:&quot;user&quot;,&quot;content&quot;:&quot;&quot;,&quot;isCandidate&quot;:true,&quot;isSendMail&quot;:false,&quot;isSendPhone&quot;:false,&quot;isSendMessage&quot;:false】]】')}" activiti:elementVariable="assignee">
<completionCondition>\${nrOfCompletedInstances/nrOfInstances==1}</completionCondition>
</multiInstanceLoopCharacteristics>
</userTask>
<endEvent id="end_1" name="结束"></endEvent>
<sequenceFlow id="flow_1" sourceRef="start_1" targetRef="task_cosign"></sequenceFlow>
<sequenceFlow id="flow_2" sourceRef="task_cosign" targetRef="end_1"></sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane bpmnElement="__PROCESS_ID__" id="BPMNPlane_1">
<bpmndi:BPMNShape bpmnElement="start_1" id="BPMNShape_start_1">
<omgdc:Bounds height="30.0" width="30.0" x="150.0" y="85.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="task_cosign" id="BPMNShape_task_cosign">
<omgdc:Bounds height="80.0" width="100.0" x="250.0" y="60.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="end_1" id="BPMNShape_end_1">
<omgdc:Bounds height="28.0" width="28.0" x="430.0" y="86.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="flow_1" id="BPMNEdge_flow_1">
<omgdi:waypoint x="180.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="250.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="flow_2" id="BPMNEdge_flow_2">
<omgdi:waypoint x="350.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="430.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>`;

View File

@@ -0,0 +1,95 @@
// 新建流程模板库 + 实例化助手(T4.1 §0.5 P3)。
//
// 四个模板以真实流程结构为骨架抽形;模板源用占位符 __PROCESS_ID__ / __PROCESS_NAME__,
// 由 {@link buildNewProcessXml} 按用户输入的 key/名称实例化替换。
//
// 🔑 中文 key 与 moddle 的冲突:bpmn-moddle 拒非 ASCII 的 process id(NCName 校验),故进
// Modeler 的 XML 里 <process id> 必须是 ASCII。方案对齐存量改造链(后端 BpmnIdSanitizer + 发布
// restore):
// - key 是合法 ASCII NCName → 直接用作 process id,idMap 空(发布即以该 key 部署,无需还原)。
// - key 含中文等非法字符 → process id 用稳定 ASCII(与 BpmnIdSanitizer 同哈希方案),
// idMap={原中文 key → 净化 id};发布时后端按 metaInfo.eip4IdMap restore 回中文 key(process
// key = XML <process id>,见 ProcessModelController.deploy)。
import { BLANK_BPMN } from './blank.bpmn';
import { SINGLE_APPROVAL_BPMN } from './single-approval.bpmn';
import { TWO_LEVEL_BPMN } from './two-level.bpmn';
import { COSIGN_BPMN } from './cosign.bpmn';
export interface ProcessTemplate {
id: string;
label: string;
/** 未实例化的模板源(含 __PROCESS_ID__/__PROCESS_NAME__ 占位符)。 */
xml: string;
}
export const PROCESS_TEMPLATES: ProcessTemplate[] = [
{ id: 'blank', label: '空白流程', xml: BLANK_BPMN },
{ id: 'single-approval', label: '单人审批', xml: SINGLE_APPROVAL_BPMN },
{ id: 'two-level', label: '两级审批', xml: TWO_LEVEL_BPMN },
{ id: 'cosign', label: '会签', xml: COSIGN_BPMN },
];
export function getTemplate(id: string): ProcessTemplate | undefined {
return PROCESS_TEMPLATES.find((t) => t.id === id);
}
/** ASCII NCName 判定(逐字对齐后端 BpmnIdSanitizer.isValidNcName:首字符字母/下划线,余加数字/-/.)。 */
export function isAsciiNcName(s: string): boolean {
return /^[A-Za-z_][A-Za-z0-9_.\-]*$/.test(s);
}
/** Java String.hashCode(int 溢出语义),与后端 BpmnIdSanitizer 的净化 id 生成一致。 */
function javaHashCode(s: string): number {
let h = 0;
for (let i = 0; i < s.length; i++) {
h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;
}
return h;
}
/**
* 中文等非法 key → 稳定 ASCII id:`n` + hex(hashCode & 0x7fffffff)(对齐 BpmnIdSanitizer.sanitize)。
*
* M-1 前提:新建模板里**只有 process key 一个**可能非 ASCII 的 id,节点 id(start_1/task_* 等)全 ASCII,
* 故文档内不会出现两个非法 id → 净化 id 碰撞不可达,无需后端的 -2/-3 去重。若将来允许中文节点 id,
* 须对齐 BpmnIdSanitizer 的碰撞序号方案(否则两 id 哈希相同会串引用、restore 还原错)。
*/
function sanitizedId(key: string): string {
return 'n' + (javaHashCode(key) & 0x7fffffff).toString(16);
}
/** 属性值 XML 转义(name 进 name="…",须转义 & < > " 与 ')。 */
function xmlEscapeAttr(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
export interface NewProcessXml {
/** 实例化后的 BPMN(占位符已替换,可直接 importXML)。 */
xml: string;
/** 实际写入 <process id> 的 ASCII id。 */
processId: string;
/** 发布还原映射;ASCII key 时为空对象。 */
idMap: Record<string, string>;
}
/**
* 用用户输入的名称/key 实例化模板:把 __PROCESS_ID__ 换成 ASCII 的 processId、__PROCESS_NAME__ 换成
* 转义后的展示名。返回实例化 XML + 发布还原用的 idMap。key 前后空白已 trim。
*/
export function buildNewProcessXml(templateXml: string, name: string, key: string): NewProcessXml {
const trimmedKey = key.trim();
const processId = isAsciiNcName(trimmedKey) ? trimmedKey : sanitizedId(trimmedKey);
const idMap = processId === trimmedKey ? {} : { [trimmedKey]: processId };
const xml = templateXml
.split('__PROCESS_ID__')
.join(processId)
.split('__PROCESS_NAME__')
.join(xmlEscapeAttr(name.trim()));
return { xml, processId, idMap };
}

View File

@@ -0,0 +1,41 @@
// 新建流程模板——单人审批(start → 1 userTask → end)。
//
// userTask 带 activiti:candidateUsers 示例表达式:外层对象用**全角【】**包裹(引擎运行期
// CandidateUsersHandler 全局 【→{ 还原为 JSON),items 一项 type:user(content 留空供用户在
// EIP4 侧板填人员 id)。逐字对齐 candidateExpression codec 的 build 输出:
// businessObject 值层:${candidateUsersHandler.getCandidateUsers(execution,'【"items":[…】]】')}
// XML 属性层:内层引号写作 &quot;(属性以 " 分隔)。
//
// 约束同 blank:全小写元素名 + isExecutable="true" + 完整 DI;占位符 __PROCESS_ID__/__PROCESS_NAME__。
export const SINGLE_APPROVAL_BPMN = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/processdef">
<process id="__PROCESS_ID__" name="__PROCESS_NAME__" isExecutable="true">
<startEvent id="start_1" name="发起"></startEvent>
<userTask id="task_approve" name="审批" activiti:exclusive="false" activiti:candidateUsers="\${candidateUsersHandler.getCandidateUsers(execution,'【&quot;items&quot;:[【&quot;type&quot;:&quot;user&quot;,&quot;content&quot;:&quot;&quot;,&quot;isCandidate&quot;:true,&quot;isSendMail&quot;:false,&quot;isSendPhone&quot;:false,&quot;isSendMessage&quot;:false】]】')}"></userTask>
<endEvent id="end_1" name="结束"></endEvent>
<sequenceFlow id="flow_1" sourceRef="start_1" targetRef="task_approve"></sequenceFlow>
<sequenceFlow id="flow_2" sourceRef="task_approve" targetRef="end_1"></sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane bpmnElement="__PROCESS_ID__" id="BPMNPlane_1">
<bpmndi:BPMNShape bpmnElement="start_1" id="BPMNShape_start_1">
<omgdc:Bounds height="30.0" width="30.0" x="150.0" y="85.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="task_approve" id="BPMNShape_task_approve">
<omgdc:Bounds height="80.0" width="100.0" x="240.0" y="60.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="end_1" id="BPMNShape_end_1">
<omgdc:Bounds height="28.0" width="28.0" x="400.0" y="86.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="flow_1" id="BPMNEdge_flow_1">
<omgdi:waypoint x="180.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="240.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="flow_2" id="BPMNEdge_flow_2">
<omgdi:waypoint x="340.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="400.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>`;

View File

@@ -0,0 +1,204 @@
import { describe, it, expect } from 'vitest';
import BpmnModdle from 'bpmn-moddle';
import activiti from '../moddle/activiti.json';
import {
PROCESS_TEMPLATES,
buildNewProcessXml,
isAsciiNcName,
} from './index';
import { buildCandidateExpression, type UserPropertyItem } from '../candidateExpression';
// 模板可部署前提的三重门(对照 T4.1):
// ① bpmn-moddle fromXML 无警告(结构合法,activiti 扩展属性全被描述符识别)。
// ② 真序列化(fromXML→toXML)后基础元素名**全小写**——防 PascalCase 回归(Flowable 大小写敏感,
// <Process>/<UserTask> 会被 ProcessValidator 判 0 个可执行流程、部署失败,见 moddle/serialization.test)。
// ③ 保留 isExecutable="true"(缺则 ProcessValidator 拒)。
// ④ 会签模板含 multiInstanceLoopCharacteristics。
// 均用**实例化后**(buildNewProcessXml 替换占位符)的 XML,逐字复现新建流程真正 importXML/部署的源。
/** 元素名正则(可选 bpmn: 前缀 + 精确 token + 分隔符),大小写敏感(同 serialization.test)。 */
const openTag = (name: string) => new RegExp('<(bpmn:)?' + name + '[\\s/>]');
// [小写名, PascalCase 名]——出现小写即断言对应 PascalCase 不出现。
const BASE_TYPES: Array<[lower: string, pascal: string]> = [
['definitions', 'Definitions'],
['process', 'Process'],
['startEvent', 'StartEvent'],
['endEvent', 'EndEvent'],
['sequenceFlow', 'SequenceFlow'],
['userTask', 'UserTask'],
['multiInstanceLoopCharacteristics', 'MultiInstanceLoopCharacteristics'],
];
async function roundTrip(xml: string): Promise<{ out: string; warnings: unknown[] }> {
const moddle = new BpmnModdle({ activiti });
const { rootElement, warnings } = await moddle.fromXML(xml);
const { xml: out } = await moddle.toXML(rootElement, { format: true });
return { out, warnings: warnings ?? [] };
}
describe('新建流程模板库', () => {
it('登记齐 4 个模板(空白/单人/两级/会签)', () => {
expect(PROCESS_TEMPLATES.map((t) => t.id)).toEqual([
'blank',
'single-approval',
'two-level',
'cosign',
]);
});
for (const t of PROCESS_TEMPLATES) {
describe(`模板 ${t.id}`, () => {
// ASCII key → process id 直接用 key,不引 idMap;此实例化 XML 即真正被 importXML/部署的源。
const { xml, processId, idMap } = buildNewProcessXml(t.xml, '测试流程', 'TestProc');
it('占位符已全部替换(无 __PROCESS_ID__/__PROCESS_NAME__ 残留)', () => {
expect(xml).not.toContain('__PROCESS_ID__');
expect(xml).not.toContain('__PROCESS_NAME__');
expect(processId).toBe('TestProc');
expect(idMap).toEqual({});
});
it('① bpmn-moddle fromXML 无警告(结构合法)', async () => {
const { warnings } = await roundTrip(xml);
expect(warnings).toEqual([]);
});
it('② 真序列化后基础元素名全小写(无 PascalCase,Flowable 可识别)', async () => {
const { out } = await roundTrip(xml);
for (const [lower, pascal] of BASE_TYPES) {
if (openTag(lower).test(out)) {
expect(out, `不应含 PascalCase <${pascal}>`).not.toMatch(openTag(pascal));
}
}
// 每个模板至少含小写 process/startEvent/endEvent/sequenceFlow。
for (const lower of ['process', 'startEvent', 'endEvent', 'sequenceFlow']) {
expect(out, `应含小写 <${lower}>`).toMatch(openTag(lower));
}
});
it('③ 保留 isExecutable="true"(ProcessValidator 前提)', async () => {
const { out } = await roundTrip(xml);
expect(out).toMatch(/<(bpmn:)?process[\s][^>]*isExecutable="true"/);
});
it('含完整 BPMNDiagram DI(画布不空白)', () => {
expect(xml).toContain('BPMNDiagram');
expect(xml).toContain('BPMNPlane');
});
});
}
it('④ 会签模板含 multiInstanceLoopCharacteristics + elementVariable + 完成条件', async () => {
const cosign = PROCESS_TEMPLATES.find((t) => t.id === 'cosign')!;
const { xml } = buildNewProcessXml(cosign.xml, '会签流程', 'CosignProc');
const { out } = await roundTrip(xml);
expect(out).toMatch(openTag('multiInstanceLoopCharacteristics'));
expect(out).toContain('elementVariable="assignee"');
expect(out).toMatch(/completionCondition/);
});
it('单人/两级/会签模板均含 userTask(空白模板不含)', async () => {
for (const id of ['single-approval', 'two-level', 'cosign']) {
const t = PROCESS_TEMPLATES.find((x) => x.id === id)!;
const { out } = await roundTrip(buildNewProcessXml(t.xml, 'n', 'K').xml);
expect(out, `${id} 应含 userTask`).toMatch(openTag('userTask'));
}
const blank = PROCESS_TEMPLATES.find((x) => x.id === 'blank')!;
const { out } = await roundTrip(buildNewProcessXml(blank.xml, 'n', 'K').xml);
expect(out).not.toMatch(openTag('userTask'));
});
});
describe('buildNewProcessXml —— key/名称替换', () => {
const single = PROCESS_TEMPLATES.find((t) => t.id === 'single-approval')!;
it('ASCII key 直接作 process id,idMap 空', () => {
const { xml, processId, idMap } = buildNewProcessXml(single.xml, '请假审批', 'LeaveApply');
expect(processId).toBe('LeaveApply');
expect(idMap).toEqual({});
expect(xml).toContain('id="LeaveApply"');
expect(xml).toContain('bpmnElement="LeaveApply"'); // DI plane 引用同步替换
});
it('中文 key → process id 净化为 ASCII,idMap={原 key→净化 id},XML 内无中文 id', async () => {
const { xml, processId, idMap } = buildNewProcessXml(single.xml, '总包合同交底', '总包合同交底');
expect(isAsciiNcName(processId)).toBe(true);
expect(idMap).toEqual({ 总包合同交底: processId });
expect(xml).toContain('id="' + processId + '"');
expect(xml).toContain('bpmnElement="' + processId + '"');
// moddle 拒中文 id:中文 key 实例化后仍能 fromXML(证明 id 已净化为 ASCII)。
const { warnings } = await roundTrip(xml);
expect(warnings).toEqual([]);
});
it('展示名进 process name(中文/特殊字符转义,round-trip 还原原文)', async () => {
const { xml } = buildNewProcessXml(single.xml, 'A&B <测试>', 'K');
expect(xml).toContain('name="A&amp;B &lt;测试&gt;"');
const moddle = new BpmnModdle({ activiti });
const { rootElement } = await moddle.fromXML(xml);
const proc = (rootElement as { rootElements: Array<{ $type: string; name?: string }> }).rootElements.find(
(e) => e.$type === 'bpmn:Process',
);
expect(proc?.name).toBe('A&B <测试>');
});
it('key 前后空白 trim 后再判定/替换', () => {
const { processId, idMap } = buildNewProcessXml(single.xml, 'n', ' LeaveApply ');
expect(processId).toBe('LeaveApply');
expect(idMap).toEqual({});
});
});
// I-1(守命根回归):模板里的 activiti:candidateUsers / collection 是**硬编码字符串**,其与
// candidateExpression codec build 输出的逐字对齐此前只是实测、无测试守护。这里从各模板 fromXML 解出
// 属性值(moddle 已把 &quot; 解码为真引号、全角【】保留——即 codec 处理的 businessObject 值层),
// 断言 === buildCandidateExpression(标准 item, 变体)。模板 JSON 键序/转义漂移或 codec 改契约都会被
// 单测立即抓到,而非等 live 部署才暴露(部署后表达式解析即断)。
describe('模板办理人表达式与 codec 逐字对齐(守命根)', () => {
// 模板示例项:一项 type:user、content 空、候选、三通知关(与 templates/*.bpmn.ts 硬编码一致)。
const STD_ITEM: UserPropertyItem = {
type: 'user',
content: '',
isCandidate: true,
isSendMail: false,
isSendPhone: false,
isSendMessage: false,
};
interface ModdleEl {
$type: string;
get(name: string): unknown;
}
async function userTasksOf(templateXml: string): Promise<ModdleEl[]> {
const moddle = new BpmnModdle({ activiti });
// ASCII key → process id 直接用 key,实例化 XML 即真正 importXML/部署的源。
const { rootElement } = await moddle.fromXML(buildNewProcessXml(templateXml, 'n', 'K').xml);
const proc = (rootElement as unknown as { rootElements: ModdleEl[] }).rootElements.find(
(e) => e.$type === 'bpmn:Process',
);
const flow = (proc?.get('flowElements') ?? []) as ModdleEl[];
return flow.filter((e) => e.$type === 'bpmn:UserTask');
}
it('单人审批:userTask candidateUsers === buildCandidateExpression([std],candidate)', async () => {
const [ut] = await userTasksOf(PROCESS_TEMPLATES.find((t) => t.id === 'single-approval')!.xml);
expect(ut.get('activiti:candidateUsers')).toBe(buildCandidateExpression([STD_ITEM], 'candidate'));
});
it('两级审批:两 userTask candidateUsers 均 === buildCandidateExpression([std],candidate)', async () => {
const uts = await userTasksOf(PROCESS_TEMPLATES.find((t) => t.id === 'two-level')!.xml);
expect(uts).toHaveLength(2);
const expected = buildCandidateExpression([STD_ITEM], 'candidate');
for (const ut of uts) {
expect(ut.get('activiti:candidateUsers')).toBe(expected);
}
});
it('会签:multiInstance collection === buildCandidateExpression([std],multiInstance)', async () => {
const [ut] = await userTasksOf(PROCESS_TEMPLATES.find((t) => t.id === 'cosign')!.xml);
const loop = ut.get('loopCharacteristics') as ModdleEl;
expect(loop.get('activiti:collection')).toBe(buildCandidateExpression([STD_ITEM], 'multiInstance'));
});
});

View File

@@ -0,0 +1,45 @@
// 新建流程模板——两级审批(start → 一级 userTask → 二级 userTask → end)。
//
// 两个 userTask 各带 activiti:candidateUsers(type:user,content 留空供侧板填人);结构、
// 全角【】/&quot; 转义、约束(全小写元素名 + isExecutable + 完整 DI + 占位符)同 single-approval。
export const TWO_LEVEL_BPMN = `<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/processdef">
<process id="__PROCESS_ID__" name="__PROCESS_NAME__" isExecutable="true">
<startEvent id="start_1" name="发起"></startEvent>
<userTask id="task_level1" name="一级审批" activiti:exclusive="false" activiti:candidateUsers="\${candidateUsersHandler.getCandidateUsers(execution,'【&quot;items&quot;:[【&quot;type&quot;:&quot;user&quot;,&quot;content&quot;:&quot;&quot;,&quot;isCandidate&quot;:true,&quot;isSendMail&quot;:false,&quot;isSendPhone&quot;:false,&quot;isSendMessage&quot;:false】]】')}"></userTask>
<userTask id="task_level2" name="二级审批" activiti:exclusive="false" activiti:candidateUsers="\${candidateUsersHandler.getCandidateUsers(execution,'【&quot;items&quot;:[【&quot;type&quot;:&quot;user&quot;,&quot;content&quot;:&quot;&quot;,&quot;isCandidate&quot;:true,&quot;isSendMail&quot;:false,&quot;isSendPhone&quot;:false,&quot;isSendMessage&quot;:false】]】')}"></userTask>
<endEvent id="end_1" name="结束"></endEvent>
<sequenceFlow id="flow_1" sourceRef="start_1" targetRef="task_level1"></sequenceFlow>
<sequenceFlow id="flow_2" sourceRef="task_level1" targetRef="task_level2"></sequenceFlow>
<sequenceFlow id="flow_3" sourceRef="task_level2" targetRef="end_1"></sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane bpmnElement="__PROCESS_ID__" id="BPMNPlane_1">
<bpmndi:BPMNShape bpmnElement="start_1" id="BPMNShape_start_1">
<omgdc:Bounds height="30.0" width="30.0" x="150.0" y="85.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="task_level1" id="BPMNShape_task_level1">
<omgdc:Bounds height="80.0" width="100.0" x="230.0" y="60.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="task_level2" id="BPMNShape_task_level2">
<omgdc:Bounds height="80.0" width="100.0" x="390.0" y="60.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="end_1" id="BPMNShape_end_1">
<omgdc:Bounds height="28.0" width="28.0" x="550.0" y="86.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="flow_1" id="BPMNEdge_flow_1">
<omgdi:waypoint x="180.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="230.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="flow_2" id="BPMNEdge_flow_2">
<omgdi:waypoint x="330.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="390.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="flow_3" id="BPMNEdge_flow_3">
<omgdi:waypoint x="490.0" y="100.0"></omgdi:waypoint>
<omgdi:waypoint x="550.0" y="100.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>`;

View File

@@ -0,0 +1,55 @@
import { describe, it, expect, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useSelectedElement } from './useSelectedElement';
function makeModeler() {
let handler: ((e: unknown) => void) | null = null;
const on = vi.fn((ev: string, cb: (e: unknown) => void) => {
if (ev === 'selection.changed') handler = cb;
});
const off = vi.fn();
return {
modeler: { on, off },
on,
off,
fire: (sel: unknown[]) => act(() => handler?.({ newSelection: sel })),
};
}
describe('useSelectedElement', () => {
it('单选返回该 element', () => {
const { modeler, fire } = makeModeler();
const { result } = renderHook(() => useSelectedElement(modeler));
const el = { id: 'a', type: 'bpmn:UserTask', businessObject: { get: () => undefined } };
fire([el]);
expect(result.current).toBe(el);
});
it('多选返回 null', () => {
const { modeler, fire } = makeModeler();
const { result } = renderHook(() => useSelectedElement(modeler));
fire([{ id: 'a' }, { id: 'b' }]);
expect(result.current).toBeNull();
});
it('空选返回 null', () => {
const { modeler, fire } = makeModeler();
const { result } = renderHook(() => useSelectedElement(modeler));
fire([{ id: 'a' }]);
expect(result.current).not.toBeNull();
fire([]);
expect(result.current).toBeNull();
});
it('卸载时解绑 selection.changed', () => {
const { modeler, off } = makeModeler();
const { unmount } = renderHook(() => useSelectedElement(modeler));
unmount();
expect(off).toHaveBeenCalledWith('selection.changed', expect.any(Function));
});
it('modeler 为 null 时返回 null 且不订阅', () => {
const { result } = renderHook(() => useSelectedElement(null));
expect(result.current).toBeNull();
});
});

View File

@@ -0,0 +1,56 @@
// 订阅 bpmn-js 'selection.changed',返回当前单选 element(多选/空选返 null)。
// 卸载时解绑;modeler 为 null 时不订阅、恒返 null。
import { useEffect, useState } from 'react';
/** bpmn-js businessObject 的最小契约(本侧板用到的读法)。 */
export interface BpmnBusinessObject {
$type?: string;
/** 未在 moddle 描述符中声明的长尾扩展属性(命名空间键→字符串值)。 */
$attrs?: Record<string, string>;
/** 读取声明属性(如 'activiti:candidateUsers'/'loopCharacteristics'/'extensionElements')。 */
get(name: string): unknown;
}
/** bpmn-js diagram element 的最小契约。 */
export interface BpmnElement {
id: string;
/** moddle 类型,如 'bpmn:UserTask'。 */
type: string;
businessObject: BpmnBusinessObject;
}
/** 订阅所需的最小 modeler 契约(bpmn-js Modeler 天然满足)。 */
export interface SelectionModeler {
on(event: string, cb: (e: unknown) => void): void;
off?(event: string, cb: (e: unknown) => void): void;
}
interface SelectionChangedEvent {
newSelection?: unknown[];
}
/**
* 返回当前单选的 bpmn element;多选或空选返 null。modeler 变更/卸载自动重订阅、解绑。
*/
export function useSelectedElement(
modeler: SelectionModeler | null | undefined,
): BpmnElement | null {
const [element, setElement] = useState<BpmnElement | null>(null);
useEffect(() => {
if (!modeler) {
setElement(null);
return;
}
const handler = (e: unknown) => {
const sel = ((e as SelectionChangedEvent | undefined)?.newSelection ?? []) as BpmnElement[];
setElement(sel.length === 1 ? sel[0] : null);
};
modeler.on('selection.changed', handler);
return () => {
modeler.off?.('selection.changed', handler);
};
}, [modeler]);
return element;
}

View File

@@ -30,10 +30,11 @@ describe('DesignCenterPage 入口按钮', () => {
profileMock.mockReset(); profileMock.mockReset();
}); });
it('admin 看到 [+ 新建功能] 与 [⚡ AI 建功能]', async () => { it('admin 看到 [流程设计] [+ 新建功能] 与 [⚡ AI 建功能]', async () => {
profileMock.mockReturnValue({ userId: 'ADMIN', account: 'admin', name: 'x', roles: [] }); profileMock.mockReturnValue({ userId: 'ADMIN', account: 'admin', name: 'x', roles: [] });
renderPage(); renderPage();
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('dc-process-modeler')).toBeInTheDocument();
expect(screen.getByTestId('dc-new-feature')).toBeInTheDocument(); expect(screen.getByTestId('dc-new-feature')).toBeInTheDocument();
expect(screen.getByTestId('dc-ai-feature')).toBeInTheDocument(); expect(screen.getByTestId('dc-ai-feature')).toBeInTheDocument();
}); });
@@ -42,6 +43,7 @@ describe('DesignCenterPage 入口按钮', () => {
it('非 admin 不渲染入口(整页降级)', () => { it('非 admin 不渲染入口(整页降级)', () => {
profileMock.mockReturnValue({ userId: 'U1', account: 'zhangsan', name: 'z', roles: [] }); profileMock.mockReturnValue({ userId: 'U1', account: 'zhangsan', name: 'z', roles: [] });
renderPage(); renderPage();
expect(screen.queryByTestId('dc-process-modeler')).not.toBeInTheDocument();
expect(screen.queryByTestId('dc-new-feature')).not.toBeInTheDocument(); expect(screen.queryByTestId('dc-new-feature')).not.toBeInTheDocument();
expect(screen.queryByTestId('dc-ai-feature')).not.toBeInTheDocument(); expect(screen.queryByTestId('dc-ai-feature')).not.toBeInTheDocument();
}); });

View File

@@ -73,6 +73,14 @@ export function DesignCenterPage() {
</div> </div>
</div> </div>
<div style={{ flex: 1 }} /> <div style={{ flex: 1 }} />
<button
className="btn btn-sm"
data-testid="dc-process-modeler"
onClick={() => navigate('/process-modeler')}
title="在线流程设计器:可视化编辑存量 BPMN 流程 / 新建流程"
>
流程设计
</button>
<button <button
className="btn btn-sm" className="btn btn-sm"
data-testid="dc-new-feature" data-testid="dc-new-feature"

View File

@@ -0,0 +1,448 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { SYNTHETIC_BPMN } from '../modeler/moddle/fixtures/synthetic-full-surface.bpmn';
// bpmn-js Modeler:jsdom 跑不动真渲染,stub 成类(可断言 importXML/saveXML/destroy 调用)。
const { importXMLMock, saveXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor } = vi.hoisted(() => {
const importXMLMock = vi.fn();
const saveXMLMock = vi.fn();
const destroyMock = vi.fn();
const attachToMock = vi.fn();
const getMock = vi.fn((service: string) => {
if (service === 'propertiesPanel') return { attachTo: attachToMock };
if (service === 'canvas') return { zoom: vi.fn() };
return {};
});
const onMock = vi.fn();
const ModelerCtor = vi.fn().mockImplementation(() => ({
importXML: importXMLMock,
saveXML: saveXMLMock,
destroy: destroyMock,
get: getMock,
on: onMock,
}));
return { importXMLMock, saveXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor };
});
vi.mock('bpmn-js/lib/Modeler', () => ({ default: ModelerCtor }));
// 标准属性面板模块只作为 additionalModules 配置项传入被 mock 的 Modeler,永不真正执行。
vi.mock('bpmn-js-properties-panel', () => ({
BpmnPropertiesPanelModule: {},
BpmnPropertiesProviderModule: {},
}));
vi.mock('../api/processModeler', () => ({
fetchProcDefSource: vi.fn(),
fetchProcDefSourceByKey: vi.fn(),
fetchProcessOptions: vi.fn(),
// Eip4Panel(右栏叠板)挂载时拉 formKey 数据源——mock 成空列表避免真请求。
fetchWfTemplates: vi.fn(() => Promise.resolve({ templates: [], degraded: false })),
listModels: vi.fn(() => Promise.resolve([])),
getModel: vi.fn(),
createDraft: vi.fn(() => Promise.resolve('NEW-1')),
saveDraft: vi.fn(() => Promise.resolve()),
draftFromProcDef: vi.fn(() => Promise.resolve('FP-1')),
deleteDraft: vi.fn(() => Promise.resolve()),
// T3.3 发布:PublishConfirm 挂载拉 impact、确认调 deploy——mock 成默认成功态。
deployModel: vi.fn(() => Promise.resolve({ ok: true, deploymentId: 'D1', processKey: 'k', newVersion: 4 })),
fetchImpact: vi.fn(() => Promise.resolve({ found: true, processKey: 'k', currentVersion: 3, runningInstances: 0 })),
}));
vi.mock('../auth/token', async (importOriginal) => ({
...(await importOriginal<typeof import('../auth/token')>()),
getProfile: vi.fn(),
}));
import { ProcessModelerPage } from './ProcessModelerPage';
import {
fetchProcDefSource,
fetchProcDefSourceByKey,
fetchProcessOptions,
listModels,
getModel,
createDraft,
saveDraft,
draftFromProcDef,
deleteDraft,
deployModel,
fetchImpact,
} from '../api/processModeler';
import { getProfile } from '../auth/token';
const mSource = vi.mocked(fetchProcDefSource);
const mSourceByKey = vi.mocked(fetchProcDefSourceByKey);
const mOptions = vi.mocked(fetchProcessOptions);
const mListModels = vi.mocked(listModels);
const mGetModel = vi.mocked(getModel);
const mCreateDraft = vi.mocked(createDraft);
const mSaveDraft = vi.mocked(saveDraft);
const mFromProcDef = vi.mocked(draftFromProcDef);
const mDeleteDraft = vi.mocked(deleteDraft);
const mDeploy = vi.mocked(deployModel);
const mImpact = vi.mocked(fetchImpact);
const mProfile = vi.mocked(getProfile);
function renderPage(initialPath = '/process-modeler') {
return render(
<MemoryRouter initialEntries={[initialPath]}>
<ProcessModelerPage />
</MemoryRouter>,
);
}
beforeEach(() => {
importXMLMock.mockReset().mockResolvedValue(undefined);
saveXMLMock.mockReset().mockResolvedValue({ xml: '<edited/>' });
destroyMock.mockReset();
attachToMock.mockReset();
getMock.mockClear();
onMock.mockReset();
ModelerCtor.mockClear();
mSource.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } });
mSourceByKey.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } });
mOptions.mockReset().mockResolvedValue([]);
mListModels.mockReset().mockResolvedValue([]);
mGetModel.mockReset().mockResolvedValue({
found: true,
bpmnXml: SYNTHETIC_BPMN,
metaInfo: JSON.stringify({ eip4IdMap: { '总包合同交底': 'Proc_zbht' } }),
key: '总包合同交底',
});
mCreateDraft.mockReset().mockResolvedValue('NEW-1');
mSaveDraft.mockReset().mockResolvedValue(undefined);
mFromProcDef.mockReset().mockResolvedValue('FP-1');
mDeleteDraft.mockReset().mockResolvedValue(undefined);
mDeploy.mockReset().mockResolvedValue({ ok: true, deploymentId: 'D1', processKey: 'k', newVersion: 4 });
mImpact.mockReset().mockResolvedValue({ found: true, processKey: 'k', currentVersion: 3, runningInstances: 0 });
mProfile.mockReset().mockReturnValue({ userId: 'ADMIN', account: 'admin', name: '管理员', roles: [] });
});
describe('ProcessModelerPage', () => {
it('admin 渲染画布容器与标准属性面板容器', async () => {
renderPage();
expect(screen.getByTestId('process-modeler-canvas')).toBeInTheDocument();
expect(screen.getByTestId('process-modeler-props')).toBeInTheDocument();
// flush Eip4Panel 挂载期 fetchWfTemplates 的 setState(避免 act 告警)
await act(async () => {
await Promise.resolve();
});
});
it('非 admin 降级为「仅管理员可用」文案,不渲染画布', () => {
mProfile.mockReturnValue({ userId: 'U9', account: 'zhang', name: '张三', roles: [] });
renderPage();
expect(screen.getByText(/仅管理员可用/)).toBeInTheDocument();
expect(screen.queryByTestId('process-modeler-canvas')).not.toBeInTheDocument();
});
it('?procDefId= 时载入存量流程并把返回的 bpmnXml 交给 Modeler.importXML', async () => {
renderPage('/process-modeler?procDefId=PD-1');
await waitFor(() => expect(mSource).toHaveBeenCalledWith('PD-1'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalledWith(SYNTHETIC_BPMN));
expect(ModelerCtor).toHaveBeenCalledTimes(1);
});
it('构造后显式 attachTo 属性面板容器一次(修 live 面板从不挂载)', async () => {
renderPage('/process-modeler?procDefId=PD-1');
await waitFor(() => expect(attachToMock).toHaveBeenCalledTimes(1));
expect(attachToMock).toHaveBeenCalledWith(screen.getByTestId('process-modeler-props'));
});
it('接口 found:false 时显示未找到文案且不 importXML', async () => {
mSource.mockResolvedValue({ found: false });
renderPage('/process-modeler?procDefId=PD-x');
await waitFor(() => expect(screen.getByText(/未找到|无 BPMN|加载失败/)).toBeInTheDocument());
expect(importXMLMock).not.toHaveBeenCalled();
});
it('无参时展示「打开存量流程」选择器(数据源 process-select)', async () => {
mOptions.mockResolvedValue([{ label: '总包合同交底', value: '总包合同交底', source: 'model', id: 'MDL-1', key: 'zbht' }]);
renderPage();
await waitFor(() => expect(mOptions).toHaveBeenCalled());
expect(screen.getByTestId('process-modeler-open-select')).toBeInTheDocument();
expect(await screen.findByText('总包合同交底')).toBeInTheDocument();
});
it('?procKey= 时走 by-key 载入并 importXML(source=model 语义缺口修复)', async () => {
renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底'));
await waitFor(() => expect(mSourceByKey).toHaveBeenCalledWith('总包合同交底'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalledWith(SYNTHETIC_BPMN));
expect(mSource).not.toHaveBeenCalled(); // 未走 by-id 路径
});
it('选中 source=model 选项 → 派到 by-key(procKey),不走 by-id', async () => {
mOptions.mockResolvedValue([{ label: '模型流程', value: '模型流程', source: 'model', id: 'MDL-9', key: 'MKEY' }]);
renderPage();
const select = await screen.findByTestId('process-modeler-open-select');
await screen.findByText('模型流程');
fireEvent.change(select, { target: { value: '0' } });
await waitFor(() => expect(mSourceByKey).toHaveBeenCalledWith('MKEY'));
expect(mSource).not.toHaveBeenCalled();
});
it('选中 source=processDefinition 选项 → 派到 by-id(procDefId)', async () => {
mOptions.mockResolvedValue([
{ label: '部署流程', value: '部署流程', source: 'processDefinition', id: '部署流程:3:uuid', key: 'k' },
]);
renderPage();
const select = await screen.findByTestId('process-modeler-open-select');
await screen.findByText('部署流程');
fireEvent.change(select, { target: { value: '0' } });
await waitFor(() => expect(mSource).toHaveBeenCalledWith('部署流程:3:uuid'));
expect(mSourceByKey).not.toHaveBeenCalled();
});
// 🔴 红线回归(T1.5 评审遗留 + T2.4 顺带收口):双包冲突会静默丢弃 userTask,
// 故构造参数必须锁死——moddleExtensions 键恰为 ['activiti'],additionalModules 长度恰 2。
// 防「顺手」加 Camunda provider / 双载 flowable 描述符导致静默回归。
it('红线:Modeler 构造参数 moddleExtensions 键恰 [activiti] 且 additionalModules 长度 2', async () => {
renderPage('/process-modeler?procDefId=PD-1');
await waitFor(() => expect(ModelerCtor).toHaveBeenCalledTimes(1));
const opts = ModelerCtor.mock.calls[0][0] as {
moddleExtensions: Record<string, unknown>;
additionalModules: unknown[];
};
expect(Object.keys(opts.moddleExtensions)).toEqual(['activiti']);
expect(opts.additionalModules).toHaveLength(2);
});
// ── T2.5 存草稿 ────────────────────────────────────────────────────────────
const saveBtn = () => screen.getByTestId('process-modeler-save-draft');
it('存草稿(存量按 key,无 modelId):createDraft 带 eip4IdMap 进 metaInfo,不走 from-procdef', async () => {
renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
await waitFor(() => expect(saveBtn()).not.toBeDisabled());
fireEvent.click(saveBtn());
await waitFor(() => expect(mCreateDraft).toHaveBeenCalled());
const body = mCreateDraft.mock.calls[0][0];
expect(body.bpmnXml).toBe('<edited/>');
expect(JSON.parse(body.metaInfo!).eip4IdMap).toEqual({ '总包合同交底': 'Proc_zbht' });
expect(JSON.parse(body.metaInfo!)).toHaveProperty('sourceProcDefId'); // 结构对齐 from-procdef
expect(mFromProcDef).not.toHaveBeenCalled();
});
it('I-2 首存后回填 ?modelId=(令刷新幂等):触发按 modelId 重载', async () => {
renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
await waitFor(() => expect(saveBtn()).not.toBeDisabled());
fireEvent.click(saveBtn());
await waitFor(() => expect(mCreateDraft).toHaveBeenCalled());
// 回填 ?modelId=NEW-1 → 载入效果按 modelId 重载(getModel)——证明 setParams 已写入。
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('NEW-1'));
});
it('存草稿(存量按 procDefId,无 modelId):from-procdef 建草稿(后端 metaInfo)再 PUT', async () => {
renderPage('/process-modeler?procDefId=PD-1');
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
await waitFor(() => expect(saveBtn()).not.toBeDisabled());
fireEvent.click(saveBtn());
await waitFor(() => expect(mFromProcDef).toHaveBeenCalledWith('PD-1'));
await waitFor(() => expect(mSaveDraft).toHaveBeenCalledWith('FP-1', { bpmnXml: '<edited/>' }));
expect(mCreateDraft).not.toHaveBeenCalled();
});
it('第二次保存(已有 modelId):走 saveDraft(PUT),不重发 metaInfo', async () => {
renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
await waitFor(() => expect(saveBtn()).not.toBeDisabled());
fireEvent.click(saveBtn()); // 首次:createDraft → modelId=NEW-1 → 回填 ?modelId= → 重载
await waitFor(() => expect(mCreateDraft).toHaveBeenCalled());
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('NEW-1')); // 回填后重载完成
await waitFor(() => expect(saveBtn()).not.toBeDisabled()); // saving 复位 + 重载就绪
fireEvent.click(saveBtn()); // 二次:PUT NEW-1(modelId 已在)
await waitFor(() => expect(mSaveDraft).toHaveBeenCalledWith('NEW-1', { bpmnXml: '<edited/>' }));
const putBody = mSaveDraft.mock.calls[mSaveDraft.mock.calls.length - 1][1];
expect('metaInfo' in putBody).toBe(false); // 不重发 metaInfo,保住 eip4IdMap
});
it('打开草稿(?modelId=)走 getModel→importXML', async () => {
renderPage('/process-modeler?modelId=MD-7');
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('MD-7'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalledWith(SYNTHETIC_BPMN));
expect(mSource).not.toHaveBeenCalled();
expect(mSourceByKey).not.toHaveBeenCalled();
});
// ── T2.5 草稿列表打开 ──────────────────────────────────────────────────────
it('草稿 tab:列出草稿→点「打开」→setParams(modelId)→getModel→importXML', async () => {
mListModels.mockResolvedValue([{ id: 'MD-1', name: '草稿甲', key: 'k1' }]);
renderPage();
fireEvent.click(screen.getByTestId('process-modeler-tab-draft'));
await waitFor(() => expect(mListModels).toHaveBeenCalled());
expect(await screen.findByText('草稿甲')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('process-modeler-draft-open-0'));
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('MD-1'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalledWith(SYNTHETIC_BPMN));
});
// ── T2.5 草稿删除(前端;后端 DELETE 端点待补) ──────────────────────────────
it('草稿删除:confirm=确认→deleteDraft→列表刷新', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
mListModels.mockResolvedValue([{ id: 'MD-1', name: '草稿甲', key: 'k1' }]);
renderPage();
fireEvent.click(screen.getByTestId('process-modeler-tab-draft'));
await screen.findByText('草稿甲');
const before = mListModels.mock.calls.length;
fireEvent.click(screen.getByTestId('process-modeler-draft-delete-0'));
await waitFor(() => expect(mDeleteDraft).toHaveBeenCalledWith('MD-1'));
await waitFor(() => expect(mListModels.mock.calls.length).toBeGreaterThan(before)); // 刷新
confirmSpy.mockRestore();
});
it('草稿删除:confirm=取消→不调 deleteDraft', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
mListModels.mockResolvedValue([{ id: 'MD-1', name: '草稿甲', key: 'k1' }]);
renderPage();
fireEvent.click(screen.getByTestId('process-modeler-tab-draft'));
await screen.findByText('草稿甲');
fireEvent.click(screen.getByTestId('process-modeler-draft-delete-0'));
await act(async () => {
await Promise.resolve();
});
expect(mDeleteDraft).not.toHaveBeenCalled();
confirmSpy.mockRestore();
});
// ── T3.3 发布 gating + 同人确认 ────────────────────────────────────────────
const publishBtn = () => screen.getByTestId('process-modeler-publish');
it('未打开任何流程时发布按钮 disabled(无 Modeler 实例)', async () => {
renderPage();
expect(publishBtn()).toBeDisabled();
await act(async () => {
await Promise.resolve();
});
});
it('发布 gating:存量按 key 打开(尚无 modelId)→点发布不开确认弹窗、不 deploy', async () => {
renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
await waitFor(() => expect(publishBtn()).not.toBeDisabled()); // 可点(触发提示分支)
fireEvent.click(publishBtn());
await act(async () => {
await Promise.resolve();
});
// 无 modelId:提示先存草稿,不开弹窗、不发布
expect(screen.queryByTestId('process-modeler-publish-confirm')).not.toBeInTheDocument();
expect(mDeploy).not.toHaveBeenCalled();
});
it('发布:打开草稿(有 modelId)→点发布→先持久化(I2)→开同人确认弹窗并按 modelId 拉 impact', async () => {
renderPage('/process-modeler?modelId=MD-7');
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
await waitFor(() => expect(publishBtn()).not.toBeDisabled());
fireEvent.click(publishBtn());
await waitFor(() => expect(saveXMLMock).toHaveBeenCalled());
// I2:发布前先 saveDraft(当前 xml) 持久化,使部署内容==预览==diff current 侧。
await waitFor(() => expect(mSaveDraft).toHaveBeenCalledWith('MD-7', { bpmnXml: '<edited/>' }));
await waitFor(() => expect(screen.getByTestId('process-modeler-publish-confirm')).toBeInTheDocument());
await waitFor(() => expect(mImpact).toHaveBeenCalledWith('MD-7'));
// 确认发布 → deployModel(MD-7) → 成功后弹窗关闭
fireEvent.click(screen.getByTestId('publish-confirm-btn'));
await waitFor(() => expect(mDeploy).toHaveBeenCalledWith('MD-7'));
await waitFor(() =>
expect(screen.queryByTestId('process-modeler-publish-confirm')).not.toBeInTheDocument(),
);
});
// I1 锁:存量按 key 打开→改→首存(reload)→发布,diff 基线必须仍是**原始源**(非「已存版」),故 diff 非空。
it('I1:存量 save→publish 后 diff 基线仍是原始源→变更清单非空', async () => {
// 原始源(办理人 type=position) vs 首存后 reload/当前编辑器态(办理人 type=user)。
const EDITED = SYNTHETIC_BPMN.replace(
'&quot;type&quot;:&quot;position&quot;',
'&quot;type&quot;:&quot;user&quot;',
);
mSourceByKey.mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } });
// 首存后 setParams(modelId=NEW-1) 触发 reload:getModel 返回已存(编辑)版,模拟服务端草稿态。
mGetModel.mockResolvedValue({ found: true, bpmnXml: EDITED, metaInfo: JSON.stringify({ eip4IdMap: {} }), key: '总包合同交底' });
// 当前编辑器 saveXML 返回编辑版(与已存版一致)。
saveXMLMock.mockResolvedValue({ xml: EDITED });
renderPage('/process-modeler?procKey=' + encodeURIComponent('总包合同交底'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalledWith(SYNTHETIC_BPMN)); // 初次载原始源
await waitFor(() => expect(saveBtn()).not.toBeDisabled());
fireEvent.click(saveBtn()); // 首存 → createDraft NEW-1 → 回填 ?modelId= → reload
await waitFor(() => expect(mCreateDraft).toHaveBeenCalled());
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('NEW-1'));
await waitFor(() => expect(publishBtn()).not.toBeDisabled());
fireEvent.click(publishBtn());
await waitFor(() => expect(screen.getByTestId('process-modeler-publish-confirm')).toBeInTheDocument());
// 基线保留为原始源 → diff(原始, 编辑) 非空、含「办理人变更」;未修复则基线=编辑版 → diff 空。
expect(screen.queryByTestId('publish-diff-empty')).not.toBeInTheDocument();
expect(screen.getByTestId('publish-diff-list')).toHaveTextContent('办理人变更');
});
// ── T4.1 新建流程(模板库 + NewProcessDialog;NewProcessDialog 不 mock,跑真实例化) ─────
it('“新建流程”按钮可用并打开新建对话框', async () => {
renderPage();
const btn = await screen.findByTestId('process-modeler-new');
expect(btn).not.toBeDisabled();
fireEvent.click(btn);
expect(await screen.findByTestId('new-process-name')).toBeInTheDocument();
expect(screen.getByTestId('new-process-template')).toBeInTheDocument();
});
it('新建确认→挂 Modeler 并 importXML 模板实例化 XML(process id=用户 key,不取存量源)', async () => {
renderPage();
fireEvent.click(await screen.findByTestId('process-modeler-new'));
fireEvent.change(await screen.findByTestId('new-process-name'), { target: { value: '请假审批' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: 'leaveApply' } });
fireEvent.change(screen.getByTestId('new-process-template'), { target: { value: 'single-approval' } });
fireEvent.click(screen.getByTestId('new-process-confirm'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
const xml = importXMLMock.mock.calls[0][0] as string;
expect(xml).toContain('id="leaveApply"');
expect(xml).toContain('userTask');
expect(xml).not.toContain('__PROCESS_ID__');
// 新建不走任何存量/草稿取源。
expect(mSource).not.toHaveBeenCalled();
expect(mSourceByKey).not.toHaveBeenCalled();
expect(mGetModel).not.toHaveBeenCalled();
// 打开器叠层消失(newDraft 激活)。
expect(screen.queryByTestId('process-modeler-open-select')).not.toBeInTheDocument();
});
it('新建会签模板→importXML 含 multiInstance', async () => {
renderPage();
fireEvent.click(await screen.findByTestId('process-modeler-new'));
fireEvent.change(await screen.findByTestId('new-process-name'), { target: { value: '会签' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: 'cosignFlow' } });
fireEvent.change(screen.getByTestId('new-process-template'), { target: { value: 'cosign' } });
fireEvent.click(screen.getByTestId('new-process-confirm'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
expect(importXMLMock.mock.calls[0][0] as string).toContain('multiInstanceLoopCharacteristics');
});
it('新建后存草稿→createDraft 带展示名/key/空 eip4IdMap,回填 ?modelId= 重载', async () => {
renderPage();
fireEvent.click(await screen.findByTestId('process-modeler-new'));
fireEvent.change(await screen.findByTestId('new-process-name'), { target: { value: '请假审批' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: 'leaveApply' } });
fireEvent.click(screen.getByTestId('new-process-confirm'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
await waitFor(() => expect(saveBtn()).not.toBeDisabled());
fireEvent.click(saveBtn());
await waitFor(() => expect(mCreateDraft).toHaveBeenCalled());
const body = mCreateDraft.mock.calls[0][0];
expect(body.name).toBe('请假审批'); // 展示名(非 key)
expect(body.key).toBe('leaveApply');
expect(JSON.parse(body.metaInfo!).eip4IdMap).toEqual({}); // ASCII key 无还原映射
expect(mFromProcDef).not.toHaveBeenCalled();
// 首存回填 ?modelId=NEW-1 → 按 modelId 重载。
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('NEW-1'));
});
it('新建中文 key→process id 净化为 ASCII,createDraft.metaInfo.eip4IdMap 记录还原映射', async () => {
renderPage();
fireEvent.click(await screen.findByTestId('process-modeler-new'));
fireEvent.change(await screen.findByTestId('new-process-name'), { target: { value: '总包合同交底' } });
fireEvent.change(screen.getByTestId('new-process-key'), { target: { value: '总包合同交底' } });
fireEvent.click(screen.getByTestId('new-process-confirm'));
await waitFor(() => expect(importXMLMock).toHaveBeenCalled());
expect(importXMLMock.mock.calls[0][0] as string).not.toContain('id="总包合同交底"');
await waitFor(() => expect(saveBtn()).not.toBeDisabled());
fireEvent.click(saveBtn());
await waitFor(() => expect(mCreateDraft).toHaveBeenCalled());
const meta = JSON.parse(mCreateDraft.mock.calls[0][0].metaInfo!);
expect(Object.keys(meta.eip4IdMap)).toEqual(['总包合同交底']);
});
});

View File

@@ -0,0 +1,594 @@
// 在线流程 Modeler(B3)——可编辑 BPMN 设计器页。
// T1.5 骨架:admin 门 + 三栏布局 + bpmn-js Modeler + 存量只读载入。
// T2.4:右栏叠 EIP4 定制侧板(办理人/会签/formKey…)。
// T2.5:顶栏「保存草稿」可用(saveXML→create/from-procdef→PUT,metaInfo 带 eip4IdMap);
// 打开器加「草稿」tab(listModels→?modelId=→getModel→importXML)+ 草稿删除。
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import Modeler from 'bpmn-js/lib/Modeler';
import { BpmnPropertiesPanelModule, BpmnPropertiesProviderModule } from 'bpmn-js-properties-panel';
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import '@bpmn-io/properties-panel/dist/assets/properties-panel.css';
import activitiModdle from '../modeler/moddle/activiti.json';
import { getProfile, isAdminProfile } from '../auth/token';
import {
fetchProcDefSource,
fetchProcDefSourceByKey,
fetchProcessOptions,
listModels,
getModel,
createDraft,
saveDraft,
draftFromProcDef,
deleteDraft,
type ProcessOption,
type ModelSummary,
} from '../api/processModeler';
import { Eip4Panel, type PanelModeler } from '../modeler/Eip4Panel';
import { PublishConfirm } from '../modeler/PublishConfirm';
import { NewProcessDialog, type NewProcessResult } from '../modeler/NewProcessDialog';
import { toast } from '../components/ui';
// bpmn-js/lib/Modeler 自带类型,但选项对象里的标准面板模块(本项目无类型)与 moddle JSON
// 会与官方选项类型产生摩擦;照 ProcessDiagram 惯例把构造器收窄为本页用到的最小契约再实例化。
interface ModelerLike {
importXML(xml: string): Promise<unknown>;
saveXML(opts?: { format?: boolean }): Promise<{ xml: string }>;
destroy(): void;
get(service: string): unknown;
on(event: string, cb: (e: unknown) => void): void;
}
const ModelerCtor = Modeler as unknown as new (options: Record<string, unknown>) => ModelerLike;
type LoadState = 'idle' | 'loading' | 'ready' | 'error';
/** 从草稿 metaInfo JSON 串取 eip4IdMap(发布还原用;防御性)。 */
function parseMetaIdMap(metaInfo?: string): Record<string, string> {
if (!metaInfo) return {};
try {
const o = JSON.parse(metaInfo) as { eip4IdMap?: unknown };
return o && typeof o.eip4IdMap === 'object' && o.eip4IdMap
? (o.eip4IdMap as Record<string, string>)
: {};
} catch {
return {};
}
}
export function ProcessModelerPage() {
const profile = getProfile();
const isAdmin = isAdminProfile(profile);
const navigate = useNavigate();
const [params, setParams] = useSearchParams();
// 打开三条路:?procDefId=(source=processDefinition)/ ?procKey=(存量按 key)/ ?modelId=(草稿)。
const procDefId = params.get('procDefId') ?? '';
const procKey = params.get('procKey') ?? '';
const modelIdParam = params.get('modelId') ?? '';
const hasTarget = !!procDefId || !!procKey || !!modelIdParam;
const canvasRef = useRef<HTMLDivElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const modelerRef = useRef<ModelerLike | null>(null);
// Modeler 实例入 state 以驱动 Eip4Panel 重渲染(selection.changed 订阅需要真实例)。
const [modelerReady, setModelerReady] = useState<ModelerLike | null>(null);
// 净化映射 原id→净化id:存量载入时暂存,保存草稿写进 metaInfo、发布还原(T3.x)时用。
const idMapRef = useRef<Record<string, string>>({});
// 当前草稿 modelId(打开草稿或首次保存后写入);空=尚未落草稿。
const modelIdRef = useRef<string>('');
// 当前载入流程的 key(存量 procDefKey / 草稿 key)——新建草稿的 name/key 源。
const loadedKeyRef = useRef<string>('');
// 新建流程的展示名(首存草稿的 name 用;存量/草稿路为空,createDraft 回退用 key)。
const newNameRef = useRef<string>('');
// 打开时的**原始**源 XML(发布影响摘要的 diff 基线:openSource vs 当前 saveXML)。
const openSourceRef = useRef<string>('');
// 基线归属标识:openSourceRef 对应哪个打开目标。存量首存会 setParams(modelId) 触发载入 effect
// 重跑(procKey→modelId),若每次重设基线,则「打开存量→改→存→发布」的 diff(已存版,已存版) 恒空
// (I1)。故首存前把归属预置为新 modelId,effect 见归属未变即**保留原始基线不重置**。
const baselineTargetRef = useRef<string>('');
const [loadState, setLoadState] = useState<LoadState>('idle');
const [loadError, setLoadError] = useState('');
const [saving, setSaving] = useState(false);
// 发布弹窗:非 null 时展示 PublishConfirm,xml=点发布瞬间的 saveXML 结果。
const [publish, setPublish] = useState<{ xml: string } | null>(null);
// 新建流程:对话框开关 + pending 新建(非 null 时无 URL 目标也挂 Modeler 并 import 模板实例化 XML,
// 首存前不落草稿——走 T2.5 createDraft 首存路径)。
const [showNewDialog, setShowNewDialog] = useState(false);
const [newDraft, setNewDraft] = useState<NewProcessResult | null>(null);
const [options, setOptions] = useState<ProcessOption[]>([]);
const [optionsError, setOptionsError] = useState('');
// 打开器 tab:存量流程 / 草稿。
const [openTab, setOpenTab] = useState<'existing' | 'draft'>('existing');
const [drafts, setDrafts] = useState<ModelSummary[]>([]);
const [draftsError, setDraftsError] = useState('');
const [draftsReload, setDraftsReload] = useState(0);
// 未打开任何流程 + 存量 tab 时拉存量流程选项(复用旧 ProcessSelectDialog 端点)。
useEffect(() => {
if (!isAdmin || hasTarget || openTab !== 'existing') return;
let alive = true;
fetchProcessOptions()
.then((opts) => alive && setOptions(opts))
.catch(() => alive && setOptionsError('存量流程列表加载失败'));
return () => {
alive = false;
};
}, [isAdmin, hasTarget, openTab]);
// 未打开任何流程 + 草稿 tab 时拉草稿列表。
useEffect(() => {
if (!isAdmin || hasTarget || openTab !== 'draft') return;
let alive = true;
setDraftsError('');
listModels()
.then((d) => alive && setDrafts(d))
.catch(() => alive && setDraftsError('草稿列表加载失败'));
return () => {
alive = false;
};
}, [isAdmin, hasTarget, openTab, draftsReload]);
// 有目标(或 pending 新建)时挂载 Modeler 并载入 BPMN(草稿→getModel / 存量→source / 新建→模板)。
useEffect(() => {
if (!isAdmin) return;
if (!hasTarget && !newDraft) return;
let alive = true;
let modeler: ModelerLike | null = null;
setLoadState('loading');
setLoadError('');
(async () => {
try {
// 新建流程:无 URL 目标但有 pending newDraft → 直接用模板实例化 XML(无远端取源、无 found 守卫)。
const isNew = !hasTarget && !!newDraft;
let bpmnXml: string;
// 非新建三条路统一成 {found,bpmnXml,idMap,key}。
let src: { found: boolean; bpmnXml?: string; idMap?: Record<string, string>; key?: string } | undefined;
if (isNew) {
bpmnXml = newDraft!.xml;
} else {
if (modelIdParam) {
const m = await getModel(modelIdParam);
src = { found: m.found, bpmnXml: m.bpmnXml, idMap: parseMetaIdMap(m.metaInfo), key: m.key };
} else if (procDefId) {
const s = await fetchProcDefSource(procDefId);
src = { found: s.found, bpmnXml: s.bpmnXml, idMap: s.idMap, key: s.procDefKey };
} else {
const s = await fetchProcDefSourceByKey(procKey);
src = { found: s.found, bpmnXml: s.bpmnXml, idMap: s.idMap, key: s.procDefKey };
}
if (!alive) return;
if (!src.found || !src.bpmnXml) {
setLoadError('未找到该流程的 BPMN 源(可能未部署或无布局信息)');
setLoadState('error');
return;
}
bpmnXml = src.bpmnXml;
}
if (!alive) return;
if (!canvasRef.current) {
// 画布容器缺失(异常时序):明确报错,别停在 loading 无提示(T1.5 评审 M-2)。
setLoadError('画布未就绪,请重试');
setLoadState('error');
return;
}
modeler = new ModelerCtor({
container: canvasRef.current,
propertiesPanel: { parent: panelRef.current },
// ⚠️ 只载标准 BpmnPropertiesProviderModule,严禁引 Camunda provider——它会把
// camunda 描述符注进 moddle,与 activiti 描述符在 bpmn:UserTask 上同名扩展冲突
// (not allowed without redefines) 静默丢弃 userTask(T1.1 评审 M-3 实证)。
additionalModules: [BpmnPropertiesPanelModule, BpmnPropertiesProviderModule],
// ⚠️ moddleExtensions 只声明 activiti:语料 1509/3 两命名空间不混用,双载会因同名
// 扩展属性冲突静默丢弃 userTask;单载 activiti 时 flowable 文档经 moddle lax 往返零丢失。
moddleExtensions: { activiti: activitiModdle },
});
// ⚠️ 显式 attachTo:live 实证——只靠构造参数 propertiesPanel.parent,面板从不挂载。
if (panelRef.current) {
try {
(modeler.get('propertiesPanel') as { attachTo(el: HTMLElement): void }).attachTo(panelRef.current);
} catch {
/* 面板模块缺失 / stub 时忽略 */
}
}
if (isNew) {
// 新建:idMap(中文 key 还原用)/key/名称进 ref,供首存 createDraft;无原始源→diff 基线空。
idMapRef.current = newDraft!.idMap;
loadedKeyRef.current = newDraft!.key;
newNameRef.current = newDraft!.name;
modelIdRef.current = '';
openSourceRef.current = '';
baselineTargetRef.current = 'new:' + newDraft!.key;
} else {
idMapRef.current = src!.idMap ?? {};
loadedKeyRef.current = src!.key ?? '';
newNameRef.current = '';
// diff 基线:仅在**首次打开某目标**时捕获原始源;同目标重跑(含首存后 procKey→modelId
// 的 reload,归属已由 handleSaveDraft 预置成新 modelId)则保留,防 I1 基线被冲成「已存版」。
const openTargetKey = modelIdParam
? 'model:' + modelIdParam
: procDefId
? 'pd:' + procDefId
: 'pk:' + procKey;
if (baselineTargetRef.current !== openTargetKey) {
openSourceRef.current = bpmnXml; // 此处 bpmnXml 已由上方 found 守卫保证非空
baselineTargetRef.current = openTargetKey;
}
// 草稿路:记住 modelId(后续保存走 PUT);存量路:清空(首次保存新建草稿)。
modelIdRef.current = modelIdParam || '';
}
await modeler.importXML(bpmnXml);
if (!alive) return;
modelerRef.current = modeler;
setModelerReady(modeler);
try {
const canvas = modeler.get('canvas') as { zoom(mode: string, point?: string): void };
canvas.zoom('fit-viewport', 'auto');
} catch {
/* stub / 无布局时忽略 */
}
setLoadState('ready');
} catch {
if (alive) {
setLoadError('流程加载失败');
setLoadState('error');
}
}
})();
return () => {
alive = false;
if (modeler) {
try {
modeler.destroy();
} catch {
/* 视图已卸载 */
}
}
modelerRef.current = null;
setModelerReady(null);
};
}, [isAdmin, procDefId, procKey, modelIdParam, newDraft]);
// 保存草稿:saveXML → 有 modelId 走 PUT(不重发 metaInfo,保住 eip4IdMap);
// 无 modelId:存量按 procDefId 走 from-procdef(后端写 metaInfo)再 PUT 覆盖为编辑源;
// 存量按 key / 新建走 create(前端带 eip4IdMap 进 metaInfo)。
async function handleSaveDraft() {
const modeler = modelerRef.current;
if (!modeler || saving) return;
setSaving(true);
try {
const { xml } = await modeler.saveXML({ format: true });
let modelId = modelIdRef.current;
if (modelId) {
await saveDraft(modelId, { bpmnXml: xml });
} else if (procDefId) {
modelId = await draftFromProcDef(procDefId);
await saveDraft(modelId, { bpmnXml: xml });
modelIdRef.current = modelId;
// I1:预置基线归属为新 modelId,使随后的 reload 保留原始源基线(不被冲成「已存版」)。
baselineTargetRef.current = 'model:' + modelId;
// I-2:首存回填 ?modelId=,令刷新幂等(不再重复建草稿)、二次保存恒走 PUT。
setParams({ modelId }, { replace: true });
} else {
const key = loadedKeyRef.current || procKey || 'new_process';
// 新建流程用展示名(newNameRef);存量按 key 无展示名,回退用 key。
const name = newNameRef.current || key;
// metaInfo 结构与 from-procdef 对齐(sourceProcDefId 便于 T3.x 影响摘要/审计,
// 虽 restore 只读 eip4IdMap;新建中文 key 的 idMap 使发布 restore 回中文 process key)。
const metaInfo = JSON.stringify({
eip4IdMap: idMapRef.current,
sourceProcDefId: procDefId || '',
originalKey: key,
});
modelId = await createDraft({ name, key, bpmnXml: xml, metaInfo });
modelIdRef.current = modelId;
// I1:同上,reload 保留原始源基线。
baselineTargetRef.current = 'model:' + modelId;
// 新建首存后清 pending newDraft:随后回填 ?modelId= 触发按 modelId 正常重载(幂等)。
if (newDraft) setNewDraft(null);
setParams({ modelId }, { replace: true });
}
toast('已保存草稿', 'ok');
} catch {
toast('保存草稿失败', 'err');
} finally {
setSaving(false);
}
}
// 发布:需先有草稿(modelId)——未存则提示先存;已存则先把当前编辑器态持久化进草稿,再开确认弹窗。
// I2:后端 deploy 从服务端草稿取源部署,故发布前必须 saveDraft(currentXml),使
// 部署内容 == 预览内容 == diff 的 current 侧(否则「打开草稿→改未存→直接发布」预览≠部署)。
async function handlePublishClick() {
const modeler = modelerRef.current;
if (!modeler || saving) return;
const modelId = modelIdRef.current;
if (!modelId) {
toast('请先保存草稿,再发布', 'warn');
return;
}
try {
const { xml } = await modeler.saveXML({ format: true });
await saveDraft(modelId, { bpmnXml: xml }); // 持久化当前态,保证部署==预览
setPublish({ xml });
} catch {
toast('发布前保存失败,请重试', 'err');
}
}
if (!isAdmin) {
return <div style={{ padding: 24, color: 'var(--text-3)' }}>流程设计器仅管理员可用。</div>;
}
// 可载入 = 有可用打开参数:processDefinition 需 id(procDefId);其余(model/history)需 key。
const loadableOptions = options.filter((o) =>
o.source === 'processDefinition' ? !!o.id : !!o.key,
);
// 选择器按 source 分派:processDefinition→?procDefId=<id>;其余→?procKey=<key>。
function openSelected(indexValue: string) {
if (indexValue === '') return;
const opt = loadableOptions[Number(indexValue)];
if (!opt) return;
if (opt.source === 'processDefinition' && opt.id) {
setParams({ procDefId: opt.id });
} else if (opt.key) {
setParams({ procKey: opt.key });
}
}
function openDraft(id: string) {
setParams({ modelId: id });
}
async function onDeleteDraft(d: ModelSummary) {
if (typeof window !== 'undefined' && !window.confirm(`删除草稿「${d.name || d.key || d.id}」?`)) {
return;
}
try {
await deleteDraft(d.id);
toast('草稿已删除', 'ok');
setDraftsReload((x) => x + 1);
} catch {
toast('删除草稿失败', 'err');
}
}
return (
<div
data-testid="process-modeler-root"
style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}
>
{/* 顶栏 */}
<div
style={{
height: 48,
display: 'flex',
alignItems: 'center',
gap: 12,
padding: '0 16px',
borderBottom: '1px solid var(--line)',
flexShrink: 0,
}}
>
<span style={{ fontWeight: 600, fontSize: 15 }}>流程设计器</span>
<span className="muted" style={{ fontSize: 12, flex: 1 }}>
{hasTarget
? `已打开:${modelIdParam ? '草稿 ' + modelIdParam : procDefId || procKey}`
: newDraft
? `新建流程:${newDraft.name}(${newDraft.key})`
: '在线编辑 BPMN 流程定义(可编辑存量 / 草稿 / 新建)'}
</span>
<button
className="btn btn-sm"
data-testid="process-modeler-save-draft"
disabled={!modelerReady || saving}
onClick={handleSaveDraft}
title="保存为草稿(act_re_model)"
>
{saving ? '保存中…' : '保存草稿'}
</button>
<button
className="btn btn-sm btn-primary"
data-testid="process-modeler-publish"
disabled={!modelerReady || saving}
onClick={handlePublishClick}
title="发布(同人确认 + 影响摘要)"
>
发布
</button>
<button className="btn btn-sm" data-testid="process-modeler-back" onClick={() => navigate('/design-center')}>
返回
</button>
</div>
{/* 主体:左画布 + 右栏(上=EIP4 侧板 / 下=标准属性面板) */}
<div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
<div style={{ flex: 1, position: 'relative', minWidth: 0, background: '#fff' }}>
<div ref={canvasRef} data-testid="process-modeler-canvas" style={{ width: '100%', height: '100%' }} />
{/* 未打开任何流程且无 pending 新建:叠加打开器(存量流程 / 草稿 两 tab) */}
{!hasTarget && !newDraft ? (
<div
style={{
position: 'absolute',
inset: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 12,
background: 'var(--surface, #fff)',
}}
>
<div style={{ display: 'flex', gap: 8 }}>
<button
className={openTab === 'existing' ? 'btn btn-sm btn-primary' : 'btn btn-sm'}
data-testid="process-modeler-tab-existing"
onClick={() => setOpenTab('existing')}
>
存量流程
</button>
<button
className={openTab === 'draft' ? 'btn btn-sm btn-primary' : 'btn btn-sm'}
data-testid="process-modeler-tab-draft"
onClick={() => setOpenTab('draft')}
>
草稿
</button>
</div>
{openTab === 'existing' ? (
<>
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>选择一个存量流程开始编辑</div>
<select
data-testid="process-modeler-open-select"
defaultValue=""
onChange={(e) => openSelected(e.target.value)}
style={{ minWidth: 280, padding: '6px 8px' }}
>
<option value="">打开存量流程…</option>
{loadableOptions.map((o, i) => (
<option key={o.id ?? o.key ?? i} value={i}>
{o.label}
</option>
))}
</select>
{optionsError ? (
<div style={{ color: 'var(--err)', fontSize: 12 }}>{optionsError}</div>
) : null}
<button
className="btn btn-sm"
data-testid="process-modeler-new"
onClick={() => setShowNewDialog(true)}
title="新建流程(空白 / 单人 / 两级 / 会签 模板)"
>
+ 新建流程
</button>
</>
) : (
<div
data-testid="process-modeler-draft-list"
style={{
minWidth: 320,
maxHeight: 320,
overflow: 'auto',
display: 'flex',
flexDirection: 'column',
gap: 4,
}}
>
{drafts.length === 0 ? (
<div style={{ color: 'var(--text-3)', fontSize: 13, textAlign: 'center' }}>暂无草稿</div>
) : (
drafts.map((d, i) => (
<div
key={d.id}
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
padding: '4px 6px',
border: '1px solid var(--line)',
borderRadius: 4,
}}
>
<span style={{ flex: 1, minWidth: 0, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{d.name || d.key || d.id}
</span>
<button
className="btn btn-sm"
data-testid={`process-modeler-draft-open-${i}`}
onClick={() => openDraft(d.id)}
>
打开
</button>
<button
className="btn btn-sm"
data-testid={`process-modeler-draft-delete-${i}`}
onClick={() => onDeleteDraft(d)}
>
删除
</button>
</div>
))
)}
{draftsError ? (
<div style={{ color: 'var(--err)', fontSize: 12 }}>{draftsError}</div>
) : null}
</div>
)}
</div>
) : null}
{/* 载入中 / 载入失败 */}
{hasTarget && loadState === 'loading' ? (
<div style={overlayMsgStyle('var(--text-3)')} data-testid="process-modeler-loading">
加载流程中…
</div>
) : null}
{hasTarget && loadState === 'error' ? (
<div style={overlayMsgStyle('var(--warn, #d48806)')} data-testid="process-modeler-error">
{loadError}
</div>
) : null}
</div>
<div
style={{
width: 360,
flexShrink: 0,
borderLeft: '1px solid var(--line)',
display: 'flex',
flexDirection: 'column',
minHeight: 0,
}}
>
{/* EIP4 定制侧板(办理人/会签/formKey/扩展属性/监听器)——选中 userTask 时叠加 */}
<Eip4Panel modeler={modelerReady as unknown as PanelModeler | null} />
{/* 标准属性面板宿主(bpmn-js-properties-panel attachTo 进此容器) */}
<div ref={panelRef} data-testid="process-modeler-props" style={{ flex: 1, overflow: 'auto', minHeight: 0 }} />
</div>
</div>
{/* 新建流程对话框(名称/key/模板 → 实例化模板进入编辑态,首存前不落草稿) */}
{showNewDialog ? (
<NewProcessDialog
onClose={() => setShowNewDialog(false)}
onConfirm={(r) => {
setShowNewDialog(false);
setNewDraft(r); // 触发挂载 effect:importXML(模板实例化 XML) + 清空 diff 基线
}}
/>
) : null}
{/* 同人确认发布弹窗(影响摘要 + 节点级 diff + 422 校验清单) */}
{publish && modelIdRef.current ? (
<PublishConfirm
modelId={modelIdRef.current}
openSourceXml={openSourceRef.current}
currentXml={publish.xml}
processKeyHint={loadedKeyRef.current}
onClose={() => setPublish(null)}
onPublished={() => setPublish(null)}
/>
) : null}
</div>
);
}
function overlayMsgStyle(color: string): React.CSSProperties {
return {
position: 'absolute',
top: 16,
left: 16,
padding: '8px 12px',
background: 'rgba(255,255,255,0.92)',
borderRadius: 4,
color,
fontSize: 13,
};
}

View File

@@ -0,0 +1,178 @@
#!/usr/bin/env node
/**
* 语料级办理人/会签表达式 codec 往返核查(T2.3 评审加分项)
*
* 对本地 eip4 库(5433, search_path=eip3)里 act_ge_bytearray 的全部真实 BPMN,抽出每个
* activiti/flowable 的 candidateUsers / collection 属性值(实体解码到 businessObject 属性
* 值层),跑与 src/modeler/candidateExpression.ts **逐字镜像**的 parse/build,统计:
* - byteIdentical : build(parse(x)) === x 逐字一致
* - engineEquiv : 非逐字但引擎运行期等价(整串全局 【→{ 、】→} 还原后相同)
* —— 覆盖 content 用半角 ${users} 的 scriptUser 会签变体(build 归一为全角,
* 引擎 CandidateUsersHandler:54 全局替换后复原,语义无损)
* - parseNull : 前缀匹配但解析失败(硬失败)
* - hardMismatch : 既非逐字亦非引擎等价(硬失败)
*
* ⚠️ 本文件内联的 parse/build 必须与 candidateExpression.ts 保持一致;单测
* (candidateExpression.test.ts)是编解码契约的权威来源,本工具是全语料回归的旁证。
*
* 取数:psql 子进程(不引 pg 依赖),同 tools/modeler-fidelity-sweep.mjs。
* 用法:node tools/codec-corpus-sweep.mjs
* 环境变量:PG_HOST(localhost) PG_PORT(5433) PG_DB(eip4) PG_SCHEMA(eip3) EXPECTED_TOTAL(1512)
*/
import { execFileSync } from 'node:child_process';
const PG_HOST = process.env.PG_HOST || 'localhost';
const PG_PORT = process.env.PG_PORT || '5433';
const PG_DB = process.env.PG_DB || 'eip4';
const PG_SCHEMA = process.env.PG_SCHEMA || 'eip3';
const EXPECTED_TOTAL = Number(process.env.EXPECTED_TOTAL || 1512);
// ── 镜像 src/modeler/candidateExpression.ts(逐字)────────────────────────────
const CANDIDATE_PREFIX = "${candidateUsersHandler.getCandidateUsers(execution,'";
const MULTI_PREFIX = "${multiInstanceUsersHandler.getUsers(execution,'";
const SUFFIX = "')}";
const KNOWN_ITEM_KEYS = ['type', 'content', 'isCandidate', 'isSendMail', 'isSendPhone', 'isSendMessage'];
const KNOWN_ITEM_KEY_SET = new Set(KNOWN_ITEM_KEYS);
const fullToHalf = (s) => s.split('【').join('{').split('】').join('}');
const halfToFull = (s) => s.split('{').join('【').split('}').join('】');
const escapeLeaf = (v) => v.split("'").join('‘').split('"').join('“');
function reorderItem(src) {
const o = {};
for (const k of KNOWN_ITEM_KEYS) if (src[k] !== undefined) o[k] = src[k];
for (const k of Object.keys(src)) if (!KNOWN_ITEM_KEY_SET.has(k) && src[k] !== undefined) o[k] = src[k];
return o;
}
function parse(expr) {
if (typeof expr !== 'string' || expr.length === 0) return null;
let variant, prefix;
if (expr.startsWith(CANDIDATE_PREFIX)) { variant = 'candidate'; prefix = CANDIDATE_PREFIX; }
else if (expr.startsWith(MULTI_PREFIX)) { variant = 'multiInstance'; prefix = MULTI_PREFIX; }
else return null;
if (!expr.endsWith(SUFFIX)) return null;
const content = expr.slice(prefix.length, expr.length - SUFFIX.length);
let obj;
try { obj = JSON.parse(fullToHalf(content)); } catch { return null; }
if (obj === null || typeof obj !== 'object') return null;
if (!Array.isArray(obj.items)) return null;
for (const el of obj.items) {
if (el === null || typeof el !== 'object' || Array.isArray(el)) return null;
if (typeof el.type !== 'string') return null;
}
const items = obj.items.map(reorderItem);
const meta = { ...obj };
delete meta.items;
return { items, variant, meta };
}
function build(items, variant, meta) {
const prefix = variant === 'multiInstance' ? MULTI_PREFIX : CANDIDATE_PREFIX;
const outer = { items: items.map(reorderItem), ...(meta ?? {}) };
const json = JSON.stringify(outer, (_k, v) => (typeof v === 'string' ? escapeLeaf(v) : v));
return prefix + halfToFull(json) + SUFFIX;
}
// 镜像引擎 CandidateUsersHandler:54 的整串全局字面替换
const engineRestore = (s) => s.split('【').join('{').split('】').join('}');
// ─────────────────────────────────────────────────────────────────────────
function decodeEntities(s) {
return String(s)
.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10)))
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&');
}
function pullCorpus() {
const sql =
`set search_path=${PG_SCHEMA},public; ` +
`select b.id_||'|'||translate(encode(b.bytes_,'base64'),E'\\n','') ` +
`from act_ge_bytearray b where b.name_ like '%.bpmn%' or b.name_ like '%.xml';`;
const out = execFileSync(
'psql',
['-h', PG_HOST, '-p', PG_PORT, '-d', PG_DB, '-tA', '-c', sql],
{ encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024 },
);
const docs = [];
for (const line of out.split('\n')) {
if (!line) continue;
const i = line.indexOf('|');
if (i < 0) continue;
docs.push({ id: line.slice(0, i), b64: line.slice(i + 1) });
}
return docs;
}
function main() {
process.stdout.write(`连库拉取语料 (${PG_HOST}:${PG_PORT}/${PG_DB}, schema=${PG_SCHEMA}) ...\n`);
const docs = pullCorpus();
process.stdout.write(`取到 ${docs.length} 个 .bpmn/.xml 文档,开始 codec 往返扫描 ...\n\n`);
const EXPR_RE = /(?:activiti|flowable):(?:candidateUsers|collection)="([^"]*)"/g;
let exprs = 0;
let byteIdentical = 0;
let engineEquiv = 0;
let parseNull = 0;
let hardMismatch = 0;
const itemKeySets = new Map();
const metaKeySets = new Map();
const hardSamples = [];
const parseNullSamples = [];
for (const doc of docs) {
const xml = Buffer.from(doc.b64, 'base64').toString('utf8');
let m;
EXPR_RE.lastIndex = 0;
while ((m = EXPR_RE.exec(xml)) !== null) {
const val = decodeEntities(m[1]);
if (!val.includes('Handler')) continue; // collection 也可是普通变量名,非 handler 表达式
exprs++;
const r = parse(val);
if (!r) {
parseNull++;
if (parseNullSamples.length < 5) parseNullSamples.push(val.slice(0, 200));
continue;
}
for (const it of r.items) itemKeySets.set(Object.keys(it).join(','), (itemKeySets.get(Object.keys(it).join(',')) || 0) + 1);
metaKeySets.set(Object.keys(r.meta).join(','), (metaKeySets.get(Object.keys(r.meta).join(',')) || 0) + 1);
const rebuilt = build(r.items, r.variant, r.meta);
if (rebuilt === val) byteIdentical++;
else if (engineRestore(rebuilt) === engineRestore(val)) engineEquiv++;
else {
hardMismatch++;
if (hardSamples.length < 5) hardSamples.push({ val: val.slice(0, 300), rebuilt: rebuilt.slice(0, 300) });
}
}
}
const line = '─'.repeat(60);
process.stdout.write(`${line}\ncodec 往返扫描结果\n${line}\n`);
process.stdout.write(`总文档 ${docs.length}(预期 ${EXPECTED_TOTAL})|表达式 ${exprs}\n`);
process.stdout.write(`逐字一致 ${byteIdentical}|引擎运行期等价 ${engineEquiv}|解析失败 ${parseNull}|硬不匹配 ${hardMismatch}\n`);
process.stdout.write(`\nitem 键集分布:\n`);
for (const [k, c] of [...itemKeySets].sort((a, b) => b[1] - a[1])) process.stdout.write(` ${c.toString().padStart(6)} [${k}]\n`);
process.stdout.write(`\nmeta 键集分布:\n`);
for (const [k, c] of [...metaKeySets].sort((a, b) => b[1] - a[1])) process.stdout.write(` ${c.toString().padStart(6)} [${k || '(空)'}]\n`);
if (parseNullSamples.length) {
process.stdout.write(`\n解析失败样本:\n`);
for (const s of parseNullSamples) process.stdout.write(` ${s}\n`);
}
if (hardSamples.length) {
process.stdout.write(`\n硬不匹配样本(既非逐字亦非引擎等价):\n`);
for (const s of hardSamples) process.stdout.write(` 原文: ${s.val}\n 重建: ${s.rebuilt}\n`);
}
process.stdout.write(`${line}\n`);
// 硬门:每条表达式都能解析,且要么逐字要么引擎等价(无硬失败),且语料规模符合预期。
const gateOk = parseNull === 0 && hardMismatch === 0 && docs.length === EXPECTED_TOTAL;
process.exit(gateOk ? 0 : 1);
}
try {
main();
} catch (e) {
if (e && e.stderr) process.stderr.write(String(e.stderr));
process.stderr.write(`扫描崩溃: ${(e && e.stack) || e}\n`);
process.exit(2);
}

View File

@@ -0,0 +1,325 @@
#!/usr/bin/env node
/**
* 全量真实流程 moddle round-trip 保真扫描(Task 1.2)
*
* 对本地 eip4 库(5433, search_path=eip3)里 act_ge_bytearray 的全部真实 BPMN
* (name_ like %.bpmn% / %.xml)逐条做 bpmn-moddle fromXML→toXML 往返,验证
* 「所有 activiti / flowable 扩展属性(含值,实体解码归一后) + 扩展元素结构
* + 全部 bpmn 元素 id 集合」在往返前后多重集一致(数据级零丢失,非字节级)。
*
* 取数:psql 子进程(不引 pg 依赖);命名空间嗅探后单载 activiti 或 flowable
* (T1.1 实证:双载会因跨包同名 extends 冲突丢 userTask)。进 moddle 前先净化
* 中文/非法 id(镜像后端 ProcessDiagramController.sanitizeBpmnIds;moddle-xml
* 拒绝非 ASCII-NCName id,1445/1512 文档 process id 为中文)。
*
* 用法:node tools/modeler-fidelity-sweep.mjs
* 环境变量:PG_HOST(localhost) PG_PORT(5433) PG_DB(eip4) PG_SCHEMA(eip3)
*/
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import BpmnModdle from 'bpmn-moddle';
const HERE = dirname(fileURLToPath(import.meta.url));
const activiti = JSON.parse(readFileSync(resolve(HERE, '../src/modeler/moddle/activiti.json'), 'utf8'));
const flowable = JSON.parse(readFileSync(resolve(HERE, '../src/modeler/moddle/flowable.json'), 'utf8'));
const PG_HOST = process.env.PG_HOST || 'localhost';
const PG_PORT = process.env.PG_PORT || '5433';
const PG_DB = process.env.PG_DB || 'eip4';
const PG_SCHEMA = process.env.PG_SCHEMA || 'eip3';
// ── 取数:psql 拉 id|name|base64(base64 去换行,同勘探法)───────────────────
function pullCorpus() {
const sql =
`set search_path=${PG_SCHEMA},public; ` +
`select b.id_||'|'||b.name_||'|'||translate(encode(b.bytes_,'base64'),E'\\n','') ` +
`from act_ge_bytearray b where b.name_ like '%.bpmn%' or b.name_ like '%.xml';`;
const out = execFileSync(
'psql',
['-h', PG_HOST, '-p', PG_PORT, '-d', PG_DB, '-tA', '-c', sql],
{ encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024 },
);
const docs = [];
for (const line of out.split('\n')) {
if (!line) continue;
const i1 = line.indexOf('|');
const i2 = line.indexOf('|', i1 + 1);
if (i1 < 0 || i2 < 0) continue;
docs.push({ id: line.slice(0, i1), name: line.slice(i1 + 1, i2), b64: line.slice(i2 + 1) });
}
return docs;
}
// ── XML 实体解码归一(数据级比对:&quot;→" &#34;→" 全角/中文原样)────────────
function decodeEntities(s) {
return String(s)
.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(parseInt(h, 16)))
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10)))
.replace(/&quot;/g, '"')
.replace(/&apos;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&'); // amp 最后解,避免 &amp;#34; 被二次解码
}
// ── id 净化:镜像 ProcessDiagramController.sanitizeBpmnIds(可逆非本工具关注)─
// 安全 id = ASCII-NCName(首字符字母/下划线,其余字母/数字/_/-/.)。非法则映射为
// 稳定唯一占位符(本工具用无冲突计数器,隔离 T1.3 哈希碰撞与 moddle 保真两问题)。
const ID_ATTR = /\b(id|bpmnElement|sourceRef|targetRef|attachedToRef|processRef|default)\s*=\s*"([^"]+)"/g;
function isSafeId(v) {
return /^[A-Za-z_][A-Za-z0-9_.-]*$/.test(v);
}
function sanitizeIds(xml) {
const map = new Map();
let n = 0;
let m;
ID_ATTR.lastIndex = 0;
while ((m = ID_ATTR.exec(xml))) {
const val = m[2];
if (!isSafeId(val) && !map.has(val)) map.set(val, `sanid_${n++}`);
}
if (map.size === 0) return { xml, remapped: 0 };
ID_ATTR.lastIndex = 0;
const rewritten = xml.replace(ID_ATTR, (_, attr, val) => `${attr}="${map.get(val) ?? val}"`);
return { xml: rewritten, remapped: map.size };
}
// ── 命名空间嗅探:activiti 优先,其次 flowable,默认 activiti ─────────────────
// M3 前提:靠字面量 uri/前缀识别命名空间,依赖语料使用规范前缀 activiti/flowable。
// §0 实测本库确如此(activiti 1509 / flowable 3,无自定义前缀重映射),故成立;
// 若未来语料出现 xmlns:act="http://activiti.org/bpmn" 之类别名,此处需扩正则。
function sniffModdle(xml) {
const hasActiviti = xml.includes('activiti.org/bpmn') || /\bactiviti:/.test(xml);
const hasFlowable = xml.includes('flowable.org/bpmn') || /\bflowable:/.test(xml);
if (hasActiviti) return { pkg: { activiti }, ns: 'activiti' };
if (hasFlowable) return { pkg: { flowable }, ns: 'flowable' };
return { pkg: { activiti }, ns: 'activiti(default)' };
}
// ── 扩展面「多重集」签名:数据级零丢失的比对基础 ───────────────────────────
// 逐 tag 扫描(well-formed BPMN 下正则足够),区分扩展元素 tag / 原生元素上的
// 扩展属性;文本单独扫;id 全量。所有值实体解码后入袋(顺序无关)。
const TAG_RE = /<([/!?]?)([\w:.-]+)((?:[^>"']|"[^"]*"|'[^']*')*)>/g;
const ATTR_RE = /([\w:.-]+)\s*=\s*"([^"]*)"/g;
const EXT_TEXT_RE = /<((?:activiti|flowable):[\w.-]+)((?:[^>"']|"[^"]*"|'[^']*')*)>([^<]*)<\//g;
// I1:引用类属性单独入袋,捕捉 round-trip/净化重写破坏的连线(sourceRef/targetRef/
// bpmnElement/processRef/attachedToRef/default)。与 sanitizeIds 的 ID_ATTR 同覆盖面。
const REF_ATTRS = new Set(['sourceRef', 'targetRef', 'bpmnElement', 'processRef', 'attachedToRef', 'default']);
function surface(xml) {
const extAttrs = []; // 原生元素上的 activiti:/flowable: 属性 p:name=value
const extElemTags = []; // 扩展元素本身 tag
const extElemAttrs = [];// 扩展元素上的属性(含无前缀) tag@attr=value
const extElemText = []; // 扩展叶元素的文本 tag#text=value
const ids = []; // 全部 id="..."(含原生/DI/扩展)
const refs = []; // 引用类属性 an=value(连线/DI 指向完整性,I1)
let m;
TAG_RE.lastIndex = 0;
while ((m = TAG_RE.exec(xml))) {
const close = m[1];
const name = m[2];
const attrBlob = m[3] || '';
if (close === '/' || close === '!' || close === '?') continue; // 闭合/注释/声明
const isExt = /^(activiti|flowable):/.test(name);
let a;
ATTR_RE.lastIndex = 0;
while ((a = ATTR_RE.exec(attrBlob))) {
const an = a[1];
const av = decodeEntities(a[2]);
if (an === 'id') ids.push(av);
else if (REF_ATTRS.has(an)) refs.push(`${an}=${av}`);
if (isExt) {
extElemAttrs.push(`${name}@${an}=${av}`);
} else if (/^(activiti|flowable):/.test(an)) {
extAttrs.push(`${an}=${av}`);
}
}
if (isExt) extElemTags.push(name);
}
// M4:extElemText 对叶元素文本做 trim 归一(去两端空白),故不比对纯空白/缩进差异。
// 扩展叶文本(监听器 field 值、表单选项 name 等)非空白敏感,且前后同样 trim,对称无偏。
EXT_TEXT_RE.lastIndex = 0;
while ((m = EXT_TEXT_RE.exec(xml))) {
const t = decodeEntities(m[3]).trim();
if (t) extElemText.push(`${m[1]}#text=${t}`);
}
return { extAttrs, extElemTags, extElemAttrs, extElemText, ids, refs };
}
function bag(arr) {
const b = new Map();
for (const v of arr) b.set(v, (b.get(v) || 0) + 1);
return b;
}
// 多重集差异:返回 {missing:[...], added:[...]}(before→after)
function diffBag(before, after) {
const b = bag(before);
const a = bag(after);
const missing = [];
const added = [];
for (const [k, c] of b) {
const ac = a.get(k) || 0;
if (ac < c) missing.push(`${k} (×${c - ac})`);
}
for (const [k, c] of a) {
const bc = b.get(k) || 0;
if (bc < c) added.push(`${k} (×${c - bc})`);
}
return { missing, added };
}
// ── 主流程 ───────────────────────────────────────────────────────────────
async function main() {
process.stdout.write(`连库拉取语料 (${PG_HOST}:${PG_PORT}/${PG_DB}, schema=${PG_SCHEMA}) ...\n`);
const docs = pullCorpus();
process.stdout.write(`取到 ${docs.length} 个 .bpmn/.xml 文档,开始 round-trip 扫描 ...\n\n`);
let ok = 0;
const failures = [];
const decodeFailures = [];
const parseErrors = [];
const warnCounts = new Map(); // 归一 warning key → 次数
const nsCounts = new Map();
for (const doc of docs) {
// 1) base64 → UTF8,并校验解码无损(非法 UTF8 会 toString 回落 U+FFFD)
const buf = Buffer.from(doc.b64, 'base64');
const xml = buf.toString('utf8');
if (!Buffer.from(xml, 'utf8').equals(buf)) {
decodeFailures.push({ id: doc.id, name: doc.name, bytes: buf.length });
continue;
}
// 2) 命名空间嗅探 → 单载
const { pkg, ns } = sniffModdle(xml);
nsCounts.set(ns, (nsCounts.get(ns) || 0) + 1);
// 3) 净化非法 id(否则中文 id 文档被 moddle 整体拒收)
const { xml: sanitized } = sanitizeIds(xml);
// 4) round-trip
let out;
let warnings = [];
try {
const moddle = new BpmnModdle(pkg);
const parsed = await moddle.fromXML(sanitized);
warnings = parsed.warnings || [];
const exported = await moddle.toXML(parsed.rootElement, { format: false });
out = exported.xml;
} catch (e) {
parseErrors.push({ id: doc.id, name: doc.name, error: String(e && e.message || e) });
continue;
}
const unresolvedRefs = [];
for (const w of warnings) {
const msg = String(w && w.message || w);
const key = normWarn(msg);
warnCounts.set(key, (warnCounts.get(key) || 0) + 1);
if (key === 'unresolved reference') {
const mr = msg.match(/unresolved reference <([^>]+)>/i);
unresolvedRefs.push(mr ? mr[1] : msg.slice(0, 60));
}
}
// 5) 数据级零丢失比对:sanitized(前) vs out(后)
const before = surface(sanitized);
const after = surface(out);
const diffs = {};
let lost = false;
for (const k of ['extAttrs', 'extElemTags', 'extElemAttrs', 'extElemText', 'ids', 'refs']) {
const d = diffBag(before[k], after[k]);
if (d.missing.length || d.added.length) {
diffs[k] = d;
lost = true;
}
}
// I1②:未解析引用计入硬门(净化/往返破坏连线的直接信号,不再只当 warning)
if (lost || unresolvedRefs.length) {
failures.push({ id: doc.id, name: doc.name, ns, diffs, unresolved: unresolvedRefs });
} else {
ok++;
}
}
const expectedTotal = Number(process.env.EXPECTED_TOTAL || 1512);
report({ total: docs.length, ok, failures, decodeFailures, parseErrors, warnCounts, nsCounts, expectedTotal });
// 硬门:真实 BPMN 全部零丢失 + 无解析异常 + 无解码失败 + 语料规模符合预期。
// (M2:解码失败与规模不符均判失败——过滤集内本应 100% 干净 UTF8,且恒 EXPECTED_TOTAL 篇)
const gateOk =
failures.length === 0 &&
parseErrors.length === 0 &&
decodeFailures.length === 0 &&
docs.length === expectedTotal;
process.exit(gateOk ? 0 : 1);
}
// warning 归一:抽取属性/元素名做聚合键
function normWarn(msg) {
const mAttr = msg.match(/unknown (?:type|attribute) <([^>]+)>/i);
if (mAttr) return `unknown <${mAttr[1]}>`;
const mUn = msg.match(/unparsable content <([^>]+)>/i);
if (mUn) return `unparsable <${mUn[1]}>`;
const mRef = msg.match(/unresolved reference <([^>]+)>/i);
if (mRef) return 'unresolved reference';
return msg.replace(/<[^>]*>/g, '<…>').slice(0, 80);
}
function report(r) {
const line = '─'.repeat(60);
process.stdout.write(`${line}\n保真扫描结果\n${line}\n`);
process.stdout.write(`匹配 ${r.ok}/${r.total} 零丢失(真实 BPMN)\n`);
process.stdout.write(`总文档 ${r.total}(预期 ${r.expectedTotal})|零丢失 ${r.ok}|丢失 ${r.failures.length}|解析异常 ${r.parseErrors.length}|解码失败 ${r.decodeFailures.length}\n`);
if (r.total !== r.expectedTotal) {
process.stdout.write(`⚠ 语料规模 ${r.total} ≠ 预期 ${r.expectedTotal}(EXPECTED_TOTAL)→ 判失败\n`);
}
process.stdout.write(`\n命名空间加载分布:\n`);
for (const [ns, c] of [...r.nsCounts].sort((a, b) => b[1] - a[1])) {
process.stdout.write(` ${ns}: ${c}\n`);
}
process.stdout.write(`\nfromXML warnings(按归一键聚合,仅描述符覆盖信号,不判失败):\n`);
const ws = [...r.warnCounts].sort((a, b) => b[1] - a[1]);
if (!ws.length) process.stdout.write(' (无)\n');
for (const [k, c] of ws.slice(0, 40)) process.stdout.write(` ${c.toString().padStart(6)} ${k}\n`);
if (ws.length > 40) process.stdout.write(` … 另有 ${ws.length - 40} 类\n`);
if (r.decodeFailures.length) {
process.stdout.write(`\nbase64→UTF8 解码失败文档(单列,非 UTF8 BPMN):\n`);
for (const d of r.decodeFailures) process.stdout.write(` id=${d.id} name=${d.name} bytes=${d.bytes}\n`);
}
if (r.parseErrors.length) {
process.stdout.write(`\nmoddle 解析/序列化异常:\n`);
for (const e of r.parseErrors.slice(0, 30)) process.stdout.write(` id=${e.id} name=${e.name}\n ${e.error}\n`);
}
if (r.failures.length) {
process.stdout.write(`\n零丢失失败清单(round-trip 前后扩展面差异):\n`);
for (const f of r.failures.slice(0, 30)) {
process.stdout.write(` id=${f.id} name=${f.name} [${f.ns}]\n`);
for (const [k, d] of Object.entries(f.diffs)) {
if (d.missing.length) process.stdout.write(` ${k} 丢失: ${d.missing.slice(0, 6).join(' ; ')}${d.missing.length > 6 ? ' …' : ''}\n`);
if (d.added.length) process.stdout.write(` ${k} 新增: ${d.added.slice(0, 6).join(' ; ')}${d.added.length > 6 ? ' …' : ''}\n`);
}
if (f.unresolved && f.unresolved.length) {
process.stdout.write(` 未解析引用(I1): ${f.unresolved.slice(0, 6).join(' ; ')}${f.unresolved.length > 6 ? ' …' : ''}\n`);
}
}
if (r.failures.length > 30) process.stdout.write(` … 另有 ${r.failures.length - 30} 个失败文档\n`);
}
process.stdout.write(`${line}\n`);
}
main().catch((e) => {
// M5:psql 等子进程失败时把其 stderr 透出来(execFileSync 把 stderr 挂在 e.stderr)
if (e && e.stderr) process.stderr.write(String(e.stderr));
process.stderr.write(`扫描崩溃: ${e && e.stack || e}\n`);
process.exit(2);
});

View File

@@ -8,6 +8,7 @@
"moduleResolution": "bundler", "moduleResolution": "bundler",
"allowImportingTsExtensions": true, "allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"moduleDetection": "force", "moduleDetection": "force",
"noEmit": true, "noEmit": true,