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,955 @@
1
+ import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
2
+ import { createFlowRuntime } from '../core/flow/runtime.js'
3
+ import { predictWorkflow } from '../core/flow/prediction.js'
4
+ import {
5
+ clearDefinitions,
6
+ createBlankDefinition,
7
+ definitionFromImport,
8
+ disableDefinition,
9
+ duplicateDefinition,
10
+ getPublishedDefinition,
11
+ isDefinitionRunnable,
12
+ loadDefinitions,
13
+ publishDefinition,
14
+ removeDefinition,
15
+ rollbackDefinition,
16
+ saveDefinitions,
17
+ upsertDefinition
18
+ } from '../center/storage.js'
19
+ import { createOaDemoInstances } from '../testing/oaSeed.js'
20
+ import { INSTANCE_STORAGE_KEY, UI_STORAGE_KEY, clone, isValidInstance } from './shared.js'
21
+ import { createPersistence } from './persistence.js'
22
+ import { createCustomTasks } from './custom-tasks.js'
23
+ import { createMockRuntimeContext, mockDepartments, mockRoles, mockUsers } from '../testing/mock.js'
24
+ import { flowStorage } from '../storage.js'
25
+ import {
26
+ buildAuditRows,
27
+ buildCcItems,
28
+ buildDoneItems,
29
+ buildMonitorMetrics,
30
+ buildNotifications,
31
+ buildPendingItems,
32
+ getAmount,
33
+ nextInstanceCode,
34
+ sameId
35
+ } from './model.js'
36
+
37
+ export function useWorkbench(props) {
38
+ const now = ref(Date.now())
39
+ const definitions = ref([])
40
+ const instances = ref(
41
+ (props.seedInstances || []).filter(isValidInstance).map((instance) => clone(instance))
42
+ )
43
+ const initialUsers = props.users?.length ? props.users : mockUsers
44
+ const currentUserId = ref(props.initiatorId ?? initialUsers[0]?.id ?? null)
45
+ const org = reactive({
46
+ users: clone(initialUsers),
47
+ departments: clone(props.departments?.length ? props.departments : mockDepartments),
48
+ roles: clone(props.roles?.length ? props.roles : mockRoles)
49
+ })
50
+ const view = ref('home')
51
+ const requestScope = ref('mine')
52
+ const taskTab = ref('approve')
53
+ const activeInstanceId = ref(null)
54
+ const activeTaskId = ref(null)
55
+ const detailInstanceId = ref(null)
56
+ const startDialogDefinitionId = ref(null)
57
+ const readNotificationIds = ref([])
58
+ const favorites = ref([])
59
+ const drafts = ref({})
60
+ const savedViews = ref([])
61
+ const adminLogs = ref([])
62
+ const ready = ref(false)
63
+ const storageReady = ref(false)
64
+ const customExecutingTaskIds = ref([])
65
+
66
+ // 可变的生命周期状态收在一个对象里:拆出去的职责模块(持久化 / 自定义节点)要共享同一份,
67
+ // 裸 let 无法跨模块赋值,改成对象字段后按引用传给 ctx。
68
+ const lifecycle = {
69
+ deadlineTimer: null,
70
+ clockTimer: null,
71
+ persistTimer: null,
72
+ uiPersistTimer: null,
73
+ customSweepTimer: null,
74
+ customSweepRunning: false,
75
+ hydrating: false,
76
+ disposed: false
77
+ }
78
+ const customExecutionKeys = new Set()
79
+ const customStuckKeys = new Set()
80
+ const customControllers = new Map()
81
+
82
+ // 职责模块:refs / state / 兄弟函数装进一个 ctx 交出去(同一份引用,不改行为)
83
+ const ctx = {
84
+ definitions, instances, currentUserId, readNotificationIds, favorites, drafts, savedViews,
85
+ adminLogs, storageReady, ready, customExecutingTaskIds, customExecutionKeys, customStuckKeys,
86
+ customControllers, props, lifecycle
87
+ }
88
+ const { hydrate, persistNow, schedulePersist, scheduleUiPersist } = createPersistence(ctx)
89
+ const {
90
+ resolveCustomExecutors, executorLabelOf, pendingCustomEntries, completeCustomEntry,
91
+ runCustomSweep, scheduleCustomSweep
92
+ } = createCustomTasks(ctx)
93
+
94
+ const userIndex = computed(
95
+ () => new Map(org.users.map((user) => [String(user.id), user]))
96
+ )
97
+ const deptIndex = computed(
98
+ () => new Map(org.departments.map((dept) => [String(dept.id), dept]))
99
+ )
100
+ const roleIndex = computed(
101
+ () => new Map(org.roles.map((role) => [String(role.id), role]))
102
+ )
103
+ const currentUser = computed(
104
+ () => userIndex.value.get(String(currentUserId.value)) || null
105
+ )
106
+ const currentUserRoleNames = computed(() =>
107
+ (currentUser.value?.roleIds || [])
108
+ .map((roleId) => roleIndex.value.get(String(roleId))?.roleName)
109
+ .filter(Boolean)
110
+ )
111
+ const isAdmin = computed(() =>
112
+ (currentUser.value?.roleIds || []).some((roleId) => {
113
+ const role = roleIndex.value.get(String(roleId))
114
+ return role?.roleKey === 'flow_admin' || String(role?.roleName || '').includes('流程管理员')
115
+ })
116
+ )
117
+
118
+ const currentUserName = computed(
119
+ () => currentUser.value?.realName || currentUser.value?.username || '未设置'
120
+ )
121
+ const currentUserDept = computed(
122
+ () =>
123
+ currentUser.value?.deptName ||
124
+ deptIndex.value.get(String(currentUser.value?.deptId))?.name ||
125
+ '未分配部门'
126
+ )
127
+
128
+ const publishedDefinitions = computed(() =>
129
+ definitions.value.filter(isDefinitionRunnable).map((definition) => getPublishedDefinition(definition))
130
+ )
131
+
132
+ const pendingItems = computed(() =>
133
+ buildPendingItems(instances.value, currentUserId.value, now.value)
134
+ )
135
+ const approveItems = computed(() => pendingItems.value.filter((item) => item.kind === 'approve'))
136
+ const submitItems = computed(() => pendingItems.value.filter((item) => item.kind === 'submit'))
137
+ const ccItems = computed(() => buildCcItems(instances.value, currentUserId.value))
138
+ const doneItems = computed(() => buildDoneItems(instances.value, currentUserId.value))
139
+ const myInstances = computed(() =>
140
+ instances.value
141
+ .filter((instance) => sameId(instance?.initiatorId, currentUserId.value))
142
+ .slice()
143
+ .sort((left, right) => String(right.updatedAt).localeCompare(String(left.updatedAt)))
144
+ )
145
+ const notifications = computed(() =>
146
+ buildNotifications(instances.value, currentUserId.value, readNotificationIds.value, now.value)
147
+ )
148
+ const unreadNotifications = computed(() =>
149
+ notifications.value.filter((notification) => !notification.read)
150
+ )
151
+ const metrics = computed(() => buildMonitorMetrics(instances.value, now.value))
152
+ const auditRows = computed(() => buildAuditRows(instances.value, adminLogs.value))
153
+ const activeInstance = computed(
154
+ () => instances.value.find((instance) => sameId(instance.id, activeInstanceId.value)) || null
155
+ )
156
+ const activeTask = computed(() => {
157
+ const instance = activeInstance.value
158
+ if (!instance || !activeTaskId.value) return null
159
+ return (
160
+ (instance.state?.tasks || []).find((task) => sameId(task.id, activeTaskId.value)) || null
161
+ )
162
+ })
163
+ const detailInstance = computed(
164
+ () => instances.value.find((instance) => sameId(instance.id, detailInstanceId.value)) || null
165
+ )
166
+ const startDialogDefinition = computed(
167
+ () =>
168
+ definitions.value.find(
169
+ (definition) => sameId(definition.meta?.id, startDialogDefinitionId.value)
170
+ ) || null
171
+ )
172
+ const usersWithStats = computed(() =>
173
+ org.users.map((user) => {
174
+ const roles = (user.roleIds || [])
175
+ .map((roleId) => roleIndex.value.get(String(roleId)))
176
+ .filter(Boolean)
177
+ const pending = buildPendingItems(instances.value, user.id, now.value).length
178
+ const isUserAdmin = roles.some(
179
+ (role) => role.roleKey === 'flow_admin' || String(role.roleName || '').includes('流程管理员')
180
+ )
181
+ return {
182
+ ...user,
183
+ deptLabel:
184
+ user.deptName || deptIndex.value.get(String(user.deptId))?.name || '未分配部门',
185
+ roleLabel: roles.map((role) => role.roleName).join(' / ') || user.title || '成员',
186
+ pending,
187
+ isAdmin: isUserAdmin
188
+ }
189
+ })
190
+ )
191
+
192
+ const viewTitle = computed(
193
+ () =>
194
+ ({
195
+ home: '工作台',
196
+ tasks: '待办中心',
197
+ requests:
198
+ requestScope.value === 'mine'
199
+ ? '我的申请'
200
+ : requestScope.value === 'cc'
201
+ ? '抄送我的'
202
+ : '已办事项',
203
+ templates: '模板中心',
204
+ monitor: '流程监控',
205
+ design: '流程设计',
206
+ notifications: '通知中心'
207
+ })[view.value] || '工作台'
208
+ )
209
+
210
+ function contextFor(instance, initiatorId = instance?.initiatorId) {
211
+ return createMockRuntimeContext({
212
+ initiatorId: initiatorId ?? instance?.state?.initiator?.id ?? org.users[0]?.id,
213
+ users: org.users,
214
+ departments: org.departments,
215
+ roles: org.roles,
216
+ extraCcUsers: instance?.extraCcUsers || {}
217
+ })
218
+ }
219
+
220
+ function runtimeFor(instance) {
221
+ return createFlowRuntime({
222
+ workflow: instance.definition.workflow,
223
+ state: instance.state,
224
+ context: contextFor(instance)
225
+ })
226
+ }
227
+
228
+ function syncState(instance, state) {
229
+ instance.state = state
230
+ instance.updatedAt = state?.endedAt || new Date().toISOString()
231
+ }
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+ function tickAllInstances() {
242
+ let changed = false
243
+ instances.value.forEach((instance) => {
244
+ if (instance.state?.status !== 'running') return
245
+ try {
246
+ const runtime = runtimeFor(instance)
247
+ const state = runtime.tick()
248
+ if (JSON.stringify(state) !== JSON.stringify(instance.state)) {
249
+ syncState(instance, state)
250
+ changed = true
251
+ }
252
+ } catch {
253
+ // 单个损坏实例不影响其它实例的超时扫描
254
+ }
255
+ })
256
+ if (changed) schedulePersist()
257
+ }
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+ function navigate(nextView, payload = {}) {
272
+ view.value = nextView
273
+ if (payload.scope) requestScope.value = payload.scope
274
+ if (payload.taskTab) taskTab.value = payload.taskTab
275
+ if ('instanceId' in payload) activeInstanceId.value = payload.instanceId
276
+ if ('taskId' in payload) activeTaskId.value = payload.taskId
277
+ if (payload.detailInstanceId) detailInstanceId.value = payload.detailInstanceId
278
+ }
279
+
280
+ function openTask(item) {
281
+ navigate('tasks', {
282
+ instanceId: item.instance.id,
283
+ taskId: item.task.id
284
+ })
285
+ }
286
+
287
+ function openInstanceDetail(instanceId) {
288
+ detailInstanceId.value = instanceId
289
+ }
290
+
291
+ function closeInstanceDetail() {
292
+ detailInstanceId.value = null
293
+ }
294
+
295
+ function openStartDialog(definitionId) {
296
+ startDialogDefinitionId.value = definitionId
297
+ }
298
+
299
+ function closeStartDialog() {
300
+ startDialogDefinitionId.value = null
301
+ }
302
+
303
+ function selectTask(instanceId, taskId) {
304
+ activeInstanceId.value = instanceId
305
+ activeTaskId.value = taskId
306
+ }
307
+
308
+ function switchUser(userId) {
309
+ if (!userIndex.value.has(String(userId))) return
310
+ currentUserId.value = userId
311
+ if (
312
+ activeTask.value &&
313
+ !canActOnTask(activeInstance.value, activeTask.value, userId)
314
+ ) {
315
+ activeTaskId.value = null
316
+ activeInstanceId.value = null
317
+ }
318
+ }
319
+
320
+ function applyOrg(payload) {
321
+ if (!payload) return
322
+ if (Array.isArray(payload.users) && payload.users.length) org.users = clone(payload.users)
323
+ if (Array.isArray(payload.departments) && payload.departments.length) {
324
+ org.departments = clone(payload.departments)
325
+ }
326
+ if (Array.isArray(payload.roles) && payload.roles.length) org.roles = clone(payload.roles)
327
+ if (!userIndex.value.has(String(currentUserId.value))) {
328
+ currentUserId.value = org.users[0]?.id ?? null
329
+ }
330
+ tickAllInstances()
331
+ }
332
+
333
+ function findInstance(instanceId) {
334
+ return instances.value.find((instance) => sameId(instance.id, instanceId)) || null
335
+ }
336
+
337
+ function findTask(instance, taskId) {
338
+ return (instance?.state?.tasks || []).find((task) => sameId(task.id, taskId)) || null
339
+ }
340
+
341
+ function recordAudit(instance, action, detail, nodeName = '') {
342
+ const log = {
343
+ id: `admin_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
344
+ at: new Date().toISOString(),
345
+ actorId: currentUserId.value,
346
+ actorName: currentUserName.value,
347
+ action,
348
+ detail,
349
+ nodeName,
350
+ instanceId: instance.id,
351
+ instanceName: instance.name,
352
+ code: instance.code || ''
353
+ }
354
+ adminLogs.value = [log, ...adminLogs.value]
355
+ scheduleUiPersist()
356
+ return log
357
+ }
358
+
359
+ function actOnTask(instanceId, taskId, action, payload = {}) {
360
+ const instance = findInstance(instanceId)
361
+ const task = findTask(instance, taskId)
362
+ if (!instance || !task) throw new Error('任务不存在或已被处理')
363
+ const runtime = runtimeFor(instance)
364
+ const user = userIndex.value.get(String(currentUserId.value)) || currentUser.value
365
+ let state
366
+ if (action === 'approve') {
367
+ state = runtime.approve(task.id, { user, comment: payload.comment || '' })
368
+ } else if (action === 'reject') {
369
+ state = runtime.reject(task.id, { user, comment: payload.comment || '' })
370
+ } else if (action === 'transfer') {
371
+ const target = userIndex.value.get(String(payload.targetUserId))
372
+ if (!target) throw new Error('请选择有效的转交对象')
373
+ state = runtime.transfer(task.id, {
374
+ user,
375
+ toUser: target,
376
+ comment: payload.comment || ''
377
+ })
378
+ } else if (action === 'addSign') {
379
+ const target = userIndex.value.get(String(payload.targetUserId))
380
+ if (!target) throw new Error('请选择有效的加签对象')
381
+ state = runtime.addSign(task.id, {
382
+ user,
383
+ toUser: target,
384
+ comment: payload.comment || ''
385
+ })
386
+ } else if (action === 'resubmit') {
387
+ state = runtime.resubmit(task.id, {
388
+ user,
389
+ data: payload.data || {},
390
+ comment: payload.comment || ''
391
+ })
392
+ } else {
393
+ throw new Error(`不支持的操作:${action}`)
394
+ }
395
+ syncState(instance, state)
396
+ schedulePersist()
397
+ return state
398
+ }
399
+
400
+ function urgeTask(instanceId, taskId, message) {
401
+ const instance = findInstance(instanceId)
402
+ const task = findTask(instance, taskId)
403
+ if (!instance || !task) throw new Error('任务不存在或已被处理')
404
+ const reminder = {
405
+ id: `urge_${Date.now()}`,
406
+ byId: currentUserId.value,
407
+ byName: currentUserName.value,
408
+ at: new Date().toISOString(),
409
+ taskId: task.id,
410
+ message: message || '请尽快处理该审批节点'
411
+ }
412
+ instance.reminders = [...(instance.reminders || []), reminder]
413
+ instance.updatedAt = new Date().toISOString()
414
+ recordAudit(instance, '催办', reminder.message, task.nodeName)
415
+ schedulePersist()
416
+ return reminder
417
+ }
418
+
419
+ function revokeInstance(instanceId, reason) {
420
+ const instance = findInstance(instanceId)
421
+ if (!instance) throw new Error('流程实例不存在')
422
+ const runtime = runtimeFor(instance)
423
+ const state = runtime.revoke({
424
+ user: currentUser.value,
425
+ reason: reason || '发起人撤回'
426
+ })
427
+ syncState(instance, state)
428
+ schedulePersist()
429
+ return state
430
+ }
431
+
432
+ function terminateInstance(instanceId, reason) {
433
+ const instance = findInstance(instanceId)
434
+ if (!instance) throw new Error('流程实例不存在')
435
+ const runtime = runtimeFor(instance)
436
+ const state = runtime.cancel(reason || '流程管理员终止')
437
+ syncState(instance, state)
438
+ recordAudit(instance, '终止流程', reason || '流程管理员终止')
439
+ schedulePersist()
440
+ return state
441
+ }
442
+
443
+ function makeExtraCcUsers(selections) {
444
+ const result = {}
445
+ Object.entries(selections || {}).forEach(([nodeId, userIds]) => {
446
+ const users = (userIds || [])
447
+ .map((userId) => userIndex.value.get(String(userId)))
448
+ .filter(Boolean)
449
+ .map((user) => clone(user))
450
+ if (users.length) result[nodeId] = users
451
+ })
452
+ return result
453
+ }
454
+
455
+ function startFlow({ definition, title, data, ccSelections = {}, attachments = [], initiatorId }) {
456
+ if (!definition?.workflow) throw new Error('流程定义不可用')
457
+ const published = clone(getPublishedDefinition(definition))
458
+ if (published.meta) delete published.meta.revisions
459
+ const initiator = userIndex.value.get(String(initiatorId ?? currentUserId.value))
460
+ if (!initiator) throw new Error('发起人不存在')
461
+ const context = createMockRuntimeContext({
462
+ initiatorId: initiator.id,
463
+ users: org.users,
464
+ departments: org.departments,
465
+ roles: org.roles,
466
+ extraCcUsers: makeExtraCcUsers(ccSelections)
467
+ })
468
+ const runtime = createFlowRuntime({ workflow: published.workflow, context })
469
+ const state = runtime.start(data || {}, initiator)
470
+ const amount = getAmount({ state, definition: published })
471
+ const priority =
472
+ amount >= 100000 ? 'urgent' : amount >= 30000 ? 'high' : 'normal'
473
+ const code = nextInstanceCode(definitions.value, published, instances.value)
474
+ const instance = {
475
+ id: `oa_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
476
+ code,
477
+ name: title?.trim() || `${published.meta?.name || '业务申请'} · ${formatDate()}`,
478
+ definition: published,
479
+ definitionVersion: published.meta?.version || 1,
480
+ initiatorId: initiator.id,
481
+ initiator: {
482
+ id: initiator.id,
483
+ name: initiator.realName || initiator.username || String(initiator.id),
484
+ deptName: initiator.deptName || currentDeptName(initiator.deptId)
485
+ },
486
+ extraCcUsers: makeExtraCcUsers(ccSelections),
487
+ attachments: clone(
488
+ (attachments || []).map((file) => ({
489
+ name: file.name || '未命名附件',
490
+ size: Number(file.size) || 0,
491
+ type: file.type || ''
492
+ }))
493
+ ),
494
+ priority,
495
+ createdAt: new Date().toISOString(),
496
+ updatedAt: new Date().toISOString(),
497
+ state
498
+ }
499
+ instances.value = [instance, ...instances.value]
500
+ schedulePersist()
501
+ navigate('requests', {
502
+ scope: 'mine',
503
+ detailInstanceId: instance.id
504
+ })
505
+ return instance
506
+ }
507
+
508
+ function currentDeptName(deptId) {
509
+ return deptIndex.value.get(String(deptId))?.name || ''
510
+ }
511
+
512
+ function formatDate() {
513
+ const date = new Date()
514
+ return `${date.getMonth() + 1}月${date.getDate()}日`
515
+ }
516
+
517
+ function markNotificationRead(ids) {
518
+ const next = new Set(readNotificationIds.value)
519
+ ;(Array.isArray(ids) ? ids : [ids]).forEach((id) => {
520
+ if (id) next.add(id)
521
+ })
522
+ readNotificationIds.value = [...next]
523
+ scheduleUiPersist()
524
+ }
525
+
526
+ function markAllNotificationsRead() {
527
+ const next = new Set(readNotificationIds.value)
528
+ notifications.value.forEach((notification) => next.add(notification.id))
529
+ readNotificationIds.value = [...next]
530
+ scheduleUiPersist()
531
+ }
532
+
533
+ function toggleFavorite(definitionId) {
534
+ const key = String(definitionId)
535
+ const set = new Set(favorites.value.map(String))
536
+ if (set.has(key)) set.delete(key)
537
+ else set.add(key)
538
+ favorites.value = [...set]
539
+ scheduleUiPersist()
540
+ }
541
+
542
+ function draftKey(definitionId) {
543
+ return `${currentUserId.value}:${definitionId}`
544
+ }
545
+
546
+ function getDraft(definitionId) {
547
+ return drafts.value[draftKey(definitionId)] || null
548
+ }
549
+
550
+ function saveDraft(definitionId, payload) {
551
+ drafts.value = {
552
+ ...drafts.value,
553
+ [draftKey(definitionId)]: {
554
+ ...payload,
555
+ savedAt: new Date().toISOString()
556
+ }
557
+ }
558
+ scheduleUiPersist()
559
+ }
560
+
561
+ function clearDraft(definitionId) {
562
+ if (!drafts.value[draftKey(definitionId)]) return
563
+ const next = { ...drafts.value }
564
+ delete next[draftKey(definitionId)]
565
+ drafts.value = next
566
+ scheduleUiPersist()
567
+ }
568
+
569
+ function saveView(viewData) {
570
+ const entry = {
571
+ id: `view_${Date.now()}`,
572
+ name: viewData.name,
573
+ scope: viewData.scope || requestScope.value,
574
+ userId: currentUserId.value,
575
+ filter: clone(viewData.filter || {}),
576
+ createdAt: new Date().toISOString()
577
+ }
578
+ savedViews.value = [entry, ...savedViews.value].slice(0, 12)
579
+ scheduleUiPersist()
580
+ return entry
581
+ }
582
+
583
+ function removeView(viewId) {
584
+ savedViews.value = savedViews.value.filter((entry) => entry.id !== viewId)
585
+ scheduleUiPersist()
586
+ }
587
+
588
+ async function saveDesign(definition) {
589
+ definitions.value = upsertDefinition(definitions.value, definition)
590
+ await saveDefinitions(definitions.value)
591
+ return definitions.value.find((item) => sameId(item.meta.id, definition.meta.id)) || definition
592
+ }
593
+
594
+ async function publishDesign(definitionId) {
595
+ const definition = definitions.value.find((item) => sameId(item.meta?.id, definitionId))
596
+ if (!definition) throw new Error('流程定义不存在')
597
+ definitions.value = publishDefinition(definitions.value, definition)
598
+ await saveDefinitions(definitions.value)
599
+ return definitions.value.find((item) => sameId(item.meta?.id, definitionId))
600
+ }
601
+
602
+ async function rollbackDesign(definitionId, version) {
603
+ definitions.value = rollbackDefinition(definitions.value, definitionId, version)
604
+ await saveDefinitions(definitions.value)
605
+ return definitions.value.find((item) => sameId(item.meta?.id, definitionId))
606
+ }
607
+
608
+ async function createDesign(name) {
609
+ const definition = createBlankDefinition(name)
610
+ definitions.value = [definition, ...definitions.value]
611
+ await saveDefinitions(definitions.value)
612
+ return definition
613
+ }
614
+
615
+ async function duplicateDesign(source) {
616
+ const copy = duplicateDefinition(source)
617
+ definitions.value = [copy, ...definitions.value]
618
+ await saveDefinitions(definitions.value)
619
+ return copy
620
+ }
621
+
622
+ async function disableDesign(definitionId) {
623
+ definitions.value = disableDefinition(definitions.value, definitionId)
624
+ await saveDefinitions(definitions.value)
625
+ return definitions.value.find((item) => sameId(item.meta?.id, definitionId))
626
+ }
627
+
628
+ async function removeDesign(definitionId) {
629
+ definitions.value = removeDefinition(definitions.value, definitionId)
630
+ await saveDefinitions(definitions.value)
631
+ }
632
+
633
+ async function importDesign(input) {
634
+ const definition = definitionFromImport(input)
635
+ definitions.value = [definition, ...definitions.value]
636
+ await saveDefinitions(definitions.value)
637
+ return definition
638
+ }
639
+
640
+ function getCcNodes(definition) {
641
+ const result = []
642
+ const visit = (node) => {
643
+ if (!node) return
644
+ if (node.type === 'cc' && node.allowInitiatorAddUsers !== false) {
645
+ result.push({ nodeId: node.nodeId, nodeName: node.nodeName })
646
+ }
647
+ if (node.childNode) visit(node.childNode)
648
+ ;(node.branchList || []).forEach(visit)
649
+ }
650
+ visit(definition?.workflow)
651
+ return result
652
+ }
653
+
654
+ function predictInstance(instance) {
655
+ if (!instance?.definition?.workflow) return null
656
+ try {
657
+ return predictWorkflow({
658
+ definition: instance.definition,
659
+ data: instance.state?.variables || {},
660
+ context: contextFor(instance),
661
+ initiator: instance.state?.initiator || instance.initiator
662
+ })
663
+ } catch {
664
+ return null
665
+ }
666
+ }
667
+
668
+ function previewRoute({ definition, data, ccSelections, initiatorId }) {
669
+ const initiator =
670
+ userIndex.value.get(String(initiatorId ?? currentUserId.value)) || currentUser.value
671
+ const context = createMockRuntimeContext({
672
+ initiatorId: initiator?.id,
673
+ users: org.users,
674
+ departments: org.departments,
675
+ roles: org.roles,
676
+ extraCcUsers: makeExtraCcUsers(ccSelections)
677
+ })
678
+ return predictWorkflow({
679
+ definition,
680
+ data: data || {},
681
+ context,
682
+ initiator
683
+ })
684
+ }
685
+
686
+ function searchAll(keyword) {
687
+ const text = String(keyword || '').trim().toLowerCase()
688
+ if (!text) return { instances: [], templates: [] }
689
+ const accessible = (instance) => {
690
+ if (isAdmin.value) return true
691
+ const userId = currentUserId.value
692
+ if (sameId(instance.initiatorId, userId)) return true
693
+ const state = instance.state || {}
694
+ if (
695
+ (state.tasks || []).some(
696
+ (task) =>
697
+ (task.approvers || []).some((user) => sameId(user.id, userId)) ||
698
+ (task.approvedBy || []).some((user) => sameId(user.id, userId)) ||
699
+ (task.records || []).some((record) => sameId(record.approver?.id, userId))
700
+ )
701
+ ) {
702
+ return true
703
+ }
704
+ return (state.ccRecords || []).some((record) =>
705
+ (record.users || []).some((user) => sameId(user.id, userId))
706
+ )
707
+ }
708
+ const matchedInstances = instances.value
709
+ .filter(
710
+ (instance) =>
711
+ accessible(instance) &&
712
+ [instance.name, instance.code, instance.initiator?.name, instance.definition?.meta?.name]
713
+ .filter(Boolean)
714
+ .some((field) => String(field).toLowerCase().includes(text))
715
+ )
716
+ .slice(0, 5)
717
+ const matchedTemplates = publishedDefinitions.value
718
+ .filter((definition) =>
719
+ [definition.meta?.name, definition.meta?.description, definition.meta?.business?.category]
720
+ .filter(Boolean)
721
+ .some((field) => String(field).toLowerCase().includes(text))
722
+ )
723
+ .slice(0, 4)
724
+ return { instances: matchedInstances, templates: matchedTemplates }
725
+ }
726
+
727
+ async function resetDemoData() {
728
+ if (lifecycle.customSweepTimer) {
729
+ clearTimeout(lifecycle.customSweepTimer)
730
+ lifecycle.customSweepTimer = null
731
+ }
732
+ customControllers.forEach((controller) => controller.abort())
733
+ customControllers.clear()
734
+ customExecutionKeys.clear()
735
+ customExecutingTaskIds.value = []
736
+ await clearDefinitions()
737
+ await flowStorage.remove(INSTANCE_STORAGE_KEY)
738
+ await flowStorage.remove(UI_STORAGE_KEY)
739
+ definitions.value = await loadDefinitions()
740
+ instances.value = createOaDemoInstances()
741
+ org.users = clone(props.users?.length ? props.users : mockUsers)
742
+ org.departments = clone(props.departments?.length ? props.departments : mockDepartments)
743
+ org.roles = clone(props.roles?.length ? props.roles : mockRoles)
744
+ readNotificationIds.value = []
745
+ favorites.value = []
746
+ drafts.value = {}
747
+ customStuckKeys.clear()
748
+ savedViews.value = []
749
+ adminLogs.value = []
750
+ currentUserId.value = org.users[0]?.id ?? null
751
+ activeInstanceId.value = null
752
+ activeTaskId.value = null
753
+ detailInstanceId.value = null
754
+ startDialogDefinitionId.value = null
755
+ view.value = 'home'
756
+ requestScope.value = 'mine'
757
+ taskTab.value = 'approve'
758
+ now.value = Date.now()
759
+ await persistNow()
760
+ scheduleUiPersist()
761
+ }
762
+
763
+ function canActOnTask(instance, task, userId = currentUserId.value) {
764
+ if (!instance || !task || task.status !== 'pending' || instance.state?.status !== 'running') {
765
+ return false
766
+ }
767
+ if (task.kind === 'submit') {
768
+ return sameId(instance.state?.initiator?.id, userId)
769
+ }
770
+ return (
771
+ (task.approvers || []).some((approver) => sameId(approver.id, userId)) &&
772
+ !(task.approvedBy || []).some((approver) => sameId(approver.id, userId))
773
+ )
774
+ }
775
+
776
+ function canRevoke(instance, userId = currentUserId.value) {
777
+ return (
778
+ instance?.state?.status === 'running' &&
779
+ sameId(instance?.state?.initiator?.id, userId)
780
+ )
781
+ }
782
+
783
+ function canTransfer(instance, task) {
784
+ const workflow = instance?.definition?.workflow
785
+ const node = workflow ? findNodeInWorkflow(workflow, task?.nodeId) : null
786
+ return node?.allowTransfer !== false
787
+ }
788
+
789
+ function findNodeInWorkflow(node, nodeId) {
790
+ if (!node) return null
791
+ if (sameId(node.nodeId, nodeId)) return node
792
+ for (const branch of node.branchList || []) {
793
+ const found = findNodeInWorkflow(branch, nodeId)
794
+ if (found) return found
795
+ }
796
+ return findNodeInWorkflow(node.childNode, nodeId)
797
+ }
798
+
799
+ watch(
800
+ [instances, currentUserId],
801
+ () => {
802
+ if (!lifecycle.hydrating) {
803
+ schedulePersist()
804
+ scheduleCustomSweep()
805
+ }
806
+ },
807
+ { deep: true }
808
+ )
809
+ watch(
810
+ [readNotificationIds, favorites, drafts, savedViews, adminLogs],
811
+ () => {
812
+ if (!lifecycle.hydrating) scheduleUiPersist()
813
+ },
814
+ { deep: true }
815
+ )
816
+ watch(
817
+ () => [props.users, props.departments, props.roles],
818
+ () => {
819
+ if (props.users?.length) org.users = clone(props.users)
820
+ if (props.departments?.length) org.departments = clone(props.departments)
821
+ if (props.roles?.length) org.roles = clone(props.roles)
822
+ if (!userIndex.value.has(String(currentUserId.value))) {
823
+ currentUserId.value = org.users[0]?.id ?? null
824
+ }
825
+ },
826
+ { deep: true }
827
+ )
828
+
829
+ onMounted(() => {
830
+ hydrate()
831
+ lifecycle.deadlineTimer = setInterval(tickAllInstances, 30000)
832
+ lifecycle.clockTimer = setInterval(() => {
833
+ now.value = Date.now()
834
+ }, 30000)
835
+ })
836
+
837
+ onBeforeUnmount(() => {
838
+ lifecycle.disposed = true
839
+ if (lifecycle.deadlineTimer) clearInterval(lifecycle.deadlineTimer)
840
+ if (lifecycle.clockTimer) clearInterval(lifecycle.clockTimer)
841
+ if (lifecycle.persistTimer) {
842
+ clearTimeout(lifecycle.persistTimer)
843
+ lifecycle.persistTimer = null
844
+ }
845
+ if (lifecycle.uiPersistTimer) {
846
+ clearTimeout(lifecycle.uiPersistTimer)
847
+ lifecycle.uiPersistTimer = null
848
+ }
849
+ if (lifecycle.customSweepTimer) {
850
+ clearTimeout(lifecycle.customSweepTimer)
851
+ lifecycle.customSweepTimer = null
852
+ }
853
+ customControllers.forEach((controller) => controller.abort())
854
+ customControllers.clear()
855
+ persistNow()
856
+ flowStorage
857
+ .setJSON(UI_STORAGE_KEY, {
858
+ readNotificationIds: readNotificationIds.value,
859
+ favorites: favorites.value,
860
+ drafts: drafts.value,
861
+ savedViews: savedViews.value,
862
+ adminLogs: adminLogs.value
863
+ })
864
+ .catch(() => {})
865
+ })
866
+
867
+ // 拆出的模块通过 ctx 调用这些兄弟函数:此处回填,保证生命周期回调触发时它们已就位
868
+ Object.assign(ctx, {
869
+ tickAllInstances, runtimeFor, syncState, findNodeInWorkflow,
870
+ schedulePersist, persistNow, scheduleUiPersist, hydrate,
871
+ resolveCustomExecutors, executorLabelOf, pendingCustomEntries, completeCustomEntry,
872
+ runCustomSweep, scheduleCustomSweep
873
+ })
874
+
875
+ return {
876
+ now,
877
+ definitions,
878
+ publishedDefinitions,
879
+ instances,
880
+ org,
881
+ currentUserId,
882
+ currentUser,
883
+ currentUserName,
884
+ currentUserDept,
885
+ currentUserRoleNames,
886
+ isAdmin,
887
+ usersWithStats,
888
+ pendingItems,
889
+ approveItems,
890
+ submitItems,
891
+ ccItems,
892
+ doneItems,
893
+ myInstances,
894
+ notifications,
895
+ unreadNotifications,
896
+ metrics,
897
+ auditRows,
898
+ view,
899
+ viewTitle,
900
+ requestScope,
901
+ taskTab,
902
+ activeInstance,
903
+ activeTask,
904
+ activeInstanceId,
905
+ activeTaskId,
906
+ detailInstance,
907
+ detailInstanceId,
908
+ startDialogDefinitionId,
909
+ startDialogDefinition,
910
+ openStartDialog,
911
+ closeStartDialog,
912
+ ready,
913
+ customExecutingTaskIds,
914
+ favoriteIds: favorites,
915
+ savedViews,
916
+ navigate,
917
+ openTask,
918
+ openInstanceDetail,
919
+ closeInstanceDetail,
920
+ selectTask,
921
+ switchUser,
922
+ applyOrg,
923
+ actOnTask,
924
+ urgeTask,
925
+ revokeInstance,
926
+ terminateInstance,
927
+ startFlow,
928
+ markNotificationRead,
929
+ markAllNotificationsRead,
930
+ toggleFavorite,
931
+ getDraft,
932
+ saveDraft,
933
+ clearDraft,
934
+ saveView,
935
+ removeView,
936
+ saveDesign,
937
+ publishDesign,
938
+ rollbackDesign,
939
+ createDesign,
940
+ duplicateDesign,
941
+ disableDesign,
942
+ removeDesign,
943
+ importDesign,
944
+ getCcNodes,
945
+ predictInstance,
946
+ previewRoute,
947
+ searchAll,
948
+ resetDemoData,
949
+ canActOnTask,
950
+ canRevoke,
951
+ canTransfer,
952
+ findInstance,
953
+ tickAllInstances
954
+ }
955
+ }