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
@@ -1,39 +1,33 @@
1
- import { subject } from '@casl/ability';
2
- import { columnName } from '../resource/define_resource.js';
3
- import { buildAbility, canRecord, inOrgScope, } from '../auth/ability.js';
4
- import { accessibleBy, conditionSql } from '../auth/sql.js';
5
- import { fromRow, jsonValue, selectedFields, serialize, systemInput, writableInput, } from './contracts.js';
6
- import { resolveActorConditions } from '../auth/conditions.js';
7
- import { AdulaError } from './errors.js';
8
- import { sequence } from '../services/settings.js';
9
- import { recordMutation } from '../events/record_mutation.js';
10
- import { formatTitle, titleFields } from './record_title.js';
11
- import { fieldValue } from '../resource/values.js';
12
- import { claimAttachment, isAttachmentId, loadAttachments, releaseAttachment, } from '../attachments/attachment_service.js';
13
- /** Per-process cache of planner row estimates for identical list queries. */
14
- const estimates = new Map();
15
- const ESTIMATE_TTL_MS = 30_000;
16
- const ESTIMATE_CACHE_LIMIT = 500;
17
- const AGGREGATE_GROUP_LIMIT = 1000;
1
+ import * as read from './resource/read.js';
2
+ import * as query from './resource/query.js';
3
+ import * as form from './resource/editor.js';
4
+ import * as write from './resource/write.js';
5
+ import { transition } from './resource/lifecycle.js';
6
+ import { restore } from './resource/trash.js';
7
+ import { exportCsv } from './resource/export.js';
8
+ export { canQueryField } from './resource/shared.js';
9
+ export { EXPORT_ROW_LIMIT } from './resource/export.js';
18
10
  /**
19
- * Whether an actor may sort, filter or search by a field. Querying reveals values
20
- * indirectly, so it needs unconditional view access at the field's level.
11
+ * Authorized reads and writes of registered resources. The work is done by the modules
12
+ * under ./resource (query, read, editor, write, lifecycle); this class keeps the public
13
+ * surface and hands them its database and registry.
21
14
  */
