adula 2.1.0 → 2.2.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 (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +4 -2
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -1,11 +1,32 @@
1
+ import { canView, resourceLabel } from '../collaboration/shared.js';
1
2
  import { AdulaError } from '../admin/errors.js';
2
3
  import { fromRow } from '../admin/contracts.js';
3
- import { columnName } from '../resource/define_resource.js';
4
+ import { withLinks } from '../admin/resource/shared.js';
4
5
  import { recordMutation } from '../events/record_mutation.js';
5
6
  import { notifyWithTemplate } from '../core/message_templates.js';
7
+ import { WorkflowDelegations, actionableBy } from './delegations.js';
8
+ import { addDays, assertTimeZone, calendarDate } from './calendar.js';
6
9
  import { nextStep, } from './define_workflow.js';
10
+ import { slaState } from './sla.js';
11
+ export { slaState } from './sla.js';
7
12
  const MAX_STEPS_PER_TICK = 25;
13
+ const HOUR = 3600000;
8
14
  const BACKOFF_SECONDS = [30, 120, 600, 1800, 7200];
15
+ /** Orders an actor's actionable rows: their own, then those routed for them, then delegated. */
16
+ const MINE_FIRST = '(a.assignee_id = ? AND a.delegation_id IS NULL) DESC, coalesce(a.on_behalf_of = ?, false) DESC, a.id';
17
+ /**
18
+ * Whose approval an actor decides as a delegate: the delegator of an approval routed to
19
+ * them, the delegator's own approval, or one routed earlier through a delegation that has
20
+ * ended (its approver is on_behalf_of). Null when it is the actor's own.
21
+ */
22
+ function onBehalfOf(row, actorId) {
23
+ const routedFor = row.on_behalf_of === null || row.on_behalf_of === undefined ? null : Number(row.on_behalf_of);
24
+ if (Number(row.assignee_id) === actorId)
25
+ return routedFor;
26
+ if (routedFor === actorId)
27
+ return null;
28
+ return row.delegation_id ? routedFor : Number(row.assignee_id);
29
+ }
9
30
  class StepFailure extends Error {
10
31
  permanent;
11
32
  /** A permanent failure stops the run now instead of retrying a configuration error. */
@@ -28,6 +49,7 @@ export class WorkflowEngine {
28
49
  assignments;
29
50
  options;
30
51
  #definitions = new Map();
52
+ #delegations;
31
53
  constructor(db, registry, resources, actors, assignments, definitions, options = {}) {
32
54
  this.db = db;
33
55
  this.registry = registry;
@@ -35,6 +57,12 @@ export class WorkflowEngine {
35
57
  this.actors = actors;
36
58
  this.assignments = assignments;
37
59
  this.options = options;
60
+ if (options.timeZone)
61
+ assertTimeZone(options.timeZone);
62
+ this.#delegations = new WorkflowDelegations(db, {
63
+ now: () => this.now(),
64
+ timeZone: options.timeZone,
65
+ });
38
66
  for (const definition of definitions)
39
67
  this.register(definition);
40
68
  }
@@ -72,16 +100,13 @@ export class WorkflowEngine {
72
100
  return this.registry.all().flatMap((resource) => {
73
101
  if (!resource.submittable)
74
102
  return [];
75
- const module = this.registry.owner(resource.name);
76
103
  return [
77
104
  {
78
- name: `adula.workflows.start.${resource.name}`,
79
- event: `${module}.${resource.name}.submitted`,
105
+ ...workflowKey(this.registry, resource.name, 'start'),
80
106
  handle: (event, trx) => this.start(trx, event),
81
107
  },
82
108
  {
83
- name: `adula.workflows.cancel.${resource.name}`,
84
- event: `${module}.${resource.name}.cancelled`,
109
+ ...workflowKey(this.registry, resource.name, 'cancel'),
85
110
  handle: (event, trx) => this.cancelRuns(trx, resource.name, Number(event.payload.id), Number(event.payload.actorId)),
86
111
  },
87
112
  ];
@@ -189,6 +214,9 @@ export class WorkflowEngine {
189
214
  const step = definition.steps[stepName];
190
215
  const move = async (event, detail = {}) => {
191
216
  const target = nextStep(definition, stepName, event);
217
+ // A definition built without defineWorkflow could still loop; stop it here.
218
+ if (target === stepName)
219
+ throw new StepFailure(`Step ${stepName} cannot name itself as its next step`, true);
192
220
  await trx('workflow_runs')
193
221
  .where('id', run.id)
194
222
  .update({
@@ -243,22 +271,11 @@ export class WorkflowEngine {
243
271
  // Waiting on nobody would hide the run for hours of retries; fail it where admins look.
244
272
  if (!eligible.length)
245
273
  throw new StepFailure(`No eligible approver for ${stepName}: ${users.length ? `${users.length} recipients cannot view the record` : 'the recipients resolve to no active user'}. Fix the recipients, then retry the run.`, true);
246
- const due = step.dueInDays
247
- ? new Date(this.now().getTime() + step.dueInDays * 86400000).toISOString().slice(0, 10)
248
- : null;
249
- for (const userId of eligible)
250
- await this.assignments.create(trx, {
251
- resource: run.resource,
252
- recordId: Number(run.record_id),
253
- assigneeId: userId,
254
- assignedBy: run.started_by,
255
- title: step.label,
256
- kind: 'approval',
257
- dueOn: due,
258
- workflowRunId: run.id,
259
- workflowStep: stepName,
260
- });
261
- await this.log(trx, run.id, stepName, 'approval_requested', null, { approvers: eligible });
274
+ const delegated = await this.openApprovals(trx, run, stepName, step, eligible);
275
+ await this.log(trx, run.id, stepName, 'approval_requested', null, {
276
+ approvers: eligible,
277
+ ...(delegated.length ? { delegated } : {}),
278
+ });
262
279
  }
263
280
  await trx('workflow_runs').where('id', run.id).update({
264
281
  status: 'waiting',
@@ -338,14 +355,17 @@ export class WorkflowEngine {
338
355
  throw new AdulaError(404, 'E_WORKFLOW_NOT_FOUND', 'التدفق غير موجود');
339
356
  if (!(await this.resources.permits(run.resource, Number(run.record_id), actor)))
340
357
  throw new AdulaError(404, 'E_WORKFLOW_NOT_FOUND', 'التدفق غير موجود');
341
- const assignment = await trx('assignments')
358
+ // The actor's own approval first, then one they hold for a delegator (ADR 044).
359
+ const assignment = await trx('assignments as a')
342
360
  .where({
343
- workflow_run_id: run.id,
344
- workflow_step: run.current_step,
345
- assignee_id: actor.id,
346
- status: 'open',
361
+ 'a.workflow_run_id': run.id,
362
+ 'a.workflow_step': run.current_step,
363
+ 'a.status': 'open',
347
364
  })
348
- .first();
365
+ .modify(actionableBy(trx, actor.id, this.today()))
366
+ .orderByRaw(MINE_FIRST, [actor.id, actor.id])
367
+ .forUpdate()
368
+ .first('a.*');
349
369
  if (run.status !== 'waiting' || !assignment)
350
370
  throw new AdulaError(409, 'E_WORKFLOW_STATE', 'لا توجد موافقة مطلوبة منك في هذه الخطوة');
351
371
  const definition = this.definition(run.definition, run.definition_version);
@@ -389,9 +409,11 @@ export class WorkflowEngine {
389
409
  last_error: null,
390
410
  updated_at: trx.fn.now(),
391
411
  });
412
+ const behalf = onBehalfOf(assignment, actor.id);
392
413
  await this.log(trx, run.id, run.current_step, logged, actor.id, {
393
414
  ...(logged === 'decided' ? { outcome: decision } : {}),
394
415
  ...(note ? { comment: note } : {}),
416
+ ...(behalf ? { onBehalfOf: behalf, onBehalfOfName: await this.userName(trx, behalf) } : {}),
395
417
  next: target,
396
418
  });
397
419
  await this.advance(trx, run.id);
@@ -410,6 +432,193 @@ export class WorkflowEngine {
410
432
  throw new AdulaError(404, 'E_WORKFLOW_NOT_FOUND', 'لا يوجد تدفق فاشل بهذا المعرّف');
411
433
  await this.log(this.db, runId, null, 'retried', actorId, {});
412
434
  }
435
+ /**
436
+ * One pass of the `sla:` job family (ADR 044). Approvers whose deadline is near get one
437
+ * reminder; overdue approvals run their step's escalation policy once: mark overdue
438
+ * (tell the approvers), notify a target, or reassign to it. Every action happens under
439
+ * the run's row lock and is recorded in workflow_escalations, whose unique key per
440
+ * assignment and level makes a repeated or concurrent pass a no-op.
441
+ */
442
+ async evaluateSla(options = {}) {
443
+ const limit = Math.max(1, Math.min(500, Math.floor(Number(options.limit) || 100)));
444
+ const now = this.now();
445
+ const pending = () => this.db('assignments as a')
446
+ .join('workflow_runs as r', 'r.id', 'a.workflow_run_id')
447
+ .where({ 'a.status': 'open', 'r.status': 'waiting' })
448
+ .whereRaw('a.workflow_step = r.current_step');
449
+ const reminders = await pending()
450
+ .whereNull('a.reminded_at')
451
+ .whereNull('a.escalated_at')
452
+ .where('a.due_soon_at', '<=', now)
453
+ .where('a.due_at', '>', now)
454
+ .orderBy('a.due_at')
455
+ .limit(limit)
456
+ .select('a.id', 'a.workflow_run_id');
457
+ let reminded = 0;
458
+ for (const due of reminders)
459
+ if (await this.db.transaction((trx) => this.remind(trx, due.workflow_run_id, due.id, now)))
460
+ reminded++;
461
+ const late = await pending()
462
+ .whereNull('a.escalated_at')
463
+ .where('a.due_at', '<=', now)
464
+ .groupBy('a.workflow_run_id')
465
+ .orderByRaw('min(a.due_at)')
466
+ .limit(limit)
467
+ .select('a.workflow_run_id');
468
+ let escalated = 0;
469
+ for (const due of late)
470
+ if (await this.db.transaction((trx) => this.escalate(trx, due.workflow_run_id, now)))
471
+ escalated++;
472
+ return { reminded, escalated };
473
+ }
474
+ async remind(trx, runId, assignmentId, now) {
475
+ const run = await trx('workflow_runs').where('id', runId).forUpdate().skipLocked().first();
476
+ if (!run || run.status !== 'waiting')
477
+ return false;
478
+ const row = await trx('assignments')
479
+ .where({ id: assignmentId, status: 'open', workflow_step: run.current_step })
480
+ .whereNull('reminded_at')
481
+ .whereNull('escalated_at')
482
+ .forUpdate()
483
+ .first();
484
+ if (!row)
485
+ return false;
486
+ await trx('assignments').where('id', row.id).update({ reminded_at: now });
487
+ const holder = await this.holder(trx, run, row);
488
+ const recorded = await this.record(trx, run, row, 'due_soon', 'remind', [holder]);
489
+ if (!recorded)
490
+ return false;
491
+ await this.notifyDeadline(trx, run, row, holder, 'workflow.sla_due_soon');
492
+ await this.log(trx, run.id, run.current_step, 'sla_reminded', null, {
493
+ assignee: holder,
494
+ dueAt: new Date(row.due_at).toISOString(),
495
+ });
496
+ return true;
497
+ }
498
+ async escalate(trx, runId, now) {
499
+ const run = await trx('workflow_runs').where('id', runId).forUpdate().skipLocked().first();
500
+ if (!run || run.status !== 'waiting')
501
+ return false;
502
+ const rows = await trx('assignments')
503
+ .where({ workflow_run_id: run.id, workflow_step: run.current_step, status: 'open' })
504
+ .whereNull('escalated_at')
505
+ .where('due_at', '<=', now)
506
+ .orderBy('id')
507
+ .forUpdate();
508
+ if (!rows.length)
509
+ return false;
510
+ await trx('assignments')
511
+ .whereIn('id', rows.map((row) => row.id))
512
+ .update({ escalated_at: now, reminded_at: trx.raw('coalesce(reminded_at, ?)', [now]) });
513
+ let step;
514
+ try {
515
+ step = this.definition(run.definition, run.definition_version).steps[run.current_step];
516
+ }
517
+ catch { }
518
+ const policy = step && (step.type === 'approval' || step.type === 'decision')
519
+ ? step.sla?.escalate
520
+ : undefined;
521
+ let action = policy?.action ?? 'overdue';
522
+ let targets = [];
523
+ let reason;
524
+ if (policy && policy.action !== 'overdue') {
525
+ try {
526
+ const context = await this.context(trx, run);
527
+ const late = new Set();
528
+ for (const row of rows) {
529
+ late.add(Number(row.assignee_id));
530
+ if (row.on_behalf_of)
531
+ late.add(Number(row.on_behalf_of));
532
+ }
533
+ for (const userId of await this.escalationTargets(trx, run, context, policy.to, rows))
534
+ // The requester never receives their own request (ADR 044, no self-approval).
535
+ if (!late.has(userId) &&
536
+ userId !== Number(run.started_by) &&
537
+ (await this.canView(run.resource, run.record_id, userId)))
538
+ targets.push(userId);
539
+ }
540
+ catch (error) {
541
+ reason = String(error?.message ?? error).slice(0, 300);
542
+ }
543
+ // A policy that finds nobody still marks the approval overdue, never silently waits.
544
+ if (!targets.length) {
545
+ reason ??= 'no eligible escalation target';
546
+ action = 'overdue';
547
+ }
548
+ }
549
+ let recorded = 0;
550
+ for (const row of rows)
551
+ if (await this.record(trx, run, row, 'overdue', action, targets))
552
+ recorded++;
553
+ if (!recorded)
554
+ return false;
555
+ // Late approvers are told at their current holder: the approver again once the
556
+ // delegation that routed the approval has ended.
557
+ const holders = [];
558
+ for (const row of rows)
559
+ holders.push(await this.holder(trx, run, row));
560
+ for (const [index, row] of rows.entries())
561
+ await this.notifyDeadline(trx, run, row, holders[index], 'workflow.sla_overdue');
562
+ if (action === 'notify') {
563
+ const names = [];
564
+ for (const row of rows) {
565
+ const name = await this.userName(trx, Number(row.on_behalf_of ?? row.assignee_id));
566
+ if (name && !names.includes(name))
567
+ names.push(name);
568
+ }
569
+ for (const userId of targets)
570
+ await this.notifyDeadline(trx, run, rows[0], userId, 'workflow.sla_escalated', {
571
+ assignee: names.join('، '),
572
+ });
573
+ }
574
+ if (action === 'reassign' && step && (step.type === 'approval' || step.type === 'decision')) {
575
+ await trx('assignments')
576
+ .whereIn('id', rows.map((row) => row.id))
577
+ .update({
578
+ status: 'cancelled',
579
+ completed_at: trx.fn.now(),
580
+ close_reason: 'أُعيد الإسناد بعد تجاوز المهلة',
581
+ });
582
+ const dueAt = new Date(Math.min(...rows.map((row) => new Date(row.due_at).getTime())));
583
+ await this.openApprovals(trx, run, run.current_step, step, targets, {
584
+ dueAt,
585
+ dueSoonAt: null,
586
+ escalatedAt: now,
587
+ });
588
+ }
589
+ await this.log(trx, run.id, run.current_step, 'sla_escalated', null, {
590
+ action,
591
+ late: holders,
592
+ targets,
593
+ ...(reason ? { reason } : {}),
594
+ });
595
+ return true;
596
+ }
597
+ /** Records one SLA action per assignment and level; false when it was already recorded. */
598
+ async record(trx, run, row, level, action, targets) {
599
+ const inserted = await trx('workflow_escalations')
600
+ .insert({
601
+ run_id: run.id,
602
+ step: run.current_step,
603
+ assignment_id: row.id,
604
+ level,
605
+ action,
606
+ targets: JSON.stringify(targets),
607
+ })
608
+ .onConflict(['assignment_id', 'level'])
609
+ .ignore()
610
+ .returning('id');
611
+ return inserted.length > 0;
612
+ }
613
+ async notifyDeadline(trx, run, row, userId, template, extra = {}) {
614
+ await notifyWithTemplate(trx, userId, template, {
615
+ title: String(row.title),
616
+ resource: this.resources.label(run.resource),
617
+ id: run.record_id,
618
+ due: new Date(row.due_at).toISOString().slice(0, 16).replace('T', ' ') + ' UTC',
619
+ ...extra,
620
+ }, undefined, { resource: String(run.resource), recordId: Number(run.record_id) });
621
+ }
413
622
  /**
414
623
  * Explicit version migration for runs that have not finished: `mapStep` returns
415
624
  * the equivalent step name in the new version.
@@ -461,17 +670,24 @@ export class WorkflowEngine {
461
670
  async inbox(actor, options = {}) {
462
671
  if (options.runIds && !options.runIds.length)
463
672
  return [];
673
+ // Delegated approvals count too, so one run may match twice (ADR 044).
464
674
  const query = this.db('workflow_runs as r')
465
675
  .join('assignments as a', 'a.workflow_run_id', 'r.id')
466
- .where({ 'a.assignee_id': actor.id, 'a.status': 'open', 'r.status': 'waiting' })
467
- .whereRaw('a.workflow_step = r.current_step');
676
+ .where({ 'a.status': 'open', 'r.status': 'waiting' })
677
+ .whereRaw('a.workflow_step = r.current_step')
678
+ .modify(actionableBy(this.db, actor.id, this.today()));
468
679
  if (options.runIds)
469
680
  query.whereIn('r.id', [...new Set(options.runIds)].slice(0, 100));
470
- const rows = await query.orderBy('a.id', 'desc').limit(100).select('r.*');
681
+ const rows = await query.orderBy('a.id', 'desc').limit(200).select('r.*');
471
682
  const runs = [];
472
- for (const row of rows)
683
+ const seen = new Set();
684
+ for (const row of rows) {
685
+ if (seen.has(String(row.id)) || runs.length >= 100)
686
+ continue;
687
+ seen.add(String(row.id));
473
688
  if (await this.resources.permits(row.resource, Number(row.record_id), actor))
474
689
  runs.push(await this.present(row, actor));
690
+ }
475
691
  return runs;
476
692
  }
477
693
  async failed(limit = 100) {
@@ -494,28 +710,31 @@ export class WorkflowEngine {
494
710
  .limit(200)
495
711
  .select('e.*', 'u.full_name as actor_name');
496
712
  const mine = actor
497
- ? await this.db('assignments')
713
+ ? await this.db('assignments as a')
498
714
  .where({
499
- workflow_run_id: row.id,
500
- workflow_step: row.current_step,
501
- assignee_id: actor.id,
502
- status: 'open',
715
+ 'a.workflow_run_id': row.id,
716
+ 'a.workflow_step': row.current_step,
717
+ 'a.status': 'open',
503
718
  })
504
- .first('id', 'title')
719
+ .modify(actionableBy(this.db, actor.id, this.today()))
720
+ .orderByRaw(MINE_FIRST, [actor.id, actor.id])
721
+ .first('a.*')
722
+ : undefined;
723
+ const behalf = mine && actor ? onBehalfOf(mine, actor.id) : null;
724
+ const deadline = row.status === 'waiting'
725
+ ? await this.db('assignments')
726
+ .where({ workflow_run_id: row.id, workflow_step: row.current_step, status: 'open' })
727
+ .whereNotNull('due_at')
728
+ .first(this.db.raw('min(due_at) as due_at'), this.db.raw('min(due_soon_at) as due_soon_at'), this.db.raw('bool_or(escalated_at IS NOT NULL) as escalated'))
505
729
  : undefined;
506
730
  const step = row.current_step ? definition?.steps[row.current_step] : undefined;
507
731
  const titles = actor
508
732
  ? await this.resources.titles(row.resource, [Number(row.record_id)], actor)
509
733
  : undefined;
510
- let resourceLabel = String(row.resource);
511
- try {
512
- resourceLabel = this.resources.label(row.resource);
513
- }
514
- catch { }
515
734
  return {
516
735
  id: String(row.id),
517
736
  resource: String(row.resource),
518
- resourceLabel,
737
+ resourceLabel: resourceLabel(this.resources, String(row.resource)),
519
738
  recordId: Number(row.record_id),
520
739
  recordTitle: titles?.get(Number(row.record_id)) ?? null,
521
740
  definition: String(row.definition),
@@ -534,6 +753,7 @@ export class WorkflowEngine {
534
753
  step: event.step ?? null,
535
754
  event: String(event.event),
536
755
  actorName: event.actor_name ? String(event.actor_name) : null,
756
+ onBehalfOfName: typeof event.detail?.onBehalfOfName === 'string' ? event.detail.onBehalfOfName : null,
537
757
  detail: (event.detail ?? {}),
538
758
  at: new Date(event.created_at).toISOString(),
539
759
  })),
@@ -542,6 +762,14 @@ export class WorkflowEngine {
542
762
  assignmentId: Number(mine.id),
543
763
  title: String(mine.title),
544
764
  ...(step?.type === 'decision' ? { decision: this.decisionForm(step) } : {}),
765
+ onBehalfOf: behalf ? { id: behalf, name: await this.userName(this.db, behalf) } : null,
766
+ }
767
+ : null,
768
+ sla: deadline?.due_at
769
+ ? {
770
+ dueAt: new Date(deadline.due_at).toISOString(),
771
+ state: slaState(new Date(deadline.due_at), deadline.due_soon_at ? new Date(deadline.due_soon_at) : null, this.now()),
772
+ escalated: Boolean(deadline.escalated),
545
773
  }
546
774
  : null,
547
775
  };
@@ -612,8 +840,10 @@ export class WorkflowEngine {
612
840
  const row = await trx(resource.name).where('id', run.record_id).first();
613
841
  if (!row)
614
842
  throw new StepFailure('The workflow record no longer exists');
843
+ // manyToMany links are not columns; steps see them like any other value.
844
+ const [record] = await withLinks(trx, resource, [fromRow(row, resource)]);
615
845
  return {
616
- record: fromRow(row, resource),
846
+ record,
617
847
  run: {
618
848
  id: String(run.id),
619
849
  resource: String(run.resource),
@@ -623,11 +853,13 @@ export class WorkflowEngine {
623
853
  db: trx,
624
854
  };
625
855
  }
626
- /** Workflow writes are system writes attributed to the submitter, with history. */
856
+ /**
857
+ * Workflow writes are system writes attributed to the submitter, with history. They go
858
+ * through systemSave, so the resource validator, hooks, relation checks and the
859
+ * optimistic lock apply; a rejected write fails the step like any other step error.
860
+ */
627
861
  async updateRecord(trx, run, record, values) {
628
862
  const resource = this.registry.get(run.resource);
629
- const update = { updated_at: trx.fn.now() };
630
- const changes = [];
631
863
  for (const [key, value] of Object.entries(values)) {
632
864
  const field = resource.fields[key];
633
865
  if (!field || ['hasMany', 'attachment'].includes(field.type) || field.sequence)
@@ -639,26 +871,15 @@ export class WorkflowEngine {
639
871
  if (!valid)
640
872
  throw new StepFailure(`Invalid lookup value for ${key}`);
641
873
  }
642
- update[field.column ?? columnName(key)] =
643
- field.type === 'json' ? JSON.stringify(value) : value;
644
- if (JSON.stringify(record[key] ?? null) !== JSON.stringify(value ?? null))
645
- changes.push({ field: key, before: record[key] ?? null, after: value ?? null });
646
874
  }
647
- if (resource.version)
648
- update.version = Number(record.version) + 1;
649
- if (run.started_by)
650
- update.updated_by = run.started_by;
651
- await trx(resource.name).where('id', run.record_id).update(update);
652
- if (run.started_by)
653
- await recordMutation(trx, {
654
- module: this.registry.owner(resource.name),
655
- resource: resource.name,
656
- id: run.record_id,
657
- actorId: Number(run.started_by),
658
- action: 'update',
659
- fields: Object.keys(values),
660
- changes,
661
- });
875
+ // A run started by an event without a user is an unattributed system update.
876
+ await this.resources.systemSave(resource.name, values, Number(run.record_id), {
877
+ actorId: run.started_by ? Number(run.started_by) : null,
878
+ trx,
879
+ reason: `workflow:${run.definition}`,
880
+ version: resource.version ? Number(record.version) : undefined,
881
+ submitted: true,
882
+ });
662
883
  }
663
884
  async cancelDocument(trx, run, record) {
664
885
  const resource = this.registry.get(run.resource);
@@ -710,11 +931,8 @@ export class WorkflowEngine {
710
931
  const byName = await db('roles').where('name', reference).first('id');
711
932
  return byName ? Number(byName.id) : null;
712
933
  }
713
- async canView(resource, id, userId) {
714
- const user = await this.db('users').where('id', userId).first('disabled_at');
715
- if (!user || user.disabled_at)
716
- return false;
717
- return this.resources.permits(resource, Number(id), await this.actors.load(userId));
934
+ canView(resource, id, userId) {
935
+ return canView(this.db, this.resources, this.actors, resource, id, userId);
718
936
  }
719
937
  async log(db, runId, step, event, actorId, detail) {
720
938
  await db('workflow_events').insert({
@@ -725,10 +943,149 @@ export class WorkflowEngine {
725
943
  detail: JSON.stringify(detail),
726
944
  });
727
945
  }
946
+ /**
947
+ * Opens one approval per approver. An approver with a delegation in force today is
948
+ * replaced by the delegate when the delegate may view the record (ADR 044); the row
949
+ * keeps the approver in on_behalf_of, so both see it while the delegation lasts.
950
+ * Returns the routed pairs for the run log.
951
+ */
952
+ async openApprovals(trx, run, stepName, step, approvers, deadline = this.deadline(step)) {
953
+ // Calendar days of the system's time zone: at 01:00 in Riyadh it is already the
954
+ // next day there, though not yet in UTC.
955
+ const dueOn = deadline
956
+ ? calendarDate(deadline.dueAt, this.options.timeZone)
957
+ : step.dueInDays
958
+ ? addDays(this.today(), step.dueInDays)
959
+ : null;
960
+ const routed = [];
961
+ const opened = new Set();
962
+ for (const approver of approvers) {
963
+ let assigneeId = approver;
964
+ const active = await this.delegateFor(trx, run, approver);
965
+ let delegation = null;
966
+ if (active) {
967
+ delegation = active;
968
+ assigneeId = active.delegateId;
969
+ routed.push({ from: approver, to: assigneeId });
970
+ }
971
+ const key = `${assigneeId}:${delegation ? approver : ''}`;
972
+ if (opened.has(key))
973
+ continue;
974
+ opened.add(key);
975
+ await this.assignments.create(trx, {
976
+ resource: run.resource,
977
+ recordId: Number(run.record_id),
978
+ assigneeId,
979
+ assignedBy: run.started_by,
980
+ title: step.label,
981
+ kind: 'approval',
982
+ dueOn,
983
+ workflowRunId: run.id,
984
+ workflowStep: stepName,
985
+ onBehalfOf: delegation ? approver : null,
986
+ delegationId: delegation?.id ?? null,
987
+ dueAt: deadline?.dueAt ?? null,
988
+ dueSoonAt: deadline?.dueSoonAt ?? null,
989
+ escalatedAt: deadline?.escalatedAt ?? null,
990
+ });
991
+ }
992
+ return routed;
993
+ }
994
+ /** The SLA deadline of a step opening now, or null when the step declares none. */
995
+ deadline(step) {
996
+ if (!step.sla)
997
+ return null;
998
+ const now = this.now().getTime();
999
+ const dueAt = new Date(now + step.sla.hours * HOUR);
1000
+ const soon = step.sla.dueSoonHours ?? step.sla.hours / 4;
1001
+ return { dueAt, dueSoonAt: soon > 0 ? new Date(dueAt.getTime() - soon * HOUR) : null };
1002
+ }
1003
+ async escalationTargets(trx, run, context, to, late) {
1004
+ if (typeof to === 'object' && to !== null && 'manager' in to) {
1005
+ // The approver of record: the delegator when the late approval was delegated.
1006
+ const approvers = [...new Set(late.map((row) => Number(row.on_behalf_of ?? row.assignee_id)))];
1007
+ const found = [];
1008
+ for (const approver of approvers)
1009
+ found.push(...(await this.managers(trx, to.manager, approver)));
1010
+ return [...new Set(found)];
1011
+ }
1012
+ return this.recipients(trx, run, context, to);
1013
+ }
1014
+ /**
1015
+ * The approver's managers in the org tree: active holders of the role whose role is
1016
+ * scoped to the approver's unit or, failing that, to the nearest ancestor unit.
1017
+ */
1018
+ async managers(trx, role, approver) {
1019
+ const roleId = await this.roleId(trx, role);
1020
+ if (roleId === null)
1021
+ return [];
1022
+ const rows = await trx('user_roles as ur')
1023
+ .join('org_units as o', 'o.id', 'ur.org_unit_id')
1024
+ .join('users as u', 'u.id', 'ur.user_id')
1025
+ .where('ur.role_id', roleId)
1026
+ .whereNot('ur.user_id', approver)
1027
+ .whereNull('u.disabled_at')
1028
+ .whereRaw('o.path @> ANY (SELECT ou.path FROM user_org_units m JOIN org_units ou ON ou.id = m.org_unit_id WHERE m.user_id = ?)', [approver])
1029
+ .select('ur.user_id', trx.raw('nlevel(o.path) AS depth'));
1030
+ const nearest = Math.max(...rows.map((row) => Number(row.depth)));
1031
+ return rows.filter((row) => Number(row.depth) === nearest).map((row) => Number(row.user_id));
1032
+ }
1033
+ /**
1034
+ * The delegate an approver's approvals go to today, or null to keep them with the
1035
+ * approver (ADR 044). Routing is one hop and only to someone who can act: never the
1036
+ * person who started the run (no self-approval), never a delegate who is away and
1037
+ * delegating in turn, and never a delegate who cannot view the record.
1038
+ */
1039
+ async delegateFor(db, run, approver) {
1040
+ const active = await this.#delegations.active(approver, db);
1041
+ if (!active || active.delegateId === Number(run.started_by))
1042
+ return null;
1043
+ if (await this.#delegations.active(active.delegateId, db))
1044
+ return null;
1045
+ if (!(await this.canView(run.resource, run.record_id, active.delegateId)))
1046
+ return null;
1047
+ return active;
1048
+ }
1049
+ /**
1050
+ * Who is told about an open approval now: the delegate it was routed to while that
1051
+ * delegation lasts; otherwise its approver, or the approver's current delegate when
1052
+ * the approver is away today.
1053
+ */
1054
+ async holder(db, run, row) {
1055
+ let approver = Number(row.assignee_id);
1056
+ if (row.delegation_id && row.on_behalf_of) {
1057
+ const today = this.today();
1058
+ const routed = await db('workflow_delegations')
1059
+ .where('id', row.delegation_id)
1060
+ .whereNull('revoked_at')
1061
+ .where('starts_on', '<=', today)
1062
+ .where('ends_on', '>=', today)
1063
+ .first('id');
1064
+ if (routed)
1065
+ return approver;
1066
+ approver = Number(row.on_behalf_of);
1067
+ }
1068
+ const away = await this.delegateFor(db, run, approver);
1069
+ return away ? away.delegateId : approver;
1070
+ }
1071
+ async userName(db, id) {
1072
+ const row = await db('users').where('id', id).first('full_name', 'email');
1073
+ return row ? String(row.full_name ?? row.email ?? `#${id}`) : null;
1074
+ }
1075
+ today() {
1076
+ return calendarDate(this.now(), this.options.timeZone);
1077
+ }
728
1078
  now() {
729
1079
  return this.options.now?.() ?? new Date();
730
1080
  }
731
1081
  }
1082
+ /** The listener name and domain event that start or cancel a resource's workflow. */
1083
+ function workflowKey(registry, resource, kind) {
1084
+ return {
1085
+ name: `adula.workflows.${kind}.${resource}`,
1086
+ event: `${registry.owner(resource)}.${resource}.${kind === 'start' ? 'submitted' : 'cancelled'}`,
1087
+ };
1088
+ }
732
1089
  /**
733
1090
  * Listeners resolved per call, so hosts can build the engine lazily (for example
734
1091
  * per request) while the listener list is fixed at boot from the registry.
@@ -737,16 +1094,17 @@ export function workflowListeners(registry, engine) {
737
1094
  return registry.all().flatMap((resource) => {
738
1095
  if (!resource.submittable)
739
1096
  return [];
740
- const module = registry.owner(resource.name);
741
- return ['start', 'cancel'].map((kind) => ({
742
- name: `adula.workflows.${kind}.${resource.name}`,
743
- event: `${module}.${resource.name}.${kind === 'start' ? 'submitted' : 'cancelled'}`,
744
- handle: (event, trx) => {
745
- const listener = engine()
746
- .listeners()
747
- .find((entry) => entry.name === `adula.workflows.${kind}.${resource.name}`);
748
- return listener ? listener.handle(event, trx) : Promise.resolve();
749
- },
750
- }));
1097
+ return ['start', 'cancel'].map((kind) => {
1098
+ const key = workflowKey(registry, resource.name, kind);
1099
+ return {
1100
+ ...key,
1101
+ handle: (event, trx) => {
1102
+ const listener = engine()
1103
+ .listeners()
1104
+ .find((entry) => entry.name === key.name);
1105
+ return listener ? listener.handle(event, trx) : Promise.resolve();
1106
+ },
1107
+ };
1108
+ });
751
1109
  });
752
1110
  }