adula 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -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,428 @@ 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
+ }
1011
+ /** Template keys of the notifications that quote a comment's text. */
1012
+ export const COMMENT_NOTIFICATION_KEYS = ['comment.mentioned', 'comment.created'];
1013
+ export const DELETED_COMMENT_TITLE = 'تعليق محذوف';
1014
+ export const DELETED_COMMENT_BODY = 'حُذف هذا التعليق.';
1015
+ /**
1016
+ * Ids and template keys of the notifications that quote a comment: those naming it
1017
+ * (comment_id, 2.3.0) and those written before notifications named their comment. A
1018
+ * comment's notifications were inserted in its own transaction, so their created_at equals
1019
+ * the comment's (both now()), and they quote its text from the start: the first 100
1020
+ * characters are matched, which the 200-unit excerpt always contains. Read before a
1021
+ * comment's body changes. `comment` is one comment id, or 'deleted' for every deleted one.
1022
+ */
1023
+ export async function commentNotifications(db, comment) {
1024
+ const result = await db.raw(`SELECT DISTINCT n.id, n.template_key FROM notifications n JOIN comments c
1025
+ ON n.comment_id = c.id OR (
1026
+ n.comment_id IS NULL AND n.template_key IN (?, ?) AND n.created_at = c.created_at
1027
+ AND (n.resource IS NULL OR (n.resource = c.resource AND n.record_id = c.record_id))
1028
+ AND (strpos(n.body, left(c.body, 100)) > 0 OR strpos(n.title, left(c.body, 100)) > 0))
1029
+ WHERE ${comment === 'deleted' ? 'c.deleted_at IS NOT NULL' : 'c.id = ?'}`, [...COMMENT_NOTIFICATION_KEYS, ...(comment === 'deleted' ? [] : [comment])]);
1030
+ return result.rows.map((row) => ({
1031
+ id: Number(row.id),
1032
+ key: String(row.template_key ?? ''),
1033
+ }));
1034
+ }
1035
+ /**
1036
+ * Stops what has not been sent yet of the given notifications: pending e-mail is skipped
1037
+ * and pending channel deliveries are withdrawn (a channel worker re-checks the pending
1038
+ * state before it sends, so a claimed delivery is not sent either).
1039
+ */
1040
+ export async function withdrawNotificationDelivery(db, ids) {
1041
+ if (!ids.length)
1042
+ return;
1043
+ await db('notifications').whereIn('id', ids).where('mail_state', 'pending').update({
1044
+ mail_state: 'skipped',
1045
+ });
1046
+ await db('notification_deliveries')
1047
+ .whereIn('notification_id', ids)
1048
+ .where('state', 'pending')
1049
+ .update({ state: 'skipped', error_category: 'withdrawn' });
1050
+ }
1051
+ /**
1052
+ * Comment notifications name their comment (2.3.0), so deleting or editing the comment
1053
+ * withdraws the quoted text. Notifications of comments deleted before this migration are
1054
+ * found by their transaction time and quoted text, and withdrawn here.
1055
+ */
1056
+ export async function createCommentNotificationsSchema(db) {
1057
+ await db.schema.alterTable('notifications', (t) => {
1058
+ t.bigInteger('comment_id').references('id').inTable('comments').onDelete('SET NULL');
1059
+ });
1060
+ await db.raw('CREATE INDEX notifications_comment_id ON notifications (comment_id) WHERE comment_id IS NOT NULL');
1061
+ await withdrawDeletedCommentNotifications(db);
1062
+ }
1063
+ /** Replaces the quoted text of every deleted comment's notifications with a neutral note. */
1064
+ export async function withdrawDeletedCommentNotifications(db) {
1065
+ const rows = await commentNotifications(db, 'deleted');
1066
+ const ids = rows.map((row) => row.id);
1067
+ for (let start = 0; start < ids.length; start += 1000) {
1068
+ const chunk = ids.slice(start, start + 1000);
1069
+ await db('notifications')
1070
+ .whereIn('id', chunk)
1071
+ .update({ title: DELETED_COMMENT_TITLE, body: DELETED_COMMENT_BODY });
1072
+ await withdrawNotificationDelivery(db, chunk);
1073
+ }
1074
+ }
1075
+ /**
1076
+ * The built-in assistant (ADR 052): conversation metadata (never message text), pending
1077
+ * write proposals awaiting the user's confirmation, and per-user daily token usage.
1078
+ */
1079
+ export async function createAssistantSchema(db) {
1080
+ await db.schema.createTable('ai_conversations', (t) => {
1081
+ // Integer: the id is the record_id of the conversation's activity entries.
1082
+ t.increments('id');
1083
+ t.integer('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
1084
+ t.integer('impersonator_id').references('id').inTable('users').onDelete('SET NULL');
1085
+ t.integer('turns').notNullable().defaultTo(0);
1086
+ t.integer('tokens').notNullable().defaultTo(0);
1087
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
1088
+ t.timestamp('last_turn_at', { useTz: true });
1089
+ t.index(['user_id', 'created_at']);
1090
+ });
1091
+ await db.schema.createTable('ai_pending_actions', (t) => {
1092
+ t.uuid('id').primary();
1093
+ t.integer('conversation_id')
1094
+ .notNullable()
1095
+ .references('id')
1096
+ .inTable('ai_conversations')
1097
+ .onDelete('CASCADE');
1098
+ t.integer('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
1099
+ t.integer('impersonator_id');
1100
+ t.string('resource').notNullable();
1101
+ t.string('action').notNullable();
1102
+ t.integer('record_id');
1103
+ t.jsonb('input');
1104
+ t.integer('version');
1105
+ t.timestamp('expires_at', { useTz: true }).notNullable();
1106
+ t.timestamp('consumed_at', { useTz: true });
1107
+ t.string('outcome', 20);
1108
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
1109
+ t.index(['user_id', 'consumed_at']);
1110
+ t.index(['expires_at']);
1111
+ });
1112
+ await db.schema.createTable('ai_usage', (t) => {
1113
+ t.integer('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
1114
+ t.date('day').notNullable();
1115
+ t.integer('prompt_tokens').notNullable().defaultTo(0);
1116
+ t.integer('completion_tokens').notNullable().defaultTo(0);
1117
+ t.integer('reserved').notNullable().defaultTo(0);
1118
+ t.integer('requests').notNullable().defaultTo(0);
1119
+ t.primary(['user_id', 'day']);
1120
+ });
1121
+ }
1122
+ /**
1123
+ * Cloud and downloadable backups (ADR 051): one connection per destination with its refresh
1124
+ * token sealed by the host's SecretBox, and one row per backup run.
1125
+ */
1126
+ export async function createCloudBackupsSchema(db) {
1127
+ await db.schema.createTable('backup_connections', (t) => {
1128
+ t.increments('id');
1129
+ t.string('provider', 20).notNullable().unique();
1130
+ t.string('status', 20).notNullable().defaultTo('connected');
1131
+ t.string('account_label', 320);
1132
+ t.text('refresh_token').notNullable();
1133
+ t.string('schedule', 10).notNullable().defaultTo('off');
1134
+ t.integer('connected_by').notNullable().references('id').inTable('users').onDelete('RESTRICT');
1135
+ t.timestamp('connected_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
1136
+ t.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
1137
+ });
1138
+ await db.raw(`ALTER TABLE backup_connections
1139
+ ADD CONSTRAINT backup_connections_provider CHECK (provider IN ('google', 'onedrive')),
1140
+ ADD CONSTRAINT backup_connections_status CHECK (status IN ('connected', 'revoked')),
1141
+ ADD CONSTRAINT backup_connections_schedule CHECK (schedule IN ('off', 'daily', 'weekly'))`);
1142
+ await db.schema.createTable('backup_runs', (t) => {
1143
+ t.bigIncrements('id');
1144
+ t.string('kind', 20).notNullable();
1145
+ t.integer('connection_id').references('id').inTable('backup_connections').onDelete('SET NULL');
1146
+ t.string('trigger', 10).notNullable().defaultTo('manual');
1147
+ t.string('status', 20).notNullable().defaultTo('queued');
1148
+ t.integer('requested_by').notNullable().references('id').inTable('users').onDelete('RESTRICT');
1149
+ t.string('file_name', 200);
1150
+ t.bigInteger('size_bytes');
1151
+ t.string('sha256', 64);
1152
+ t.string('remote_id', 500);
1153
+ t.timestamp('expires_at', { useTz: true });
1154
+ t.string('error_category', 40);
1155
+ t.string('error_message', 500);
1156
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
1157
+ t.timestamp('started_at', { useTz: true });
1158
+ t.timestamp('finished_at', { useTz: true });
1159
+ });
1160
+ await db.raw(`ALTER TABLE backup_runs
1161
+ ADD CONSTRAINT backup_runs_kind CHECK (kind IN ('download', 'google', 'onedrive')),
1162
+ ADD CONSTRAINT backup_runs_trigger CHECK (trigger IN ('manual', 'schedule')),
1163
+ ADD CONSTRAINT backup_runs_status
1164
+ CHECK (status IN ('queued', 'running', 'succeeded', 'failed', 'expired'))`);
1165
+ await db.raw(`CREATE UNIQUE INDEX backup_runs_active ON backup_runs (kind) WHERE status IN ('queued', 'running')`);
1166
+ await db.raw('CREATE INDEX backup_runs_kind_created ON backup_runs (kind, created_at DESC)');
1167
+ }
1168
+ /**
1169
+ * Appearance occasions (ADR 053): dated overrides of the base identity, which is the system
1170
+ * setting `appearance.identity`. Logos are `attachments` rows, so only the id is kept here.
1171
+ * Overlapping ranges are refused by the service under a table lock.
1172
+ */
1173
+ export async function createAppearanceSchema(db) {
1174
+ await db.schema.createTable('appearance_occasions', (t) => {
1175
+ t.increments('id');
1176
+ t.string('name', 80).notNullable();
1177
+ t.date('starts_on').notNullable();
1178
+ t.date('ends_on').notNullable();
1179
+ t.string('primary_color', 7);
1180
+ t.integer('logo_id');
1181
+ t.string('banner', 160);
1182
+ t.string('login_title', 120);
1183
+ t.string('login_description', 300);
1184
+ t.integer('created_by').references('id').inTable('users').onDelete('SET NULL');
1185
+ t.integer('updated_by').references('id').inTable('users').onDelete('SET NULL');
1186
+ t.timestamp('created_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
1187
+ t.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
1188
+ t.index(['starts_on', 'ends_on']);
1189
+ });
1190
+ await db.raw('ALTER TABLE appearance_occasions ADD CONSTRAINT appearance_occasions_dates CHECK (ends_on >= starts_on)');
1191
+ await db.raw("ALTER TABLE appearance_occasions ADD CONSTRAINT appearance_occasions_color CHECK (primary_color IS NULL OR primary_color ~ '^#[0-9a-f]{6}$')");
1192
+ }