22
- export function canQueryField(resource, actor, ability, key) {
23
- const level = Math.max(resource.fields[key].permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0);
24
- // Conditional field rules cannot safely authorize a global sort/search.
25
- return (actor.permissionLevel >= level &&
26
- ability.can('view', resource.name, key) &&
27
- !ability.rules.some((rule) => rule.conditions &&
28
- (!rule.fields || rule.fields.includes(key)) &&
29
- (rule.subject === resource.name || rule.subject === 'all')));
30
- }
31
15
  export class ResourceService {
32
16
  db;
33
17
  registry;
34
- constructor(db, registry) {
18
+ context;
19
+ /** `attachments.pdfPreview: false` reports PDFs as download-only in summaries (ADR 047). */
20
+ constructor(db, registry, options = {}) {
35
21
  this.db = db;
36
22
  this.registry = registry;
23
+ this.context = { db, registry, attachments: options.attachments };
24
+ }
25
+ /**
26
+ * Runs work in one database transaction; pass the transaction to save(), transition(),
27
+ * restore() or amend() so several reads and writes commit or roll back together.
28
+ */
29
+ async transaction(work) {
30
+ return this.db.transaction(work);
37
31
  }
38
32
  /** The Arabic label of a registered resource, for notifications and titles. */
39
33
  label(name) {
@@ -41,304 +35,24 @@ export class ResourceService {
41
35
  }
42
36
  /** Project navigation is derived from registered resources and the current actor. */
43
37
  navigation(actor) {
44
- const ability = buildAbility(actor.rules, this.registry.all());
45
- const children = new Set(this.registry
46
- .all()
47
- .flatMap((resource) => Object.values(resource.fields).flatMap((field) => field.type === 'hasMany' ? [field.resource] : [])));
48
- return this.registry
49
- .all()
50
- .filter((resource) => !children.has(resource.name) &&
51
- resource.actions.includes('view') &&
52
- (!resource.scoped || actor.orgPaths.length > 0) &&
53
- ability.can('view', resource.name))
54
- .map((resource) => ({
55
- name: resource.name,
56
- label: resource.label.ar,
57
- href: `/resources/${resource.name}`,
58
- module: this.registry.owner(resource.name),
59
- moduleLabel: this.registry
60
- .modules()
61
- .find((module) => module.name === this.registry.owner(resource.name))?.label.ar ??
62
- this.registry.owner(resource.name),
63
- }));
38
+ return read.navigation(this.context, actor);
64
39
  }
65
40
  describe(name, actor) {
66
- const resource = this.registry.get(name);
67
- const ability = this.authorizeAction(resource, actor, 'view');
68
- const serialized = new Set(resource.serialize ?? [...resource.list, ...resource.show]);
69
- const fields = Object.entries(resource.fields)
70
- .filter(([key, field]) => serialized.has(key) &&
71
- actor.permissionLevel >=
72
- Math.max(field.permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0) &&
73
- ability.can('view', name, key))
74
- .map(([key, field]) => ({
75
- ...field,
76
- key,
77
- sortable: Boolean(field.sortable && this.canQueryField(resource, actor, ability, key)),
78
- filterable: Boolean(field.filterable && this.canQueryField(resource, actor, ability, key)),
79
- }));
80
- const visible = new Set(fields.map((field) => field.key));
81
- const searchable = Object.entries(resource.fields).filter(([, field]) => field.searchable);
82
- return {
83
- name,
84
- label: resource.label.ar,
85
- recordLabel: resource.recordLabel?.ar ?? null,
86
- createLabel: resource.createLabel?.ar ?? null,
87
- fields,
88
- list: resource.list.filter((key) => visible.has(key)),
89
- show: resource.show.filter((key) => visible.has(key)),
90
- searchable: searchable.length > 0 &&
91
- searchable.every(([key]) => this.canQueryField(resource, actor, ability, key)),
92
- canCreate: resource.actions.includes('create') && ability.can('create', name),
93
- scoped: resource.scoped,
94
- submittable: Boolean(resource.submittable),
95
- };
96
- }
97
- permissions(resource, record, actor, ability) {
98
- return Object.fromEntries(resource.actions.map((action) => [
99
- action,
100
- canRecord(ability, actor, resource, action, record) &&
101
- (!resource.submittable ||
102
- !['update', 'delete', 'submit'].includes(action) ||
103
- record.docStatus === 0) &&
104
- (action !== 'cancel' || (resource.submittable && record.docStatus === 1)) &&
105
- (action !== 'amend' || (resource.submittable && record.docStatus === 2)),
106
- ]));
107
- }
108
- normalizeValues(resource, record) {
109
- for (const [key, field] of Object.entries(resource.fields)) {
110
- if (!(key in record))
111
- continue;
112
- try {
113
- record[key] = fieldValue(field, record[key]);
114
- }
115
- catch (error) {
116
- throw new AdulaError(422, 'E_FIELD_VALUE', `${key}: ${error.message}`);
117
- }
118
- }
119
- }
120
- /** Stored attachment ids become summaries for readers; copies keep policy checks on raw rows. */
121
- async hydrate(db, resource, records) {
122
- const keys = Object.keys(resource.fields).filter((key) => resource.fields[key].type === 'attachment');
123
- if (!keys.length || !records.length)
124
- return records;
125
- const ids = records.flatMap((record) => keys.map((key) => record[key]).filter(isAttachmentId));
126
- const summaries = await loadAttachments(db, ids);
127
- return records.map((record) => {
128
- const copy = { ...record };
129
- for (const key of keys)
130
- if (key in copy)
131
- copy[key] = isAttachmentId(copy[key]) ? (summaries.get(copy[key]) ?? null) : null;
132
- return copy;
133
- });
134
- }
135
- async hydrateOne(db, resource, record) {
136
- const [hydrated] = await this.hydrate(db, resource, [record]);
137
- return hydrated;
138
- }
139
- authorizeAction(resource, actor, action) {
140
- const ability = buildAbility(actor.rules, this.registry.all());
141
- if (!resource.actions.includes(action) || !ability.can(action, resource.name))
142
- throw new AdulaError(403, 'E_FORBIDDEN', 'ليس لديك صلاحية لهذا الإجراء');
143
- for (const rule of ability.rulesFor(action, resource.name))
144
- conditionSql(rule.conditions, resource);
145
- return ability;
146
- }
147
- scopedQuery(db, resource, actor) {
148
- const query = db(`${resource.name} as r`).whereNull('r.deleted_at');
149
- if (resource.scoped) {
150
- query.join('org_units as ou', 'ou.id', 'r.org_unit_id').where((scope) => {
151
- if (!actor.orgPaths.length)
152
- scope.whereRaw('FALSE');
153
- actor.orgPaths.forEach((path) => scope.orWhereRaw('ou.path <@ ?::ltree', [path]));
154
- });
155
- }
156
- return query;
157
- }
158
- columns(resource, ability, write = false, extra = []) {
159
- return selectedFields(resource, ability, { write, extra }).map((key) => `r.${resource.fields[key]?.column ?? columnName(key)}`);
160
- }
161
- async find(db, resource, actor, ability, id, lock = false) {
162
- const query = this.scopedQuery(db, resource, actor)
163
- .where('r.id', id)
164
- .select(this.columns(resource, ability, lock));
165
- if (resource.scoped)
166
- query.select('ou.path as org_path');
167
- if (lock)
168
- query.forUpdate('r');
169
- const row = await query.first();
170
- if (!row)
171
- throw new AdulaError(404, 'E_NOT_FOUND', 'السجل غير موجود');
172
- return fromRow(row, resource);
173
- }
174
- /** A live record regardless of any actor's scope, for system writes. */
175
- async findAny(db, resource, id, lock = false) {
176
- const query = db(`${resource.name} as r`).whereNull('r.deleted_at').where('r.id', id);
177
- query.select(selectedFields(resource, buildAbility([], []), { write: true }).map((key) => `r.${resource.fields[key]?.column ?? columnName(key)}`));
178
- if (resource.scoped)
179
- query.leftJoin('org_units as ou', 'ou.id', 'r.org_unit_id').select('ou.path as org_path');
180
- if (lock)
181
- query.forUpdate('r');
182
- const row = await query.first();
183
- if (!row)
184
- throw new AdulaError(404, 'E_NOT_FOUND', 'السجل غير موجود');
185
- return fromRow(row, resource);
186
- }
187
- requireRecord(ability, actor, resource, action, record) {
188
- if (resource.scoped && !inOrgScope(record.orgPath, actor.orgPaths))
189
- throw new AdulaError(404, 'E_NOT_FOUND', 'السجل غير موجود');
190
- if (!canRecord(ability, actor, resource, action, record))
191
- throw new AdulaError(403, 'E_FORBIDDEN', 'ليس لديك صلاحية لهذا الإجراء');
41
+ return read.describe(this.context, name, actor);
192
42
  }
193
43
  /**
194
44
  * Authorizes one record for collaboration features (comments, tags, assignments...).
195
45
  * Scope and conditional rules apply exactly as for show/update.
196
46
  */
197
47
  async access(name, id, actor, action = 'view', db = this.db) {
198
- let resource;
199
- try {
200
- resource = this.registry.get(name);
201
- }
202
- catch {
203
- throw new AdulaError(404, 'E_NOT_FOUND', 'الكيان غير موجود');
204
- }
205
- if (!Number.isSafeInteger(id) || id <= 0)
206
- throw new AdulaError(404, 'E_NOT_FOUND', 'السجل غير موجود');
207
- const ability = this.authorizeAction(resource, actor, action);
208
- const record = await this.find(db, resource, actor, ability, id);
209
- this.requireRecord(ability, actor, resource, action, record);
210
- return { resource, record, ability };
48
+ return read.access(this.context, name, id, actor, action, db);
211
49
  }
212
50
  /** Whether a (possibly other) actor may perform an action on a record; never throws for denial. */
213
51
  async permits(name, id, actor, action = 'view') {
214
- try {
215
- await this.access(name, id, actor, action);
216
- return true;
217
- }
218
- catch (error) {
219
- if (error instanceof AdulaError && [403, 404].includes(error.status))
220
- return false;
221
- throw error;
222
- }
52
+ return read.permits(this.context, name, id, actor, action);
223
53
  }
224
54
  async list(name, actor, options = {}) {
225
- const resource = this.registry.get(name);
226
- const ability = this.authorizeAction(resource, actor, 'view');
227
- const limit = Math.max(1, Math.min(100, Math.floor(Number(options.limit) || 25)));
228
- const sort = options.sort ?? 'id';
229
- const direction = options.direction === 'desc' ? 'desc' : 'asc';
230
- if (sort !== 'id' && !resource.fields[sort]?.sortable)
231
- throw new AdulaError(422, 'E_SORT', 'Unsupported sort field');
232
- // Sorting/filtering private fields would otherwise reveal their values indirectly.
233
- if (sort !== 'id' && !this.canQueryField(resource, actor, ability, sort))
234
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', 'Forbidden sort field');
235
- const sortColumn = `r.${resource.fields[sort]?.column ?? columnName(sort)}`;
236
- const query = accessibleBy(this.db(`${name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', resource);
237
- query.select(this.columns(resource, ability, false, [sort]));
238
- if (resource.scoped)
239
- query.select('ou.path as org_path');
240
- if (options.search) {
241
- const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable);
242
- if (!searchable.length ||
243
- searchable.some(([key]) => !this.canQueryField(resource, actor, ability, key)))
244
- throw new AdulaError(403, 'E_SEARCH', 'Search is unavailable');
245
- query.whereRaw("r.search_vector @@ plainto_tsquery('simple', ?)", [options.search]);
246
- }
247
- for (const [key, value] of Object.entries(options.filters ?? {})) {
248
- if (!resource.fields[key]?.filterable || !this.canQueryField(resource, actor, ability, key))
249
- throw new AdulaError(422, 'E_FILTER', 'Unsupported filter');
250
- if (value !== null && !['string', 'number', 'boolean'].includes(typeof value))
251
- throw new AdulaError(422, 'E_FILTER', 'Invalid filter value');
252
- query.where(`r.${resource.fields[key].column ?? columnName(key)}`, value);
253
- }
254
- if (options.tag !== undefined && options.tag !== null && options.tag !== '') {
255
- if (typeof options.tag !== 'string' || options.tag.length > 60)
256
- throw new AdulaError(422, 'E_FILTER', 'Invalid tag filter');
257
- query.whereExists((exists) => exists
258
- .from('taggables as tg')
259
- .join('tags as tn', 'tn.id', 'tg.tag_id')
260
- .where('tg.resource', name)
261
- .whereRaw('tg.record_id = r.id')
262
- .where('tn.name', options.tag));
263
- }
264
- // Estimate the authorized, filtered query, never the deployment-wide table cardinality.
265
- // Only the first page pays for the extra planner round trip; later pages keep its figure.
266
- let estimatedTotal;
267
- if (options.estimate !== false && !options.cursor) {
268
- const compiled = query.clone().clearSelect().select('r.id').toSQL();
269
- // The planner estimate is approximate by nature; reuse it briefly for the same
270
- // authorized, filtered query instead of planning it on every first page.
271
- const key = `${compiled.sql}\u0000${JSON.stringify(compiled.bindings)}`;
272
- const cached = estimates.get(key);
273
- if (cached && cached.at > Date.now() - ESTIMATE_TTL_MS)
274
- estimatedTotal = cached.rows;
275
- else {
276
- const estimate = await this.db.raw(`EXPLAIN (FORMAT JSON) ${compiled.sql}`, [
277
- ...compiled.bindings,
278
- ]);
279
- estimatedTotal = Number(estimate.rows[0]['QUERY PLAN'][0].Plan['Plan Rows']);
280
- if (estimates.size >= ESTIMATE_CACHE_LIMIT)
281
- estimates.delete(estimates.keys().next().value);
282
- estimates.set(key, { rows: estimatedTotal, at: Date.now() });
283
- }
284
- }
285
- if (options.cursor) {
286
- let cursor;
287
- try {
288
- cursor = JSON.parse(Buffer.from(options.cursor, 'base64url').toString());
289
- }
290
- catch {
291
- throw new AdulaError(422, 'E_CURSOR', 'Invalid cursor');
292
- }
293
- if (cursor.sort !== sort ||
294
- cursor.direction !== direction ||
295
- !Number.isSafeInteger(cursor.id) ||
296
- (cursor.value !== null && !['number', 'string', 'boolean'].includes(typeof cursor.value)))
297
- throw new AdulaError(422, 'E_CURSOR', 'Invalid cursor');
298
- query.where((q) => {
299
- if (cursor.value === null)
300
- q.whereNull(sortColumn).andWhere('r.id', direction === 'asc' ? '>' : '<', cursor.id);
301
- else
302
- q.where(sortColumn, direction === 'asc' ? '>' : '<', cursor.value)
303
- .orWhere((same) => same
304
- .where(sortColumn, cursor.value)
305
- .andWhere('r.id', direction === 'asc' ? '>' : '<', cursor.id))
306
- .orWhereNull(sortColumn);
307
- });
308
- }
309
- query.orderBy(sortColumn, direction, 'last');
310
- if (sort !== 'id')
311
- query.orderBy('r.id', direction);
312
- const rows = await query.limit(limit + 1);
313
- const records = rows
314
- .slice(0, limit)
315
- .map((row) => fromRow(row, resource));
316
- const last = records.at(-1);
317
- if (estimatedTotal !== undefined) {
318
- estimatedTotal =
319
- !options.cursor && rows.length <= limit
320
- ? rows.length
321
- : Math.max(estimatedTotal, rows.length);
322
- }
323
- const hydrated = await this.hydrate(this.db, resource, records);
324
- return {
325
- data: hydrated.map((record) => serialize(resource, record, ability, actor)),
326
- permissions: Object.fromEntries(records.map((record) => [
327
- String(record.id),
328
- this.permissions(resource, record, actor, ability),
329
- ])),
330
- meta: {
331
- limit,
332
- estimatedTotal,
333
- nextCursor: rows.length > limit && last
334
- ? Buffer.from(JSON.stringify({ id: last.id, value: last[sort] ?? null, sort, direction })).toString('base64url')
335
- : null,
336
- },
337
- related: await this.preload(resource, records, actor),
338
- };
339
- }
340
- canQueryField(resource, actor, ability, key) {
341
- return canQueryField(resource, actor, ability, key);
55
+ return query.list(this.context, name, actor, options);
342
56
  }
343
57
  /**
344
58
  * Counts and totals over the records the actor may view, grouped by queryable fields,
@@ -347,417 +61,53 @@ export class ResourceService {
347
61
  * the actor may query (E_FIELD_FORBIDDEN otherwise), so no hidden value leaks.
348
62
  */
349
63
  async aggregate(name, actor, options = {}) {
350
- const resource = this.registry.get(name);
351
- const ability = this.authorizeAction(resource, actor, 'view');
352
- const standard = new Set([
353
- ...(resource.submittable ? ['docStatus'] : []),
354
- ...(resource.scoped ? ['orgUnitId'] : []),
355
- ]);
356
- const column = (key) => `r.${resource.fields[key]?.column ?? columnName(key)}`;
357
- const queryable = (key, kinds) => {
358
- if (typeof key !== 'string')
359
- return false;
360
- if (standard.has(key))
361
- return !kinds;
362
- // Own keys only: names such as "constructor" are not fields.
363
- if (!Object.hasOwn(resource.fields, key))
364
- return false;
365
- const field = resource.fields[key];
366
- return (Boolean(field) &&
367
- !['hasMany', 'json', 'attachment'].includes(field.type) &&
368
- (!kinds || kinds.includes(field.type)) &&
369
- this.canQueryField(resource, actor, ability, key));
370
- };
371
- const groupBy = options.groupBy ?? [];
372
- const sums = options.sum ?? [];
373
- if (!Array.isArray(groupBy) || groupBy.length > 3 || !Array.isArray(sums) || sums.length > 5)
374
- throw new AdulaError(422, 'E_AGGREGATE', 'Group by up to three fields and total up to five');
375
- for (const key of groupBy)
376
- if (!queryable(key))
377
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', `Field cannot be grouped: ${String(key)}`);
378
- for (const key of sums)
379
- if (!queryable(key, ['integer', 'money']))
380
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', `Field cannot be totalled: ${String(key)}`);
381
- const query = accessibleBy(this.db(`${name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', resource);
382
- for (const [key, value] of Object.entries(options.filters ?? {})) {
383
- if (!resource.fields[key]?.filterable || !queryable(key))
384
- throw new AdulaError(422, 'E_FILTER', 'Unsupported filter');
385
- if (value !== null && !['string', 'number', 'boolean'].includes(typeof value))
386
- throw new AdulaError(422, 'E_FILTER', 'Invalid filter value');
387
- query.where(column(key), value);
388
- }
389
- if (options.where !== undefined && options.where !== null) {
390
- if (typeof options.where !== 'object' || Array.isArray(options.where))
391
- throw new AdulaError(422, 'E_FILTER', 'Conditions must be an object');
392
- for (const key of Object.keys(options.where))
393
- if (!queryable(key))
394
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', `Field cannot be filtered: ${key}`);
395
- let where;
396
- try {
397
- where = conditionSql(resolveActorConditions(options.where, actor.id), resource);
398
- }
399
- catch (error) {
400
- throw new AdulaError(422, 'E_FILTER', error.message);
401
- }
402
- query.whereRaw(where.text, where.bindings);
403
- }
404
- if (options.search) {
405
- const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable);
406
- if (!searchable.length || searchable.some(([key]) => !queryable(key)))
407
- throw new AdulaError(403, 'E_SEARCH', 'Search is unavailable');
408
- query.whereRaw("r.search_vector @@ plainto_tsquery('simple', ?)", [options.search]);
409
- }
410
- const selects = groupBy.map((key, index) => `${key === 'docStatus' ? 'r.doc_status' : column(key)} as g${index}`);
411
- if (options.count !== false)
412
- selects.push(this.db.raw('count(*)::int as count'));
413
- sums.forEach((key, index) => selects.push(this.db.raw(`sum(??)::text as s${index}`, [column(key)])));
414
- query.select(selects);
415
- groupBy.forEach((_, index) => query.groupByRaw(`${index + 1}`));
416
- groupBy.forEach((_, index) => query.orderByRaw(`${index + 1} ASC NULLS LAST`));
417
- const rows = await query.limit(AGGREGATE_GROUP_LIMIT + 1);
418
- return {
419
- truncated: rows.length > AGGREGATE_GROUP_LIMIT,
420
- rows: rows.slice(0, AGGREGATE_GROUP_LIMIT).map((row) => {
421
- const group = fromRow(Object.fromEntries(groupBy.map((key, index) => [
422
- key === 'docStatus'
423
- ? 'doc_status'
424
- : key === 'orgUnitId'
425
- ? 'org_unit_id'
426
- : (resource.fields[key].column ?? columnName(key)),
427
- row[`g${index}`],
428
- ])), resource);
429
- return {
430
- group: Object.fromEntries(groupBy.map((key) => [key, jsonValue(group[key])])),
431
- ...(options.count !== false ? { count: Number(row.count) } : {}),
432
- ...(sums.length
433
- ? {
434
- sum: Object.fromEntries(sums.map((key, index) => [
435
- key,
436
- row[`s${index}`] === null ? null : String(row[`s${index}`]),
437
- ])),
438
- }
439
- : {}),
440
- };
441
- }),
442
- };
443
- }
444
- async preload(resource, records, actor) {
445
- const related = {};
446
- const ability = buildAbility(actor.rules, this.registry.all());
447
- for (const [key, field] of Object.entries(resource.fields)) {
448
- if (field.type === 'user' && records.length) {
449
- const ids = records
450
- .filter((record) => key in serialize(resource, record, ability, actor))
451
- .map((record) => record[key])
452
- .filter((v) => v !== null && v !== undefined);
453
- // A display name only: readers of the record need not read account e-mails.
454
- if (ids.length) {
455
- const users = await this.db('users')
456
- .whereIn('id', [...new Set(ids)])
457
- .select('id', 'full_name');
458
- related[key] = users.map((row) => ({
459
- id: Number(row.id),
460
- fullName: String(row.full_name ?? ''),
461
- }));
462
- }
463
- continue;
464
- }
465
- if (field.type !== 'belongsTo' || !records.length)
466
- continue;
467
- const target = this.registry.get(field.resource);
468
- if (!ability.can('view', target.name))
469
- continue;
470
- const ids = records
471
- .filter((record) => key in serialize(resource, record, ability, actor))
472
- .map((record) => record[key])
473
- .filter((v) => v !== null && v !== undefined);
474
- if (!ids.length)
475
- continue;
476
- const query = accessibleBy(this.db(`${target.name} as r`).whereIn('r.id', ids).whereNull('r.deleted_at'), ability, actor, 'view', target).select(this.columns(target, ability));
477
- if (target.scoped)
478
- query.select('ou.path as org_path');
479
- const rows = await query;
480
- const targets = await this.hydrate(this.db, target, rows.map((r) => fromRow(r, target)));
481
- const title = await this.titler(target);
482
- related[key] = targets.map((r) => {
483
- const row = serialize(target, r, ability, actor);
484
- // `_title` cannot collide with a field key; clients label the relation with it.
485
- return { ...row, _title: title(row) };
486
- });
487
- }
488
- return related;
489
- }
490
- /** Formats record titles of one resource, loading the labels of its title lookups once. */
491
- async titler(resource) {
492
- const groups = titleFields(resource).flatMap((key) => {
493
- const field = resource.fields[key];
494
- return field.type === 'lookup' ? [field.group] : [];
495
- });
496
- const labels = new Map();
497
- if (groups.length)
498
- for (const row of await this.db('lookups')
499
- .whereIn('group', groups)
500
- .select('group', 'key', 'label_ar'))
501
- labels.set(`${row.group}\u0000${row.key}`, String(row.label_ar));
502
- return (record) => formatTitle(resource, record, (group, key) => labels.get(`${group}\u0000${key}`));
64
+ return query.aggregate(this.context, name, actor, options);
503
65
  }
504
66
  /**
505
67
  * Titles of records the actor may view, read under the actor's field access (#32).
506
68
  * Records the actor cannot view are left out; callers fall back to the record id.
507
69
  */
508
70
  async titles(name, ids, actor) {
509
- const result = new Map();
510
- let resource;
511
- try {
512
- resource = this.registry.get(name);
513
- }
514
- catch {
515
- return result;
516
- }
517
- const wanted = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];
518
- const ability = buildAbility(actor.rules, this.registry.all());
519
- if (!wanted.length || !resource.actions.includes('view') || !ability.can('view', name))
520
- return result;
521
- const query = accessibleBy(this.db(`${resource.name} as r`).whereIn('r.id', wanted).whereNull('r.deleted_at'), ability, actor, 'view', resource).select(this.columns(resource, ability));
522
- if (resource.scoped)
523
- query.select('ou.path as org_path');
524
- const rows = await query;
525
- const records = rows.map((row) => fromRow(row, resource));
526
- const title = await this.titler(resource);
527
- for (const record of records) {
528
- if (!canRecord(ability, actor, resource, 'view', record))
529
- continue;
530
- const text = title(serialize(resource, record, ability, actor));
531
- if (text)
532
- result.set(Number(record.id), text);
533
- }
534
- return result;
71
+ return read.titles(this.context, name, ids, actor);
535
72
  }
536
73
  async show(name, id, actor) {
537
- const resource = this.registry.get(name);
538
- const ability = this.authorizeAction(resource, actor, 'view');
539
- const record = await this.find(this.db, resource, actor, ability, id);
540
- this.requireRecord(ability, actor, resource, 'view', record);
541
- const [hydrated] = await this.hydrate(this.db, resource, [record]);
542
- return {
543
- data: serialize(resource, hydrated, ability, actor),
544
- permissions: this.permissions(resource, record, actor, ability),
545
- related: await this.preload(resource, [record], actor),
546
- };
74
+ return read.show(this.context, name, id, actor);
547
75
  }
548
76
  async relationOptions(name, key, actor, options = {}) {
549
- if (this.registry.get(name).fields[key]?.type === 'user')
550
- return this.userOptions(name, key, actor, options);
551
- const editor = await this.editor(name, actor, options.id);
552
- const field = editor.fields.find((entry) => entry.key === key);
553
- if (!field || field.type !== 'belongsTo')
554
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', 'ليس لديك صلاحية لهذا الحقل');
555
- const target = this.registry.get(field.resource);
556
- const page = await this.list(target.name, actor, {
557
- search: options.search,
558
- cursor: options.cursor,
559
- limit: 50,
560
- estimate: false,
561
- });
562
- const title = await this.titler(target);
563
- return {
564
- data: page.data.map((row) => ({
565
- value: String(row.id),
566
- label: title(row) ?? `#${row.id}`,
567
- })),
568
- nextCursor: page.meta.nextCursor,
569
- };
570
- }
571
- /**
572
- * Choices for a user field. A form lists active members of the record's unit or its
573
- * ancestors (the users the record is visible to through membership); a filter lists
574
- * active users who share organization scope with the actor. Only names are returned.
575
- */
576
- async userOptions(name, key, actor, options) {
577
- const resource = this.registry.get(name);
578
- let path = null;
579
- if (options.purpose === 'filter') {
580
- const field = this.describe(name, actor).fields.find((entry) => entry.key === key);
581
- if (!field?.filterable)
582
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', 'ليس لديك صلاحية لهذا الحقل');
583
- }
584
- else {
585
- const editor = await this.editor(name, actor, options.id);
586
- if (!editor.fields.some((entry) => entry.key === key))
587
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', 'ليس لديك صلاحية لهذا الحقل');
588
- if (resource.scoped) {
589
- const unit = options.orgUnitId ??
590
- (editor.record?.orgUnitId === undefined ? undefined : Number(editor.record.orgUnitId));
591
- // Without a unit (for example an inline row) the choices follow the actor's scope;
592
- // saving still checks the record's unit.
593
- if (unit !== undefined) {
594
- const row = await this.db('org_units').where('id', unit).first('path');
595
- // Only units the actor works in (or the record's current unit) may be probed.
596
- if (!row ||
597
- (!inOrgScope(row.path, actor.orgPaths) &&
598
- Number(unit) !== Number(editor.record?.orgUnitId)))
599
- return { data: [], nextCursor: null };
600
- path = String(row.path);
601
- }
602
- }
603
- }
604
- let after = 0;
605
- if (options.cursor !== undefined && options.cursor !== '') {
606
- after = Number(options.cursor);
607
- if (!Number.isSafeInteger(after) || after < 0)
608
- throw new AdulaError(422, 'E_CURSOR', 'Invalid cursor');
609
- }
610
- const query = this.eligibleUsers(this.db, path, actor)
611
- .where('u.id', '>', after)
612
- .orderBy('u.id')
613
- .limit(51)
614
- .select('u.id', 'u.full_name');
615
- if (options.search)
616
- query.whereILike('u.full_name', `%${options.search.replace(/[\\%_]/g, '\\$&')}%`);
617
- const rows = await query;
618
- return {
619
- data: rows.slice(0, 50).map((row) => ({
620
- value: String(row.id),
621
- label: String(row.full_name || `#${row.id}`),
622
- })),
623
- nextCursor: rows.length > 50 ? String(rows[49].id) : null,
624
- };
625
- }
626
- /**
627
- * Active users eligible for a user field: members of the unit at `path` or of one of
628
- * its ancestors, or (without a path) users sharing organization scope with the actor.
629
- * A system write on an unscoped resource passes no actor: any active member qualifies.
630
- */
631
- eligibleUsers(db, path, actor) {
632
- return db('users as u')
633
- .whereNull('u.disabled_at')
634
- .whereExists((members) => {
635
- members
636
- .from('user_org_units as m')
637
- .join('org_units as o', 'o.id', 'm.org_unit_id')
638
- .whereRaw('m.user_id = u.id');
639
- if (path !== null)
640
- members.whereRaw('?::ltree <@ o.path', [path]);
641
- else if (actor)
642
- members.where((scope) => {
643
- if (!actor.orgPaths.length)
644
- scope.whereRaw('FALSE');
645
- for (const own of actor.orgPaths)
646
- scope.orWhereRaw('o.path <@ ?::ltree', [own]).orWhereRaw('o.path @> ?::ltree', [own]);
647
- });
648
- })
649
- .distinct();
77
+ return form.relationOptions(this.context, name, key, actor, options);
650
78
  }
651
79
  /** Deferred relation reads re-authorize the parent and each child on every request. */
652
80
  async children(name, id, actor) {
653
- const resource = this.registry.get(name);
654
- const ability = this.authorizeAction(resource, actor, 'view');
655
- const parent = await this.find(this.db, resource, actor, ability, id);
656
- this.requireRecord(ability, actor, resource, 'view', parent);
657
- return this.childrenOf(resource, parent, actor, ability);
81
+ return read.recordChildren(this.context, name, id, actor);
658
82
  }
659
- /** Inline children of an already authorized parent record. */
660
- async childrenOf(resource, parent, actor, ability) {
661
- const name = resource.name;
662
- const id = Number(parent.id);
663
- const result = {};
664
- for (const key of resource.show) {
665
- const field = resource.fields[key];
666
- if (field.type !== 'hasMany' ||
667
- !ability.can('view', subject(name, parent), key) ||
668
- actor.permissionLevel <
669
- Math.max(field.permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0))
670
- continue;
671
- if (resource.serialize && !resource.serialize.includes(key))
672
- continue;
673
- const child = this.registry.get(field.resource);
674
- if (!ability.can('view', child.name) || !child.actions.includes('view'))
675
- continue;
676
- const rows = await accessibleBy(this.db(`${child.name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', child)
677
- .where(`r.${child.fields[field.foreignKey].column ?? columnName(field.foreignKey)}`, id)
678
- .select([...this.columns(child, ability), ...(child.scoped ? ['ou.path as org_path'] : [])])
679
- .orderBy('r.id')
680
- .limit(101);
681
- const children = await this.hydrate(this.db, child, rows.slice(0, 100).map((row) => fromRow(row, child)));
682
- result[key] = {
683
- rows: children.map((row) => serialize(child, row, ability, actor)),
684
- hasMore: rows.length > 100,
685
- };
686
- }
687
- return result;
83
+ /**
84
+ * The lines of a printed document (ADR 048), authorized like children(): the hasMany
85
+ * field's rules and level, the child's view permission and each line's scope apply,
86
+ * and a group is read only when the record exposes it (`serialize`, or `list` and
87
+ * `show`) or one of the resource's code print templates declares it. Each group holds up
88
+ * to `limit` rows (`hasMore` beyond) with the display rows of the lines' relations.
89
+ */
90
+ async documentLines(name, id, actor, options) {
91
+ return read.documentLines(this.context, name, id, actor, options.fields, options.limit);
688
92
  }
689
93
  /** Active lookup labels for the lookup fields the actor may read on this resource. */
690
94
  async lookups(name, actor) {
691
- const options = {};
692
- for (const field of this.describe(name, actor).fields) {
693
- if (field.type !== 'lookup')
694
- continue;
695
- const rows = await this.db('lookups')
696
- .where({ group: field.group, active: true })
697
- .orderBy(['sort', 'id'])
698
- .select('key', 'label_ar');
699
- options[field.key] = rows.map((row) => ({ value: row.key, label: row.label_ar }));
700
- }
701
- return options;
95
+ return read.lookups(this.context, name, actor);
702
96
  }
703
97
  /** The last 50 recorded mutations of one record, after authorizing the record itself. */
704
98
  async activity(name, id, actor) {
705
- const resource = this.registry.get(name);
706
- const ability = this.authorizeAction(resource, actor, 'view');
707
- const record = await this.find(this.db, resource, actor, ability, id);
708
- this.requireRecord(ability, actor, resource, 'view', record);
709
- return this.activityOf(name, id);
99
+ return read.activity(this.context, name, id, actor);
710
100
  }
711
101
  /**
712
102
  * Inline children and recent activity of one record, authorized with a single record
713
103
  * read (for deferred page props that would otherwise read the record twice).
714
104
  */
715
105
  async details(name, id, actor) {
716
- const resource = this.registry.get(name);
717
- const ability = this.authorizeAction(resource, actor, 'view');
718
- const record = await this.find(this.db, resource, actor, ability, id);
719
- this.requireRecord(ability, actor, resource, 'view', record);
720
- return {
721
- children: await this.childrenOf(resource, record, actor, ability),
722
- activity: await this.activityOf(name, id),
723
- };
106
+ return read.details(this.context, name, id, actor);
724
107
  }
725
108
  /** show(), children() and activity() of one record from a single record read. */
726
109
  async record(name, id, actor) {
727
- const resource = this.registry.get(name);
728
- const ability = this.authorizeAction(resource, actor, 'view');
729
- const record = await this.find(this.db, resource, actor, ability, id);
730
- this.requireRecord(ability, actor, resource, 'view', record);
731
- const [hydrated] = await this.hydrate(this.db, resource, [record]);
732
- return {
733
- data: serialize(resource, hydrated, ability, actor),
734
- permissions: this.permissions(resource, record, actor, ability),
735
- related: await this.preload(resource, [record], actor),
736
- children: await this.childrenOf(resource, record, actor, ability),
737
- activity: await this.activityOf(name, id),
738
- };
739
- }
740
- async activityOf(name, id) {
741
- const rows = await this.db('activities as a')
742
- .leftJoin('users as u', 'u.id', 'a.actor_id')
743
- .where({ 'a.resource': name, 'a.record_id': id })
744
- .orderBy('a.id', 'desc')
745
- .limit(50)
746
- .select('a.id', 'a.action', 'a.changes', 'a.actor_id', 'a.created_at', 'u.full_name as actor_name');
747
- return rows.map((row) => ({
748
- id: Number(row.id),
749
- action: String(row.action),
750
- fields: Array.isArray(row.changes?.fields) ? row.changes.fields : [],
751
- actorId: Number(row.actor_id),
752
- // A display name only: record viewers need not be able to read account e-mails.
753
- actorName: row.actor_name ? String(row.actor_name) : null,
754
- /**
755
- * @deprecated Always null. Kept so project-owned copies of resource-show from
756
- * earlier releases still compile; they fall back to the actor id.
757
- */
758
- actorEmail: null,
759
- createdAt: new Date(row.created_at).toISOString(),
760
- }));
110
+ return read.recordPage(this.context, name, id, actor);
761
111
  }
762
112
  /**
763
113
  * The form description for create (no id) or update. `defaults` pre-fills a create form
@@ -766,219 +116,10 @@ export class ResourceService {
766
116
  * is dropped. Defaults are only initial values; saving validates as usual.
767
117
  */
768
118
  async editor(name, actor, id, request = {}) {
769
- const resource = this.registry.get(name);
770
- const action = id === undefined ? 'create' : 'update';
771
- const ability = this.authorizeAction(resource, actor, action);
772
- const record = id === undefined ? undefined : await this.find(this.db, resource, actor, ability, id);
773
- if (record) {
774
- this.requireRecord(ability, actor, resource, action, record);
775
- if (resource.submittable && record.docStatus !== 0)
776
- throw new AdulaError(409, 'E_DOCUMENT_LOCKED', 'Only draft documents can be edited');
777
- }
778
- const fields = resource.form
779
- .filter((key) => {
780
- const field = resource.fields[key];
781
- return (!field.sequence &&
782
- actor.permissionLevel >=
783
- Math.max(field.permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0) &&
784
- ability.can(action, record ? subject(name, record) : name, key));
785
- })
786
- .map((key) => ({ key, ...resource.fields[key] }));
787
- const options = {};
788
- const relationSearch = {};
789
- const inline = {};
790
- for (const field of fields) {
791
- if (field.type === 'hasMany' && field.inline) {
792
- const child = this.registry.get(field.resource);
793
- const rows = record && ability.can('view', child.name)
794
- ? await accessibleBy(this.db(`${child.name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', child)
795
- .where(`r.${child.fields[field.foreignKey].column ?? columnName(field.foreignKey)}`, id)
796
- .select([
797
- ...this.columns(child, ability),
798
- ...(child.scoped ? ['ou.path as org_path'] : []),
799
- ])
800
- .orderBy('r.id')
801
- .limit(101)
802
- : [];
803
- const records = rows.slice(0, 100).map((row) => fromRow(row, child));
804
- const hydratedRows = await this.hydrate(this.db, child, records);
805
- const childFields = child.form.filter((key) => key !== field.foreignKey &&
806
- !child.fields[key].sequence &&
807
- actor.permissionLevel >=
808
- Math.max(child.fields[key].permissionLevel ?? 0, child.hidden?.includes(key) ? 1 : 0));
809
- inline[field.key] = {
810
- fields: childFields.map((key) => ({ key, ...child.fields[key] })),
811
- createFields: childFields.filter((key) => ability.can('create', child.name, key)),
812
- updateFields: Object.fromEntries(records.map((row) => [
813
- String(row.id),
814
- childFields.filter((key) => ability.can('update', subject(child.name, row), key)),
815
- ])),
816
- rows: hydratedRows.map((row) => serialize(child, row, ability, actor)),
817
- hasMore: rows.length > 100,
818
- canCreate: child.actions.includes('create') && ability.can('create', child.name),
819
- permissions: Object.fromEntries(records.map((row) => [
820
- String(row.id),
821
- {
822
- update: child.actions.includes('update') &&
823
- ability.can('update', subject(child.name, row)),
824
- delete: child.actions.includes('delete') &&
825
- ability.can('delete', subject(child.name, row)),
826
- },
827
- ])),
828
- };
829
- }
830
- if (field.type === 'lookup') {
831
- const lookups = await this.db('lookups')
832
- .where({ group: field.group, active: true })
833
- .orderBy('id')
834
- .select('key', 'label_ar');
835
- options[field.key] = lookups.map((row) => ({ value: row.key, label: row.label_ar }));
836
- }
837
- else if (field.type === 'belongsTo') {
838
- const target = this.registry.get(field.resource);
839
- if (ability.can('view', target.name)) {
840
- relationSearch[field.key] = this.describe(target.name, actor).searchable;
841
- const page = await this.list(target.name, actor, { limit: 50, estimate: false });
842
- const title = await this.titler(target);
843
- options[field.key] = page.data.map((row) => ({
844
- value: String(row.id),
845
- label: title(row) ?? `#${row.id}`,
846
- }));
847
- const selected = record?.[field.key];
848
- if (selected !== null &&
849
- selected !== undefined &&
850
- !options[field.key].some((option) => option.value === String(selected))) {
851
- try {
852
- const current = await this.show(target.name, Number(selected), actor);
853
- options[field.key].push({
854
- value: String(current.data.id),
855
- label: title(current.data) ?? `#${current.data.id}`,
856
- });
857
- }
858
- catch (error) {
859
- if (!(error instanceof AdulaError) || ![403, 404].includes(error.status))
860
- throw error;
861
- }
862
- }
863
- }
864
- else
865
- options[field.key] = [];
866
- }
867
- else if (field.type === 'user') {
868
- // Choices depend on the unit chosen in the form; they load from relationOptions.
869
- relationSearch[field.key] = true;
870
- options[field.key] = [];
871
- const selected = record?.[field.key];
872
- if (selected !== null && selected !== undefined) {
873
- const current = await this.db('users')
874
- .where('id', Number(selected))
875
- .first('id', 'full_name');
876
- if (current)
877
- options[field.key].push({
878
- value: String(current.id),
879
- label: String(current.full_name || `#${current.id}`),
880
- });
881
- }
882
- }
883
- }
884
- const units = resource.scoped && !resource.scope
885
- ? await this.db('org_units')
886
- .where((query) => {
887
- if (!actor.orgPaths.length)
888
- query.whereRaw('FALSE');
889
- for (const path of actor.orgPaths)
890
- query.orWhereRaw('path <@ ?::ltree', [path]);
891
- })
892
- .orderBy('path')
893
- .limit(100)
894
- .select('id', 'name')
895
- : [];
896
- if (record?.orgUnitId && !units.some((unit) => Number(unit.id) === Number(record.orgUnitId))) {
897
- const current = await this.db('org_units')
898
- .where('id', Number(record.orgUnitId))
899
- .first('id', 'name');
900
- if (current)
901
- units.push(current);
902
- }
903
- const defaults = {};
904
- const requested = request.defaults;
905
- if (id === undefined && requested && typeof requested === 'object')
906
- for (const field of fields) {
907
- const raw = Object.hasOwn(requested, field.key) ? requested[field.key] : undefined;
908
- if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean')
909
- continue;
910
- let value = raw;
911
- try {
912
- if (['integer', 'belongsTo', 'user'].includes(field.type))
913
- value = Number(raw);
914
- else if (field.type === 'boolean')
915
- value = raw === true || raw === 'true';
916
- else
917
- value = String(raw);
918
- value = fieldValue(field, value);
919
- }
920
- catch {
921
- continue;
922
- }
923
- if (['attachment', 'json', 'hasMany'].includes(field.type))
924
- continue;
925
- if (field.type === 'user') {
926
- // The unit is chosen later in the form; saving checks the record's unit.
927
- const user = await this.eligibleUsers(this.db, null, actor)
928
- .where('u.id', Number(value))
929
- .first('u.id', 'u.full_name');
930
- if (!user)
931
- continue;
932
- const choices = options[field.key] ?? (options[field.key] = []);
933
- if (!choices.some((option) => option.value === String(user.id)))
934
- choices.push({ value: String(user.id), label: String(user.full_name || `#${user.id}`) });
935
- }
936
- if (field.type === 'lookup' || field.type === 'belongsTo') {
937
- const choices = options[field.key] ?? [];
938
- if (!choices.some((option) => option.value === String(value))) {
939
- if (field.type === 'lookup')
940
- continue;
941
- try {
942
- // Authorized exactly like opening the related record.
943
- const target = this.registry.get(field.resource);
944
- const current = await this.show(target.name, Number(value), actor);
945
- const title = await this.titler(target);
946
- choices.push({
947
- value: String(current.data.id),
948
- label: title(current.data) ?? `#${current.data.id}`,
949
- });
950
- }
951
- catch (error) {
952
- if (!(error instanceof AdulaError) || ![403, 404].includes(error.status))
953
- throw error;
954
- continue;
955
- }
956
- }
957
- }
958
- defaults[field.key] = value;
959
- }
960
- return {
961
- mode: action,
962
- name,
963
- label: resource.label.ar,
964
- recordLabel: resource.recordLabel?.ar ?? null,
965
- fields,
966
- /** Initial values of a create form, already checked against the actor's access. */
967
- defaults,
968
- inline,
969
- options,
970
- relationSearch,
971
- orgUnits: units.map((row) => ({ value: String(row.id), label: String(row.name) })),
972
- scoped: resource.scoped,
973
- /** The belongsTo field whose record decides the unit; the form shows no unit picker. */
974
- scopeFrom: resource.scope?.from ?? null,
975
- record: record
976
- ? serialize(resource, await this.hydrateOne(this.db, resource, record), ability, actor)
977
- : null,
978
- };
119
+ return form.editor(this.context, name, actor, id, request);
979
120
  }
980
121
  async save(name, actor, input, id, transaction) {
981
- return this.persist(name, actor, input, id, transaction);
122
+ return write.persist(this.context, name, actor, input, id, transaction);
982
123
  }
983
124
  /**
984
125
  * A write decided by module code rather than by a user's role rules: state transitions,
@@ -989,14 +130,7 @@ export class ResourceService {
989
130
  * Returns the full stored record; module code must not send it to users unfiltered.
990
131
  */
991
132
  async systemSave(name, values, id, options) {
992
- if (!Number.isSafeInteger(options.actorId) || options.actorId <= 0)
993
- throw new AdulaError(422, 'E_ACTOR', 'systemSave requires the author user id');
994
- const actor = { id: options.actorId, orgPaths: [], permissionLevel: 0, rules: [] };
995
- return this.persist(name, actor, values, id, options.trx, undefined, {
996
- reason: options.reason,
997
- version: options.version,
998
- chooser: options.chooser,
999
- });
133
+ return write.systemSave(this.context, name, values, id, options);
1000
134
  }
1001
135
  /**
1002
136
  * Moves the records whose scope follows this parent (`scope: { from }`) to the parent's
@@ -1004,348 +138,28 @@ export class ResourceService {
1004
138
  * `updated` event, or right after moving the parent. Returns the number of moved records.
1005
139
  */
1006
140
  async rehome(parentName, parentId, options) {
1007
- const run = async (trx) => {
1008
- const parent = await this.findAny(trx, this.registry.get(parentName), parentId);
1009
- let moved = 0;
1010
- for (const child of this.registry.all()) {
1011
- const field = child.scope && child.fields[child.scope.from];
1012
- if (!field || field.type !== 'belongsTo' || field.resource !== parentName)
1013
- continue;
1014
- const column = field.column ?? columnName(child.scope.from);
1015
- const ids = await trx(child.name)
1016
- .where(column, parentId)
1017
- .whereNull('deleted_at')
1018
- .whereNot('org_unit_id', Number(parent.orgUnitId))
1019
- .orderBy('id')
1020
- .pluck('id');
1021
- for (const id of ids) {
1022
- await this.systemSave(child.name, {}, Number(id), { ...options, trx });
1023
- moved++;
1024
- }
1025
- }
1026
- return moved;
1027
- };
1028
- return options.trx ? run(options.trx) : this.db.transaction(run);
141
+ return write.rehome(this.context, parentName, parentId, options);
1029
142
  }
1030
- async persist(name, actor, input, id, transaction, parentWrite, system) {
1031
- const resource = this.registry.get(name);
1032
- const action = id === undefined ? 'create' : 'update';
1033
- // System writes carry no role rules; this ability is used only for serialization shape.
1034
- const ability = system
1035
- ? buildAbility([{ action: 'manage', subject: 'all' }], this.registry.all())
1036
- : this.authorizeAction(resource, actor, action);
1037
- const form = system ? systemInput(resource, input) : writableInput(resource, input);
1038
- const load = (db, target, key, lock = false) => system
1039
- ? this.findAny(db, target, key, lock)
1040
- : this.find(db, target, actor, ability, key, lock);
1041
- const check = (target, act, record) => {
1042
- if (!system)
1043
- this.requireRecord(ability, actor, target, act, record);
1044
- };
1045
- const validated = system ? {} : await resource.validator.validate(form);
1046
- const work = async (trx) => {
1047
- const existing = id === undefined ? {} : await load(trx, resource, id, true);
1048
- if (id !== undefined) {
1049
- check(resource, action, existing);
1050
- if (!system || system.version !== undefined)
1051
- this.requireVersion(resource, existing, system ? system.version : input.version);
1052
- if (resource.submittable && existing.docStatus !== 0)
1053
- throw new AdulaError(409, 'E_DOCUMENT_LOCKED', 'Only draft documents can be edited');
1054
- }
1055
- if (system) {
1056
- // The validator sees the complete form, so a partial update keeps required values.
1057
- const formKeys = resource.form.filter((key) => resource.fields[key].type !== 'hasMany');
1058
- const pick = (record) => Object.fromEntries(formKeys.filter((key) => key in record).map((key) => [key, record[key]]));
1059
- Object.assign(validated, await resource.validator.validate({ ...pick(existing), ...pick(form) }), Object.fromEntries(Object.entries(form).filter(([key]) => !formKeys.includes(key))));
1060
- }
1061
- const candidate = {
1062
- ...existing,
1063
- ...validated,
1064
- createdBy: existing.createdBy ?? actor.id,
1065
- updatedBy: actor.id,
1066
- };
1067
- if (resource.submittable)
1068
- candidate.docStatus = existing.docStatus ?? 0;
1069
- this.normalizeValues(resource, candidate);
1070
- const locate = async () => {
1071
- if (!resource.scoped)
1072
- return;
1073
- if (resource.scope) {
1074
- // Inherited scope: the parent decides the unit before any authorization (#45).
1075
- const field = resource.fields[resource.scope.from];
1076
- const parentId = Number(candidate[resource.scope.from]);
1077
- if (field.type !== 'belongsTo' || !Number.isSafeInteger(parentId) || parentId <= 0)
1078
- throw new AdulaError(422, 'E_REQUIRED', `Required field: ${resource.scope.from}`);
1079
- const parentResource = this.registry.get(field.resource);
1080
- const parent = await load(trx, parentResource, parentId);
1081
- check(parentResource, 'view', parent);
1082
- candidate.orgUnitId = parent.orgUnitId;
1083
- }
1084
- else if (!system || 'orgUnitId' in input || id === undefined)
1085
- candidate.orgUnitId = input.orgUnitId ?? existing.orgUnitId;
1086
- const unit = await trx('org_units')
1087
- .where('id', Number(candidate.orgUnitId) || -1)
1088
- .first('path');
1089
- if (system && !unit)
1090
- throw new AdulaError(422, 'E_ORG_UNIT', 'الوحدة التنظيمية غير موجودة');
1091
- candidate.orgPath = unit?.path;
1092
- };
1093
- await locate();
1094
- check(resource, action, candidate);
1095
- // Validators may add fields (defaults, transforms); those are written too, so check them.
1096
- const written = new Set(system
1097
- ? []
1098
- : [
1099
- ...Object.keys(form),
1100
- ...Object.keys(validated).filter((key) => key in resource.fields),
1101
- ]);
1102
- for (const key of written) {
1103
- const field = resource.fields[key];
1104
- if (!ability.can(action, subject(name, candidate), key) ||
1105
- (id !== undefined && !ability.can(action, subject(name, existing), key)) ||
1106
- actor.permissionLevel <
1107
- Math.max(field.permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0))
1108
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', `Field is forbidden: ${key}`);
1109
- if (field.sequence)
1110
- throw new AdulaError(422, 'E_SEQUENCE_READONLY', 'Sequence fields are generated');
1111
- }
1112
- for (const [key, field] of Object.entries(resource.fields))
1113
- if (field.sequence && id === undefined)
1114
- candidate[key] = await sequence(trx, field.sequence);
1115
- const context = { trx, userId: actor.id, action };
1116
- await resource.hooks?.beforeSave?.(candidate, context);
1117
- this.normalizeValues(resource, candidate);
1118
- // A hook may change the parent of an inherited scope; the unit follows it.
1119
- if (resource.scope)
1120
- await locate();
1121
- // A hook may also move the record: later checks use the unit it chose.
1122
- if (resource.scoped) {
1123
- const unit = await trx('org_units')
1124
- .where('id', Number(candidate.orgUnitId) || -1)
1125
- .first('path');
1126
- candidate.orgPath = unit?.path;
1127
- }
1128
- for (const [key, field] of Object.entries(resource.fields)) {
1129
- if (field.required &&
1130
- field.type !== 'hasMany' &&
1131
- (candidate[key] === null || candidate[key] === undefined))
1132
- throw new AdulaError(422, 'E_REQUIRED', `Required field: ${key}`);
1133
- if (field.type === 'belongsTo' && candidate[key] !== null && candidate[key] !== undefined) {
1134
- const related = this.registry.get(field.resource);
1135
- const target = await load(trx, related, Number(candidate[key]));
1136
- check(related, 'view', target);
1137
- }
1138
- // A new user, or a record moved by a user to another unit, needs an eligible user.
1139
- // An unchanged value never blocks other edits, even after the account is disabled.
1140
- if (field.type === 'user' &&
1141
- candidate[key] !== null &&
1142
- candidate[key] !== undefined &&
1143
- (Number(candidate[key]) !== Number(existing[key]) ||
1144
- (!system &&
1145
- resource.scoped &&
1146
- Number(candidate.orgUnitId) !== Number(existing.orgUnitId)))) {
1147
- const eligible = await this.eligibleUsers(trx, resource.scoped ? String(candidate.orgPath ?? '') || null : null, system ? (system.chooser ?? null) : actor)
1148
- .where('u.id', Number(candidate[key]))
1149
- .first('u.id');
1150
- if (!eligible || (resource.scoped && !candidate.orgPath))
1151
- throw new AdulaError(422, 'E_USER_FIELD', `${key}: اختر مستخدماً نشطاً من الوحدة التنظيمية للسجل أو الوحدات الأعلى منها`);
1152
- }
1153
- if (field.type === 'lookup' && candidate[key] !== null && candidate[key] !== undefined) {
1154
- if (!(await trx('lookups')
1155
- .where({ group: field.group, key: candidate[key], active: true })
1156
- .first()))
1157
- throw new AdulaError(422, 'E_LOOKUP', `Invalid lookup: ${key}`);
1158
- }
1159
- if (field.type === 'attachment' &&
1160
- isAttachmentId(candidate[key]) &&
1161
- (candidate[key] !== existing[key] ||
1162
- (resource.scoped && Number(candidate.orgUnitId) !== Number(existing.orgUnitId))))
1163
- await claimAttachment(trx, {
1164
- attachmentId: candidate[key],
1165
- actor,
1166
- resource: name,
1167
- field: key,
1168
- recordId: id,
1169
- orgUnitId: resource.scoped ? Number(candidate.orgUnitId) : null,
1170
- scoped: resource.scoped,
1171
- });
1172
- }
1173
- // Hooks may calculate fields, but may never move a record past authorization.
1174
- check(resource, action, candidate);
1175
- await this.requireInlineParents(trx, resource, actor, candidate, existing, parentWrite, Boolean(system));
1176
- if (id !== undefined &&
1177
- resource.scoped &&
1178
- Number(candidate.orgUnitId) !== Number(existing.orgUnitId)) {
1179
- for (const field of Object.values(resource.fields)) {
1180
- if (field.type !== 'hasMany' || !field.inline)
1181
- continue;
1182
- const child = this.registry.get(field.resource);
1183
- if (await trx(child.name)
1184
- .where(child.fields[field.foreignKey].column ?? columnName(field.foreignKey), id)
1185
- .whereNull('deleted_at')
1186
- .first('id'))
1187
- throw new AdulaError(422, 'E_INLINE_SCOPE', 'Cannot change organization while inline rows exist');
1188
- }
1189
- }
1190
- const values = { updated_by: actor.id, updated_at: trx.fn.now() };
1191
- if (id === undefined)
1192
- values.created_by = actor.id;
1193
- if (resource.scoped)
1194
- values.org_unit_id = candidate.orgUnitId;
1195
- if (resource.version)
1196
- values.version = id === undefined ? 1 : Number(existing.version) + 1;
1197
- for (const [key, field] of Object.entries(resource.fields)) {
1198
- if (field.type !== 'hasMany' && key in candidate)
1199
- values[field.column ?? columnName(key)] =
1200
- field.type === 'json' ? JSON.stringify(candidate[key]) : candidate[key];
1201
- }
1202
- const [row] = id === undefined
1203
- ? await trx(name).insert(values).returning('*')
1204
- : await trx(name).where({ id }).update(values).returning('*');
1205
- const saved = { ...fromRow(row, resource), orgPath: candidate.orgPath };
1206
- for (const [key, field] of Object.entries(resource.fields)) {
1207
- if (field.type !== 'attachment' || !(key in candidate))
1208
- continue;
1209
- const next = isAttachmentId(candidate[key]) ? candidate[key] : null;
1210
- const previous = isAttachmentId(existing[key]) ? existing[key] : null;
1211
- if (next !== null && id === undefined)
1212
- await claimAttachment(trx, {
1213
- attachmentId: next,
1214
- actor,
1215
- resource: name,
1216
- field: key,
1217
- recordId: Number(row.id),
1218
- orgUnitId: resource.scoped ? Number(candidate.orgUnitId) : null,
1219
- scoped: resource.scoped,
1220
- });
1221
- if (previous !== null && previous !== next)
1222
- await releaseAttachment(trx, previous);
1223
- }
1224
- for (const [key, field] of Object.entries(resource.fields)) {
1225
- if (field.type !== 'hasMany' || !(key in form))
1226
- continue;
1227
- if (!field.inline || !Array.isArray(form[key]) || form[key].length > 100)
1228
- throw new AdulaError(422, 'E_INLINE', 'Invalid inline rows (maximum 100)');
1229
- const childResource = this.registry.get(field.resource);
1230
- const seen = new Set();
1231
- for (const child of form[key]) {
1232
- if (!child || typeof child !== 'object' || Array.isArray(child))
1233
- throw new AdulaError(422, 'E_INLINE', 'Inline rows must be objects');
1234
- const { id: childId, _delete: remove, ...data } = child;
1235
- if (remove !== undefined && typeof remove !== 'boolean')
1236
- throw new AdulaError(422, 'E_INLINE', 'Invalid deletion marker');
1237
- if (childId !== undefined) {
1238
- if (id === undefined ||
1239
- !Number.isSafeInteger(childId) ||
1240
- Number(childId) <= 0 ||
1241
- seen.has(Number(childId)))
1242
- throw new AdulaError(422, 'E_INLINE', 'Invalid or repeated inline record identifier');
1243
- seen.add(Number(childId));
1244
- const childAbility = this.authorizeAction(childResource, actor, remove ? 'delete' : 'update');
1245
- const owned = await this.find(trx, childResource, actor, childAbility, Number(childId), true);
1246
- if (Number(owned[field.foreignKey]) !== Number(row.id))
1247
- throw new AdulaError(404, 'E_NOT_FOUND', 'السجل غير موجود');
1248
- }
1249
- if (remove) {
1250
- if (childId === undefined)
1251
- throw new AdulaError(422, 'E_INLINE', 'Deleting an inline row requires its identifier');
1252
- await this.transition(field.resource, Number(childId), actor, 'delete', data.version, trx);
1253
- continue;
1254
- }
1255
- await this.persist(field.resource, actor, {
1256
- ...data,
1257
- [field.foreignKey]: row.id,
1258
- ...(childResource.scoped && !childResource.scope
1259
- ? { orgUnitId: candidate.orgUnitId }
1260
- : {}),
1261
- }, childId === undefined ? undefined : Number(childId), trx, { name, id: Number(row.id), action });
1262
- }
1263
- }
1264
- const changes = [];
1265
- if (id !== undefined)
1266
- for (const key of Object.keys(resource.fields)) {
1267
- if (resource.fields[key].type === 'hasMany' || !(key in saved))
1268
- continue;
1269
- const before = existing[key] ?? null;
1270
- const after = saved[key] ?? null;
1271
- if (JSON.stringify(before) !== JSON.stringify(after))
1272
- changes.push({ field: key, before, after });
1273
- }
1274
- await this.audit(trx, resource, actor, action, saved, Object.keys(form), changes, system);
1275
- await resource.hooks?.afterSave?.(saved, context);
1276
- if (system)
1277
- return (await this.hydrateOne(trx, resource, saved));
1278
- return serialize(resource, await this.hydrateOne(trx, resource, saved), ability, actor);
1279
- };
1280
- return transaction ? work(transaction) : this.db.transaction(work);
1281
- }
1282
- requireVersion(resource, existing, version) {
1283
- if (resource.version && (!Number.isSafeInteger(version) || version !== existing.version))
1284
- throw new AdulaError(409, 'E_VERSION_CONFLICT', 'تم تعديل السجل بواسطة مستخدم آخر. حدّث الصفحة وحاول مجدداً.');
143
+ async transition(name, id, actor, action, version, transaction) {
144
+ return transition(this.context, name, id, actor, action, version, transaction);
1285
145
  }
1286
- /** Inline children share the parent's draft state, organization and update authority. */
1287
- async requireInlineParents(trx, resource, actor, candidate, existing = {}, parentWrite, system = false) {
1288
- for (const parent of this.registry.all()) {
1289
- for (const [key, field] of Object.entries(parent.fields)) {
1290
- if (field.type !== 'hasMany' || !field.inline || field.resource !== resource.name)
1291
- continue;
1292
- const parentId = candidate[field.foreignKey];
1293
- if (parentId === undefined || parentId === null)
1294
- continue;
1295
- if (existing[field.foreignKey] !== undefined &&
1296
- Number(existing[field.foreignKey]) !== Number(parentId))
1297
- throw new AdulaError(422, 'E_INLINE_PARENT', 'Inline records cannot be moved to another parent');
1298
- const action = parentWrite?.name === parent.name && parentWrite.id === Number(parentId)
1299
- ? parentWrite.action
1300
- : 'update';
1301
- let record;
1302
- if (system)
1303
- record = await this.findAny(trx, parent, Number(parentId), true);
1304
- else {
1305
- const ability = this.authorizeAction(parent, actor, action);
1306
- record = await this.find(trx, parent, actor, ability, Number(parentId), true);
1307
- this.requireRecord(ability, actor, parent, action, record);
1308
- if (!ability.can(action, subject(parent.name, record), key) ||
1309
- actor.permissionLevel <
1310
- Math.max(field.permissionLevel ?? 0, parent.hidden?.includes(key) ? 1 : 0))
1311
- throw new AdulaError(403, 'E_FIELD_FORBIDDEN', 'ليس لديك صلاحية تعديل البنود');
1312
- }
1313
- if (parent.submittable && record.docStatus !== 0)
1314
- throw new AdulaError(409, 'E_DOCUMENT_LOCKED', 'Only draft document lines can be edited');
1315
- if (parent.scoped &&
1316
- resource.scoped &&
1317
- Number(record.orgUnitId) !== Number(candidate.orgUnitId))
1318
- throw new AdulaError(422, 'E_INLINE_SCOPE', 'Inline records must use the parent organization');
1319
- }
1320
- }
146
+ /**
147
+ * Restores a soft-deleted record (ADR 046). Authorized by the actor's delete rule: its
148
+ * conditions and organization scope are evaluated on the deleted record (404 outside
149
+ * the scope or when the record is not deleted, 403 when a condition refuses). Records a
150
+ * `restore` activity and a `<module>.<resource>.restored` event.
151
+ */
152
+ async restore(name, id, actor, transaction) {
153
+ return restore(this.context, name, id, actor, transaction);
1321
154
  }
1322
- async transition(name, id, actor, action, version, transaction) {
1323
- const resource = this.registry.get(name);
1324
- const ability = this.authorizeAction(resource, actor, action);
1325
- const work = async (trx) => {
1326
- const record = await this.find(trx, resource, actor, ability, id, true);
1327
- this.requireRecord(ability, actor, resource, action, record);
1328
- this.requireVersion(resource, record, version);
1329
- await this.requireInlineParents(trx, resource, actor, record);
1330
- const values = { updated_by: actor.id, updated_at: trx.fn.now() };
1331
- if (resource.version)
1332
- values.version = Number(record.version) + 1;
1333
- if (action === 'delete') {
1334
- if (resource.submittable && record.docStatus !== 0)
1335
- throw new AdulaError(409, 'E_DOCUMENT_LOCKED', 'Only drafts can be deleted');
1336
- values.deleted_at = trx.fn.now();
1337
- }
1338
- else {
1339
- if (!resource.submittable || record.docStatus !== (action === 'submit' ? 0 : 1))
1340
- throw new AdulaError(409, 'E_DOCUMENT_STATE', 'Invalid document transition');
1341
- values.doc_status = action === 'submit' ? 1 : 2;
1342
- }
1343
- const [row] = await trx(name).where({ id }).update(values).returning('*');
1344
- const saved = fromRow(row, resource);
1345
- await this.audit(trx, resource, actor, action, saved, []);
1346
- return serialize(resource, await this.hydrateOne(trx, resource, saved), ability, actor);
1347
- };
1348
- return transaction ? work(transaction) : this.db.transaction(work);
155
+ /**
156
+ * The currently filtered list as CSV (BOM, CRLF), read through list() with the same
157
+ * authorization, filters, search, tag and sort; columns are the list fields the actor
158
+ * may read, as display values. Above EXPORT_ROW_LIMIT rows it is 422 E_EXPORT_LIMIT.
159
+ * Every export is recorded in the activity log (`core.exports`, `exported`).
160
+ */
161
+ async export(name, actor, options = {}) {
162
+ return exportCsv(this.context, name, actor, options);
1349
163
  }
1350
164
  /**
1351
165
  * Amend-by-copy: a cancelled document is copied into a new draft that points to
@@ -1353,96 +167,6 @@ export class ResourceService {
1353
167
  * cancelled and unchanged; sequence fields receive new numbers.
1354
168
  */
1355
169
  async amend(name, id, actor, transaction) {
1356
- const resource = this.registry.get(name);
1357
- if (!resource.submittable)
1358
- throw new AdulaError(409, 'E_DOCUMENT_STATE', 'Only submittable documents can be amended');
1359
- const ability = this.authorizeAction(resource, actor, 'amend');
1360
- const work = async (trx) => {
1361
- const source = await this.find(trx, resource, actor, ability, id, true);
1362
- this.requireRecord(ability, actor, resource, 'amend', source);
1363
- if (source.docStatus !== 2)
1364
- throw new AdulaError(409, 'E_DOCUMENT_STATE', 'Only cancelled documents can be amended');
1365
- const existing = await trx(name)
1366
- .where('amended_from_id', id)
1367
- .whereNull('deleted_at')
1368
- .first('id');
1369
- if (existing)
1370
- throw new AdulaError(409, 'E_ALREADY_AMENDED', 'تم تعديل هذا المستند بالنسخ من قبل');
1371
- const values = {
1372
- created_by: actor.id,
1373
- updated_by: actor.id,
1374
- doc_status: 0,
1375
- amended_from_id: id,
1376
- };
1377
- if (resource.scoped)
1378
- values.org_unit_id = source.orgUnitId;
1379
- if (resource.version)
1380
- values.version = 1;
1381
- const copied = [];
1382
- for (const [key, field] of Object.entries(resource.fields)) {
1383
- if (field.type === 'hasMany' || !(key in source))
1384
- continue;
1385
- const column = field.column ?? columnName(key);
1386
- if (field.sequence)
1387
- values[column] = await sequence(trx, field.sequence);
1388
- else if (field.type === 'attachment')
1389
- continue;
1390
- else {
1391
- values[column] = field.type === 'json' ? JSON.stringify(source[key]) : source[key];
1392
- copied.push(key);
1393
- }
1394
- }
1395
- const [row] = await trx(name).insert(values).returning('*');
1396
- const saved = { ...fromRow(row, resource), orgPath: source.orgPath };
1397
- for (const field of Object.values(resource.fields)) {
1398
- if (field.type !== 'hasMany' || !field.inline)
1399
- continue;
1400
- const child = this.registry.get(field.resource);
1401
- const foreign = child.fields[field.foreignKey].column ?? columnName(field.foreignKey);
1402
- const lines = await trx(child.name).where(foreign, id).whereNull('deleted_at').orderBy('id');
1403
- for (const line of lines) {
1404
- const copy = {
1405
- created_by: actor.id,
1406
- updated_by: actor.id,
1407
- [foreign]: row.id,
1408
- };
1409
- if (child.scoped)
1410
- copy.org_unit_id = line.org_unit_id;
1411
- if (child.version)
1412
- copy.version = 1;
1413
- for (const [key, childField] of Object.entries(child.fields)) {
1414
- const column = childField.column ?? columnName(key);
1415
- if (key === field.foreignKey ||
1416
- childField.type === 'hasMany' ||
1417
- childField.type === 'attachment' ||
1418
- !(column in line))
1419
- continue;
1420
- copy[column] = childField.sequence
1421
- ? await sequence(trx, childField.sequence)
1422
- : childField.type === 'json'
1423
- ? JSON.stringify(line[column])
1424
- : line[column];
1425
- }
1426
- const [inserted] = await trx(child.name).insert(copy).returning('id');
1427
- await this.audit(trx, child, actor, 'create', { id: inserted.id }, Object.keys(child.fields));
1428
- }
1429
- }
1430
- await this.audit(trx, resource, actor, 'amend', saved, copied);
1431
- return serialize(resource, await this.hydrateOne(trx, resource, saved), ability, actor);
1432
- };
1433
- return transaction ? work(transaction) : this.db.transaction(work);
1434
- }
1435
- async audit(trx, resource, actor, action, record, fields, changes, system) {
1436
- await recordMutation(trx, {
1437
- ...(system ? { system: true, reason: system.reason } : {}),
1438
- module: this.registry.owner(resource.name),
1439
- resource: resource.name,
1440
- id: record.id,
1441
- actorId: actor.id,
1442
- impersonatorId: actor.impersonatorId,
1443
- action,
1444
- fields,
1445
- changes,
1446
- });
170
+ return write.amend(this.context, name, id, actor, transaction);
1447
171
  }
1448
172
  }