adula 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +5 -3
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -3,7 +3,9 @@ import type { ResourceRegistry } from '../resource/registry.js';
3
3
  type Schema = Record<string, unknown>;
4
4
  /**
5
5
  * OpenAPI 3.1 description of the resource API, generated from the registry. When
6
- * an actor is given, only resources and actions it may use are described.
6
+ * an actor is given, only resources, actions and fields it may use are described.
7
+ * Every operation carries an `operationId` of the form `<resource>.<operation>`
8
+ * (or `imports.<operation>`), which apiClientSource turns into typed client methods.
7
9
  */
8
10
  export declare function openApiDocument(registry: ResourceRegistry, options: {
9
11
  title: string;
@@ -1,4 +1,21 @@
1
1
  import { buildAbility } from '../auth/ability.js';
2
+ import { canQueryField, fieldLevel } from '../admin/resource/shared.js';
3
+ import { attachmentLimit, isMultipleAttachment } from '../resource/values.js';
4
+ function readable(resource, key, access) {
5
+ return (!access ||
6
+ (access.actor.permissionLevel >= fieldLevel(resource, key) &&
7
+ access.ability.can('view', resource.name, key)));
8
+ }
9
+ function writable(resource, key, access) {
10
+ return (!access ||
11
+ (access.actor.permissionLevel >= fieldLevel(resource, key) &&
12
+ (access.ability.can('create', resource.name, key) ||
13
+ access.ability.can('update', resource.name, key))));
14
+ }
15
+ /** Sorting and filtering need unconditional view access at the field's level (canQueryField). */
16
+ function queryable(resource, key, access) {
17
+ return !access || canQueryField(resource, access.actor, access.ability, key);
18
+ }
2
19
  function fieldSchema(field, mode, registry) {
3
20
  const description = field.label.ar;
4
21
  switch (field.type) {
@@ -18,38 +35,135 @@ function fieldSchema(field, mode, registry) {
18
35
  return { type: 'string', format: 'date-time', description };
19
36
  case 'json':
20
37
  return { description };
38
+ case 'decimal':
39
+ case 'percent':
40
+ return {
41
+ type: 'string',
42
+ pattern: '^-?\\d+(\\.\\d+)?$',
43
+ description: `${description} (decimal string)`,
44
+ };
45
+ case 'enum':
46
+ return { type: 'string', enum: field.options.map((option) => option.value), description };
47
+ case 'multiSelect':
48
+ return {
49
+ type: 'array',
50
+ uniqueItems: true,
51
+ items: { type: 'string', enum: field.options.map((option) => option.value) },
52
+ description,
53
+ };
54
+ case 'manyToMany':
55
+ return {
56
+ type: 'array',
57
+ uniqueItems: true,
58
+ items: { type: 'integer' },
59
+ description: `${description} → ${field.resource} ids`,
60
+ };
61
+ case 'email':
62
+ return { type: 'string', format: 'email', description };
63
+ case 'url':
64
+ return { type: 'string', format: 'uri', description };
21
65
  case 'belongsTo':
22
66
  return { type: 'integer', description: `${description} → ${field.resource}` };
23
67
  case 'user':
24
68
  return { type: 'integer', description: `${description} → user id (related: id, fullName)` };
25
69
  case 'lookup':
26
70
  return { type: 'string', description: `${description} (lookup group ${field.group})` };
27
- case 'attachment':
71
+ case 'attachment': {
72
+ const summary = {
73
+ type: 'object',
74
+ properties: {
75
+ id: { type: 'integer' },
76
+ name: { type: 'string' },
77
+ size: { type: 'integer' },
78
+ mimeType: { type: 'string' },
79
+ url: { type: 'string' },
80
+ preview: { type: ['string', 'null'], enum: ['image', 'pdf', 'text', null] },
81
+ },
82
+ required: ['id', 'name', 'size', 'mimeType'],
83
+ };
84
+ // A multiple field is the ordered array of its files (ADR 047).
85
+ if (field.multiple)
86
+ return mode === 'write'
87
+ ? {
88
+ type: 'array',
89
+ // A required field needs at least one file (write.ts refuses an empty array).
90
+ ...(field.required ? { minItems: 1 } : {}),
91
+ maxItems: attachmentLimit(field),
92
+ uniqueItems: true,
93
+ items: { type: 'integer' },
94
+ description: `${description} (ordered ids returned by POST /attachments)`,
95
+ }
96
+ : { type: 'array', description, items: summary };
28
97
  return mode === 'write'
29
98
  ? { type: 'integer', description: `${description} (id returned by POST /attachments)` }
30
- : {
31
- type: 'object',
32
- description,
33
- properties: {
34
- id: { type: 'integer' },
35
- name: { type: 'string' },
36
- size: { type: 'integer' },
37
- mimeType: { type: 'string' },
38
- },
39
- };
99
+ : { ...summary, description };
100
+ }
40
101
  case 'hasMany': {
41
102
  const child = registry.get(field.resource);
103
+ // Rows are saved with the parent: it sets the foreign key (and a scoped child's unit);
104
+ // `id` updates an existing row and `_delete: true` with `id` removes it.
105
+ const inherited = [field.foreignKey, ...(child.scoped && !child.scope ? ['orgUnitId'] : [])];
42
106
  return {
43
107
  type: 'array',
44
108
  maxItems: 100,
45
109
  description,
46
- items: { $ref: `#/components/schemas/${child.name}_input` },
110
+ items: {
111
+ 'allOf': [{ $ref: `#/components/schemas/${child.name}_input` }],
112
+ 'properties': { id: { type: 'integer' }, _delete: { type: 'boolean' } },
113
+ 'x-adula-inherited': inherited,
114
+ },
47
115
  };
48
116
  }
49
117
  default:
50
118
  return { type: 'string', description };
51
119
  }
52
120
  }
121
+ /** The JSON type a query-string filter value is coerced to (see queryValue in admin/resource/query.ts). */
122
+ function filterSchema(field) {
123
+ // Several files have no equality filter, only filters[field][empty].
124
+ if (isMultipleAttachment(field))
125
+ return undefined;
126
+ switch (field.type) {
127
+ case 'integer':
128
+ case 'belongsTo':
129
+ case 'user':
130
+ case 'attachment':
131
+ return { type: 'integer' };
132
+ case 'boolean':
133
+ return { type: 'boolean' };
134
+ case 'money':
135
+ return { type: 'string', pattern: '^-?\\d+$' };
136
+ case 'date':
137
+ return { type: 'string', format: 'date' };
138
+ case 'datetime':
139
+ return { type: 'string', format: 'date-time' };
140
+ case 'string':
141
+ case 'text':
142
+ case 'lookup':
143
+ return { type: 'string' };
144
+ default:
145
+ return undefined;
146
+ }
147
+ }
148
+ /** Equality filters on filterable fields, sent as `filters[field]=value` (deepObject). */
149
+ function filtersParameter(resource, access) {
150
+ const properties = Object.fromEntries(Object.entries(resource.fields).flatMap(([key, field]) => {
151
+ const schema = field.filterable && queryable(resource, key, access) && filterSchema(field);
152
+ return schema ? [[key, { ...schema, description: field.label.en ?? field.label.ar }]] : [];
153
+ }));
154
+ if (!Object.keys(properties).length)
155
+ return [];
156
+ return [
157
+ {
158
+ name: 'filters',
159
+ in: 'query',
160
+ style: 'deepObject',
161
+ explode: true,
162
+ description: 'Equality filters on filterable fields, as filters[field]=value',
163
+ schema: { type: 'object', additionalProperties: false, properties },
164
+ },
165
+ ];
166
+ }
53
167
  function nullable(schema, required) {
54
168
  if (required)
55
169
  return schema;
@@ -57,8 +171,8 @@ function nullable(schema, required) {
57
171
  return { ...schema, type: [schema.type, 'null'] };
58
172
  return schema;
59
173
  }
60
- function schemas(resource, registry) {
61
- const readKeys = (resource.serialize ?? [...new Set([...resource.list, ...resource.show])]).filter((key) => resource.fields[key]?.type !== 'hasMany');
174
+ function schemas(resource, registry, access) {
175
+ const readKeys = (resource.serialize ?? [...new Set([...resource.list, ...resource.show])]).filter((key) => resource.fields[key]?.type !== 'hasMany' && readable(resource, key, access));
62
176
  const read = {
63
177
  type: 'object',
64
178
  description: `${resource.label.ar}. Fields the caller may not read are omitted.`,
@@ -80,14 +194,20 @@ function schemas(resource, registry) {
80
194
  : {}),
81
195
  ...(resource.scoped ? { orgUnitId: { type: 'integer' } } : {}),
82
196
  },
83
- required: ['id'],
197
+ // serialize() always adds the lifecycle columns; other fields depend on row rules.
198
+ required: [
199
+ 'id',
200
+ ...(resource.version ? ['version'] : []),
201
+ ...(resource.submittable ? ['docStatus'] : []),
202
+ ...(resource.scoped ? ['orgUnitId'] : []),
203
+ ],
84
204
  };
85
- const writable = resource.form.filter((key) => !resource.fields[key].sequence);
205
+ const inputKeys = resource.form.filter((key) => !resource.fields[key].sequence && writable(resource, key, access));
86
206
  const input = {
87
207
  type: 'object',
88
208
  additionalProperties: false,
89
209
  properties: {
90
- ...Object.fromEntries(writable.map((key) => [
210
+ ...Object.fromEntries(inputKeys.map((key) => [
91
211
  key,
92
212
  nullable(fieldSchema(resource.fields[key], 'write', registry), Boolean(resource.fields[key].required)),
93
213
  ])),
@@ -97,7 +217,7 @@ function schemas(resource, registry) {
97
217
  : {}),
98
218
  },
99
219
  required: [
100
- ...writable.filter((key) => resource.fields[key].required),
220
+ ...inputKeys.filter((key) => resource.fields[key].required),
101
221
  ...(resource.scoped && !resource.scope ? ['orgUnitId'] : []),
102
222
  ],
103
223
  };
@@ -113,15 +233,109 @@ const error = {
113
233
  error: {
114
234
  type: 'object',
115
235
  properties: { code: { type: 'string' }, message: { type: 'string' } },
236
+ required: ['code', 'message'],
116
237
  },
117
238
  },
239
+ required: ['error'],
240
+ },
241
+ },
242
+ },
243
+ };
244
+ /** An import batch as ImportBatches returns it (ImportBatchRecord); every key is always present. */
245
+ const importBatchSchema = {
246
+ type: 'object',
247
+ properties: {
248
+ id: { type: 'integer' },
249
+ resource: { type: 'string' },
250
+ resourceLabel: { type: 'string' },
251
+ fileName: { type: 'string' },
252
+ status: {
253
+ enum: ['mapping', 'validated', 'queued', 'running', 'done', 'failed'],
254
+ description: 'validated: a dry run finished; start again to import for real',
255
+ },
256
+ mode: { enum: ['create', 'upsert'] },
257
+ matchField: { type: ['string', 'null'], description: 'Unique field matched on upsert' },
258
+ dryRun: { type: 'boolean' },
259
+ headers: { type: 'array', items: { type: 'string' } },
260
+ mapping: {
261
+ type: 'object',
262
+ description: 'Column index → field key',
263
+ additionalProperties: { type: 'string' },
264
+ },
265
+ sample: { type: 'array', items: { type: 'array', items: { type: 'string' } } },
266
+ total: { type: 'integer' },
267
+ processed: { type: 'integer' },
268
+ created: { type: 'integer', description: 'Created (in a dry run: would be created)' },
269
+ updated: { type: 'integer', description: 'Updated by upsert (in a dry run: would be updated)' },
270
+ failed: { type: 'integer' },
271
+ errors: {
272
+ type: 'array',
273
+ items: {
274
+ type: 'object',
275
+ properties: { row: { type: 'integer' }, message: { type: 'string' } },
276
+ required: ['row', 'message'],
277
+ },
278
+ },
279
+ report: {
280
+ type: 'array',
281
+ description: 'Per-row outcome; row is the file line (the header is line 1)',
282
+ items: {
283
+ type: 'object',
284
+ properties: {
285
+ row: { type: 'integer' },
286
+ ok: { type: 'boolean' },
287
+ action: { enum: ['create', 'update'] },
288
+ message: { type: 'string' },
289
+ },
290
+ required: ['row', 'ok'],
291
+ },
292
+ },
293
+ createdAt: { type: 'string', format: 'date-time' },
294
+ finishedAt: { type: ['string', 'null'], format: 'date-time' },
295
+ targets: {
296
+ type: 'array',
297
+ items: {
298
+ type: 'object',
299
+ properties: {
300
+ key: { type: 'string' },
301
+ label: { type: 'string' },
302
+ type: { type: 'string' },
303
+ required: { type: 'boolean' },
304
+ unique: { type: 'boolean', description: 'Usable as the upsert match field' },
305
+ },
306
+ required: ['key', 'label', 'type', 'required', 'unique'],
118
307
  },
119
308
  },
120
309
  },
310
+ required: [
311
+ 'id',
312
+ 'resource',
313
+ 'resourceLabel',
314
+ 'fileName',
315
+ 'status',
316
+ 'mode',
317
+ 'matchField',
318
+ 'dryRun',
319
+ 'headers',
320
+ 'mapping',
321
+ 'sample',
322
+ 'total',
323
+ 'processed',
324
+ 'created',
325
+ 'updated',
326
+ 'failed',
327
+ 'errors',
328
+ 'report',
329
+ 'createdAt',
330
+ 'finishedAt',
331
+ 'targets',
332
+ ],
121
333
  };
122
334
  /**
123
335
  * OpenAPI 3.1 description of the resource API, generated from the registry. When
124
- * an actor is given, only resources and actions it may use are described.
336
+ * an actor is given, only resources, actions and fields it may use are described.
337
+ * Every operation carries an `operationId` of the form `<resource>.<operation>`
338
+ * (or `imports.<operation>`), which apiClientSource turns into typed client methods.
125
339
  */
126
340
  export function openApiDocument(registry, options) {
127
341
  const base = options.basePath ?? '/api/v1';
@@ -130,37 +344,68 @@ export function openApiDocument(registry, options) {
130
344
  const children = new Set(registry
131
345
  .all()
132
346
  .flatMap((resource) => Object.values(resource.fields).flatMap((field) => field.type === 'hasMany' ? [field.resource] : [])));
347
+ const ability = options.actor ? buildAbility(options.actor.rules, registry.all()) : undefined;
348
+ const access = options.actor && ability ? { actor: options.actor, ability } : undefined;
349
+ const batchRef = { $ref: '#/components/schemas/ImportBatch' };
350
+ const batch = (description) => ({
351
+ description,
352
+ content: {
353
+ 'application/json': {
354
+ schema: { type: 'object', properties: { data: batchRef }, required: ['data'] },
355
+ },
356
+ },
357
+ });
358
+ let importable = false;
133
359
  for (const resource of registry.all()) {
134
- const ability = options.actor ? buildAbility(options.actor.rules, registry.all()) : undefined;
135
360
  const allowed = new Set(resource.actions.filter((action) => !ability || ability.can(action, resource.name)));
136
361
  if (ability && !allowed.has('view'))
137
362
  continue;
138
- const { read, input } = schemas(resource, registry);
363
+ const { read, input } = schemas(resource, registry, access);
139
364
  components[resource.name] = read;
140
365
  components[`${resource.name}_input`] = input;
141
366
  if (children.has(resource.name))
142
367
  continue;
143
368
  const ref = { $ref: `#/components/schemas/${resource.name}` };
144
369
  const inputRef = { $ref: `#/components/schemas/${resource.name}_input` };
145
- const tag = resource.label.en;
370
+ // The API document is English; a resource without label.en falls back to Arabic.
371
+ const tag = resource.label.en ?? resource.label.ar;
146
372
  const one = (description) => ({
147
373
  description,
148
- content: { 'application/json': { schema: { type: 'object', properties: { data: ref } } } },
374
+ content: {
375
+ 'application/json': {
376
+ schema: { type: 'object', properties: { data: ref }, required: ['data'] },
377
+ },
378
+ },
149
379
  });
380
+ const operationId = (operation) => `${resource.name}.${operation}`;
150
381
  const idParam = { name: 'id', in: 'path', required: true, schema: { type: 'integer' } };
382
+ const sortable = [
383
+ 'id',
384
+ ...Object.entries(resource.fields)
385
+ .filter(([key, field]) => field.sortable && queryable(resource, key, access))
386
+ .map(([key]) => key),
387
+ ];
151
388
  const collection = {};
152
389
  const item = {};
153
390
  if (allowed.has('view')) {
154
391
  collection.get = {
155
392
  tags: [tag],
156
- summary: `List ${resource.label.en}`,
393
+ operationId: operationId('list'),
394
+ summary: `List ${tag}`,
157
395
  parameters: [
158
396
  { name: 'limit', in: 'query', schema: { type: 'integer', maximum: 100 } },
159
397
  { name: 'cursor', in: 'query', schema: { type: 'string' } },
160
398
  { name: 'search', in: 'query', schema: { type: 'string' } },
161
- { name: 'sort', in: 'query', schema: { type: 'string' } },
399
+ { name: 'sort', in: 'query', schema: { enum: sortable } },
162
400
  { name: 'direction', in: 'query', schema: { enum: ['asc', 'desc'] } },
163
401
  { name: 'tag', in: 'query', schema: { type: 'string' } },
402
+ {
403
+ name: 'estimate',
404
+ in: 'query',
405
+ description: 'false skips the estimated total',
406
+ schema: { type: 'boolean' },
407
+ },
408
+ ...filtersParameter(resource, access),
164
409
  ],
165
410
  responses: {
166
411
  200: {
@@ -178,18 +423,22 @@ export function openApiDocument(registry, options) {
178
423
  nextCursor: { type: ['string', 'null'] },
179
424
  estimatedTotal: { type: 'integer' },
180
425
  },
426
+ required: ['limit', 'nextCursor'],
181
427
  },
182
428
  },
429
+ required: ['data', 'meta'],
183
430
  },
184
431
  },
185
432
  },
186
433
  },
187
434
  403: error,
435
+ 422: error,
188
436
  },
189
437
  };
190
438
  item.get = {
191
439
  tags: [tag],
192
- summary: `Show one ${resource.label.en} record`,
440
+ operationId: operationId('show'),
441
+ summary: `Show one ${tag} record`,
193
442
  parameters: [idParam],
194
443
  responses: { 200: one('Record'), 403: error, 404: error },
195
444
  };
@@ -197,14 +446,16 @@ export function openApiDocument(registry, options) {
197
446
  if (allowed.has('create'))
198
447
  collection.post = {
199
448
  tags: [tag],
200
- summary: `Create ${resource.label.en}`,
449
+ operationId: operationId('create'),
450
+ summary: `Create ${tag}`,
201
451
  requestBody: { required: true, content: { 'application/json': { schema: inputRef } } },
202
452
  responses: { 201: one('Created'), 403: error, 409: error, 422: error },
203
453
  };
204
454
  if (allowed.has('update'))
205
455
  item.patch = {
206
456
  tags: [tag],
207
- summary: `Update ${resource.label.en}`,
457
+ operationId: operationId('update'),
458
+ summary: `Update ${tag}`,
208
459
  parameters: [idParam],
209
460
  requestBody: { required: true, content: { 'application/json': { schema: inputRef } } },
210
461
  responses: { 200: one('Updated'), 403: error, 404: error, 409: error, 422: error },
@@ -212,7 +463,8 @@ export function openApiDocument(registry, options) {
212
463
  if (allowed.has('delete'))
213
464
  item.delete = {
214
465
  tags: [tag],
215
- summary: `Soft-delete ${resource.label.en}`,
466
+ operationId: operationId('delete'),
467
+ summary: `Soft-delete ${tag}`,
216
468
  parameters: [idParam],
217
469
  responses: { 200: one('Deleted'), 403: error, 404: error, 409: error },
218
470
  };
@@ -220,7 +472,8 @@ export function openApiDocument(registry, options) {
220
472
  paths[`${base}/resources/${resource.name}/aggregate`] = {
221
473
  get: {
222
474
  tags: [tag],
223
- summary: `Count and total ${resource.label.en} by group`,
475
+ operationId: operationId('aggregate'),
476
+ summary: `Count and total ${tag} by group`,
224
477
  description: 'Only records the token may view are counted; grouped, totalled and filtered fields must be readable without conditions.',
225
478
  parameters: [
226
479
  {
@@ -242,6 +495,13 @@ export function openApiDocument(registry, options) {
242
495
  schema: { type: 'string' },
243
496
  },
244
497
  { name: 'search', in: 'query', schema: { type: 'string' } },
498
+ {
499
+ name: 'count',
500
+ in: 'query',
501
+ description: 'false leaves out the group counts',
502
+ schema: { type: 'boolean' },
503
+ },
504
+ ...filtersParameter(resource, access),
245
505
  ],
246
506
  responses: {
247
507
  200: {
@@ -267,11 +527,14 @@ export function openApiDocument(registry, options) {
267
527
  additionalProperties: { type: ['string', 'null'] },
268
528
  },
269
529
  },
530
+ required: ['group'],
270
531
  },
271
532
  },
272
533
  },
534
+ required: ['rows'],
273
535
  },
274
536
  },
537
+ required: ['data'],
275
538
  },
276
539
  },
277
540
  },
@@ -290,7 +553,8 @@ export function openApiDocument(registry, options) {
290
553
  paths[`${base}/resources/${resource.name}/{id}/${action}`] = {
291
554
  post: {
292
555
  tags: [tag],
293
- summary: `${action === 'submit' ? 'Submit' : 'Cancel'} ${resource.label.en}`,
556
+ operationId: operationId(action),
557
+ summary: `${action === 'submit' ? 'Submit' : 'Cancel'} ${tag}`,
294
558
  parameters: [idParam],
295
559
  requestBody: {
296
560
  content: {
@@ -302,6 +566,165 @@ export function openApiDocument(registry, options) {
302
566
  responses: { 200: one('Transitioned'), 403: error, 404: error, 409: error },
303
567
  },
304
568
  };
569
+ if (resource.submittable && allowed.has('amend'))
570
+ paths[`${base}/resources/${resource.name}/{id}/amend`] = {
571
+ post: {
572
+ tags: [tag],
573
+ operationId: operationId('amend'),
574
+ summary: `Amend a cancelled ${tag} record by copy`,
575
+ description: 'Creates a new draft copied from the cancelled document.',
576
+ parameters: [idParam],
577
+ responses: { 201: one('Amended draft'), 403: error, 404: error, 409: error, 422: error },
578
+ },
579
+ };
580
+ // Imports save each row through the same create (and, on upsert, update) authorization
581
+ // as ImportBatches.targets; upsert matches on a unique importable field.
582
+ if (allowed.has('create')) {
583
+ importable = true;
584
+ const matchFields = resource.form.filter((key) => resource.fields[key].unique &&
585
+ !resource.fields[key].sequence &&
586
+ !['hasMany', 'attachment', 'json'].includes(resource.fields[key].type) &&
587
+ writable(resource, key, access));
588
+ const modes = allowed.has('update') && matchFields.length ? ['create', 'upsert'] : ['create'];
589
+ paths[`${base}/resources/${resource.name}/imports`] = {
590
+ post: {
591
+ tags: [tag, 'Imports'],
592
+ operationId: operationId('import'),
593
+ summary: `Upload a CSV import of ${tag}`,
594
+ requestBody: {
595
+ required: true,
596
+ content: {
597
+ 'application/json': {
598
+ schema: {
599
+ type: 'object',
600
+ additionalProperties: false,
601
+ properties: {
602
+ fileName: { type: 'string' },
603
+ content: {
604
+ type: 'string',
605
+ description: 'The file text (CSV), or base64 bytes with encoding base64',
606
+ },
607
+ format: {
608
+ type: 'string',
609
+ description: "Import adapter name, for example 'csv' (default: detected)",
610
+ },
611
+ encoding: {
612
+ enum: ['base64'],
613
+ description: 'content is base64 (binary formats)',
614
+ },
615
+ mode: { enum: modes },
616
+ ...(modes.includes('upsert')
617
+ ? {
618
+ matchField: {
619
+ enum: matchFields,
620
+ description: 'Unique field matched on upsert',
621
+ },
622
+ }
623
+ : {}),
624
+ dryRun: {
625
+ type: 'boolean',
626
+ description: 'Validate every row in a rolled-back transaction (status validated)',
627
+ },
628
+ },
629
+ required: ['fileName', 'content'],
630
+ },
631
+ },
632
+ },
633
+ },
634
+ responses: { 201: batch('Batch awaiting its column mapping'), 403: error, 422: error },
635
+ },
636
+ };
637
+ paths[`${base}/resources/${resource.name}/imports/template`] = {
638
+ get: {
639
+ tags: [tag, 'Imports'],
640
+ operationId: operationId('importTemplate'),
641
+ summary: `CSV template for importing ${tag}`,
642
+ parameters: [
643
+ {
644
+ name: 'mode',
645
+ in: 'query',
646
+ description: 'upsert also needs update permission',
647
+ schema: { enum: modes },
648
+ },
649
+ ],
650
+ responses: {
651
+ 200: {
652
+ description: 'CSV header row',
653
+ content: { 'text/csv': { schema: { type: 'string' } } },
654
+ },
655
+ 403: error,
656
+ },
657
+ },
658
+ };
659
+ }
660
+ }
661
+ if (importable) {
662
+ components.ImportBatch = importBatchSchema;
663
+ const batchId = { name: 'id', in: 'path', required: true, schema: { type: 'integer' } };
664
+ paths[`${base}/imports`] = {
665
+ get: {
666
+ tags: ['Imports'],
667
+ operationId: 'imports.list',
668
+ summary: "The caller's latest import batches",
669
+ responses: {
670
+ 200: {
671
+ description: 'Batches',
672
+ content: {
673
+ 'application/json': {
674
+ schema: {
675
+ type: 'object',
676
+ properties: { data: { type: 'array', items: batchRef } },
677
+ required: ['data'],
678
+ },
679
+ },
680
+ },
681
+ },
682
+ },
683
+ },
684
+ };
685
+ paths[`${base}/imports/{id}`] = {
686
+ get: {
687
+ tags: ['Imports'],
688
+ operationId: 'imports.show',
689
+ summary: 'One import batch of the caller',
690
+ parameters: [batchId],
691
+ responses: { 200: batch('Batch'), 404: error },
692
+ },
693
+ };
694
+ paths[`${base}/imports/{id}/start`] = {
695
+ post: {
696
+ tags: ['Imports'],
697
+ operationId: 'imports.start',
698
+ summary: 'Store the column mapping and queue the batch (again after a dry run)',
699
+ parameters: [batchId],
700
+ requestBody: {
701
+ required: true,
702
+ content: {
703
+ 'application/json': {
704
+ schema: {
705
+ type: 'object',
706
+ properties: {
707
+ mapping: {
708
+ type: 'object',
709
+ description: 'Column index → field key',
710
+ additionalProperties: { type: 'string' },
711
+ },
712
+ mode: { enum: ['create', 'upsert'] },
713
+ matchField: { type: 'string', description: 'Unique field matched on upsert' },
714
+ dryRun: {
715
+ type: 'boolean',
716
+ description: 'Validate only; defaults to false for a validated batch',
717
+ },
718
+ },
719
+ additionalProperties: false,
720
+ required: ['mapping'],
721
+ },
722
+ },
723
+ },
724
+ },
725
+ responses: { 200: batch('Queued'), 403: error, 404: error, 409: error, 422: error },
726
+ },
727
+ };
305
728
  }
306
729
  return {
307
730
  openapi: '3.1.0',