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,345 @@
1
+ import { subject } from '@casl/ability';
2
+ import { columnName } from '../../resource/define_resource.js';
3
+ import { inOrgScope } from '../../auth/ability.js';
4
+ import { accessibleBy } from '../../auth/sql.js';
5
+ import { fromRow, serialize } from '../contracts.js';
6
+ import { AdulaError, documentLocked, forbiddenField, invalidCursor } from '../errors.js';
7
+ import { attachmentLimit, fieldValue } from '../../resource/values.js';
8
+ import { escapeLike } from '../../core/like.js';
9
+ import { avatarUrlFor, avatarVersionColumn } from '../../core/user_avatars.js';
10
+ import { labelText } from '../../languages/catalog.js';
11
+ import { authorizeAction, columns, eligibleUsers, fieldLevel, find, hydrate, hydrateOne, requireRecord, } from './shared.js';
12
+ import { describe, show, titler } from './read.js';
13
+ import { list } from './query.js';
14
+ /** Whether an error only means the actor cannot open a related record. */
15
+ const unreachable = (error) => error instanceof AdulaError && [403, 404].includes(error.status);
16
+ /** The form description for create (no id) or update; see ResourceService.editor. */
17
+ export async function editor(ctx, name, actor, id, request = {}) {
18
+ const { db, registry } = ctx;
19
+ const resource = registry.get(name);
20
+ const action = id === undefined ? 'create' : 'update';
21
+ const ability = authorizeAction(ctx, resource, actor, action);
22
+ const record = id === undefined ? undefined : await find(db, resource, actor, ability, id);
23
+ if (record) {
24
+ requireRecord(ability, actor, resource, action, record);
25
+ if (resource.submittable && record.docStatus !== 0)
26
+ throw documentLocked();
27
+ }
28
+ const fields = resource.form
29
+ .filter((key) => {
30
+ const field = resource.fields[key];
31
+ return (!field.sequence &&
32
+ actor.permissionLevel >= fieldLevel(resource, key) &&
33
+ ability.can(action, record ? subject(name, record) : name, key));
34
+ })
35
+ .map((key) => editorField(key, resource.fields[key]));
36
+ // User choices also carry the person's picture (null without one, ADR 050).
37
+ const options = {};
38
+ const relationSearch = {};
39
+ const onlyChoice = new Map();
40
+ const inline = {};
41
+ for (const field of fields) {
42
+ if (field.type === 'hasMany' && field.inline) {
43
+ const child = registry.get(field.resource);
44
+ const rows = record && ability.can('view', child.name)
45
+ ? await accessibleBy(db(`${child.name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', child)
46
+ .where(`r.${child.fields[field.foreignKey].column ?? columnName(field.foreignKey)}`, id)
47
+ .select([
48
+ ...columns(child, ability),
49
+ ...(child.scoped ? ['ou.path as org_path'] : []),
50
+ ])
51
+ .orderBy('r.id')
52
+ .limit(101)
53
+ : [];
54
+ const records = rows.slice(0, 100).map((row) => fromRow(row, child));
55
+ const hydratedRows = await hydrate(db, child, records, ctx.attachments);
56
+ // Inline rows do not edit many-to-many links: rows load without them, and an
57
+ // inline payload's manyToMany keys are ignored (write.ts writeInlineRows).
58
+ const childFields = child.form.filter((key) => key !== field.foreignKey &&
59
+ child.fields[key].type !== 'manyToMany' &&
60
+ !child.fields[key].sequence &&
61
+ actor.permissionLevel >= fieldLevel(child, key));
62
+ inline[field.key] = {
63
+ fields: childFields.map((key) => editorField(key, child.fields[key])),
64
+ createFields: childFields.filter((key) => ability.can('create', child.name, key)),
65
+ updateFields: Object.fromEntries(records.map((row) => [
66
+ String(row.id),
67
+ childFields.filter((key) => ability.can('update', subject(child.name, row), key)),
68
+ ])),
69
+ rows: hydratedRows.map((row) => serialize(child, row, ability, actor)),
70
+ hasMore: rows.length > 100,
71
+ canCreate: child.actions.includes('create') && ability.can('create', child.name),
72
+ permissions: Object.fromEntries(records.map((row) => [
73
+ String(row.id),
74
+ {
75
+ update: child.actions.includes('update') && ability.can('update', subject(child.name, row)),
76
+ delete: child.actions.includes('delete') && ability.can('delete', subject(child.name, row)),
77
+ },
78
+ ])),
79
+ };
80
+ }
81
+ if (field.type === 'lookup') {
82
+ const lookups = await db('lookups')
83
+ .where({ group: field.group, active: true })
84
+ .orderBy('id')
85
+ .select('key', 'label_ar');
86
+ options[field.key] = lookups.map((row) => ({ value: row.key, label: row.label_ar }));
87
+ }
88
+ else if (field.type === 'enum' || field.type === 'multiSelect') {
89
+ options[field.key] = field.options.map((option) => ({
90
+ value: option.value,
91
+ label: labelText(option.label),
92
+ }));
93
+ }
94
+ else if (field.type === 'belongsTo' || field.type === 'manyToMany') {
95
+ const target = registry.get(field.resource);
96
+ if (ability.can('view', target.name)) {
97
+ relationSearch[field.key] = describe(ctx, target.name, actor).searchable;
98
+ const page = await list(ctx, target.name, actor, { limit: 50, estimate: false });
99
+ const title = await titler(ctx, target);
100
+ options[field.key] = page.data.map((row) => ({
101
+ value: String(row.id),
102
+ label: title(row) ?? `#${row.id}`,
103
+ }));
104
+ if (field.type === 'belongsTo' &&
105
+ field.required &&
106
+ page.data.length === 1 &&
107
+ page.meta.nextCursor === null)
108
+ onlyChoice.set(field.key, Number(page.data[0].id));
109
+ const value = record?.[field.key];
110
+ // Current values outside the first page keep a labelled choice when still viewable.
111
+ for (const selected of Array.isArray(value) ? value : [value]) {
112
+ if (selected === null ||
113
+ selected === undefined ||
114
+ options[field.key].some((option) => option.value === String(selected)))
115
+ continue;
116
+ try {
117
+ const current = await show(ctx, target.name, Number(selected), actor);
118
+ options[field.key].push({
119
+ value: String(current.data.id),
120
+ label: title(current.data) ?? `#${current.data.id}`,
121
+ });
122
+ }
123
+ catch (error) {
124
+ if (!unreachable(error))
125
+ throw error;
126
+ }
127
+ }
128
+ }
129
+ else
130
+ options[field.key] = [];
131
+ }
132
+ else if (field.type === 'user') {
133
+ // Choices depend on the unit chosen in the form; they load from relationOptions.
134
+ relationSearch[field.key] = true;
135
+ options[field.key] = [];
136
+ const selected = record?.[field.key];
137
+ if (selected !== null && selected !== undefined) {
138
+ const current = await db('users as u')
139
+ .where('u.id', Number(selected))
140
+ .first('u.id', 'u.full_name', avatarVersionColumn(db, 'u.id'));
141
+ if (current)
142
+ options[field.key].push({
143
+ value: String(current.id),
144
+ label: String(current.full_name || `#${current.id}`),
145
+ avatarUrl: avatarUrlFor(current.id, current.avatar_version),
146
+ });
147
+ }
148
+ }
149
+ }
150
+ const units = resource.scoped && !resource.scope
151
+ ? await db('org_units')
152
+ .where((query) => {
153
+ if (!actor.orgPaths.length)
154
+ query.whereRaw('FALSE');
155
+ for (const path of actor.orgPaths)
156
+ query.orWhereRaw('path <@ ?::ltree', [path]);
157
+ })
158
+ .orderBy('path')
159
+ .limit(100)
160
+ .select('id', 'name')
161
+ : [];
162
+ if (record?.orgUnitId && !units.some((unit) => Number(unit.id) === Number(record.orgUnitId))) {
163
+ const current = await db('org_units').where('id', Number(record.orgUnitId)).first('id', 'name');
164
+ if (current)
165
+ units.push(current);
166
+ }
167
+ const defaults = {};
168
+ // Declared field defaults prefill a create form; requested defaults below override them.
169
+ if (id === undefined)
170
+ for (const field of fields)
171
+ if (field.default !== undefined && field.default !== null)
172
+ defaults[field.key] = Array.isArray(field.default)
173
+ ? [...field.default]
174
+ : field.default;
175
+ const requested = request.defaults;
176
+ if (id === undefined && requested && typeof requested === 'object')
177
+ for (const field of fields) {
178
+ const raw = Object.hasOwn(requested, field.key) ? requested[field.key] : undefined;
179
+ if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean')
180
+ continue;
181
+ let value = raw;
182
+ try {
183
+ if (['integer', 'belongsTo', 'user'].includes(field.type))
184
+ value = Number(raw);
185
+ else if (field.type === 'boolean')
186
+ value = raw === true || raw === 'true';
187
+ else
188
+ value = String(raw);
189
+ value = fieldValue(field, value);
190
+ }
191
+ catch {
192
+ continue;
193
+ }
194
+ if (['attachment', 'json', 'hasMany'].includes(field.type))
195
+ continue;
196
+ if (field.type === 'user') {
197
+ // The unit is chosen later in the form; saving checks the record's unit.
198
+ const user = await eligibleUsers(db, null, actor)
199
+ .where('u.id', Number(value))
200
+ .first('u.id', 'u.full_name', avatarVersionColumn(db, 'u.id'));
201
+ if (!user)
202
+ continue;
203
+ const choices = options[field.key] ?? (options[field.key] = []);
204
+ if (!choices.some((option) => option.value === String(user.id)))
205
+ choices.push({
206
+ value: String(user.id),
207
+ label: String(user.full_name || `#${user.id}`),
208
+ avatarUrl: avatarUrlFor(user.id, user.avatar_version),
209
+ });
210
+ }
211
+ if (field.type === 'lookup' || field.type === 'belongsTo') {
212
+ const choices = options[field.key] ?? [];
213
+ if (!choices.some((option) => option.value === String(value))) {
214
+ if (field.type === 'lookup')
215
+ continue;
216
+ try {
217
+ // Authorized exactly like opening the related record.
218
+ const target = registry.get(field.resource);
219
+ const current = await show(ctx, target.name, Number(value), actor);
220
+ const title = await titler(ctx, target);
221
+ choices.push({
222
+ value: String(current.data.id),
223
+ label: title(current.data) ?? `#${current.data.id}`,
224
+ });
225
+ }
226
+ catch (error) {
227
+ if (!unreachable(error))
228
+ throw error;
229
+ continue;
230
+ }
231
+ }
232
+ }
233
+ defaults[field.key] = value;
234
+ }
235
+ // A required belongsTo whose actor can choose only one record starts on it (#115, ADR 030);
236
+ // saving still authorizes the reference.
237
+ if (id === undefined)
238
+ for (const [key, only] of onlyChoice)
239
+ if (defaults[key] === undefined)
240
+ defaults[key] = only;
241
+ return {
242
+ mode: action,
243
+ name,
244
+ label: resource.label.ar,
245
+ recordLabel: resource.recordLabel?.ar ?? null,
246
+ fields,
247
+ /** Initial values of a create form, already checked against the actor's access. */
248
+ defaults,
249
+ inline,
250
+ options,
251
+ relationSearch,
252
+ orgUnits: units.map((row) => ({ value: String(row.id), label: String(row.name) })),
253
+ scoped: resource.scoped,
254
+ /** The belongsTo field whose record decides the unit; the form shows no unit picker. */
255
+ scopeFrom: resource.scope?.from ?? null,
256
+ record: record
257
+ ? serialize(resource, await hydrateOne(db, resource, record, ctx.attachments), ability, actor)
258
+ : null,
259
+ };
260
+ }
261
+ /** Choices of a belongsTo or user field in a form or filter; see ResourceService.relationOptions. */
262
+ export async function relationOptions(ctx, name, key, actor, options = {}) {
263
+ if (ctx.registry.get(name).fields[key]?.type === 'user')
264
+ return userOptions(ctx, name, key, actor, options);
265
+ const form = await editor(ctx, name, actor, options.id);
266
+ const field = form.fields.find((entry) => entry.key === key);
267
+ if (!field || (field.type !== 'belongsTo' && field.type !== 'manyToMany'))
268
+ throw forbiddenField('ليس لديك صلاحية لهذا الحقل');
269
+ const target = ctx.registry.get(field.resource);
270
+ const page = await list(ctx, target.name, actor, {
271
+ search: options.search,
272
+ cursor: options.cursor,
273
+ limit: 50,
274
+ estimate: false,
275
+ });
276
+ const title = await titler(ctx, target);
277
+ return {
278
+ data: page.data.map((row) => ({
279
+ value: String(row.id),
280
+ label: title(row) ?? `#${row.id}`,
281
+ })),
282
+ nextCursor: page.meta.nextCursor,
283
+ };
284
+ }
285
+ /**
286
+ * Choices for a user field. A form lists active members of the record's unit or its
287
+ * ancestors (the users the record is visible to through membership); a filter lists
288
+ * active users who share organization scope with the actor. Only names are returned.
289
+ */
290
+ async function userOptions(ctx, name, key, actor, options) {
291
+ const resource = ctx.registry.get(name);
292
+ let path = null;
293
+ if (options.purpose === 'filter') {
294
+ const field = describe(ctx, name, actor).fields.find((entry) => entry.key === key);
295
+ if (!field?.filterable)
296
+ throw forbiddenField('ليس لديك صلاحية لهذا الحقل');
297
+ }
298
+ else {
299
+ const form = await editor(ctx, name, actor, options.id);
300
+ if (!form.fields.some((entry) => entry.key === key))
301
+ throw forbiddenField('ليس لديك صلاحية لهذا الحقل');
302
+ if (resource.scoped) {
303
+ const unit = options.orgUnitId ??
304
+ (form.record?.orgUnitId === undefined ? undefined : Number(form.record.orgUnitId));
305
+ // Without a unit (for example an inline row) the choices follow the actor's scope;
306
+ // saving still checks the record's unit.
307
+ if (unit !== undefined) {
308
+ const row = await ctx.db('org_units').where('id', unit).first('path');
309
+ // Only units the actor works in (or the record's current unit) may be probed.
310
+ if (!row ||
311
+ (!inOrgScope(row.path, actor.orgPaths) && Number(unit) !== Number(form.record?.orgUnitId)))
312
+ return { data: [], nextCursor: null };
313
+ path = String(row.path);
314
+ }
315
+ }
316
+ }
317
+ let after = 0;
318
+ if (options.cursor !== undefined && options.cursor !== '') {
319
+ after = Number(options.cursor);
320
+ if (!Number.isSafeInteger(after) || after < 0)
321
+ throw invalidCursor();
322
+ }
323
+ const query = eligibleUsers(ctx.db, path, actor)
324
+ .where('u.id', '>', after)
325
+ .orderBy('u.id')
326
+ .limit(51)
327
+ .select('u.id', 'u.full_name', avatarVersionColumn(ctx.db, 'u.id'));
328
+ if (options.search)
329
+ query.whereILike('u.full_name', `%${escapeLike(options.search)}%`);
330
+ const rows = await query;
331
+ return {
332
+ data: rows.slice(0, 50).map((row) => ({
333
+ value: String(row.id),
334
+ label: String(row.full_name || `#${row.id}`),
335
+ avatarUrl: avatarUrlFor(row.id, row.avatar_version),
336
+ })),
337
+ nextCursor: rows.length > 50 ? String(rows[49].id) : null,
338
+ };
339
+ }
340
+ /** A form field as the editor sends it: a multiple attachment field carries its resolved limit. */
341
+ function editorField(key, field) {
342
+ return field.type === 'attachment' && field.multiple
343
+ ? { key, ...field, max: attachmentLimit(field) }
344
+ : { key, ...field };
345
+ }
@@ -0,0 +1,54 @@
1
+ import type { Field, JsonValue } from '../../resource/types.js';
2
+ import type { Actor } from '../../auth/ability.js';
3
+ import { type ListOptions } from './query.js';
4
+ import type { ResourceContext } from './shared.js';
5
+ /** Most rows one synchronous export may contain (ADR 046). */
6
+ export declare const EXPORT_ROW_LIMIT = 5000;
7
+ export type ExportOptions = Omit<ListOptions, 'limit' | 'cursor' | 'estimate'>;
8
+ export type CsvExport = {
9
+ /** UTF-8 text with a byte order mark and CRLF line endings. */
10
+ content: string;
11
+ /** Display file name (may contain Arabic); send it as an RFC 5987 filename*. */
12
+ filename: string;
13
+ /** ASCII-only fallback file name for the plain filename parameter. */
14
+ asciiFilename: string;
15
+ rows: number;
16
+ };
17
+ /** An xlsx export; the same file names as CsvExport with the .xlsx extension. */
18
+ export type XlsxExport = {
19
+ content: Uint8Array;
20
+ filename: string;
21
+ asciiFilename: string;
22
+ rows: number;
23
+ };
24
+ /**
25
+ * The currently filtered list as CSV; see ResourceService.export. The rows, limit and audit
26
+ * come from collectExport.
27
+ */
28
+ export declare function exportCsv(ctx: ResourceContext, name: string, actor: Actor, options?: ExportOptions): Promise<CsvExport>;
29
+ /**
30
+ * The currently filtered list as an Excel workbook (one right-to-left sheet, bold header),
31
+ * with the same rows, columns, limit and audit as exportCsv. Numbers, amounts and dates are
32
+ * typed cells; other values are text, guarded like CSV against formula evaluation.
33
+ */
34
+ export declare function exportXlsx(ctx: ResourceContext, name: string, actor: Actor, options?: ExportOptions): Promise<XlsxExport>;
35
+ /**
36
+ * The display text of one stored value: lookup and option labels, titles, names, «نعم/لا»,
37
+ * ISO dates. Several values (multiSelect, manyToMany) are joined with «، » as lists show them.
38
+ */
39
+ export declare function cellText(field: Field, value: JsonValue | undefined, resolve: {
40
+ lookup: (group: string, key: string) => string | undefined;
41
+ title: (id: number) => string | undefined;
42
+ }): string;
43
+ /**
44
+ * One quoted CSV cell. User text starting with a tab or a carriage return, or whose first
45
+ * non-whitespace character is = + - @ or a full-width = + - @, is prefixed with an
46
+ * apostrophe so spreadsheets do not evaluate it as a formula.
47
+ */
48
+ export declare function csvCell(text: string, guard: boolean): string;
49
+ /**
50
+ * Prefixes an apostrophe to text a spreadsheet would evaluate as a formula: a leading tab or
51
+ * carriage return, or = + - @ (also full width) as the first non-whitespace character. CSV
52
+ * export, xlsx export and xlsx templates share this one rule.
53
+ */
54
+ export declare function guardFormula(text: string): string;
@@ -0,0 +1,262 @@
1
+ import writeXlsxFile from 'write-excel-file/node';
2
+ import { AdulaError } from '../errors.js';
3
+ import { labelText, translate } from '../../languages/catalog.js';
4
+ import { logActivity } from '../../core/activity.js';
5
+ import { countUpTo, list } from './query.js';
6
+ import { describe } from './read.js';
7
+ /** Most rows one synchronous export may contain (ADR 046). */
8
+ export const EXPORT_ROW_LIMIT = 5000;
9
+ const PAGE_SIZE = 100;
10
+ const ACTIVITY_RESOURCE = 'core.exports';
11
+ /**
12
+ * The currently filtered list, read page by page through list(), so the actor's rules,
13
+ * organization scope, field redaction and the soft-delete filter are exactly the list's.
14
+ * More than EXPORT_ROW_LIMIT matching rows is 422 E_EXPORT_LIMIT and nothing is produced.
15
+ */
16
+ async function collectExport(ctx, name, actor, options) {
17
+ const resource = ctx.registry.get(name);
18
+ const description = describe(ctx, name, actor);
19
+ const readable = new Map(description.fields.map((field) => [field.key, field]));
20
+ // Hidden fields are left out, not blanked; inline children have no single value.
21
+ const keys = description.list.filter((key) => readable.has(key) && resource.fields[key].type !== 'hasMany');
22
+ const query = {
23
+ search: options.search,
24
+ sort: options.sort,
25
+ direction: options.direction,
26
+ filters: options.filters,
27
+ tag: options.tag,
28
+ trashed: options.trashed,
29
+ };
30
+ // One bounded count first: an oversized export costs a single query, not 50 pages.
31
+ if ((await countUpTo(ctx, name, actor, query, EXPORT_ROW_LIMIT)) > EXPORT_ROW_LIMIT)
32
+ throw exportLimit();
33
+ const records = [];
34
+ const titles = new Map();
35
+ let cursor;
36
+ do {
37
+ const page = await list(ctx, name, actor, {
38
+ ...query,
39
+ limit: PAGE_SIZE,
40
+ cursor,
41
+ estimate: false,
42
+ });
43
+ records.push(...page.data);
44
+ // Rows added while paging still cannot push the export past the limit.
45
+ if (records.length > EXPORT_ROW_LIMIT)
46
+ throw exportLimit();
47
+ for (const [key, rows] of Object.entries(page.related)) {
48
+ const known = titles.get(key) ?? new Map();
49
+ for (const row of rows) {
50
+ const title = typeof row._title === 'string' ? row._title : row.fullName;
51
+ if (typeof title === 'string' && title)
52
+ known.set(Number(row.id), title);
53
+ }
54
+ titles.set(key, known);
55
+ }
56
+ cursor = page.meta.nextCursor ?? undefined;
57
+ } while (cursor);
58
+ const groups = keys.flatMap((key) => {
59
+ const field = resource.fields[key];
60
+ return field.type === 'lookup' ? [field.group] : [];
61
+ });
62
+ const lookupLabels = new Map();
63
+ if (groups.length)
64
+ for (const row of await ctx
65
+ .db('lookups')
66
+ .whereIn('group', groups)
67
+ .select('group', 'key', 'label_ar'))
68
+ lookupLabels.set(`${row.group}\u0000${row.key}`, String(row.label_ar));
69
+ const display = (key, field, value) => cellText(field, value, {
70
+ lookup: (group, entry) => lookupLabels.get(`${group}\u0000${entry}`),
71
+ title: (id) => titles.get(key)?.get(id),
72
+ });
73
+ const rows = records.map((record) => keys.map((key) => {
74
+ const field = resource.fields[key];
75
+ return { field, text: display(key, field, record[key]), raw: record[key] };
76
+ }));
77
+ const audit = async (format) => {
78
+ await logActivity(ctx.db, {
79
+ resource: ACTIVITY_RESOURCE,
80
+ recordId: 0,
81
+ actorId: actor.id,
82
+ impersonatorId: actor.impersonatorId,
83
+ action: 'exported',
84
+ changes: {
85
+ resource: name,
86
+ format,
87
+ query: {
88
+ ...(options.search ? { search: options.search } : {}),
89
+ ...(options.sort ? { sort: options.sort } : {}),
90
+ ...(options.direction ? { direction: options.direction } : {}),
91
+ ...(options.filters && Object.keys(options.filters).length
92
+ ? { filters: options.filters }
93
+ : {}),
94
+ ...(options.tag ? { tag: options.tag } : {}),
95
+ ...(options.trashed ? { trashed: true } : {}),
96
+ },
97
+ rows: records.length,
98
+ },
99
+ });
100
+ };
101
+ return { resource, keys, rows, audit };
102
+ }
103
+ /**
104
+ * The currently filtered list as CSV; see ResourceService.export. The rows, limit and audit
105
+ * come from collectExport.
106
+ */
107
+ export async function exportCsv(ctx, name, actor, options = {}) {
108
+ const { resource, keys, rows, audit } = await collectExport(ctx, name, actor, options);
109
+ const lines = [
110
+ keys.map((key) => csvCell(labelText(resource.fields[key].label), true)).join(','),
111
+ ...rows.map((row) => row.map((cell) => csvCell(cell.text, textual(cell.field))).join(',')),
112
+ ];
113
+ await audit('csv');
114
+ const day = new Date().toISOString().slice(0, 10);
115
+ return {
116
+ content: `\uFEFF${lines.join('\r\n')}\r\n`,
117
+ filename: `${labelText(resource.label)}-${day}.csv`,
118
+ asciiFilename: `${name}-${day}.csv`,
119
+ rows: rows.length,
120
+ };
121
+ }
122
+ /**
123
+ * The currently filtered list as an Excel workbook (one right-to-left sheet, bold header),
124
+ * with the same rows, columns, limit and audit as exportCsv. Numbers, amounts and dates are
125
+ * typed cells; other values are text, guarded like CSV against formula evaluation.
126
+ */
127
+ export async function exportXlsx(ctx, name, actor, options = {}) {
128
+ const { resource, keys, rows, audit } = await collectExport(ctx, name, actor, options);
129
+ const header = keys.map((key) => ({
130
+ value: guardFormula(labelText(resource.fields[key].label)),
131
+ fontWeight: 'bold',
132
+ }));
133
+ const data = [header, ...rows.map((row) => row.map(xlsxCell))];
134
+ const content = await writeXlsxFile(data, {
135
+ sheet: sheetName(labelText(resource.label)),
136
+ rightToLeft: true,
137
+ stickyRowsCount: 1,
138
+ }).toBuffer();
139
+ await audit('xlsx');
140
+ const day = new Date().toISOString().slice(0, 10);
141
+ return {
142
+ content: new Uint8Array(content.buffer, content.byteOffset, content.byteLength),
143
+ filename: `${labelText(resource.label)}-${day}.xlsx`,
144
+ asciiFilename: `${name}-${day}.xlsx`,
145
+ rows: rows.length,
146
+ };
147
+ }
148
+ /** Excel sheet names: at most 31 characters, none of [ ] : * ? / \, not quoted. */
149
+ function sheetName(label) {
150
+ const clean = label
151
+ .replace(/[[\]:*?/\\]/g, ' ')
152
+ .trim()
153
+ .replace(/^'+|'+$/g, '')
154
+ .slice(0, 31)
155
+ .trim();
156
+ return clean || 'Sheet1';
157
+ }
158
+ const NUMERIC = new Set(['integer', 'decimal', 'percent']);
159
+ /** One typed xlsx cell; anything that is not a safe number or date stays guarded text. */
160
+ function xlsxCell({ field, text, raw }) {
161
+ if (raw === null || raw === undefined || raw === '')
162
+ return null;
163
+ if (NUMERIC.has(field.type)) {
164
+ const value = typeof raw === 'number' ? raw : Number(raw);
165
+ if (Number.isFinite(value) && String(raw).trim() !== '')
166
+ return value;
167
+ }
168
+ if (field.type === 'money' && /^-?\d+$/.test(String(raw))) {
169
+ const minor = BigInt(String(raw));
170
+ const limit = BigInt(Number.MAX_SAFE_INTEGER);
171
+ if (minor <= limit && minor >= -limit)
172
+ return { value: Number(minor) / 100, type: Number, format: '#,##0.00' };
173
+ }
174
+ if (field.type === 'date' && typeof raw === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(raw)) {
175
+ const date = new Date(`${raw}T00:00:00.000Z`);
176
+ if (!Number.isNaN(date.getTime()))
177
+ return { value: date, type: Date, format: 'yyyy-mm-dd' };
178
+ }
179
+ return text === '' ? null : guardFormula(text);
180
+ }
181
+ function exportLimit() {
182
+ return new AdulaError(422, 'E_EXPORT_LIMIT', 'عدد السجلات المطابقة يتجاوز حد التصدير (5000 سجل). ضيّق التصفية ثم أعد المحاولة.');
183
+ }
184
+ /** Fields whose text comes from users, and so may carry a spreadsheet formula. */
185
+ function textual(field) {
186
+ return !['integer', 'money', 'decimal', 'percent', 'boolean', 'date', 'datetime'].includes(field.type);
187
+ }
188
+ /**
189
+ * The display text of one stored value: lookup and option labels, titles, names, «نعم/لا»,
190
+ * ISO dates. Several values (multiSelect, manyToMany) are joined with «، » as lists show them.
191
+ */
192
+ export function cellText(field, value, resolve) {
193
+ if (value === null || value === undefined || value === '')
194
+ return '';
195
+ switch (field.type) {
196
+ case 'boolean':
197
+ return translate(value === true ? 'list.value.yes' : 'list.value.no');
198
+ case 'lookup':
199
+ return resolve.lookup(field.group, String(value)) ?? String(value);
200
+ case 'belongsTo':
201
+ case 'user':
202
+ // A record the reader may not view is never named, not even by its id.
203
+ return resolve.title(Number(value)) ?? translate('list.value.unavailable');
204
+ case 'enum':
205
+ return optionText(field.options, value);
206
+ case 'multiSelect':
207
+ return Array.isArray(value)
208
+ ? value.map((entry) => optionText(field.options, entry)).join('، ')
209
+ : optionText(field.options, value);
210
+ case 'manyToMany':
211
+ return Array.isArray(value)
212
+ ? value
213
+ .map((id) => resolve.title(Number(id)) ?? translate('list.value.unavailable'))
214
+ .join('، ')
215
+ : String(value);
216
+ case 'money':
217
+ return moneyText(String(value));
218
+ case 'attachment': {
219
+ // A multiple field lists its file names in order, joined like other lists.
220
+ const name = (entry) => entry && typeof entry === 'object' && !Array.isArray(entry)
221
+ ? String(entry.name ?? '')
222
+ : String(entry);
223
+ return Array.isArray(value) ? value.map(name).join('، ') : name(value);
224
+ }
225
+ case 'json':
226
+ return JSON.stringify(value);
227
+ default:
228
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
229
+ }
230
+ }
231
+ /** The label of an enum or multiSelect option in the interface language; unknown keys stay. */
232
+ function optionText(options, value) {
233
+ const option = options.find((entry) => entry.value === String(value));
234
+ return option ? labelText(option.label) : String(value);
235
+ }
236
+ /** Canonical minor units as a plain decimal amount (150000 → 1500.00), as forms show it. */
237
+ function moneyText(minor) {
238
+ if (!/^-?\d+$/.test(minor))
239
+ return minor;
240
+ const amount = BigInt(minor);
241
+ const abs = amount < 0n ? -amount : amount;
242
+ return `${amount < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`;
243
+ }
244
+ /** Text a spreadsheet may evaluate: a leading tab or CR, or = + - @ (also full width) after spaces. */
245
+ const FORMULA_START = /^(?:[\t\r]|\s*[=+\-@\uFF1D\uFF0B\uFF0D\uFF20])/;
246
+ /**
247
+ * One quoted CSV cell. User text starting with a tab or a carriage return, or whose first
248
+ * non-whitespace character is = + - @ or a full-width = + - @, is prefixed with an
249
+ * apostrophe so spreadsheets do not evaluate it as a formula.
250
+ */
251
+ export function csvCell(text, guard) {
252
+ const safe = guard ? guardFormula(text) : text;
253
+ return `"${safe.replaceAll('"', '""')}"`;
254
+ }
255
+ /**
256
+ * Prefixes an apostrophe to text a spreadsheet would evaluate as a formula: a leading tab or
257
+ * carriage return, or = + - @ (also full width) as the first non-whitespace character. CSV
258
+ * export, xlsx export and xlsx templates share this one rule.
259
+ */
260
+ export function guardFormula(text) {
261
+ return FORMULA_START.test(text) ? `'${text}` : text;
262
+ }