@zerodep-dev/flow-ts-engine 0.0.0-stage → 1.0.0

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 (219) hide show
  1. package/LICENSE +202 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/client/client.d.ts +112 -0
  4. package/dist/client/client.d.ts.map +1 -0
  5. package/dist/client/client.js +67 -0
  6. package/dist/client/client.js.map +1 -0
  7. package/dist/client/endpoint.d.ts +20 -0
  8. package/dist/client/endpoint.d.ts.map +1 -0
  9. package/dist/client/endpoint.js +153 -0
  10. package/dist/client/endpoint.js.map +1 -0
  11. package/dist/client/http.d.ts +30 -0
  12. package/dist/client/http.d.ts.map +1 -0
  13. package/dist/client/http.js +67 -0
  14. package/dist/client/http.js.map +1 -0
  15. package/dist/client/index.d.ts +12 -0
  16. package/dist/client/index.d.ts.map +1 -0
  17. package/dist/client/index.js +11 -0
  18. package/dist/client/index.js.map +1 -0
  19. package/dist/client/port.d.ts +24 -0
  20. package/dist/client/port.d.ts.map +1 -0
  21. package/dist/client/port.js +53 -0
  22. package/dist/client/port.js.map +1 -0
  23. package/dist/client/protocol.d.ts +26 -0
  24. package/dist/client/protocol.d.ts.map +1 -0
  25. package/dist/client/protocol.js +13 -0
  26. package/dist/client/protocol.js.map +1 -0
  27. package/dist/commands/admin.d.ts +41 -0
  28. package/dist/commands/admin.d.ts.map +1 -0
  29. package/dist/commands/admin.js +228 -0
  30. package/dist/commands/admin.js.map +1 -0
  31. package/dist/commands/complete.d.ts +36 -0
  32. package/dist/commands/complete.d.ts.map +1 -0
  33. package/dist/commands/complete.js +289 -0
  34. package/dist/commands/complete.js.map +1 -0
  35. package/dist/commands/dispatch.d.ts +11 -0
  36. package/dist/commands/dispatch.d.ts.map +1 -0
  37. package/dist/commands/dispatch.js +77 -0
  38. package/dist/commands/dispatch.js.map +1 -0
  39. package/dist/commands/operate.d.ts +14 -0
  40. package/dist/commands/operate.d.ts.map +1 -0
  41. package/dist/commands/operate.js +72 -0
  42. package/dist/commands/operate.js.map +1 -0
  43. package/dist/commands/operations.d.ts +75 -0
  44. package/dist/commands/operations.d.ts.map +1 -0
  45. package/dist/commands/operations.js +417 -0
  46. package/dist/commands/operations.js.map +1 -0
  47. package/dist/commands/signal.d.ts +9 -0
  48. package/dist/commands/signal.d.ts.map +1 -0
  49. package/dist/commands/signal.js +78 -0
  50. package/dist/commands/signal.js.map +1 -0
  51. package/dist/commands/start.d.ts +41 -0
  52. package/dist/commands/start.d.ts.map +1 -0
  53. package/dist/commands/start.js +186 -0
  54. package/dist/commands/start.js.map +1 -0
  55. package/dist/commands/submission.d.ts +20 -0
  56. package/dist/commands/submission.d.ts.map +1 -0
  57. package/dist/commands/submission.js +29 -0
  58. package/dist/commands/submission.js.map +1 -0
  59. package/dist/core/channels.d.ts +13 -0
  60. package/dist/core/channels.d.ts.map +1 -0
  61. package/dist/core/channels.js +13 -0
  62. package/dist/core/channels.js.map +1 -0
  63. package/dist/core/context.d.ts +76 -0
  64. package/dist/core/context.d.ts.map +1 -0
  65. package/dist/core/context.js +148 -0
  66. package/dist/core/context.js.map +1 -0
  67. package/dist/core/entities.d.ts +392 -0
  68. package/dist/core/entities.d.ts.map +1 -0
  69. package/dist/core/entities.js +282 -0
  70. package/dist/core/entities.js.map +1 -0
  71. package/dist/core/errors.d.ts +35 -0
  72. package/dist/core/errors.d.ts.map +1 -0
  73. package/dist/core/errors.js +18 -0
  74. package/dist/core/errors.js.map +1 -0
  75. package/dist/engine.d.ts +146 -0
  76. package/dist/engine.d.ts.map +1 -0
  77. package/dist/engine.js +85 -0
  78. package/dist/engine.js.map +1 -0
  79. package/dist/extensions.d.ts +198 -0
  80. package/dist/extensions.d.ts.map +1 -0
  81. package/dist/extensions.js +7 -0
  82. package/dist/extensions.js.map +1 -0
  83. package/dist/index.d.ts +19 -0
  84. package/dist/index.d.ts.map +1 -0
  85. package/dist/index.js +15 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/jobs/jobs.d.ts +27 -0
  88. package/dist/jobs/jobs.d.ts.map +1 -0
  89. package/dist/jobs/jobs.js +299 -0
  90. package/dist/jobs/jobs.js.map +1 -0
  91. package/dist/notify/collect.d.ts +38 -0
  92. package/dist/notify/collect.d.ts.map +1 -0
  93. package/dist/notify/collect.js +100 -0
  94. package/dist/notify/collect.js.map +1 -0
  95. package/dist/notify/inbox.d.ts +26 -0
  96. package/dist/notify/inbox.d.ts.map +1 -0
  97. package/dist/notify/inbox.js +87 -0
  98. package/dist/notify/inbox.js.map +1 -0
  99. package/dist/org/directory.d.ts +74 -0
  100. package/dist/org/directory.d.ts.map +1 -0
  101. package/dist/org/directory.js +254 -0
  102. package/dist/org/directory.js.map +1 -0
  103. package/dist/org/entities.d.ts +69 -0
  104. package/dist/org/entities.d.ts.map +1 -0
  105. package/dist/org/entities.js +39 -0
  106. package/dist/org/entities.js.map +1 -0
  107. package/dist/org/index.d.ts +5 -0
  108. package/dist/org/index.d.ts.map +1 -0
  109. package/dist/org/index.js +5 -0
  110. package/dist/org/index.js.map +1 -0
  111. package/dist/proxy/proxies.d.ts +18 -0
  112. package/dist/proxy/proxies.d.ts.map +1 -0
  113. package/dist/proxy/proxies.js +102 -0
  114. package/dist/proxy/proxies.js.map +1 -0
  115. package/dist/publish/project.d.ts +45 -0
  116. package/dist/publish/project.d.ts.map +1 -0
  117. package/dist/publish/project.js +176 -0
  118. package/dist/publish/project.js.map +1 -0
  119. package/dist/publish/publish.d.ts +42 -0
  120. package/dist/publish/publish.d.ts.map +1 -0
  121. package/dist/publish/publish.js +274 -0
  122. package/dist/publish/publish.js.map +1 -0
  123. package/dist/queries/queries.d.ts +24 -0
  124. package/dist/queries/queries.d.ts.map +1 -0
  125. package/dist/queries/queries.js +326 -0
  126. package/dist/queries/queries.js.map +1 -0
  127. package/dist/queries/stats.d.ts +9 -0
  128. package/dist/queries/stats.d.ts.map +1 -0
  129. package/dist/queries/stats.js +189 -0
  130. package/dist/queries/stats.js.map +1 -0
  131. package/dist/runtime/assignees.d.ts +32 -0
  132. package/dist/runtime/assignees.d.ts.map +1 -0
  133. package/dist/runtime/assignees.js +93 -0
  134. package/dist/runtime/assignees.js.map +1 -0
  135. package/dist/runtime/calls.d.ts +18 -0
  136. package/dist/runtime/calls.d.ts.map +1 -0
  137. package/dist/runtime/calls.js +182 -0
  138. package/dist/runtime/calls.js.map +1 -0
  139. package/dist/runtime/countersign.d.ts +26 -0
  140. package/dist/runtime/countersign.d.ts.map +1 -0
  141. package/dist/runtime/countersign.js +63 -0
  142. package/dist/runtime/countersign.js.map +1 -0
  143. package/dist/runtime/execution.d.ts +150 -0
  144. package/dist/runtime/execution.d.ts.map +1 -0
  145. package/dist/runtime/execution.js +792 -0
  146. package/dist/runtime/execution.js.map +1 -0
  147. package/dist/runtime/next-steps.d.ts +56 -0
  148. package/dist/runtime/next-steps.d.ts.map +1 -0
  149. package/dist/runtime/next-steps.js +145 -0
  150. package/dist/runtime/next-steps.js.map +1 -0
  151. package/dist/runtime/state.d.ts +26 -0
  152. package/dist/runtime/state.d.ts.map +1 -0
  153. package/dist/runtime/state.js +32 -0
  154. package/dist/runtime/state.js.map +1 -0
  155. package/dist/testing/scenarios.d.ts +35 -0
  156. package/dist/testing/scenarios.d.ts.map +1 -0
  157. package/dist/testing/scenarios.js +63 -0
  158. package/dist/testing/scenarios.js.map +1 -0
  159. package/dist/testing/simulate.d.ts +55 -0
  160. package/dist/testing/simulate.d.ts.map +1 -0
  161. package/dist/testing/simulate.js +122 -0
  162. package/dist/testing/simulate.js.map +1 -0
  163. package/dist/testing/testing.d.ts +31 -0
  164. package/dist/testing/testing.d.ts.map +1 -0
  165. package/dist/testing/testing.js +54 -0
  166. package/dist/testing/testing.js.map +1 -0
  167. package/dist/types.d.ts +283 -0
  168. package/dist/types.d.ts.map +1 -0
  169. package/dist/types.js +2 -0
  170. package/dist/types.js.map +1 -0
  171. package/dist/views.d.ts +317 -0
  172. package/dist/views.d.ts.map +1 -0
  173. package/dist/views.js +9 -0
  174. package/dist/views.js.map +1 -0
  175. package/package.json +76 -3
  176. package/src/client/client.ts +194 -0
  177. package/src/client/endpoint.ts +174 -0
  178. package/src/client/http.ts +99 -0
  179. package/src/client/index.ts +12 -0
  180. package/src/client/port.ts +78 -0
  181. package/src/client/protocol.ts +36 -0
  182. package/src/commands/admin.ts +308 -0
  183. package/src/commands/complete.ts +368 -0
  184. package/src/commands/dispatch.ts +106 -0
  185. package/src/commands/operate.ts +110 -0
  186. package/src/commands/operations.ts +524 -0
  187. package/src/commands/signal.ts +96 -0
  188. package/src/commands/start.ts +255 -0
  189. package/src/commands/submission.ts +51 -0
  190. package/src/core/channels.ts +14 -0
  191. package/src/core/context.ts +252 -0
  192. package/src/core/entities.ts +335 -0
  193. package/src/core/errors.ts +42 -0
  194. package/src/engine.ts +247 -0
  195. package/src/extensions.ts +231 -0
  196. package/src/index.ts +77 -0
  197. package/src/jobs/jobs.ts +320 -0
  198. package/src/notify/collect.ts +155 -0
  199. package/src/notify/inbox.ts +107 -0
  200. package/src/org/directory.ts +332 -0
  201. package/src/org/entities.ts +62 -0
  202. package/src/org/index.ts +21 -0
  203. package/src/proxy/proxies.ts +132 -0
  204. package/src/publish/project.ts +230 -0
  205. package/src/publish/publish.ts +314 -0
  206. package/src/queries/queries.ts +427 -0
  207. package/src/queries/stats.ts +207 -0
  208. package/src/runtime/assignees.ts +121 -0
  209. package/src/runtime/calls.ts +196 -0
  210. package/src/runtime/countersign.ts +83 -0
  211. package/src/runtime/execution.ts +915 -0
  212. package/src/runtime/next-steps.ts +213 -0
  213. package/src/runtime/state.ts +55 -0
  214. package/src/testing/scenarios.ts +95 -0
  215. package/src/testing/simulate.ts +190 -0
  216. package/src/testing/testing.ts +84 -0
  217. package/src/types.ts +286 -0
  218. package/src/views.ts +334 -0
  219. package/README.md +0 -3
