gbflowengine 0.0.0-stage → 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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +270 -2
  3. package/dist/gbflowengine.css +1 -0
  4. package/dist/gbflowengine.js +19682 -0
  5. package/dist/gbflowengine.js.map +1 -0
  6. package/dist/gbflowengine.umd.cjs +5 -0
  7. package/dist/gbflowengine.umd.cjs.map +1 -0
  8. package/package.json +83 -4
  9. package/src/center/DefinitionInspect.vue +291 -0
  10. package/src/center/FlowCenter.vue +33 -0
  11. package/src/center/index.js +29 -0
  12. package/src/center/storage.js +748 -0
  13. package/src/core/flow/condition.js +160 -0
  14. package/src/core/flow/customNode.js +385 -0
  15. package/src/core/flow/defaults.js +124 -0
  16. package/src/core/flow/flowConstant.js +265 -0
  17. package/src/core/flow/flowNodeUtils.js +30 -0
  18. package/src/core/flow/index.js +47 -0
  19. package/src/core/flow/node.js +44 -0
  20. package/src/core/flow/nodeFactory.js +58 -0
  21. package/src/core/flow/prediction.js +325 -0
  22. package/src/core/flow/runtime/auto.js +83 -0
  23. package/src/core/flow/runtime/decide.js +329 -0
  24. package/src/core/flow/runtime/event.js +28 -0
  25. package/src/core/flow/runtime/execute.js +357 -0
  26. package/src/core/flow/runtime/helpers.js +52 -0
  27. package/src/core/flow/runtime/query.js +146 -0
  28. package/src/core/flow/runtime/reject.js +137 -0
  29. package/src/core/flow/runtime/token.js +269 -0
  30. package/src/core/flow/runtime.js +129 -0
  31. package/src/core/flow/schema.js +864 -0
  32. package/src/definition/FlowDefinitionDesigner.vue +338 -0
  33. package/src/definition/index.js +9 -0
  34. package/src/index.js +39 -0
  35. package/src/storage.js +200 -0
  36. package/src/testing/FlowTestPanel.vue +2502 -0
  37. package/src/testing/UserConfigDrawer.vue +376 -0
  38. package/src/testing/diagram/FlowProgressDiagram.vue +318 -0
  39. package/src/testing/diagramModel.js +517 -0
  40. package/src/testing/index.js +23 -0
  41. package/src/testing/mock.js +246 -0
  42. package/src/testing/oaExecutors.js +51 -0
  43. package/src/testing/oaSeed.js +467 -0
  44. package/src/testing/sample.js +412 -0
  45. package/src/testing/seed.js +122 -0
  46. package/src/utils/format.js +27 -0
  47. package/src/visual/FlowCanvas.vue +441 -0
  48. package/src/visual/NodeProgressDetail.vue +43 -0
  49. package/src/visual/NodeStatusBadge.vue +17 -0
  50. package/src/visual/NodeWrap.vue +47 -0
  51. package/src/visual/ScWorkflow.vue +50 -0
  52. package/src/visual/SelectDialog.vue +460 -0
  53. package/src/visual/conditionHelpers.js +117 -0
  54. package/src/visual/index.js +6 -0
  55. package/src/visual/nodes/AddNode.vue +223 -0
  56. package/src/visual/nodes/ApproverNode.vue +348 -0
  57. package/src/visual/nodes/BranchNode.vue +442 -0
  58. package/src/visual/nodes/CustomNode.vue +339 -0
  59. package/src/visual/nodes/EndNode.vue +22 -0
  60. package/src/visual/nodes/PassNode.vue +101 -0
  61. package/src/visual/nodes/PromoterNode.vue +135 -0
  62. package/src/visual/nodes/RejectNode.vue +101 -0
  63. package/src/visual/nodes/SendNode.vue +152 -0
  64. package/src/visual/styles.scss +879 -0
  65. package/src/visual/useScNodeStatus.js +18 -0
  66. package/src/workbench/OaWorkbench.vue +1341 -0
  67. package/src/workbench/components/ApprovalWorkspace.vue +2090 -0
  68. package/src/workbench/components/CategoryIcon.vue +74 -0
  69. package/src/workbench/components/NotificationIcon.vue +73 -0
  70. package/src/workbench/components/ProcessSteps.vue +557 -0
  71. package/src/workbench/components/ResubmitDialog.vue +227 -0
  72. package/src/workbench/components/SidebarNav.vue +138 -0
  73. package/src/workbench/components/StartFlowDialog.vue +1058 -0
  74. package/src/workbench/components/UserAvatar.vue +68 -0
  75. package/src/workbench/custom-tasks.js +130 -0
  76. package/src/workbench/model.js +1080 -0
  77. package/src/workbench/pages/DesignPage.vue +798 -0
  78. package/src/workbench/pages/HomePage.vue +1050 -0
  79. package/src/workbench/pages/MonitorPage.vue +1029 -0
  80. package/src/workbench/pages/NotificationsPage.vue +554 -0
  81. package/src/workbench/pages/RequestsPage.vue +644 -0
  82. package/src/workbench/pages/TaskCenterPage.vue +1155 -0
  83. package/src/workbench/pages/TemplatesPage.vue +680 -0
  84. package/src/workbench/persistence.js +89 -0
  85. package/src/workbench/shared.js +18 -0
  86. package/src/workbench/styles.scss +555 -0
  87. package/src/workbench/useWorkbench.js +955 -0
  88. package/types/center.d.ts +5 -0
  89. package/types/core.d.ts +479 -0
  90. package/types/definition.d.ts +4 -0
  91. package/types/index.d.ts +34 -0
  92. package/types/testing.d.ts +20 -0
  93. package/types/visual.d.ts +20 -0
