adula 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +5 -3
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -1,4 +1,5 @@
1
- import { identifier, columnName } from '../resource/define_resource.js';
1
+ import { identifier, columnName, joinTable } from '../resource/define_resource.js';
2
+ import { decimalShape, TEXT_LIMITS } from '../resource/values.js';
2
3
  export async function createCoreSchema(db) {
3
4
  await db.raw('CREATE EXTENSION IF NOT EXISTS ltree WITH SCHEMA public');
4
5
  await db.schema.createTable('org_units', (t) => {
@@ -161,8 +162,231 @@ export async function createSavedViewsSchema(db) {
161
162
  t.index(['resource', 'shared']);
162
163
  });
163
164
  }
164
- export async function createResourceTable(db, resource) {
165
+ /** PostgreSQL limits identifiers to 63 bytes and silently truncates longer index names. */
166
+ const indexName = (name) => name.slice(0, 63);
167
+ /** The column type of one stored field (format_type() spelling), or null when it has none. */
168
+ export function fieldColumnType(field) {
169
+ switch (field.type) {
170
+ case 'hasMany':
171
+ case 'manyToMany':
172
+ return null;
173
+ case 'attachment':
174
+ return field.multiple ? 'jsonb' : 'integer';
175
+ case 'belongsTo':
176
+ case 'user':
177
+ case 'integer':
178
+ return 'integer';
179
+ case 'money':
180
+ return 'bigint';
181
+ case 'boolean':
182
+ return 'boolean';
183
+ case 'date':
184
+ return 'date';
185
+ case 'datetime':
186
+ return 'timestamp with time zone';
187
+ case 'json':
188
+ case 'multiSelect':
189
+ return 'jsonb';
190
+ case 'text':
191
+ return 'text';
192
+ case 'decimal':
193
+ case 'percent': {
194
+ const { precision, scale } = decimalShape(field);
195
+ return `numeric(${precision},${scale})`;
196
+ }
197
+ default:
198
+ return `character varying(${TEXT_LIMITS[field.type] ?? 255})`;
199
+ }
200
+ }
201
+ /** NOT NULL: required or sequence fields, unless visibleWhen may hide (and clear) them. */
202
+ function notNull(field) {
203
+ return Boolean(field.sequence || (field.required && field.visibleWhen === undefined));
204
+ }
205
+ /** Whether a field `default` becomes the column default (scalars only, not multiSelect). */
206
+ function columnDefault(field) {
207
+ if (field.default === undefined || field.default === null || Array.isArray(field.default))
208
+ return undefined;
209
+ return field.default;
210
+ }
211
+ /**
212
+ * The table a definition expects: standard and field columns with their types,
213
+ * nullability and defaults, the partial unique indexes (single fields and the
214
+ * resource's composite `unique`) and the join tables of manyToMany fields.
215
+ * createResourceTable builds it and the `resources.schema` doctor check compares it
216
+ * with the live database.
217
+ */
218
+ export function resourceSchema(resource) {
165
219
  const table = identifier(resource.name);
220
+ const standard = (name, type, nullable = false, references) => ({
221
+ name,
222
+ type,
223
+ nullable,
224
+ field: null,
225
+ ...(references ? { references } : {}),
226
+ });
227
+ const columns = [standard('id', 'integer')];
228
+ if (resource.scoped)
229
+ columns.push(standard('org_unit_id', 'integer', false, 'org_units'));
230
+ columns.push(standard('created_by', 'integer', false, 'users'), standard('updated_by', 'integer', false, 'users'), standard('created_at', 'timestamp with time zone'), standard('updated_at', 'timestamp with time zone'), standard('deleted_at', 'timestamp with time zone', true));
231
+ if (resource.version)
232
+ columns.push(standard('version', 'integer'));
233
+ if (resource.submittable)
234
+ columns.push(standard('doc_status', 'smallint'), standard('amended_from_id', 'integer', true, table));
235
+ const unique = [];
236
+ const joinTables = [];
237
+ const columnOf = (key) => key === 'orgUnitId' ? 'org_unit_id' : (resource.fields[key]?.column ?? columnName(key));
238
+ for (const [key, field] of Object.entries(resource.fields)) {
239
+ if (field.type === 'manyToMany') {
240
+ joinTables.push({ ...joinTable(table, key, field), field: key, resource: field.resource });
241
+ continue;
242
+ }
243
+ const type = fieldColumnType(field);
244
+ if (!type)
245
+ continue;
246
+ const name = identifier(field.column ?? columnName(key));
247
+ const fallback = columnDefault(field);
248
+ columns.push({
249
+ name,
250
+ type,
251
+ nullable: !notNull(field),
252
+ field: key,
253
+ ...(fallback === undefined ? {} : { default: fallback }),
254
+ ...(field.type === 'belongsTo'
255
+ ? { references: identifier(field.resource) }
256
+ : field.type === 'attachment' && !field.multiple
257
+ ? { references: 'attachments' }
258
+ : field.type === 'user'
259
+ ? { references: 'users' }
260
+ : {}),
261
+ });
262
+ if (field.unique)
263
+ unique.push({
264
+ name: indexName(`${table}_${columnName(key)}_active_unique`),
265
+ columns: [name],
266
+ fields: [key],
267
+ excludeCancelled: Boolean(resource.submittable),
268
+ });
269
+ }
270
+ for (const keys of resource.unique ?? []) {
271
+ const names = keys.map((key) => identifier(columnOf(key)));
272
+ unique.push({
273
+ name: indexName(`${table}_${names.join('_')}_active_unique`),
274
+ columns: names,
275
+ fields: [...keys],
276
+ excludeCancelled: Boolean(resource.submittable),
277
+ });
278
+ }
279
+ return {
280
+ table,
281
+ columns,
282
+ unique,
283
+ joinTables,
284
+ searchable: Object.entries(resource.fields)
285
+ .filter(([, field]) => field.searchable)
286
+ .map(([key, field]) => identifier(field.column ?? columnName(key))),
287
+ };
288
+ }
289
+ /** Adds one field column to a table builder, as createResourceTable and alterResourceTable do. */
290
+ function addFieldColumn(t, key, field, options) {
291
+ const name = field.column ?? columnName(key);
292
+ let column;
293
+ switch (field.type) {
294
+ case 'belongsTo':
295
+ column = t.integer(name);
296
+ column.references('id').inTable(identifier(field.resource)).onDelete('RESTRICT').index();
297
+ break;
298
+ case 'attachment':
299
+ // Several files are a JSON array of attachment ids; the attachments rows keep the
300
+ // binding (resource, record, field), so no foreign key is needed (ADR 047).
301
+ if (field.multiple) {
302
+ column = t.jsonb(name);
303
+ break;
304
+ }
305
+ column = t.integer(name);
306
+ column.references('id').inTable('attachments').onDelete('RESTRICT').index();
307
+ break;
308
+ case 'user':
309
+ column = t.integer(name);
310
+ column.references('id').inTable('users').onDelete('RESTRICT').index();
311
+ break;
312
+ case 'integer':
313
+ column = t.integer(name);
314
+ break;
315
+ case 'money':
316
+ column = t.bigInteger(name);
317
+ break;
318
+ case 'decimal':
319
+ case 'percent': {
320
+ const { precision, scale } = decimalShape(field);
321
+ column = t.decimal(name, precision, scale);
322
+ break;
323
+ }
324
+ case 'boolean':
325
+ column = t.boolean(name);
326
+ break;
327
+ case 'date':
328
+ column = t.date(name);
329
+ break;
330
+ case 'datetime':
331
+ column = t.timestamp(name, { useTz: true });
332
+ break;
333
+ case 'json':
334
+ case 'multiSelect':
335
+ column = t.jsonb(name);
336
+ break;
337
+ case 'text':
338
+ column = t.text(name);
339
+ break;
340
+ case 'email':
341
+ case 'phone':
342
+ case 'url':
343
+ case 'enum':
344
+ column = t.string(name, TEXT_LIMITS[field.type]);
345
+ break;
346
+ default:
347
+ column = t.string(name);
348
+ }
349
+ const fallback = columnDefault(field);
350
+ if (fallback !== undefined)
351
+ column.defaultTo(fallback);
352
+ // A column added to a table that may hold rows is NOT NULL only when it has a default.
353
+ if (notNull(field) && (!options.alter || fallback !== undefined))
354
+ column.notNullable();
355
+ }
356
+ /** The predicate of a resource unique index (see ResourceUniqueIndex). */
357
+ function uniquePredicate(excludeCancelled) {
358
+ return excludeCancelled ? 'deleted_at IS NULL AND doc_status <> 2' : 'deleted_at IS NULL';
359
+ }
360
+ /**
361
+ * Partial unique indexes over live rows and, on submittable tables, documents that are not
362
+ * cancelled (a cancelled original must not block its amended copy). A composite index
363
+ * treats NULLs as equal (PostgreSQL 15+ NULLS NOT DISTINCT): ("A", null) twice is a
364
+ * duplicate, since a combination with an empty member still names one record. A
365
+ * single-field index keeps allowing many NULLs.
366
+ */
367
+ async function createUniqueIndexes(db, table, indexes, ifNotExists = false) {
368
+ for (const index of indexes)
369
+ await db.raw(`CREATE UNIQUE INDEX ${ifNotExists ? 'IF NOT EXISTS ' : ''}?? ON ?? (${index.columns
370
+ .map(() => '??')
371
+ .join(', ')})${index.columns.length > 1 ? ' NULLS NOT DISTINCT' : ''} WHERE ${uniquePredicate(index.excludeCancelled)}`, [index.name, table, ...index.columns]);
372
+ }
373
+ async function createJoinTables(db, owner, joins) {
374
+ for (const join of joins)
375
+ await db.schema.createTable(join.table, (t) => {
376
+ // Owner rows are soft-deleted, so neither side cascades.
377
+ t.integer(join.owner).notNullable().references('id').inTable(owner).onDelete('RESTRICT');
378
+ t.integer(join.target)
379
+ .notNullable()
380
+ .references('id')
381
+ .inTable(identifier(join.resource))
382
+ .onDelete('RESTRICT')
383
+ .index();
384
+ t.primary([join.owner, join.target]);
385
+ });
386
+ }
387
+ export async function createResourceTable(db, resource) {
388
+ const shape = resourceSchema(resource);
389
+ const table = shape.table;
166
390
  await db.schema.createTable(table, (t) => {
167
391
  t.increments('id');
168
392
  if (resource.scoped)
@@ -183,72 +407,77 @@ export async function createResourceTable(db, resource) {
183
407
  t.smallint('doc_status').notNullable().defaultTo(0);
184
408
  t.integer('amended_from_id').references('id').inTable(table).onDelete('RESTRICT').index();
185
409
  }
410
+ // Legacy replay only: see the customFields note on the parameter.
186
411
  if (resource.customFields)
187
412
  t.jsonb('custom_fields').notNullable().defaultTo('{}');
188
- for (const [key, field] of Object.entries(resource.fields)) {
189
- if (field.type === 'hasMany')
190
- continue;
191
- const name = field.column ?? columnName(key);
192
- let column;
193
- switch (field.type) {
194
- case 'belongsTo':
195
- column = t.integer(name);
196
- column.references('id').inTable(identifier(field.resource)).onDelete('RESTRICT').index();
197
- break;
198
- case 'attachment':
199
- column = t.integer(name);
200
- column.references('id').inTable('attachments').onDelete('RESTRICT').index();
201
- break;
202
- case 'user':
203
- column = t.integer(name);
204
- column.references('id').inTable('users').onDelete('RESTRICT').index();
205
- break;
206
- case 'integer':
207
- column = t.integer(name);
208
- break;
209
- case 'money':
210
- column = t.bigInteger(name);
211
- break;
212
- case 'boolean':
213
- column = t.boolean(name);
214
- break;
215
- case 'date':
216
- column = t.date(name);
217
- break;
218
- case 'datetime':
219
- column = t.timestamp(name, { useTz: true });
220
- break;
221
- case 'json':
222
- column = t.jsonb(name);
223
- break;
224
- case 'text':
225
- column = t.text(name);
226
- break;
227
- default:
228
- column = t.string(name);
229
- }
230
- if (field.required || field.sequence)
231
- column.notNullable();
232
- }
413
+ for (const [key, field] of Object.entries(resource.fields))
414
+ if (fieldColumnType(field))
415
+ addFieldColumn(t, key, field, { alter: false });
233
416
  if (resource.scoped)
234
417
  t.index(['org_unit_id', 'deleted_at']);
235
418
  });
236
- for (const [key, field] of Object.entries(resource.fields)) {
237
- if (field.unique)
238
- await db.raw('CREATE UNIQUE INDEX ?? ON ?? (??) WHERE deleted_at IS NULL', [
239
- `${table}_${columnName(key)}_active_unique`,
240
- table,
241
- field.column ?? columnName(key),
242
- ]);
243
- }
244
- const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable);
245
- if (searchable.length) {
246
- const expression = searchable
247
- .map(([key, field]) => `coalesce("${identifier(field.column ?? columnName(key))}", '')`)
419
+ await createUniqueIndexes(db, table, shape.unique);
420
+ if (shape.searchable.length) {
421
+ const expression = shape.searchable
422
+ .map((column) => `coalesce("${column}", '')`)
248
423
  .join(` || ' ' || `);
249
424
  await db.raw(`ALTER TABLE "${table}" ADD COLUMN search_vector tsvector GENERATED ALWAYS AS (to_tsvector('simple', ${expression})) STORED`);
250
425
  await db.raw('CREATE INDEX ?? ON ?? USING gin(search_vector)', [`${table}_search_gin`, table]);
251
426
  }
427
+ await createJoinTables(db, table, shape.joinTables);
428
+ }
429
+ /** Whether a live table holds submittable documents (it has a doc_status column). */
430
+ async function hasDocStatus(db, table) {
431
+ const result = await db.raw(`SELECT EXISTS (SELECT 1 FROM pg_attribute
432
+ WHERE attrelid = to_regclass(?) AND attname = 'doc_status' AND NOT attisdropped) AS present`, [table]);
433
+ return Boolean(result.rows[0]?.present);
434
+ }
435
+ /**
436
+ * Applies a ResourceAddition: drops NOT NULL from the named columns, adds the columns
437
+ * (NOT NULL only with a default, since the table may hold rows), creates join tables,
438
+ * recreates the named unique indexes with the cancelled-document predicate and creates
439
+ * the new unique indexes (excluding cancelled documents on a submittable table). It never
440
+ * tightens a constraint or drops data, so released migrations replay unchanged. The
441
+ * generated search_vector is not changed: making a field searchable needs a hand-written
442
+ * migration.
443
+ */
444
+ export async function alterResourceTable(db, name, addition) {
445
+ const table = identifier(name);
446
+ const fields = Object.entries(addition.fields ?? {});
447
+ const columns = fields.filter(([, field]) => fieldColumnType(field));
448
+ const excludeCancelled = await hasDocStatus(db, table);
449
+ for (const column of addition.dropNotNull ?? [])
450
+ await db.raw('ALTER TABLE ?? ALTER COLUMN ?? DROP NOT NULL', [table, identifier(column)]);
451
+ if (columns.length)
452
+ await db.schema.alterTable(table, (t) => {
453
+ for (const [key, field] of columns)
454
+ addFieldColumn(t, key, field, { alter: true });
455
+ });
456
+ await createJoinTables(db, table, fields.flatMap(([key, field]) => field.type === 'manyToMany'
457
+ ? [{ ...joinTable(table, key, field), field: key, resource: field.resource }]
458
+ : []));
459
+ const named = (names) => ({
460
+ name: indexName(`${table}_${names.map(identifier).join('_')}_active_unique`),
461
+ columns: [...names],
462
+ fields: [],
463
+ excludeCancelled,
464
+ });
465
+ // Dropped and created in the same migration transaction: the values stay unique among
466
+ // live, non-cancelled rows throughout, and the new predicate only admits more rows.
467
+ for (const stale of addition.recreateUnique ?? []) {
468
+ await db.raw('DROP INDEX IF EXISTS ??', [identifier(stale.index)]);
469
+ await createUniqueIndexes(db, table, [named(stale.columns)], true);
470
+ }
471
+ await createUniqueIndexes(db, table, [
472
+ // Added unique fields get the index createResourceTable would have created.
473
+ ...resourceSchema({
474
+ name: table,
475
+ scoped: false,
476
+ submittable: excludeCancelled,
477
+ fields: Object.fromEntries(columns),
478
+ }).unique,
479
+ ...(addition.unique ?? []).map(named),
480
+ ]);
252
481
  }
253
482
  /** Record collaboration (phase 3): comments with mentions, followers, tags and field history. */
254
483
  export async function createCollaborationSchema(db) {
@@ -536,3 +765,246 @@ export async function createInboundWebhooksSchema(db) {
536
765
  t.index(['received_at']);
537
766
  });
538
767
  }
768
+ /**
769
+ * TOTP two-factor authentication (2.2): one row per user with the sealed secret and
770
+ * the last accepted time step (replay guard), and one row per recovery code so a
771
+ * code is consumed atomically. Codes are stored as SHA-256 over a per-code salt.
772
+ */
773
+ export async function createTwoFactorSchema(db) {
774
+ await db.schema.createTable('user_two_factor', (t) => {
775
+ t.integer('user_id').primary().references('id').inTable('users').onDelete('CASCADE');
776
+ t.text('secret').notNullable();
777
+ t.bigInteger('last_used_step');
778
+ t.timestamp('enabled_at', { useTz: true });
779
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
780
+ t.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
781
+ });
782
+ await db.schema.createTable('user_two_factor_recovery_codes', (t) => {
783
+ t.increments('id');
784
+ t.integer('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
785
+ t.string('salt', 32).notNullable();
786
+ t.string('code_hash', 64).notNullable();
787
+ t.timestamp('used_at', { useTz: true });
788
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
789
+ t.index(['user_id']);
790
+ });
791
+ }
792
+ /**
793
+ * Import modes: upsert by a unique field, dry-run validation and its per-row report.
794
+ * `updated` counts rows an upsert changed; `report` holds the dry run's row outcomes.
795
+ */
796
+ export async function createImportModesSchema(db) {
797
+ await db.schema.alterTable('import_batches', (t) => {
798
+ t.string('mode', 20).notNullable().defaultTo('create');
799
+ t.string('match_field', 100);
800
+ t.boolean('dry_run').notNullable().defaultTo(false);
801
+ t.integer('updated').notNullable().defaultTo(0);
802
+ t.jsonb('report').notNullable().defaultTo('[]');
803
+ });
804
+ }
805
+ /**
806
+ * Background synchronization runs (sync_jobs.ts): one row per queued, running or
807
+ * finished run. The partial unique index allows one open (queued or running) run per job.
808
+ */
809
+ export async function createSyncJobsSchema(db) {
810
+ await db.schema.createTable('sync_job_runs', (t) => {
811
+ t.bigIncrements('id');
812
+ t.string('job', 100).notNullable();
813
+ t.string('trigger', 20).notNullable();
814
+ t.string('status', 20).notNullable().defaultTo('queued');
815
+ t.integer('requested_by').references('id').inTable('users').onDelete('SET NULL');
816
+ t.timestamp('queued_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
817
+ t.timestamp('started_at', { useTz: true });
818
+ t.timestamp('finished_at', { useTz: true });
819
+ t.integer('duration_ms');
820
+ t.string('error_category', 64);
821
+ t.string('error_message', 500);
822
+ t.jsonb('stats').notNullable().defaultTo('{}');
823
+ t.index(['job', 'id']);
824
+ });
825
+ await db.raw("ALTER TABLE sync_job_runs ADD CONSTRAINT sync_job_runs_trigger_check CHECK (trigger IN ('schedule', 'manual'))");
826
+ await db.raw("ALTER TABLE sync_job_runs ADD CONSTRAINT sync_job_runs_status_check CHECK (status IN ('queued', 'running', 'succeeded', 'failed'))");
827
+ await db.raw("CREATE UNIQUE INDEX sync_job_runs_open_unique ON sync_job_runs (job) WHERE status IN ('queued', 'running')");
828
+ await db.raw("CREATE INDEX sync_job_runs_queued_idx ON sync_job_runs (queued_at, id) WHERE status = 'queued'");
829
+ }
830
+ /**
831
+ * Notification channels (2.x): per-user channel preferences (e-mail opt-out, the
832
+ * address of an HTTP provider channel such as SMS or WhatsApp) and the delivery state
833
+ * of channels other than in-app and e-mail, which keeps its notifications.mail_state.
834
+ * Only error categories are stored, never provider response bodies.
835
+ */
836
+ export async function createNotificationChannelsSchema(db) {
837
+ await db.schema.createTable('user_notification_channels', (t) => {
838
+ t.increments('id');
839
+ t.integer('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
840
+ t.string('channel', 40).notNullable();
841
+ t.boolean('enabled').notNullable();
842
+ /** The channel address (a phone number); null for e-mail, which uses users.email. */
843
+ t.string('address', 40);
844
+ t.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
845
+ t.unique(['user_id', 'channel']);
846
+ });
847
+ await db.schema.createTable('notification_deliveries', (t) => {
848
+ t.uuid('id').primary();
849
+ t.integer('notification_id')
850
+ .notNullable()
851
+ .references('id')
852
+ .inTable('notifications')
853
+ .onDelete('CASCADE');
854
+ t.string('channel', 40).notNullable();
855
+ t.string('state', 10).notNullable().defaultTo('pending');
856
+ t.integer('attempts').notNullable().defaultTo(0);
857
+ t.string('error_category', 40);
858
+ t.timestamp('next_attempt_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
859
+ t.timestamp('sent_at', { useTz: true });
860
+ /** The claim that may write this row; a worker whose lease was taken over writes nothing. */
861
+ t.uuid('lease_id');
862
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
863
+ t.unique(['notification_id', 'channel']);
864
+ });
865
+ await db.raw("ALTER TABLE notification_deliveries ADD CONSTRAINT notification_deliveries_state_check CHECK (state IN ('pending','sent','failed','skipped'))");
866
+ await db.raw("CREATE INDEX notification_deliveries_pending ON notification_deliveries (next_attempt_at) WHERE state = 'pending'");
867
+ }
868
+ /**
869
+ * Confirmation of a notification channel address (2.x): a one-time code sent to the
870
+ * number before the channel can be enabled with it. One row per user and channel, the
871
+ * code stored as SHA-256 over a per-code salt and void after five wrong attempts; the
872
+ * row also counts codes sent in a 24-hour window. Preferences record when their number
873
+ * was confirmed; a number without confirmed_at never receives messages.
874
+ */
875
+ export async function createChannelConfirmationsSchema(db) {
876
+ await db.schema.alterTable('user_notification_channels', (t) => {
877
+ t.timestamp('confirmed_at', { useTz: true });
878
+ });
879
+ await db.schema.createTable('notification_channel_confirmations', (t) => {
880
+ t.increments('id');
881
+ t.integer('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
882
+ t.string('channel', 40).notNullable();
883
+ t.string('address', 40).notNullable();
884
+ t.string('salt', 32).notNullable();
885
+ t.string('code_hash', 64).notNullable();
886
+ t.integer('attempts').notNullable().defaultTo(0);
887
+ t.timestamp('expires_at', { useTz: true }).notNullable();
888
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
889
+ t.integer('sent_count').notNullable().defaultTo(0);
890
+ t.timestamp('window_started_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
891
+ t.unique(['user_id', 'channel']);
892
+ t.index(['expires_at']);
893
+ });
894
+ }
895
+ /**
896
+ * Import worker leases: a claimed batch belongs to one worker until lease_expires_at;
897
+ * every progress write names lease_id, so a worker whose lease was taken over writes nothing.
898
+ */
899
+ export async function createImportLeasesSchema(db) {
900
+ await db.schema.alterTable('import_batches', (t) => {
901
+ t.uuid('lease_id');
902
+ t.timestamp('lease_expires_at', { useTz: true });
903
+ });
904
+ }
905
+ /**
906
+ * Approval delegation and SLA deadlines (ADR 044). A delegation routes a user's new
907
+ * approvals to a delegate for a date range and lets the delegate act on the user's
908
+ * pending ones; overlap is refused by WorkflowDelegations under a row lock. Approval
909
+ * assignments gain a deadline, the delegation they were routed through and the SLA
910
+ * markers; workflow_escalations records each reminder and escalation once.
911
+ */
912
+ export async function createWorkflowDelegationSlaSchema(db) {
913
+ await db.schema.createTable('workflow_delegations', (t) => {
914
+ t.increments('id');
915
+ t.integer('delegator_id').notNullable().references('id').inTable('users').onDelete('RESTRICT');
916
+ t.integer('delegate_id').notNullable().references('id').inTable('users').onDelete('RESTRICT');
917
+ t.date('starts_on').notNullable();
918
+ t.date('ends_on').notNullable();
919
+ t.string('note', 500);
920
+ t.integer('created_by').references('id').inTable('users').onDelete('SET NULL');
921
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
922
+ t.timestamp('revoked_at', { useTz: true });
923
+ t.integer('revoked_by').references('id').inTable('users').onDelete('SET NULL');
924
+ t.index(['delegator_id', 'ends_on']);
925
+ t.index(['delegate_id', 'ends_on']);
926
+ });
927
+ await db.raw('ALTER TABLE workflow_delegations ADD CONSTRAINT workflow_delegations_distinct CHECK (delegator_id <> delegate_id), ADD CONSTRAINT workflow_delegations_range CHECK (ends_on >= starts_on)');
928
+ await db.schema.alterTable('assignments', (t) => {
929
+ t.integer('on_behalf_of').references('id').inTable('users').onDelete('RESTRICT');
930
+ t.integer('delegation_id').references('id').inTable('workflow_delegations').onDelete('RESTRICT');
931
+ t.timestamp('due_at', { useTz: true });
932
+ t.timestamp('due_soon_at', { useTz: true });
933
+ t.timestamp('reminded_at', { useTz: true });
934
+ t.timestamp('escalated_at', { useTz: true });
935
+ });
936
+ await db.raw("CREATE INDEX assignments_sla_due ON assignments (due_at) WHERE status = 'open' AND due_at IS NOT NULL");
937
+ // Inboxes and My tasks filter open approvals by the approver they were routed for.
938
+ await db.raw("CREATE INDEX assignments_on_behalf_of ON assignments (on_behalf_of) WHERE status = 'open' AND on_behalf_of IS NOT NULL");
939
+ await db.raw('CREATE INDEX assignments_delegation ON assignments (delegation_id) WHERE delegation_id IS NOT NULL');
940
+ await db.schema.createTable('workflow_escalations', (t) => {
941
+ t.bigIncrements('id');
942
+ t.uuid('run_id').notNullable().references('id').inTable('workflow_runs').onDelete('CASCADE');
943
+ t.string('step', 100).notNullable();
944
+ t.bigInteger('assignment_id')
945
+ .notNullable()
946
+ .references('id')
947
+ .inTable('assignments')
948
+ .onDelete('CASCADE');
949
+ t.string('level', 20).notNullable();
950
+ t.string('action', 20).notNullable();
951
+ t.jsonb('targets').notNullable().defaultTo('[]');
952
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
953
+ t.unique(['assignment_id', 'level']);
954
+ t.index(['run_id', 'id']);
955
+ });
956
+ }
957
+ /**
958
+ * Administrator print templates (ADR 048). A template row points to its current
959
+ * version; versions are immutable (a trigger refuses UPDATE and DELETE, except clearing
960
+ * created_by when the author is deleted), so a printed
961
+ * document's recorded version always resolves to the markup that produced it.
962
+ * Templates are deployment-wide, like message_templates.
963
+ */
964
+ export async function createPrintTemplatesSchema(db) {
965
+ await db.schema.createTable('print_templates', (t) => {
966
+ t.increments('id');
967
+ t.string('resource', 63).notNullable();
968
+ t.string('key', 64).notNullable();
969
+ t.string('label', 200).notNullable();
970
+ t.integer('current_version').notNullable().defaultTo(0);
971
+ t.boolean('active').notNullable().defaultTo(true);
972
+ t.integer('created_by').references('id').inTable('users').onDelete('SET NULL');
973
+ t.integer('updated_by').references('id').inTable('users').onDelete('SET NULL');
974
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
975
+ t.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
976
+ t.unique(['resource', 'key']);
977
+ });
978
+ await db.schema.createTable('print_template_versions', (t) => {
979
+ t.bigIncrements('id');
980
+ t.integer('template_id')
981
+ .notNullable()
982
+ .references('id')
983
+ .inTable('print_templates')
984
+ .onDelete('RESTRICT');
985
+ t.integer('version').notNullable();
986
+ t.string('label', 200).notNullable();
987
+ t.text('body').notNullable();
988
+ t.string('paper', 10).notNullable();
989
+ t.string('orientation', 10).notNullable();
990
+ t.string('header', 500).notNullable().defaultTo('');
991
+ t.string('footer', 500).notNullable().defaultTo('');
992
+ t.integer('created_by').references('id').inTable('users').onDelete('SET NULL');
993
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
994
+ t.unique(['template_id', 'version']);
995
+ });
996
+ await db.raw("ALTER TABLE print_template_versions ADD CONSTRAINT print_template_versions_paper CHECK (paper IN ('A4', 'A5', 'Letter')), ADD CONSTRAINT print_template_versions_orientation CHECK (orientation IN ('portrait', 'landscape')), ADD CONSTRAINT print_template_versions_positive CHECK (version > 0)");
997
+ await db.raw(`CREATE FUNCTION adula_print_template_versions_immutable() RETURNS trigger AS $$
998
+ BEGIN
999
+ -- Deleting the author only clears created_by (ON DELETE SET NULL); nothing else changes.
1000
+ IF TG_OP = 'UPDATE' AND NEW.created_by IS NULL
1001
+ AND (NEW.id, NEW.template_id, NEW.version, NEW.label, NEW.body, NEW.paper, NEW.orientation, NEW.header, NEW.footer, NEW.created_at)
1002
+ IS NOT DISTINCT FROM (OLD.id, OLD.template_id, OLD.version, OLD.label, OLD.body, OLD.paper, OLD.orientation, OLD.header, OLD.footer, OLD.created_at)
1003
+ THEN
1004
+ RETURN NEW;
1005
+ END IF;
1006
+ RAISE EXCEPTION 'print_template_versions rows are immutable';
1007
+ END
1008
+ $$ LANGUAGE plpgsql`);
1009
+ await db.raw('CREATE TRIGGER print_template_versions_immutable BEFORE UPDATE OR DELETE ON print_template_versions FOR EACH ROW EXECUTE FUNCTION adula_print_template_versions_immutable()');
1010
+ }
@@ -0,0 +1,56 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Resource } from '../resource/types.js';
3
+ import { type ResourceAddition, type ResourceColumn, type ResourceJoinTable, type ResourceTableDefinition, type ResourceUniqueIndex } from './schema.js';
4
+ /** What the live database lacks or holds differently from a definition's resourceSchema. */
5
+ export type SchemaDrift = {
6
+ table: string;
7
+ /** The table itself does not exist (its create-migration has not run). */
8
+ missingTable: boolean;
9
+ missingColumns: ResourceColumn[];
10
+ /** Columns whose PostgreSQL type differs (varchar lengths are not compared). */
11
+ wrongTypes: {
12
+ column: string;
13
+ expected: string;
14
+ actual: string;
15
+ }[];
16
+ /**
17
+ * Field columns that are NOT NULL while the definition lets them be empty (for example
18
+ * a required field that gained `visibleWhen`). Only this relaxing direction is reported:
19
+ * NOT NULL is never added automatically.
20
+ */
21
+ notNullColumns: string[];
22
+ missingUnique: ResourceUniqueIndex[];
23
+ /**
24
+ * Unique indexes of a submittable table whose predicate still counts cancelled
25
+ * documents (created before cancelled documents were excluded): `index` is the live
26
+ * index name, `expected` the index the definition wants instead.
27
+ */
28
+ staleUnique: {
29
+ index: string;
30
+ expected: ResourceUniqueIndex;
31
+ }[];
32
+ missingJoinTables: ResourceJoinTable[];
33
+ };
34
+ /**
35
+ * Compares the live table (resolved through the connection's search_path) with what the
36
+ * definition expects: missing columns, different types, NOT NULL columns the definition
37
+ * lets be empty, missing unique indexes (by column set, whatever their name), unique
38
+ * indexes that still count cancelled documents and missing join tables. Nothing is changed.
39
+ */
40
+ export declare function schemaDrift(db: Knex, resource: ResourceTableDefinition): Promise<SchemaDrift>;
41
+ /** Whether a drift needs nothing. */
42
+ export declare function inSync(drift: SchemaDrift): boolean;
43
+ /** Whether adula:resource:migration has something to write for a drift. */
44
+ export declare function migratable(drift: SchemaDrift): boolean;
45
+ /** One line per difference, for adula:doctor and adula:resource:migration. */
46
+ export declare function describeDrift(drift: SchemaDrift): string[];
47
+ /**
48
+ * The migration content for a drift: snapshots of the fields whose column or join table
49
+ * is missing, the missing unique indexes not created with those fields, and the relaxing
50
+ * changes (NOT NULL dropped, unique indexes recreated without cancelled documents). Wrong
51
+ * types are never changed and NOT NULL is never added automatically; they need a
52
+ * hand-written migration.
53
+ */
54
+ export declare function resourceAddition(resource: Pick<Resource, 'fields'>, drift: SchemaDrift): ResourceAddition;
55
+ /** The source of a migration that applies `addition` with alterResourceTable. */
56
+ export declare function additionMigrationSource(name: string, addition: ResourceAddition): string;