gbflowengine 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +271 -271
  2. package/dist/gbflowengine.css +1 -1
  3. package/dist/gbflowengine.js +8232 -6913
  4. package/dist/gbflowengine.js.map +1 -1
  5. package/dist/gbflowengine.umd.cjs +2 -2
  6. package/dist/gbflowengine.umd.cjs.map +1 -1
  7. package/package.json +85 -84
  8. package/src/center/DefinitionInspect.vue +291 -291
  9. package/src/center/FlowCenter.vue +33 -33
  10. package/src/center/index.js +29 -29
  11. package/src/center/storage.js +748 -748
  12. package/src/core/flow/condition.js +160 -160
  13. package/src/core/flow/customNode.js +385 -385
  14. package/src/core/flow/defaults.js +124 -124
  15. package/src/core/flow/flowConstant.js +265 -265
  16. package/src/core/flow/flowNodeUtils.js +29 -29
  17. package/src/core/flow/index.js +47 -47
  18. package/src/core/flow/node.js +44 -44
  19. package/src/core/flow/nodeFactory.js +58 -58
  20. package/src/core/flow/prediction.js +325 -325
  21. package/src/core/flow/schema.js +864 -864
  22. package/src/definition/FlowDefinitionDesigner.vue +338 -338
  23. package/src/definition/index.js +9 -9
  24. package/src/index.js +39 -39
  25. package/src/storage.js +200 -200
  26. package/src/testing/FlowTestPanel.vue +2502 -2502
  27. package/src/testing/UserConfigDrawer.vue +376 -376
  28. package/src/testing/diagram/FlowProgressDiagram.vue +318 -318
  29. package/src/testing/diagramModel.js +517 -517
  30. package/src/testing/index.js +23 -23
  31. package/src/testing/mock.js +246 -246
  32. package/src/testing/oaExecutors.js +51 -51
  33. package/src/testing/oaSeed.js +467 -467
  34. package/src/testing/sample.js +412 -412
  35. package/src/testing/seed.js +122 -122
  36. package/src/utils/format.js +27 -27
  37. package/src/visual/FlowCanvas.vue +440 -440
  38. package/src/visual/NodeProgressDetail.vue +43 -43
  39. package/src/visual/NodeStatusBadge.vue +17 -17
  40. package/src/visual/NodeWrap.vue +46 -46
  41. package/src/visual/ScWorkflow.vue +49 -49
  42. package/src/visual/SelectDialog.vue +459 -459
  43. package/src/visual/conditionHelpers.js +116 -116
  44. package/src/visual/index.js +6 -6
  45. package/src/visual/nodes/AddNode.vue +222 -222
  46. package/src/visual/nodes/ApproverNode.vue +347 -347
  47. package/src/visual/nodes/BranchNode.vue +441 -441
  48. package/src/visual/nodes/CustomNode.vue +339 -339
  49. package/src/visual/nodes/EndNode.vue +21 -21
  50. package/src/visual/nodes/PassNode.vue +100 -100
  51. package/src/visual/nodes/PromoterNode.vue +134 -134
  52. package/src/visual/nodes/RejectNode.vue +100 -100
  53. package/src/visual/nodes/SendNode.vue +151 -151
  54. package/src/visual/styles.scss +879 -879
  55. package/src/visual/useScNodeStatus.js +18 -18
  56. package/src/workbench/OaWorkbench.vue +1341 -1341
  57. package/src/workbench/components/ApprovalWorkspace.vue +2090 -2090
  58. package/src/workbench/components/CategoryIcon.vue +74 -74
  59. package/src/workbench/components/NotificationIcon.vue +73 -73
  60. package/src/workbench/components/ProcessSteps.vue +557 -557
  61. package/src/workbench/components/ResubmitDialog.vue +227 -227
  62. package/src/workbench/components/SidebarNav.vue +138 -138
  63. package/src/workbench/components/StartFlowDialog.vue +1058 -1058
  64. package/src/workbench/components/UserAvatar.vue +68 -68
  65. package/src/workbench/model.js +1080 -1080
  66. package/src/workbench/pages/DesignPage.vue +798 -798
  67. package/src/workbench/pages/HomePage.vue +1050 -1050
  68. package/src/workbench/pages/MonitorPage.vue +1029 -1029
  69. package/src/workbench/pages/NotificationsPage.vue +554 -554
  70. package/src/workbench/pages/RequestsPage.vue +644 -644
  71. package/src/workbench/pages/TaskCenterPage.vue +1155 -1155
  72. package/src/workbench/pages/TemplatesPage.vue +680 -680
  73. package/src/workbench/styles.scss +555 -555
  74. package/types/center.d.ts +5 -5
  75. package/types/core.d.ts +479 -479
  76. package/types/definition.d.ts +4 -4
  77. package/types/index.d.ts +34 -34
  78. package/types/testing.d.ts +20 -20
  79. package/types/visual.d.ts +20 -20