@@ -0,0 +1,427 @@
1
+ /**
2
+ * 查询:待办、已办、抄送、我发起的、查单据、实例与待办详情、发起视图、能发起的流程。
3
+ */
4
+ import { and, not, or, type Ref } from '@zerodep-dev/easy-query-ts';
5
+ import {
6
+ fieldStates,
7
+ processGraph,
8
+ formManifest,
9
+ type ProcessDefinition,
10
+ type TaskNode,
11
+ type VariableDeclaration,
12
+ } from '@zerodep-dev/flow-ts-model';
13
+ import { actorTokens } from '../runtime/assignees.ts';
14
+ import { nextSteps, picksOf } from '../runtime/next-steps.ts';
15
+ import {
16
+ FlowCc,
17
+ FlowDefinition,
18
+ FlowEvent,
19
+ FlowInstance,
20
+ FlowWorkItem,
21
+ type flowSchema,
22
+ } from '../core/entities.ts';
23
+ import { FlowError } from '../core/errors.ts';
24
+ import { workItemSummary } from '../runtime/execution.ts';
25
+ import { availableOperations, excludeToken } from '../commands/operations.ts';
26
+ import { remindable, withdrawable } from '../commands/admin.ts';
27
+ import type { EngineCore } from '../core/context.ts';
28
+ import { stepsAfter } from '../runtime/next-steps.ts';
29
+ import { defaultsOf } from '../commands/start.ts';
30
+ import { outcomesFor, returnTargets } from '../commands/complete.ts';
31
+ import type { TodoItem, OutcomeView, WorkItemField } from '../views.ts';
32
+ import type { FlowEngine } from '../engine.ts';
33
+ import type { Actor, ListFilter } from '../types.ts';
34
+
35
+ type InstanceRef = Ref<typeof flowSchema, 'FlowInstance'>;
36
+
37
+ /** 发起的时刻在这段时间里、是这个流程的 */
38
+ const startedWithin = (i: InstanceRef, filter: ListFilter) => [
39
+ ...(filter.processKey ? [i.processKey.eq(filter.processKey)] : []),
40
+ ...(filter.from ? [i.startedAt.ge(new Date(filter.from))] : []),
41
+ ...(filter.to ? [i.startedAt.le(new Date(filter.to))] : []),
42
+ ];
43
+
44
+ /** 待办列表的列:待办加所属实例的流程与标题 */
45
+ const todoColumns = (
46
+ w: any,
47
+ ): Record<
48
+ Exclude<keyof TodoItem, 'summary' | 'quickOutcome'> | 'definitionId' | 'variables',
49
+ any
50
+ > => ({
51
+ id: w.id,
52
+ instanceId: w.instanceId,
53
+ node: w.node,
54
+ nodeName: w.nodeName,
55
+ round: w.round,
56
+ state: w.state,
57
+ assignment: w.assignment,
58
+ assignee: w.assignee,
59
+ proxyFor: w.proxyFor,
60
+ arrival: w.arrival,
61
+ createdAt: w.createdAt,
62
+ dueAt: w.dueAt,
63
+ completedAt: w.completedAt,
64
+ outcome: w.outcome,
65
+ processKey: w.instance.processKey,
66
+ instanceStatus: w.instance.status,
67
+ title: w.instance.title,
68
+ definitionId: w.instance.definitionId,
69
+ variables: w.instance.variables,
70
+ });
71
+
72
+ /** 待办详情的字段:变量当字段清单,按环节的表单权限算;不能处理时一律只读 */
73
+ function fieldsOf(
74
+ definition: ProcessDefinition,
75
+ task: TaskNode | undefined,
76
+ variables: Readonly<Record<string, unknown>>,
77
+ candidate: boolean,
78
+ ): WorkItemField[] {
79
+ const manifest = formManifest(definition);
80
+ const states = fieldStates(manifest, {
81
+ access: task?.form,
82
+ read: (name) => variables[name.startsWith('form.') ? name.slice(5) : name],
83
+ });
84
+ return Object.entries(manifest).flatMap(([name, field]) => {
85
+ const state = states.get(name);
86
+ if (!state?.visible) return [];
87
+ return [
88
+ {
89
+ name,
90
+ label: field.label,
91
+ type: field.type as VariableDeclaration['type'],
92
+ value: variables[name] ?? null,
93
+ editable: candidate && state.editable,
94
+ required: candidate && state.required,
95
+ },
96
+ ];
97
+ });
98
+ }
99
+
100
+ /** 查询:装进引擎核心(core.queries),别的模块经它调用 */
101
+ export function createQueries(core: EngineCore) {
102
+ const {
103
+ options,
104
+ db,
105
+ operations,
106
+ definitionOf,
107
+ isCandidate,
108
+ execution,
109
+ latestDefinition,
110
+ itemsOf,
111
+ } = core;
112
+
113
+ /** 这个人直接经手过实例:发起的、待办落到他或他处理过、在他能认领的收件箱里、抄送给他 */
114
+ const handled = (i: InstanceRef, actor: Actor) =>
115
+ or(
116
+ i.startedBy.eq(actor.id),
117
+ i.id.in(
118
+ db
119
+ .queryable(FlowWorkItem)
120
+ .where((w) =>
121
+ or(
122
+ w.assignee.eq(actor.id),
123
+ w.completedBy.eq(actor.id),
124
+ and(w.state.eq('open'), w.assignee.isNull(), w.candidates.hasAny(actorTokens(actor))),
125
+ ),
126
+ )
127
+ .select((w) => w.instanceId),
128
+ ),
129
+ i.id.in(
130
+ db
131
+ .queryable(FlowCc)
132
+ .where((c) => c.recipient.eq(actor.id))
133
+ .select((c) => c.instanceId),
134
+ ),
135
+ );
136
+
137
+ /** 经手过:直接经手的,加上它们调起的子流程(父流程的人看得到子流程走到哪;只往下一层,子流程的人看不到父流程) */
138
+ const involves = (i: InstanceRef, actor: Actor) =>
139
+ or(
140
+ handled(i, actor),
141
+ i.parentId.in(
142
+ db
143
+ .queryable(FlowInstance)
144
+ .where((p) => handled(p, actor))
145
+ .select((p) => p.id),
146
+ ),
147
+ );
148
+
149
+ /** 列表行补上摘要列(按实例的定义里 summary 列出的字段取流程变量)与批量处理时选的结果 */
150
+ async function withSummary(rows: Record<string, any>[]): Promise<TodoItem[]> {
151
+ const result: TodoItem[] = [];
152
+ for (const { definitionId, variables, ...row } of rows) {
153
+ const definition = await definitionOf(db, definitionId as number);
154
+ const values = variables as Record<string, unknown>;
155
+ const summary = Object.fromEntries(
156
+ (definition.summary ?? []).map((field) => [
157
+ field,
158
+ values[field.startsWith('form.') ? field.slice(5) : field],
159
+ ]),
160
+ );
161
+ const node = definition.nodes.find((n) => n.id === row['node']);
162
+ const quick =
163
+ row['state'] === 'open' && node?.type === 'task'
164
+ ? node.outcomes.find(
165
+ (o) => (o.kind ?? 'approve') === 'approve' && o.comment !== 'required',
166
+ )
167
+ : undefined;
168
+ result.push({
169
+ ...(row as Omit<TodoItem, 'summary' | 'quickOutcome'>),
170
+ summary,
171
+ quickOutcome: quick?.key ?? null,
172
+ });
173
+ }
174
+ return result;
175
+ }
176
+
177
+ const query: FlowEngine['query'] = {
178
+ incidents: (instance) => core.jobs.incidents(instance),
179
+ processes: async () => {
180
+ const rows = await db
181
+ .queryable(FlowDefinition)
182
+ .where((d) => d.enabled.eq(true))
183
+ .orderBy((d) => [d.processKey, d.version.desc()])
184
+ .toList();
185
+ const latest = new Map<string, ProcessDefinition>();
186
+ for (const row of rows)
187
+ if (!latest.has(row.processKey)) latest.set(row.processKey, row.model);
188
+ return [...latest.values()];
189
+ },
190
+ startView: async (key, actor) => {
191
+ const row = await latestDefinition(db, key);
192
+ const model = row.model;
193
+ const startNode = model.nodes.find((node) => node.type === 'start');
194
+ const values = defaultsOf(model);
195
+ // 还没有实例:按发起人与默认值预测下一步
196
+ const read = (field: string) => values[field.startsWith('form.') ? field.slice(5) : field];
197
+ const next = startNode
198
+ ? await nextSteps(
199
+ {
200
+ context: {
201
+ instance: { id: 0, processKey: key, businessKey: null, startedBy: actor.id },
202
+ variables: values,
203
+ read,
204
+ args: {},
205
+ },
206
+ handledBy: {},
207
+ options,
208
+ resolver: (name: string) => options.extensions?.resolvers?.[name],
209
+ graph: processGraph(model),
210
+ definition: model,
211
+ previous: actor.id,
212
+ },
213
+ startNode.id,
214
+ { read },
215
+ )
216
+ : [];
217
+ return {
218
+ process: { key, name: model.name, version: row.version },
219
+ manifest: formManifest(model),
220
+ access: startNode?.type === 'start' ? (startNode.form ?? null) : null,
221
+ values,
222
+ next,
223
+ picks: picksOf(next),
224
+ };
225
+ },
226
+ workItem: async (id, actor) => {
227
+ const workItem = await db.queryable(FlowWorkItem).find(id);
228
+ if (!workItem) throw new FlowError('not-found', `没有待办 ${id}`);
229
+ const instance = await db.queryable(FlowInstance).findOrThrow(workItem.instanceId);
230
+ const definition = await definitionOf(db, instance.definitionId);
231
+ const node = definition.nodes.find((n) => n.id === workItem.node);
232
+ const task = node?.type === 'task' ? node : undefined;
233
+ const open = workItem.state === 'open' && instance.status === 'active';
234
+ const candidate = open && isCandidate(workItem, actor);
235
+ const graph = processGraph(definition);
236
+ // 暂存只给处理人看:别人看到的待办没有它,字段显示存着的值
237
+ const draft = workItem.assignee === actor.id ? workItem.draft : null;
238
+ // 能处理的人才看到各个结果之后要给谁选处理人
239
+ const exec = task && candidate ? await execution(db, definition, instance, actor) : undefined;
240
+ const outcomes: OutcomeView[] = [];
241
+ for (const outcome of task ? outcomesFor(task, workItem) : []) {
242
+ const next = exec ? await stepsAfter(options, exec, task!, outcome, actor.id) : [];
243
+ const chooses = exec && outcome.kind === 'return' && outcome.target === 'choose';
244
+ const targets = chooses
245
+ ? returnTargets({ definition, graph, state: instance.state }, workItem.node).map(
246
+ (id) => ({
247
+ node: id,
248
+ nodeName: graph.node(id)?.name ?? id,
249
+ handler: instance.state.handledBy[id] ?? null,
250
+ }),
251
+ )
252
+ : [];
253
+ outcomes.push({ ...outcome, next, picks: picksOf(next), targets });
254
+ }
255
+ return {
256
+ workItem: { ...workItem, draft },
257
+ draft,
258
+ instance,
259
+ outcomes,
260
+ claimable: candidate && workItem.assignee === null,
261
+ completable: candidate,
262
+ operations: task
263
+ ? availableOperations(operations, {
264
+ item: workItem,
265
+ node: task,
266
+ instance,
267
+ actor,
268
+ candidate: isCandidate(workItem, actor),
269
+ items: await itemsOf(db, instance.id),
270
+ })
271
+ : [],
272
+ fields: fieldsOf(
273
+ definition,
274
+ task,
275
+ { ...instance.variables, ...(draft?.values ?? {}) },
276
+ candidate,
277
+ ),
278
+ };
279
+ },
280
+ started: (actor, filter = {}) =>
281
+ db
282
+ .queryable(FlowInstance)
283
+ .where((i) => [i.startedBy.eq(actor.id), i.status.ne('draft'), ...startedWithin(i, filter)])
284
+ .orderBy((i) => i.id.desc())
285
+ .toList(),
286
+ search: async (actor, filter = {}) => {
287
+ const scope = filter.scope ?? 'involved';
288
+ if (scope === 'all' && !actor.admin)
289
+ throw new FlowError('forbidden', '只有管理员能查全部单据');
290
+ const text = filter.text?.trim();
291
+ const status = filter.status?.length ? [...filter.status] : undefined;
292
+ return db
293
+ .queryable(FlowInstance)
294
+ .where((i) => [
295
+ status ? i.status.in(status) : i.status.ne('draft'),
296
+ ...(scope === 'started' ? [i.startedBy.eq(actor.id)] : []),
297
+ ...(scope === 'involved' ? [involves(i, actor)] : []),
298
+ ...(text
299
+ ? [
300
+ or(
301
+ i.title.like(text, { ignoreCase: true }),
302
+ i.businessKey.like(text, { ignoreCase: true }),
303
+ ),
304
+ ]
305
+ : []),
306
+ ...startedWithin(i, filter),
307
+ ])
308
+ .orderBy((i) => i.id.desc())
309
+ .toPage(Math.max(1, filter.page ?? 1), Math.min(200, Math.max(1, filter.size ?? 20)));
310
+ },
311
+ cc: (actor) =>
312
+ db
313
+ .queryable(FlowCc)
314
+ .where((c) => c.recipient.eq(actor.id))
315
+ .orderBy((c) => [c.readAt.isNull().desc(), c.id.desc()])
316
+ .select((c) => ({
317
+ id: c.id,
318
+ instanceId: c.instanceId,
319
+ node: c.node,
320
+ recipient: c.recipient,
321
+ sender: c.sender,
322
+ message: c.message,
323
+ at: c.at,
324
+ readAt: c.readAt,
325
+ processKey: c.instance.processKey,
326
+ title: c.instance.title,
327
+ status: c.instance.status,
328
+ }))
329
+ .toList(),
330
+ todo: (actor) =>
331
+ db
332
+ .queryable(FlowWorkItem)
333
+ .where((w) => [
334
+ w.state.eq('open'),
335
+ or(
336
+ w.assignee.eq(actor.id),
337
+ and(
338
+ w.assignee.isNull(),
339
+ w.candidates.hasAny(actorTokens(actor)),
340
+ not(w.candidates.has(excludeToken(actor.id))),
341
+ ),
342
+ ),
343
+ ])
344
+ .orderBy((w) => w.id)
345
+ .select(todoColumns)
346
+ .toList()
347
+ .then(withSummary),
348
+ done: (actor, filter = {}) =>
349
+ db
350
+ .queryable(FlowWorkItem)
351
+ .where((w) => [
352
+ w.state.eq('done'),
353
+ w.completedBy.eq(actor.id),
354
+ ...(filter.processKey ? [w.instance.processKey.eq(filter.processKey)] : []),
355
+ ...(filter.from ? [w.completedAt.ge(new Date(filter.from))] : []),
356
+ ...(filter.to ? [w.completedAt.le(new Date(filter.to))] : []),
357
+ ])
358
+ .orderBy((w) => w.id.desc())
359
+ .select(todoColumns)
360
+ .toList()
361
+ .then(withSummary),
362
+ designations: (actor) =>
363
+ db
364
+ .queryable(FlowWorkItem)
365
+ .where((w) => [
366
+ w.state.eq('open'),
367
+ w.awaitingDesignation.eq(true),
368
+ w.designator.eq(actor.id),
369
+ ])
370
+ .orderBy((w) => w.id)
371
+ .select(todoColumns)
372
+ .toList()
373
+ .then(withSummary),
374
+ instance: async (id, actor) => {
375
+ const instance = await db.queryable(FlowInstance).find(id);
376
+ if (!instance) throw new FlowError('not-found', `没有实例 ${id}`);
377
+ if (
378
+ actor &&
379
+ !actor.admin &&
380
+ !(await db
381
+ .queryable(FlowInstance)
382
+ .where((i) => [i.id.eq(id), involves(i, actor)])
383
+ .any())
384
+ )
385
+ throw new FlowError('forbidden', `实例 ${id} 不是你经手的`);
386
+ const items = await db
387
+ .queryable(FlowWorkItem)
388
+ .where((w) => w.instanceId.eq(id))
389
+ .orderBy((w) => w.id)
390
+ .toList();
391
+ const events = await db
392
+ .queryable(FlowEvent)
393
+ .where((e) => e.instanceId.eq(id))
394
+ .orderBy((e) => e.id)
395
+ .toList();
396
+ const definition = await definitionOf(db, instance.definitionId);
397
+ const nodes = definition.nodes;
398
+ const current = instance.current.map((node) => ({
399
+ node,
400
+ name: nodes.find((n) => n.id === node)?.name ?? node,
401
+ }));
402
+ const active = instance.status === 'active';
403
+ const starter = actor?.id === instance.startedBy;
404
+ const actions = {
405
+ withdraw: active && starter && withdrawable(definition, items, instance.startedBy),
406
+ remind:
407
+ active &&
408
+ (starter || actor?.admin === true) &&
409
+ items.some((w) => w.state === 'open' && remindable(definition, w.node)),
410
+ manage: actor?.admin === true && ['active', 'suspended'].includes(instance.status),
411
+ };
412
+ return {
413
+ instance,
414
+ definition,
415
+ current,
416
+ workItems: items.map(workItemSummary),
417
+ events,
418
+ actions,
419
+ };
420
+ },
421
+ };
422
+
423
+ return { withSummary, query };
424
+ }
425
+
426
+ /** createQueries 给出的函数 */
427
+ export type Queries = ReturnType<typeof createQueries>;
@@ -0,0 +1,207 @@
1
+ /**
2
+ * 监控与统计(docs/decisions/0010 第 4 节):管理员的看板——这段时间发起、结束了多少,各流程平均走多久,
3
+ * 哪些环节最慢(瓶颈)、超时最多,谁手上压着待办,有多少异常。计数在库里分组算;时长按这段时间结束的行在这里算
4
+ * (只取这段时间的,看板默认 30 天)。按天的趋势用调用方的时区分日子。
5
+ */
6
+ import { FlowInstance, FlowJob, FlowWorkItem } from '../core/entities.ts';
7
+ import type { EngineCore } from '../core/context.ts';
8
+ import type { FlowStats, StatsFilter } from '../views.ts';
9
+
10
+ const HOUR = 3_600_000;
11
+ const DAY = 24 * HOUR;
12
+ /** 结束了的状态(不算草稿、进行中、暂停) */
13
+ const ENDED = ['completed', 'terminated', 'withdrawn'] as const;
14
+
15
+ /** 平均小时数,保留一位;没有行时为空 */
16
+ const averageHours = (durations: readonly number[]) =>
17
+ durations.length
18
+ ? Math.round((durations.reduce((a, b) => a + b, 0) / durations.length / HOUR) * 10) / 10
19
+ : null;
20
+
21
+ /** 统计:装进引擎核心(core.stats) */
22
+ export function createStats(core: EngineCore) {
23
+ const { db, now } = core;
24
+
25
+ async function overview(filter: StatsFilter = {}): Promise<FlowStats> {
26
+ const at = now();
27
+ const to = filter.to ?? at;
28
+ const from = filter.from ?? new Date(to.getTime() - 30 * DAY);
29
+ const day = new Intl.DateTimeFormat('en-CA', {
30
+ timeZone: filter.timeZone ?? 'UTC',
31
+ year: 'numeric',
32
+ month: '2-digit',
33
+ day: '2-digit',
34
+ });
35
+ const key = filter.processKey;
36
+
37
+ const [active, started, ended, done, open, incidents] = await Promise.all([
38
+ db
39
+ .queryable(FlowInstance)
40
+ .where((i) => [
41
+ i.status.in(['active', 'suspended']),
42
+ ...(key ? [i.processKey.eq(key)] : []),
43
+ ])
44
+ .groupBy((i) => ({ processKey: i.processKey }))
45
+ .select((g) => ({ processKey: g.key.processKey, count: g.count() }))
46
+ .toList(),
47
+ db
48
+ .queryable(FlowInstance)
49
+ .where((i) => [
50
+ i.status.ne('draft'),
51
+ i.startedAt.ge(from),
52
+ i.startedAt.le(to),
53
+ ...(key ? [i.processKey.eq(key)] : []),
54
+ ])
55
+ .select((i) => ({ processKey: i.processKey, startedAt: i.startedAt }))
56
+ .toList(),
57
+ db
58
+ .queryable(FlowInstance)
59
+ .where((i) => [
60
+ i.status.in([...ENDED]),
61
+ i.endedAt.ge(from),
62
+ i.endedAt.le(to),
63
+ ...(key ? [i.processKey.eq(key)] : []),
64
+ ])
65
+ .select((i) => ({
66
+ processKey: i.processKey,
67
+ status: i.status,
68
+ startedAt: i.startedAt,
69
+ endedAt: i.endedAt,
70
+ }))
71
+ .toList(),
72
+ db
73
+ .queryable(FlowWorkItem)
74
+ .where((w) => [
75
+ w.state.eq('done'),
76
+ w.completedAt.ge(from),
77
+ w.completedAt.le(to),
78
+ ...(key ? [w.instance.processKey.eq(key)] : []),
79
+ ])
80
+ .select((w) => ({
81
+ processKey: w.instance.processKey,
82
+ node: w.node,
83
+ nodeName: w.nodeName,
84
+ createdAt: w.createdAt,
85
+ completedAt: w.completedAt,
86
+ dueAt: w.dueAt,
87
+ }))
88
+ .toList(),
89
+ db
90
+ .queryable(FlowWorkItem)
91
+ .where((w) => [
92
+ w.state.eq('open'),
93
+ w.assignee.isNotNull(),
94
+ ...(key ? [w.instance.processKey.eq(key)] : []),
95
+ ])
96
+ .groupBy((w) => ({ assignee: w.assignee }))
97
+ .select((g) => ({
98
+ user: g.key.assignee,
99
+ open: g.count(),
100
+ overdue: g.count((w) => w.dueAt.lt(at)),
101
+ }))
102
+ .toList(),
103
+ db
104
+ .queryable(FlowJob)
105
+ .where((j) => [j.state.eq('failed')])
106
+ .count(),
107
+ ]);
108
+
109
+ // 各流程:进行中、发起、结束、平均时长
110
+ const processes = new Map<
111
+ string,
112
+ { active: number; started: number; finished: number; durations: number[] }
113
+ >();
114
+ const processOf = (key: string) => {
115
+ let entry = processes.get(key);
116
+ if (!entry)
117
+ processes.set(key, (entry = { active: 0, started: 0, finished: 0, durations: [] }));
118
+ return entry;
119
+ };
120
+ for (const row of active) processOf(row.processKey).active = row.count;
121
+ for (const row of started) processOf(row.processKey).started++;
122
+ for (const row of ended) {
123
+ const entry = processOf(row.processKey);
124
+ entry.finished++;
125
+ if (row.endedAt) entry.durations.push(row.endedAt.getTime() - row.startedAt.getTime());
126
+ }
127
+
128
+ // 各环节:办了几份、平均停多久、超时几份;慢的在前
129
+ const nodes = new Map<
130
+ string,
131
+ { processKey: string; node: string; nodeName: string; durations: number[]; overdue: number }
132
+ >();
133
+ for (const row of done) {
134
+ const id = `${row.processKey}\u0000${row.node}`;
135
+ let entry = nodes.get(id);
136
+ if (!entry)
137
+ nodes.set(
138
+ id,
139
+ (entry = {
140
+ processKey: row.processKey,
141
+ node: row.node,
142
+ nodeName: row.nodeName,
143
+ durations: [],
144
+ overdue: 0,
145
+ }),
146
+ );
147
+ const completed = row.completedAt ?? at;
148
+ entry.durations.push(completed.getTime() - row.createdAt.getTime());
149
+ if (row.dueAt && completed > row.dueAt) entry.overdue++;
150
+ }
151
+
152
+ // 按天:发起与结束
153
+ const daily = new Map<string, { started: number; finished: number }>();
154
+ for (let t = from.getTime(); t <= to.getTime(); t += DAY)
155
+ daily.set(day.format(new Date(t)), { started: 0, finished: 0 });
156
+ daily.set(day.format(to), daily.get(day.format(to)) ?? { started: 0, finished: 0 });
157
+ for (const row of started) {
158
+ const bucket = daily.get(day.format(row.startedAt));
159
+ if (bucket) bucket.started++;
160
+ }
161
+ for (const row of ended) {
162
+ const bucket = row.endedAt && daily.get(day.format(row.endedAt));
163
+ if (bucket) bucket.finished++;
164
+ }
165
+
166
+ const workload = open
167
+ .filter((row): row is typeof row & { user: string } => row.user !== null)
168
+ .sort((a, b) => b.open - a.open);
169
+ return {
170
+ from,
171
+ to,
172
+ totals: {
173
+ active: active.reduce((sum, row) => sum + row.count, 0),
174
+ started: started.length,
175
+ finished: ended.length,
176
+ rejected: ended.filter((row) => row.status !== 'completed').length,
177
+ open: workload.reduce((sum, row) => sum + row.open, 0),
178
+ overdue: workload.reduce((sum, row) => sum + row.overdue, 0),
179
+ incidents,
180
+ },
181
+ processes: [...processes].map(([processKey, entry]) => ({
182
+ processKey,
183
+ active: entry.active,
184
+ started: entry.started,
185
+ finished: entry.finished,
186
+ averageHours: averageHours(entry.durations),
187
+ })),
188
+ nodes: [...nodes.values()]
189
+ .map((entry) => ({
190
+ processKey: entry.processKey,
191
+ node: entry.node,
192
+ nodeName: entry.nodeName,
193
+ done: entry.durations.length,
194
+ averageHours: averageHours(entry.durations)!,
195
+ overdue: entry.overdue,
196
+ }))
197
+ .sort((a, b) => b.averageHours - a.averageHours),
198
+ workload,
199
+ daily: [...daily].map(([date, counts]) => ({ date, ...counts })),
200
+ };
201
+ }
202
+
203
+ return { overview };
204
+ }
205
+
206
+ /** 统计模块 */
207
+ export type Stats = ReturnType<typeof createStats>;