adula 2.0.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.
- package/README.md +149 -18
- package/build/agent/AGENTS.template.md +4 -4
- package/build/agent/capabilities.md +22 -11
- package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
- package/build/agent/skills/idea-review/SKILL.md +2 -2
- 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_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 +185 -0
- package/build/commands/backup_services.d.ts +31 -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 +4 -1
- package/build/commands/install.d.ts +8 -0
- package/build/commands/install.js +63 -45
- package/build/commands/main.d.ts +3 -2
- package/build/commands/main.js +26 -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 +72 -0
- package/build/commands/resource_snapshot.d.ts +2 -0
- package/build/commands/resource_snapshot.js +3 -0
- package/build/commands/sla_evaluate.d.ts +14 -0
- package/build/commands/sla_evaluate.js +16 -0
- package/build/commands/ui.js +5 -3
- 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/index.d.ts +56 -10
- package/build/index.js +34 -6
- 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 +77 -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 +59 -0
- package/build/src/admin/resource/editor.js +323 -0
- package/build/src/admin/resource/export.d.ts +37 -0
- package/build/src/admin/resource/export.js +181 -0
- package/build/src/admin/resource/lifecycle.d.ts +21 -0
- package/build/src/admin/resource/lifecycle.js +91 -0
- package/build/src/admin/resource/query.d.ts +100 -0
- package/build/src/admin/resource/query.js +508 -0
- package/build/src/admin/resource/read.d.ts +106 -0
- package/build/src/admin/resource/read.js +327 -0
- package/build/src/admin/resource/shared.d.ts +77 -0
- package/build/src/admin/resource/shared.js +222 -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 +574 -0
- package/build/src/admin/resource_service.d.ts +66 -193
- package/build/src/admin/resource_service.js +69 -1345
- package/build/src/attachments/attachment_service.d.ts +46 -2
- package/build/src/attachments/attachment_service.js +96 -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/collaboration/assignments.d.ts +36 -1
- package/build/src/collaboration/assignments.js +132 -66
- package/build/src/collaboration/record_collaboration.d.ts +2 -3
- package/build/src/collaboration/record_collaboration.js +19 -16
- package/build/src/collaboration/shared.d.ts +16 -0
- package/build/src/collaboration/shared.js +21 -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 +34 -8
- package/build/src/commands/doctor.d.ts +14 -2
- package/build/src/commands/doctor.js +50 -5
- 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 +10 -13
- package/build/src/commands/snapshot.js +31 -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 +129 -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/message_templates.d.ts +7 -2
- package/build/src/core/message_templates.js +72 -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 +2 -2
- package/build/src/core/saved_views.d.ts +8 -1
- package/build/src/core/saved_views.js +36 -2
- 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 +19 -2
- 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 +4 -0
- package/build/src/core/ui_preferences.js +4 -1
- package/build/src/core/user_invitations.d.ts +5 -1
- package/build/src/core/user_invitations.js +7 -1
- package/build/src/core/users.js +1 -1
- 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 +155 -2
- package/build/src/database/schema.js +531 -59
- package/build/src/database/schema_diff.d.ts +56 -0
- package/build/src/database/schema_diff.js +157 -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 +552 -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 +118 -16
- package/build/src/integrations/imports.js +406 -73
- package/build/src/integrations/openapi.d.ts +3 -1
- package/build/src/integrations/openapi.js +454 -31
- package/build/src/integrations/outbound.d.ts +51 -0
- package/build/src/integrations/outbound.js +195 -0
- package/build/src/integrations/print.d.ts +21 -1
- package/build/src/integrations/print.js +63 -21
- package/build/src/integrations/print_templates.d.ts +216 -0
- package/build/src/integrations/print_templates.js +1015 -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/languages/ar.d.ts +11 -0
- package/build/src/languages/ar.js +336 -0
- package/build/src/languages/ar_ui.d.ts +332 -0
- package/build/src/languages/ar_ui.js +333 -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 +330 -0
- package/build/src/languages/en_ui.d.ts +3 -0
- package/build/src/languages/en_ui.js +328 -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 +96 -0
- package/build/src/lists/dashboards.js +241 -0
- package/build/src/mcp/tools.js +1 -1
- package/build/src/resource/define_resource.d.ts +18 -1
- package/build/src/resource/define_resource.js +205 -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 +304 -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 +93 -0
- package/build/src/workflows/delegations.js +287 -0
- package/build/src/workflows/engine.d.ts +69 -4
- package/build/src/workflows/engine.js +441 -83
- 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 +5 -2
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { AdulaError } from '../admin/errors.js';
|
|
2
|
+
import { logActivity } from '../core/activity.js';
|
|
3
|
+
import { notifyWithTemplate } from '../core/message_templates.js';
|
|
4
|
+
import { escapeLike } from '../core/like.js';
|
|
5
|
+
import { assertTimeZone, calendarDate } from './calendar.js';
|
|
6
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
7
|
+
const MAX_DAYS = 366;
|
|
8
|
+
const NOTE_LIMIT = 500;
|
|
9
|
+
/** The activity log subject for delegation changes. */
|
|
10
|
+
export const DELEGATION_ACTIVITY = 'core.workflow_delegations';
|
|
11
|
+
/** node-postgres reads a date column as local midnight; read it back with local fields. */
|
|
12
|
+
function dateText(value) {
|
|
13
|
+
if (value instanceof Date)
|
|
14
|
+
return `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
|
|
15
|
+
return String(value).slice(0, 10);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Narrows an assignments query (aliased `a`) to the rows a user may act on today:
|
|
19
|
+
* - their own rows, and rows routed to them through a delegation still in force;
|
|
20
|
+
* - rows routed away from them (on_behalf_of): the approver always keeps them;
|
|
21
|
+
* - as a delegate, the open approvals of users who delegated to them for today,
|
|
22
|
+
* including rows routed earlier through a delegation that has since ended.
|
|
23
|
+
* A delegate never holds an approval of a run they started themselves, so delegation
|
|
24
|
+
* cannot let anyone approve their own request. Delegation never widens record access:
|
|
25
|
+
* every caller still checks the record with the acting user's own rights.
|
|
26
|
+
*/
|
|
27
|
+
export function actionableBy(db, actorId, today) {
|
|
28
|
+
const active = (alias) => db.raw(`${alias}.revoked_at IS NULL AND ${alias}.starts_on <= ?::date AND ${alias}.ends_on >= ?::date`, [today, today]);
|
|
29
|
+
const routedActive = () => db('workflow_delegations as dr').whereRaw('dr.id = a.delegation_id').whereRaw(active('dr'));
|
|
30
|
+
const ownRun = () => db('workflow_runs as ws').whereRaw('ws.id = a.workflow_run_id').where('ws.started_by', actorId);
|
|
31
|
+
const delegators = () => db('workflow_delegations as dd')
|
|
32
|
+
.where('dd.delegate_id', actorId)
|
|
33
|
+
.whereRaw(active('dd'))
|
|
34
|
+
.select('dd.delegator_id');
|
|
35
|
+
return (query) => query.where((where) => {
|
|
36
|
+
where
|
|
37
|
+
.where((own) => own
|
|
38
|
+
.where('a.assignee_id', actorId)
|
|
39
|
+
.where((routed) => routed
|
|
40
|
+
.whereNull('a.delegation_id')
|
|
41
|
+
.orWhere((held) => held.whereExists(routedActive()).whereNotExists(ownRun()))))
|
|
42
|
+
.orWhere('a.on_behalf_of', actorId)
|
|
43
|
+
.orWhere((delegated) => delegated
|
|
44
|
+
.whereNotNull('a.workflow_run_id')
|
|
45
|
+
.whereNotExists(ownRun())
|
|
46
|
+
.where((source) => source
|
|
47
|
+
.where((plain) => plain.whereNull('a.delegation_id').whereIn('a.assignee_id', delegators()))
|
|
48
|
+
.orWhere((stale) => stale
|
|
49
|
+
.whereNotNull('a.delegation_id')
|
|
50
|
+
.whereNotExists(routedActive())
|
|
51
|
+
.whereIn('a.on_behalf_of', delegators()))));
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/** The SQL flag `delegation_active` for an assignments query aliased `a`. */
|
|
55
|
+
export function delegationActive(db, today) {
|
|
56
|
+
return db.raw('EXISTS (SELECT 1 FROM workflow_delegations wd WHERE wd.id = a.delegation_id AND wd.revoked_at IS NULL AND wd.starts_on <= ?::date AND wd.ends_on >= ?::date) AS delegation_active', [today, today]);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Out-of-office delegation of workflow approvals. A user delegates to one person per
|
|
60
|
+
* date range (overlapping ranges are refused); administrators manage delegations for
|
|
61
|
+
* others. Creation and revocation are written to the activity log and the delegate is
|
|
62
|
+
* notified. Manual tasks are never delegated, only workflow approvals.
|
|
63
|
+
*/
|
|
64
|
+
export class WorkflowDelegations {
|
|
65
|
+
db;
|
|
66
|
+
options;
|
|
67
|
+
constructor(db, options = {}) {
|
|
68
|
+
this.db = db;
|
|
69
|
+
this.options = options;
|
|
70
|
+
if (options.timeZone)
|
|
71
|
+
assertTimeZone(options.timeZone);
|
|
72
|
+
}
|
|
73
|
+
/** A user's own delegations (given and received), newest first. */
|
|
74
|
+
async forUser(userId) {
|
|
75
|
+
const rows = await this.query()
|
|
76
|
+
.where((q) => q.where('d.delegator_id', userId).orWhere('d.delegate_id', userId))
|
|
77
|
+
.orderBy('d.id', 'desc')
|
|
78
|
+
.limit(100);
|
|
79
|
+
const list = rows.map((row) => this.present(row));
|
|
80
|
+
return {
|
|
81
|
+
given: list.filter((item) => item.delegatorId === userId),
|
|
82
|
+
received: list.filter((item) => item.delegateId === userId && item.status !== 'revoked'),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Active users a delegate can be chosen from (id and display name only), at most 20.
|
|
87
|
+
* The search needs two characters and matches names, or an e-mail address exactly, so
|
|
88
|
+
* the picker cannot list the whole user directory or probe e-mail fragments.
|
|
89
|
+
*/
|
|
90
|
+
async candidates(search, exceptId) {
|
|
91
|
+
const text = typeof search === 'string' ? search.trim().slice(0, 100) : '';
|
|
92
|
+
if (text.length < 2)
|
|
93
|
+
return [];
|
|
94
|
+
const rows = await this.db('users')
|
|
95
|
+
.whereNull('disabled_at')
|
|
96
|
+
.whereNot('id', exceptId)
|
|
97
|
+
.where((q) => q
|
|
98
|
+
.whereILike('full_name', `%${escapeLike(text)}%`)
|
|
99
|
+
.orWhereRaw('lower(email) = lower(?)', [text]))
|
|
100
|
+
.orderBy('full_name')
|
|
101
|
+
.limit(20)
|
|
102
|
+
.select('id', 'full_name', 'email');
|
|
103
|
+
return rows.map((row) => ({
|
|
104
|
+
id: Number(row.id),
|
|
105
|
+
name: String(row.full_name ?? row.email ?? `#${row.id}`),
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
108
|
+
/** Every delegation that has not ended, for administrators. */
|
|
109
|
+
async current() {
|
|
110
|
+
const rows = await this.query()
|
|
111
|
+
.whereNull('d.revoked_at')
|
|
112
|
+
.where('d.ends_on', '>=', this.today())
|
|
113
|
+
.orderBy('d.starts_on')
|
|
114
|
+
.limit(500);
|
|
115
|
+
return rows.map((row) => this.present(row));
|
|
116
|
+
}
|
|
117
|
+
/** The delegation in force today for a user, if any. */
|
|
118
|
+
async active(delegatorId, db = this.db) {
|
|
119
|
+
const today = this.today();
|
|
120
|
+
const row = await db('workflow_delegations')
|
|
121
|
+
.where('delegator_id', delegatorId)
|
|
122
|
+
.whereNull('revoked_at')
|
|
123
|
+
.where('starts_on', '<=', today)
|
|
124
|
+
.where('ends_on', '>=', today)
|
|
125
|
+
.orderBy('id', 'desc')
|
|
126
|
+
.first('id', 'delegate_id');
|
|
127
|
+
return row ? { id: Number(row.id), delegateId: Number(row.delegate_id) } : null;
|
|
128
|
+
}
|
|
129
|
+
/** Creates a delegation; the caller decides whether `createdBy` may act for the delegator. */
|
|
130
|
+
async create(input, createdBy) {
|
|
131
|
+
const delegatorId = Number(input.delegatorId);
|
|
132
|
+
const delegateId = Number(input.delegateId);
|
|
133
|
+
if (!Number.isSafeInteger(delegatorId) || delegatorId <= 0)
|
|
134
|
+
throw new AdulaError(422, 'E_DELEGATION_USER', 'المستخدم غير صالح');
|
|
135
|
+
if (!Number.isSafeInteger(delegateId) || delegateId <= 0)
|
|
136
|
+
throw new AdulaError(422, 'E_DELEGATE', 'اختر المفوَّض إليه');
|
|
137
|
+
if (delegateId === delegatorId)
|
|
138
|
+
throw new AdulaError(422, 'E_DELEGATE', 'لا يمكن التفويض إلى النفس');
|
|
139
|
+
const startsOn = this.date(input.startsOn, 'تاريخ البداية');
|
|
140
|
+
const endsOn = this.date(input.endsOn, 'تاريخ النهاية');
|
|
141
|
+
if (endsOn < startsOn)
|
|
142
|
+
throw new AdulaError(422, 'E_DELEGATION_RANGE', 'تاريخ النهاية قبل تاريخ البداية');
|
|
143
|
+
if (endsOn < this.today())
|
|
144
|
+
throw new AdulaError(422, 'E_DELEGATION_RANGE', 'لا يمكن إنشاء تفويض انتهت مدته');
|
|
145
|
+
if ((Date.parse(endsOn) - Date.parse(startsOn)) / 86400000 >= MAX_DAYS)
|
|
146
|
+
throw new AdulaError(422, 'E_DELEGATION_RANGE', 'مدة التفويض لا تتجاوز سنة');
|
|
147
|
+
const note = input.note === undefined || input.note === null || input.note === ''
|
|
148
|
+
? null
|
|
149
|
+
: typeof input.note === 'string' && input.note.trim().length <= NOTE_LIMIT
|
|
150
|
+
? input.note.trim() || null
|
|
151
|
+
: undefined;
|
|
152
|
+
if (note === undefined)
|
|
153
|
+
throw new AdulaError(422, 'E_DELEGATION_NOTE', 'الملاحظة لا تتجاوز 500 حرف');
|
|
154
|
+
return this.db.transaction(async (trx) => {
|
|
155
|
+
// The delegator's row serializes concurrent requests, so overlap checks hold.
|
|
156
|
+
// Locked in id order and without blocking foreign-key checks on these users.
|
|
157
|
+
const users = await trx('users')
|
|
158
|
+
.whereIn('id', [delegatorId, delegateId])
|
|
159
|
+
.orderBy('id')
|
|
160
|
+
.forNoKeyUpdate();
|
|
161
|
+
const delegator = users.find((user) => Number(user.id) === delegatorId);
|
|
162
|
+
const delegate = users.find((user) => Number(user.id) === delegateId);
|
|
163
|
+
if (!delegator)
|
|
164
|
+
throw new AdulaError(422, 'E_DELEGATION_USER', 'المستخدم غير صالح');
|
|
165
|
+
if (!delegate || delegate.disabled_at)
|
|
166
|
+
throw new AdulaError(422, 'E_DELEGATE', 'المفوَّض إليه غير موجود أو معطّل');
|
|
167
|
+
const overlap = await trx('workflow_delegations')
|
|
168
|
+
.where('delegator_id', delegatorId)
|
|
169
|
+
.whereNull('revoked_at')
|
|
170
|
+
.where('starts_on', '<=', endsOn)
|
|
171
|
+
.where('ends_on', '>=', startsOn)
|
|
172
|
+
.first('id');
|
|
173
|
+
if (overlap)
|
|
174
|
+
throw new AdulaError(409, 'E_DELEGATION_OVERLAP', 'يوجد تفويض آخر في هذه المدة؛ ألغه أو اختر مدة أخرى');
|
|
175
|
+
const [row] = await trx('workflow_delegations')
|
|
176
|
+
.insert({
|
|
177
|
+
delegator_id: delegatorId,
|
|
178
|
+
delegate_id: delegateId,
|
|
179
|
+
starts_on: startsOn,
|
|
180
|
+
ends_on: endsOn,
|
|
181
|
+
note,
|
|
182
|
+
created_by: createdBy,
|
|
183
|
+
})
|
|
184
|
+
.returning('id');
|
|
185
|
+
const id = Number(row.id);
|
|
186
|
+
await logActivity(trx, {
|
|
187
|
+
resource: DELEGATION_ACTIVITY,
|
|
188
|
+
recordId: id,
|
|
189
|
+
actorId: createdBy,
|
|
190
|
+
action: 'delegation_created',
|
|
191
|
+
changes: { delegatorId, delegateId, startsOn, endsOn },
|
|
192
|
+
});
|
|
193
|
+
await notifyWithTemplate(trx, delegateId, 'workflow.delegated', {
|
|
194
|
+
delegator: delegator.full_name ?? delegator.email ?? `#${delegatorId}`,
|
|
195
|
+
from: startsOn,
|
|
196
|
+
to: endsOn,
|
|
197
|
+
});
|
|
198
|
+
return this.present(await this.query(trx).where('d.id', id).first());
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Ends a delegation now. `ownerId` must be the delegator unless `any` (administrators);
|
|
203
|
+
* unknown or foreign ids read as not found. `actorId` (default `ownerId`) is recorded,
|
|
204
|
+
* for example the administrator behind an impersonation. Open approvals routed through
|
|
205
|
+
* the delegation return to their approver.
|
|
206
|
+
*/
|
|
207
|
+
async revoke(id, ownerId, options = {}) {
|
|
208
|
+
const key = Number(id);
|
|
209
|
+
const actorId = options.actorId ?? ownerId;
|
|
210
|
+
if (!Number.isSafeInteger(key) || key <= 0)
|
|
211
|
+
throw new AdulaError(404, 'E_DELEGATION_NOT_FOUND', 'التفويض غير موجود');
|
|
212
|
+
await this.db.transaction(async (trx) => {
|
|
213
|
+
const row = await trx('workflow_delegations').where('id', key).forUpdate().first();
|
|
214
|
+
if (!row || (!options.any && Number(row.delegator_id) !== ownerId))
|
|
215
|
+
throw new AdulaError(404, 'E_DELEGATION_NOT_FOUND', 'التفويض غير موجود');
|
|
216
|
+
if (row.revoked_at)
|
|
217
|
+
return;
|
|
218
|
+
await trx('workflow_delegations')
|
|
219
|
+
.where('id', key)
|
|
220
|
+
.update({ revoked_at: this.now(), revoked_by: actorId });
|
|
221
|
+
const returned = await trx('assignments')
|
|
222
|
+
.where({ delegation_id: key, status: 'open' })
|
|
223
|
+
.update({
|
|
224
|
+
assignee_id: trx.raw('on_behalf_of'),
|
|
225
|
+
on_behalf_of: null,
|
|
226
|
+
delegation_id: null,
|
|
227
|
+
});
|
|
228
|
+
await logActivity(trx, {
|
|
229
|
+
resource: DELEGATION_ACTIVITY,
|
|
230
|
+
recordId: key,
|
|
231
|
+
actorId,
|
|
232
|
+
action: 'delegation_revoked',
|
|
233
|
+
changes: {
|
|
234
|
+
delegatorId: Number(row.delegator_id),
|
|
235
|
+
delegateId: Number(row.delegate_id),
|
|
236
|
+
returned,
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
date(value, field) {
|
|
242
|
+
// Round-trip the date: Date.parse accepts impossible days such as 2027-02-30.
|
|
243
|
+
if (typeof value !== 'string' ||
|
|
244
|
+
!DATE.test(value) ||
|
|
245
|
+
Number.isNaN(Date.parse(value)) ||
|
|
246
|
+
new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) !== value)
|
|
247
|
+
throw new AdulaError(422, 'E_DELEGATION_RANGE', `${field} غير صالح`);
|
|
248
|
+
return value;
|
|
249
|
+
}
|
|
250
|
+
query(db = this.db) {
|
|
251
|
+
return db('workflow_delegations as d')
|
|
252
|
+
.leftJoin('users as f', 'f.id', 'd.delegator_id')
|
|
253
|
+
.leftJoin('users as t', 't.id', 'd.delegate_id')
|
|
254
|
+
.select('d.*', 'f.full_name as delegator_name', 't.full_name as delegate_name');
|
|
255
|
+
}
|
|
256
|
+
present(row) {
|
|
257
|
+
const today = this.today();
|
|
258
|
+
const startsOn = dateText(row.starts_on);
|
|
259
|
+
const endsOn = dateText(row.ends_on);
|
|
260
|
+
return {
|
|
261
|
+
id: Number(row.id),
|
|
262
|
+
delegatorId: Number(row.delegator_id),
|
|
263
|
+
delegatorName: row.delegator_name ? String(row.delegator_name) : null,
|
|
264
|
+
delegateId: Number(row.delegate_id),
|
|
265
|
+
delegateName: row.delegate_name ? String(row.delegate_name) : null,
|
|
266
|
+
startsOn,
|
|
267
|
+
endsOn,
|
|
268
|
+
note: row.note ? String(row.note) : null,
|
|
269
|
+
status: row.revoked_at
|
|
270
|
+
? 'revoked'
|
|
271
|
+
: endsOn < today
|
|
272
|
+
? 'ended'
|
|
273
|
+
: startsOn > today
|
|
274
|
+
? 'scheduled'
|
|
275
|
+
: 'active',
|
|
276
|
+
createdBy: row.created_by === null ? null : Number(row.created_by),
|
|
277
|
+
createdAt: new Date(row.created_at).toISOString(),
|
|
278
|
+
revokedAt: row.revoked_at ? new Date(row.revoked_at).toISOString() : null,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
now() {
|
|
282
|
+
return this.options.now?.() ?? new Date();
|
|
283
|
+
}
|
|
284
|
+
today() {
|
|
285
|
+
return calendarDate(this.now(), this.options.timeZone);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -6,7 +6,11 @@ import type { JsonValue } from '../resource/types.js';
|
|
|
6
6
|
import type { DomainEvent, Listener } from '../events/outbox.js';
|
|
7
7
|
import type { HttpPoster } from '../integrations/webhooks.js';
|
|
8
8
|
import type { Assignments } from '../collaboration/assignments.js';
|
|
9
|
+
import { type ActorLoader } from '../collaboration/shared.js';
|
|
9
10
|
import { type WorkflowDefinition } from './define_workflow.js';
|
|
11
|
+
import { type SlaEvaluation, type WorkflowSlaStatus } from './sla.js';
|
|
12
|
+
export { slaState } from './sla.js';
|
|
13
|
+
export type { SlaEvaluation, SlaState, WorkflowSlaStatus } from './sla.js';
|
|
10
14
|
export type WorkflowRunStatus = 'pending_definition' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled';
|
|
11
15
|
export type WorkflowRun = {
|
|
12
16
|
id: string;
|
|
@@ -31,6 +35,8 @@ export type WorkflowRun = {
|
|
|
31
35
|
step: string | null;
|
|
32
36
|
event: string;
|
|
33
37
|
actorName: string | null;
|
|
38
|
+
/** Set when the actor decided as a delegate (ADR 044). */
|
|
39
|
+
onBehalfOfName?: string | null;
|
|
34
40
|
detail: {
|
|
35
41
|
[key: string]: JsonValue;
|
|
36
42
|
};
|
|
@@ -42,7 +48,14 @@ export type WorkflowRun = {
|
|
|
42
48
|
title: string;
|
|
43
49
|
/** Set at a decision step: its outcomes in declaration order (#42). */
|
|
44
50
|
decision?: WorkflowDecisionForm;
|
|
51
|
+
/** The approver the viewer decides for as their delegate; null for their own approval. */
|
|
52
|
+
onBehalfOf?: {
|
|
53
|
+
id: number;
|
|
54
|
+
name: string | null;
|
|
55
|
+
} | null;
|
|
45
56
|
} | null;
|
|
57
|
+
/** The current step's SLA deadline while the run waits on approvers; null without one. */
|
|
58
|
+
sla?: WorkflowSlaStatus | null;
|
|
46
59
|
};
|
|
47
60
|
/** What an approver needs to take a decision at a decision step. */
|
|
48
61
|
export type WorkflowDecisionForm = {
|
|
@@ -60,6 +73,11 @@ export type WorkflowOptions = {
|
|
|
60
73
|
step: string;
|
|
61
74
|
}) => void | Promise<void>;
|
|
62
75
|
now?: () => Date;
|
|
76
|
+
/**
|
|
77
|
+
* The system time zone (IANA name, default UTC). Due dates (dueOn) and delegation
|
|
78
|
+
* ranges are calendar days in this zone (ADR 044).
|
|
79
|
+
*/
|
|
80
|
+
timeZone?: string;
|
|
63
81
|
};
|
|
64
82
|
/**
|
|
65
83
|
* Durable workflow engine over workflow_runs. Every step runs inside the run's
|
|
@@ -75,9 +93,7 @@ export declare class WorkflowEngine {
|
|
|
75
93
|
private actors;
|
|
76
94
|
private assignments;
|
|
77
95
|
private options;
|
|
78
|
-
constructor(db: Knex, registry: ResourceRegistry, resources: ResourceService, actors:
|
|
79
|
-
load(id: number): Promise<Actor>;
|
|
80
|
-
}, assignments: Assignments, definitions: readonly WorkflowDefinition[], options?: WorkflowOptions);
|
|
96
|
+
constructor(db: Knex, registry: ResourceRegistry, resources: ResourceService, actors: ActorLoader, assignments: Assignments, definitions: readonly WorkflowDefinition[], options?: WorkflowOptions);
|
|
81
97
|
register(definition: WorkflowDefinition): this;
|
|
82
98
|
/** The newest version of each workflow attached to a resource. */
|
|
83
99
|
private latestFor;
|
|
@@ -102,6 +118,21 @@ export declare class WorkflowEngine {
|
|
|
102
118
|
decide(runId: string, actor: Actor, decision: string, comment?: unknown): Promise<WorkflowRun>;
|
|
103
119
|
/** Administrators put a failed run back to its failed step. */
|
|
104
120
|
retry(runId: string, actorId: number): Promise<void>;
|
|
121
|
+
/**
|
|
122
|
+
* One pass of the `sla:` job family (ADR 044). Approvers whose deadline is near get one
|
|
123
|
+
* reminder; overdue approvals run their step's escalation policy once: mark overdue
|
|
124
|
+
* (tell the approvers), notify a target, or reassign to it. Every action happens under
|
|
125
|
+
* the run's row lock and is recorded in workflow_escalations, whose unique key per
|
|
126
|
+
* assignment and level makes a repeated or concurrent pass a no-op.
|
|
127
|
+
*/
|
|
128
|
+
evaluateSla(options?: {
|
|
129
|
+
limit?: number;
|
|
130
|
+
}): Promise<SlaEvaluation>;
|
|
131
|
+
private remind;
|
|
132
|
+
private escalate;
|
|
133
|
+
/** Records one SLA action per assignment and level; false when it was already recorded. */
|
|
134
|
+
private record;
|
|
135
|
+
private notifyDeadline;
|
|
105
136
|
/**
|
|
106
137
|
* Explicit version migration for runs that have not finished: `mapStep` returns
|
|
107
138
|
* the equivalent step name in the new version.
|
|
@@ -124,7 +155,11 @@ export declare class WorkflowEngine {
|
|
|
124
155
|
private fail;
|
|
125
156
|
private cancelRuns;
|
|
126
157
|
private context;
|
|
127
|
-
/**
|
|
158
|
+
/**
|
|
159
|
+
* Workflow writes are system writes attributed to the submitter, with history. They go
|
|
160
|
+
* through systemSave, so the resource validator, hooks, relation checks and the
|
|
161
|
+
* optimistic lock apply; a rejected write fails the step like any other step error.
|
|
162
|
+
*/
|
|
128
163
|
private updateRecord;
|
|
129
164
|
private cancelDocument;
|
|
130
165
|
private recipients;
|
|
@@ -132,6 +167,36 @@ export declare class WorkflowEngine {
|
|
|
132
167
|
private roleId;
|
|
133
168
|
private canView;
|
|
134
169
|
private log;
|
|
170
|
+
/**
|
|
171
|
+
* Opens one approval per approver. An approver with a delegation in force today is
|
|
172
|
+
* replaced by the delegate when the delegate may view the record (ADR 044); the row
|
|
173
|
+
* keeps the approver in on_behalf_of, so both see it while the delegation lasts.
|
|
174
|
+
* Returns the routed pairs for the run log.
|
|
175
|
+
*/
|
|
176
|
+
private openApprovals;
|
|
177
|
+
/** The SLA deadline of a step opening now, or null when the step declares none. */
|
|
178
|
+
private deadline;
|
|
179
|
+
private escalationTargets;
|
|
180
|
+
/**
|
|
181
|
+
* The approver's managers in the org tree: active holders of the role whose role is
|
|
182
|
+
* scoped to the approver's unit or, failing that, to the nearest ancestor unit.
|
|
183
|
+
*/
|
|
184
|
+
private managers;
|
|
185
|
+
/**
|
|
186
|
+
* The delegate an approver's approvals go to today, or null to keep them with the
|
|
187
|
+
* approver (ADR 044). Routing is one hop and only to someone who can act: never the
|
|
188
|
+
* person who started the run (no self-approval), never a delegate who is away and
|
|
189
|
+
* delegating in turn, and never a delegate who cannot view the record.
|
|
190
|
+
*/
|
|
191
|
+
private delegateFor;
|
|
192
|
+
/**
|
|
193
|
+
* Who is told about an open approval now: the delegate it was routed to while that
|
|
194
|
+
* delegation lasts; otherwise its approver, or the approver's current delegate when
|
|
195
|
+
* the approver is away today.
|
|
196
|
+
*/
|
|
197
|
+
private holder;
|
|
198
|
+
private userName;
|
|
199
|
+
private today;
|
|
135
200
|
private now;
|
|
136
201
|
}
|
|
137
202
|
/**
|