Compare commits
8 Commits
ac5ab12574
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 821b79c9d8 | |||
| 3808011c8c | |||
| 54b0200ac0 | |||
| 2477f67afe | |||
| ad8f63cf93 | |||
| 8ea0ef2f1e | |||
| 0428a5c9d1 | |||
| 406f053ec2 |
264
e2e/process-modeler.spec.ts
Normal file
264
e2e/process-modeler.spec.ts
Normal 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);
|
||||||
|
});
|
||||||
36
playwright.process-modeler.config.ts
Normal file
36
playwright.process-modeler.config.ts
Normal 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,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -223,6 +223,146 @@ export async function deleteDraft(id: string): Promise<void> {
|
|||||||
await http.delete(`/api/workflow/models/${encodeURIComponent(id)}`);
|
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 信封,防御性返回数组)。 */
|
/** GET /api/process-select/options —— 取存量流程选项(解 amis 信封,防御性返回数组)。 */
|
||||||
export async function fetchProcessOptions(q?: string): Promise<ProcessOption[]> {
|
export async function fetchProcessOptions(q?: string): Promise<ProcessOption[]> {
|
||||||
const { data } = await http.get<ProcessSelectEnvelope>('/api/process-select/options', {
|
const { data } = await http.get<ProcessSelectEnvelope>('/api/process-select/options', {
|
||||||
|
|||||||
@@ -513,8 +513,8 @@ describe('Eip4Panel — 扩展属性(长尾 $attrs)', () => {
|
|||||||
describe('Eip4Panel — 任务监听器(taskListener)', () => {
|
describe('Eip4Panel — 任务监听器(taskListener)', () => {
|
||||||
it('增:新监听器写回 extensionElements,并保留已有监听器的 field(引用不动)', async () => {
|
it('增:新监听器写回 extensionElements,并保留已有监听器的 field(引用不动)', async () => {
|
||||||
const { modeler, updateProperties, moddle, select } = makeModeler();
|
const { modeler, updateProperties, moddle, select } = makeModeler();
|
||||||
const fieldObj = moddleEl('activiti:field', { name: 'mailTemplate' });
|
const fieldObj = moddleEl('activiti:Field', { name: 'mailTemplate' });
|
||||||
const existing = moddleEl('activiti:taskListener', {
|
const existing = moddleEl('activiti:TaskListener', {
|
||||||
event: 'complete',
|
event: 'complete',
|
||||||
class: 'com.dsasp.server.wf.user.listener.TaskCompleteListener',
|
class: 'com.dsasp.server.wf.user.listener.TaskCompleteListener',
|
||||||
fields: [fieldObj],
|
fields: [fieldObj],
|
||||||
@@ -543,14 +543,14 @@ describe('Eip4Panel — 任务监听器(taskListener)', () => {
|
|||||||
fireEvent.change(screen.getByTestId('eip4-listener-event-0'), { target: { value: 'assignment' } });
|
fireEvent.change(screen.getByTestId('eip4-listener-event-0'), { target: { value: 'assignment' } });
|
||||||
fireEvent.change(screen.getByTestId('eip4-listener-value-0'), { target: { value: 'com.X.Listener' } });
|
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 ext = lastPayload(updateProperties).extensionElements as { values: Array<Record<string, unknown>> };
|
||||||
const listener = ext.values.find((v) => v.$type === 'activiti:taskListener')!;
|
const listener = ext.values.find((v) => v.$type === 'activiti:TaskListener')!;
|
||||||
expect(listener.event).toBe('assignment');
|
expect(listener.event).toBe('assignment');
|
||||||
expect(listener.class).toBe('com.X.Listener');
|
expect(listener.class).toBe('com.X.Listener');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('删:移除唯一监听器 → extensionElements=undefined', async () => {
|
it('删:移除唯一监听器 → extensionElements=undefined', async () => {
|
||||||
const { modeler, updateProperties, select } = makeModeler();
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
const existing = moddleEl('activiti:taskListener', { event: 'create', class: 'com.X' });
|
const existing = moddleEl('activiti:TaskListener', { event: 'create', class: 'com.X' });
|
||||||
render(<Eip4Panel modeler={modeler} />);
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
await select(userTask({ extensionElements: { values: [existing] } }));
|
await select(userTask({ extensionElements: { values: [existing] } }));
|
||||||
fireEvent.click(screen.getByTestId('eip4-listener-remove-0'));
|
fireEvent.click(screen.getByTestId('eip4-listener-remove-0'));
|
||||||
@@ -569,7 +569,7 @@ describe('Eip4Panel — 任务监听器(taskListener)', () => {
|
|||||||
});
|
});
|
||||||
fireEvent.change(screen.getByTestId('eip4-listener-value-0'), { target: { value: '${bean}' } });
|
fireEvent.change(screen.getByTestId('eip4-listener-value-0'), { target: { value: '${bean}' } });
|
||||||
const ext = lastPayload(updateProperties).extensionElements as { values: Array<Record<string, unknown>> };
|
const ext = lastPayload(updateProperties).extensionElements as { values: Array<Record<string, unknown>> };
|
||||||
const listener = ext.values.find((v) => v.$type === 'activiti:taskListener')!;
|
const listener = ext.values.find((v) => v.$type === 'activiti:TaskListener')!;
|
||||||
expect(listener.delegateExpression).toBe('${bean}');
|
expect(listener.delegateExpression).toBe('${bean}');
|
||||||
expect('class' in listener).toBe(false);
|
expect('class' in listener).toBe(false);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -385,10 +385,13 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
|
|||||||
// 任务监听器
|
// 任务监听器
|
||||||
const extEl = bo.get('extensionElements') as { values?: unknown[] } | undefined;
|
const extEl = bo.get('extensionElements') as { values?: unknown[] } | undefined;
|
||||||
const values = (extEl?.values ?? []) as unknown[];
|
const values = (extEl?.values ?? []) as unknown[];
|
||||||
otherExtRef.current = values.filter((v) => (v as { $type?: string }).$type !== 'activiti:taskListener');
|
// 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(
|
setListeners(
|
||||||
values
|
values
|
||||||
.filter((v) => (v as { $type?: string }).$type === 'activiti:taskListener')
|
.filter((v) => (v as { $type?: string }).$type === 'activiti:TaskListener')
|
||||||
.map((v) => {
|
.map((v) => {
|
||||||
const cls = mget(v, 'class') as string | undefined;
|
const cls = mget(v, 'class') as string | undefined;
|
||||||
const del = mget(v, 'delegateExpression') as string | undefined;
|
const del = mget(v, 'delegateExpression') as string | undefined;
|
||||||
@@ -499,7 +502,7 @@ export function Eip4Panel({ modeler }: { modeler: PanelModeler | null }) {
|
|||||||
const props: Record<string, unknown> = { event: l.event };
|
const props: Record<string, unknown> = { event: l.event };
|
||||||
props[l.mode] = l.value;
|
props[l.mode] = l.value;
|
||||||
if (l.fields && l.fields.length) props.fields = l.fields;
|
if (l.fields && l.fields.length) props.fields = l.fields;
|
||||||
return moddle.create('activiti:taskListener', props);
|
return moddle.create('activiti:TaskListener', props);
|
||||||
});
|
});
|
||||||
const all = [...otherExtRef.current, ...listenerEls];
|
const all = [...otherExtRef.current, ...listenerEls];
|
||||||
const extEl = all.length ? moddle.create('bpmn:ExtensionElements', { values: all }) : undefined;
|
const extEl = all.length ? moddle.create('bpmn:ExtensionElements', { values: all }) : undefined;
|
||||||
|
|||||||
94
src/modeler/NewProcessDialog.test.tsx
Normal file
94
src/modeler/NewProcessDialog.test.tsx
Normal 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();
|
||||||
|
});
|
||||||
|
});
|
||||||
113
src/modeler/NewProcessDialog.tsx
Normal file
113
src/modeler/NewProcessDialog.tsx
Normal 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' };
|
||||||
139
src/modeler/PublishConfirm.test.tsx
Normal file
139
src/modeler/PublishConfirm.test.tsx
Normal 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(
|
||||||
|
'"type":"position"',
|
||||||
|
'"type":"user"',
|
||||||
|
);
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
188
src/modeler/PublishConfirm.tsx
Normal file
188
src/modeler/PublishConfirm.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
194
src/modeler/diffSummary.test.ts
Normal file
194
src/modeler/diffSummary.test.ts
Normal 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(
|
||||||
|
'"type":"position"',
|
||||||
|
'"type":"user"',
|
||||||
|
);
|
||||||
|
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(
|
||||||
|
'"type":"projectRoleType"',
|
||||||
|
'"type":"scriptUser"',
|
||||||
|
);
|
||||||
|
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(
|
||||||
|
'"type":"position"',
|
||||||
|
'"type":"user"',
|
||||||
|
);
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
// 办理人表达式属性值需把 " 转义成 " 才能进 XML 属性。
|
||||||
|
const candAttr = (items: UserPropertyItem[]) =>
|
||||||
|
buildCandidateExpression(items, 'candidate').replace(/"/g, '"');
|
||||||
|
|
||||||
|
// 默认命名空间(无前缀),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(
|
||||||
|
'"content":"true,false,false,false,false,false,false,false,false,false,false"',
|
||||||
|
'"content":"${x}"',
|
||||||
|
);
|
||||||
|
const withFull = SYNTHETIC_BPMN.replace(
|
||||||
|
'"content":"true,false,false,false,false,false,false,false,false,false,false"',
|
||||||
|
'"content":"$【x】"',
|
||||||
|
);
|
||||||
|
expect(withHalf).not.toBe(withFull); // 两版确有字面差异
|
||||||
|
expect(diffSummary(withHalf, withFull)).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
175
src/modeler/diffSummary.ts
Normal file
175
src/modeler/diffSummary.ts
Normal 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;
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "Activiti",
|
"name": "Activiti",
|
||||||
"uri": "http://activiti.org/bpmn",
|
"uri": "http://activiti.org/bpmn",
|
||||||
"prefix": "activiti",
|
"prefix": "activiti",
|
||||||
|
"xml": { "tagAlias": "lowerCase" },
|
||||||
"associations": [],
|
"associations": [],
|
||||||
"types": [
|
"types": [
|
||||||
{
|
{
|
||||||
@@ -90,7 +91,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "taskListener",
|
"name": "TaskListener",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["bpmn:UserTask"] },
|
"meta": { "allowedIn": ["bpmn:UserTask"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -98,11 +99,11 @@
|
|||||||
{ "name": "class", "isAttr": true, "type": "String" },
|
{ "name": "class", "isAttr": true, "type": "String" },
|
||||||
{ "name": "expression", "isAttr": true, "type": "String" },
|
{ "name": "expression", "isAttr": true, "type": "String" },
|
||||||
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
|
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
|
||||||
{ "name": "fields", "type": "field", "isMany": true }
|
{ "name": "fields", "type": "Field", "isMany": true }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "executionListener",
|
"name": "ExecutionListener",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["*"] },
|
"meta": { "allowedIn": ["*"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -110,11 +111,11 @@
|
|||||||
{ "name": "class", "isAttr": true, "type": "String" },
|
{ "name": "class", "isAttr": true, "type": "String" },
|
||||||
{ "name": "expression", "isAttr": true, "type": "String" },
|
{ "name": "expression", "isAttr": true, "type": "String" },
|
||||||
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
|
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
|
||||||
{ "name": "fields", "type": "field", "isMany": true }
|
{ "name": "fields", "type": "Field", "isMany": true }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "field",
|
"name": "Field",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["*"] },
|
"meta": { "allowedIn": ["*"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -125,7 +126,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "formProperty",
|
"name": "FormProperty",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["*"] },
|
"meta": { "allowedIn": ["*"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -140,11 +141,11 @@
|
|||||||
{ "name": "datePattern", "isAttr": true, "type": "String" },
|
{ "name": "datePattern", "isAttr": true, "type": "String" },
|
||||||
{ "name": "default", "isAttr": true, "type": "String" },
|
{ "name": "default", "isAttr": true, "type": "String" },
|
||||||
{ "name": "value", "isAttr": true, "type": "String" },
|
{ "name": "value", "isAttr": true, "type": "String" },
|
||||||
{ "name": "values", "type": "value", "isMany": true }
|
{ "name": "values", "type": "Value", "isMany": true }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "value",
|
"name": "Value",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"properties": [
|
"properties": [
|
||||||
{ "name": "id", "isAttr": true, "type": "String" },
|
{ "name": "id", "isAttr": true, "type": "String" },
|
||||||
@@ -152,7 +153,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "in",
|
"name": "In",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["*"] },
|
"meta": { "allowedIn": ["*"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -163,7 +164,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "out",
|
"name": "Out",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["*"] },
|
"meta": { "allowedIn": ["*"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
|
|||||||
@@ -37,9 +37,11 @@ function warns(res: any, re: RegExp): any[] {
|
|||||||
|
|
||||||
describe('activiti/flowable moddle 描述符 — 语料覆盖', () => {
|
describe('activiti/flowable moddle 描述符 — 语料覆盖', () => {
|
||||||
it('§0 全部实测 activiti 属性/元素在 activiti.json 有声明', () => {
|
it('§0 全部实测 activiti 属性/元素在 activiti.json 有声明', () => {
|
||||||
const declared = JSON.stringify(activiti);
|
// 大小写不敏感:自定义元素类型名遵循 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) =>
|
[...CORPUS_ATTRS, ...CORPUS_ELEMENTS].forEach((n) =>
|
||||||
expect(declared, `activiti:${n} 未声明`).toContain(`"${n}"`));
|
expect(declared, `activiti:${n} 未声明`).toContain(`"${n.toLowerCase()}"`));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('flowable.json 声明命名空间与 flowable:assignee', () => {
|
it('flowable.json 声明命名空间与 flowable:assignee', () => {
|
||||||
@@ -85,14 +87,14 @@ describe('activiti round-trip 零丢失(合成 fixture 覆盖全扩展面)',
|
|||||||
const { rootElement } = await newActiviti().fromXML(SYNTHETIC_BPMN);
|
const { rootElement } = await newActiviti().fromXML(SYNTHETIC_BPMN);
|
||||||
const receive = findById(rootElement, 't_receive');
|
const receive = findById(rootElement, 't_receive');
|
||||||
const listener = receive.extensionElements.values.find(
|
const listener = receive.extensionElements.values.find(
|
||||||
(v: any) => v.$type === 'activiti:taskListener',
|
(v: any) => v.$type === 'activiti:TaskListener',
|
||||||
);
|
);
|
||||||
expect(listener.event).toBe('complete');
|
expect(listener.event).toBe('complete');
|
||||||
expect(listener.class).toBe('com.dsasp.server.wf.user.listener.TaskCompleteListener');
|
expect(listener.class).toBe('com.dsasp.server.wf.user.listener.TaskCompleteListener');
|
||||||
expect(listener.fields[0].name).toBe('mailTemplate');
|
expect(listener.fields[0].name).toBe('mailTemplate');
|
||||||
expect(listener.fields[0].string).toBe('审批完成通知');
|
expect(listener.fields[0].string).toBe('审批完成通知');
|
||||||
const formProp = receive.extensionElements.values.find(
|
const formProp = receive.extensionElements.values.find(
|
||||||
(v: any) => v.$type === 'activiti:formProperty',
|
(v: any) => v.$type === 'activiti:FormProperty',
|
||||||
);
|
);
|
||||||
expect(formProp.id).toBe('fp_remark');
|
expect(formProp.id).toBe('fp_remark');
|
||||||
expect(formProp.values.map((v: any) => v.name)).toEqual(['同意', '驳回']);
|
expect(formProp.values.map((v: any) => v.name)).toEqual(['同意', '驳回']);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "Flowable",
|
"name": "Flowable",
|
||||||
"uri": "http://flowable.org/bpmn",
|
"uri": "http://flowable.org/bpmn",
|
||||||
"prefix": "flowable",
|
"prefix": "flowable",
|
||||||
|
"xml": { "tagAlias": "lowerCase" },
|
||||||
"associations": [],
|
"associations": [],
|
||||||
"types": [
|
"types": [
|
||||||
{
|
{
|
||||||
@@ -44,7 +45,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "taskListener",
|
"name": "TaskListener",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["bpmn:UserTask"] },
|
"meta": { "allowedIn": ["bpmn:UserTask"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -52,11 +53,11 @@
|
|||||||
{ "name": "class", "isAttr": true, "type": "String" },
|
{ "name": "class", "isAttr": true, "type": "String" },
|
||||||
{ "name": "expression", "isAttr": true, "type": "String" },
|
{ "name": "expression", "isAttr": true, "type": "String" },
|
||||||
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
|
{ "name": "delegateExpression", "isAttr": true, "type": "String" },
|
||||||
{ "name": "fields", "type": "field", "isMany": true }
|
{ "name": "fields", "type": "Field", "isMany": true }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "field",
|
"name": "Field",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["*"] },
|
"meta": { "allowedIn": ["*"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -67,7 +68,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "formProperty",
|
"name": "FormProperty",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"meta": { "allowedIn": ["*"] },
|
"meta": { "allowedIn": ["*"] },
|
||||||
"properties": [
|
"properties": [
|
||||||
@@ -75,11 +76,11 @@
|
|||||||
{ "name": "name", "isAttr": true, "type": "String" },
|
{ "name": "name", "isAttr": true, "type": "String" },
|
||||||
{ "name": "type", "isAttr": true, "type": "String" },
|
{ "name": "type", "isAttr": true, "type": "String" },
|
||||||
{ "name": "required", "isAttr": true, "type": "String" },
|
{ "name": "required", "isAttr": true, "type": "String" },
|
||||||
{ "name": "values", "type": "value", "isMany": true }
|
{ "name": "values", "type": "Value", "isMany": true }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "value",
|
"name": "Value",
|
||||||
"superClass": ["Element"],
|
"superClass": ["Element"],
|
||||||
"properties": [
|
"properties": [
|
||||||
{ "name": "id", "isAttr": true, "type": "String" },
|
{ "name": "id", "isAttr": true, "type": "String" },
|
||||||
|
|||||||
95
src/modeler/moddle/serialization.test.ts
Normal file
95
src/modeler/moddle/serialization.test.ts
Normal 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"');
|
||||||
|
});
|
||||||
|
});
|
||||||
35
src/modeler/templates/blank.bpmn.ts
Normal file
35
src/modeler/templates/blank.bpmn.ts
Normal 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>`;
|
||||||
46
src/modeler/templates/cosign.bpmn.ts
Normal file
46
src/modeler/templates/cosign.bpmn.ts
Normal 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,'【"items":[【"type":"user","content":"","isCandidate":true,"isSendMail":false,"isSendPhone":false,"isSendMessage":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>`;
|
||||||
95
src/modeler/templates/index.ts
Normal file
95
src/modeler/templates/index.ts
Normal 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, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
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 };
|
||||||
|
}
|
||||||
41
src/modeler/templates/single-approval.bpmn.ts
Normal file
41
src/modeler/templates/single-approval.bpmn.ts
Normal 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 属性层:内层引号写作 "(属性以 " 分隔)。
|
||||||
|
//
|
||||||
|
// 约束同 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,'【"items":[【"type":"user","content":"","isCandidate":true,"isSendMail":false,"isSendPhone":false,"isSendMessage":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>`;
|
||||||
204
src/modeler/templates/templates.test.ts
Normal file
204
src/modeler/templates/templates.test.ts
Normal 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&B <测试>"');
|
||||||
|
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 已把 " 解码为真引号、全角【】保留——即 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'));
|
||||||
|
});
|
||||||
|
});
|
||||||
45
src/modeler/templates/two-level.bpmn.ts
Normal file
45
src/modeler/templates/two-level.bpmn.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
// 新建流程模板——两级审批(start → 一级 userTask → 二级 userTask → end)。
|
||||||
|
//
|
||||||
|
// 两个 userTask 各带 activiti:candidateUsers(type:user,content 留空供侧板填人);结构、
|
||||||
|
// 全角【】/" 转义、约束(全小写元素名 + 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,'【"items":[【"type":"user","content":"","isCandidate":true,"isSendMail":false,"isSendPhone":false,"isSendMessage":false】]】')}"></userTask>
|
||||||
|
<userTask id="task_level2" name="二级审批" activiti:exclusive="false" activiti:candidateUsers="\${candidateUsersHandler.getCandidateUsers(execution,'【"items":[【"type":"user","content":"","isCandidate":true,"isSendMail":false,"isSendPhone":false,"isSendMessage":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>`;
|
||||||
@@ -42,6 +42,9 @@ vi.mock('../api/processModeler', () => ({
|
|||||||
saveDraft: vi.fn(() => Promise.resolve()),
|
saveDraft: vi.fn(() => Promise.resolve()),
|
||||||
draftFromProcDef: vi.fn(() => Promise.resolve('FP-1')),
|
draftFromProcDef: vi.fn(() => Promise.resolve('FP-1')),
|
||||||
deleteDraft: vi.fn(() => Promise.resolve()),
|
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) => ({
|
vi.mock('../auth/token', async (importOriginal) => ({
|
||||||
...(await importOriginal<typeof import('../auth/token')>()),
|
...(await importOriginal<typeof import('../auth/token')>()),
|
||||||
@@ -59,6 +62,8 @@ import {
|
|||||||
saveDraft,
|
saveDraft,
|
||||||
draftFromProcDef,
|
draftFromProcDef,
|
||||||
deleteDraft,
|
deleteDraft,
|
||||||
|
deployModel,
|
||||||
|
fetchImpact,
|
||||||
} from '../api/processModeler';
|
} from '../api/processModeler';
|
||||||
import { getProfile } from '../auth/token';
|
import { getProfile } from '../auth/token';
|
||||||
|
|
||||||
@@ -71,6 +76,8 @@ const mCreateDraft = vi.mocked(createDraft);
|
|||||||
const mSaveDraft = vi.mocked(saveDraft);
|
const mSaveDraft = vi.mocked(saveDraft);
|
||||||
const mFromProcDef = vi.mocked(draftFromProcDef);
|
const mFromProcDef = vi.mocked(draftFromProcDef);
|
||||||
const mDeleteDraft = vi.mocked(deleteDraft);
|
const mDeleteDraft = vi.mocked(deleteDraft);
|
||||||
|
const mDeploy = vi.mocked(deployModel);
|
||||||
|
const mImpact = vi.mocked(fetchImpact);
|
||||||
const mProfile = vi.mocked(getProfile);
|
const mProfile = vi.mocked(getProfile);
|
||||||
|
|
||||||
function renderPage(initialPath = '/process-modeler') {
|
function renderPage(initialPath = '/process-modeler') {
|
||||||
@@ -103,6 +110,8 @@ beforeEach(() => {
|
|||||||
mSaveDraft.mockReset().mockResolvedValue(undefined);
|
mSaveDraft.mockReset().mockResolvedValue(undefined);
|
||||||
mFromProcDef.mockReset().mockResolvedValue('FP-1');
|
mFromProcDef.mockReset().mockResolvedValue('FP-1');
|
||||||
mDeleteDraft.mockReset().mockResolvedValue(undefined);
|
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: [] });
|
mProfile.mockReset().mockReturnValue({ userId: 'ADMIN', account: 'admin', name: '管理员', roles: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -292,4 +301,148 @@ describe('ProcessModelerPage', () => {
|
|||||||
expect(mDeleteDraft).not.toHaveBeenCalled();
|
expect(mDeleteDraft).not.toHaveBeenCalled();
|
||||||
confirmSpy.mockRestore();
|
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(
|
||||||
|
'"type":"position"',
|
||||||
|
'"type":"user"',
|
||||||
|
);
|
||||||
|
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(['总包合同交底']);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ import {
|
|||||||
type ModelSummary,
|
type ModelSummary,
|
||||||
} from '../api/processModeler';
|
} from '../api/processModeler';
|
||||||
import { Eip4Panel, type PanelModeler } from '../modeler/Eip4Panel';
|
import { Eip4Panel, type PanelModeler } from '../modeler/Eip4Panel';
|
||||||
|
import { PublishConfirm } from '../modeler/PublishConfirm';
|
||||||
|
import { NewProcessDialog, type NewProcessResult } from '../modeler/NewProcessDialog';
|
||||||
import { toast } from '../components/ui';
|
import { toast } from '../components/ui';
|
||||||
|
|
||||||
// bpmn-js/lib/Modeler 自带类型,但选项对象里的标准面板模块(本项目无类型)与 moddle JSON
|
// bpmn-js/lib/Modeler 自带类型,但选项对象里的标准面板模块(本项目无类型)与 moddle JSON
|
||||||
@@ -77,10 +79,24 @@ export function ProcessModelerPage() {
|
|||||||
const modelIdRef = useRef<string>('');
|
const modelIdRef = useRef<string>('');
|
||||||
// 当前载入流程的 key(存量 procDefKey / 草稿 key)——新建草稿的 name/key 源。
|
// 当前载入流程的 key(存量 procDefKey / 草稿 key)——新建草稿的 name/key 源。
|
||||||
const loadedKeyRef = useRef<string>('');
|
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 [loadState, setLoadState] = useState<LoadState>('idle');
|
||||||
const [loadError, setLoadError] = useState('');
|
const [loadError, setLoadError] = useState('');
|
||||||
const [saving, setSaving] = useState(false);
|
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 [options, setOptions] = useState<ProcessOption[]>([]);
|
||||||
const [optionsError, setOptionsError] = useState('');
|
const [optionsError, setOptionsError] = useState('');
|
||||||
// 打开器 tab:存量流程 / 草稿。
|
// 打开器 tab:存量流程 / 草稿。
|
||||||
@@ -114,9 +130,10 @@ export function ProcessModelerPage() {
|
|||||||
};
|
};
|
||||||
}, [isAdmin, hasTarget, openTab, draftsReload]);
|
}, [isAdmin, hasTarget, openTab, draftsReload]);
|
||||||
|
|
||||||
// 有目标时挂载 Modeler 并载入 BPMN(草稿→getModel / 存量→source)。
|
// 有目标(或 pending 新建)时挂载 Modeler 并载入 BPMN(草稿→getModel / 存量→source / 新建→模板)。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isAdmin || !hasTarget) return;
|
if (!isAdmin) return;
|
||||||
|
if (!hasTarget && !newDraft) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
let modeler: ModelerLike | null = null;
|
let modeler: ModelerLike | null = null;
|
||||||
setLoadState('loading');
|
setLoadState('loading');
|
||||||
@@ -124,24 +141,33 @@ export function ProcessModelerPage() {
|
|||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
// 三条路统一成 {found,bpmnXml,idMap,key}。
|
// 新建流程:无 URL 目标但有 pending newDraft → 直接用模板实例化 XML(无远端取源、无 found 守卫)。
|
||||||
let src: { found: boolean; bpmnXml?: string; idMap?: Record<string, string>; key?: string };
|
const isNew = !hasTarget && !!newDraft;
|
||||||
if (modelIdParam) {
|
let bpmnXml: string;
|
||||||
const m = await getModel(modelIdParam);
|
// 非新建三条路统一成 {found,bpmnXml,idMap,key}。
|
||||||
src = { found: m.found, bpmnXml: m.bpmnXml, idMap: parseMetaIdMap(m.metaInfo), key: m.key };
|
let src: { found: boolean; bpmnXml?: string; idMap?: Record<string, string>; key?: string } | undefined;
|
||||||
} else if (procDefId) {
|
if (isNew) {
|
||||||
const s = await fetchProcDefSource(procDefId);
|
bpmnXml = newDraft!.xml;
|
||||||
src = { found: s.found, bpmnXml: s.bpmnXml, idMap: s.idMap, key: s.procDefKey };
|
|
||||||
} else {
|
} else {
|
||||||
const s = await fetchProcDefSourceByKey(procKey);
|
if (modelIdParam) {
|
||||||
src = { found: s.found, bpmnXml: s.bpmnXml, idMap: s.idMap, key: s.procDefKey };
|
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 (!alive) return;
|
||||||
if (!src.found || !src.bpmnXml) {
|
|
||||||
setLoadError('未找到该流程的 BPMN 源(可能未部署或无布局信息)');
|
|
||||||
setLoadState('error');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!canvasRef.current) {
|
if (!canvasRef.current) {
|
||||||
// 画布容器缺失(异常时序):明确报错,别停在 loading 无提示(T1.5 评审 M-2)。
|
// 画布容器缺失(异常时序):明确报错,别停在 loading 无提示(T1.5 评审 M-2)。
|
||||||
setLoadError('画布未就绪,请重试');
|
setLoadError('画布未就绪,请重试');
|
||||||
@@ -167,11 +193,33 @@ export function ProcessModelerPage() {
|
|||||||
/* 面板模块缺失 / stub 时忽略 */
|
/* 面板模块缺失 / stub 时忽略 */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
idMapRef.current = src.idMap ?? {};
|
if (isNew) {
|
||||||
loadedKeyRef.current = src.key ?? '';
|
// 新建:idMap(中文 key 还原用)/key/名称进 ref,供首存 createDraft;无原始源→diff 基线空。
|
||||||
// 草稿路:记住 modelId(后续保存走 PUT);存量路:清空(首次保存新建草稿)。
|
idMapRef.current = newDraft!.idMap;
|
||||||
modelIdRef.current = modelIdParam || '';
|
loadedKeyRef.current = newDraft!.key;
|
||||||
await modeler.importXML(src.bpmnXml);
|
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;
|
if (!alive) return;
|
||||||
modelerRef.current = modeler;
|
modelerRef.current = modeler;
|
||||||
setModelerReady(modeler);
|
setModelerReady(modeler);
|
||||||
@@ -202,7 +250,7 @@ export function ProcessModelerPage() {
|
|||||||
modelerRef.current = null;
|
modelerRef.current = null;
|
||||||
setModelerReady(null);
|
setModelerReady(null);
|
||||||
};
|
};
|
||||||
}, [isAdmin, procDefId, procKey, modelIdParam]);
|
}, [isAdmin, procDefId, procKey, modelIdParam, newDraft]);
|
||||||
|
|
||||||
// 保存草稿:saveXML → 有 modelId 走 PUT(不重发 metaInfo,保住 eip4IdMap);
|
// 保存草稿:saveXML → 有 modelId 走 PUT(不重发 metaInfo,保住 eip4IdMap);
|
||||||
// 无 modelId:存量按 procDefId 走 from-procdef(后端写 metaInfo)再 PUT 覆盖为编辑源;
|
// 无 modelId:存量按 procDefId 走 from-procdef(后端写 metaInfo)再 PUT 覆盖为编辑源;
|
||||||
@@ -220,19 +268,27 @@ export function ProcessModelerPage() {
|
|||||||
modelId = await draftFromProcDef(procDefId);
|
modelId = await draftFromProcDef(procDefId);
|
||||||
await saveDraft(modelId, { bpmnXml: xml });
|
await saveDraft(modelId, { bpmnXml: xml });
|
||||||
modelIdRef.current = modelId;
|
modelIdRef.current = modelId;
|
||||||
|
// I1:预置基线归属为新 modelId,使随后的 reload 保留原始源基线(不被冲成「已存版」)。
|
||||||
|
baselineTargetRef.current = 'model:' + modelId;
|
||||||
// I-2:首存回填 ?modelId=,令刷新幂等(不再重复建草稿)、二次保存恒走 PUT。
|
// I-2:首存回填 ?modelId=,令刷新幂等(不再重复建草稿)、二次保存恒走 PUT。
|
||||||
setParams({ modelId }, { replace: true });
|
setParams({ modelId }, { replace: true });
|
||||||
} else {
|
} else {
|
||||||
const key = loadedKeyRef.current || procKey || 'new_process';
|
const key = loadedKeyRef.current || procKey || 'new_process';
|
||||||
|
// 新建流程用展示名(newNameRef);存量按 key 无展示名,回退用 key。
|
||||||
|
const name = newNameRef.current || key;
|
||||||
// metaInfo 结构与 from-procdef 对齐(sourceProcDefId 便于 T3.x 影响摘要/审计,
|
// metaInfo 结构与 from-procdef 对齐(sourceProcDefId 便于 T3.x 影响摘要/审计,
|
||||||
// 虽 restore 只读 eip4IdMap)。
|
// 虽 restore 只读 eip4IdMap;新建中文 key 的 idMap 使发布 restore 回中文 process key)。
|
||||||
const metaInfo = JSON.stringify({
|
const metaInfo = JSON.stringify({
|
||||||
eip4IdMap: idMapRef.current,
|
eip4IdMap: idMapRef.current,
|
||||||
sourceProcDefId: procDefId || '',
|
sourceProcDefId: procDefId || '',
|
||||||
originalKey: key,
|
originalKey: key,
|
||||||
});
|
});
|
||||||
modelId = await createDraft({ name: key, key, bpmnXml: xml, metaInfo });
|
modelId = await createDraft({ name, key, bpmnXml: xml, metaInfo });
|
||||||
modelIdRef.current = modelId;
|
modelIdRef.current = modelId;
|
||||||
|
// I1:同上,reload 保留原始源基线。
|
||||||
|
baselineTargetRef.current = 'model:' + modelId;
|
||||||
|
// 新建首存后清 pending newDraft:随后回填 ?modelId= 触发按 modelId 正常重载(幂等)。
|
||||||
|
if (newDraft) setNewDraft(null);
|
||||||
setParams({ modelId }, { replace: true });
|
setParams({ modelId }, { replace: true });
|
||||||
}
|
}
|
||||||
toast('已保存草稿', 'ok');
|
toast('已保存草稿', 'ok');
|
||||||
@@ -243,6 +299,26 @@ export function ProcessModelerPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 发布:需先有草稿(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) {
|
if (!isAdmin) {
|
||||||
return <div style={{ padding: 24, color: 'var(--text-3)' }}>流程设计器仅管理员可用。</div>;
|
return <div style={{ padding: 24, color: 'var(--text-3)' }}>流程设计器仅管理员可用。</div>;
|
||||||
}
|
}
|
||||||
@@ -302,7 +378,9 @@ export function ProcessModelerPage() {
|
|||||||
<span className="muted" style={{ fontSize: 12, flex: 1 }}>
|
<span className="muted" style={{ fontSize: 12, flex: 1 }}>
|
||||||
{hasTarget
|
{hasTarget
|
||||||
? `已打开:${modelIdParam ? '草稿 ' + modelIdParam : procDefId || procKey}`
|
? `已打开:${modelIdParam ? '草稿 ' + modelIdParam : procDefId || procKey}`
|
||||||
: '在线编辑 BPMN 流程定义(可编辑存量 / 草稿)'}
|
: newDraft
|
||||||
|
? `新建流程:${newDraft.name}(${newDraft.key})`
|
||||||
|
: '在线编辑 BPMN 流程定义(可编辑存量 / 草稿 / 新建)'}
|
||||||
</span>
|
</span>
|
||||||
<button
|
<button
|
||||||
className="btn btn-sm"
|
className="btn btn-sm"
|
||||||
@@ -313,7 +391,13 @@ export function ProcessModelerPage() {
|
|||||||
>
|
>
|
||||||
{saving ? '保存中…' : '保存草稿'}
|
{saving ? '保存中…' : '保存草稿'}
|
||||||
</button>
|
</button>
|
||||||
<button className="btn btn-sm btn-primary" data-testid="process-modeler-publish" disabled title="发布(下阶段)">
|
<button
|
||||||
|
className="btn btn-sm btn-primary"
|
||||||
|
data-testid="process-modeler-publish"
|
||||||
|
disabled={!modelerReady || saving}
|
||||||
|
onClick={handlePublishClick}
|
||||||
|
title="发布(同人确认 + 影响摘要)"
|
||||||
|
>
|
||||||
发布
|
发布
|
||||||
</button>
|
</button>
|
||||||
<button className="btn btn-sm" data-testid="process-modeler-back" onClick={() => navigate('/design-center')}>
|
<button className="btn btn-sm" data-testid="process-modeler-back" onClick={() => navigate('/design-center')}>
|
||||||
@@ -326,8 +410,8 @@ export function ProcessModelerPage() {
|
|||||||
<div style={{ flex: 1, position: 'relative', minWidth: 0, background: '#fff' }}>
|
<div style={{ flex: 1, position: 'relative', minWidth: 0, background: '#fff' }}>
|
||||||
<div ref={canvasRef} data-testid="process-modeler-canvas" style={{ width: '100%', height: '100%' }} />
|
<div ref={canvasRef} data-testid="process-modeler-canvas" style={{ width: '100%', height: '100%' }} />
|
||||||
|
|
||||||
{/* 未打开任何流程:叠加打开器(存量流程 / 草稿 两 tab) */}
|
{/* 未打开任何流程且无 pending 新建:叠加打开器(存量流程 / 草稿 两 tab) */}
|
||||||
{!hasTarget ? (
|
{!hasTarget && !newDraft ? (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
@@ -376,7 +460,12 @@ export function ProcessModelerPage() {
|
|||||||
{optionsError ? (
|
{optionsError ? (
|
||||||
<div style={{ color: 'var(--err)', fontSize: 12 }}>{optionsError}</div>
|
<div style={{ color: 'var(--err)', fontSize: 12 }}>{optionsError}</div>
|
||||||
) : null}
|
) : null}
|
||||||
<button className="btn btn-sm" data-testid="process-modeler-new" disabled title="新建流程(下阶段)">
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
data-testid="process-modeler-new"
|
||||||
|
onClick={() => setShowNewDialog(true)}
|
||||||
|
title="新建流程(空白 / 单人 / 两级 / 会签 模板)"
|
||||||
|
>
|
||||||
+ 新建流程
|
+ 新建流程
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
@@ -464,6 +553,29 @@ export function ProcessModelerPage() {
|
|||||||
<div ref={panelRef} data-testid="process-modeler-props" style={{ flex: 1, overflow: 'auto', minHeight: 0 }} />
|
<div ref={panelRef} data-testid="process-modeler-props" style={{ flex: 1, overflow: 'auto', minHeight: 0 }} />
|
||||||
</div>
|
</div>
|
||||||
</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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user