@zerodep-dev/flow-ts-engine 0.0.0-stage → 0.1.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 +21 -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,155 @@
1
+ /**
2
+ * 通知(docs/decisions/0010):推进写完流转记录时,按这一步的事件生成通知,与推进同一个事务写入。
3
+ *
4
+ * | 事件 | 来自 | 发给 |
5
+ * | arrived / returned | 新建的待办(退回来的是 returned) | 处理人;收件箱里的发给能认领的人 |
6
+ * | reminded | 手动催办、收件箱很久没人认领 | 同上 |
7
+ * | dueSoon | 到期前的提醒 | 同上 |
8
+ * | overdue | 待办超时 | 同上 |
9
+ * | cc | 抄送 | 抄送的人 |
10
+ * | finished | 实例结束(完成、终止、撤回) | 发起人 |
11
+ *
12
+ * 流程级、节点级的 notify 设置:`false` 不发;`to` 加收件人;`template` 换文字(花括号里是字段名,同标题模板)。
13
+ * 不发给引起这件事的人自己(自己催自己、自己撤回)。
14
+ */
15
+ import type { NotifyEvent, NotifySettings } from '@zerodep-dev/flow-ts-model';
16
+ import { FlowWorkItem } from '../core/entities.ts';
17
+ import type { FlowEventView } from '../types.ts';
18
+ import { expandToUsers, parseCandidate } from '../runtime/assignees.ts';
19
+ import { renderTitle, type Execution, type WorkItemRow } from '../runtime/execution.ts';
20
+
21
+ /** 要写进 flow_notification 的一行 */
22
+ export interface NotificationInsert {
23
+ readonly recipient: string;
24
+ readonly event: NotifyEvent;
25
+ readonly instanceId: number;
26
+ readonly workItemId: number | null;
27
+ readonly node: string | null;
28
+ readonly nodeName: string | null;
29
+ readonly processKey: string;
30
+ readonly title: string | null;
31
+ readonly message: string | null;
32
+ readonly sender: string | null;
33
+ readonly createdAt: Date;
34
+ readonly readAt: null;
35
+ readonly sentAt: null;
36
+ readonly attempts: 0;
37
+ readonly lastError: null;
38
+ }
39
+
40
+ const FINISHED = new Set(['completed', 'terminated', 'withdrawn']);
41
+
42
+ /** 待办的收件人:处理人;收件箱里的是能认领的人(候选展开成人,去掉排除的) */
43
+ async function itemRecipients(exec: Execution, item: WorkItemRow): Promise<string[]> {
44
+ if (item.assignee) return [item.assignee];
45
+ const excluded = new Set(
46
+ item.candidates.filter((t) => t.startsWith('-')).map((t) => parseCandidate(t.slice(1)).value),
47
+ );
48
+ const candidates = item.candidates.filter((t) => !t.startsWith('-')).map(parseCandidate);
49
+ // 没配 org 时角色、部门展不开:只发给直接点名的人
50
+ const users = exec.options.org
51
+ ? await expandToUsers(candidates, exec.options)
52
+ : candidates.filter((c) => c.kind === 'user').map((c) => c.value);
53
+ return users.filter((user) => !excluded.has(user));
54
+ }
55
+
56
+ /** 这一步的事件 → 通知 */
57
+ export async function collectNotifications(
58
+ exec: Execution,
59
+ events: readonly FlowEventView[],
60
+ title: string | null,
61
+ ): Promise<NotificationInsert[]> {
62
+ const rows: NotificationInsert[] = [];
63
+ const seen = new Set<string>();
64
+ const processSettings: NotifySettings = exec.definition.settings?.notify ?? {};
65
+
66
+ const add = async (
67
+ event: NotifyEvent,
68
+ recipients: readonly string[],
69
+ fields: { node: string | null; workItemId: number | null; sender: string | null },
70
+ ) => {
71
+ const node = fields.node ? exec.graph.node(fields.node) : undefined;
72
+ const setting = node?.notify?.[event] ?? processSettings[event];
73
+ if (setting === false) return;
74
+ const extra = setting?.to ? await exec.resolveUsers(setting.to) : [];
75
+ const message = setting?.template ? renderTitle(setting.template, exec.read) : null;
76
+ for (const recipient of [...recipients, ...extra]) {
77
+ const key = `${recipient}|${event}|${fields.workItemId ?? ''}`;
78
+ if (recipient === fields.sender || seen.has(key)) continue;
79
+ seen.add(key);
80
+ rows.push({
81
+ recipient,
82
+ event,
83
+ instanceId: exec.instance.id,
84
+ workItemId: fields.workItemId,
85
+ node: fields.node,
86
+ nodeName: node?.name ?? null,
87
+ processKey: exec.instance.processKey,
88
+ title,
89
+ message,
90
+ sender: fields.sender,
91
+ createdAt: exec.now,
92
+ readAt: null,
93
+ sentAt: null,
94
+ attempts: 0,
95
+ lastError: null,
96
+ });
97
+ }
98
+ };
99
+
100
+ // 催办、提醒、超时的待办不在这一步新建的里:一次查出来
101
+ const mentioned = events
102
+ .filter(
103
+ (e) => (e.type === 'workItem.reminded' || e.type === 'workItem.overdue') && e.workItemId,
104
+ )
105
+ .map((e) => e.workItemId!);
106
+ const existing = mentioned.length
107
+ ? await exec.tx
108
+ .queryable(FlowWorkItem)
109
+ .where((w) => w.id.in(mentioned))
110
+ .toList()
111
+ : [];
112
+ const itemOf = (id: number | null) =>
113
+ exec.created.find((w) => w.id === id) ?? existing.find((w) => w.id === id);
114
+
115
+ for (const event of events) {
116
+ const fields = { node: event.node, workItemId: event.workItemId, sender: event.actor };
117
+ const item = itemOf(event.workItemId);
118
+ switch (event.type) {
119
+ case 'workItem.created':
120
+ if (item)
121
+ await add(
122
+ item.arrival === 'return' ? 'returned' : 'arrived',
123
+ await itemRecipients(exec, item),
124
+ fields,
125
+ );
126
+ break;
127
+ case 'workItem.reminded': {
128
+ if (!item || item.state !== 'open') break;
129
+ const data = event.data ?? {};
130
+ // 到期前的提醒是 dueSoon;手动催办、没人认领的提醒是 reminded
131
+ const kind: NotifyEvent =
132
+ data['auto'] && data['reason'] !== 'unclaimed' ? 'dueSoon' : 'reminded';
133
+ await add(kind, await itemRecipients(exec, item), fields);
134
+ break;
135
+ }
136
+ case 'workItem.overdue':
137
+ if (item && item.state === 'open')
138
+ await add('overdue', await itemRecipients(exec, item), fields);
139
+ break;
140
+ case 'instance.cc': {
141
+ const to = (event.data?.['to'] ?? []) as readonly string[];
142
+ await add('cc', to, fields);
143
+ break;
144
+ }
145
+ }
146
+ }
147
+
148
+ if (FINISHED.has(exec.status) && !FINISHED.has(exec.instance.status))
149
+ await add('finished', [exec.instance.startedBy], {
150
+ node: null,
151
+ workItemId: null,
152
+ sender: exec.actor?.id ?? null,
153
+ });
154
+ return rows;
155
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * 通知的信箱与发件箱(docs/decisions/0010;推进时怎么生成见 collect.ts):我的通知、未读数、标为已读;外部投递——
3
+ * 引擎选项给了 notifications.deliver 时,提交后把还没送到的逐条交给它,抛错的记下原因、留着,到点作业再试(最多 MAX_ATTEMPTS 次)。
4
+ */
5
+ import type { Row } from '@zerodep-dev/easy-query-ts';
6
+ import { FlowNotification } from '../core/entities.ts';
7
+ import type { EngineCore } from '../core/context.ts';
8
+ import type { Actor } from '../types.ts';
9
+ import type { NotificationView } from '../views.ts';
10
+
11
+ /** 外部投递最多试几次(之后留在表里,管理员看 lastError) */
12
+ export const MAX_ATTEMPTS = 5;
13
+
14
+ /** 表里的一行 → 给页面与投递的样子 */
15
+ export const notificationView = (row: Row<typeof FlowNotification>): NotificationView => ({
16
+ id: row.id,
17
+ recipient: row.recipient,
18
+ event: row.event as NotificationView['event'],
19
+ instanceId: row.instanceId,
20
+ workItemId: row.workItemId,
21
+ node: row.node,
22
+ nodeName: row.nodeName,
23
+ processKey: row.processKey,
24
+ title: row.title,
25
+ message: row.message,
26
+ sender: row.sender,
27
+ createdAt: row.createdAt,
28
+ readAt: row.readAt,
29
+ });
30
+
31
+ /** 通知:装进引擎核心(core.notifications) */
32
+ export function createNotifications(core: EngineCore) {
33
+ const { db, options, now } = core;
34
+
35
+ /** 我的通知,新的在前;unreadOnly 只要没读的 */
36
+ const list = async (actor: Actor, filter: { unreadOnly?: boolean; limit?: number } = {}) =>
37
+ (
38
+ await db
39
+ .queryable(FlowNotification)
40
+ .where((n) => [n.recipient.eq(actor.id), ...(filter.unreadOnly ? [n.readAt.isNull()] : [])])
41
+ .orderBy((n) => n.id.desc())
42
+ .limit(Math.min(200, Math.max(1, filter.limit ?? 50)))
43
+ .toList()
44
+ ).map(notificationView);
45
+
46
+ /** 我没读的有几条 */
47
+ const unread = (actor: Actor) =>
48
+ db
49
+ .queryable(FlowNotification)
50
+ .where((n) => [n.recipient.eq(actor.id), n.readAt.isNull()])
51
+ .count();
52
+
53
+ /** 标为已读:给了编号只标这些(只能标自己的),不给时全部;返回标了几条 */
54
+ const read = (actor: Actor, ids?: readonly number[]) =>
55
+ db
56
+ .update(FlowNotification)
57
+ .set({ readAt: now() })
58
+ .where((n) => [
59
+ n.recipient.eq(actor.id),
60
+ n.readAt.isNull(),
61
+ ...(ids ? [n.id.in([...ids])] : []),
62
+ ])
63
+ .execute();
64
+
65
+ /** 外部投递还没送到的(提交后、到点作业里都调它);没配 deliver 时什么也不做。返回送到了几条 */
66
+ async function deliverPending(): Promise<number> {
67
+ const deliver = options.notifications?.deliver;
68
+ if (!deliver) return 0;
69
+ const pending = await db
70
+ .queryable(FlowNotification)
71
+ .where((n) => [n.sentAt.isNull(), n.attempts.lt(MAX_ATTEMPTS)])
72
+ .orderBy((n) => n.id)
73
+ .limit(100)
74
+ .toList();
75
+ let sent = 0;
76
+ for (const row of pending) {
77
+ // 先占用:带条件地把次数加一,别的进程(多实例部署)已经占了就跳过,不重复投递
78
+ const claimed = await db
79
+ .update(FlowNotification)
80
+ .set({ attempts: row.attempts + 1 })
81
+ .where((n) => [n.id.eq(row.id), n.sentAt.isNull(), n.attempts.eq(row.attempts)])
82
+ .execute();
83
+ if (claimed === 0) continue;
84
+ try {
85
+ await deliver(notificationView(row));
86
+ await db
87
+ .update(FlowNotification)
88
+ .set({ sentAt: now(), lastError: null })
89
+ .where((n) => n.id.eq(row.id))
90
+ .execute();
91
+ sent++;
92
+ } catch (error) {
93
+ await db
94
+ .update(FlowNotification)
95
+ .set({ lastError: error instanceof Error ? error.message : String(error) })
96
+ .where((n) => n.id.eq(row.id))
97
+ .execute();
98
+ }
99
+ }
100
+ return sent;
101
+ }
102
+
103
+ return { list, unread, read, deliverPending };
104
+ }
105
+
106
+ /** createNotifications 给出的函数 */
107
+ export type Notifications = ReturnType<typeof createNotifications>;
@@ -0,0 +1,332 @@
1
+ /**
2
+ * 组织目录:把组织的表接到引擎上——org(角色、部门展开成人)、处理人解析器(上级、部门负责人)、做事的人(Actor)。
3
+ *
4
+ * const directory = createOrgDirectory({ adapter, isAdmin: (e) => e.roles.includes('admin') });
5
+ * await directory.createTables();
6
+ * const engine = createFlowEngine({ adapter, org: directory.org, extensions: { resolvers: directory.resolvers } });
7
+ *
8
+ * 引擎在事务里展开处理人,读的是内存里的一份快照,不另发查询:组织很小、很少变,快照省掉每个节点的几次往返,
9
+ * 也不会在只有一条连接的库(PGlite)上等自己的事务。经目录改的(sync、save*、removeDepartment)会自动刷新,并广播 ORG_CHANNEL:
10
+ * 多实例部署时别的进程收听它、调 refresh()(见 core/channels.ts);绕过目录直接改了表也调 refresh()
11
+ */
12
+ import { createDb, type Adapter } from '@zerodep-dev/easy-query-ts';
13
+ import { ORG_CHANNEL } from '../core/channels.ts';
14
+ import { FlowError } from '../core/errors.ts';
15
+ import type { Actor, ExtensionContext, FlowOrg, Resolver } from '../types.ts';
16
+ import {
17
+ OrgDepartment,
18
+ OrgEmployee,
19
+ OrgRole,
20
+ orgSchema,
21
+ type DepartmentRow,
22
+ type EmployeeRow,
23
+ type OrgDb,
24
+ type RoleRow,
25
+ } from './entities.ts';
26
+
27
+ export interface OrgDirectoryOptions {
28
+ readonly adapter: Adapter;
29
+ /** 谁能做管理员的事(干预流程、处理异常);不给时没有管理员 */
30
+ readonly isAdmin?: (employee: EmployeeRow) => boolean;
31
+ /** 扩展种类(候选写成 `{ group }`)的成员;不给时为空 */
32
+ readonly groupMembers?: (group: string) => readonly string[] | Promise<readonly string[]>;
33
+ }
34
+
35
+ /** 部门的值;sort 不写时是 0 */
36
+ export type DepartmentInput = Omit<DepartmentRow, 'sort'> & { readonly sort?: number };
37
+ /** 员工的值;不写的:职务、上级为空,没有角色,在职 */
38
+ export type EmployeeInput = Pick<EmployeeRow, 'id' | 'name' | 'departmentId'> &
39
+ Partial<Pick<EmployeeRow, 'title' | 'managerId' | 'roles' | 'active'>>;
40
+
41
+ /** 整批同步的数据:三张表的全部行 */
42
+ export interface OrgData {
43
+ readonly departments: readonly DepartmentInput[];
44
+ readonly roles: readonly RoleRow[];
45
+ readonly employees: readonly EmployeeInput[];
46
+ }
47
+
48
+ /** 读出来的组织:部门按树的先序(上级在前、同级按 sort),员工、角色按编号 */
49
+ export interface OrgSnapshot {
50
+ readonly departments: readonly DepartmentRow[];
51
+ readonly roles: readonly RoleRow[];
52
+ readonly employees: readonly EmployeeRow[];
53
+ }
54
+
55
+ export interface OrgDirectory {
56
+ readonly db: OrgDb;
57
+ /** 建缺的表(开发、测试;生产走迁移脚本) */
58
+ createTables(): Promise<void>;
59
+ /** 整批替换成这份数据(从 HR 系统同步、演示数据),一个事务里做完,然后刷新快照 */
60
+ sync(data: OrgData): Promise<void>;
61
+ /** 重新读快照 */
62
+ refresh(): Promise<void>;
63
+ /** 新增或修改部门(按编号):上级要存在,不能是它自己或它下面的部门;负责人要是在职的员工 */
64
+ saveDepartment(row: DepartmentInput): Promise<void>;
65
+ /** 删部门:下面还有部门或员工时不删(invalid-input) */
66
+ removeDepartment(id: string): Promise<void>;
67
+ /** 新增或修改员工(按编号):部门要存在,上级不能是他自己或他的下属;离职写 active: false,不删 */
68
+ saveEmployee(row: EmployeeInput): Promise<void>;
69
+ /** 新增或修改角色(按编号) */
70
+ saveRole(row: RoleRow): Promise<void>;
71
+ /** 当前的组织(没读过时先读) */
72
+ snapshot(): Promise<OrgSnapshot>;
73
+ /** 给引擎的 org:角色、部门(含下级部门)展开成在职的人;部门收件箱的负责人是部门负责人 */
74
+ readonly org: FlowOrg;
75
+ /**
76
+ * 处理人解析器,参数(定义里的 args):
77
+ * - `manager`:发起人的直属上级;`levels: 2` 是上级的上级;`field` 指定按单据里这个字段的人算(默认发起人)。离职的跳过,再往上找
78
+ * - `departmentHead`:发起人所在部门的负责人;`level: 1` 是他所在的一级部门(根部门下面那一级)的,他本身在更高的部门时按所在部门;
79
+ * 负责人是他自己、空缺或离职时找上级部门的;`field` 同上
80
+ */
81
+ readonly resolvers: { readonly manager: Resolver; readonly departmentHead: Resolver };
82
+ /** 引擎眼里的这个人:角色、所在部门及其全部上级部门(上级部门的收件箱他也看得到,与 members 的展开一致);不在或离职时 undefined */
83
+ actorOf(id: string): Promise<Actor | undefined>;
84
+ }
85
+
86
+ /** 快照加上查找用的索引 */
87
+ interface Loaded extends OrgSnapshot {
88
+ readonly department: ReadonlyMap<string, DepartmentRow>;
89
+ readonly employee: ReadonlyMap<string, EmployeeRow>;
90
+ readonly children: ReadonlyMap<string | null, readonly DepartmentRow[]>;
91
+ }
92
+
93
+ export function createOrgDirectory(options: OrgDirectoryOptions): OrgDirectory {
94
+ const db = createDb({ schema: orgSchema, adapter: options.adapter });
95
+ let loading: Promise<Loaded> | undefined;
96
+
97
+ const load = () =>
98
+ (loading ??= read(db).catch((error: unknown) => {
99
+ loading = undefined;
100
+ throw error;
101
+ }));
102
+ const refresh = async () => {
103
+ loading = undefined;
104
+ await load();
105
+ };
106
+
107
+ /** 部门和它下面的全部部门(数据里有环时也会停下) */
108
+ const subtree = (org: Loaded, id: string): Set<string> => {
109
+ const found = new Set([id]);
110
+ for (const at of found) for (const child of org.children.get(at) ?? []) found.add(child.id);
111
+ return found;
112
+ };
113
+
114
+ /** 部门和它的全部上级部门,从近到远 */
115
+ const lineage = (org: Loaded, id: string | null): DepartmentRow[] => {
116
+ const chain: DepartmentRow[] = [];
117
+ for (let at = id; at !== null;) {
118
+ const department = org.department.get(at);
119
+ // 数据里有环时停下
120
+ if (!department || chain.includes(department)) break;
121
+ chain.push(department);
122
+ at = department.parentId;
123
+ }
124
+ return chain;
125
+ };
126
+
127
+ const active = (org: Loaded, id: string | null) => {
128
+ const employee = id === null ? undefined : org.employee.get(id);
129
+ return employee?.active ? employee : undefined;
130
+ };
131
+
132
+ /** 解析器按谁算:args.field 指的单据字段,默认发起人 */
133
+ const subjectOf = (org: Loaded, context: ExtensionContext) => {
134
+ const field = context.args.field;
135
+ const id = typeof field === 'string' ? context.read(field) : context.instance.startedBy;
136
+ return typeof id === 'string' ? org.employee.get(id) : undefined;
137
+ };
138
+
139
+ const manager: Resolver = async (context) => {
140
+ const org = await load();
141
+ let levels = typeof context.args.levels === 'number' ? context.args.levels : 1;
142
+ const seen = new Set<string>();
143
+ for (let at = subjectOf(org, context)?.managerId ?? null; at !== null && !seen.has(at);) {
144
+ seen.add(at);
145
+ const employee = org.employee.get(at);
146
+ if (!employee) break;
147
+ if (employee.active && --levels === 0) return [employee.id];
148
+ at = employee.managerId;
149
+ }
150
+ return [];
151
+ };
152
+
153
+ const departmentHead: Resolver = async (context) => {
154
+ const org = await load();
155
+ const subject = subjectOf(org, context);
156
+ if (!subject) return [];
157
+ const chain = lineage(org, subject.departmentId);
158
+ // chain 从近到远、最后一个是根:第 level 级部门在倒数第 level + 1 个
159
+ const level = typeof context.args.level === 'number' ? context.args.level : undefined;
160
+ const from = level === undefined ? 0 : Math.max(0, chain.length - 1 - level);
161
+ const head = chain
162
+ .slice(from)
163
+ .map((department) => active(org, department.headId))
164
+ .find((employee) => employee && employee.id !== subject.id);
165
+ return head ? [head.id] : [];
166
+ };
167
+
168
+ const org: FlowOrg = {
169
+ members: async (source) => {
170
+ if ('group' in source) return (await options.groupMembers?.(source.group)) ?? [];
171
+ const loaded = await load();
172
+ if ('role' in source)
173
+ return loaded.employees
174
+ .filter((e) => e.active && e.roles.includes(source.role))
175
+ .map((e) => e.id);
176
+ const departments = subtree(loaded, source.department);
177
+ return loaded.employees
178
+ .filter((e) => e.active && departments.has(e.departmentId))
179
+ .map((e) => e.id);
180
+ },
181
+ inboxManager: async ({ kind, value }) => {
182
+ if (kind !== 'department') return undefined;
183
+ const loaded = await load();
184
+ return lineage(loaded, value)
185
+ .map((department) => active(loaded, department.headId))
186
+ .find(Boolean)?.id;
187
+ },
188
+ };
189
+
190
+ const invalid = (message: string) => new FlowError('invalid-input', message);
191
+
192
+ async function saveDepartment(row: DepartmentInput) {
193
+ const loaded = await load();
194
+ if (row.parentId != null) {
195
+ if (!loaded.department.has(row.parentId)) throw invalid(`没有上级部门 ${row.parentId}`);
196
+ if (subtree(loaded, row.id).has(row.parentId))
197
+ throw invalid('上级部门不能是它自己或它下面的部门');
198
+ }
199
+ if (row.headId != null && !active(loaded, row.headId))
200
+ throw invalid(`负责人 ${row.headId} 不是在职的员工`);
201
+ await db
202
+ .insert(OrgDepartment)
203
+ .values(row)
204
+ .onConflict((d) => d.id)
205
+ .merge()
206
+ .execute();
207
+ await db.notify(ORG_CHANNEL);
208
+ await refresh();
209
+ }
210
+
211
+ async function removeDepartment(id: string) {
212
+ const loaded = await load();
213
+ if ((loaded.children.get(id) ?? []).length > 0) throw invalid('下面还有部门,先移走或删掉它们');
214
+ if (loaded.employees.some((e) => e.departmentId === id))
215
+ throw invalid('部门里还有员工(含离职的),先调到别的部门');
216
+ await db
217
+ .delete(OrgDepartment)
218
+ .where((d) => d.id.eq(id))
219
+ .execute();
220
+ await db.notify(ORG_CHANNEL);
221
+ await refresh();
222
+ }
223
+
224
+ async function saveEmployee(row: EmployeeInput) {
225
+ const loaded = await load();
226
+ if (!loaded.department.has(row.departmentId)) throw invalid(`没有部门 ${row.departmentId}`);
227
+ // 顺着上级往上走,走回他自己就是绕成了圈
228
+ for (let at = row.managerId ?? null, steps = 0; at !== null; steps++) {
229
+ if (at === row.id || steps > loaded.employees.length)
230
+ throw invalid('上级不能是他自己或他的下属');
231
+ at = loaded.employee.get(at)?.managerId ?? null;
232
+ }
233
+ if (row.managerId != null && !loaded.employee.has(row.managerId))
234
+ throw invalid(`没有员工 ${row.managerId}`);
235
+ await db
236
+ .insert(OrgEmployee)
237
+ .values(row)
238
+ .onConflict((e) => e.id)
239
+ .merge()
240
+ .execute();
241
+ await db.notify(ORG_CHANNEL);
242
+ await refresh();
243
+ }
244
+
245
+ async function saveRole(row: RoleRow) {
246
+ await db
247
+ .insert(OrgRole)
248
+ .values(row)
249
+ .onConflict((r) => r.id)
250
+ .merge()
251
+ .execute();
252
+ await db.notify(ORG_CHANNEL);
253
+ await refresh();
254
+ }
255
+
256
+ return {
257
+ db,
258
+ createTables: () => db.createTables(),
259
+ saveDepartment,
260
+ removeDepartment,
261
+ saveEmployee,
262
+ saveRole,
263
+ sync: async (data) => {
264
+ await db.transaction(async (tx) => {
265
+ for (const entity of [OrgEmployee, OrgRole, OrgDepartment])
266
+ await tx.delete(entity).all().execute();
267
+ if (data.departments.length)
268
+ await tx.insert(OrgDepartment).values(data.departments).execute();
269
+ if (data.roles.length) await tx.insert(OrgRole).values(data.roles).execute();
270
+ if (data.employees.length) await tx.insert(OrgEmployee).values(data.employees).execute();
271
+ await tx.notify(ORG_CHANNEL);
272
+ });
273
+ await refresh();
274
+ },
275
+ refresh,
276
+ snapshot: load,
277
+ org,
278
+ resolvers: { manager, departmentHead },
279
+ actorOf: async (id) => {
280
+ const loaded = await load();
281
+ const employee = active(loaded, id);
282
+ if (!employee) return undefined;
283
+ return {
284
+ id: employee.id,
285
+ name: employee.name,
286
+ roles: employee.roles,
287
+ departments: lineage(loaded, employee.departmentId).map((d) => d.id),
288
+ admin: options.isAdmin?.(employee) ?? false,
289
+ };
290
+ },
291
+ };
292
+ }
293
+
294
+ /** 读三张表、排好、建索引;读失败时下次再读 */
295
+ async function read(db: OrgDb): Promise<Loaded> {
296
+ const [departments, roles, employees] = await Promise.all([
297
+ db
298
+ .queryable(OrgDepartment)
299
+ .orderBy((d) => [d.sort, d.id])
300
+ .toList(),
301
+ db
302
+ .queryable(OrgRole)
303
+ .orderBy((r) => r.id)
304
+ .toList(),
305
+ db
306
+ .queryable(OrgEmployee)
307
+ .orderBy((e) => e.id)
308
+ .toList(),
309
+ ]);
310
+ const children = new Map<string | null, DepartmentRow[]>();
311
+ for (const department of departments) {
312
+ const siblings = children.get(department.parentId) ?? [];
313
+ siblings.push(department);
314
+ children.set(department.parentId, siblings);
315
+ }
316
+ const ordered: DepartmentRow[] = [];
317
+ const visit = (parent: string | null) => {
318
+ for (const child of children.get(parent) ?? []) {
319
+ ordered.push(child);
320
+ visit(child.id);
321
+ }
322
+ };
323
+ visit(null);
324
+ return {
325
+ departments: ordered,
326
+ roles,
327
+ employees,
328
+ department: new Map(departments.map((d) => [d.id, d])),
329
+ employee: new Map(employees.map((e) => [e.id, e])),
330
+ children,
331
+ };
332
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 组织的表:部门(树)、角色、员工(带上级)。引擎不依赖它们(org 与解析器是选项里的函数),这是现成的一种接法:
3
+ * 没有自己的组织库时直接用,有 HR 系统时按 `directory.sync()` 整批同步进来。
4
+ * 编号是文字(工号、部门编码),与引擎里人的编号(Actor.id)一一对应;同引擎的表一样只有逻辑外键
5
+ */
6
+ import { col, defineSchema, entity, type Db, type Row } from '@zerodep-dev/easy-query-ts';
7
+
8
+ const text = () => col.string().dbType('text');
9
+
10
+ /** 部门:parentId 为空的是根 */
11
+ export const OrgDepartment = entity(
12
+ 'org_department',
13
+ {
14
+ id: text().primaryKey(),
15
+ name: text(),
16
+ parentId: text().nullable(),
17
+ /** 部门负责人 */
18
+ headId: text().nullable(),
19
+ /** 同级里的先后 */
20
+ sort: col.int().dbDefault('0'),
21
+ },
22
+ { comment: '部门', indexes: [{ columns: ['parentId'] }] },
23
+ );
24
+
25
+ /** 角色(财务、法务……):定义里按编号写处理人 */
26
+ export const OrgRole = entity(
27
+ 'org_role',
28
+ {
29
+ id: text().primaryKey(),
30
+ name: text(),
31
+ },
32
+ { comment: '角色' },
33
+ );
34
+
35
+ /** 员工:一个所在部门、若干角色、一个直属上级;离职的不删,active 置否(历史待办里的名字还在) */
36
+ export const OrgEmployee = entity(
37
+ 'org_employee',
38
+ {
39
+ id: text().primaryKey(),
40
+ name: text(),
41
+ /** 职务(显示用) */
42
+ title: text().nullable(),
43
+ departmentId: text(),
44
+ /** 直属上级;最高的人没有 */
45
+ managerId: text().nullable(),
46
+ roles: col.array(text()).dbDefault("'{}'"),
47
+ active: col.boolean().dbDefault('true'),
48
+ },
49
+ {
50
+ comment: '员工',
51
+ indexes: [{ columns: ['departmentId'] }, { columns: ['roles'], using: 'gin' }],
52
+ },
53
+ );
54
+
55
+ export const orgSchema = defineSchema({ OrgDepartment, OrgRole, OrgEmployee });
56
+
57
+ /** 组织用的 Db */
58
+ export type OrgDb = Db<typeof orgSchema>;
59
+
60
+ export type DepartmentRow = Row<typeof OrgDepartment>;
61
+ export type RoleRow = Row<typeof OrgRole>;
62
+ export type EmployeeRow = Row<typeof OrgEmployee>;
@@ -0,0 +1,21 @@
1
+ /** 组织目录(`@zerodep-dev/flow-ts-engine/org`):组织的表,与接到引擎上的 org、处理人解析器、Actor */
2
+ export { ORG_CHANNEL } from '../core/channels.ts';
3
+ export {
4
+ createOrgDirectory,
5
+ type DepartmentInput,
6
+ type EmployeeInput,
7
+ type OrgData,
8
+ type OrgDirectory,
9
+ type OrgDirectoryOptions,
10
+ type OrgSnapshot,
11
+ } from './directory.ts';
12
+ export {
13
+ OrgDepartment,
14
+ OrgEmployee,
15
+ OrgRole,
16
+ orgSchema,
17
+ type DepartmentRow,
18
+ type EmployeeRow,
19
+ type OrgDb,
20
+ type RoleRow,
21
+ } from './entities.ts';