adula 2.2.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 (132) hide show
  1. package/README.md +1 -1
  2. package/build/agent/capabilities.md +2 -3
  3. package/build/agent/skills/adula-frontend-design/SKILL.md +5 -3
  4. package/build/commands/adula_assistant_prune.d.ts +10 -0
  5. package/build/commands/adula_assistant_prune.js +12 -0
  6. package/build/commands/backup_open.d.ts +16 -0
  7. package/build/commands/backup_open.js +48 -0
  8. package/build/commands/backup_restore_test.js +3 -0
  9. package/build/commands/backup_seal.d.ts +12 -0
  10. package/build/commands/backup_seal.js +36 -0
  11. package/build/commands/backup_services.d.ts +3 -1
  12. package/build/commands/doctor.js +18 -1
  13. package/build/commands/install.js +6 -0
  14. package/build/commands/main.d.ts +2 -2
  15. package/build/commands/main.js +6 -0
  16. package/build/commands/resource_migration.js +12 -3
  17. package/build/commands/resource_snapshot.js +18 -4
  18. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  19. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  20. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  21. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  22. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  23. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  24. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  25. package/build/database/migrations/1770000000056_appearance.js +10 -0
  26. package/build/index.d.ts +36 -6
  27. package/build/index.js +18 -3
  28. package/build/src/admin/controller.js +18 -4
  29. package/build/src/admin/resource/editor.d.ts +1 -0
  30. package/build/src/admin/resource/editor.js +26 -4
  31. package/build/src/admin/resource/export.d.ts +21 -4
  32. package/build/src/admin/resource/export.js +117 -36
  33. package/build/src/admin/resource/lifecycle.d.ts +2 -0
  34. package/build/src/admin/resource/query.d.ts +14 -3
  35. package/build/src/admin/resource/query.js +98 -11
  36. package/build/src/admin/resource/read.d.ts +3 -0
  37. package/build/src/admin/resource/read.js +75 -14
  38. package/build/src/admin/resource/shared.d.ts +16 -0
  39. package/build/src/admin/resource/shared.js +47 -4
  40. package/build/src/admin/resource/write.js +37 -8
  41. package/build/src/admin/resource_service.d.ts +17 -3
  42. package/build/src/admin/resource_service.js +16 -2
  43. package/build/src/admin/resource_tools.d.ts +111 -0
  44. package/build/src/admin/resource_tools.js +139 -0
  45. package/build/src/ai/assistant.d.ts +100 -0
  46. package/build/src/ai/assistant.js +487 -0
  47. package/build/src/ai/client.d.ts +49 -0
  48. package/build/src/ai/client.js +85 -0
  49. package/build/src/ai/prompt.d.ts +23 -0
  50. package/build/src/ai/prompt.js +83 -0
  51. package/build/src/ai/settings.d.ts +56 -0
  52. package/build/src/ai/settings.js +214 -0
  53. package/build/src/ai/usage.d.ts +16 -0
  54. package/build/src/ai/usage.js +33 -0
  55. package/build/src/appearance/appearance.d.ts +134 -0
  56. package/build/src/appearance/appearance.js +461 -0
  57. package/build/src/appearance/colors.d.ts +43 -0
  58. package/build/src/appearance/colors.js +99 -0
  59. package/build/src/appearance/logo.d.ts +32 -0
  60. package/build/src/appearance/logo.js +112 -0
  61. package/build/src/auth/actor_store.d.ts +5 -1
  62. package/build/src/auth/actor_store.js +8 -4
  63. package/build/src/backups/archive.d.ts +52 -0
  64. package/build/src/backups/archive.js +362 -0
  65. package/build/src/backups/cloud_backups.d.ts +133 -0
  66. package/build/src/backups/cloud_backups.js +650 -0
  67. package/build/src/backups/doctor.d.ts +7 -0
  68. package/build/src/backups/doctor.js +55 -0
  69. package/build/src/backups/providers.d.ts +81 -0
  70. package/build/src/backups/providers.js +470 -0
  71. package/build/src/collaboration/assignments.d.ts +24 -2
  72. package/build/src/collaboration/assignments.js +88 -32
  73. package/build/src/collaboration/record_collaboration.d.ts +19 -1
  74. package/build/src/collaboration/record_collaboration.js +109 -37
  75. package/build/src/collaboration/shared.d.ts +10 -2
  76. package/build/src/collaboration/shared.js +14 -1
  77. package/build/src/commands/capabilities.js +1 -1
  78. package/build/src/commands/doctor.d.ts +10 -0
  79. package/build/src/commands/doctor.js +31 -1
  80. package/build/src/commands/snapshot.d.ts +14 -0
  81. package/build/src/commands/snapshot.js +23 -0
  82. package/build/src/core/administrators.js +19 -3
  83. package/build/src/core/avatar_image.d.ts +33 -0
  84. package/build/src/core/avatar_image.js +278 -0
  85. package/build/src/core/mail_settings.d.ts +83 -0
  86. package/build/src/core/mail_settings.js +274 -0
  87. package/build/src/core/mail_test.d.ts +16 -0
  88. package/build/src/core/mail_test.js +81 -6
  89. package/build/src/core/message_templates.d.ts +8 -0
  90. package/build/src/core/message_templates.js +12 -3
  91. package/build/src/core/roles.js +24 -7
  92. package/build/src/core/saved_views.js +55 -24
  93. package/build/src/core/settings.d.ts +2 -2
  94. package/build/src/core/settings.js +15 -4
  95. package/build/src/core/ui_preferences.d.ts +6 -0
  96. package/build/src/core/ui_preferences.js +12 -1
  97. package/build/src/core/user_avatars.d.ts +79 -0
  98. package/build/src/core/user_avatars.js +186 -0
  99. package/build/src/core/user_preferences.d.ts +36 -0
  100. package/build/src/core/user_preferences.js +125 -0
  101. package/build/src/core/users.d.ts +2 -0
  102. package/build/src/core/users.js +4 -2
  103. package/build/src/database/schema.d.ts +46 -0
  104. package/build/src/database/schema.js +182 -0
  105. package/build/src/database/schema_diff.d.ts +16 -2
  106. package/build/src/database/schema_diff.js +40 -7
  107. package/build/src/integrations/api_client.js +18 -3
  108. package/build/src/integrations/imports.d.ts +16 -4
  109. package/build/src/integrations/imports.js +36 -8
  110. package/build/src/integrations/openapi.js +15 -4
  111. package/build/src/integrations/outbound.d.ts +43 -0
  112. package/build/src/integrations/outbound.js +98 -17
  113. package/build/src/integrations/print.d.ts +2 -1
  114. package/build/src/integrations/print.js +7 -3
  115. package/build/src/integrations/print_templates.js +3 -1
  116. package/build/src/integrations/xlsx.d.ts +41 -0
  117. package/build/src/integrations/xlsx.js +519 -0
  118. package/build/src/languages/ar.js +22 -0
  119. package/build/src/languages/ar_ui.d.ts +143 -14
  120. package/build/src/languages/ar_ui.js +145 -14
  121. package/build/src/languages/en.js +22 -0
  122. package/build/src/languages/en_ui.js +144 -14
  123. package/build/src/lists/dashboards.d.ts +42 -0
  124. package/build/src/lists/dashboards.js +49 -0
  125. package/build/src/mcp/tools.js +9 -104
  126. package/build/src/resource/define_resource.js +7 -0
  127. package/build/src/resource/types.d.ts +9 -0
  128. package/build/src/workflows/delegations.d.ts +15 -1
  129. package/build/src/workflows/delegations.js +49 -10
  130. package/build/src/workflows/engine.d.ts +11 -0
  131. package/build/src/workflows/engine.js +29 -7
  132. package/package.json +5 -1