@@ -0,0 +1,1080 @@
1
+ /**
2
+ * OA 工作台的纯数据模型:只做派生与格式化,不依赖 Vue 或浏览器 API。
3
+ * 列表、通知、监控指标、流程轨迹都从这里生成,便于单测与复用。
4
+ */
5
+ import { getAllNodes } from '../core/flow/index.js'
6
+ import { FlowNodeType, SignModeLabel } from '../core/flow/flowConstant.js'
7
+ import { formatDateTime } from '../utils/format.js'
8
+ import { customNodeSummary } from '../core/flow/customNode.js'
9
+
10
+ const HOUR = 3600 * 1000
11
+ const DAY = 24 * HOUR
12
+
13
+ export const INSTANCE_STATUS = {
14
+ idle: { label: '未开始', tone: 'neutral' },
15
+ running: { label: '审批中', tone: 'info' },
16
+ completed: { label: '已通过', tone: 'success' },
17
+ rejected: { label: '已驳回', tone: 'danger' },
18
+ cancelled: { label: '已终止', tone: 'neutral' },
19
+ revoked: { label: '已撤回', tone: 'neutral' }
20
+ }
21
+
22
+ export const TASK_ACTION_LABEL = {
23
+ approve: '同意',
24
+ reject: '驳回',
25
+ transfer: '转交',
26
+ addSign: '加签',
27
+ resubmit: '重新提交',
28
+ execute: '执行成功',
29
+ executeFailed: '执行失败'
30
+ }
31
+
32
+ export const PRIORITY_META = {
33
+ urgent: { label: '加急', tone: 'danger', rank: 0 },
34
+ high: { label: '优先', tone: 'warning', rank: 1 },
35
+ normal: { label: '常规', tone: 'neutral', rank: 2 }
36
+ }
37
+
38
+ export const NOTIFICATION_META = {
39
+ todo: { label: '待办', tone: 'info' },
40
+ overdue: { label: '超时', tone: 'danger' },
41
+ urge: { label: '催办', tone: 'warning' },
42
+ cc: { label: '抄送', tone: 'neutral' },
43
+ result: { label: '结果', tone: 'success' }
44
+ }
45
+
46
+ const CATEGORY_HINTS = [
47
+ { keys: ['采购', 'purchase', 'buy'], category: '采购', codePrefix: 'CG' },
48
+ { keys: ['报销', '费用', 'expense', 'reimburse'], category: '财务', codePrefix: 'BX' },
49
+ { keys: ['合同', '法务', 'contract', 'legal'], category: '法务', codePrefix: 'HT' },
50
+ { keys: ['请假', '入职', '人事', 'leave', 'hr'], category: '人事', codePrefix: 'QJ' }
51
+ ]
52
+
53
+ const MONEY_KEY = /(amount|total|price|cost|money|budget|金额)/i
54
+ const KEY_VARIABLE_ORDER = [
55
+ 'amount',
56
+ 'contractName',
57
+ 'days',
58
+ 'category',
59
+ 'leaveType',
60
+ 'expenseType',
61
+ 'counterparty',
62
+ 'reason',
63
+ 'applyDate',
64
+ 'startDate'
65
+ ]
66
+
67
+ export const sameId = (left, right) =>
68
+ left !== undefined && left !== null && right !== undefined && right !== null
69
+ ? String(left) === String(right)
70
+ : false
71
+
72
+ export function statusMeta(status) {
73
+ return INSTANCE_STATUS[status] || INSTANCE_STATUS.idle
74
+ }
75
+
76
+ export function formatMoney(value) {
77
+ const number = Number(value)
78
+ if (!Number.isFinite(number)) return '—'
79
+ return `¥ ${number.toLocaleString('zh-CN', {
80
+ minimumFractionDigits: Number.isInteger(number) ? 0 : 2,
81
+ maximumFractionDigits: 2
82
+ })}`
83
+ }
84
+
85
+ export function formatNumber(value) {
86
+ const number = Number(value)
87
+ return Number.isFinite(number) ? number.toLocaleString('zh-CN') : String(value ?? '—')
88
+ }
89
+
90
+ export function formatRelativeTime(value, now = Date.now()) {
91
+ const time = new Date(value || 0).getTime()
92
+ if (!Number.isFinite(time) || time <= 0) return '—'
93
+ const diff = Math.max(0, now - time)
94
+ if (diff < 60 * 1000) return '刚刚'
95
+ if (diff < HOUR) return `${Math.floor(diff / (60 * 1000))} 分钟前`
96
+ if (diff < DAY) return `${Math.floor(diff / HOUR)} 小时前`
97
+ if (diff < DAY * 2) return `昨天 ${formatDateTime(value).slice(-5)}`
98
+ if (diff < DAY * 7) return `${Math.floor(diff / DAY)} 天前`
99
+ return formatDateTime(value, { short: true })
100
+ }
101
+
102
+ export function formatElapsed(value, now = Date.now()) {
103
+ const time = new Date(value || 0).getTime()
104
+ if (!Number.isFinite(time) || time <= 0) return '—'
105
+ const diff = Math.max(0, now - time)
106
+ if (diff < 60 * 1000) return '刚刚'
107
+ if (diff < HOUR) return `${Math.floor(diff / (60 * 1000))} 分钟`
108
+ if (diff < DAY) {
109
+ const hours = Math.floor(diff / HOUR)
110
+ const minutes = Math.floor((diff % HOUR) / (60 * 1000))
111
+ return minutes ? `${hours} 小时 ${minutes} 分` : `${hours} 小时`
112
+ }
113
+ const days = Math.floor(diff / DAY)
114
+ const hours = Math.floor((diff % DAY) / HOUR)
115
+ return hours ? `${days} 天 ${hours} 小时` : `${days} 天`
116
+ }
117
+
118
+ export function formatSla(hours) {
119
+ const value = Number(hours)
120
+ if (!Number.isFinite(value) || value <= 0) return '按实际处理'
121
+ if (value < 8) return '当日办结'
122
+ if (value <= 24) return '1 个工作日内'
123
+ if (value <= 48) return '2 个工作日内'
124
+ return `${Math.ceil(value / 24)} 个工作日内`
125
+ }
126
+
127
+ export function getAmount(instance) {
128
+ const variables = instance?.state?.variables || {}
129
+ const businessFields = instance?.definition?.meta?.business?.keyFields || []
130
+ const moneyField = businessFields.find((field) => field.type === 'money')
131
+ const candidates = [
132
+ moneyField?.variable,
133
+ 'amount',
134
+ 'total',
135
+ 'contractAmount',
136
+ 'expenseAmount'
137
+ ].filter(Boolean)
138
+ for (const key of candidates) {
139
+ const value = Number(variables[key])
140
+ if (Number.isFinite(value)) return value
141
+ }
142
+ const matched = Object.entries(variables).find(
143
+ ([key, value]) => MONEY_KEY.test(key) && Number.isFinite(Number(value))
144
+ )
145
+ return matched ? Number(matched[1]) : null
146
+ }
147
+
148
+ export function resolveBusiness(definition) {
149
+ const source = definition?.meta?.business || {}
150
+ const text = `${definition?.meta?.name || ''} ${(definition?.meta?.tags || []).join(' ')}`
151
+ const hint = CATEGORY_HINTS.find((item) =>
152
+ item.keys.some((key) => text.toLowerCase().includes(String(key).toLowerCase()))
153
+ )
154
+ return {
155
+ category: source.category || hint?.category || '通用',
156
+ scenario: source.scenario || definition?.meta?.description || '按标准流程完成申请与审批',
157
+ slaHours: Number(source.slaHours) || 24,
158
+ codePrefix: source.codePrefix || hint?.codePrefix || 'SP',
159
+ materials: Array.isArray(source.materials) ? source.materials : [],
160
+ keyFields: Array.isArray(source.keyFields) ? source.keyFields : [],
161
+ popularity: Number(source.popularity) || 50,
162
+ owner: source.owner || '流程管理部'
163
+ }
164
+ }
165
+
166
+ export function instanceCode(instance) {
167
+ if (instance?.code) return instance.code
168
+ const prefix = resolveBusiness(instance?.definition).codePrefix
169
+ const created = new Date(instance?.createdAt || Date.now())
170
+ const stamp = `${created.getFullYear()}${String(created.getMonth() + 1).padStart(2, '0')}${String(
171
+ created.getDate()
172
+ ).padStart(2, '0')}`
173
+ return `${prefix}-${stamp}-${String(instance?.id || '').slice(-3).toUpperCase() || '001'}`
174
+ }
175
+
176
+ export function instanceTitle(instance) {
177
+ return instance?.name || instance?.definition?.meta?.name || '未命名流程'
178
+ }
179
+
180
+ export function instanceSlaHours(instance) {
181
+ return resolveBusiness(instance?.definition).slaHours
182
+ }
183
+
184
+ export function taskWaitHours(task, now = Date.now()) {
185
+ const created = new Date(task?.createdAt || 0).getTime()
186
+ if (!Number.isFinite(created) || created <= 0) return 0
187
+ return Math.max(0, (now - created) / HOUR)
188
+ }
189
+
190
+ export function isTaskOverdue(instance, task, now = Date.now()) {
191
+ if (!task || task.status !== 'pending') return false
192
+ if (task.dueAt) return new Date(task.dueAt).getTime() <= now
193
+ const slaHours = Math.min(instanceSlaHours(instance), 24)
194
+ return taskWaitHours(task, now) > slaHours
195
+ }
196
+
197
+ export function isTaskDueSoon(instance, task, now = Date.now()) {
198
+ if (!task || task.status !== 'pending' || isTaskOverdue(instance, task, now)) return false
199
+ if (task.dueAt) {
200
+ const remaining = new Date(task.dueAt).getTime() - now
201
+ return remaining <= 4 * HOUR
202
+ }
203
+ const slaHours = Math.min(instanceSlaHours(instance), 24)
204
+ const remaining = slaHours - taskWaitHours(task, now)
205
+ return remaining > 0 && remaining <= 4
206
+ }
207
+
208
+ export function taskPriority(instance, task, now = Date.now()) {
209
+ const amount = getAmount(instance) || 0
210
+ if (instance?.priority === 'urgent') return 'urgent'
211
+ if (isTaskOverdue(instance, task, now)) return 'urgent'
212
+ if (amount >= 100000) return 'urgent'
213
+ if (instance?.priority === 'high') return 'high'
214
+ if (amount >= 30000) return 'high'
215
+ if (taskWaitHours(task, now) >= 8) return 'high'
216
+ return 'normal'
217
+ }
218
+
219
+ function collectFields(components, result = []) {
220
+ ;(components || []).forEach((component) => {
221
+ if (!component) return
222
+ if (Array.isArray(component.children) && component.children.length) {
223
+ component.children.forEach((child) => {
224
+ collectFields(Array.isArray(child) ? child : [child], result)
225
+ })
226
+ return
227
+ }
228
+ const variableName = component.props?.variableName
229
+ if (!variableName) return
230
+ result.push({
231
+ label: component.props?.label || variableName,
232
+ variableName,
233
+ type: component.type || 'input',
234
+ required: Boolean(component.required),
235
+ options: Array.isArray(component.props?.options) ? component.props.options : [],
236
+ width: component.style?.width || '100%'
237
+ })
238
+ })
239
+ return result
240
+ }
241
+
242
+ export function getFormFields(definition) {
243
+ return collectFields(definition?.form?.components)
244
+ }
245
+
246
+ function optionLabel(field, value) {
247
+ const option = field.options.find((item) => sameId(item.value, value))
248
+ return option?.label || String(value)
249
+ }
250
+
251
+ export function formatFieldValue(field, value) {
252
+ if (value === null || value === undefined || value === '') return '—'
253
+ if (typeof value === 'boolean') return value ? '是' : '否'
254
+ if (Array.isArray(value)) {
255
+ if (!value.length) return '—'
256
+ return value.map((item) => optionLabel(field, item)).join('、')
257
+ }
258
+ if (
259
+ field.type === 'checkbox-group' ||
260
+ field.type === 'select' ||
261
+ field.type === 'radio-group' ||
262
+ field.type === 'radio'
263
+ ) {
264
+ return optionLabel(field, value)
265
+ }
266
+ if (field.type === 'date-picker' || /date/i.test(field.variableName)) {
267
+ return formatDateTime(value, { dateOnly: true })
268
+ }
269
+ if (field.type === 'input-number' || MONEY_KEY.test(field.variableName)) {
270
+ return MONEY_KEY.test(field.variableName) ? formatMoney(value) : formatNumber(value)
271
+ }
272
+ return String(value)
273
+ }
274
+
275
+ export function buildFormEntries(instanceOrDefinition, variablesArg) {
276
+ const definition = instanceOrDefinition?.definition || instanceOrDefinition
277
+ const variables = variablesArg || instanceOrDefinition?.state?.variables || {}
278
+ return getFormFields(definition).map((field) => ({
279
+ ...field,
280
+ value: formatFieldValue(field, variables[field.variableName]),
281
+ rawValue: variables[field.variableName],
282
+ wide: field.width === '100%' || field.type === 'textarea'
283
+ }))
284
+ }
285
+
286
+ export function buildKeyFacts(instance) {
287
+ const variables = instance?.state?.variables || {}
288
+ const fields = getFormFields(instance?.definition)
289
+ const fieldIndex = new Map(fields.map((field) => [field.variableName, field]))
290
+ const business = resolveBusiness(instance?.definition)
291
+ let keyFields = business.keyFields
292
+ if (!keyFields.length) {
293
+ keyFields = [...fields]
294
+ .sort((left, right) => {
295
+ const leftIndex = KEY_VARIABLE_ORDER.indexOf(left.variableName)
296
+ const rightIndex = KEY_VARIABLE_ORDER.indexOf(right.variableName)
297
+ return (
298
+ (leftIndex < 0 ? 99 : leftIndex) - (rightIndex < 0 ? 99 : rightIndex)
299
+ )
300
+ })
301
+ .slice(0, 4)
302
+ .map((field) => ({
303
+ variable: field.variableName,
304
+ label: field.label,
305
+ type: MONEY_KEY.test(field.variableName) ? 'money' : undefined,
306
+ emphasis: MONEY_KEY.test(field.variableName)
307
+ }))
308
+ }
309
+ return keyFields
310
+ .map((item) => {
311
+ const field = fieldIndex.get(item.variable) || {
312
+ variableName: item.variable,
313
+ label: item.label || item.variable,
314
+ type: 'input'
315
+ }
316
+ const raw = variables[item.variable]
317
+ let value = formatFieldValue(field, raw)
318
+ if (item.type === 'money') value = formatMoney(raw)
319
+ return {
320
+ key: item.variable,
321
+ label: item.label || field.label,
322
+ value,
323
+ emphasis: Boolean(item.emphasis) || item.type === 'money',
324
+ raw
325
+ }
326
+ })
327
+ .filter((item) => item.value !== '—')
328
+ }
329
+
330
+ export function currentPendingTasks(instance) {
331
+ return (instance?.state?.tasks || []).filter((task) => task.status === 'pending')
332
+ }
333
+
334
+ export function pendingTasksFor(instance, userId) {
335
+ return currentPendingTasks(instance).filter((task) => {
336
+ if (task.kind === 'submit') return sameId(instance?.state?.initiator?.id, userId) || sameId(instance?.initiatorId, userId)
337
+ return (
338
+ (task.approvers || []).some((approver) => sameId(approver.id, userId)) &&
339
+ !(task.approvedBy || []).some((approver) => sameId(approver.id, userId))
340
+ )
341
+ })
342
+ }
343
+
344
+ export function buildPendingItems(instances, userId, now = Date.now()) {
345
+ const items = []
346
+ ;(instances || []).forEach((instance) => {
347
+ if (instance?.state?.status !== 'running') return
348
+ pendingTasksFor(instance, userId).forEach((task) => {
349
+ const approver = (task.approvers || []).find((item) => sameId(item.id, userId))
350
+ const overdue = isTaskOverdue(instance, task, now)
351
+ const priority = taskPriority(instance, task, now)
352
+ items.push({
353
+ id: `${instance.id}:${task.id}`,
354
+ instance,
355
+ task,
356
+ kind: task.kind === 'submit' ? 'submit' : 'approve',
357
+ title: instanceTitle(instance),
358
+ code: instanceCode(instance),
359
+ nodeName: task.nodeName,
360
+ initiatorName: instance?.initiator?.name || instance?.state?.initiator?.name || '未知发起人',
361
+ initiatorDept: instance?.initiator?.deptName || instance?.state?.initiator?.deptName || '',
362
+ category: resolveBusiness(instance.definition).category,
363
+ amount: getAmount(instance),
364
+ priority,
365
+ priorityMeta: PRIORITY_META[priority],
366
+ overdue,
367
+ dueSoon: isTaskDueSoon(instance, task, now),
368
+ waitHours: taskWaitHours(task, now),
369
+ arrivedAt: task.createdAt,
370
+ signModeLabel: task.kind === 'submit' ? '' : SignModeLabel[task.signMode] || '',
371
+ progress: {
372
+ approved: (task.approvedBy || []).length,
373
+ total: (task.approvers || []).length
374
+ },
375
+ approver: approver || null,
376
+ cycle: task.cycle || instance?.state?.cycle || 1
377
+ })
378
+ })
379
+ })
380
+ return items.sort((left, right) => {
381
+ if (left.overdue !== right.overdue) return left.overdue ? -1 : 1
382
+ if (left.priority !== right.priority) {
383
+ return PRIORITY_META[left.priority].rank - PRIORITY_META[right.priority].rank
384
+ }
385
+ return String(left.arrivedAt).localeCompare(String(right.arrivedAt))
386
+ })
387
+ }
388
+
389
+ export function buildCcItems(instances, userId) {
390
+ const items = []
391
+ ;(instances || []).forEach((instance) => {
392
+ ;(instance?.state?.ccRecords || []).forEach((record) => {
393
+ if (!(record.users || []).some((user) => sameId(user.id, userId))) return
394
+ items.push({
395
+ id: `${instance.id}:${record.id}`,
396
+ instance,
397
+ record,
398
+ title: instanceTitle(instance),
399
+ code: instanceCode(instance),
400
+ nodeName: record.nodeName,
401
+ initiatorName: instance?.initiator?.name || instance?.state?.initiator?.name || '',
402
+ at: record.createdAt,
403
+ cycle: record.cycle || 1
404
+ })
405
+ })
406
+ })
407
+ return items.sort((left, right) => String(right.at).localeCompare(String(left.at)))
408
+ }
409
+
410
+ export function buildDoneItems(instances, userId) {
411
+ const items = []
412
+ ;(instances || []).forEach((instance) => {
413
+ ;(instance?.state?.tasks || []).forEach((task) => {
414
+ ;(task.records || []).forEach((record) => {
415
+ if (!sameId(record.approver?.id, userId)) return
416
+ items.push({
417
+ id: `${instance.id}:${task.id}:${record.at}`,
418
+ instance,
419
+ task,
420
+ record,
421
+ title: instanceTitle(instance),
422
+ code: instanceCode(instance),
423
+ nodeName: task.nodeName,
424
+ action: record.action,
425
+ actionLabel: TASK_ACTION_LABEL[record.action] || record.action,
426
+ comment: record.comment || '',
427
+ at: record.at,
428
+ targetName: record.target?.name || ''
429
+ })
430
+ })
431
+ })
432
+ })
433
+ return items.sort((left, right) => String(right.at).localeCompare(String(left.at)))
434
+ }
435
+
436
+ function resultTitle(instance) {
437
+ const status = instance?.state?.status
438
+ if (status === 'completed') return '申请已通过'
439
+ if (status === 'rejected') return '申请被驳回'
440
+ if (status === 'revoked') return '申请已撤回'
441
+ if (
442
+ status === 'cancelled' &&
443
+ (instance?.state?.history || []).some((event) => event.event === 'customFailed')
444
+ ) {
445
+ return '流程执行失败,已终止'
446
+ }
447
+ if (status === 'cancelled') return '流程已终止'
448
+ return '流程已结束'
449
+ }
450
+
451
+ export function buildNotifications(instances, userId, readIds = [], now = Date.now()) {
452
+ const read = new Set(readIds)
453
+ const rank = { overdue: 0, urge: 1, todo: 2, cc: 3, result: 4 }
454
+ const notifications = []
455
+ ;(instances || []).forEach((instance) => {
456
+ const status = instance?.state?.status
457
+ const initiatorId = instance?.state?.initiator?.id ?? instance?.initiatorId
458
+ pendingTasksFor(instance, userId).forEach((task) => {
459
+ const id = `todo:${userId}:${instance.id}:${task.id}`
460
+ notifications.push({
461
+ id,
462
+ type: 'todo',
463
+ at: task.createdAt,
464
+ title: task.kind === 'submit' ? '申请已退回,待你修改' : `待你审批 · ${task.nodeName}`,
465
+ description: `${instanceCode(instance)} · ${instanceTitle(instance)}`,
466
+ instance,
467
+ task,
468
+ action: 'task',
469
+ read: read.has(id)
470
+ })
471
+ if (isTaskOverdue(instance, task, now)) {
472
+ const overdueId = `overdue:${userId}:${instance.id}:${task.id}`
473
+ const overdueAt =
474
+ task.dueAt ||
475
+ new Date(
476
+ new Date(task.createdAt).getTime() + Math.min(instanceSlaHours(instance), 24) * HOUR
477
+ ).toISOString()
478
+ notifications.push({
479
+ id: overdueId,
480
+ type: 'overdue',
481
+ at: overdueAt,
482
+ title: `审批已超时 · ${task.nodeName}`,
483
+ description: `${instanceCode(instance)} 已等待 ${formatElapsed(task.createdAt, now)}`,
484
+ instance,
485
+ task,
486
+ action: 'task',
487
+ read: read.has(overdueId)
488
+ })
489
+ }
490
+ })
491
+
492
+ ;(instance?.state?.ccRecords || []).forEach((record) => {
493
+ if (!(record.users || []).some((user) => sameId(user.id, userId))) return
494
+ const id = `cc:${userId}:${instance.id}:${record.id}`
495
+ notifications.push({
496
+ id,
497
+ type: 'cc',
498
+ at: record.createdAt,
499
+ title: '抄送给你',
500
+ description: `${instanceCode(instance)} · ${instanceTitle(instance)} · ${record.nodeName}`,
501
+ instance,
502
+ action: 'instance',
503
+ read: read.has(id)
504
+ })
505
+ })
506
+
507
+ ;(instance?.reminders || []).forEach((reminder) => {
508
+ const task = (instance?.state?.tasks || []).find((item) => item.id === reminder.taskId)
509
+ if (
510
+ !task ||
511
+ task.status !== 'pending' ||
512
+ !(task.approvers || []).some((item) => sameId(item.id, userId))
513
+ ) {
514
+ return
515
+ }
516
+ const id = `urge:${userId}:${instance.id}:${reminder.id}`
517
+ notifications.push({
518
+ id,
519
+ type: 'urge',
520
+ at: reminder.at,
521
+ title: '收到一条催办',
522
+ description: `${reminder.byName || '流程管理员'} 催办了「${task.nodeName}」:${reminder.message || '请尽快处理'}`,
523
+ instance,
524
+ task,
525
+ action: 'task',
526
+ read: read.has(id)
527
+ })
528
+ })
529
+
530
+ if (sameId(initiatorId, userId) && ['completed', 'rejected', 'revoked', 'cancelled'].includes(status)) {
531
+ const id = `result:${userId}:${instance.id}:${status}`
532
+ notifications.push({
533
+ id,
534
+ type: 'result',
535
+ at: instance?.state?.endedAt || instance?.updatedAt,
536
+ title: resultTitle(instance),
537
+ description: `${instanceCode(instance)} · ${instanceTitle(instance)}`,
538
+ instance,
539
+ action: 'instance',
540
+ read: read.has(id)
541
+ })
542
+ }
543
+ })
544
+ return notifications
545
+ .sort((left, right) => {
546
+ if (rank[left.type] !== rank[right.type]) return rank[left.type] - rank[right.type]
547
+ return String(right.at).localeCompare(String(left.at))
548
+ })
549
+ .slice(0, 80)
550
+ }
551
+
552
+ export function buildMonitorMetrics(instances, now = Date.now()) {
553
+ const list = instances || []
554
+ const running = list.filter((item) => item?.state?.status === 'running').length
555
+ const completed = list.filter((item) => item?.state?.status === 'completed').length
556
+ const rejected = list.filter((item) => item?.state?.status === 'rejected').length
557
+ const finished = list.filter((item) =>
558
+ ['completed', 'rejected', 'revoked', 'cancelled'].includes(item?.state?.status)
559
+ )
560
+ const durations = list
561
+ .filter((item) => ['completed', 'rejected'].includes(item?.state?.status))
562
+ .map((item) => {
563
+ const start = new Date(item?.state?.startedAt || item?.createdAt || 0).getTime()
564
+ const end = new Date(item?.state?.endedAt || item?.updatedAt || 0).getTime()
565
+ return start && end && end > start ? (end - start) / HOUR : null
566
+ })
567
+ .filter((value) => Number.isFinite(value) && value > 0)
568
+ const pendingTasks = list.flatMap((instance) =>
569
+ currentPendingTasks(instance).map((task) => ({ instance, task }))
570
+ )
571
+ const overdue = pendingTasks.filter(({ instance, task }) => isTaskOverdue(instance, task, now))
572
+
573
+ const byTemplate = new Map()
574
+ const departments = new Map()
575
+ const bottlenecks = new Map()
576
+ const days = Array.from({ length: 7 }).map((_, index) => {
577
+ const date = new Date(now - (6 - index) * DAY)
578
+ return {
579
+ label: `${date.getMonth() + 1}/${date.getDate()}`,
580
+ key: date.toDateString(),
581
+ count: 0
582
+ }
583
+ })
584
+ const dayIndex = new Map(days.map((day) => [day.key, day]))
585
+
586
+ list.forEach((instance) => {
587
+ const business = resolveBusiness(instance.definition)
588
+ const templateName = instance?.definition?.meta?.name || '未命名流程'
589
+ if (!byTemplate.has(templateName)) {
590
+ byTemplate.set(templateName, {
591
+ name: templateName,
592
+ category: business.category,
593
+ total: 0,
594
+ running: 0,
595
+ completed: 0,
596
+ rejected: 0
597
+ })
598
+ }
599
+ const template = byTemplate.get(templateName)
600
+ template.total += 1
601
+ if (instance?.state?.status === 'running') template.running += 1
602
+ if (instance?.state?.status === 'completed') template.completed += 1
603
+ if (instance?.state?.status === 'rejected') template.rejected += 1
604
+
605
+ const dept = instance?.initiator?.deptName || instance?.state?.initiator?.deptName || '未分配部门'
606
+ departments.set(dept, (departments.get(dept) || 0) + 1)
607
+
608
+ const createdDay = new Date(instance?.createdAt || 0).toDateString()
609
+ if (dayIndex.has(createdDay)) dayIndex.get(createdDay).count += 1
610
+ })
611
+
612
+ pendingTasks.forEach(({ instance, task }) => {
613
+ if (task.kind === 'submit') return
614
+ const templateName = instance?.definition?.meta?.name || '未命名流程'
615
+ const key = `${templateName} · ${task.nodeName}`
616
+ if (!bottlenecks.has(key)) {
617
+ bottlenecks.set(key, {
618
+ key,
619
+ nodeName: task.nodeName,
620
+ templateName,
621
+ count: 0,
622
+ maxWaitHours: 0
623
+ })
624
+ }
625
+ const item = bottlenecks.get(key)
626
+ item.count += 1
627
+ item.maxWaitHours = Math.max(item.maxWaitHours, taskWaitHours(task, now))
628
+ })
629
+
630
+ return {
631
+ total: list.length,
632
+ running,
633
+ completed,
634
+ rejected,
635
+ avgHours: durations.length
636
+ ? durations.reduce((sum, value) => sum + value, 0) / durations.length
637
+ : 0,
638
+ overdueTasks: overdue.length,
639
+ pendingTasks: pendingTasks.length,
640
+ timeoutRate: pendingTasks.length ? (overdue.length / pendingTasks.length) * 100 : 0,
641
+ rejectRate: finished.length ? (rejected / finished.length) * 100 : 0,
642
+ byTemplate: [...byTemplate.values()].sort((left, right) => right.total - left.total),
643
+ departments: [...departments.entries()]
644
+ .map(([name, count]) => ({ name, count }))
645
+ .sort((left, right) => right.count - left.count),
646
+ bottlenecks: [...bottlenecks.values()]
647
+ .sort((left, right) => right.count - left.count || right.maxWaitHours - left.maxWaitHours)
648
+ .slice(0, 5),
649
+ trend: days.map(({ label, count }) => ({ label, count }))
650
+ }
651
+ }
652
+
653
+ function historyActor(event) {
654
+ if (event?.approver) return event.approver.name || ''
655
+ if (event?.initiator) return event.initiator.name || ''
656
+ if (event?.users?.length) return event.users.map((user) => user.name).join('、')
657
+ return '系统'
658
+ }
659
+
660
+ function findNodeName(index, nodeId) {
661
+ if (nodeId === undefined || nodeId === null) return ''
662
+ return index.get(String(nodeId))?.nodeName || ''
663
+ }
664
+
665
+ function historyDetail(instance, event, index) {
666
+ const nodeName = findNodeName(index, event.nodeId)
667
+ switch (event.event) {
668
+ case 'start':
669
+ return `提交「${instanceTitle(instance)}」`
670
+ case 'approve':
671
+ return `${nodeName || '审批'} · ${event.comment || '同意'}`
672
+ case 'reject':
673
+ return `${nodeName || '审批'} · ${event.comment || '驳回'}`
674
+ case 'transfer':
675
+ return `${nodeName || '审批'} · 转交给 ${event.target?.name || '—'}`
676
+ case 'addSign':
677
+ return `${nodeName || '审批'} · 加签 ${event.target?.name || '—'}`
678
+ case 'resubmit':
679
+ return '修改表单后重新提交'
680
+ case 'customCompleted':
681
+ return event.resultVariable
682
+ ? `执行成功,结果已写入 ${event.resultVariable}`
683
+ : '自定义节点执行成功'
684
+ case 'customFailed':
685
+ return `执行失败:${event.error || ''}`
686
+ case 'cc':
687
+ return `${nodeName || '抄送'} · ${(event.users || []).map((user) => user.name).join('、')}`
688
+ case 'branch':
689
+ return `命中分支 ${findNodeName(index, event.branchId) || (event.branchIds || []).map((id) => findNodeName(index, id)).filter(Boolean).join('、') || ''}`
690
+ case 'timeoutApprove':
691
+ return `${nodeName || '审批'} · 超时自动通过`
692
+ case 'timeoutReject':
693
+ return `${nodeName || '审批'} · 超时自动拒绝`
694
+ case 'revoke':
695
+ return event.reason || '发起人撤回'
696
+ case 'cancel':
697
+ return event.reason || '流程终止'
698
+ case 'finished':
699
+ return `流程${statusMeta(event.status).label}`
700
+ case 'join':
701
+ return '并行分支汇聚'
702
+ case 'split':
703
+ return '并行分支展开'
704
+ default:
705
+ return nodeName || event.event
706
+ }
707
+ }
708
+
709
+ const AUDIT_EVENTS = new Set([
710
+ 'start',
711
+ 'approve',
712
+ 'reject',
713
+ 'transfer',
714
+ 'addSign',
715
+ 'resubmit',
716
+ 'customCompleted',
717
+ 'customFailed',
718
+ 'cc',
719
+ 'branch',
720
+ 'timeoutApprove',
721
+ 'timeoutReject',
722
+ 'revoke',
723
+ 'cancel',
724
+ 'finished'
725
+ ])
726
+
727
+ const AUDIT_ACTION = {
728
+ start: '提交申请',
729
+ approve: '同意',
730
+ reject: '驳回',
731
+ transfer: '转办',
732
+ addSign: '加签',
733
+ resubmit: '重新提交',
734
+ customCompleted: '自定义节点成功',
735
+ customFailed: '自定义节点失败',
736
+ cc: '抄送',
737
+ branch: '分支决策',
738
+ timeoutApprove: '超时自动通过',
739
+ timeoutReject: '超时自动拒绝',
740
+ revoke: '撤回',
741
+ cancel: '终止',
742
+ finished: '流程结束'
743
+ }
744
+
745
+ export function buildAuditRows(instances, extraLogs = []) {
746
+ const rows = []
747
+ ;(instances || []).forEach((instance) => {
748
+ const nodes = getAllNodes(instance?.definition?.workflow)
749
+ const index = new Map(nodes.map((node) => [String(node.nodeId), node]))
750
+ ;(instance?.state?.history || []).forEach((event) => {
751
+ if (!AUDIT_EVENTS.has(event.event)) return
752
+ rows.push({
753
+ id: `${instance.id}:${event.id}`,
754
+ at: event.at,
755
+ code: instanceCode(instance),
756
+ instanceName: instanceTitle(instance),
757
+ instance,
758
+ actor: historyActor(event),
759
+ action: AUDIT_ACTION[event.event] || event.event,
760
+ detail: historyDetail(instance, event, index),
761
+ nodeName: findNodeName(index, event.nodeId),
762
+ source: 'engine'
763
+ })
764
+ })
765
+ })
766
+ ;(extraLogs || []).forEach((log) => {
767
+ rows.push({
768
+ id: log.id,
769
+ at: log.at,
770
+ code: log.code || '—',
771
+ instanceName: log.instanceName || '—',
772
+ instance: log.instanceId
773
+ ? (instances || []).find((item) => sameId(item.id, log.instanceId))
774
+ : null,
775
+ actor: log.actorName || '系统',
776
+ action: log.action,
777
+ detail: log.detail || '',
778
+ nodeName: log.nodeName || '',
779
+ source: 'admin'
780
+ })
781
+ })
782
+ return rows.sort((left, right) => String(right.at).localeCompare(String(left.at)))
783
+ }
784
+
785
+ function taskRecordRows(task) {
786
+ return (task?.records || []).map((record) => ({
787
+ action: record.action,
788
+ actionLabel: TASK_ACTION_LABEL[record.action] || record.action,
789
+ actorName: record.approver?.name || '系统',
790
+ targetName: record.target?.name || '',
791
+ comment: record.comment || '',
792
+ at: record.at,
793
+ system: Boolean(record.system)
794
+ }))
795
+ }
796
+
797
+ function terminalStep(instance) {
798
+ const status = instance?.state?.status
799
+ if (!['completed', 'rejected', 'revoked', 'cancelled'].includes(status)) return null
800
+ const customFailure =
801
+ status === 'cancelled'
802
+ ? [...(instance?.state?.history || [])]
803
+ .reverse()
804
+ .find((event) => event.event === 'customFailed')
805
+ : null
806
+ return {
807
+ key: 'end',
808
+ kind: 'end',
809
+ title: customFailure
810
+ ? '自定义节点执行失败'
811
+ : status === 'completed'
812
+ ? '流程完成'
813
+ : status === 'rejected'
814
+ ? '流程被驳回'
815
+ : status === 'revoked'
816
+ ? '发起人已撤回'
817
+ : '管理员已终止',
818
+ subtitle: customFailure ? '流程已终止' : statusMeta(status).label,
819
+ status: customFailure
820
+ ? 'failed'
821
+ : status === 'completed'
822
+ ? 'done'
823
+ : status === 'rejected'
824
+ ? 'rejected'
825
+ : 'cancelled',
826
+ at: instance?.state?.endedAt || instance?.updatedAt,
827
+ actor: instance?.state?.history?.find((event) => event.event === 'cancel' || event.event === 'revoke')?.approver?.name || '',
828
+ records: customFailure
829
+ ? [
830
+ {
831
+ action: 'executeFailed',
832
+ actionLabel: '执行失败',
833
+ actorName: '系统执行器',
834
+ comment: customFailure.error || '自定义节点执行失败',
835
+ at: customFailure.at,
836
+ system: true
837
+ }
838
+ ]
839
+ : [],
840
+ actors: []
841
+ }
842
+ }
843
+
844
+ function predictionNodeToStep(node, index) {
845
+ return {
846
+ key: `prediction_${node.id}_${index}`,
847
+ kind: node.kind,
848
+ title:
849
+ node.kind === 'start'
850
+ ? '提交申请'
851
+ : node.kind === 'cc'
852
+ ? `抄送 · ${node.nodeName}`
853
+ : node.kind === 'end'
854
+ ? '流程结束'
855
+ : node.nodeName,
856
+ subtitle:
857
+ node.kind === 'approve'
858
+ ? `${node.signModeLabel || ''}${node.approvers?.length ? ` · ${node.approvers.map((user) => user.name).join('、')}` : ' · 自动通过'}`
859
+ : node.kind === 'cc'
860
+ ? (node.ccUsers || []).map((user) => user.name).join('、') || '未配置抄送人'
861
+ : node.kind === 'branch' || node.kind === 'parallel' || node.kind === 'inclusive'
862
+ ? node.decision?.branchNames?.join('、') || node.decision?.branchName || ''
863
+ : node.note || '',
864
+ status: 'upcoming',
865
+ at: '',
866
+ records: [],
867
+ actors: [],
868
+ node
869
+ }
870
+ }
871
+
872
+ /**
873
+ * 实际流程轨迹:已发生的任务/抄送/分支事件 + 当前节点;
874
+ * 运行中的实例会从预测路径里补出后续节点(置灰),方便看清完整路径。
875
+ */
876
+ export function buildProcessSteps(instance, prediction = null, now = Date.now()) {
877
+ if (!instance?.state) return []
878
+ const events = []
879
+ const start = {
880
+ key: 'start',
881
+ kind: 'start',
882
+ title: '提交申请',
883
+ subtitle: instance?.state?.initiator?.deptName || '',
884
+ status: 'done',
885
+ at: instance?.state?.startedAt,
886
+ actor: instance?.state?.initiator?.name || instance?.initiator?.name || '发起人',
887
+ records: [],
888
+ actors: []
889
+ }
890
+ events.push(start)
891
+
892
+ ;(instance?.state?.tasks || []).forEach((task) => {
893
+ const approvedBy = new Set((task.approvedBy || []).map((user) => String(user.id)))
894
+ const records = taskRecordRows(task)
895
+ const isCustom = task.kind === 'custom'
896
+ const overdue = !isCustom && task.status === 'pending' && isTaskOverdue(instance, task, now)
897
+ events.push({
898
+ key: `task_${task.id}`,
899
+ kind: isCustom ? 'custom' : task.kind === 'submit' ? 'submit' : 'task',
900
+ title: task.kind === 'submit' ? '发起人修改后重新提交' : task.nodeName,
901
+ subtitle: isCustom
902
+ ? `自定义节点 · ${customNodeSummary(task.custom)}`
903
+ : task.kind === 'submit'
904
+ ? '等待发起人处理'
905
+ : `${SignModeLabel[task.signMode] || ''} · ${(task.approvers || []).length} 人`,
906
+ status:
907
+ task.status === 'pending'
908
+ ? 'current'
909
+ : ['approved', 'completed'].includes(task.status)
910
+ ? 'done'
911
+ : task.status === 'rejected'
912
+ ? 'rejected'
913
+ : task.status === 'failed'
914
+ ? 'failed'
915
+ : 'cancelled',
916
+ at: task.finishedAt || task.records?.at(-1)?.at || task.createdAt,
917
+ createdAt: task.createdAt,
918
+ actor:
919
+ records.length > 0
920
+ ? records.map((record) => record.actorName).join('、')
921
+ : (task.approvers || []).map((user) => user.name).join('、'),
922
+ records,
923
+ actors: isCustom
924
+ ? []
925
+ : (task.approvers || []).map((user) => ({
926
+ name: user.name,
927
+ deptName: user.deptName || '',
928
+ done: approvedBy.has(String(user.id)),
929
+ addedBy: user.addedBy?.name || ''
930
+ })),
931
+ progress: isCustom
932
+ ? undefined
933
+ : {
934
+ approved: approvedBy.size,
935
+ total: (task.approvers || []).length
936
+ },
937
+ overdue,
938
+ waitHours: task.status === 'pending' ? taskWaitHours(task, now) : 0,
939
+ customError: task.lastError || '',
940
+ task
941
+ })
942
+ })
943
+
944
+ ;(instance?.state?.ccRecords || []).forEach((record) => {
945
+ events.push({
946
+ key: `cc_${record.id}`,
947
+ kind: 'cc',
948
+ title: `抄送 · ${record.nodeName}`,
949
+ subtitle: (record.users || []).map((user) => user.name).join('、'),
950
+ status: 'done',
951
+ at: record.createdAt,
952
+ actor: (record.users || []).map((user) => user.name).join('、'),
953
+ records: [],
954
+ actors: (record.users || []).map((user) => ({ name: user.name, done: true }))
955
+ })
956
+ })
957
+
958
+ const ordered = events.sort((left, right) => {
959
+ const leftTime = new Date(left.at || 0).getTime()
960
+ const rightTime = new Date(right.at || 0).getTime()
961
+ return leftTime - rightTime
962
+ })
963
+
964
+ const end = terminalStep(instance)
965
+ if (end) ordered.push(end)
966
+
967
+ if (instance?.state?.status === 'running' && prediction?.nodes?.length) {
968
+ const pending = currentPendingTasks(instance)
969
+ let lastPredictionIndex = -1
970
+ pending.forEach((task) => {
971
+ prediction.nodes.forEach((node, index) => {
972
+ if (sameId(node.nodeId, task.nodeId)) lastPredictionIndex = Math.max(lastPredictionIndex, index)
973
+ })
974
+ })
975
+ if (lastPredictionIndex >= 0) {
976
+ prediction.nodes.slice(lastPredictionIndex + 1).forEach((node, index) => {
977
+ if (!['approve', 'cc', 'custom', 'end'].includes(node.kind)) return
978
+ ordered.push(predictionNodeToStep(node, index))
979
+ })
980
+ }
981
+ }
982
+
983
+ return ordered
984
+ }
985
+
986
+ /** 已命中的分支决策,用于在轨迹上方做紧凑说明,避免打乱纵向步骤。 */
987
+ export function buildRouteDecisions(instance) {
988
+ const nodes = getAllNodes(instance?.definition?.workflow)
989
+ const nodeIndex = new Map(nodes.map((node) => [String(node.nodeId), node]))
990
+ return (instance?.state?.history || [])
991
+ .filter((event) => event.event === 'branch' || event.event === 'split' || event.event === 'join')
992
+ .map((event) => {
993
+ const names =
994
+ event.event === 'branch'
995
+ ? [
996
+ findNodeName(nodeIndex, event.branchId),
997
+ ...(event.branchIds || []).map((id) => findNodeName(nodeIndex, id))
998
+ ].filter(Boolean)
999
+ : []
1000
+ return {
1001
+ id: event.id,
1002
+ at: event.at,
1003
+ event: event.event,
1004
+ text:
1005
+ event.event === 'branch'
1006
+ ? `命中「${names.join('、') || '默认分支'}」`
1007
+ : event.event === 'split'
1008
+ ? '并行分支展开'
1009
+ : '并行分支汇聚'
1010
+ }
1011
+ })
1012
+ }
1013
+
1014
+ /** 发起前路径预测:把 predictWorkflow 的节点压平成纵向步骤。 */
1015
+ export function buildPredictionSteps(prediction) {
1016
+ const nodes = prediction?.nodes || []
1017
+ return nodes
1018
+ .filter((node) => !['parallel_branch', 'condition'].includes(node.kind))
1019
+ .map((node, index) => {
1020
+ const step = predictionNodeToStep(node, index)
1021
+ if (node.kind === 'start') {
1022
+ step.title = '发起申请'
1023
+ step.subtitle = prediction?.initiator?.deptName || ''
1024
+ step.actor = prediction?.initiator?.name || ''
1025
+ step.status = 'done'
1026
+ }
1027
+ if (node.kind === 'branch' || node.kind === 'parallel' || node.kind === 'inclusive') {
1028
+ step.title = node.nodeName
1029
+ step.subtitle = node.decision?.branchNames?.join('、') || node.decision?.branchName || node.note || ''
1030
+ }
1031
+ if (node.kind === 'end') {
1032
+ step.subtitle = '审批完成'
1033
+ }
1034
+ return step
1035
+ })
1036
+ }
1037
+
1038
+ export function buildTemplateCards(definitions) {
1039
+ return (definitions || [])
1040
+ .filter((definition) => {
1041
+ const status = definition?.meta?.status
1042
+ return !status || status === 'published'
1043
+ })
1044
+ .map((definition) => {
1045
+ const business = resolveBusiness(definition)
1046
+ const nodes = getAllNodes(definition?.workflow)
1047
+ return {
1048
+ id: definition?.meta?.id,
1049
+ definition,
1050
+ name: definition?.meta?.name || '未命名流程',
1051
+ description: definition?.meta?.description || business.scenario,
1052
+ business,
1053
+ nodeCount: nodes.length,
1054
+ approvalCount: nodes.filter((node) => node.type === FlowNodeType.APPROVE).length,
1055
+ customCount: nodes.filter((node) => node.type === FlowNodeType.CUSTOM).length,
1056
+ slaLabel: formatSla(business.slaHours),
1057
+ updatedAt: definition?.meta?.updatedAt,
1058
+ version: definition?.meta?.version || 1
1059
+ }
1060
+ })
1061
+ .sort((left, right) => right.business.popularity - left.business.popularity)
1062
+ }
1063
+
1064
+ export function nextInstanceCode(definitions, definition, existingInstances = []) {
1065
+ const business = resolveBusiness(definition)
1066
+ const now = new Date()
1067
+ const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(
1068
+ now.getDate()
1069
+ ).padStart(2, '0')}`
1070
+ const prefix = `${business.codePrefix}-${stamp}-`
1071
+ const used = new Set(
1072
+ (existingInstances || [])
1073
+ .filter((instance) => sameId(instance?.definition?.meta?.id, definition?.meta?.id))
1074
+ .map((instance) => Number(String(instance.code || '').slice(prefix.length)))
1075
+ .filter((value) => Number.isFinite(value))
1076
+ )
1077
+ let sequence = 1
1078
+ while (used.has(sequence)) sequence += 1
1079
+ return `${prefix}${String(sequence).padStart(3, '0')}`
1080
+ }