@aventoapp/framework 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 (160) hide show
  1. package/dist/index.js +6 -0
  2. package/dist/index.js.map +7 -0
  3. package/dist/native/index.js +2522 -0
  4. package/dist/native/index.js.map +7 -0
  5. package/dist/server/index.js +2776 -0
  6. package/dist/server/index.js.map +7 -0
  7. package/dist/server/workflow/index.js +537 -0
  8. package/dist/server/workflow/index.js.map +7 -0
  9. package/dist/shared/index.js +62 -0
  10. package/dist/shared/index.js.map +7 -0
  11. package/dist/web/index.js +7323 -0
  12. package/dist/web/index.js.map +7 -0
  13. package/package.json +81 -0
  14. package/schemas/Workflow.json +14 -0
  15. package/schemas/WorkflowHistory.json +22 -0
  16. package/schemas/WorkflowInstance.json +16 -0
  17. package/schemas/WorkflowState.json +18 -0
  18. package/schemas/WorkflowTransition.json +27 -0
  19. package/src/index.js +8 -0
  20. package/src/native/components/NativeAuthProvider.jsx +249 -0
  21. package/src/native/components/NativeDetail.jsx +270 -0
  22. package/src/native/components/NativeForm.jsx +543 -0
  23. package/src/native/components/NativeGrid.jsx +90 -0
  24. package/src/native/components/NativeJsonGrid.jsx +213 -0
  25. package/src/native/components/NativeJsonView.jsx +454 -0
  26. package/src/native/components/NativeJsonViewContext.js +17 -0
  27. package/src/native/components/NativeShell.jsx +68 -0
  28. package/src/native/components/NativeViewComponent.jsx +351 -0
  29. package/src/native/extensions/NativeExtensionRegistry.js +81 -0
  30. package/src/native/hooks/useNativeStore.js +72 -0
  31. package/src/native/index.js +15 -0
  32. package/src/native/layouts/NativeStackLayout.jsx +30 -0
  33. package/src/native/layouts/NativeTabLayout.jsx +96 -0
  34. package/src/native/storage.js +13 -0
  35. package/src/native/stores/NativeBaseStore.js +348 -0
  36. package/src/native/stores/NativeStoreContext.jsx +53 -0
  37. package/src/server/ai/capabilities-routes.js +106 -0
  38. package/src/server/ai/index.js +1 -0
  39. package/src/server/cache/MemoryCache.js +153 -0
  40. package/src/server/cache/index.js +2 -0
  41. package/src/server/cache/middleware.js +12 -0
  42. package/src/server/db/index.js +14 -0
  43. package/src/server/db/mongo.js +137 -0
  44. package/src/server/db/postgres.js +144 -0
  45. package/src/server/index.js +38 -0
  46. package/src/server/middleware/auth.js +682 -0
  47. package/src/server/middleware/can-flags.js +132 -0
  48. package/src/server/middleware/entityRoles.js +105 -0
  49. package/src/server/middleware/index.js +58 -0
  50. package/src/server/middleware/permissions.js +240 -0
  51. package/src/server/middleware/tenant.js +203 -0
  52. package/src/server/realtime/EventBus.js +45 -0
  53. package/src/server/realtime/WebSocketServer.js +105 -0
  54. package/src/server/realtime/index.js +3 -0
  55. package/src/server/realtime/middleware.js +18 -0
  56. package/src/server/services/email-templates.js +157 -0
  57. package/src/server/services/email.js +78 -0
  58. package/src/server/services/index.js +15 -0
  59. package/src/server/services/storage.js +119 -0
  60. package/src/server/utils/index.js +16 -0
  61. package/src/server/utils/paginate.js +65 -0
  62. package/src/server/utils/query-builder.js +293 -0
  63. package/src/server/utils/route-loader.js +61 -0
  64. package/src/server/workflow/WorkflowEngine.js +494 -0
  65. package/src/server/workflow/index.js +2 -0
  66. package/src/server/workflow/workflow-routes.js +174 -0
  67. package/src/shared/index.js +10 -0
  68. package/src/shared/utils/field-accessor.js +108 -0
  69. package/src/shared/utils/index.js +7 -0
  70. package/src/shared/utils/validation-utils.js +83 -0
  71. package/src/web/components/AppRouter/AppRouter.jsx +130 -0
  72. package/src/web/components/AppRouter/index.js +1 -0
  73. package/src/web/components/AppShell/AppShell.jsx +101 -0
  74. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -0
  75. package/src/web/components/AppShell/ShellConfig.js +53 -0
  76. package/src/web/components/AppShell/index.js +3 -0
  77. package/src/web/components/AuthProvider.jsx +426 -0
  78. package/src/web/components/CardList/CardList.jsx +272 -0
  79. package/src/web/components/CardList/index.js +2 -0
  80. package/src/web/components/DetailView/DetailView.jsx +281 -0
  81. package/src/web/components/DetailView/index.js +2 -0
  82. package/src/web/components/Form/Form.jsx +300 -0
  83. package/src/web/components/Form/FormField.jsx +226 -0
  84. package/src/web/components/Form/index.js +3 -0
  85. package/src/web/components/Grid/Grid.jsx +304 -0
  86. package/src/web/components/Grid/index.js +2 -0
  87. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -0
  88. package/src/web/components/IconRegistry/index.js +1 -0
  89. package/src/web/components/JsonView/JsonView.jsx +647 -0
  90. package/src/web/components/JsonView/ViewComponent.jsx +1045 -0
  91. package/src/web/components/JsonView/ViewToolbar.jsx +141 -0
  92. package/src/web/components/JsonView/index.js +14 -0
  93. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -0
  94. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -0
  95. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -0
  96. package/src/web/components/JsonView/layouts/index.js +8 -0
  97. package/src/web/components/Layout.jsx +265 -0
  98. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -0
  99. package/src/web/components/MobileLayout/index.js +1 -0
  100. package/src/web/components/Navigation/Navigation.jsx +248 -0
  101. package/src/web/components/Navigation/index.js +1 -0
  102. package/src/web/components/NotificationProvider.jsx +55 -0
  103. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -0
  104. package/src/web/components/Pagination/Pagination.jsx +73 -0
  105. package/src/web/components/Pagination/index.js +8 -0
  106. package/src/web/components/SimpleList/SimpleList.jsx +177 -0
  107. package/src/web/components/SimpleList/index.js +2 -0
  108. package/src/web/components/TenantProvider.jsx +121 -0
  109. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -0
  110. package/src/web/components/WorkflowActions/index.js +1 -0
  111. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -0
  112. package/src/web/components/WorkflowField/index.js +2 -0
  113. package/src/web/components/WorkflowField/workflowColors.js +32 -0
  114. package/src/web/components/auth/DevTenantSelector.jsx +90 -0
  115. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -0
  116. package/src/web/components/auth/RegisterForm.jsx +168 -0
  117. package/src/web/components/auth/ResetPasswordForm.jsx +121 -0
  118. package/src/web/components/auth/VerifyEmailView.jsx +85 -0
  119. package/src/web/components/auth/index.js +5 -0
  120. package/src/web/components/index.js +39 -0
  121. package/src/web/components/layouts/CardListLayout.jsx +68 -0
  122. package/src/web/components/layouts/FullscreenLayout.jsx +30 -0
  123. package/src/web/components/layouts/MobileStackLayout.jsx +28 -0
  124. package/src/web/components/layouts/WizardLayout.jsx +86 -0
  125. package/src/web/components/layouts/index.js +4 -0
  126. package/src/web/components/mobile/Badge.jsx +105 -0
  127. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -0
  128. package/src/web/components/mobile/EmptyState.jsx +30 -0
  129. package/src/web/components/mobile/QuickActionButton.jsx +77 -0
  130. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -0
  131. package/src/web/components/mobile/StarRating.jsx +42 -0
  132. package/src/web/components/mobile/StatCard.jsx +65 -0
  133. package/src/web/components/mobile/index.js +7 -0
  134. package/src/web/extensions/ExtensionRegistry.js +79 -0
  135. package/src/web/extensions/index.js +7 -0
  136. package/src/web/hooks/index.js +15 -0
  137. package/src/web/hooks/useApi.js +76 -0
  138. package/src/web/hooks/useAuth.js +37 -0
  139. package/src/web/hooks/useDebouncedSave.js +158 -0
  140. package/src/web/hooks/useIsMobile.js +14 -0
  141. package/src/web/hooks/useOfflineQueue.js +99 -0
  142. package/src/web/hooks/useSelectionModel.js +143 -0
  143. package/src/web/hooks/useServerAutocomplete.js +146 -0
  144. package/src/web/hooks/useStore.js +107 -0
  145. package/src/web/hooks/useSubscription.js +130 -0
  146. package/src/web/hooks/useTenant.js +39 -0
  147. package/src/web/hooks/useTenantResolver.js +65 -0
  148. package/src/web/hooks/useUndoRedo.js +77 -0
  149. package/src/web/hooks/useViews.js +113 -0
  150. package/src/web/hooks/useWorkflow.js +190 -0
  151. package/src/web/index.js +117 -0
  152. package/src/web/stores/BaseStore.js +439 -0
  153. package/src/web/stores/StoreContext.jsx +93 -0
  154. package/src/web/stores/index.js +3 -0
  155. package/src/web/theme/index.js +3 -0
  156. package/src/web/theme/mui-theme.js +228 -0
  157. package/src/web/utils/formatTimeAgo.js +22 -0
  158. package/src/web/utils/index.js +1 -0
  159. package/src/web/views/ViewRegistry.js +235 -0
  160. package/src/web/views/index.js +2 -0
