adula 2.1.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 +4 -2
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -0,0 +1,323 @@
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 { labelText } from '../../languages/catalog.js';
10
+ import { authorizeAction, columns, eligibleUsers, fieldLevel, find, hydrate, hydrateOne, requireRecord, } from './shared.js';
11
+ import { describe, show, titler } from './read.js';
12
+ import { list } from './query.js';
13
+ /** Whether an error only means the actor cannot open a related record. */
14
+ const unreachable = (error) => error instanceof AdulaError && [403, 404].includes(error.status);
15
+ /** The form description for create (no id) or update; see ResourceService.editor. */
16
+ export async function editor(ctx, name, actor, id, request = {}) {
17
+ const { db, registry } = ctx;
18
+ const resource = registry.get(name);
19
+ const action = id === undefined ? 'create' : 'update';
20
+ const ability = authorizeAction(ctx, resource, actor, action);
21
+ const record = id === undefined ? undefined : await find(db, resource, actor, ability, id);
22
+ if (record) {
23
+ requireRecord(ability, actor, resource, action, record);
24
+ if (resource.submittable && record.docStatus !== 0)
25
+ throw documentLocked();
26
+ }
27
+ const fields = resource.form
28
+ .filter((key) => {
29
+ const field = resource.fields[key];
30
+ return (!field.sequence &&
31
+ actor.permissionLevel >= fieldLevel(resource, key) &&
32
+ ability.can(action, record ? subject(name, record) : name, key));
33
+ })
34
+ .map((key) => editorField(key, resource.fields[key]));
35
+ const options = {};
36
+ const relationSearch = {};
37
+ const inline = {};
38
+ for (const field of fields) {
39
+ if (field.type === 'hasMany' && field.inline) {
40
+ const child = registry.get(field.resource);
41
+ const rows = record && ability.can('view', child.name)
42
+ ? await accessibleBy(db(`${child.name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', child)
43
+ .where(`r.${child.fields[field.foreignKey].column ?? columnName(field.foreignKey)}`, id)
44
+ .select([
45
+ ...columns(child, ability),
46
+ ...(child.scoped ? ['ou.path as org_path'] : []),
47
+ ])
48
+ .orderBy('r.id')
49
+ .limit(101)
50
+ : [];
51
+ const records = rows.slice(0, 100).map((row) => fromRow(row, child));
52
+ const hydratedRows = await hydrate(db, child, records, ctx.attachments);
53
+ // Inline rows do not edit many-to-many links: rows load without them, and an
54
+ // inline payload's manyToMany keys are ignored (write.ts writeInlineRows).
55
+ const childFields = child.form.filter((key) => key !== field.foreignKey &&
56
+ child.fields[key].type !== 'manyToMany' &&
57
+ !child.fields[key].sequence &&
58
+ actor.permissionLevel >= fieldLevel(child, key));
59
+ inline[field.key] = {
60
+ fields: childFields.map((key) => editorField(key, child.fields[key])),
61
+ createFields: childFields.filter((key) => ability.can('create', child.name, key)),
62
+ updateFields: Object.fromEntries(records.map((row) => [
63
+ String(row.id),
64
+ childFields.filter((key) => ability.can('update', subject(child.name, row), key)),
65
+ ])),
66
+ rows: hydratedRows.map((row) => serialize(child, row, ability, actor)),
67
+ hasMore: rows.length > 100,
68
+ canCreate: child.actions.includes('create') && ability.can('create', child.name),
69
+ permissions: Object.fromEntries(records.map((row) => [
70
+ String(row.id),
71
+ {
72
+ update: child.actions.includes('update') && ability.can('update', subject(child.name, row)),
73
+ delete: child.actions.includes('delete') && ability.can('delete', subject(child.name, row)),
74
+ },
75
+ ])),
76
+ };
77
+ }
78
+ if (field.type === 'lookup') {
79
+ const lookups = await db('lookups')
80
+ .where({ group: field.group, active: true })
81
+ .orderBy('id')
82
+ .select('key', 'label_ar');
83
+ options[field.key] = lookups.map((row) => ({ value: row.key, label: row.label_ar }));
84
+ }
85
+ else if (field.type === 'enum' || field.type === 'multiSelect') {
86
+ options[field.key] = field.options.map((option) => ({
87
+ value: option.value,
88
+ label: labelText(option.label),
89
+ }));
90
+ }
91
+ else if (field.type === 'belongsTo' || field.type === 'manyToMany') {
92
+ const target = registry.get(field.resource);
93
+ if (ability.can('view', target.name)) {
94
+ relationSearch[field.key] = describe(ctx, target.name, actor).searchable;
95
+ const page = await list(ctx, target.name, actor, { limit: 50, estimate: false });
96
+ const title = await titler(ctx, target);
97
+ options[field.key] = page.data.map((row) => ({
98
+ value: String(row.id),
99
+ label: title(row) ?? `#${row.id}`,
100
+ }));
101
+ const value = record?.[field.key];
102
+ // Current values outside the first page keep a labelled choice when still viewable.
103
+ for (const selected of Array.isArray(value) ? value : [value]) {
104
+ if (selected === null ||
105
+ selected === undefined ||
106
+ options[field.key].some((option) => option.value === String(selected)))
107
+ continue;
108
+ try {
109
+ const current = await show(ctx, target.name, Number(selected), actor);
110
+ options[field.key].push({
111
+ value: String(current.data.id),
112
+ label: title(current.data) ?? `#${current.data.id}`,
113
+ });
114
+ }
115
+ catch (error) {
116
+ if (!unreachable(error))
117
+ throw error;
118
+ }
119
+ }
120
+ }
121
+ else
122
+ options[field.key] = [];
123
+ }
124
+ else if (field.type === 'user') {
125
+ // Choices depend on the unit chosen in the form; they load from relationOptions.
126
+ relationSearch[field.key] = true;
127
+ options[field.key] = [];
128
+ const selected = record?.[field.key];
129
+ if (selected !== null && selected !== undefined) {
130
+ const current = await db('users').where('id', Number(selected)).first('id', 'full_name');
131
+ if (current)
132
+ options[field.key].push({
133
+ value: String(current.id),
134
+ label: String(current.full_name || `#${current.id}`),
135
+ });
136
+ }
137
+ }
138
+ }
139
+ const units = resource.scoped && !resource.scope
140
+ ? await db('org_units')
141
+ .where((query) => {
142
+ if (!actor.orgPaths.length)
143
+ query.whereRaw('FALSE');
144
+ for (const path of actor.orgPaths)
145
+ query.orWhereRaw('path <@ ?::ltree', [path]);
146
+ })
147
+ .orderBy('path')
148
+ .limit(100)
149
+ .select('id', 'name')
150
+ : [];
151
+ if (record?.orgUnitId && !units.some((unit) => Number(unit.id) === Number(record.orgUnitId))) {
152
+ const current = await db('org_units').where('id', Number(record.orgUnitId)).first('id', 'name');
153
+ if (current)
154
+ units.push(current);
155
+ }
156
+ const defaults = {};
157
+ // Declared field defaults prefill a create form; requested defaults below override them.
158
+ if (id === undefined)
159
+ for (const field of fields)
160
+ if (field.default !== undefined && field.default !== null)
161
+ defaults[field.key] = Array.isArray(field.default)
162
+ ? [...field.default]
163
+ : field.default;
164
+ const requested = request.defaults;
165
+ if (id === undefined && requested && typeof requested === 'object')
166
+ for (const field of fields) {
167
+ const raw = Object.hasOwn(requested, field.key) ? requested[field.key] : undefined;
168
+ if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean')
169
+ continue;
170
+ let value = raw;
171
+ try {
172
+ if (['integer', 'belongsTo', 'user'].includes(field.type))
173
+ value = Number(raw);
174
+ else if (field.type === 'boolean')
175
+ value = raw === true || raw === 'true';
176
+ else
177
+ value = String(raw);
178
+ value = fieldValue(field, value);
179
+ }
180
+ catch {
181
+ continue;
182
+ }
183
+ if (['attachment', 'json', 'hasMany'].includes(field.type))
184
+ continue;
185
+ if (field.type === 'user') {
186
+ // The unit is chosen later in the form; saving checks the record's unit.
187
+ const user = await eligibleUsers(db, null, actor)
188
+ .where('u.id', Number(value))
189
+ .first('u.id', 'u.full_name');
190
+ if (!user)
191
+ continue;
192
+ const choices = options[field.key] ?? (options[field.key] = []);
193
+ if (!choices.some((option) => option.value === String(user.id)))
194
+ choices.push({ value: String(user.id), label: String(user.full_name || `#${user.id}`) });
195
+ }
196
+ if (field.type === 'lookup' || field.type === 'belongsTo') {
197
+ const choices = options[field.key] ?? [];
198
+ if (!choices.some((option) => option.value === String(value))) {
199
+ if (field.type === 'lookup')
200
+ continue;
201
+ try {
202
+ // Authorized exactly like opening the related record.
203
+ const target = registry.get(field.resource);
204
+ const current = await show(ctx, target.name, Number(value), actor);
205
+ const title = await titler(ctx, target);
206
+ choices.push({
207
+ value: String(current.data.id),
208
+ label: title(current.data) ?? `#${current.data.id}`,
209
+ });
210
+ }
211
+ catch (error) {
212
+ if (!unreachable(error))
213
+ throw error;
214
+ continue;
215
+ }
216
+ }
217
+ }
218
+ defaults[field.key] = value;
219
+ }
220
+ return {
221
+ mode: action,
222
+ name,
223
+ label: resource.label.ar,
224
+ recordLabel: resource.recordLabel?.ar ?? null,
225
+ fields,
226
+ /** Initial values of a create form, already checked against the actor's access. */
227
+ defaults,
228
+ inline,
229
+ options,
230
+ relationSearch,
231
+ orgUnits: units.map((row) => ({ value: String(row.id), label: String(row.name) })),
232
+ scoped: resource.scoped,
233
+ /** The belongsTo field whose record decides the unit; the form shows no unit picker. */
234
+ scopeFrom: resource.scope?.from ?? null,
235
+ record: record
236
+ ? serialize(resource, await hydrateOne(db, resource, record, ctx.attachments), ability, actor)
237
+ : null,
238
+ };
239
+ }
240
+ /** Choices of a belongsTo or user field in a form or filter; see ResourceService.relationOptions. */
241
+ export async function relationOptions(ctx, name, key, actor, options = {}) {
242
+ if (ctx.registry.get(name).fields[key]?.type === 'user')
243
+ return userOptions(ctx, name, key, actor, options);
244
+ const form = await editor(ctx, name, actor, options.id);
245
+ const field = form.fields.find((entry) => entry.key === key);
246
+ if (!field || (field.type !== 'belongsTo' && field.type !== 'manyToMany'))
247
+ throw forbiddenField('ليس لديك صلاحية لهذا الحقل');
248
+ const target = ctx.registry.get(field.resource);
249
+ const page = await list(ctx, target.name, actor, {
250
+ search: options.search,
251
+ cursor: options.cursor,
252
+ limit: 50,
253
+ estimate: false,
254
+ });
255
+ const title = await titler(ctx, target);
256
+ return {
257
+ data: page.data.map((row) => ({
258
+ value: String(row.id),
259
+ label: title(row) ?? `#${row.id}`,
260
+ })),
261
+ nextCursor: page.meta.nextCursor,
262
+ };
263
+ }
264
+ /**
265
+ * Choices for a user field. A form lists active members of the record's unit or its
266
+ * ancestors (the users the record is visible to through membership); a filter lists
267
+ * active users who share organization scope with the actor. Only names are returned.
268
+ */
269
+ async function userOptions(ctx, name, key, actor, options) {
270
+ const resource = ctx.registry.get(name);
271
+ let path = null;
272
+ if (options.purpose === 'filter') {
273
+ const field = describe(ctx, name, actor).fields.find((entry) => entry.key === key);
274
+ if (!field?.filterable)
275
+ throw forbiddenField('ليس لديك صلاحية لهذا الحقل');
276
+ }
277
+ else {
278
+ const form = await editor(ctx, name, actor, options.id);
279
+ if (!form.fields.some((entry) => entry.key === key))
280
+ throw forbiddenField('ليس لديك صلاحية لهذا الحقل');
281
+ if (resource.scoped) {
282
+ const unit = options.orgUnitId ??
283
+ (form.record?.orgUnitId === undefined ? undefined : Number(form.record.orgUnitId));
284
+ // Without a unit (for example an inline row) the choices follow the actor's scope;
285
+ // saving still checks the record's unit.
286
+ if (unit !== undefined) {
287
+ const row = await ctx.db('org_units').where('id', unit).first('path');
288
+ // Only units the actor works in (or the record's current unit) may be probed.
289
+ if (!row ||
290
+ (!inOrgScope(row.path, actor.orgPaths) && Number(unit) !== Number(form.record?.orgUnitId)))
291
+ return { data: [], nextCursor: null };
292
+ path = String(row.path);
293
+ }
294
+ }
295
+ }
296
+ let after = 0;
297
+ if (options.cursor !== undefined && options.cursor !== '') {
298
+ after = Number(options.cursor);
299
+ if (!Number.isSafeInteger(after) || after < 0)
300
+ throw invalidCursor();
301
+ }
302
+ const query = eligibleUsers(ctx.db, path, actor)
303
+ .where('u.id', '>', after)
304
+ .orderBy('u.id')
305
+ .limit(51)
306
+ .select('u.id', 'u.full_name');
307
+ if (options.search)
308
+ query.whereILike('u.full_name', `%${escapeLike(options.search)}%`);
309
+ const rows = await query;
310
+ return {
311
+ data: rows.slice(0, 50).map((row) => ({
312
+ value: String(row.id),
313
+ label: String(row.full_name || `#${row.id}`),
314
+ })),
315
+ nextCursor: rows.length > 50 ? String(rows[49].id) : null,
316
+ };
317
+ }
318
+ /** A form field as the editor sends it: a multiple attachment field carries its resolved limit. */
319
+ function editorField(key, field) {
320
+ return field.type === 'attachment' && field.multiple
321
+ ? { key, ...field, max: attachmentLimit(field) }
322
+ : { key, ...field };
323
+ }
@@ -0,0 +1,37 @@
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
+ /**
18
+ * The currently filtered list as CSV; see ResourceService.export. Rows are read page by
19
+ * page through list(), so the actor's rules, organization scope, field redaction and the
20
+ * soft-delete filter are exactly the list's. More than EXPORT_ROW_LIMIT matching rows is
21
+ * 422 E_EXPORT_LIMIT and nothing is produced.
22
+ */
23
+ export declare function exportCsv(ctx: ResourceContext, name: string, actor: Actor, options?: ExportOptions): Promise<CsvExport>;
24
+ /**
25
+ * The display text of one stored value: lookup and option labels, titles, names, «نعم/لا»,
26
+ * ISO dates. Several values (multiSelect, manyToMany) are joined with «، » as lists show them.
27
+ */
28
+ export declare function cellText(field: Field, value: JsonValue | undefined, resolve: {
29
+ lookup: (group: string, key: string) => string | undefined;
30
+ title: (id: number) => string | undefined;
31
+ }): string;
32
+ /**
33
+ * One quoted CSV cell. User text starting with a tab or a carriage return, or whose first
34
+ * non-whitespace character is = + - @ or a full-width = + - @, is prefixed with an
35
+ * apostrophe so spreadsheets do not evaluate it as a formula.
36
+ */
37
+ export declare function csvCell(text: string, guard: boolean): string;
@@ -0,0 +1,181 @@
1
+ import { AdulaError } from '../errors.js';
2
+ import { labelText, translate } from '../../languages/catalog.js';
3
+ import { logActivity } from '../../core/activity.js';
4
+ import { countUpTo, list } from './query.js';
5
+ import { describe } from './read.js';
6
+ /** Most rows one synchronous export may contain (ADR 046). */
7
+ export const EXPORT_ROW_LIMIT = 5000;
8
+ const PAGE_SIZE = 100;
9
+ const ACTIVITY_RESOURCE = 'core.exports';
10
+ /**
11
+ * The currently filtered list as CSV; see ResourceService.export. Rows are read page by
12
+ * page through list(), so the actor's rules, organization scope, field redaction and the
13
+ * soft-delete filter are exactly the list's. More than EXPORT_ROW_LIMIT matching rows is
14
+ * 422 E_EXPORT_LIMIT and nothing is produced.
15
+ */
16
+ export async function exportCsv(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 lines = [
74
+ keys.map((key) => csvCell(labelText(resource.fields[key].label), true)).join(','),
75
+ ...records.map((record) => keys
76
+ .map((key) => {
77
+ const field = resource.fields[key];
78
+ return csvCell(display(key, field, record[key]), textual(field));
79
+ })
80
+ .join(',')),
81
+ ];
82
+ await logActivity(ctx.db, {
83
+ resource: ACTIVITY_RESOURCE,
84
+ recordId: 0,
85
+ actorId: actor.id,
86
+ impersonatorId: actor.impersonatorId,
87
+ action: 'exported',
88
+ changes: {
89
+ resource: name,
90
+ query: {
91
+ ...(options.search ? { search: options.search } : {}),
92
+ ...(options.sort ? { sort: options.sort } : {}),
93
+ ...(options.direction ? { direction: options.direction } : {}),
94
+ ...(options.filters && Object.keys(options.filters).length
95
+ ? { filters: options.filters }
96
+ : {}),
97
+ ...(options.tag ? { tag: options.tag } : {}),
98
+ ...(options.trashed ? { trashed: true } : {}),
99
+ },
100
+ rows: records.length,
101
+ },
102
+ });
103
+ const day = new Date().toISOString().slice(0, 10);
104
+ return {
105
+ content: `\uFEFF${lines.join('\r\n')}\r\n`,
106
+ filename: `${labelText(resource.label)}-${day}.csv`,
107
+ asciiFilename: `${name}-${day}.csv`,
108
+ rows: records.length,
109
+ };
110
+ }
111
+ function exportLimit() {
112
+ return new AdulaError(422, 'E_EXPORT_LIMIT', 'عدد السجلات المطابقة يتجاوز حد التصدير (5000 سجل). ضيّق التصفية ثم أعد المحاولة.');
113
+ }
114
+ /** Fields whose text comes from users, and so may carry a spreadsheet formula. */
115
+ function textual(field) {
116
+ return !['integer', 'money', 'decimal', 'percent', 'boolean', 'date', 'datetime'].includes(field.type);
117
+ }
118
+ /**
119
+ * The display text of one stored value: lookup and option labels, titles, names, «نعم/لا»,
120
+ * ISO dates. Several values (multiSelect, manyToMany) are joined with «، » as lists show them.
121
+ */
122
+ export function cellText(field, value, resolve) {
123
+ if (value === null || value === undefined || value === '')
124
+ return '';
125
+ switch (field.type) {
126
+ case 'boolean':
127
+ return translate(value === true ? 'list.value.yes' : 'list.value.no');
128
+ case 'lookup':
129
+ return resolve.lookup(field.group, String(value)) ?? String(value);
130
+ case 'belongsTo':
131
+ case 'user':
132
+ return resolve.title(Number(value)) ?? `#${value}`;
133
+ case 'enum':
134
+ return optionText(field.options, value);
135
+ case 'multiSelect':
136
+ return Array.isArray(value)
137
+ ? value.map((entry) => optionText(field.options, entry)).join('، ')
138
+ : optionText(field.options, value);
139
+ case 'manyToMany':
140
+ return Array.isArray(value)
141
+ ? value.map((id) => resolve.title(Number(id)) ?? `#${id}`).join('، ')
142
+ : String(value);
143
+ case 'money':
144
+ return moneyText(String(value));
145
+ case 'attachment': {
146
+ // A multiple field lists its file names in order, joined like other lists.
147
+ const name = (entry) => entry && typeof entry === 'object' && !Array.isArray(entry)
148
+ ? String(entry.name ?? '')
149
+ : String(entry);
150
+ return Array.isArray(value) ? value.map(name).join('، ') : name(value);
151
+ }
152
+ case 'json':
153
+ return JSON.stringify(value);
154
+ default:
155
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
156
+ }
157
+ }
158
+ /** The label of an enum or multiSelect option in the interface language; unknown keys stay. */
159
+ function optionText(options, value) {
160
+ const option = options.find((entry) => entry.value === String(value));
161
+ return option ? labelText(option.label) : String(value);
162
+ }
163
+ /** Canonical minor units as a plain decimal amount (150000 → 1500.00), as forms show it. */
164
+ function moneyText(minor) {
165
+ if (!/^-?\d+$/.test(minor))
166
+ return minor;
167
+ const amount = BigInt(minor);
168
+ const abs = amount < 0n ? -amount : amount;
169
+ return `${amount < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`;
170
+ }
171
+ /** Text a spreadsheet may evaluate: a leading tab or CR, or = + - @ (also full width) after spaces. */
172
+ const FORMULA_START = /^(?:[\t\r]|\s*[=+\-@\uFF1D\uFF0B\uFF0D\uFF20])/;
173
+ /**
174
+ * One quoted CSV cell. User text starting with a tab or a carriage return, or whose first
175
+ * non-whitespace character is = + - @ or a full-width = + - @, is prefixed with an
176
+ * apostrophe so spreadsheets do not evaluate it as a formula.
177
+ */
178
+ export function csvCell(text, guard) {
179
+ const safe = guard && FORMULA_START.test(text) ? `'${text}` : text;
180
+ return `"${safe.replaceAll('"', '""')}"`;
181
+ }
@@ -0,0 +1,21 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Action, RecordData, Resource } from '../../resource/types.js';
3
+ import type { Actor } from '../../auth/ability.js';
4
+ import { type FieldChange } from '../../events/record_mutation.js';
5
+ import { type ResourceContext } from './shared.js';
6
+ /** The parent record an inline write belongs to, with the action taken on that parent. */
7
+ export type ParentWrite = {
8
+ name: string;
9
+ id: number;
10
+ action: 'create' | 'update' | 'amend';
11
+ };
12
+ /** Optimistic lock of versioned resources (409 E_VERSION_CONFLICT). */
13
+ export declare function requireVersion(resource: Resource, existing: RecordData, version: unknown): void;
14
+ /** Inline children share the parent's draft state, organization and update authority. */
15
+ export declare function requireInlineParents(ctx: ResourceContext, trx: Knex.Transaction, resource: Resource, actor: Actor, candidate: RecordData, existing?: RecordData, parentWrite?: ParentWrite, system?: boolean): Promise<void>;
16
+ /** Records one mutation in the activity log and the domain event stream. */
17
+ export declare function audit(ctx: ResourceContext, trx: Knex.Transaction, resource: Resource, actor: Actor, action: Action | 'restore', record: RecordData, fields: string[], changes?: FieldChange[], system?: {
18
+ reason?: string;
19
+ }): Promise<void>;
20
+ /** Soft delete, submit or cancel of one record; see ResourceService.transition. */
21
+ export declare function transition(ctx: ResourceContext, name: string, id: number, actor: Actor, action: 'delete' | 'submit' | 'cancel', version?: unknown, transaction?: Knex.Transaction): Promise<import("../../resource/types.js").SerializedRecord>;
@@ -0,0 +1,91 @@
1
+ import { subject } from '@casl/ability';
2
+ import { fromRow, serialize } from '../contracts.js';
3
+ import { AdulaError, documentLocked, forbiddenField, inlineScope, invalidDocumentState, } from '../errors.js';
4
+ import { recordMutation } from '../../events/record_mutation.js';
5
+ import { authorizeAction, fieldLevel, find, findAny, hydrateOne, requireRecord, withLinks, } from './shared.js';
6
+ /** Optimistic lock of versioned resources (409 E_VERSION_CONFLICT). */
7
+ export function requireVersion(resource, existing, version) {
8
+ if (resource.version && (!Number.isSafeInteger(version) || version !== existing.version))
9
+ throw new AdulaError(409, 'E_VERSION_CONFLICT', 'تم تعديل السجل بواسطة مستخدم آخر. حدّث الصفحة وحاول مجدداً.');
10
+ }
11
+ /** Inline children share the parent's draft state, organization and update authority. */
12
+ export async function requireInlineParents(ctx, trx, resource, actor, candidate, existing = {}, parentWrite, system = false) {
13
+ for (const parent of ctx.registry.all()) {
14
+ for (const [key, field] of Object.entries(parent.fields)) {
15
+ if (field.type !== 'hasMany' || !field.inline || field.resource !== resource.name)
16
+ continue;
17
+ const parentId = candidate[field.foreignKey];
18
+ if (parentId === undefined || parentId === null)
19
+ continue;
20
+ if (existing[field.foreignKey] !== undefined &&
21
+ Number(existing[field.foreignKey]) !== Number(parentId))
22
+ throw new AdulaError(422, 'E_INLINE_PARENT', 'Inline records cannot be moved to another parent');
23
+ const action = parentWrite?.name === parent.name && parentWrite.id === Number(parentId)
24
+ ? parentWrite.action
25
+ : 'update';
26
+ let record;
27
+ // amend() authorized the cancelled source; its new draft is checked for state and
28
+ // scope below, and each copied line by the child's own create rules.
29
+ if (system || action === 'amend')
30
+ record = await findAny(trx, parent, Number(parentId), true);
31
+ else {
32
+ const ability = authorizeAction(ctx, parent, actor, action);
33
+ record = await find(trx, parent, actor, ability, Number(parentId), true);
34
+ requireRecord(ability, actor, parent, action, record);
35
+ if (!ability.can(action, subject(parent.name, record), key) ||
36
+ actor.permissionLevel < fieldLevel(parent, key))
37
+ throw forbiddenField('ليس لديك صلاحية تعديل البنود');
38
+ }
39
+ if (parent.submittable && record.docStatus !== 0)
40
+ throw documentLocked('Only draft document lines can be edited');
41
+ if (parent.scoped &&
42
+ resource.scoped &&
43
+ Number(record.orgUnitId) !== Number(candidate.orgUnitId))
44
+ throw inlineScope('Inline records must use the parent organization');
45
+ }
46
+ }
47
+ }
48
+ /** Records one mutation in the activity log and the domain event stream. */
49
+ export async function audit(ctx, trx, resource, actor, action, record, fields, changes, system) {
50
+ await recordMutation(trx, {
51
+ ...(system ? { system: true, reason: system.reason } : {}),
52
+ module: ctx.registry.owner(resource.name),
53
+ resource: resource.name,
54
+ id: record.id,
55
+ actorId: actor.id,
56
+ impersonatorId: actor.impersonatorId,
57
+ action,
58
+ fields,
59
+ changes,
60
+ });
61
+ }
62
+ /** Soft delete, submit or cancel of one record; see ResourceService.transition. */
63
+ export async function transition(ctx, name, id, actor, action, version, transaction) {
64
+ const resource = ctx.registry.get(name);
65
+ const ability = authorizeAction(ctx, resource, actor, action);
66
+ const work = async (trx) => {
67
+ const record = await find(trx, resource, actor, ability, id, true);
68
+ requireRecord(ability, actor, resource, action, record);
69
+ requireVersion(resource, record, version);
70
+ await requireInlineParents(ctx, trx, resource, actor, record);
71
+ const values = { updated_by: actor.id, updated_at: trx.fn.now() };
72
+ if (resource.version)
73
+ values.version = Number(record.version) + 1;
74
+ if (action === 'delete') {
75
+ if (resource.submittable && record.docStatus !== 0)
76
+ throw documentLocked('Only drafts can be deleted');
77
+ values.deleted_at = trx.fn.now();
78
+ }
79
+ else {
80
+ if (!resource.submittable || record.docStatus !== (action === 'submit' ? 0 : 1))
81
+ throw invalidDocumentState('Invalid document transition');
82
+ values.doc_status = action === 'submit' ? 1 : 2;
83
+ }
84
+ const [row] = await trx(name).where({ id }).update(values).returning('*');
85
+ // manyToMany links are not columns; the response carries them like show().
86
+ const [saved] = await withLinks(trx, resource, [fromRow(row, resource)]);
87
+ await audit(ctx, trx, resource, actor, action, saved, []);
88
+ return serialize(resource, await hydrateOne(trx, resource, saved, ctx.attachments), ability, actor);
89
+ };
90
+ return transaction ? work(transaction) : ctx.db.transaction(work);
91
+ }