@aventoapp/framework 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +260 -0
  2. package/dist/index.js.map +1 -1
  3. package/dist/native/index.js.map +1 -1
  4. package/dist/offline/index.js +399 -0
  5. package/dist/offline/index.js.map +7 -0
  6. package/dist/server/index.js +75 -0
  7. package/dist/server/index.js.map +3 -3
  8. package/dist/server/workflow/index.js.map +1 -1
  9. package/dist/shared/index.js.map +1 -1
  10. package/dist/web/index.js.map +1 -1
  11. package/package.json +10 -7
  12. package/schemas/Workflow.json +14 -14
  13. package/schemas/WorkflowHistory.json +22 -22
  14. package/schemas/WorkflowInstance.json +16 -16
  15. package/schemas/WorkflowState.json +18 -18
  16. package/schemas/WorkflowTransition.json +27 -27
  17. package/src/index.js +8 -8
  18. package/src/native/components/NativeAuthProvider.jsx +249 -249
  19. package/src/native/components/NativeDetail.jsx +270 -270
  20. package/src/native/components/NativeForm.jsx +543 -543
  21. package/src/native/components/NativeGrid.jsx +90 -90
  22. package/src/native/components/NativeJsonGrid.jsx +213 -213
  23. package/src/native/components/NativeJsonView.jsx +454 -454
  24. package/src/native/components/NativeJsonViewContext.js +17 -17
  25. package/src/native/components/NativeShell.jsx +68 -68
  26. package/src/native/components/NativeViewComponent.jsx +351 -351
  27. package/src/native/extensions/NativeExtensionRegistry.js +81 -81
  28. package/src/native/hooks/useNativeStore.js +72 -72
  29. package/src/native/index.js +15 -15
  30. package/src/native/layouts/NativeStackLayout.jsx +30 -30
  31. package/src/native/layouts/NativeTabLayout.jsx +96 -96
  32. package/src/native/storage.js +13 -13
  33. package/src/native/stores/NativeBaseStore.js +348 -348
  34. package/src/native/stores/NativeStoreContext.jsx +53 -53
  35. package/src/offline/clock.js +12 -0
  36. package/src/offline/coalesce.js +45 -0
  37. package/src/offline/diff.js +17 -0
  38. package/src/offline/idb.js +52 -0
  39. package/src/offline/index.js +13 -0
  40. package/src/offline/kit.js +121 -0
  41. package/src/offline/outbox.js +83 -0
  42. package/src/offline/store.js +26 -0
  43. package/src/offline/syncer.js +55 -0
  44. package/src/server/ai/capabilities-routes.js +106 -106
  45. package/src/server/ai/index.js +1 -1
  46. package/src/server/cache/MemoryCache.js +153 -153
  47. package/src/server/cache/index.js +2 -2
  48. package/src/server/cache/middleware.js +12 -12
  49. package/src/server/db/index.js +14 -14
  50. package/src/server/db/mongo.js +137 -137
  51. package/src/server/db/postgres.js +144 -144
  52. package/src/server/index.js +42 -38
  53. package/src/server/middleware/auth.js +682 -682
  54. package/src/server/middleware/can-flags.js +132 -132
  55. package/src/server/middleware/entityRoles.js +105 -105
  56. package/src/server/middleware/index.js +58 -58
  57. package/src/server/middleware/permissions.js +240 -240
  58. package/src/server/middleware/tenant.js +203 -203
  59. package/src/server/offline/field-lww.js +66 -0
  60. package/src/server/offline/index.js +1 -0
  61. package/src/server/realtime/EventBus.js +45 -45
  62. package/src/server/realtime/WebSocketServer.js +105 -105
  63. package/src/server/realtime/index.js +3 -3
  64. package/src/server/realtime/middleware.js +18 -18
  65. package/src/server/services/email-templates.js +157 -157
  66. package/src/server/services/email.js +78 -78
  67. package/src/server/services/index.js +15 -15
  68. package/src/server/services/storage.js +119 -119
  69. package/src/server/utils/index.js +16 -16
  70. package/src/server/utils/paginate.js +65 -65
  71. package/src/server/utils/query-builder.js +293 -293
  72. package/src/server/utils/route-loader.js +61 -61
  73. package/src/server/workflow/WorkflowEngine.js +494 -494
  74. package/src/server/workflow/index.js +2 -2
  75. package/src/server/workflow/workflow-routes.js +174 -174
  76. package/src/shared/index.js +10 -10
  77. package/src/shared/utils/field-accessor.js +108 -108
  78. package/src/shared/utils/index.js +7 -7
  79. package/src/shared/utils/validation-utils.js +83 -83
  80. package/src/web/components/AppRouter/AppRouter.jsx +130 -130
  81. package/src/web/components/AppRouter/index.js +1 -1
  82. package/src/web/components/AppShell/AppShell.jsx +101 -101
  83. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -54
  84. package/src/web/components/AppShell/ShellConfig.js +53 -53
  85. package/src/web/components/AppShell/index.js +3 -3
  86. package/src/web/components/AuthProvider.jsx +426 -426
  87. package/src/web/components/CardList/CardList.jsx +272 -272
  88. package/src/web/components/CardList/index.js +2 -2
  89. package/src/web/components/DetailView/DetailView.jsx +281 -281
  90. package/src/web/components/DetailView/index.js +2 -2
  91. package/src/web/components/Form/Form.jsx +300 -300
  92. package/src/web/components/Form/FormField.jsx +226 -226
  93. package/src/web/components/Form/index.js +3 -3
  94. package/src/web/components/Grid/Grid.jsx +304 -304
  95. package/src/web/components/Grid/index.js +2 -2
  96. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -127
  97. package/src/web/components/IconRegistry/index.js +1 -1
  98. package/src/web/components/JsonView/JsonView.jsx +647 -647
  99. package/src/web/components/JsonView/ViewComponent.jsx +1045 -1045
  100. package/src/web/components/JsonView/ViewToolbar.jsx +141 -141
  101. package/src/web/components/JsonView/index.js +14 -14
  102. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -41
  103. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -122
  104. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -112
  105. package/src/web/components/JsonView/layouts/index.js +8 -8
  106. package/src/web/components/Layout.jsx +265 -265
  107. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -385
  108. package/src/web/components/MobileLayout/index.js +1 -1
  109. package/src/web/components/Navigation/Navigation.jsx +248 -248
  110. package/src/web/components/Navigation/index.js +1 -1
  111. package/src/web/components/NotificationProvider.jsx +55 -55
  112. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -82
  113. package/src/web/components/Pagination/Pagination.jsx +73 -73
  114. package/src/web/components/Pagination/index.js +8 -8
  115. package/src/web/components/SimpleList/SimpleList.jsx +177 -177
  116. package/src/web/components/SimpleList/index.js +2 -2
  117. package/src/web/components/TenantProvider.jsx +121 -121
  118. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -71
  119. package/src/web/components/WorkflowActions/index.js +1 -1
  120. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -176
  121. package/src/web/components/WorkflowField/index.js +2 -2
  122. package/src/web/components/WorkflowField/workflowColors.js +32 -32
  123. package/src/web/components/auth/DevTenantSelector.jsx +90 -90
  124. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -94
  125. package/src/web/components/auth/RegisterForm.jsx +168 -168
  126. package/src/web/components/auth/ResetPasswordForm.jsx +121 -121
  127. package/src/web/components/auth/VerifyEmailView.jsx +85 -85
  128. package/src/web/components/auth/index.js +5 -5
  129. package/src/web/components/index.js +39 -39
  130. package/src/web/components/layouts/CardListLayout.jsx +68 -68
  131. package/src/web/components/layouts/FullscreenLayout.jsx +30 -30
  132. package/src/web/components/layouts/MobileStackLayout.jsx +28 -28
  133. package/src/web/components/layouts/WizardLayout.jsx +86 -86
  134. package/src/web/components/layouts/index.js +4 -4
  135. package/src/web/components/mobile/Badge.jsx +105 -105
  136. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -104
  137. package/src/web/components/mobile/EmptyState.jsx +30 -30
  138. package/src/web/components/mobile/QuickActionButton.jsx +77 -77
  139. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -123
  140. package/src/web/components/mobile/StarRating.jsx +42 -42
  141. package/src/web/components/mobile/StatCard.jsx +65 -65
  142. package/src/web/components/mobile/index.js +7 -7
  143. package/src/web/extensions/ExtensionRegistry.js +79 -79
  144. package/src/web/extensions/index.js +7 -7
  145. package/src/web/hooks/index.js +15 -15
  146. package/src/web/hooks/useApi.js +76 -76
  147. package/src/web/hooks/useAuth.js +37 -37
  148. package/src/web/hooks/useDebouncedSave.js +158 -158
  149. package/src/web/hooks/useIsMobile.js +14 -14
  150. package/src/web/hooks/useOfflineQueue.js +99 -99
  151. package/src/web/hooks/useSelectionModel.js +143 -143
  152. package/src/web/hooks/useServerAutocomplete.js +146 -146
  153. package/src/web/hooks/useStore.js +107 -107
  154. package/src/web/hooks/useSubscription.js +130 -130
  155. package/src/web/hooks/useTenant.js +39 -39
  156. package/src/web/hooks/useTenantResolver.js +65 -65
  157. package/src/web/hooks/useUndoRedo.js +77 -77
  158. package/src/web/hooks/useViews.js +113 -113
  159. package/src/web/hooks/useWorkflow.js +190 -190
  160. package/src/web/index.js +117 -117
  161. package/src/web/stores/BaseStore.js +439 -439
  162. package/src/web/stores/StoreContext.jsx +93 -93
  163. package/src/web/stores/index.js +3 -3
  164. package/src/web/theme/index.js +3 -3
  165. package/src/web/theme/mui-theme.js +228 -228
  166. package/src/web/utils/formatTimeAgo.js +22 -22
  167. package/src/web/utils/index.js +1 -1
  168. package/src/web/views/ViewRegistry.js +235 -235
  169. package/src/web/views/index.js +2 -2
@@ -1,494 +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;
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;