@@ -0,0 +1,494 @@
1
+ /**
2
+ * WorkflowEngine
3
+ *
4
+ * Stateless workflow engine that manages workflow instances and transitions.
5
+ * Instantiate per-request with a database connection.
6
+ *
7
+ * Works with the framework-level workflow tables:
8
+ * - workflows: Workflow definitions
9
+ * - workflow_states: States within each workflow (with isInitial/isFinal flags)
10
+ * - workflow_transitions: Transitions between states (with roles/conditions)
11
+ * - workflow_instances: Active instances linking entities to workflows
12
+ * - workflow_histories: Audit trail of state changes
13
+ */
14
+ export class WorkflowEngine {
15
+ constructor(db) {
16
+ this.db = db;
17
+ }
18
+
19
+ /**
20
+ * Create a new workflow instance for an entity
21
+ * @param {string} tenantId - Tenant UUID
22
+ * @param {string} workflowId - Workflow UUID (or name to look up)
23
+ * @param {string} entityType - Entity type (e.g., 'Deal')
24
+ * @param {string} entityId - Entity UUID
25
+ * @returns {Object} Created workflow instance
26
+ */
27
+ async createInstance(tenantId, workflowId, entityType, entityId) {
28
+ // Check if workflowId is a name (not a UUID)
29
+ let workflow;
30
+ const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(workflowId);
31
+
32
+ if (isUuid) {
33
+ const result = await this.db.query(
34
+ `SELECT w.id, ws.id as initial_state_id, ws.name as initial_state
35
+ FROM workflows w
36
+ JOIN workflow_states ws ON ws.workflow_id = w.id AND ws.is_initial = true
37
+ WHERE w.id = $1 AND w.tenant_id = $2 AND w.is_active = true`,
38
+ [workflowId, tenantId]
39
+ );
40
+ workflow = result.rows[0];
41
+ } else {
42
+ // Look up by name
43
+ const result = await this.db.query(
44
+ `SELECT w.id, ws.id as initial_state_id, ws.name as initial_state
45
+ FROM workflows w
46
+ JOIN workflow_states ws ON ws.workflow_id = w.id AND ws.is_initial = true
47
+ WHERE w.name = $1 AND w.tenant_id = $2 AND w.is_active = true`,
48
+ [workflowId, tenantId]
49
+ );
50
+ workflow = result.rows[0];
51
+ }
52
+
53
+ if (!workflow) {
54
+ throw new Error(`Workflow '${workflowId}' not found or has no initial state`);
55
+ }
56
+
57
+ // Check if instance already exists for this entity
58
+ const existingResult = await this.db.query(
59
+ `SELECT id FROM workflow_instances
60
+ WHERE entity_type = $1 AND entity_id = $2 AND tenant_id = $3`,
61
+ [entityType, entityId, tenantId]
62
+ );
63
+
64
+ if (existingResult.rows[0]) {
65
+ throw new Error('Workflow instance already exists for this entity');
66
+ }
67
+
68
+ // Create instance
69
+ const instanceResult = await this.db.query(
70
+ `INSERT INTO workflow_instances
71
+ (tenant_id, workflow_id, current_state_id, entity_type, entity_id, started_at)
72
+ VALUES ($1, $2, $3, $4, $5, NOW())
73
+ RETURNING *`,
74
+ [tenantId, workflow.id, workflow.initial_state_id, entityType, entityId]
75
+ );
76
+
77
+ const instance = instanceResult.rows[0];
78
+
79
+ // Log initial state to history
80
+ await this.db.query(
81
+ `INSERT INTO workflow_histories
82
+ (tenant_id, instance_id, to_state_id, transitioned_at, notes)
83
+ VALUES ($1, $2, $3, NOW(), $4)`,
84
+ [tenantId, instance.id, workflow.initial_state_id, 'Workflow initialized']
85
+ );
86
+
87
+ return {
88
+ ...instance,
89
+ current_state: workflow.initial_state
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Get available transitions for a workflow instance based on user roles/permissions.
95
+ * @param {string} tenantId - Tenant UUID
96
+ * @param {string} instanceId - Workflow instance UUID
97
+ * @param {string[]|{roles:string[],permissions:string[]}} userContext
98
+ * Array of role names (backward compat) OR { roles, permissions } object
99
+ * @param {Object} [entityData] - Optional entity data for condition evaluation
100
+ * @returns {Object[]} Available transitions
101
+ */
102
+ async getAvailableTransitions(tenantId, instanceId, userContext, entityData = null) {
103
+ // Normalize: accept legacy array of roles or new { roles, permissions } object
104
+ const userRoles = Array.isArray(userContext) ? userContext : (userContext?.roles || []);
105
+ const userPermissions = Array.isArray(userContext) ? [] : (userContext?.permissions || []);
106
+ // Get current state and workflow
107
+ const instanceResult = await this.db.query(
108
+ `SELECT wi.current_state_id, wi.workflow_id, wi.entity_type, wi.entity_id
109
+ FROM workflow_instances wi
110
+ WHERE wi.id = $1 AND wi.tenant_id = $2`,
111
+ [instanceId, tenantId]
112
+ );
113
+
114
+ if (!instanceResult.rows[0]) {
115
+ throw new Error('Workflow instance not found');
116
+ }
117
+
118
+ const { current_state_id, workflow_id } = instanceResult.rows[0];
119
+
120
+ // Get transitions from current state
121
+ const transitionsResult = await this.db.query(
122
+ `SELECT wt.id, wt.name, wt.description, wt.roles, wt.condition, wt.requires, wt.order,
123
+ ts.id as to_state_id,
124
+ ts.name as target_state,
125
+ ts.label as target_state_label,
126
+ ts.color as target_state_color
127
+ FROM workflow_transitions wt
128
+ JOIN workflow_states ts ON wt.to_state_id = ts.id
129
+ WHERE wt.from_state_id = $1 AND wt.workflow_id = $2 AND wt.tenant_id = $3
130
+ ORDER BY wt.order ASC, wt.name ASC`,
131
+ [current_state_id, workflow_id, tenantId]
132
+ );
133
+
134
+ // Filter by roles or permissions (empty both = open to all)
135
+ const roleFilteredTransitions = transitionsResult.rows.filter(transition => {
136
+ const allowedRoles = transition.roles || [];
137
+ const allowedPerms = transition.permissions || []; // populated once DB column is added
138
+
139
+ if (allowedRoles.length === 0 && allowedPerms.length === 0) return true;
140
+
141
+ // New: check permission strings
142
+ if (allowedPerms.length > 0 && userPermissions.some(p => allowedPerms.includes(p))) return true;
143
+ // Backward compat: check role names
144
+ if (allowedRoles.length > 0 && userRoles.some(r => allowedRoles.includes(r))) return true;
145
+
146
+ return false;
147
+ });
148
+
149
+ // Filter by conditions (if entity data provided)
150
+ const conditionFilteredTransitions = roleFilteredTransitions.filter(transition => {
151
+ return this.evaluateCondition(transition.condition, entityData);
152
+ });
153
+
154
+ return conditionFilteredTransitions.map(t => ({
155
+ ruleId: t.id,
156
+ id: t.id,
157
+ name: t.name || t.target_state_label,
158
+ action: t.name || t.target_state_label,
159
+ description: t.description,
160
+ targetState: t.target_state,
161
+ targetStateLabel: t.target_state_label,
162
+ targetStateColor: t.target_state_color,
163
+ condition: t.condition, // Pass to client for UI evaluation hints
164
+ requires: t.requires || [] // Fields that must be non-empty for this transition
165
+ }));
166
+ }
167
+
168
+ /**
169
+ * Execute a workflow transition
170
+ * @param {string} tenantId - Tenant UUID
171
+ * @param {string} instanceId - Workflow instance UUID
172
+ * @param {string} ruleId - Transition rule UUID to execute
173
+ * @param {string} userId - User UUID performing the transition
174
+ * @param {string} [comment] - Optional comment
175
+ * @param {Object} [entitySnapshot] - Optional entity data snapshot
176
+ * @returns {Object} Transition result
177
+ */
178
+ async executeTransition(tenantId, instanceId, ruleId, userId, comment, entitySnapshot = null) {
179
+ // Get instance
180
+ const instanceResult = await this.db.query(
181
+ `SELECT wi.id, wi.current_state_id, wi.workflow_id
182
+ FROM workflow_instances wi
183
+ WHERE wi.id = $1 AND wi.tenant_id = $2`,
184
+ [instanceId, tenantId]
185
+ );
186
+
187
+ if (!instanceResult.rows[0]) {
188
+ throw new Error('Workflow instance not found');
189
+ }
190
+
191
+ const instance = instanceResult.rows[0];
192
+
193
+ // Get and validate transition (fetch requires + condition for guard checks)
194
+ const transitionResult = await this.db.query(
195
+ `SELECT wt.id, wt.from_state_id, wt.to_state_id, wt.name,
196
+ wt.requires, wt.condition,
197
+ fs.name as from_state,
198
+ ts.name as to_state,
199
+ ts.label as to_state_label,
200
+ ts.color as to_state_color,
201
+ ts.is_final,
202
+ wi.entity_type, wi.entity_id
203
+ FROM workflow_transitions wt
204
+ JOIN workflow_states fs ON wt.from_state_id = fs.id
205
+ JOIN workflow_states ts ON wt.to_state_id = ts.id
206
+ JOIN workflow_instances wi ON wi.id = $2
207
+ WHERE wt.id = $1 AND wt.workflow_id = $3 AND wt.tenant_id = $4`,
208
+ [ruleId, instanceId, instance.workflow_id, tenantId]
209
+ );
210
+
211
+ if (!transitionResult.rows[0]) {
212
+ throw new Error('Workflow transition not found');
213
+ }
214
+
215
+ const transition = transitionResult.rows[0];
216
+
217
+ // Validate transition is from current state
218
+ if (transition.from_state_id !== instance.current_state_id) {
219
+ throw new Error(
220
+ `Transition state '${transition.from_state}' does not match current state`
221
+ );
222
+ }
223
+
224
+ // Guard: requires[] — presence checks on entity fields
225
+ if (transition.requires && entitySnapshot) {
226
+ const requires = Array.isArray(transition.requires)
227
+ ? transition.requires
228
+ : JSON.parse(transition.requires);
229
+ const missing = requires.filter(f => {
230
+ const v = entitySnapshot[f];
231
+ return v === null || v === undefined || v === '';
232
+ });
233
+ if (missing.length > 0) {
234
+ throw new Error(`Transition blocked: required fields missing: ${missing.join(', ')}`);
235
+ }
236
+ }
237
+
238
+ // Guard: condition expression
239
+ if (transition.condition && entitySnapshot) {
240
+ if (!this.evaluateCondition(transition.condition, entitySnapshot)) {
241
+ throw new Error('Transition blocked: condition not met');
242
+ }
243
+ }
244
+
245
+ const previousStateId = instance.current_state_id;
246
+
247
+ // Begin transaction
248
+ await this.db.query('BEGIN');
249
+
250
+ try {
251
+ // Update workflow instance state
252
+ await this.db.query(
253
+ `UPDATE workflow_instances
254
+ SET current_state_id = $1,
255
+ completed_at = $2,
256
+ updated_at = NOW()
257
+ WHERE id = $3 AND tenant_id = $4`,
258
+ [
259
+ transition.to_state_id,
260
+ transition.is_final ? new Date() : null,
261
+ instanceId,
262
+ tenantId
263
+ ]
264
+ );
265
+
266
+ // Denormalize workflow_state onto entity table for zero-join reads
267
+ const entityTable = this.toEntityTableName(transition.entity_type || instance.entity_type);
268
+ await this.db.query(
269
+ `UPDATE ${entityTable} SET workflow_state = $1 WHERE id = $2 AND tenant_id = $3`,
270
+ [transition.to_state, transition.entity_id || instance.entity_id, tenantId]
271
+ ).catch(() => {
272
+ // Column may not exist on older tables — fail silently
273
+ });
274
+
275
+ // Log to history
276
+ await this.db.query(
277
+ `INSERT INTO workflow_histories
278
+ (tenant_id, instance_id, from_state_id, to_state_id, transition_id,
279
+ transitioned_at, transitioned_by, notes, entity_snapshot)
280
+ VALUES ($1, $2, $3, $4, $5, NOW(), $6, $7, $8)`,
281
+ [
282
+ tenantId,
283
+ instanceId,
284
+ previousStateId,
285
+ transition.to_state_id,
286
+ ruleId,
287
+ userId,
288
+ comment || null,
289
+ entitySnapshot ? JSON.stringify(entitySnapshot) : null
290
+ ]
291
+ );
292
+
293
+ await this.db.query('COMMIT');
294
+
295
+ return {
296
+ success: true,
297
+ previousState: transition.from_state,
298
+ newState: transition.to_state,
299
+ newStateLabel: transition.to_state_label,
300
+ newStateColor: transition.to_state_color,
301
+ action: transition.name,
302
+ isFinal: transition.is_final
303
+ };
304
+ } catch (err) {
305
+ await this.db.query('ROLLBACK');
306
+ throw err;
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Derive entity table name from entity type using the same convention as codegen.
312
+ * e.g. 'Deal' → 'deals', 'ContactNote' → 'contact_notes'
313
+ */
314
+ toEntityTableName(entityType) {
315
+ const snake = entityType
316
+ .replace(/([A-Z])/g, '_$1')
317
+ .toLowerCase()
318
+ .replace(/^_/, '');
319
+ // Simple pluralization matching schema-parser.js pluralize()
320
+ if (/([sxz]|[sc]h)$/.test(snake)) return snake + 'es';
321
+ if (/[^aeiou]y$/.test(snake)) return snake.slice(0, -1) + 'ies';
322
+ return snake + 's';
323
+ }
324
+
325
+ /**
326
+ * Get a workflow instance with state info
327
+ * @param {string} tenantId - Tenant UUID
328
+ * @param {string} instanceId - Workflow instance UUID
329
+ * @returns {Object} Instance with workflow and state details
330
+ */
331
+ async getInstance(tenantId, instanceId) {
332
+ const result = await this.db.query(
333
+ `SELECT wi.*,
334
+ w.name as workflow_name,
335
+ w.entity_type as workflow_entity_type,
336
+ ws.name as current_state,
337
+ ws.label as current_state_label,
338
+ ws.color as current_state_color,
339
+ ws.is_final as is_current_state_final
340
+ FROM workflow_instances wi
341
+ JOIN workflows w ON wi.workflow_id = w.id
342
+ JOIN workflow_states ws ON wi.current_state_id = ws.id
343
+ WHERE wi.id = $1 AND wi.tenant_id = $2`,
344
+ [instanceId, tenantId]
345
+ );
346
+
347
+ if (!result.rows[0]) {
348
+ throw new Error('Workflow instance not found');
349
+ }
350
+
351
+ return result.rows[0];
352
+ }
353
+
354
+ /**
355
+ * Get workflow instance by entity
356
+ * @param {string} tenantId - Tenant UUID
357
+ * @param {string} entityType - Entity type
358
+ * @param {string} entityId - Entity UUID
359
+ * @returns {Object|null} Instance or null if not found
360
+ */
361
+ async getInstanceByEntity(tenantId, entityType, entityId) {
362
+ const result = await this.db.query(
363
+ `SELECT wi.*,
364
+ w.name as workflow_name,
365
+ ws.name as current_state,
366
+ ws.label as current_state_label,
367
+ ws.color as current_state_color,
368
+ ws.is_final as is_current_state_final
369
+ FROM workflow_instances wi
370
+ JOIN workflows w ON wi.workflow_id = w.id
371
+ JOIN workflow_states ws ON wi.current_state_id = ws.id
372
+ WHERE wi.entity_type = $1 AND wi.entity_id = $2 AND wi.tenant_id = $3`,
373
+ [entityType, entityId, tenantId]
374
+ );
375
+
376
+ return result.rows[0] || null;
377
+ }
378
+
379
+ /**
380
+ * Get transition history for a workflow instance
381
+ * @param {string} tenantId - Tenant UUID
382
+ * @param {string} instanceId - Workflow instance UUID
383
+ * @returns {Object[]} History entries
384
+ */
385
+ async getHistory(tenantId, instanceId) {
386
+ const result = await this.db.query(
387
+ `SELECT wh.*,
388
+ fs.name as from_state,
389
+ fs.label as from_state_label,
390
+ fs.color as from_state_color,
391
+ ts.name as to_state,
392
+ ts.label as to_state_label,
393
+ ts.color as to_state_color,
394
+ wt.name as transition_name,
395
+ u.name as performed_by_name,
396
+ u.email as performed_by_email
397
+ FROM workflow_histories wh
398
+ LEFT JOIN workflow_states fs ON wh.from_state_id = fs.id
399
+ JOIN workflow_states ts ON wh.to_state_id = ts.id
400
+ LEFT JOIN workflow_transitions wt ON wh.transition_id = wt.id
401
+ LEFT JOIN users u ON wh.transitioned_by::uuid = u.id
402
+ WHERE wh.instance_id = $1 AND wh.tenant_id = $2
403
+ ORDER BY wh.transitioned_at DESC`,
404
+ [instanceId, tenantId]
405
+ );
406
+
407
+ return result.rows.map(h => ({
408
+ id: h.id,
409
+ fromState: h.from_state,
410
+ fromStateLabel: h.from_state_label,
411
+ fromStateColor: h.from_state_color,
412
+ toState: h.to_state,
413
+ toStateLabel: h.to_state_label,
414
+ toStateColor: h.to_state_color,
415
+ transitionName: h.transition_name,
416
+ transitionedAt: h.transitioned_at,
417
+ transitionedBy: h.performed_by_name || h.performed_by_email || h.transitioned_by,
418
+ notes: h.notes,
419
+ entitySnapshot: h.entity_snapshot
420
+ }));
421
+ }
422
+
423
+ /**
424
+ * Get all states for a workflow
425
+ * @param {string} tenantId - Tenant UUID
426
+ * @param {string} workflowId - Workflow UUID
427
+ * @returns {Object[]} Workflow states
428
+ */
429
+ async getWorkflowStates(tenantId, workflowId) {
430
+ const result = await this.db.query(
431
+ `SELECT id, name, label, description, color, is_initial, is_final, "order"
432
+ FROM workflow_states
433
+ WHERE workflow_id = $1 AND tenant_id = $2
434
+ ORDER BY "order" ASC, name ASC`,
435
+ [workflowId, tenantId]
436
+ );
437
+
438
+ return result.rows;
439
+ }
440
+
441
+ /**
442
+ * Get all transitions for a workflow
443
+ * @param {string} tenantId - Tenant UUID
444
+ * @param {string} workflowId - Workflow UUID
445
+ * @returns {Object[]} Workflow transitions
446
+ */
447
+ async getWorkflowTransitions(tenantId, workflowId) {
448
+ const result = await this.db.query(
449
+ `SELECT wt.*,
450
+ fs.name as from_state_name,
451
+ fs.label as from_state_label,
452
+ ts.name as to_state_name,
453
+ ts.label as to_state_label
454
+ FROM workflow_transitions wt
455
+ JOIN workflow_states fs ON wt.from_state_id = fs.id
456
+ JOIN workflow_states ts ON wt.to_state_id = ts.id
457
+ WHERE wt.workflow_id = $1 AND wt.tenant_id = $2
458
+ ORDER BY fs.order, wt.order, wt.name`,
459
+ [workflowId, tenantId]
460
+ );
461
+
462
+ return result.rows;
463
+ }
464
+
465
+ /**
466
+ * Evaluate a rule condition
467
+ * @param {string|null} condition - JavaScript expression or null
468
+ * @param {Object|null} entityData - Entity data for evaluation
469
+ * @returns {boolean} Whether condition passes
470
+ */
471
+ evaluateCondition(condition, entityData) {
472
+ // No condition = always passes
473
+ if (!condition) {
474
+ return true;
475
+ }
476
+
477
+ // No entity data = can't evaluate, assume passes
478
+ // (client will re-evaluate with full data)
479
+ if (!entityData) {
480
+ return true;
481
+ }
482
+
483
+ try {
484
+ // Create a safe evaluation context
485
+ const fn = new Function('entity', `return ${condition}`);
486
+ return !!fn(entityData);
487
+ } catch (err) {
488
+ console.error('[WorkflowEngine] Condition evaluation error:', err);
489
+ return false;
490
+ }
491
+ }
492
+ }
493
+
494
+ export default WorkflowEngine;
@@ -0,0 +1,2 @@
1
+ export { WorkflowEngine } from './WorkflowEngine.js';
2
+ export { createWorkflowRoutes } from './workflow-routes.js';
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Workflow API Routes
3
+ *
4
+ * Express router for workflow operations.
5
+ * Mount at /api/workflow with auth and tenant middleware.
6
+ */
7
+ import express from 'express';
8
+ import { WorkflowEngine } from './WorkflowEngine.js';
9
+
10
+ export function createWorkflowRoutes() {
11
+ const router = express.Router();
12
+
13
+ /**
14
+ * POST /initialize
15
+ * Initialize a workflow instance for an entity
16
+ * Body: { workflowId, entityType, entityId }
17
+ */
18
+ router.post('/initialize', async (req, res) => {
19
+ try {
20
+ const { workflowId, entityType, entityId } = req.body;
21
+
22
+ if (!workflowId || !entityType || !entityId) {
23
+ return res.status(400).json({
24
+ error: 'workflowId, entityType, and entityId are required'
25
+ });
26
+ }
27
+
28
+ const engine = new WorkflowEngine(req.db);
29
+ const instance = await engine.createInstance(
30
+ req.tenant.id,
31
+ workflowId,
32
+ entityType,
33
+ entityId
34
+ );
35
+
36
+ res.status(201).json({
37
+ instanceId: instance.id,
38
+ workflowId: instance.workflow_id,
39
+ currentState: instance.current_state,
40
+ entityType,
41
+ entityId
42
+ });
43
+ } catch (err) {
44
+ if (err.message.includes('already exists')) {
45
+ return res.status(409).json({ error: err.message });
46
+ }
47
+ if (err.message.includes('not found')) {
48
+ return res.status(404).json({ error: err.message });
49
+ }
50
+ console.error('[Workflow] Initialize error:', err);
51
+ res.status(500).json({ error: 'Failed to initialize workflow' });
52
+ }
53
+ });
54
+
55
+ /**
56
+ * GET /by-entity/:entityType/:entityId
57
+ * Get workflow instance by entity reference
58
+ */
59
+ router.get('/by-entity/:entityType/:entityId', async (req, res) => {
60
+ try {
61
+ const { entityType, entityId } = req.params;
62
+ const engine = new WorkflowEngine(req.db);
63
+ const instance = await engine.getInstanceByEntity(
64
+ req.tenant.id,
65
+ entityType,
66
+ entityId
67
+ );
68
+
69
+ if (!instance) {
70
+ return res.status(404).json({ error: 'Workflow instance not found' });
71
+ }
72
+
73
+ res.json(instance);
74
+ } catch (err) {
75
+ console.error('[Workflow] Get by entity error:', err);
76
+ res.status(500).json({ error: 'Failed to get workflow instance' });
77
+ }
78
+ });
79
+
80
+ /**
81
+ * GET /:instanceId
82
+ * Get workflow instance state and definition info
83
+ */
84
+ router.get('/:instanceId', async (req, res) => {
85
+ try {
86
+ const engine = new WorkflowEngine(req.db);
87
+ const instance = await engine.getInstance(req.tenant.id, req.params.instanceId);
88
+ res.json(instance);
89
+ } catch (err) {
90
+ if (err.message === 'Workflow instance not found') {
91
+ return res.status(404).json({ error: err.message });
92
+ }
93
+ console.error('[Workflow] Get instance error:', err);
94
+ res.status(500).json({ error: 'Failed to get workflow instance' });
95
+ }
96
+ });
97
+
98
+ /**
99
+ * GET /:instanceId/transitions
100
+ * Get available transitions for the authenticated user
101
+ */
102
+ router.get('/:instanceId/transitions', async (req, res) => {
103
+ try {
104
+ const engine = new WorkflowEngine(req.db);
105
+ const userContext = {
106
+ roles: req.user?.roles || [],
107
+ permissions: req.user?.permissions || []
108
+ };
109
+ const transitions = await engine.getAvailableTransitions(
110
+ req.tenant.id,
111
+ req.params.instanceId,
112
+ userContext
113
+ );
114
+ res.json({ transitions });
115
+ } catch (err) {
116
+ if (err.message === 'Workflow instance not found') {
117
+ return res.status(404).json({ error: err.message });
118
+ }
119
+ console.error('[Workflow] Get transitions error:', err);
120
+ res.status(500).json({ error: 'Failed to get transitions' });
121
+ }
122
+ });
123
+
124
+ /**
125
+ * POST /:instanceId/transition
126
+ * Execute a workflow transition
127
+ * Body: { ruleId, comment? }
128
+ */
129
+ router.post('/:instanceId/transition', async (req, res) => {
130
+ try {
131
+ const { ruleId, comment } = req.body;
132
+
133
+ if (!ruleId) {
134
+ return res.status(400).json({ error: 'ruleId is required' });
135
+ }
136
+
137
+ const engine = new WorkflowEngine(req.db);
138
+ const result = await engine.executeTransition(
139
+ req.tenant.id,
140
+ req.params.instanceId,
141
+ ruleId,
142
+ req.user?.id,
143
+ comment
144
+ );
145
+
146
+ res.json(result);
147
+ } catch (err) {
148
+ if (err.message.includes('not found') || err.message.includes('does not match')) {
149
+ return res.status(400).json({ error: err.message });
150
+ }
151
+ console.error('[Workflow] Execute transition error:', err);
152
+ res.status(500).json({ error: 'Failed to execute transition' });
153
+ }
154
+ });
155
+
156
+ /**
157
+ * GET /:instanceId/history
158
+ * Get transition history for a workflow instance
159
+ */
160
+ router.get('/:instanceId/history', async (req, res) => {
161
+ try {
162
+ const engine = new WorkflowEngine(req.db);
163
+ const history = await engine.getHistory(req.tenant.id, req.params.instanceId);
164
+ res.json({ history });
165
+ } catch (err) {
166
+ console.error('[Workflow] Get history error:', err);
167
+ res.status(500).json({ error: 'Failed to get workflow history' });
168
+ }
169
+ });
170
+
171
+ return router;
172
+ }
173
+
174
+ export default createWorkflowRoutes;
@@ -0,0 +1,10 @@
1
+ // @avento/framework/shared
2
+ // Shared utilities used by both server and client
3
+
4
+ // Field accessor utilities for dot-notation and joined data
5
+ export {
6
+ getFieldValue,
7
+ setFieldValue,
8
+ isRelationField,
9
+ parseRelationPath
10
+ } from './utils/field-accessor.js';