adula 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -0,0 +1,603 @@
1
+ import { subject } from '@casl/ability';
2
+ import { columnName, joinTable } from '../../resource/define_resource.js';
3
+ import { isMultipleAttachment } from '../../resource/values.js';
4
+ import { applyVisibility, missingDefaults, resourceValidator, TEXT_LIKE, } from '../../resource/definition.js';
5
+ import { currentLanguage, labelText, translate } from '../../languages/catalog.js';
6
+ import { buildAbility } from '../../auth/ability.js';
7
+ import { accessibleBy } from '../../auth/sql.js';
8
+ import { fromRow, serialize, systemInput, writableInput } from '../contracts.js';
9
+ import { AdulaError, documentLocked, forbiddenField, inlineScope, invalidDocumentState, invalidInline, missingActor, notFound, requiredField, } from '../errors.js';
10
+ import { sequence } from '../../services/settings.js';
11
+ import { claimAttachment, rebindAttachment, isAttachmentId, releaseAttachment, } from '../../attachments/attachment_service.js';
12
+ import { authorizeAction, eligibleUsers, fieldLevel, find, findAny, hydrateOne, normalizeValues, requireParentView, requireRecord, withLinks, } from './shared.js';
13
+ import { audit, requireInlineParents, requireVersion, transition, } from './lifecycle.js';
14
+ /** A normalized value as its column binding: JSON columns are bound as JSON text. */
15
+ function storedValue(field, value) {
16
+ return (field.type === 'json' || field.type === 'multiSelect' || isMultipleAttachment(field)) &&
17
+ value !== null
18
+ ? JSON.stringify(value)
19
+ : value;
20
+ }
21
+ /** The attachment ids a field value holds: one id, the ordered ids of a multiple field, or none. */
22
+ function attachmentIds(value) {
23
+ if (Array.isArray(value))
24
+ return value.filter(isAttachmentId);
25
+ return isAttachmentId(value) ? [value] : [];
26
+ }
27
+ /**
28
+ * Runs a write and turns constraint violations on the resource's table into catalog
29
+ * errors: a unique violation (PostgreSQL 23505) becomes 409 E_DUPLICATE naming the fields
30
+ * of the violated index, single or composite; a NOT NULL violation (23502), such as a
31
+ * hidden visibleWhen field stored as null in a column created NOT NULL before the rule
32
+ * existed, becomes 422 E_NOT_NULL naming the field (adula:resource:migration relaxes it).
33
+ */
34
+ async function constraintViolations(resource, write) {
35
+ try {
36
+ return await write();
37
+ }
38
+ catch (error) {
39
+ const failure = error;
40
+ if (!['23505', '23502'].includes(failure?.code ?? '') || failure.table !== resource.name)
41
+ throw error;
42
+ const byColumn = new Map(Object.entries(resource.fields).map(([key, field]) => [
43
+ field.column ?? columnName(key),
44
+ field,
45
+ ]));
46
+ const label = (column) => column === 'org_unit_id'
47
+ ? translate('ui.form.orgUnit', currentLanguage())
48
+ : byColumn.get(column)
49
+ ? labelText(byColumn.get(column).label)
50
+ : column;
51
+ if (failure.code === '23502')
52
+ throw new AdulaError(422, 'E_NOT_NULL', failure.column
53
+ ? translate('errors.E_NOT_NULL.field', currentLanguage(), {
54
+ field: label(failure.column),
55
+ })
56
+ : translate('errors.E_NOT_NULL', currentLanguage()));
57
+ const columns = /^Key \(([^)]*)\)=/.exec(failure.detail ?? '')?.[1]?.split(', ') ?? [];
58
+ const labels = columns.map(label);
59
+ throw new AdulaError(409, 'E_DUPLICATE', labels.length
60
+ ? translate('errors.E_DUPLICATE.fields', currentLanguage(), { fields: labels.join('، ') })
61
+ : translate('errors.E_DUPLICATE', currentLanguage()));
62
+ }
63
+ }
64
+ /** Replaces the links of one manyToMany field by difference: removed pairs go, new pairs come. */
65
+ async function syncLinks(trx, resource, key, ownerId, before, after) {
66
+ const field = resource.fields[key];
67
+ if (field.type !== 'manyToMany')
68
+ return;
69
+ const join = joinTable(resource.name, key, field);
70
+ const removed = before.filter((target) => !after.includes(target));
71
+ const added = after.filter((target) => !before.includes(target));
72
+ if (removed.length)
73
+ await trx(join.table).where(join.owner, ownerId).whereIn(join.target, removed).delete();
74
+ if (added.length)
75
+ await trx(join.table).insert(added.map((target) => ({ [join.owner]: ownerId, [join.target]: target })));
76
+ }
77
+ /** A module-code write; see ResourceService.systemSave. */
78
+ export async function systemSave(ctx, name, values, id, options) {
79
+ const unattributed = options.actorId === null;
80
+ if (unattributed) {
81
+ if (id === undefined)
82
+ throw missingActor('systemSave requires the author user id to create');
83
+ const resource = ctx.registry.get(name);
84
+ // Attachments are claimed for their uploader; without one nothing can be claimed.
85
+ if (Object.keys(values).some((key) => resource.fields[key]?.type === 'attachment'))
86
+ throw missingActor('Attachment writes require the author user id');
87
+ }
88
+ else if (!Number.isSafeInteger(options.actorId) || Number(options.actorId) <= 0)
89
+ throw missingActor('systemSave requires the author user id');
90
+ const actor = {
91
+ id: unattributed ? 0 : Number(options.actorId),
92
+ orgPaths: [],
93
+ permissionLevel: 0,
94
+ rules: [],
95
+ };
96
+ return persist(ctx, name, actor, values, id, options.trx, undefined, {
97
+ reason: options.reason,
98
+ version: options.version,
99
+ chooser: options.chooser,
100
+ submitted: options.submitted,
101
+ unattributed,
102
+ });
103
+ }
104
+ /** Moves records whose scope follows a parent; see ResourceService.rehome. */
105
+ export async function rehome(ctx, parentName, parentId, options) {
106
+ const run = async (trx) => {
107
+ const parent = await findAny(trx, ctx.registry.get(parentName), parentId);
108
+ let moved = 0;
109
+ for (const child of ctx.registry.all()) {
110
+ const field = child.scope && child.fields[child.scope.from];
111
+ if (!field || field.type !== 'belongsTo' || field.resource !== parentName)
112
+ continue;
113
+ const column = field.column ?? columnName(child.scope.from);
114
+ const ids = await trx(child.name)
115
+ .where(column, parentId)
116
+ .whereNull('deleted_at')
117
+ .whereNot('org_unit_id', Number(parent.orgUnitId))
118
+ .orderBy('id')
119
+ .pluck('id');
120
+ for (const id of ids) {
121
+ await systemSave(ctx, child.name, {}, Number(id), { ...options, trx });
122
+ moved++;
123
+ }
124
+ }
125
+ return moved;
126
+ };
127
+ return options.trx ? run(options.trx) : ctx.db.transaction(run);
128
+ }
129
+ /**
130
+ * Creates or updates one record, for a user (save) or for module code (system). Every
131
+ * user write, every inline row and every amended copy goes through here.
132
+ */
133
+ export async function persist(ctx, name, actor, input, id, transaction, parentWrite, system) {
134
+ const { registry } = ctx;
135
+ const resource = registry.get(name);
136
+ const action = id === undefined ? 'create' : 'update';
137
+ // System writes carry no role rules; this ability is used only for serialization shape.
138
+ const ability = system
139
+ ? buildAbility([{ action: 'manage', subject: 'all' }], registry.all())
140
+ : authorizeAction(ctx, resource, actor, action);
141
+ const form = system ? systemInput(resource, input) : writableInput(resource, input);
142
+ const load = (db, target, key, lock = false) => system ? findAny(db, target, key, lock) : find(db, target, actor, ability, key, lock);
143
+ const check = (target, act, record) => {
144
+ if (!system)
145
+ requireRecord(ability, actor, target, act, record);
146
+ };
147
+ const validator = resourceValidator(resource);
148
+ // Declared defaults fill the keys a create leaves out, before validation (see Field.default).
149
+ const defaults = id === undefined ? missingDefaults(resource, form) : {};
150
+ const formDefaults = Object.fromEntries(Object.entries(defaults).filter(([key]) => resource.form.includes(key)));
151
+ const validated = system ? {} : await validator.validate({ ...formDefaults, ...form });
152
+ const work = async (trx) => {
153
+ const existing = id === undefined ? {} : await load(trx, resource, id, true);
154
+ if (id !== undefined) {
155
+ check(resource, action, existing);
156
+ if (!system || system.version !== undefined)
157
+ requireVersion(resource, existing, system ? system.version : input.version);
158
+ if (resource.submittable &&
159
+ existing.docStatus !== 0 &&
160
+ !(system?.submitted && existing.docStatus === 1))
161
+ throw documentLocked();
162
+ }
163
+ if (system) {
164
+ // The validator sees the complete form, so a partial update keeps required values.
165
+ const formKeys = resource.form.filter((key) => resource.fields[key].type !== 'hasMany');
166
+ const pick = (record) => Object.fromEntries(formKeys.filter((key) => key in record).map((key) => [key, record[key]]));
167
+ Object.assign(validated, await validator.validate({ ...pick(existing), ...pick(defaults), ...pick(form) }), Object.fromEntries(Object.entries(form).filter(([key]) => !formKeys.includes(key))));
168
+ }
169
+ const candidate = {
170
+ ...existing,
171
+ ...defaults,
172
+ ...validated,
173
+ createdBy: existing.createdBy ?? actor.id,
174
+ updatedBy: system?.unattributed ? existing.updatedBy : actor.id,
175
+ };
176
+ if (resource.submittable)
177
+ candidate.docStatus = existing.docStatus ?? 0;
178
+ normalizeValues(resource, candidate);
179
+ applyVisibility(resource, candidate);
180
+ const locate = async () => {
181
+ if (!resource.scoped)
182
+ return;
183
+ if (resource.scope) {
184
+ // Inherited scope: the parent decides the unit before any authorization (#45).
185
+ const field = resource.fields[resource.scope.from];
186
+ const parentId = Number(candidate[resource.scope.from]);
187
+ if (field.type !== 'belongsTo' || !Number.isSafeInteger(parentId) || parentId <= 0)
188
+ throw requiredField(resource.scope.from);
189
+ const parentResource = registry.get(field.resource);
190
+ const parent = await load(trx, parentResource, parentId);
191
+ if (!system)
192
+ requireParentView(ability, actor, resource, parentResource, parent);
193
+ candidate.orgUnitId = parent.orgUnitId;
194
+ }
195
+ else if (!system || 'orgUnitId' in input || id === undefined) {
196
+ candidate.orgUnitId = input.orgUnitId ?? existing.orgUnitId;
197
+ // A user write without a unit names the missing field (#130, #132); a unit that does
198
+ // not exist or lies outside the actor's scope stays 404 below. System writes keep
199
+ // their 422 E_ORG_UNIT.
200
+ if (!system && [undefined, null, ''].includes(candidate.orgUnitId))
201
+ throw new AdulaError(422, 'E_REQUIRED', `${translate('ui.form.orgUnit', currentLanguage())}: ${translate('validation.required', currentLanguage())}`);
202
+ }
203
+ const unit = await trx('org_units')
204
+ .where('id', Number(candidate.orgUnitId) || -1)
205
+ .first('path');
206
+ if (system && !unit)
207
+ throw new AdulaError(422, 'E_ORG_UNIT', 'الوحدة التنظيمية غير موجودة');
208
+ candidate.orgPath = unit?.path;
209
+ };
210
+ await locate();
211
+ check(resource, action, candidate);
212
+ // Validators may add fields (defaults, transforms); those are written too, so check them.
213
+ const written = new Set(system
214
+ ? []
215
+ : [
216
+ ...Object.keys(form),
217
+ // A declared default is the definition's choice, not the actor's write.
218
+ ...Object.keys(validated).filter((key) => key in resource.fields &&
219
+ !(key in defaults &&
220
+ !(key in form) &&
221
+ JSON.stringify(validated[key]) === JSON.stringify(defaults[key]))),
222
+ ]);
223
+ for (const key of written) {
224
+ const field = resource.fields[key];
225
+ if (!ability.can(action, subject(name, candidate), key) ||
226
+ (id !== undefined && !ability.can(action, subject(name, existing), key)) ||
227
+ actor.permissionLevel < fieldLevel(resource, key))
228
+ throw forbiddenField(`Field is forbidden: ${key}`);
229
+ if (field.sequence)
230
+ throw new AdulaError(422, 'E_SEQUENCE_READONLY', 'Sequence fields are generated');
231
+ }
232
+ for (const [key, field] of Object.entries(resource.fields))
233
+ if (field.sequence && id === undefined)
234
+ candidate[key] = await sequence(trx, field.sequence);
235
+ const context = { trx, userId: actor.id, action };
236
+ await resource.hooks?.beforeSave?.(candidate, context);
237
+ normalizeValues(resource, candidate);
238
+ // Hidden fields store null whatever the input or a hook supplied (Field.visibleWhen).
239
+ // A field the actor may not write keeps its stored value instead: changing the
240
+ // controlling field must not wipe values (or links) the actor cannot write.
241
+ const hidden = applyVisibility(resource, candidate, {
242
+ existing: id === undefined ? undefined : existing,
243
+ writable: (key) => Boolean(system) ||
244
+ (ability.can(action, subject(name, candidate), key) &&
245
+ ability.can(action, subject(name, existing), key) &&
246
+ actor.permissionLevel >= fieldLevel(resource, key)),
247
+ });
248
+ // A hook may change the parent of an inherited scope; the unit follows it.
249
+ if (resource.scope)
250
+ await locate();
251
+ // A hook may also move the record: later checks use the unit it chose.
252
+ if (resource.scoped) {
253
+ const unit = await trx('org_units')
254
+ .where('id', Number(candidate.orgUnitId) || -1)
255
+ .first('path');
256
+ candidate.orgPath = unit?.path;
257
+ }
258
+ for (const [key, field] of Object.entries(resource.fields)) {
259
+ if (field.required &&
260
+ field.type !== 'hasMany' &&
261
+ !hidden.has(key) &&
262
+ (candidate[key] === null ||
263
+ candidate[key] === undefined ||
264
+ ((['multiSelect', 'manyToMany'].includes(field.type) || isMultipleAttachment(field)) &&
265
+ Array.isArray(candidate[key]) &&
266
+ candidate[key].length === 0) ||
267
+ // Whatever a validator or hook returned, a blank required text is missing.
268
+ (TEXT_LIKE.includes(field.type) &&
269
+ typeof candidate[key] === 'string' &&
270
+ !candidate[key].trim())))
271
+ throw requiredField(key);
272
+ // A link is checked when it is made or changed, like manyToMany links below (ADR 045):
273
+ // an unchanged value never blocks an edit after its target was deleted or moved out
274
+ // of the writer's scope (#130). The comparison runs after the hooks, so a link a hook
275
+ // changes is checked too.
276
+ if (field.type === 'belongsTo' &&
277
+ candidate[key] !== null &&
278
+ candidate[key] !== undefined &&
279
+ (id === undefined || Number(candidate[key]) !== Number(existing[key]))) {
280
+ const related = registry.get(field.resource);
281
+ const target = await load(trx, related, Number(candidate[key]));
282
+ check(related, 'view', target);
283
+ }
284
+ // Every newly linked record must be viewable, like a belongsTo value; links kept
285
+ // unchanged are not re-checked, so an edit never fails on a record moved out of scope.
286
+ // One query for all of them: the live targets the actor may view (scope and rules
287
+ // as SQL); any target missing from the count is 404, like an unviewable belongsTo.
288
+ if (field.type === 'manyToMany' && Array.isArray(candidate[key])) {
289
+ const related = registry.get(field.resource);
290
+ const before = new Set(Array.isArray(existing[key]) ? existing[key] : []);
291
+ const added = [...new Set(candidate[key])].filter((target) => !before.has(target));
292
+ if (added.length) {
293
+ const targets = trx(`${related.name} as r`)
294
+ .whereNull('r.deleted_at')
295
+ .whereIn('r.id', added);
296
+ if (!system)
297
+ accessibleBy(targets, ability, actor, 'view', related);
298
+ const [{ count }] = await targets.count({ count: 'r.id' });
299
+ if (Number(count) !== added.length)
300
+ throw notFound();
301
+ }
302
+ }
303
+ // A new user, or a record moved by a user to another unit, needs an eligible user.
304
+ // An unchanged value never blocks other edits, even after the account is disabled.
305
+ if (field.type === 'user' &&
306
+ candidate[key] !== null &&
307
+ candidate[key] !== undefined &&
308
+ (Number(candidate[key]) !== Number(existing[key]) ||
309
+ (!system &&
310
+ resource.scoped &&
311
+ Number(candidate.orgUnitId) !== Number(existing.orgUnitId)))) {
312
+ const eligible = await eligibleUsers(trx, resource.scoped ? String(candidate.orgPath ?? '') || null : null, system ? (system.chooser ?? null) : actor)
313
+ .where('u.id', Number(candidate[key]))
314
+ .first('u.id');
315
+ if (!eligible || (resource.scoped && !candidate.orgPath))
316
+ throw new AdulaError(422, 'E_USER_FIELD', `${key}: اختر مستخدماً نشطاً من الوحدة التنظيمية للسجل أو الوحدات الأعلى منها`);
317
+ }
318
+ // Shared lock: a value disabled or deleted by an administrator in a concurrent transaction
319
+ // cannot be stored after the check (LookupsAdmin refuses while a stored record uses it).
320
+ if (field.type === 'lookup' && candidate[key] !== null && candidate[key] !== undefined) {
321
+ if (!(await trx('lookups')
322
+ .where({ group: field.group, key: candidate[key], active: true })
323
+ .forShare()
324
+ .first()))
325
+ throw new AdulaError(422, 'E_LOOKUP', `Invalid lookup: ${key}`);
326
+ }
327
+ // Each newly added file is claimed by its uploader; a new record's files are verified
328
+ // here and bound once its id exists. Files the record already holds follow it to a new
329
+ // unit without the uploader check, so files from several uploaders never block a move.
330
+ if (field.type === 'attachment') {
331
+ const before = new Set(attachmentIds(existing[key]));
332
+ const moved = id !== undefined &&
333
+ resource.scoped &&
334
+ Number(candidate.orgUnitId) !== Number(existing.orgUnitId);
335
+ const kept = key in candidate ? attachmentIds(candidate[key]) : [...before];
336
+ for (const attachmentId of kept)
337
+ if (!before.has(attachmentId))
338
+ await claimAttachment(trx, {
339
+ attachmentId,
340
+ actor,
341
+ resource: name,
342
+ field: key,
343
+ recordId: id,
344
+ orgUnitId: resource.scoped ? Number(candidate.orgUnitId) : null,
345
+ scoped: resource.scoped,
346
+ });
347
+ else if (moved)
348
+ await rebindAttachment(trx, {
349
+ attachmentId,
350
+ resource: name,
351
+ field: key,
352
+ recordId: id,
353
+ orgUnitId: Number(candidate.orgUnitId),
354
+ });
355
+ }
356
+ }
357
+ // Hooks may calculate fields, but may never move a record past authorization.
358
+ check(resource, action, candidate);
359
+ await requireInlineParents(ctx, trx, resource, actor, candidate, existing, parentWrite, Boolean(system));
360
+ if (id !== undefined &&
361
+ resource.scoped &&
362
+ Number(candidate.orgUnitId) !== Number(existing.orgUnitId)) {
363
+ for (const field of Object.values(resource.fields)) {
364
+ if (field.type !== 'hasMany' || !field.inline)
365
+ continue;
366
+ const child = registry.get(field.resource);
367
+ if (await trx(child.name)
368
+ .where(child.fields[field.foreignKey].column ?? columnName(field.foreignKey), id)
369
+ .whereNull('deleted_at')
370
+ .first('id'))
371
+ throw inlineScope('Cannot change organization while inline rows exist');
372
+ }
373
+ }
374
+ const values = { updated_at: trx.fn.now() };
375
+ if (!system?.unattributed)
376
+ values.updated_by = actor.id;
377
+ if (id === undefined)
378
+ values.created_by = actor.id;
379
+ if (resource.scoped)
380
+ values.org_unit_id = candidate.orgUnitId;
381
+ if (resource.version)
382
+ values.version = id === undefined ? 1 : Number(existing.version) + 1;
383
+ for (const [key, field] of Object.entries(resource.fields)) {
384
+ if (field.type !== 'hasMany' && field.type !== 'manyToMany' && key in candidate)
385
+ values[field.column ?? columnName(key)] = storedValue(field, candidate[key]);
386
+ }
387
+ const [row] = await constraintViolations(resource, () => id === undefined
388
+ ? trx(name).insert(values).returning('*')
389
+ : trx(name).where({ id }).update(values).returning('*'));
390
+ const saved = { ...fromRow(row, resource), orgPath: candidate.orgPath };
391
+ for (const [key, field] of Object.entries(resource.fields)) {
392
+ if (field.type !== 'manyToMany')
393
+ continue;
394
+ const before = Array.isArray(existing[key]) ? existing[key] : [];
395
+ const after = key in candidate ? (candidate[key] ?? []) : before;
396
+ await syncLinks(trx, resource, key, Number(row.id), before, after);
397
+ saved[key] = after;
398
+ }
399
+ for (const [key, field] of Object.entries(resource.fields)) {
400
+ if (field.type !== 'attachment' || !(key in candidate))
401
+ continue;
402
+ const next = attachmentIds(candidate[key]);
403
+ if (id === undefined)
404
+ for (const attachmentId of next)
405
+ await claimAttachment(trx, {
406
+ attachmentId,
407
+ actor,
408
+ resource: name,
409
+ field: key,
410
+ recordId: Number(row.id),
411
+ orgUnitId: resource.scoped ? Number(candidate.orgUnitId) : null,
412
+ scoped: resource.scoped,
413
+ });
414
+ // A removed file is released; reordering only rewrites the column.
415
+ for (const previous of attachmentIds(existing[key]))
416
+ if (!next.includes(previous))
417
+ await releaseAttachment(trx, previous);
418
+ }
419
+ const inline = await writeInlineRows(ctx, trx, resource, actor, form, id, row, candidate, action);
420
+ const changes = [];
421
+ if (id !== undefined)
422
+ for (const key of Object.keys(resource.fields)) {
423
+ if (resource.fields[key].type === 'hasMany' || !(key in saved))
424
+ continue;
425
+ const before = existing[key] ?? null;
426
+ const after = saved[key] ?? null;
427
+ if (JSON.stringify(before) !== JSON.stringify(after))
428
+ changes.push({ field: key, before, after });
429
+ }
430
+ // An inline row tells its parent's write whether it changed anything.
431
+ if (parentWrite && (id === undefined || changes.length))
432
+ parentWrite.changed = true;
433
+ // A create names the submitted keys; an update names what changed (the field history
434
+ // holds the values) and the inline line groups whose rows were written, never every
435
+ // submitted key.
436
+ const fields = id === undefined ? Object.keys(form) : [...changes.map(({ field }) => field), ...inline];
437
+ if (!system?.unattributed)
438
+ await audit(ctx, trx, resource, actor, action, saved, fields, changes, system);
439
+ await resource.hooks?.afterSave?.(saved, context);
440
+ if (system)
441
+ return (await hydrateOne(trx, resource, saved, ctx.attachments));
442
+ return serialize(resource, await hydrateOne(trx, resource, saved, ctx.attachments), ability, actor);
443
+ };
444
+ return transaction ? work(transaction) : ctx.db.transaction(work);
445
+ }
446
+ /**
447
+ * Creates, updates and deletes the inline rows submitted with a parent write. Each row
448
+ * is authorized and written through persist() (or transition() for deletions). Returns
449
+ * the hasMany keys whose rows were created, changed or deleted.
450
+ */
451
+ async function writeInlineRows(ctx, trx, resource, actor, form, id, row, candidate, action) {
452
+ const name = resource.name;
453
+ const written = [];
454
+ for (const [key, field] of Object.entries(resource.fields)) {
455
+ if (field.type !== 'hasMany' || !(key in form))
456
+ continue;
457
+ if (!field.inline || !Array.isArray(form[key]) || form[key].length > 100)
458
+ throw invalidInline('Invalid inline rows (maximum 100)');
459
+ const childResource = ctx.registry.get(field.resource);
460
+ const seen = new Set();
461
+ for (const child of form[key]) {
462
+ if (!child || typeof child !== 'object' || Array.isArray(child))
463
+ throw invalidInline('Inline rows must be objects');
464
+ const { id: childId, _delete: remove, ...data } = child;
465
+ // Inline rows are not offered manyToMany fields (editor.ts); a submitted value is
466
+ // ignored so a row saved without its links never clears them.
467
+ for (const [childKey, childField] of Object.entries(childResource.fields))
468
+ if (childField.type === 'manyToMany')
469
+ delete data[childKey];
470
+ if (remove !== undefined && typeof remove !== 'boolean')
471
+ throw invalidInline('Invalid deletion marker');
472
+ if (childId !== undefined) {
473
+ if (id === undefined ||
474
+ !Number.isSafeInteger(childId) ||
475
+ Number(childId) <= 0 ||
476
+ seen.has(Number(childId)))
477
+ throw invalidInline('Invalid or repeated inline record identifier');
478
+ seen.add(Number(childId));
479
+ const childAbility = authorizeAction(ctx, childResource, actor, remove ? 'delete' : 'update');
480
+ const owned = await find(trx, childResource, actor, childAbility, Number(childId), true);
481
+ if (Number(owned[field.foreignKey]) !== Number(row.id))
482
+ throw notFound();
483
+ }
484
+ if (remove) {
485
+ if (childId === undefined)
486
+ throw invalidInline('Deleting an inline row requires its identifier');
487
+ await transition(ctx, field.resource, Number(childId), actor, 'delete', data.version, trx);
488
+ if (!written.includes(key))
489
+ written.push(key);
490
+ continue;
491
+ }
492
+ const parent = { name, id: Number(row.id), action };
493
+ await persist(ctx, field.resource, actor, {
494
+ ...data,
495
+ [field.foreignKey]: row.id,
496
+ ...(childResource.scoped && !childResource.scope
497
+ ? { orgUnitId: candidate.orgUnitId }
498
+ : {}),
499
+ }, childId === undefined ? undefined : Number(childId), trx, parent);
500
+ if (parent.changed && !written.includes(key))
501
+ written.push(key);
502
+ }
503
+ }
504
+ return written;
505
+ }
506
+ /**
507
+ * Amend-by-copy: a cancelled document is copied into a new draft that points to
508
+ * it through amended_from_id, together with its inline lines. The original stays
509
+ * cancelled and unchanged; sequence fields receive new numbers.
510
+ */
511
+ export async function amend(ctx, name, id, actor, transaction) {
512
+ const resource = ctx.registry.get(name);
513
+ if (!resource.submittable)
514
+ throw invalidDocumentState('Only submittable documents can be amended');
515
+ const ability = authorizeAction(ctx, resource, actor, 'amend');
516
+ const work = async (trx) => {
517
+ const source = await find(trx, resource, actor, ability, id, true);
518
+ requireRecord(ability, actor, resource, 'amend', source);
519
+ if (source.docStatus !== 2)
520
+ throw invalidDocumentState('Only cancelled documents can be amended');
521
+ const existing = await trx(name)
522
+ .where('amended_from_id', id)
523
+ .whereNull('deleted_at')
524
+ .first('id');
525
+ if (existing)
526
+ throw new AdulaError(409, 'E_ALREADY_AMENDED', 'تم تعديل هذا المستند بالنسخ من قبل');
527
+ const values = {
528
+ created_by: actor.id,
529
+ updated_by: actor.id,
530
+ doc_status: 0,
531
+ amended_from_id: id,
532
+ };
533
+ if (resource.scoped)
534
+ values.org_unit_id = source.orgUnitId;
535
+ if (resource.version)
536
+ values.version = 1;
537
+ const copied = [];
538
+ for (const [key, field] of Object.entries(resource.fields)) {
539
+ if (field.type === 'hasMany' || field.type === 'manyToMany' || !(key in source))
540
+ continue;
541
+ const column = field.column ?? columnName(key);
542
+ if (field.sequence)
543
+ values[column] = await sequence(trx, field.sequence);
544
+ else if (field.type === 'attachment')
545
+ continue;
546
+ else {
547
+ values[column] = storedValue(field, source[key]);
548
+ copied.push(key);
549
+ }
550
+ }
551
+ const [row] = await constraintViolations(resource, () => trx(name).insert(values).returning('*'));
552
+ const saved = { ...fromRow(row, resource), orgPath: source.orgPath };
553
+ // The copy links the same records as the cancelled original.
554
+ for (const [key, field] of Object.entries(resource.fields)) {
555
+ if (field.type !== 'manyToMany' || !Array.isArray(source[key]))
556
+ continue;
557
+ await syncLinks(trx, resource, key, Number(row.id), [], source[key]);
558
+ saved[key] = source[key];
559
+ copied.push(key);
560
+ }
561
+ for (const [lineKey, field] of Object.entries(resource.fields)) {
562
+ if (field.type !== 'hasMany' || !field.inline)
563
+ continue;
564
+ const child = ctx.registry.get(field.resource);
565
+ const foreign = child.fields[field.foreignKey].column ?? columnName(field.foreignKey);
566
+ const lines = await trx(child.name).where(foreign, id).whereNull('deleted_at').orderBy('id');
567
+ if (!lines.length)
568
+ continue;
569
+ if (!ability.can('amend', subject(name, source), lineKey) ||
570
+ actor.permissionLevel < fieldLevel(resource, lineKey))
571
+ throw forbiddenField('ليس لديك صلاحية تعديل البنود');
572
+ // Copies are new child records: they go through persist(), so the actor needs
573
+ // create on the child resource and its field rules, validator and hooks apply.
574
+ const childAbility = authorizeAction(ctx, child, actor, 'create');
575
+ // With their manyToMany links, so the copied lines link the same records.
576
+ const storedLines = await withLinks(trx, child, lines.map((line) => fromRow(line, child)));
577
+ for (const stored of storedLines) {
578
+ const data = {};
579
+ for (const key of child.form) {
580
+ const childField = child.fields[key];
581
+ if (key === field.foreignKey ||
582
+ !(key in stored) ||
583
+ childField.type === 'hasMany' ||
584
+ childField.type === 'attachment' ||
585
+ childField.sequence ||
586
+ // Values the actor could not have entered are not carried into the copy.
587
+ !childAbility.can('create', child.name, key) ||
588
+ actor.permissionLevel < fieldLevel(child, key))
589
+ continue;
590
+ data[key] = stored[key];
591
+ }
592
+ await persist(ctx, child.name, actor, {
593
+ ...data,
594
+ [field.foreignKey]: row.id,
595
+ ...(child.scoped && !child.scope ? { orgUnitId: saved.orgUnitId } : {}),
596
+ }, undefined, trx, { name, id: Number(row.id), action: 'amend' });
597
+ }
598
+ }
599
+ await audit(ctx, trx, resource, actor, 'amend', saved, copied);
600
+ return serialize(resource, await hydrateOne(trx, resource, saved, ctx.attachments), ability, actor);
601
+ };
602
+ return transaction ? work(transaction) : ctx.db.transaction(work);
603
+ }