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.
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 +5 -3
  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
@@ -0,0 +1,268 @@
1
+ import { subject } from '@casl/ability';
2
+ import { fieldValue } from '../resource/values.js';
3
+ import { buildAbility } from '../auth/ability.js';
4
+ import { AdulaError, forbiddenAction } from '../admin/errors.js';
5
+ import { labelText, translate } from '../languages/catalog.js';
6
+ import { fieldLevel } from '../admin/resource/shared.js';
7
+ import { fromRow } from '../admin/contracts.js';
8
+ /** Most records one bulk request may change. */
9
+ export const BULK_ID_LIMIT = 100;
10
+ const BUILT_IN = ['delete', 'restore', 'submit', 'cancel'];
11
+ const KEY = /^[a-z][a-zA-Z0-9_]*$/;
12
+ /**
13
+ * Declares bulk actions for one resource. Register the result on the BulkActions service.
14
+ * Definitions are checked here for shape and against the resource when registered.
15
+ */
16
+ export function defineBulkActions(resource, actions) {
17
+ if (typeof resource !== 'string' || !resource)
18
+ throw new Error('Bulk actions need a resource');
19
+ const keys = new Set();
20
+ for (const action of actions) {
21
+ if (typeof action?.key !== 'string' || !KEY.test(action.key))
22
+ throw new Error(`${resource}: invalid bulk action key ${String(action?.key)}`);
23
+ if (BUILT_IN.includes(action.key))
24
+ throw new Error(`${resource}: ${action.key} is a built-in bulk action`);
25
+ if (keys.has(action.key))
26
+ throw new Error(`${resource}: duplicate bulk action ${action.key}`);
27
+ keys.add(action.key);
28
+ if (!action.label?.ar?.trim())
29
+ throw new Error(`${resource}.${action.key}: label.ar is required`);
30
+ if (action.confirm !== undefined && !action.confirm?.ar?.trim())
31
+ throw new Error(`${resource}.${action.key}: confirm.ar is required`);
32
+ if (!action.values ||
33
+ typeof action.values !== 'object' ||
34
+ Array.isArray(action.values) ||
35
+ !Object.keys(action.values).length)
36
+ throw new Error(`${resource}.${action.key}: values must set at least one field`);
37
+ }
38
+ return Object.freeze({ resource, actions: Object.freeze([...actions]) });
39
+ }
40
+ /**
41
+ * Runs one action over selected records. Every record runs in its own transaction
42
+ * through the ordinary paths (transition, restore, save), with the actor's per-row
43
+ * policy check and audit, so one refused row does not undo the others.
44
+ */
45
+ export class BulkActions {
46
+ registry;
47
+ resources;
48
+ options;
49
+ defined;
50
+ constructor(registry, resources, definitions = [], options = {}) {
51
+ this.registry = registry;
52
+ this.resources = resources;
53
+ this.options = options;
54
+ this.defined = BulkActions.validate(registry, definitions);
55
+ }
56
+ /**
57
+ * Checks bulk action sets against the registered resources: each set names a resource,
58
+ * keys are unique per resource and every value is a writable form field value. Call it
59
+ * when the application loads its definitions, so a bad definition fails at boot.
60
+ */
61
+ static validate(registry, definitions) {
62
+ const defined = new Map();
63
+ for (const set of definitions) {
64
+ const resource = registry.get(set.resource);
65
+ const actions = defined.get(resource.name) ?? new Map();
66
+ for (const action of set.actions) {
67
+ if (actions.has(action.key))
68
+ throw new Error(`${resource.name}: duplicate bulk action ${action.key}`);
69
+ for (const [key, value] of Object.entries(action.values)) {
70
+ const field = resource.fields[key];
71
+ if (!field || !resource.form.includes(key) || field.type === 'hasMany' || field.sequence)
72
+ throw new Error(`${resource.name}.${action.key}: ${key} is not a writable form field`);
73
+ try {
74
+ fieldValue(field, value);
75
+ }
76
+ catch (error) {
77
+ throw new Error(`${resource.name}.${action.key}.${key}: ${error.message}`);
78
+ }
79
+ }
80
+ actions.set(action.key, action);
81
+ }
82
+ defined.set(resource.name, actions);
83
+ }
84
+ return defined;
85
+ }
86
+ /**
87
+ * The actions the actor may offer on this resource's list (resource-level permission).
88
+ * 403 E_FORBIDDEN when the actor may not view the resource at all.
89
+ */
90
+ available(name, actor) {
91
+ const resource = this.registry.get(name);
92
+ const ability = buildAbility(actor.rules, this.registry.all());
93
+ const holds = (action) => resource.actions.includes(action) && ability.can(action, resource.name);
94
+ const options = [];
95
+ if (!resource.actions.includes('view') || !ability.can('view', resource.name))
96
+ throw forbiddenAction();
97
+ if (holds('delete'))
98
+ options.push(builtIn('delete'));
99
+ if (resource.submittable && holds('submit'))
100
+ options.push(builtIn('submit'));
101
+ if (resource.submittable && holds('cancel'))
102
+ options.push(builtIn('cancel'));
103
+ if (holds('delete'))
104
+ options.push(builtIn('restore'));
105
+ if (holds('update'))
106
+ for (const action of this.defined.get(resource.name)?.values() ?? [])
107
+ if (Object.keys(action.values).every((key) => ability.can('update', resource.name, key) &&
108
+ actor.permissionLevel >= fieldLevel(resource, key)))
109
+ options.push({
110
+ key: action.key,
111
+ label: labelText(action.label),
112
+ builtIn: false,
113
+ scope: 'records',
114
+ confirm: action.confirm ? labelText(action.confirm) : null,
115
+ destructive: Boolean(action.destructive),
116
+ });
117
+ return options;
118
+ }
119
+ async run(name, actor, request) {
120
+ const resource = this.registry.get(name);
121
+ const offered = this.available(name, actor);
122
+ const { action, ids, versions } = parse(request);
123
+ const known = BUILT_IN.includes(action) ||
124
+ Boolean(this.defined.get(resource.name)?.has(action));
125
+ if (!known)
126
+ throw new AdulaError(422, 'E_BULK', 'الإجراء الجماعي غير معروف');
127
+ if (!offered.some((option) => option.key === action))
128
+ throw forbiddenAction();
129
+ const result = { succeeded: [], failed: [] };
130
+ for (const id of ids) {
131
+ try {
132
+ await this.one(resource, actor, action, id, versions[id]);
133
+ result.succeeded.push(id);
134
+ }
135
+ catch (error) {
136
+ const failure = failureOf(error);
137
+ if (failure.code === 'E_BULK_ROW')
138
+ this.report(error, { resource: name, action, id });
139
+ result.failed.push({ id, ...failure });
140
+ }
141
+ }
142
+ return result;
143
+ }
144
+ async one(resource, actor, action, id, version) {
145
+ const name = resource.name;
146
+ if (action === 'restore')
147
+ return this.resources.restore(name, id, actor);
148
+ if (action === 'delete' || action === 'submit' || action === 'cancel')
149
+ return this.resources.transition(name, id, actor, action, version);
150
+ const definition = this.defined.get(name).get(action);
151
+ const ability = buildAbility(actor.rules, this.registry.all());
152
+ // Read and write under one row lock, so a concurrent edit between reading the stored
153
+ // values and saving them cannot be overwritten. Authorization stays in save().
154
+ return this.resources.transaction(async (trx) => {
155
+ // Authorize the row (organization scope and update conditions) before locking it, so
156
+ // an actor cannot hold locks on records outside their reach.
157
+ await this.resources.access(name, id, actor, 'update', trx);
158
+ const row = await trx(name).where({ id }).whereNull('deleted_at').forUpdate().first();
159
+ const stored = row ? fromRow(row, resource) : {};
160
+ const after = { ...stored, ...definition.values };
161
+ // The edit form resubmits the stored values the actor may write on this record (the
162
+ // same per-record checks save() applies); the action's values replace their fields,
163
+ // so validation sees a complete record. Attachments resend their stored id, which
164
+ // save() treats as unchanged.
165
+ const input = {};
166
+ for (const key of resource.form) {
167
+ const field = resource.fields[key];
168
+ if (field.type === 'hasMany' ||
169
+ field.sequence ||
170
+ !(key in stored) ||
171
+ !ability.can('update', subject(name, stored), key) ||
172
+ !ability.can('update', subject(name, after), key) ||
173
+ actor.permissionLevel < fieldLevel(resource, key))
174
+ continue;
175
+ input[key] = stored[key];
176
+ }
177
+ Object.assign(input, definition.values);
178
+ if (resource.version)
179
+ input.version = version;
180
+ return this.resources.save(name, actor, input, id, trx);
181
+ });
182
+ }
183
+ report(error, context) {
184
+ if (this.options.report)
185
+ return this.options.report(error, context);
186
+ // No record values: only where it happened and what kind of error it was.
187
+ console.error('Bulk action row failed', {
188
+ ...context,
189
+ error: error instanceof Error ? error.name : typeof error,
190
+ code: error?.code,
191
+ });
192
+ }
193
+ }
194
+ function builtIn(key) {
195
+ return {
196
+ key,
197
+ label: translate(`list.bulk.${key}`),
198
+ builtIn: true,
199
+ scope: key === 'restore' ? 'trash' : 'records',
200
+ confirm: key === 'restore' ? null : translate(`list.bulk.${key}Confirm`),
201
+ destructive: key === 'delete' || key === 'cancel',
202
+ };
203
+ }
204
+ function parse(request) {
205
+ const invalid = () => new AdulaError(422, 'E_BULK', 'اختر من سجل واحد إلى 100 سجل لتنفيذ الإجراء الجماعي');
206
+ if (!request || typeof request !== 'object')
207
+ throw invalid();
208
+ const action = request.action;
209
+ if (typeof action !== 'string' || !KEY.test(action))
210
+ throw new AdulaError(422, 'E_BULK', 'الإجراء الجماعي غير معروف');
211
+ const positive = (value) => {
212
+ const number = typeof value === 'string' && /^\d{1,10}$/.test(value) ? Number(value) : value;
213
+ return Number.isSafeInteger(number) && Number(number) > 0 && Number(number) <= 2147483647
214
+ ? Number(number)
215
+ : null;
216
+ };
217
+ if (!Array.isArray(request.ids) || !request.ids.length || request.ids.length > BULK_ID_LIMIT)
218
+ throw invalid();
219
+ const ids = request.ids.map(positive);
220
+ if (ids.some((id) => id === null) || new Set(ids).size !== ids.length)
221
+ throw invalid();
222
+ const versions = {};
223
+ if (request.versions !== undefined && request.versions !== null) {
224
+ if (typeof request.versions !== 'object' || Array.isArray(request.versions))
225
+ throw invalid();
226
+ for (const [key, value] of Object.entries(request.versions)) {
227
+ const id = positive(key);
228
+ const version = typeof value === 'string' && /^\d{1,10}$/.test(value) ? Number(value) : value;
229
+ if (id === null || !Number.isSafeInteger(version))
230
+ throw invalid();
231
+ versions[id] = version;
232
+ }
233
+ }
234
+ return { action, ids: ids, versions };
235
+ }
236
+ /** Catalog text for row refusals whose service message is a developer (English) string. */
237
+ const ROW_MESSAGES = {
238
+ E_DOCUMENT_STATE: 'errors.E_DOCUMENT_STATE',
239
+ E_DOCUMENT_LOCKED: 'errors.E_DOCUMENT_LOCKED.2',
240
+ };
241
+ /** The code and Arabic message of one refused row; unexpected errors stay generic. */
242
+ function failureOf(error) {
243
+ if (error instanceof AdulaError)
244
+ return {
245
+ code: error.code,
246
+ // Catalog or Arabic text is user text; a developer (English) message is replaced
247
+ // by the code's catalog message.
248
+ message: error.messageKey || /[؀-ۿ]/.test(error.message)
249
+ ? error.message
250
+ : translate(ROW_MESSAGES[error.code] ?? 'errors.E_BULK_ROW'),
251
+ };
252
+ const code = error?.code;
253
+ if (code === 'E_VALIDATION_ERROR') {
254
+ // VineJS messages are already in the request language (installCatalogMessages).
255
+ const [first] = (error.messages ?? []);
256
+ return {
257
+ code: 'E_VALIDATION',
258
+ message: typeof first?.message === 'string' && first.message
259
+ ? first.message
260
+ : translate('validation.invalid'),
261
+ };
262
+ }
263
+ if (code === '23505')
264
+ return { code: 'E_DUPLICATE', message: translate('errors.E_DUPLICATE') };
265
+ if (code === '23503')
266
+ return { code: 'E_RELATION', message: translate('errors.E_RELATION') };
267
+ return { code: 'E_BULK_ROW', message: translate('errors.E_BULK_ROW') };
268
+ }
@@ -0,0 +1,96 @@
1
+ import type { Knex } from 'knex';
2
+ import type { ResourceRegistry } from '../resource/registry.js';
3
+ import type { JsonValue, Label } from '../resource/types.js';
4
+ import type { Conditions } from '../auth/conditions.js';
5
+ import { type Actor } from '../auth/ability.js';
6
+ import type { ResourceService } from '../admin/resource_service.js';
7
+ export type DashboardMeasure = 'count' | {
8
+ sum: string;
9
+ };
10
+ export type DashboardWidgetDefinition = {
11
+ /** Unique within the dashboard: /^[a-z][a-zA-Z0-9_]*$/. */
12
+ key: string;
13
+ label: Label;
14
+ resource: string;
15
+ measure: DashboardMeasure;
16
+ /** One queryable field (or docStatus / orgUnitId) to group the measure by. */
17
+ groupBy?: string;
18
+ /** List filters, including the operators of ADR 046. */
19
+ filters?: Record<string, unknown>;
20
+ /** Role-rule style conditions, as in ResourceService.aggregate. */
21
+ where?: Conditions;
22
+ };
23
+ export type DashboardDefinition = {
24
+ /** /^[a-z][a-z0-9_]*$/, used in the URL /dashboards/:name. */
25
+ name: string;
26
+ label: Label;
27
+ description?: Label;
28
+ widgets: DashboardWidgetDefinition[];
29
+ };
30
+ export type DashboardSummary = {
31
+ name: string;
32
+ label: string;
33
+ };
34
+ export type DashboardGroupRow = {
35
+ value: JsonValue;
36
+ label: string;
37
+ measure: number | string | null;
38
+ };
39
+ export type DashboardWidgetResult = {
40
+ key: string;
41
+ label: string;
42
+ resource: string;
43
+ /** The list page of the widget's resource. */
44
+ href: string;
45
+ measure: DashboardMeasure;
46
+ /**
47
+ * count: an integer; integer, decimal and percent: a decimal string total (percent points
48
+ * for percent); money: minor units as a string.
49
+ */
50
+ format: DashboardFormat;
51
+ kind: 'total' | 'grouped';
52
+ groupBy: string | null;
53
+ value?: number | string | null;
54
+ rows?: DashboardGroupRow[];
55
+ truncated: boolean;
56
+ };
57
+ export type DashboardResult = {
58
+ name: string;
59
+ label: string;
60
+ description: string | null;
61
+ widgets: DashboardWidgetResult[];
62
+ };
63
+ /** How a widget's measure reads: a count, or the sum's field type. */
64
+ export type DashboardFormat = 'count' | 'integer' | 'money' | 'decimal' | 'percent';
65
+ /** Declares an indicators page outside the resource type (ADR 046). */
66
+ export declare function defineDashboard(definition: DashboardDefinition): DashboardDefinition;
67
+ /**
68
+ * Renders dashboards as the viewer: every widget runs through ResourceService.aggregate
69
+ * with the viewer's rules, scope and field access, and a widget the viewer cannot read
70
+ * is omitted rather than failed.
71
+ */
72
+ export declare class Dashboards {
73
+ private db;
74
+ private registry;
75
+ private resources;
76
+ private dashboards;
77
+ constructor(db: Knex, registry: ResourceRegistry, resources: ResourceService, definitions?: readonly DashboardDefinition[]);
78
+ /**
79
+ * Checks dashboards against the registered resources: unique names, existing widget
80
+ * resources, integer, money, decimal or percent totals, groupable fields and filter or condition keys
81
+ * that exist on the resource. Call it when the application loads its definitions, so a
82
+ * bad definition fails at boot.
83
+ */
84
+ static validate(registry: ResourceRegistry, definitions: readonly DashboardDefinition[]): Map<string, DashboardDefinition>;
85
+ /**
86
+ * Whether the actor may read this widget: the resource is viewable and every field it
87
+ * totals, groups, filters or conditions on is one the actor may query.
88
+ */
89
+ private readable;
90
+ /** Dashboards with at least one widget the actor may read. */
91
+ list(actor: Actor): DashboardSummary[];
92
+ render(name: string, actor: Actor): Promise<DashboardResult>;
93
+ private widget;
94
+ /** Display labels of one grouped field: lookups, titles, user names, «نعم/لا». */
95
+ private labeller;
96
+ }
@@ -0,0 +1,241 @@
1
+ import { buildAbility } from '../auth/ability.js';
2
+ import { canQueryField } from '../admin/resource/shared.js';
3
+ import { AdulaError, notFound } from '../admin/errors.js';
4
+ import { labelText, translate } from '../languages/catalog.js';
5
+ import { cellText } from '../admin/resource/export.js';
6
+ /** Field types a widget may total, as ResourceService.aggregate sums them. */
7
+ const SUMMABLE = ['integer', 'money', 'decimal', 'percent'];
8
+ const NAME = /^[a-z][a-z0-9_]*$/;
9
+ const KEY = /^[a-z][a-zA-Z0-9_]*$/;
10
+ /** Declares an indicators page outside the resource type (ADR 046). */
11
+ export function defineDashboard(definition) {
12
+ const { name } = definition ?? {};
13
+ if (typeof name !== 'string' || !NAME.test(name))
14
+ throw new Error(`Invalid dashboard name: ${String(name)}`);
15
+ if (!definition.label?.ar?.trim())
16
+ throw new Error(`${name}: label.ar is required`);
17
+ if (definition.description !== undefined && !definition.description?.ar?.trim())
18
+ throw new Error(`${name}: description.ar is required`);
19
+ if (!Array.isArray(definition.widgets) || !definition.widgets.length)
20
+ throw new Error(`${name}: a dashboard needs at least one widget`);
21
+ const keys = new Set();
22
+ for (const widget of definition.widgets) {
23
+ if (typeof widget?.key !== 'string' || !KEY.test(widget.key))
24
+ throw new Error(`${name}: invalid widget key ${String(widget?.key)}`);
25
+ if (keys.has(widget.key))
26
+ throw new Error(`${name}: duplicate widget ${widget.key}`);
27
+ keys.add(widget.key);
28
+ const where = `${name}.${widget.key}`;
29
+ if (!widget.label?.ar?.trim())
30
+ throw new Error(`${where}: label.ar is required`);
31
+ if (typeof widget.resource !== 'string' || !widget.resource)
32
+ throw new Error(`${where}: resource is required`);
33
+ const measure = widget.measure;
34
+ if (measure !== 'count' &&
35
+ !(measure &&
36
+ typeof measure === 'object' &&
37
+ Object.keys(measure).length === 1 &&
38
+ typeof measure.sum === 'string'))
39
+ throw new Error(`${where}: measure is 'count' or { sum: field }`);
40
+ if (widget.groupBy !== undefined && typeof widget.groupBy !== 'string')
41
+ throw new Error(`${where}: groupBy is one field name`);
42
+ for (const [option, value] of [
43
+ ['filters', widget.filters],
44
+ ['where', widget.where],
45
+ ])
46
+ if (value !== undefined && (!value || typeof value !== 'object' || Array.isArray(value)))
47
+ throw new Error(`${where}: ${option} must be an object`);
48
+ }
49
+ return Object.freeze({ ...definition, widgets: Object.freeze([...definition.widgets]) });
50
+ }
51
+ /**
52
+ * Renders dashboards as the viewer: every widget runs through ResourceService.aggregate
53
+ * with the viewer's rules, scope and field access, and a widget the viewer cannot read
54
+ * is omitted rather than failed.
55
+ */
56
+ export class Dashboards {
57
+ db;
58
+ registry;
59
+ resources;
60
+ dashboards;
61
+ constructor(db, registry, resources, definitions = []) {
62
+ this.db = db;
63
+ this.registry = registry;
64
+ this.resources = resources;
65
+ this.dashboards = Dashboards.validate(registry, definitions);
66
+ }
67
+ /**
68
+ * Checks dashboards against the registered resources: unique names, existing widget
69
+ * resources, integer, money, decimal or percent totals, groupable fields and filter or condition keys
70
+ * that exist on the resource. Call it when the application loads its definitions, so a
71
+ * bad definition fails at boot.
72
+ */
73
+ static validate(registry, definitions) {
74
+ const dashboards = new Map();
75
+ for (const dashboard of definitions) {
76
+ if (dashboards.has(dashboard.name))
77
+ throw new Error(`Duplicate dashboard: ${dashboard.name}`);
78
+ for (const widget of dashboard.widgets) {
79
+ const resource = registry.get(widget.resource);
80
+ const where = `${dashboard.name}.${widget.key}`;
81
+ if (typeof widget.measure === 'object') {
82
+ const field = resource.fields[widget.measure.sum];
83
+ if (!field || !SUMMABLE.includes(field.type))
84
+ throw new Error(`${where}: ${widget.measure.sum} is not an integer, money, decimal or percent field`);
85
+ }
86
+ if (widget.groupBy !== undefined && !groupable(resource, widget.groupBy))
87
+ throw new Error(`${where}: ${widget.groupBy} cannot be grouped`);
88
+ for (const key of Object.keys(widget.filters ?? {}))
89
+ if (!Object.hasOwn(resource.fields, key) || !resource.fields[key].filterable)
90
+ throw new Error(`${where}: ${key} is not a filterable field`);
91
+ for (const key of Object.keys(widget.where ?? {}))
92
+ if (!groupable(resource, key))
93
+ throw new Error(`${where}: ${key} cannot be a condition`);
94
+ }
95
+ dashboards.set(dashboard.name, dashboard);
96
+ }
97
+ return dashboards;
98
+ }
99
+ /**
100
+ * Whether the actor may read this widget: the resource is viewable and every field it
101
+ * totals, groups, filters or conditions on is one the actor may query.
102
+ */
103
+ readable(widget, actor, ability) {
104
+ const resource = this.registry.get(widget.resource);
105
+ const standard = new Set(['docStatus', 'orgUnitId']);
106
+ const fields = [
107
+ ...(typeof widget.measure === 'object' ? [widget.measure.sum] : []),
108
+ ...(widget.groupBy ? [widget.groupBy] : []),
109
+ ...Object.keys(widget.filters ?? {}),
110
+ ...Object.keys(widget.where ?? {}),
111
+ ].filter((key) => !standard.has(key));
112
+ return (resource.actions.includes('view') &&
113
+ ability.can('view', resource.name) &&
114
+ (!resource.scoped || actor.orgPaths.length > 0) &&
115
+ fields.every((key) => canQueryField(resource, actor, ability, key)));
116
+ }
117
+ /** Dashboards with at least one widget the actor may read. */
118
+ list(actor) {
119
+ const ability = buildAbility(actor.rules, this.registry.all());
120
+ return [...this.dashboards.values()]
121
+ .filter((dashboard) => dashboard.widgets.some((widget) => this.readable(widget, actor, ability)))
122
+ .map((dashboard) => ({ name: dashboard.name, label: labelText(dashboard.label) }));
123
+ }
124
+ async render(name, actor) {
125
+ const dashboard = typeof name === 'string' ? this.dashboards.get(name) : undefined;
126
+ if (!dashboard)
127
+ throw notFound('لوحة المؤشرات غير موجودة');
128
+ const widgets = [];
129
+ for (const widget of dashboard.widgets) {
130
+ const rendered = await this.widget(widget, actor);
131
+ if (rendered)
132
+ widgets.push(rendered);
133
+ }
134
+ // A dashboard whose widgets are all hidden from the viewer does not exist for them.
135
+ if (!widgets.length)
136
+ throw notFound('لوحة المؤشرات غير موجودة');
137
+ return {
138
+ name: dashboard.name,
139
+ label: labelText(dashboard.label),
140
+ description: dashboard.description ? labelText(dashboard.description) : null,
141
+ widgets,
142
+ };
143
+ }
144
+ async widget(widget, actor) {
145
+ const resource = this.registry.get(widget.resource);
146
+ // A widget filtered or conditioned on a field the viewer may not query is omitted,
147
+ // never a refusal of the whole page.
148
+ if (!this.readable(widget, actor, buildAbility(actor.rules, this.registry.all())))
149
+ return null;
150
+ const sum = typeof widget.measure === 'object' ? widget.measure.sum : null;
151
+ let aggregate;
152
+ try {
153
+ aggregate = await this.resources.aggregate(resource.name, actor, {
154
+ groupBy: widget.groupBy ? [widget.groupBy] : [],
155
+ count: sum === null,
156
+ sum: sum ? [sum] : [],
157
+ filters: widget.filters,
158
+ where: widget.where,
159
+ });
160
+ }
161
+ catch (error) {
162
+ if (error instanceof AdulaError && error.status === 403)
163
+ return null;
164
+ throw error;
165
+ }
166
+ const measureOf = (row) => sum === null ? (row.count ?? 0) : (row.sum?.[sum] ?? null);
167
+ const base = {
168
+ key: widget.key,
169
+ label: labelText(widget.label),
170
+ resource: resource.name,
171
+ href: `/resources/${resource.name}`,
172
+ measure: widget.measure,
173
+ format: (sum === null ? 'count' : resource.fields[sum].type),
174
+ groupBy: widget.groupBy ?? null,
175
+ truncated: aggregate.truncated,
176
+ };
177
+ if (!widget.groupBy) {
178
+ const [row] = aggregate.rows;
179
+ return { ...base, kind: 'total', value: row ? measureOf(row) : sum === null ? 0 : null };
180
+ }
181
+ const key = widget.groupBy;
182
+ const values = aggregate.rows.map((row) => row.group[key] ?? null);
183
+ const label = await this.labeller(resource, key, values, actor);
184
+ return {
185
+ ...base,
186
+ kind: 'grouped',
187
+ rows: aggregate.rows.map((row, index) => ({
188
+ value: values[index],
189
+ label: label(values[index]),
190
+ measure: measureOf(row),
191
+ })),
192
+ };
193
+ }
194
+ /** Display labels of one grouped field: lookups, titles, user names, «نعم/لا». */
195
+ async labeller(resource, key, values, actor) {
196
+ const none = translate('list.value.none');
197
+ const ids = [
198
+ ...new Set(values.filter((value) => typeof value === 'number')),
199
+ ].filter((id) => Number.isSafeInteger(id) && id > 0);
200
+ if (key === 'docStatus')
201
+ return (value) => value === null ? none : translate(`list.status.${Number(value)}`);
202
+ if (key === 'orgUnitId') {
203
+ const names = new Map();
204
+ if (ids.length)
205
+ for (const row of await this.db('org_units').whereIn('id', ids).select('id', 'name'))
206
+ names.set(Number(row.id), String(row.name));
207
+ return (value) => value === null ? none : (names.get(Number(value)) ?? `#${value}`);
208
+ }
209
+ const field = resource.fields[key];
210
+ const titles = new Map();
211
+ const lookups = new Map();
212
+ if (field.type === 'belongsTo' && ids.length)
213
+ for (const [id, title] of await this.resources.titles(field.resource, ids, actor))
214
+ titles.set(id, title);
215
+ if (field.type === 'user' && ids.length)
216
+ // A display name only, as list() shows it: readers need not read account e-mails.
217
+ for (const row of await this.db('users').whereIn('id', ids).select('id', 'full_name'))
218
+ if (row.full_name)
219
+ titles.set(Number(row.id), String(row.full_name));
220
+ if (field.type === 'lookup')
221
+ for (const row of await this.db('lookups')
222
+ .where('group', field.group)
223
+ .select('key', 'label_ar'))
224
+ lookups.set(String(row.key), String(row.label_ar));
225
+ return (value) => value === null || value === ''
226
+ ? none
227
+ : cellText(field, value, {
228
+ lookup: (_, entry) => lookups.get(entry),
229
+ title: (id) => titles.get(id),
230
+ });
231
+ }
232
+ }
233
+ function groupable(resource, key) {
234
+ if (key === 'docStatus')
235
+ return Boolean(resource.submittable);
236
+ if (key === 'orgUnitId')
237
+ return resource.scoped;
238
+ const field = Object.hasOwn(resource.fields, key) ? resource.fields[key] : undefined;
239
+ // As aggregate(): a manyToMany field has no single value to group or compare.
240
+ return Boolean(field) && !['hasMany', 'manyToMany', 'json', 'attachment'].includes(field.type);
241
+ }
@@ -75,7 +75,7 @@ export function createResourceTools(resolveRuntime) {
75
75
  code: 'E_VALIDATION_ERROR',
76
76
  messages: error.messages,
77
77
  }));