@@ -6,12 +6,19 @@ import { resolveActorConditions } from '../../auth/conditions.js';
6
6
  import { AdulaError, forbiddenField, invalidCursor, invalidFilter, searchUnavailable, } from '../errors.js';
7
7
  import { fieldValue, isMultipleAttachment } from '../../resource/values.js';
8
8
  import { authorizeAction, canQueryField, columns, hydrate, permissions, collectionFilter, withLinks, } from './shared.js';
9
- import { preload } from './read.js';
9
+ import { preload, titler } from './read.js';
10
10
  /** Per-process cache of planner row estimates for identical list queries. */
11
11
  const estimates = new Map();
12
12
  const ESTIMATE_TTL_MS = 30_000;
13
13
  const ESTIMATE_CACHE_LIMIT = 500;
14
14
  const AGGREGATE_GROUP_LIMIT = 1000;
15
+ /**
16
+ * The default order's key: the creation time, newest first. Not a field, so a request cannot
17
+ * name it; a cursor carries it.
18
+ */
19
+ const NEWEST = '_created';
20
+ /** The column alias of the creation time's exact text in a list query. */
21
+ const NEWEST_VALUE = '_created_at';
15
22
  /**
16
23
  * Coerces a query-string or API filter/cursor value to the field's stored representation,
17
24
  * so a mismatch is rejected before PostgreSQL raises an invalid-input error.
@@ -254,14 +261,25 @@ function listQuery(ctx, name, actor, options) {
254
261
  authorizeAction(ctx, resource, actor, 'delete');
255
262
  const queryable = (key) => canQueryField(resource, actor, ability, key);
256
263
  const limit = Math.max(1, Math.min(100, Math.floor(Number(options.limit) || 25)));
257
- const sort = options.sort ?? 'id';
258
- const direction = options.direction === 'desc' ? 'desc' : 'asc';
259
- if (sort !== 'id' && !resource.fields[sort]?.sortable)
264
+ // The user's sort, else the resource's declared one, else newest first (owner, 2.3.0).
265
+ const chosen = options.sort ?? resource.defaultSort?.field;
266
+ const sort = chosen ?? NEWEST;
267
+ const direction = options.direction === 'desc' || options.direction === 'asc'
268
+ ? options.direction
269
+ : options.sort
270
+ ? 'asc'
271
+ : chosen
272
+ ? (resource.defaultSort?.direction ?? 'asc')
273
+ : 'desc';
274
+ if (sort !== 'id' && sort !== NEWEST && !resource.fields[sort]?.sortable)
275
+ throw new AdulaError(422, 'E_SORT', 'Unsupported sort field');
276
+ // The creation time orders the list only by default; it is not a field a request names.
277
+ if (options.sort === NEWEST)
260
278
  throw new AdulaError(422, 'E_SORT', 'Unsupported sort field');
261
279
  // Sorting/filtering private fields would otherwise reveal their values indirectly.
262
- if (sort !== 'id' && !queryable(sort))
280
+ if (sort !== 'id' && sort !== NEWEST && !queryable(sort))
263
281
  throw forbiddenField('Forbidden sort field');
264
- const sortColumn = `r.${resource.fields[sort]?.column ?? columnName(sort)}`;
282
+ const sortColumn = sort === NEWEST ? 'r.created_at' : `r.${resource.fields[sort]?.column ?? columnName(sort)}`;
265
283
  const base = ctx.db(`${name} as r`);
266
284
  if (trashed) {
267
285
  base.whereNotNull('r.deleted_at');
@@ -271,8 +289,19 @@ function listQuery(ctx, name, actor, options) {
271
289
  }
272
290
  else
273
291
  base.whereNull('r.deleted_at');
292
+ if (options.ids) {
293
+ const ids = options.ids.filter((id) => Number.isSafeInteger(id) && id > 0);
294
+ if (ids.length === 0)
295
+ base.whereRaw('false');
296
+ else
297
+ base.whereIn('r.id', ids);
298
+ }
274
299
  const query = accessibleBy(base, ability, actor, trashed ? 'delete' : 'view', resource);
275
- query.select(columns(resource, ability, false, [sort]));
300
+ query.select(columns(resource, ability, false, sort === NEWEST ? [] : [sort]));
301
+ // The creation time as PostgreSQL prints it, microseconds included: a page's cursor must
302
+ // compare exactly, which a JavaScript Date (milliseconds) would not.
303
+ if (sort === NEWEST)
304
+ query.select(ctx.db.raw('r.created_at::text as ??', [NEWEST_VALUE]));
276
305
  if (resource.scoped)
277
306
  query.select('ou.path as org_path');
278
307
  if (options.search)
@@ -303,11 +332,32 @@ export async function countUpTo(ctx, name, actor, options, max) {
303
332
  const [row] = await ctx.db.from(bounded.as('bounded')).count('* as count');
304
333
  return Number(row.count);
305
334
  }
335
+ /**
336
+ * Distinct tag names on records list() would return to the actor, for tag suggestions
337
+ * (RecordCollaboration.tagOptions): the same rules, organization scope and soft-delete
338
+ * filter apply, so a suggestion never names a tag found only on records the actor cannot see.
339
+ */
340
+ export async function tagNames(ctx, name, actor, limit) {
341
+ const { query } = listQuery(ctx, name, actor, {});
342
+ const ids = query.clearSelect().select('r.id');
343
+ const names = await ctx
344
+ .db('taggables as t')
345
+ .join('tags', 'tags.id', 't.tag_id')
346
+ .where('t.resource', name)
347
+ .whereIn('t.record_id', ids)
348
+ .distinct('tags.name')
349
+ .orderBy('tags.name')
350
+ .limit(limit)
351
+ .pluck('tags.name');
352
+ return names.map(String);
353
+ }
306
354
  export async function list(ctx, name, actor, options = {}) {
307
355
  const { resource, ability, trashed, limit, sort, direction, sortColumn, query } = listQuery(ctx, name, actor, options);
308
356
  // Estimate the authorized, filtered query, never the deployment-wide table cardinality.
309
357
  // Only the first page pays for the extra planner round trip; later pages keep its figure.
310
358
  let estimatedTotal;
359
+ // The authorized, filtered query before the cursor and the page limit narrow it.
360
+ const counted = query.clone();
311
361
  if (options.estimate !== false && !options.cursor) {
312
362
  estimatedTotal = await estimate(ctx.db, query);
313
363
  }
@@ -333,13 +383,23 @@ export async function list(ctx, name, actor, options = {}) {
333
383
  .map((row) => fromRow(row, resource));
334
384
  await withLinks(ctx.db, resource, records);
335
385
  const last = records.at(-1);
386
+ const lastRow = rows[Math.min(rows.length, limit) - 1];
336
387
  if (estimatedTotal !== undefined) {
337
388
  estimatedTotal =
338
- !options.cursor && rows.length <= limit ? rows.length : Math.max(estimatedTotal, rows.length);
389
+ !options.cursor && rows.length <= limit
390
+ ? rows.length
391
+ : estimatedTotal < EXACT_COUNT_LIMIT
392
+ ? await exactCount(ctx.db, counted, Math.max(estimatedTotal, rows.length))
393
+ : Math.max(estimatedTotal, rows.length);
339
394
  }
340
395
  const hydrated = await hydrate(ctx.db, resource, records, ctx.attachments);
396
+ const title = await titler(ctx, resource);
341
397
  return {
342
- data: hydrated.map((record) => serialize(resource, record, ability, actor)),
398
+ data: hydrated.map((record) => {
399
+ const row = serialize(resource, record, ability, actor);
400
+ // Like related rows, list rows carry the title formatted from the visible values (#110).
401
+ return { ...row, _title: title(row) };
402
+ }),
343
403
  permissions: Object.fromEntries(records.map((record) => [
344
404
  String(record.id),
345
405
  trashed
@@ -350,7 +410,12 @@ export async function list(ctx, name, actor, options = {}) {
350
410
  limit,
351
411
  estimatedTotal,
352
412
  nextCursor: rows.length > limit && last
353
- ? Buffer.from(JSON.stringify({ id: last.id, value: last[sort] ?? null, sort, direction })).toString('base64url')
413
+ ? Buffer.from(JSON.stringify({
414
+ id: last.id,
415
+ value: sort === NEWEST ? lastRow?.[NEWEST_VALUE] : (last[sort] ?? null),
416
+ sort,
417
+ direction,
418
+ })).toString('base64url')
354
419
  : null,
355
420
  },
356
421
  related: await preload(ctx, resource, records, actor),
@@ -364,6 +429,22 @@ function trashedPermissions(resource, record, actor, ability) {
364
429
  restore: canRecord(ability, actor, resource, 'delete', record),
365
430
  };
366
431
  }
432
+ /**
433
+ * Planner estimates are coarse for small tables and scoped filters (#111): below this figure the
434
+ * list counts exactly, so a figure under it is the real count of the authorized, filtered rows.
435
+ */
436
+ const EXACT_COUNT_LIMIT = 1000;
437
+ /** The exact row count up to EXACT_COUNT_LIMIT; above it, an estimate known to exceed the limit. */
438
+ async function exactCount(db, query, estimated) {
439
+ const bounded = query
440
+ .clearSelect()
441
+ .clearOrder()
442
+ .select('r.id')
443
+ .limit(EXACT_COUNT_LIMIT + 1);
444
+ const [row] = await db.from(bounded.as('bounded')).count('* as count');
445
+ const count = Number(row.count);
446
+ return count > EXACT_COUNT_LIMIT ? Math.max(estimated, EXACT_COUNT_LIMIT + 1) : count;
447
+ }
367
448
  /** The planner's row estimate of a list query, reused briefly for the identical query. */
368
449
  async function estimate(db, query) {
369
450
  const compiled = query.clone().clearSelect().select('r.id').toSQL();
@@ -404,7 +485,13 @@ function decodeCursor(resource, encoded, sort, direction) {
404
485
  throw invalidCursor();
405
486
  // The sort key must have the sort field's type, or PostgreSQL rejects the comparison.
406
487
  try {
407
- if (sort === 'id') {
488
+ if (sort === NEWEST) {
489
+ // PostgreSQL's own text form of a timestamp with time zone, as the list printed it.
490
+ if (typeof cursor.value !== 'string' ||
491
+ !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d{1,6})?[+-]\d{2}(:\d{2})?$/.test(cursor.value))
492
+ throw new Error('Cursor time mismatch');
493
+ }
494
+ else if (sort === 'id') {
408
495
  if (cursor.value !== cursor.id)
409
496
  throw new Error('Cursor id mismatch');
410
497
  }
@@ -52,6 +52,7 @@ export declare function activity(ctx: ResourceContext, name: string, id: number,
52
52
  fields: string[];
53
53
  actorId: number;
54
54
  actorName: string | null;
55
+ actorAvatarUrl: string | null;
55
56
  /**
56
57
  * @deprecated Always null. Kept so project-owned copies of resource-show from
57
58
  * earlier releases still compile; they fall back to the actor id.
@@ -72,6 +73,7 @@ export declare function details(ctx: ResourceContext, name: string, id: number,
72
73
  fields: string[];
73
74
  actorId: number;
74
75
  actorName: string | null;
76
+ actorAvatarUrl: string | null;
75
77
  /**
76
78
  * @deprecated Always null. Kept so project-owned copies of resource-show from
77
79
  * earlier releases still compile; they fall back to the actor id.
@@ -93,6 +95,7 @@ export declare function recordPage(ctx: ResourceContext, name: string, id: numbe
93
95
  fields: string[];
94
96
  actorId: number;
95
97
  actorName: string | null;
98
+ actorAvatarUrl: string | null;
96
99
  /**
97
100
  * @deprecated Always null. Kept so project-owned copies of resource-show from
98
101
  * earlier releases still compile; they fall back to the actor id.
@@ -4,8 +4,9 @@ import { buildAbility, canRecord } from '../../auth/ability.js';
4
4
  import { accessibleBy } from '../../auth/sql.js';
5
5
  import { fromRow, serialize } from '../contracts.js';
6
6
  import { AdulaError, notFound } from '../errors.js';
7
+ import { avatarUrlFor, avatarVersionColumn } from '../../core/user_avatars.js';
7
8
  import { formatTitle, titleFields } from '../record_title.js';
8
- import { authorizeAction, canQueryField, columns, fieldLevel, find, hydrate, permissions, requireRecord, } from './shared.js';
9
+ import { authorizeAction, canQueryField, columns, fieldLevel, find, hydrate, permissions, readableField, requireRecord, } from './shared.js';
9
10
  /** Project navigation is derived from registered resources and the current actor. */
10
11
  export function navigation(ctx, actor) {
11
12
  const { registry } = ctx;
@@ -18,7 +19,9 @@ export function navigation(ctx, actor) {
18
19
  .filter((resource) => !children.has(resource.name) &&
19
20
  resource.actions.includes('view') &&
20
21
  (!resource.scoped || actor.orgPaths.length > 0) &&
21
- ability.can('view', resource.name))
22
+ ability.can('view', resource.name) &&
23
+ // A role that may add records keeps the entry: creating and importing start there.
24
+ (ability.can('create', resource.name) || !referenceOnly(resource, actor)))
22
25
  .map((resource) => ({
23
26
  name: resource.name,
24
27
  label: resource.label.ar,
@@ -28,6 +31,23 @@ export function navigation(ctx, actor) {
28
31
  .ar ?? registry.owner(resource.name),
29
32
  }));
30
33
  }
34
+ /**
35
+ * Whether the actor reads the resource only to name its records: every rule that grants
36
+ * `view` on it is limited to its title fields (#141). Such a role reads the resource for
37
+ * titles, pickers and inherited scope checks, so navigation does not present it. A rule
38
+ * meant only for references must therefore name title fields (the resource's `title`).
39
+ */
40
+ function referenceOnly(resource, actor) {
41
+ const title = new Set(titleFields(resource));
42
+ const grants = actor.rules.filter((rule) => {
43
+ const actions = Array.isArray(rule.action) ? rule.action : [rule.action];
44
+ return (!rule.inverted &&
45
+ (rule.subject === resource.name || rule.subject === 'all') &&
46
+ (actions.includes('view') || actions.includes('manage')));
47
+ });
48
+ return (grants.length > 0 &&
49
+ grants.every((rule) => rule.fields?.length && rule.fields.every((key) => title.has(key))));
50
+ }
31
51
  export function describe(ctx, name, actor) {
32
52
  const resource = ctx.registry.get(name);
33
53
  const ability = authorizeAction(ctx, resource, actor, 'view');
@@ -111,12 +131,14 @@ export async function preload(ctx, resource, records, actor) {
111
131
  .filter((v) => v !== null && v !== undefined);
112
132
  // A display name only: readers of the record need not read account e-mails.
113
133
  if (ids.length) {
114
- const users = await db('users')
115
- .whereIn('id', [...new Set(ids)])
116
- .select('id', 'full_name');
134
+ const users = await db('users as u')
135
+ .whereIn('u.id', [...new Set(ids)])
136
+ .select('u.id', 'u.full_name', avatarVersionColumn(db, 'u.id'));
117
137
  related[key] = users.map((row) => ({
118
138
  id: Number(row.id),
119
139
  fullName: String(row.full_name ?? ''),
140
+ // The versioned picture, or null so the page shows initials and requests nothing.
141
+ avatarUrl: avatarUrlFor(row.id, row.avatar_version),
120
142
  }));
121
143
  }
122
144
  continue;
@@ -202,10 +224,19 @@ async function viewable(ctx, name, id, actor) {
202
224
  /** The serialized record with its permissions and related rows. */
203
225
  async function presented(ctx, resource, record, actor, ability) {
204
226
  const [hydrated] = await hydrate(ctx.db, resource, [record], ctx.attachments);
227
+ const related = await preload(ctx, resource, [record], actor);
228
+ // A reader of the record may read the name of its unit; clients show it instead of an id.
229
+ if (resource.scoped && record.orgUnitId !== null && record.orgUnitId !== undefined) {
230
+ const unit = await ctx.db('org_units').where('id', Number(record.orgUnitId)).first('id', 'name');
231
+ if (unit)
232
+ related.orgUnitId = [
233
+ { id: Number(unit.id), name: String(unit.name), _title: String(unit.name) },
234
+ ];
235
+ }
205
236
  return {
206
237
  data: serialize(resource, hydrated, ability, actor),
207
238
  permissions: permissions(resource, record, actor, ability),
208
- related: await preload(ctx, resource, [record], actor),
239
+ related,
209
240
  };
210
241
  }
211
242
  export async function show(ctx, name, id, actor) {
@@ -282,15 +313,15 @@ export async function lookups(ctx, name, actor) {
282
313
  }
283
314
  /** The last 50 recorded mutations of one record, after authorizing the record itself. */
284
315
  export async function activity(ctx, name, id, actor) {
285
- await viewable(ctx, name, id, actor);
286
- return activityOf(ctx, name, id);
316
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
317
+ return activityOf(ctx, resource, record, ability, actor);
287
318
  }
288
319
  /** Inline children and recent activity of one record from a single record read. */
289
320
  export async function details(ctx, name, id, actor) {
290
321
  const { resource, ability, record } = await viewable(ctx, name, id, actor);
291
322
  return {
292
323
  children: await childrenOf(ctx, resource, record, actor, ability),
293
- activity: await activityOf(ctx, name, id),
324
+ activity: await activityOf(ctx, resource, record, ability, actor),
294
325
  };
295
326
  }
296
327
  /** show(), children() and activity() of one record from a single record read. */
@@ -299,24 +330,54 @@ export async function recordPage(ctx, name, id, actor) {
299
330
  return {
300
331
  ...(await presented(ctx, resource, found, actor, ability)),
301
332
  children: await childrenOf(ctx, resource, found, actor, ability),
302
- activity: await activityOf(ctx, name, id),
333
+ activity: await activityOf(ctx, resource, found, ability, actor),
303
334
  };
304
335
  }
305
- async function activityOf(ctx, name, id) {
336
+ /**
337
+ * The record's recent activity. Each entry names only fields the viewer may read
338
+ * (readableField, as the field history); an update names the fields its field history
339
+ * recorded, plus the inline line groups it wrote, so entries stored with every submitted
340
+ * key are narrowed too.
341
+ */
342
+ async function activityOf(ctx, resource, record, ability, actor) {
306
343
  const rows = await ctx
307
344
  .db('activities as a')
308
345
  .leftJoin('users as u', 'u.id', 'a.actor_id')
309
- .where({ 'a.resource': name, 'a.record_id': id })
346
+ .where({ 'a.resource': resource.name, 'a.record_id': Number(record.id) })
310
347
  .orderBy('a.id', 'desc')
311
348
  .limit(50)
312
- .select('a.id', 'a.action', 'a.changes', 'a.actor_id', 'a.created_at', 'u.full_name as actor_name');
349
+ .select('a.id', 'a.action', 'a.changes', 'a.actor_id', 'a.created_at', 'u.full_name as actor_name', avatarVersionColumn(ctx.db, 'a.actor_id'));
350
+ const updates = rows.filter((row) => row.action === 'update').map((row) => Number(row.id));
351
+ const changed = new Map();
352
+ if (updates.length)
353
+ for (const change of await ctx
354
+ .db('field_changes')
355
+ .whereIn('activity_id', updates)
356
+ .orderBy('id')
357
+ .select('activity_id', 'field')) {
358
+ const keys = changed.get(Number(change.activity_id)) ?? [];
359
+ if (!keys.includes(String(change.field)))
360
+ keys.push(String(change.field));
361
+ changed.set(Number(change.activity_id), keys);
362
+ }
363
+ const named = (row) => {
364
+ const stored = Array.isArray(row.changes?.fields) ? row.changes.fields.map(String) : [];
365
+ if (row.action !== 'update')
366
+ return stored;
367
+ const keys = [...(changed.get(Number(row.id)) ?? [])];
368
+ for (const key of stored)
369
+ if (resource.fields[key]?.type === 'hasMany' && !keys.includes(key))
370
+ keys.push(key);
371
+ return keys;
372
+ };
313
373
  return rows.map((row) => ({
314
374
  id: Number(row.id),
315
375
  action: String(row.action),
316
- fields: Array.isArray(row.changes?.fields) ? row.changes.fields : [],
376
+ fields: named(row).filter((key) => readableField(resource, record, ability, actor, key)),
317
377
  actorId: Number(row.actor_id),
318
378
  // A display name only: record viewers need not be able to read account e-mails.
319
379
  actorName: row.actor_name ? String(row.actor_name) : null,
380
+ actorAvatarUrl: avatarUrlFor(row.actor_id, row.avatar_version),
320
381
  /**
321
382
  * @deprecated Always null. Kept so project-owned copies of resource-show from
322
383
  * earlier releases still compile; they fall back to the actor id.
@@ -18,6 +18,12 @@ export type ResourceContext = {
18
18
  * and at least 1 when the resource lists it as hidden.
19
19
  */
20
20
  export declare function fieldLevel(resource: Resource, key: string): number;
21
+ /**
22
+ * Whether a viewer may read a field of a record: exposed by the resource (serialize, or
23
+ * list and show), at the field's permission level, and allowed by the role rules on this
24
+ * record. The per-field change history and the activity entries apply this rule.
25
+ */
26
+ export declare function readableField(resource: Resource, record: RecordData, ability: AdulaAbility, actor: Actor, key: string): boolean;
21
27
  /**
22
28
  * Whether an actor may sort, filter or search by a field. Querying reveals values
23
29
  * indirectly, so it needs unconditional view access at the field's level.
@@ -43,6 +49,10 @@ export declare function find(db: Knex, resource: Resource, actor: Actor, ability
43
49
  * Adds the linked ids of every manyToMany field (ascending arrays) to records read
44
50
  * from the resource's table, so policies, serialization and audits see them like
45
51
  * column values. Mutates and returns the records.
52
+ *
53
+ * Only live targets are linked: a soft-deleted target's id is never shown, and because
54
+ * writes diff against these ids too, its join row survives an edit and the link returns
55
+ * when the target is restored.
46
56
  */
47
57
  export declare function withLinks(db: Knex, resource: Resource, records: RecordData[]): Promise<RecordData[]>;
48
58
  /**
@@ -54,6 +64,12 @@ export declare function collectionFilter(query: Knex.QueryBuilder, resource: Res
54
64
  export declare function findAny(db: Knex, resource: Resource, id: number, lock?: boolean): Promise<RecordData>;
55
65
  /** Scope (404) and conditional rules (403) of one loaded record. */
56
66
  export declare function requireRecord(ability: AdulaAbility, actor: Actor, resource: Resource, action: Action, record: RecordData): void;
67
+ /**
68
+ * A child that inherits its unit (`scope.from`, ADR 029) is written only by readers of its
69
+ * parent. The refusal names the missing rule, since the same role may read and delete
70
+ * the child (#140); a parent outside the actor's scope stays 404.
71
+ */
72
+ export declare function requireParentView(ability: AdulaAbility, actor: Actor, child: Resource, parent: Resource, record: RecordData): void;
57
73
  /** Which of the resource's actions the actor may take on one record now. */
58
74
  export declare function permissions(resource: Resource, record: RecordData, actor: Actor, ability: AdulaAbility): RecordPermissions;
59
75
  /** Coerces every present field value to its stored representation (422 E_FIELD_VALUE). */
@@ -1,8 +1,10 @@
1
+ import { subject } from '@casl/ability';
1
2
  import { columnName, joinTable } from '../../resource/define_resource.js';
2
3
  import { buildAbility, canRecord, inOrgScope, } from '../../auth/ability.js';
3
4
  import { conditionSql } from '../../auth/sql.js';
4
5
  import { fromRow, selectedFields } from '../contracts.js';
5
6
  import { AdulaError, forbiddenAction, notFound } from '../errors.js';
7
+ import { currentLanguage, labelText, translate } from '../../languages/catalog.js';
6
8
  import { fieldValue, isMultipleAttachment } from '../../resource/values.js';
7
9
  import { isAttachmentId, loadAttachments, } from '../../attachments/attachment_service.js';
8
10
  /**
@@ -12,6 +14,18 @@ import { isAttachmentId, loadAttachments, } from '../../attachments/attachment_s
12
14
  export function fieldLevel(resource, key) {
13
15
  return Math.max(resource.fields[key].permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0);
14
16
  }
17
+ /**
18
+ * Whether a viewer may read a field of a record: exposed by the resource (serialize, or
19
+ * list and show), at the field's permission level, and allowed by the role rules on this
20
+ * record. The per-field change history and the activity entries apply this rule.
21
+ */
22
+ export function readableField(resource, record, ability, actor, key) {
23
+ const serialized = resource.serialize ?? [...resource.list, ...resource.show];
24
+ return (key in resource.fields &&
25
+ serialized.includes(key) &&
26
+ actor.permissionLevel >= fieldLevel(resource, key) &&
27
+ ability.can('view', subject(resource.name, record), key));
28
+ }
15
29
  /**
16
30
  * Whether an actor may sort, filter or search by a field. Querying reveals values
17
31
  * indirectly, so it needs unconditional view access at the field's level.
@@ -69,6 +83,10 @@ export async function find(db, resource, actor, ability, id, lock = false) {
69
83
  * Adds the linked ids of every manyToMany field (ascending arrays) to records read
70
84
  * from the resource's table, so policies, serialization and audits see them like
71
85
  * column values. Mutates and returns the records.
86
+ *
87
+ * Only live targets are linked: a soft-deleted target's id is never shown, and because
88
+ * writes diff against these ids too, its join row survives an edit and the link returns
89
+ * when the target is restored.
72
90
  */
73
91
  export async function withLinks(db, resource, records) {
74
92
  if (!records.length)
@@ -78,9 +96,11 @@ export async function withLinks(db, resource, records) {
78
96
  continue;
79
97
  const join = joinTable(resource.name, key, field);
80
98
  const rows = await db(join.table)
81
- .whereIn(join.owner, records.map((record) => Number(record.id)))
82
- .orderBy(join.target)
83
- .select(`${join.owner} as owner`, `${join.target} as target`);
99
+ .join(`${field.resource} as t`, 't.id', `${join.table}.${join.target}`)
100
+ .whereNull('t.deleted_at')
101
+ .whereIn(`${join.table}.${join.owner}`, records.map((record) => Number(record.id)))
102
+ .orderBy(`${join.table}.${join.target}`)
103
+ .select(`${join.table}.${join.owner} as owner`, `${join.table}.${join.target} as target`);
84
104
  const links = new Map();
85
105
  for (const row of rows) {
86
106
  const list = links.get(Number(row.owner)) ?? [];
@@ -109,7 +129,12 @@ export function collectionFilter(query, resource, key, value) {
109
129
  if (field?.type === 'manyToMany') {
110
130
  const join = joinTable(resource.name, key, field);
111
131
  const links = (exists) => {
112
- exists.from(join.table).whereRaw('?? = r.id', [`${join.table}.${join.owner}`]);
132
+ // Links to soft-deleted targets are not shown (withLinks), so they never match.
133
+ exists
134
+ .from(join.table)
135
+ .join(`${field.resource} as t`, 't.id', `${join.table}.${join.target}`)
136
+ .whereNull('t.deleted_at')
137
+ .whereRaw('?? = r.id', [`${join.table}.${join.owner}`]);
113
138
  if (value !== null)
114
139
  exists.where(`${join.table}.${join.target}`, value);
115
140
  };
@@ -142,6 +167,24 @@ export function requireRecord(ability, actor, resource, action, record) {
142
167
  if (!canRecord(ability, actor, resource, action, record))
143
168
  throw forbiddenAction();
144
169
  }
170
+ /**
171
+ * A child that inherits its unit (`scope.from`, ADR 029) is written only by readers of its
172
+ * parent. The refusal names the missing rule, since the same role may read and delete
173
+ * the child (#140); a parent outside the actor's scope stays 404.
174
+ */
175
+ export function requireParentView(ability, actor, child, parent, record) {
176
+ try {
177
+ requireRecord(ability, actor, parent, 'view', record);
178
+ }
179
+ catch (error) {
180
+ if (!(error instanceof AdulaError) || error.status !== 403)
181
+ throw error;
182
+ throw new AdulaError(403, 'E_FORBIDDEN', translate('errors.parentView', currentLanguage(), {
183
+ child: labelText(child.label),
184
+ parent: labelText(parent.label),
185
+ }));
186
+ }
187
+ }
145
188
  /** Which of the resource's actions the actor may take on one record now. */
146
189
  export function permissions(resource, record, actor, ability) {
147
190
  return Object.fromEntries(resource.actions.map((action) => [
@@ -9,7 +9,7 @@ import { fromRow, serialize, systemInput, writableInput } from '../contracts.js'
9
9
  import { AdulaError, documentLocked, forbiddenField, inlineScope, invalidDocumentState, invalidInline, missingActor, notFound, requiredField, } from '../errors.js';
10
10
  import { sequence } from '../../services/settings.js';
11
11
  import { claimAttachment, rebindAttachment, isAttachmentId, releaseAttachment, } from '../../attachments/attachment_service.js';
12
- import { authorizeAction, eligibleUsers, fieldLevel, find, findAny, hydrateOne, normalizeValues, requireRecord, withLinks, } from './shared.js';
12
+ import { authorizeAction, eligibleUsers, fieldLevel, find, findAny, hydrateOne, normalizeValues, requireParentView, requireRecord, withLinks, } from './shared.js';
13
13
  import { audit, requireInlineParents, requireVersion, transition, } from './lifecycle.js';
14
14
  /** A normalized value as its column binding: JSON columns are bound as JSON text. */
15
15
  function storedValue(field, value) {
@@ -188,11 +188,18 @@ export async function persist(ctx, name, actor, input, id, transaction, parentWr
188
188
  throw requiredField(resource.scope.from);
189
189
  const parentResource = registry.get(field.resource);
190
190
  const parent = await load(trx, parentResource, parentId);
191
- check(parentResource, 'view', parent);
191
+ if (!system)
192
+ requireParentView(ability, actor, resource, parentResource, parent);
192
193
  candidate.orgUnitId = parent.orgUnitId;
193
194
  }
194
- else if (!system || 'orgUnitId' in input || id === undefined)
195
+ else if (!system || 'orgUnitId' in input || id === undefined) {
195
196
  candidate.orgUnitId = input.orgUnitId ?? existing.orgUnitId;
197
+ // A user write without a unit names the missing field (#130, #132); a unit that does
198
+ // not exist or lies outside the actor's scope stays 404 below. System writes keep
199
+ // their 422 E_ORG_UNIT.
200
+ if (!system && [undefined, null, ''].includes(candidate.orgUnitId))
201
+ throw new AdulaError(422, 'E_REQUIRED', `${translate('ui.form.orgUnit', currentLanguage())}: ${translate('validation.required', currentLanguage())}`);
202
+ }
196
203
  const unit = await trx('org_units')
197
204
  .where('id', Number(candidate.orgUnitId) || -1)
198
205
  .first('path');
@@ -262,7 +269,14 @@ export async function persist(ctx, name, actor, input, id, transaction, parentWr
262
269
  typeof candidate[key] === 'string' &&
263
270
  !candidate[key].trim())))
264
271
  throw requiredField(key);
265
- if (field.type === 'belongsTo' && candidate[key] !== null && candidate[key] !== undefined) {
272
+ // A link is checked when it is made or changed, like manyToMany links below (ADR 045):
273
+ // an unchanged value never blocks an edit after its target was deleted or moved out
274
+ // of the writer's scope (#130). The comparison runs after the hooks, so a link a hook
275
+ // changes is checked too.
276
+ if (field.type === 'belongsTo' &&
277
+ candidate[key] !== null &&
278
+ candidate[key] !== undefined &&
279
+ (id === undefined || Number(candidate[key]) !== Number(existing[key]))) {
266
280
  const related = registry.get(field.resource);
267
281
  const target = await load(trx, related, Number(candidate[key]));
268
282
  check(related, 'view', target);
@@ -402,7 +416,7 @@ export async function persist(ctx, name, actor, input, id, transaction, parentWr
402
416
  if (!next.includes(previous))
403
417
  await releaseAttachment(trx, previous);
404
418
  }
405
- await writeInlineRows(ctx, trx, resource, actor, form, id, row, candidate, action);
419
+ const inline = await writeInlineRows(ctx, trx, resource, actor, form, id, row, candidate, action);
406
420
  const changes = [];
407
421
  if (id !== undefined)
408
422
  for (const key of Object.keys(resource.fields)) {
@@ -413,8 +427,15 @@ export async function persist(ctx, name, actor, input, id, transaction, parentWr
413
427
  if (JSON.stringify(before) !== JSON.stringify(after))
414
428
  changes.push({ field: key, before, after });
415
429
  }
430
+ // An inline row tells its parent's write whether it changed anything.
431
+ if (parentWrite && (id === undefined || changes.length))
432
+ parentWrite.changed = true;
433
+ // A create names the submitted keys; an update names what changed (the field history
434
+ // holds the values) and the inline line groups whose rows were written, never every
435
+ // submitted key.
436
+ const fields = id === undefined ? Object.keys(form) : [...changes.map(({ field }) => field), ...inline];
416
437
  if (!system?.unattributed)
417
- await audit(ctx, trx, resource, actor, action, saved, Object.keys(form), changes, system);
438
+ await audit(ctx, trx, resource, actor, action, saved, fields, changes, system);
418
439
  await resource.hooks?.afterSave?.(saved, context);
419
440
  if (system)
420
441
  return (await hydrateOne(trx, resource, saved, ctx.attachments));
@@ -424,10 +445,12 @@ export async function persist(ctx, name, actor, input, id, transaction, parentWr
424
445
  }
425
446
  /**
426
447
  * Creates, updates and deletes the inline rows submitted with a parent write. Each row
427
- * is authorized and written through persist() (or transition() for deletions).
448
+ * is authorized and written through persist() (or transition() for deletions). Returns
449
+ * the hasMany keys whose rows were created, changed or deleted.
428
450
  */
429
451
  async function writeInlineRows(ctx, trx, resource, actor, form, id, row, candidate, action) {
430
452
  const name = resource.name;
453
+ const written = [];
431
454
  for (const [key, field] of Object.entries(resource.fields)) {
432
455
  if (field.type !== 'hasMany' || !(key in form))
433
456
  continue;
@@ -462,17 +485,23 @@ async function writeInlineRows(ctx, trx, resource, actor, form, id, row, candida
462
485
  if (childId === undefined)
463
486
  throw invalidInline('Deleting an inline row requires its identifier');
464
487
  await transition(ctx, field.resource, Number(childId), actor, 'delete', data.version, trx);
488
+ if (!written.includes(key))
489
+ written.push(key);
465
490
  continue;
466
491
  }
492
+ const parent = { name, id: Number(row.id), action };
467
493
  await persist(ctx, field.resource, actor, {
468
494
  ...data,
469
495
  [field.foreignKey]: row.id,
470
496
  ...(childResource.scoped && !childResource.scope
471
497
  ? { orgUnitId: candidate.orgUnitId }
472
498
  : {}),
473
- }, childId === undefined ? undefined : Number(childId), trx, { name, id: Number(row.id), action });
499
+ }, childId === undefined ? undefined : Number(childId), trx, parent);
500
+ if (parent.changed && !written.includes(key))
501
+ written.push(key);
474
502
  }
475
503
  }
504
+ return written;
476
505
  }
477
506
  /**
478
507
  * Amend-by-copy: a cancelled document is copied into a new draft that points to