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