78
- if (['23505', '23503'].includes(error?.code ?? ''))
78
+ if (['23505', '23503', '23502'].includes(error?.code ?? ''))
79
79
  return context.response.error(JSON.stringify({
80
80
  status: 422,
81
81
  code: 'E_CONSTRAINT',
@@ -1,5 +1,22 @@
1
- import type { Field, Resource, ResourceInput } from './types.js';
1
+ import type { Field, Label, Resource, ResourceInput } from './types.js';
2
2
  export declare function identifier(value: string): string;
3
3
  /** camelCase field key → snake_case column; validated once and memoized (hot in row mapping). */
4
4
  export declare function columnName(name: string): string;
5
+ /**
6
+ * The join table of a manyToMany field: `table`, or `<owner>_<key in snake_case>`. Its
7
+ * columns are `<owner>_id` and `<target>_id` (`related_id` when a resource links itself).
8
+ */
9
+ export declare function joinTable(owner: string, key: string, field: {
10
+ resource: string;
11
+ table?: string;
12
+ }): {
13
+ table: string;
14
+ owner: string;
15
+ target: string;
16
+ };
17
+ /**
18
+ * Arabic is required; every other language is optional, but a language a label
19
+ * names must have text (an empty `en: ''` is a mistake, not an omission).
20
+ */
21
+ export declare function assertLabel(label: Label | undefined, context: string): void;
5
22
  export declare function defineResource<const F extends Record<string, Field>>(input: ResourceInput<F>): ResourceInput<F> & Resource;