@@ -1,517 +1,517 @@
1
- import {
2
- ApproverTypeLabel,
3
- FlowNodeType,
4
- NodeTypeLabel,
5
- SignModeLabel
6
- } from '../core/flow/flowConstant.js'
7
- import { formatDateTime } from '../utils/format.js'
8
- import { customNodeSummary } from '../core/flow/customNode.js'
9
-
10
- const GROUP_TYPES = new Set([
11
- FlowNodeType.BRANCH,
12
- FlowNodeType.PARALLEL,
13
- FlowNodeType.INCLUSIVE
14
- ])
15
-
16
- const TERMINAL_TYPES = new Set([
17
- FlowNodeType.PASS,
18
- FlowNodeType.REJECT,
19
- FlowNodeType.END
20
- ])
21
-
22
- const NODE_STATUS_LABEL = {
23
- pending: '未开始',
24
- predicted: '预测',
25
- upcoming: '待执行',
26
- current: '当前节点',
27
- completed: '已完成',
28
- rejected: '已拒绝',
29
- failed: '执行失败',
30
- skipped: '未命中'
31
- }
32
-
33
- const GROUP_STATUS_LABEL = {
34
- pending: '未开始',
35
- predicted: '预测',
36
- upcoming: '待执行',
37
- current: '进行中',
38
- completed: '已执行',
39
- rejected: '已拒绝',
40
- skipped: '未到达'
41
- }
42
-
43
- const sameId = (left, right) =>
44
- left !== undefined && right !== undefined && String(left) === String(right)
45
-
46
- function formatValue(value) {
47
- if (value === null || value === undefined || value === '') return ''
48
- if (Array.isArray(value)) return value.join(',')
49
- if (typeof value === 'boolean') return value ? 'true' : 'false'
50
- return String(value)
51
- }
52
-
53
-
54
- function conditionText(branch) {
55
- const conditions = Array.isArray(branch?.conditions) ? branch.conditions : []
56
- if (!conditions.length) {
57
- return branch?.isDefaultBranch || branch?.isDefaultCondition ? '其他条件(兜底)' : ''
58
- }
59
- return conditions
60
- .map((condition) => {
61
- const label = condition.variableName || condition.variable || '字段'
62
- const value = formatValue(condition.value)
63
- return `${label} ${condition.operator}${value ? ` ${value}` : ''}`
64
- })
65
- .join(' 且 ')
66
- }
67
-
68
- function groupByNode(list) {
69
- const map = new Map()
70
- ;(list || []).forEach((item) => {
71
- const key = String(item.nodeId)
72
- if (!map.has(key)) map.set(key, [])
73
- map.get(key).push(item)
74
- })
75
- return map
76
- }
77
-
78
- function latestTask(tasks) {
79
- return [...tasks]
80
- .filter((task) => task.status === 'pending')
81
- .sort((left, right) => String(left.createdAt).localeCompare(String(right.createdAt)))
82
- .at(-1) ||
83
- [...tasks].sort((left, right) =>
84
- String(left.createdAt).localeCompare(String(right.createdAt))
85
- ).at(-1)
86
- }
87
-
88
- function selectedIdsFromDecision(decision) {
89
- if (!decision) return null
90
- if (Array.isArray(decision.branchIds)) return decision.branchIds.map(String)
91
- if (Array.isArray(decision.selectedBranchIds)) return decision.selectedBranchIds.map(String)
92
- if (decision.branchId !== undefined && decision.branchId !== null) {
93
- return [String(decision.branchId)]
94
- }
95
- if (decision.selectedBranchId !== undefined && decision.selectedBranchId !== null) {
96
- return [String(decision.selectedBranchId)]
97
- }
98
- return null
99
- }
100
-
101
- export function buildDiagramModel({ workflow, state = null, prediction = null } = {}) {
102
- if (!workflow) return { items: [], usedStatuses: [], cycle: 1 }
103
-
104
- const rawHistory = state?.history || []
105
- const rawTasks = state?.tasks || []
106
- const rawCcRecords = state?.ccRecords || []
107
- const returnEvents = rawHistory.filter((event) => event.event === 'return')
108
- const currentCycle = Math.max(Number(state?.cycle) || 1, returnEvents.length + 1)
109
- const cycleOfTime = (value) => {
110
- const time = new Date(value || 0).getTime()
111
- if (!Number.isFinite(time)) return currentCycle
112
- return 1 + returnEvents.filter((event) => new Date(event.at).getTime() <= time).length
113
- }
114
- const cycleOfEvent = (event) => Number(event.cycle) || cycleOfTime(event.at)
115
- const cycleOfRecord = (record) => Number(record.cycle) || cycleOfTime(record.createdAt || record.at)
116
-
117
- const history = rawHistory.filter((event) => cycleOfEvent(event) === currentCycle)
118
- const cycleTasks = rawTasks.filter((task) => cycleOfRecord(task) === currentCycle)
119
- const cycleCcRecords = rawCcRecords.filter((record) => cycleOfRecord(record) === currentCycle)
120
- const tasksByNode = groupByNode(cycleTasks)
121
- const ccByNode = groupByNode(cycleCcRecords)
122
- const lastReturn = [...returnEvents].reverse()[0]
123
- let predictedNodes = prediction?.nodes || []
124
- if (
125
- currentCycle > 1 &&
126
- lastReturn?.targetNodeId !== undefined &&
127
- lastReturn?.targetNodeId !== null &&
128
- !sameId(lastReturn.targetNodeId, workflow.nodeId)
129
- ) {
130
- const startIndex = predictedNodes.findIndex((node) =>
131
- sameId(node.nodeId, lastReturn.targetNodeId)
132
- )
133
- if (startIndex > 0) predictedNodes = predictedNodes.slice(startIndex)
134
- }
135
- const predictedById = new Map(predictedNodes.map((node) => [String(node.nodeId), node]))
136
- const predictedDecisions = new Map(
137
- (prediction?.decisions || []).map((decision) => [String(decision.nodeId), decision])
138
- )
139
- const predictedIds = new Set(predictedById.keys())
140
- const pendingTaskIds = cycleTasks
141
- .filter((task) => task.status === 'pending')
142
- .map((task) => String(task.nodeId))
143
- const activeTokenIds = (state?.tokens || [])
144
- .filter((token) => token.nodeId != null && !token.blockedTaskId && !token.blockedJoinGroup)
145
- .map((token) => String(token.nodeId))
146
- const currentIds = new Set([...activeTokenIds, ...pendingTaskIds])
147
-
148
- const actualDecisions = new Map()
149
- history.forEach((event) => {
150
- if (event.event !== 'branch' && event.event !== 'split') return
151
- const key = String(event.nodeId)
152
- if (!actualDecisions.has(key)) actualDecisions.set(key, new Set())
153
- const ids = actualDecisions.get(key)
154
- if (event.branchId !== undefined && event.branchId !== null) ids.add(String(event.branchId))
155
- ;(event.branchIds || []).forEach((id) => ids.add(String(id)))
156
- })
157
-
158
- const isTerminal =
159
- !!state && ['completed', 'rejected', 'cancelled'].includes(state.status)
160
-
161
- const hasEvent = (nodeId, name) =>
162
- history.some(
163
- (event) => event.event === name && sameId(event.nodeId, nodeId)
164
- )
165
-
166
- function resolveDecision(node) {
167
- const id = String(node.nodeId)
168
- if (actualDecisions.has(id)) {
169
- return { ids: [...actualDecisions.get(id)], source: 'actual' }
170
- }
171
- if (node.type === FlowNodeType.PARALLEL) {
172
- return {
173
- ids: (node.branchList || []).map((branch) => String(branch.nodeId)),
174
- source: 'parallel'
175
- }
176
- }
177
- const decision = predictedDecisions.get(id)
178
- const ids = selectedIdsFromDecision(decision)
179
- return ids ? { ids, source: 'prediction' } : null
180
- }
181
-
182
- function resolveStatus(node, branchSkipped) {
183
- if (branchSkipped) return 'skipped'
184
- const id = String(node.nodeId)
185
- if (currentIds.has(id)) return 'current'
186
- const tasks = tasksByNode.get(id) || []
187
-
188
- if (node.type === FlowNodeType.APPROVE) {
189
- const task = latestTask(tasks)
190
- if (task?.status === 'pending') return 'current'
191
- if (task?.status === 'rejected') return 'rejected'
192
- if (task?.status === 'approved') return 'completed'
193
- if (hasEvent(id, 'autoApprove')) return 'completed'
194
- } else if (node.type === FlowNodeType.CC) {
195
- if (ccByNode.has(id) || hasEvent(id, 'cc')) return 'completed'
196
- } else if (node.type === FlowNodeType.CUSTOM) {
197
- const task = latestTask(tasks)
198
- if (task?.status === 'pending') return 'current'
199
- if (task?.status === 'completed') return 'completed'
200
- if (task?.status === 'failed') return 'failed'
201
- } else if (node.type === FlowNodeType.START) {
202
- if (
203
- hasEvent(id, 'enter') ||
204
- hasEvent(id, 'start') ||
205
- hasEvent(id, 'resubmit') ||
206
- (currentCycle === 1 && state?.startedAt)
207
- ) {
208
- return 'completed'
209
- }
210
- } else if (node.type === FlowNodeType.END) {
211
- if (hasEvent(id, 'end') || state?.status === 'completed') return 'completed'
212
- } else if (node.type === FlowNodeType.PASS) {
213
- if (hasEvent(id, 'pass')) return 'completed'
214
- } else if (node.type === FlowNodeType.REJECT) {
215
- if (hasEvent(id, 'rejectNode')) return 'rejected'
216
- } else if (GROUP_TYPES.has(node.type)) {
217
- if (actualDecisions.has(id) || hasEvent(id, 'branch') || hasEvent(id, 'split')) {
218
- return 'completed'
219
- }
220
- }
221
-
222
- if (state) {
223
- if (isTerminal) return 'skipped'
224
- if (prediction) return predictedIds.has(id) ? 'upcoming' : 'skipped'
225
- return 'pending'
226
- }
227
- return predictedIds.has(id) ? 'predicted' : 'skipped'
228
- }
229
-
230
- function buildApprovers(node) {
231
- const tasks = tasksByNode.get(String(node.nodeId)) || []
232
- const predictionNode = predictedById.get(String(node.nodeId))
233
- if (tasks.length) {
234
- const task = latestTask(tasks)
235
- if (task) {
236
- return (task.approvers || []).map((approver) => ({
237
- id: approver.id,
238
- name: approver.name,
239
- deptName: approver.deptName || '',
240
- done: (task.approvedBy || []).some((item) => sameId(item.id, approver.id)),
241
- status: task.status
242
- }))
243
- }
244
- }
245
- return (predictionNode?.approvers || []).map((approver) => ({
246
- ...approver,
247
- done: false,
248
- status: 'pending'
249
- }))
250
- }
251
-
252
- function buildCcUsers(node) {
253
- const records = ccByNode.get(String(node.nodeId)) || []
254
- if (records.length) {
255
- const record = records.at(-1)
256
- return (record.users || []).map((user) => ({
257
- id: user.id,
258
- name: user.name,
259
- deptName: user.deptName || '',
260
- done: true
261
- }))
262
- }
263
- const predictionNode = predictedById.get(String(node.nodeId))
264
- return (predictionNode?.ccUsers || []).map((user) => ({
265
- ...user,
266
- done: false
267
- }))
268
- }
269
-
270
- function buildNote(node, status) {
271
- const predictionNode = predictedById.get(String(node.nodeId))
272
- if (status === 'current') {
273
- if (node.type === FlowNodeType.START) {
274
- return '等待发起人修改表单后重新提交'
275
- }
276
- if (node.type === FlowNodeType.APPROVE) {
277
- const task = latestTask(tasksByNode.get(String(node.nodeId)) || [])
278
- const timeout = task?.dueAt
279
- ? ` · ${task.termMode === 1 ? '超时自动拒绝' : '超时自动通过'} ${formatDateTime(task.dueAt, { short: true })}`
280
- : ''
281
- if (task && (task.approvedBy || []).length) {
282
- return `等待其余审批人(已同意 ${task.approvedBy.length}/${task.approvers.length})${timeout}`
283
- }
284
- return `等待审批${timeout}`
285
- }
286
- if (node.type === FlowNodeType.CUSTOM) {
287
- return `等待系统执行:${customNodeSummary(node.custom)}`
288
- }
289
- return '正在执行'
290
- }
291
- if (status === 'rejected' && hasEvent(node.nodeId, 'rejectLimitReached')) {
292
- return '已达到最大退回次数,流程不通过'
293
- }
294
- if (hasEvent(node.nodeId, 'autoApprove')) {
295
- return '未解析到审批人,系统已自动通过'
296
- }
297
- if (node.type === FlowNodeType.REJECT && status === 'rejected') {
298
- return '流程在此直接拒绝'
299
- }
300
- if (node.type === FlowNodeType.END && status === 'completed') {
301
- return '流程结束'
302
- }
303
- if (node.type === FlowNodeType.CUSTOM) {
304
- const task = latestTask(tasksByNode.get(String(node.nodeId)) || [])
305
- if (status === 'failed') {
306
- return task?.lastError ? `执行失败:${task.lastError}` : '自定义节点执行失败'
307
- }
308
- if (status === 'completed') {
309
- return task?.custom?.resultVariable
310
- ? `执行成功,结果已写入 ${task.custom.resultVariable}`
311
- : '自定义节点执行成功'
312
- }
313
- return predictionNode?.note || `系统执行:${customNodeSummary(node.custom)}`
314
- }
315
- return predictionNode?.note || ''
316
- }
317
-
318
- function buildChildStatus(items, skipped, fallback) {
319
- if (skipped) return 'skipped'
320
- if (!items.length) return fallback
321
- const statuses = items.map((item) => item.status)
322
- if (statuses.includes('current')) return 'current'
323
- if (statuses.includes('rejected')) return 'rejected'
324
- if (statuses.includes('upcoming')) return 'upcoming'
325
- if (statuses.includes('predicted')) return 'predicted'
326
- if (statuses.every((status) => status === 'completed' || status === 'skipped')) {
327
- return 'completed'
328
- }
329
- return fallback
330
- }
331
-
332
- const seen = new Set()
333
- const statusMap = {}
334
- let sequence = 0
335
-
336
- function buildGroupItem(node, branchSkipped) {
337
- const status = resolveStatus(node, branchSkipped)
338
- const decision = resolveDecision(node)
339
- const groupSkipped = branchSkipped || status === 'skipped'
340
- const branches = (node.branchList || []).map((branch) => {
341
- const selected = decision?.ids
342
- ? decision.ids.includes(String(branch.nodeId))
343
- : null
344
- const skipped = groupSkipped || selected === false
345
- const items = branch.childNode ? buildChain(branch.childNode, skipped) : []
346
- const branchStatus = selected === false
347
- ? 'skipped'
348
- : buildChildStatus(items, skipped, status === 'completed' ? 'completed' : status)
349
- const condition = conditionText(branch)
350
- statusMap[String(branch.nodeId)] = {
351
- nodeId: branch.nodeId,
352
- nodeName: branch.nodeName,
353
- type: branch.type,
354
- kind: 'branch',
355
- status: branchStatus,
356
- statusLabel: NODE_STATUS_LABEL[branchStatus] || branchStatus,
357
- selected,
358
- branchName: branch.nodeName,
359
- conditionText: condition,
360
- decisionText: selected === false ? '未命中' : selected ? '命中' : ''
361
- }
362
- return {
363
- key: `branch_${branch.nodeId}_${++sequence}`,
364
- branchId: branch.nodeId,
365
- branchName: branch.nodeName,
366
- conditionText: condition,
367
- selected,
368
- status: branchStatus,
369
- statusLabel: NODE_STATUS_LABEL[branchStatus] || branchStatus,
370
- items
371
- }
372
- })
373
-
374
- const selectedNames = branches
375
- .filter((branch) => branch.selected)
376
- .map((branch) => branch.branchName)
377
- let decisionText = ''
378
- if (node.type === FlowNodeType.PARALLEL) {
379
- decisionText = branches.length
380
- ? `${branches.length} 个分支并行执行`
381
- : '未配置并行分支'
382
- } else if (node.type === FlowNodeType.INCLUSIVE) {
383
- decisionText = selectedNames.length
384
- ? `命中:${selectedNames.join('、')}`
385
- : '未命中分支,直接进入后续节点'
386
- } else {
387
- decisionText = selectedNames.length
388
- ? `命中「${selectedNames.join('、')}」`
389
- : '未命中条件分支'
390
- }
391
-
392
- const predictionNode = predictedById.get(String(node.nodeId))
393
- const note = predictionNode?.note || ''
394
- const groupInfo = {
395
- kind: 'group',
396
- key: `group_${node.nodeId}_${++sequence}`,
397
- groupType: node.type,
398
- nodeId: node.nodeId,
399
- nodeName: node.nodeName,
400
- typeLabel: NodeTypeLabel[node.type] || node.type,
401
- status,
402
- statusLabel: GROUP_STATUS_LABEL[status] || status,
403
- decisionText,
404
- branches,
405
- note
406
- }
407
- statusMap[String(node.nodeId)] = {
408
- nodeId: node.nodeId,
409
- nodeName: node.nodeName,
410
- type: node.type,
411
- kind: 'group',
412
- status,
413
- statusLabel: GROUP_STATUS_LABEL[status] || status,
414
- decisionText,
415
- note
416
- }
417
- return groupInfo
418
- }
419
-
420
- function buildNodeItem(node, branchSkipped) {
421
- const status = resolveStatus(node, branchSkipped)
422
- const isApprove = node.type === FlowNodeType.APPROVE
423
- const isCc = node.type === FlowNodeType.CC
424
- const approvers = isApprove ? buildApprovers(node) : []
425
- const ccUsers = isCc ? buildCcUsers(node) : []
426
- const note = buildNote(node, status)
427
- const signModeLabel = isApprove
428
- ? SignModeLabel[node.signMode === 'or' ? 'or' : 'and']
429
- : ''
430
- const approverTypeLabel = isApprove
431
- ? ApproverTypeLabel[node.approverType || 'user'] || node.approverType || ''
432
- : ''
433
- statusMap[String(node.nodeId)] = {
434
- nodeId: node.nodeId,
435
- nodeName: node.nodeName,
436
- type: node.type,
437
- kind: 'node',
438
- status,
439
- statusLabel: NODE_STATUS_LABEL[status] || status,
440
- signModeLabel,
441
- approverTypeLabel,
442
- approvers,
443
- ccUsers,
444
- note
445
- }
446
- return {
447
- kind: 'node',
448
- key: `node_${node.nodeId}_${++sequence}`,
449
- nodeId: node.nodeId,
450
- nodeName: node.nodeName,
451
- type: node.type,
452
- typeLabel: NodeTypeLabel[node.type] || node.type || '节点',
453
- status,
454
- statusLabel: NODE_STATUS_LABEL[status] || status,
455
- signModeLabel,
456
- approverTypeLabel,
457
- approvers,
458
- ccUsers,
459
- note
460
- }
461
- }
462
-
463
- function buildChain(startNode, branchSkipped = false) {
464
- const items = []
465
- let node = startNode
466
- let guard = 0
467
- while (node && guard < 2000) {
468
- guard += 1
469
- const key = String(node.nodeId)
470
- if (seen.has(key)) break
471
- seen.add(key)
472
- if (GROUP_TYPES.has(node.type)) {
473
- items.push(buildGroupItem(node, branchSkipped))
474
- node = node.childNode
475
- continue
476
- }
477
- items.push(buildNodeItem(node, branchSkipped))
478
- if (TERMINAL_TYPES.has(node.type)) break
479
- node = node.childNode
480
- }
481
- return items
482
- }
483
-
484
- const items = buildChain(workflow)
485
- const usedStatuses = new Set(Object.values(statusMap).map((item) => item.status))
486
-
487
- return {
488
- items,
489
- statusMap,
490
- usedStatuses: [...usedStatuses],
491
- mode: state ? 'progress' : 'prediction',
492
- cycle: state ? currentCycle : 1,
493
- initiator: prediction?.initiator || state?.initiator || null
494
- }
495
- }
496
-
497
- /**
498
- * 折叠未命中的分支:statusMap 中分支节点带 selected 标记,
499
- * selected === false 表示该条件没命中,连同其子链一起裁掉。
500
- * 用于「实际进度 / 预测路径」视图,让不走的流程不占版面。
501
- */
502
- export function pruneUnselectedBranches(workflow, statusMap = {}) {
503
- if (!workflow) return null
504
- const next = { ...workflow }
505
- if (Array.isArray(workflow.branchList)) {
506
- const kept = workflow.branchList
507
- .filter((branch) => statusMap[String(branch.nodeId)]?.selected !== false)
508
- .map((branch) => ({
509
- ...branch,
510
- childNode: pruneUnselectedBranches(branch.childNode, statusMap)
511
- }))
512
- // 兜底:万一整组都被判为未命中,保留原分支避免渲染出空组
513
- next.branchList = kept.length ? kept : workflow.branchList
514
- }
515
- next.childNode = pruneUnselectedBranches(workflow.childNode, statusMap)
516
- return next
517
- }
1
+ import {
2
+ ApproverTypeLabel,
3
+ FlowNodeType,
4
+ NodeTypeLabel,
5
+ SignModeLabel
6
+ } from '../core/flow/flowConstant.js'
7
+ import { formatDateTime } from '../utils/format.js'
8
+ import { customNodeSummary } from '../core/flow/customNode.js'
9
+
10
+ const GROUP_TYPES = new Set([
11
+ FlowNodeType.BRANCH,
12
+ FlowNodeType.PARALLEL,
13
+ FlowNodeType.INCLUSIVE
14
+ ])
15
+
16
+ const TERMINAL_TYPES = new Set([
17
+ FlowNodeType.PASS,
18
+ FlowNodeType.REJECT,
19
+ FlowNodeType.END
20
+ ])
21
+
22
+ const NODE_STATUS_LABEL = {
23
+ pending: '未开始',
24
+ predicted: '预测',
25
+ upcoming: '待执行',
26
+ current: '当前节点',
27
+ completed: '已完成',
28
+ rejected: '已拒绝',
29
+ failed: '执行失败',
30
+ skipped: '未命中'
31
+ }
32
+
33
+ const GROUP_STATUS_LABEL = {
34
+ pending: '未开始',
35
+ predicted: '预测',
36
+ upcoming: '待执行',
37
+ current: '进行中',
38
+ completed: '已执行',
39
+ rejected: '已拒绝',
40
+ skipped: '未到达'
41
+ }
42
+
43
+ const sameId = (left, right) =>
44
+ left !== undefined && right !== undefined && String(left) === String(right)
45
+
46
+ function formatValue(value) {
47
+ if (value === null || value === undefined || value === '') return ''
48
+ if (Array.isArray(value)) return value.join(',')
49
+ if (typeof value === 'boolean') return value ? 'true' : 'false'
50
+ return String(value)
51
+ }
52
+
53
+
54
+ function conditionText(branch) {
55
+ const conditions = Array.isArray(branch?.conditions) ? branch.conditions : []
56
+ if (!conditions.length) {
57
+ return branch?.isDefaultBranch || branch?.isDefaultCondition ? '其他条件(兜底)' : ''
58
+ }
59
+ return conditions
60
+ .map((condition) => {
61
+ const label = condition.variableName || condition.variable || '字段'
62
+ const value = formatValue(condition.value)
63
+ return `${label} ${condition.operator}${value ? ` ${value}` : ''}`
64
+ })
65
+ .join(' 且 ')
66
+ }
67
+
68
+ function groupByNode(list) {
69
+ const map = new Map()
70
+ ;(list || []).forEach((item) => {
71
+ const key = String(item.nodeId)
72
+ if (!map.has(key)) map.set(key, [])
73
+ map.get(key).push(item)
74
+ })
75
+ return map
76
+ }
77
+
78
+ function latestTask(tasks) {
79
+ return [...tasks]
80
+ .filter((task) => task.status === 'pending')
81
+ .sort((left, right) => String(left.createdAt).localeCompare(String(right.createdAt)))
82
+ .at(-1) ||
83
+ [...tasks].sort((left, right) =>
84
+ String(left.createdAt).localeCompare(String(right.createdAt))
85
+ ).at(-1)
86
+ }
87
+
88
+ function selectedIdsFromDecision(decision) {
89
+ if (!decision) return null
90
+ if (Array.isArray(decision.branchIds)) return decision.branchIds.map(String)
91
+ if (Array.isArray(decision.selectedBranchIds)) return decision.selectedBranchIds.map(String)
92
+ if (decision.branchId !== undefined && decision.branchId !== null) {
93
+ return [String(decision.branchId)]
94
+ }
95
+ if (decision.selectedBranchId !== undefined && decision.selectedBranchId !== null) {
96
+ return [String(decision.selectedBranchId)]
97
+ }
98
+ return null
99
+ }
100
+
101
+ export function buildDiagramModel({ workflow, state = null, prediction = null } = {}) {
102
+ if (!workflow) return { items: [], usedStatuses: [], cycle: 1 }
103
+
104
+ const rawHistory = state?.history || []
105
+ const rawTasks = state?.tasks || []
106
+ const rawCcRecords = state?.ccRecords || []
107
+ const returnEvents = rawHistory.filter((event) => event.event === 'return')
108
+ const currentCycle = Math.max(Number(state?.cycle) || 1, returnEvents.length + 1)
109
+ const cycleOfTime = (value) => {
110
+ const time = new Date(value || 0).getTime()
111
+ if (!Number.isFinite(time)) return currentCycle
112
+ return 1 + returnEvents.filter((event) => new Date(event.at).getTime() <= time).length
113
+ }
114
+ const cycleOfEvent = (event) => Number(event.cycle) || cycleOfTime(event.at)
115
+ const cycleOfRecord = (record) => Number(record.cycle) || cycleOfTime(record.createdAt || record.at)
116
+
117
+ const history = rawHistory.filter((event) => cycleOfEvent(event) === currentCycle)
118
+ const cycleTasks = rawTasks.filter((task) => cycleOfRecord(task) === currentCycle)
119
+ const cycleCcRecords = rawCcRecords.filter((record) => cycleOfRecord(record) === currentCycle)
120
+ const tasksByNode = groupByNode(cycleTasks)
121
+ const ccByNode = groupByNode(cycleCcRecords)
122
+ const lastReturn = [...returnEvents].reverse()[0]
123
+ let predictedNodes = prediction?.nodes || []
124
+ if (
125
+ currentCycle > 1 &&
126
+ lastReturn?.targetNodeId !== undefined &&
127
+ lastReturn?.targetNodeId !== null &&
128
+ !sameId(lastReturn.targetNodeId, workflow.nodeId)
129
+ ) {
130
+ const startIndex = predictedNodes.findIndex((node) =>
131
+ sameId(node.nodeId, lastReturn.targetNodeId)
132
+ )
133
+ if (startIndex > 0) predictedNodes = predictedNodes.slice(startIndex)
134
+ }
135
+ const predictedById = new Map(predictedNodes.map((node) => [String(node.nodeId), node]))
136
+ const predictedDecisions = new Map(
137
+ (prediction?.decisions || []).map((decision) => [String(decision.nodeId), decision])
138
+ )
139
+ const predictedIds = new Set(predictedById.keys())
140
+ const pendingTaskIds = cycleTasks
141
+ .filter((task) => task.status === 'pending')
142
+ .map((task) => String(task.nodeId))
143
+ const activeTokenIds = (state?.tokens || [])
144
+ .filter((token) => token.nodeId != null && !token.blockedTaskId && !token.blockedJoinGroup)
145
+ .map((token) => String(token.nodeId))
146
+ const currentIds = new Set([...activeTokenIds, ...pendingTaskIds])
147
+
148
+ const actualDecisions = new Map()
149
+ history.forEach((event) => {
150
+ if (event.event !== 'branch' && event.event !== 'split') return
151
+ const key = String(event.nodeId)
152
+ if (!actualDecisions.has(key)) actualDecisions.set(key, new Set())
153
+ const ids = actualDecisions.get(key)
154
+ if (event.branchId !== undefined && event.branchId !== null) ids.add(String(event.branchId))
155
+ ;(event.branchIds || []).forEach((id) => ids.add(String(id)))
156
+ })
157
+
158
+ const isTerminal =
159
+ !!state && ['completed', 'rejected', 'cancelled'].includes(state.status)
160
+
161
+ const hasEvent = (nodeId, name) =>
162
+ history.some(
163
+ (event) => event.event === name && sameId(event.nodeId, nodeId)
164
+ )
165
+
166
+ function resolveDecision(node) {
167
+ const id = String(node.nodeId)
168
+ if (actualDecisions.has(id)) {
169
+ return { ids: [...actualDecisions.get(id)], source: 'actual' }
170
+ }
171
+ if (node.type === FlowNodeType.PARALLEL) {
172
+ return {
173
+ ids: (node.branchList || []).map((branch) => String(branch.nodeId)),
174
+ source: 'parallel'
175
+ }
176
+ }
177
+ const decision = predictedDecisions.get(id)
178
+ const ids = selectedIdsFromDecision(decision)
179
+ return ids ? { ids, source: 'prediction' } : null
180
+ }
181
+
182
+ function resolveStatus(node, branchSkipped) {
183
+ if (branchSkipped) return 'skipped'
184
+ const id = String(node.nodeId)
185
+ if (currentIds.has(id)) return 'current'
186
+ const tasks = tasksByNode.get(id) || []
187
+
188
+ if (node.type === FlowNodeType.APPROVE) {
189
+ const task = latestTask(tasks)
190
+ if (task?.status === 'pending') return 'current'
191
+ if (task?.status === 'rejected') return 'rejected'
192
+ if (task?.status === 'approved') return 'completed'
193
+ if (hasEvent(id, 'autoApprove')) return 'completed'
194
+ } else if (node.type === FlowNodeType.CC) {
195
+ if (ccByNode.has(id) || hasEvent(id, 'cc')) return 'completed'
196
+ } else if (node.type === FlowNodeType.CUSTOM) {
197
+ const task = latestTask(tasks)
198
+ if (task?.status === 'pending') return 'current'
199
+ if (task?.status === 'completed') return 'completed'
200
+ if (task?.status === 'failed') return 'failed'
201
+ } else if (node.type === FlowNodeType.START) {
202
+ if (
203
+ hasEvent(id, 'enter') ||
204
+ hasEvent(id, 'start') ||
205
+ hasEvent(id, 'resubmit') ||
206
+ (currentCycle === 1 && state?.startedAt)
207
+ ) {
208
+ return 'completed'
209
+ }
210
+ } else if (node.type === FlowNodeType.END) {
211
+ if (hasEvent(id, 'end') || state?.status === 'completed') return 'completed'
212
+ } else if (node.type === FlowNodeType.PASS) {
213
+ if (hasEvent(id, 'pass')) return 'completed'
214
+ } else if (node.type === FlowNodeType.REJECT) {
215
+ if (hasEvent(id, 'rejectNode')) return 'rejected'
216
+ } else if (GROUP_TYPES.has(node.type)) {
217
+ if (actualDecisions.has(id) || hasEvent(id, 'branch') || hasEvent(id, 'split')) {
218
+ return 'completed'
219
+ }
220
+ }
221
+
222
+ if (state) {
223
+ if (isTerminal) return 'skipped'
224
+ if (prediction) return predictedIds.has(id) ? 'upcoming' : 'skipped'
225
+ return 'pending'
226
+ }
227
+ return predictedIds.has(id) ? 'predicted' : 'skipped'
228
+ }
229
+
230
+ function buildApprovers(node) {
231
+ const tasks = tasksByNode.get(String(node.nodeId)) || []
232
+ const predictionNode = predictedById.get(String(node.nodeId))
233
+ if (tasks.length) {
234
+ const task = latestTask(tasks)
235
+ if (task) {
236
+ return (task.approvers || []).map((approver) => ({
237
+ id: approver.id,
238
+ name: approver.name,
239
+ deptName: approver.deptName || '',
240
+ done: (task.approvedBy || []).some((item) => sameId(item.id, approver.id)),
241
+ status: task.status
242
+ }))
243
+ }
244
+ }
245
+ return (predictionNode?.approvers || []).map((approver) => ({
246
+ ...approver,
247
+ done: false,
248
+ status: 'pending'
249
+ }))
250
+ }
251
+
252
+ function buildCcUsers(node) {
253
+ const records = ccByNode.get(String(node.nodeId)) || []
254
+ if (records.length) {
255
+ const record = records.at(-1)
256
+ return (record.users || []).map((user) => ({
257
+ id: user.id,
258
+ name: user.name,
259
+ deptName: user.deptName || '',
260
+ done: true
261
+ }))
262
+ }
263
+ const predictionNode = predictedById.get(String(node.nodeId))
264
+ return (predictionNode?.ccUsers || []).map((user) => ({
265
+ ...user,
266
+ done: false
267
+ }))
268
+ }
269
+
270
+ function buildNote(node, status) {
271
+ const predictionNode = predictedById.get(String(node.nodeId))
272
+ if (status === 'current') {
273
+ if (node.type === FlowNodeType.START) {
274
+ return '等待发起人修改表单后重新提交'
275
+ }
276
+ if (node.type === FlowNodeType.APPROVE) {
277
+ const task = latestTask(tasksByNode.get(String(node.nodeId)) || [])
278
+ const timeout = task?.dueAt
279
+ ? ` · ${task.termMode === 1 ? '超时自动拒绝' : '超时自动通过'} ${formatDateTime(task.dueAt, { short: true })}`
280
+ : ''
281
+ if (task && (task.approvedBy || []).length) {
282
+ return `等待其余审批人(已同意 ${task.approvedBy.length}/${task.approvers.length})${timeout}`
283
+ }
284
+ return `等待审批${timeout}`
285
+ }
286
+ if (node.type === FlowNodeType.CUSTOM) {
287
+ return `等待系统执行:${customNodeSummary(node.custom)}`
288
+ }
289
+ return '正在执行'
290
+ }
291
+ if (status === 'rejected' && hasEvent(node.nodeId, 'rejectLimitReached')) {
292
+ return '已达到最大退回次数,流程不通过'
293
+ }
294
+ if (hasEvent(node.nodeId, 'autoApprove')) {
295
+ return '未解析到审批人,系统已自动通过'
296
+ }
297
+ if (node.type === FlowNodeType.REJECT && status === 'rejected') {
298
+ return '流程在此直接拒绝'
299
+ }
300
+ if (node.type === FlowNodeType.END && status === 'completed') {
301
+ return '流程结束'
302
+ }
303
+ if (node.type === FlowNodeType.CUSTOM) {
304
+ const task = latestTask(tasksByNode.get(String(node.nodeId)) || [])
305
+ if (status === 'failed') {
306
+ return task?.lastError ? `执行失败:${task.lastError}` : '自定义节点执行失败'
307
+ }
308
+ if (status === 'completed') {
309
+ return task?.custom?.resultVariable
310
+ ? `执行成功,结果已写入 ${task.custom.resultVariable}`
311
+ : '自定义节点执行成功'
312
+ }
313
+ return predictionNode?.note || `系统执行:${customNodeSummary(node.custom)}`
314
+ }
315
+ return predictionNode?.note || ''
316
+ }
317
+
318
+ function buildChildStatus(items, skipped, fallback) {
319
+ if (skipped) return 'skipped'
320
+ if (!items.length) return fallback
321
+ const statuses = items.map((item) => item.status)
322
+ if (statuses.includes('current')) return 'current'
323
+ if (statuses.includes('rejected')) return 'rejected'
324
+ if (statuses.includes('upcoming')) return 'upcoming'
325
+ if (statuses.includes('predicted')) return 'predicted'
326
+ if (statuses.every((status) => status === 'completed' || status === 'skipped')) {
327
+ return 'completed'
328
+ }
329
+ return fallback
330
+ }
331
+
332
+ const seen = new Set()
333
+ const statusMap = {}
334
+ let sequence = 0
335
+
336
+ function buildGroupItem(node, branchSkipped) {
337
+ const status = resolveStatus(node, branchSkipped)
338
+ const decision = resolveDecision(node)
339
+ const groupSkipped = branchSkipped || status === 'skipped'
340
+ const branches = (node.branchList || []).map((branch) => {
341
+ const selected = decision?.ids
342
+ ? decision.ids.includes(String(branch.nodeId))
343
+ : null
344
+ const skipped = groupSkipped || selected === false
345
+ const items = branch.childNode ? buildChain(branch.childNode, skipped) : []
346
+ const branchStatus = selected === false
347
+ ? 'skipped'
348
+ : buildChildStatus(items, skipped, status === 'completed' ? 'completed' : status)
349
+ const condition = conditionText(branch)
350
+ statusMap[String(branch.nodeId)] = {
351
+ nodeId: branch.nodeId,
352
+ nodeName: branch.nodeName,
353
+ type: branch.type,
354
+ kind: 'branch',
355
+ status: branchStatus,
356
+ statusLabel: NODE_STATUS_LABEL[branchStatus] || branchStatus,
357
+ selected,
358
+ branchName: branch.nodeName,
359
+ conditionText: condition,
360
+ decisionText: selected === false ? '未命中' : selected ? '命中' : ''
361
+ }
362
+ return {
363
+ key: `branch_${branch.nodeId}_${++sequence}`,
364
+ branchId: branch.nodeId,
365
+ branchName: branch.nodeName,
366
+ conditionText: condition,
367
+ selected,
368
+ status: branchStatus,
369
+ statusLabel: NODE_STATUS_LABEL[branchStatus] || branchStatus,
370
+ items
371
+ }
372
+ })
373
+
374
+ const selectedNames = branches
375
+ .filter((branch) => branch.selected)
376
+ .map((branch) => branch.branchName)
377
+ let decisionText = ''
378
+ if (node.type === FlowNodeType.PARALLEL) {
379
+ decisionText = branches.length
380
+ ? `${branches.length} 个分支并行执行`
381
+ : '未配置并行分支'
382
+ } else if (node.type === FlowNodeType.INCLUSIVE) {
383
+ decisionText = selectedNames.length
384
+ ? `命中:${selectedNames.join('、')}`
385
+ : '未命中分支,直接进入后续节点'
386
+ } else {
387
+ decisionText = selectedNames.length
388
+ ? `命中「${selectedNames.join('、')}」`
389
+ : '未命中条件分支'
390
+ }
391
+
392
+ const predictionNode = predictedById.get(String(node.nodeId))
393
+ const note = predictionNode?.note || ''
394
+ const groupInfo = {
395
+ kind: 'group',
396
+ key: `group_${node.nodeId}_${++sequence}`,
397
+ groupType: node.type,
398
+ nodeId: node.nodeId,
399
+ nodeName: node.nodeName,
400
+ typeLabel: NodeTypeLabel[node.type] || node.type,
401
+ status,
402
+ statusLabel: GROUP_STATUS_LABEL[status] || status,
403
+ decisionText,
404
+ branches,
405
+ note
406
+ }
407
+ statusMap[String(node.nodeId)] = {
408
+ nodeId: node.nodeId,
409
+ nodeName: node.nodeName,
410
+ type: node.type,
411
+ kind: 'group',
412
+ status,
413
+ statusLabel: GROUP_STATUS_LABEL[status] || status,
414
+ decisionText,
415
+ note
416
+ }
417
+ return groupInfo
418
+ }
419
+
420
+ function buildNodeItem(node, branchSkipped) {
421
+ const status = resolveStatus(node, branchSkipped)
422
+ const isApprove = node.type === FlowNodeType.APPROVE
423
+ const isCc = node.type === FlowNodeType.CC
424
+ const approvers = isApprove ? buildApprovers(node) : []
425
+ const ccUsers = isCc ? buildCcUsers(node) : []
426
+ const note = buildNote(node, status)
427
+ const signModeLabel = isApprove
428
+ ? SignModeLabel[node.signMode === 'or' ? 'or' : 'and']
429
+ : ''
430
+ const approverTypeLabel = isApprove
431
+ ? ApproverTypeLabel[node.approverType || 'user'] || node.approverType || ''
432
+ : ''
433
+ statusMap[String(node.nodeId)] = {
434
+ nodeId: node.nodeId,
435
+ nodeName: node.nodeName,
436
+ type: node.type,
437
+ kind: 'node',
438
+ status,
439
+ statusLabel: NODE_STATUS_LABEL[status] || status,
440
+ signModeLabel,
441
+ approverTypeLabel,
442
+ approvers,
443
+ ccUsers,
444
+ note
445
+ }
446
+ return {
447
+ kind: 'node',
448
+ key: `node_${node.nodeId}_${++sequence}`,
449
+ nodeId: node.nodeId,
450
+ nodeName: node.nodeName,
451
+ type: node.type,
452
+ typeLabel: NodeTypeLabel[node.type] || node.type || '节点',
453
+ status,
454
+ statusLabel: NODE_STATUS_LABEL[status] || status,
455
+ signModeLabel,
456
+ approverTypeLabel,
457
+ approvers,
458
+ ccUsers,
459
+ note
460
+ }
461
+ }
462
+
463
+ function buildChain(startNode, branchSkipped = false) {
464
+ const items = []
465
+ let node = startNode
466
+ let guard = 0
467
+ while (node && guard < 2000) {
468
+ guard += 1
469
+ const key = String(node.nodeId)
470
+ if (seen.has(key)) break
471
+ seen.add(key)
472
+ if (GROUP_TYPES.has(node.type)) {
473
+ items.push(buildGroupItem(node, branchSkipped))
474
+ node = node.childNode
475
+ continue
476
+ }
477
+ items.push(buildNodeItem(node, branchSkipped))
478
+ if (TERMINAL_TYPES.has(node.type)) break
479
+ node = node.childNode
480
+ }
481
+ return items
482
+ }
483
+
484
+ const items = buildChain(workflow)
485
+ const usedStatuses = new Set(Object.values(statusMap).map((item) => item.status))
486
+
487
+ return {
488
+ items,
489
+ statusMap,
490
+ usedStatuses: [...usedStatuses],
491
+ mode: state ? 'progress' : 'prediction',
492
+ cycle: state ? currentCycle : 1,
493
+ initiator: prediction?.initiator || state?.initiator || null
494
+ }
495
+ }
496
+
497
+ /**
498
+ * 折叠未命中的分支:statusMap 中分支节点带 selected 标记,
499
+ * selected === false 表示该条件没命中,连同其子链一起裁掉。
500
+ * 用于「实际进度 / 预测路径」视图,让不走的流程不占版面。
501
+ */
502
+ export function pruneUnselectedBranches(workflow, statusMap = {}) {
503
+ if (!workflow) return null
504
+ const next = { ...workflow }
505
+ if (Array.isArray(workflow.branchList)) {
506
+ const kept = workflow.branchList
507
+ .filter((branch) => statusMap[String(branch.nodeId)]?.selected !== false)
508
+ .map((branch) => ({
509
+ ...branch,
510
+ childNode: pruneUnselectedBranches(branch.childNode, statusMap)
511
+ }))
512
+ // 兜底:万一整组都被判为未命中,保留原分支避免渲染出空组
513
+ next.branchList = kept.length ? kept : workflow.branchList
514
+ }
515
+ next.childNode = pruneUnselectedBranches(workflow.childNode, statusMap)
516
+ return next
517
+ }