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
@@ -4,11 +4,14 @@ import { canView, resourceLabel } from './shared.js';
4
4
  import { actionableBy, delegationActive } from '../workflows/delegations.js';
5
5
  import { assertTimeZone, calendarDate } from '../workflows/calendar.js';
6
6
  import { slaState } from '../workflows/sla.js';
7
+ import { canonicalDate } from '../resource/values.js';
8
+ import { avatarUrlFor, avatarVersionColumn } from '../core/user_avatars.js';
7
9
  const NO_DELEGATION = { delegations: new Set(), delegators: new Set() };
8
10
  const TITLE_LIMIT = 200;
9
11
  const NOTE_LIMIT = 2000;
10
12
  const REASON_LIMIT = 500;
11
- const DATE = /^\d{4}-\d{2}-\d{2}$/;
13
+ /** mine() counts open items over at most this many records, newest first: the list's scan bound. */
14
+ const COUNT_RECORDS = 1000;
12
15
  function dateOnly(value) {
13
16
  if (value === null || value === undefined)
14
17
  return null;
@@ -60,11 +63,10 @@ export class Assignments {
60
63
  throw new AdulaError(422, 'E_ASSIGNMENT_NOTE', 'الملاحظة لا تتجاوز 2000 حرف');
61
64
  const dueOn = input.dueOn === undefined || input.dueOn === null || input.dueOn === ''
62
65
  ? null
63
- : typeof input.dueOn === 'string' &&
64
- DATE.test(input.dueOn) &&
65
- !Number.isNaN(Date.parse(input.dueOn))
66
- ? input.dueOn
67
- : undefined;
66
+ : // A real calendar day: 2026-02-30 would roll over and fail the insert (#127).
67
+ typeof input.dueOn === 'string' && canonicalDate(input.dueOn, 'date')
68
+ ? input.dueOn
69
+ : undefined;
68
70
  if (dueOn === undefined)
69
71
  throw new AdulaError(422, 'E_ASSIGNMENT_DUE', 'تاريخ الاستحقاق غير صالح');
70
72
  if (!(await this.canView(name, id, assigneeId)))
@@ -116,15 +118,51 @@ export class Assignments {
116
118
  };
117
119
  return 'isTransaction' in db && db.isTransaction ? insert(db) : this.db.transaction(insert);
118
120
  }
121
+ /**
122
+ * The numbers the open list shows: every item the user may act on today, own or held
123
+ * through a delegation (ADR 044), on records the user can still open. The «مهامي» badge
124
+ * reads this, so the badge and the list agree (#156).
125
+ */
126
+ async openCounts(actor) {
127
+ const checked = new Map();
128
+ return this.#counts(actor, this.today(), (resource, recordId) => {
129
+ const key = `${resource} ${recordId}`;
130
+ let result = checked.get(key);
131
+ if (!result) {
132
+ result = this.resources.permits(resource, recordId, actor);
133
+ checked.set(key, result);
134
+ }
135
+ return result;
136
+ });
137
+ }
138
+ // Counted like the open list, after the same record check, over the newest records.
139
+ async #counts(actor, today, viewable) {
140
+ const groups = await this.db('assignments as a')
141
+ .where('a.status', 'open')
142
+ .modify(actionableBy(this.db, actor.id, today))
143
+ .groupBy('a.resource', 'a.record_id')
144
+ .orderByRaw('max(a.id) DESC')
145
+ .limit(COUNT_RECORDS)
146
+ .select('a.resource', 'a.record_id', this.db.raw('count(*)::integer AS open'), this.db.raw('count(a.workflow_run_id)::integer AS approvals'));
147
+ let open = 0;
148
+ let approvals = 0;
149
+ for (const group of groups)
150
+ if (await viewable(String(group.resource), Number(group.record_id))) {
151
+ open += Number(group.open);
152
+ approvals += Number(group.approvals);
153
+ }
154
+ return { open, approvals };
155
+ }
119
156
  /** The signed-in user's own tasks, open first; records they can no longer read are hidden. */
120
157
  async mine(actor, options = {}) {
121
158
  const status = options.status === 'done' || options.status === 'all' ? options.status : 'open';
122
159
  const limit = Math.max(1, Math.min(100, Math.floor(Number(options.limit) || 50)));
160
+ const today = this.today();
123
161
  const query = this.query().orderBy('a.id', 'desc');
124
162
  // Open items include approvals held through a delegation in force today (ADR 044);
125
163
  // closed ones are the user's own, those decided for them and those they decided.
126
164
  if (status === 'open')
127
- query.where('a.status', 'open').modify(actionableBy(this.db, actor.id, this.today()));
165
+ query.where('a.status', 'open').modify(actionableBy(this.db, actor.id, today));
128
166
  else
129
167
  query.where((own) => own
130
168
  .where('a.assignee_id', actor.id)
@@ -142,6 +180,17 @@ export class Assignments {
142
180
  if (!Number.isSafeInteger(last) || last <= 0)
143
181
  throw new AdulaError(422, 'E_CURSOR', 'مؤشر الصفحة غير صالح');
144
182
  }
183
+ // One record check per record, shared by the page and the counts.
184
+ const checked = new Map();
185
+ const viewable = (resource, recordId) => {
186
+ const key = `${resource}${recordId}`;
187
+ let result = checked.get(key);
188
+ if (!result) {
189
+ result = this.resources.permits(resource, recordId, actor);
190
+ checked.set(key, result);
191
+ }
192
+ return result;
193
+ };
145
194
  const data = [];
146
195
  const scope = await this.scope(actor.id);
147
196
  let more = true;
@@ -161,32 +210,16 @@ export class Assignments {
161
210
  break;
162
211
  }
163
212
  last = Number(row.id);
164
- if (await this.resources.permits(row.resource, Number(row.record_id), actor))
213
+ if (await viewable(String(row.resource), Number(row.record_id)))
165
214
  data.push(this.present(row, actor, scope));
166
215
  }
167
216
  }
168
- // The user's own open items are counted in SQL, as before. Items held only through
169
- // a delegation are counted after the same record check as the list (ADR 044), so the
170
- // badge never reveals approvals on records the delegate cannot open.
171
- const [{ count, approvals }] = await this.db('assignments')
172
- .where({ assignee_id: actor.id, status: 'open' })
173
- .whereNull('delegation_id')
174
- .select(this.db.raw('count(*) as count'), this.db.raw('count(workflow_run_id) as approvals'));
175
- let held = 0;
176
- const borrowed = await this.db('assignments as a')
177
- .where('a.status', 'open')
178
- .modify(actionableBy(this.db, actor.id, this.today()))
179
- .where((q) => q.whereNot('a.assignee_id', actor.id).orWhereNotNull('a.delegation_id'))
180
- .limit(200)
181
- .select('a.resource', 'a.record_id');
182
- for (const row of borrowed)
183
- if (await this.resources.permits(row.resource, Number(row.record_id), actor))
184
- held++;
217
+ const { open, approvals } = await this.#counts(actor, today, viewable);
185
218
  return {
186
219
  data: await this.titled(data, actor),
187
220
  nextCursor: more && last !== null ? String(last) : null,
188
- open: Number(count) + held,
189
- approvals: Number(approvals) + held,
221
+ open,
222
+ approvals,
190
223
  };
191
224
  }
192
225
  /**
@@ -207,7 +240,9 @@ export class Assignments {
207
240
  if (!row)
208
241
  throw new AdulaError(404, 'E_ASSIGNMENT_NOT_FOUND', 'المهمة غير موجودة');
209
242
  const involved = row.assignee_id === actor.id || row.assigned_by === actor.id;
210
- if (!involved || !(await this.resources.permits(row.resource, Number(row.record_id), actor)))
243
+ // The record check runs on this transaction: a second pool connection while the
244
+ // row is locked would let concurrent closes exhaust the pool.
245
+ if (!involved || !(await this.viewable(row, actor, trx)))
211
246
  throw new AdulaError(404, 'E_ASSIGNMENT_NOT_FOUND', 'المهمة غير موجودة');
212
247
  if (row.workflow_run_id)
213
248
  throw new AdulaError(409, 'E_ASSIGNMENT_WORKFLOW', 'تُحسم خطوات الموافقة من صندوق الموافقات');
@@ -291,7 +326,7 @@ export class Assignments {
291
326
  .leftJoin('users as b', 'b.id', 'a.assigned_by')
292
327
  .leftJoin('workflow_runs as wr', 'wr.id', 'a.workflow_run_id')
293
328
  .leftJoin('users as ob', 'ob.id', 'a.on_behalf_of')
294
- .select('a.*', 'u.full_name as assignee_name', 'b.full_name as assigned_by_name', 'ob.full_name as on_behalf_of_name', 'wr.status as run_status', 'wr.current_step as run_step', 'wr.started_by as run_started_by', delegationActive(db, this.today()));
329
+ .select('a.*', 'u.full_name as assignee_name', 'b.full_name as assigned_by_name', 'ob.full_name as on_behalf_of_name', avatarVersionColumn(db, 'a.assignee_id', 'assignee_avatar'), avatarVersionColumn(db, 'a.assigned_by', 'assigned_by_avatar'), 'wr.status as run_status', 'wr.current_step as run_step', 'wr.started_by as run_started_by', delegationActive(db, this.today()));
295
330
  }
296
331
  present(row, actor, scope = NO_DELEGATION) {
297
332
  const open = row.status === 'open';
@@ -325,8 +360,10 @@ export class Assignments {
325
360
  recordTitle: null,
326
361
  assigneeId: Number(row.assignee_id),
327
362
  assigneeName: row.assignee_name ? String(row.assignee_name) : null,
363
+ assigneeAvatarUrl: avatarUrlFor(row.assignee_id, row.assignee_avatar),
328
364
  assignedBy: row.assigned_by === null ? null : Number(row.assigned_by),
329
365
  assignedByName: row.assigned_by_name ? String(row.assigned_by_name) : null,
366
+ assignedByAvatarUrl: avatarUrlFor(row.assigned_by, row.assigned_by_avatar),
330
367
  kind: String(row.kind),
331
368
  title: String(row.title),
332
369
  note: row.note === null ? null : String(row.note),
@@ -349,9 +386,16 @@ export class Assignments {
349
386
  (own || original || delegated),
350
387
  onBehalfOf: behalf,
351
388
  dueAt: row.due_at ? new Date(row.due_at).toISOString() : null,
352
- sla: open && row.due_at
353
- ? slaState(new Date(row.due_at), row.due_soon_at ? new Date(row.due_soon_at) : null, this.now())
354
- : null,
389
+ sla: !open
390
+ ? null
391
+ : row.due_at
392
+ ? slaState(new Date(row.due_at), row.due_soon_at ? new Date(row.due_soon_at) : null, this.now())
393
+ : // A manual task is late after its due day ends in the system time zone (#128).
394
+ !row.workflow_run_id && row.due_on
395
+ ? dateOnly(row.due_on) < this.today()
396
+ ? 'overdue'
397
+ : 'on_time'
398
+ : null,
355
399
  };
356
400
  }
357
401
  /** Adds record titles in one read per resource, under the viewer's field access. */
@@ -393,6 +437,18 @@ export class Assignments {
393
437
  label(name) {
394
438
  return resourceLabel(this.resources, name);
395
439
  }
440
+ /** permits() on a given connection: denial (403/404) is false, other errors propagate. */
441
+ async viewable(row, actor, db) {
442
+ try {
443
+ await this.resources.access(String(row.resource), Number(row.record_id), actor, 'view', db);
444
+ return true;
445
+ }
446
+ catch (error) {
447
+ if (error instanceof AdulaError && (error.status === 403 || error.status === 404))
448
+ return false;
449
+ throw error;
450
+ }
451
+ }
396
452
  canView(name, id, userId) {
397
453
  return canView(this.db, this.resources, this.actors, name, id, userId);
398
454
  }
@@ -10,6 +10,8 @@ export type CommentEntry = {
10
10
  body: string;
11
11
  authorId: number;
12
12
  authorName: string | null;
13
+ /** The author's versioned picture URL, or null without one (ADR 050). */
14
+ authorAvatarUrl?: string | null;
13
15
  mentions: {
14
16
  id: number;
15
17
  name: string;
@@ -23,7 +25,10 @@ export type FieldChangeEntry = {
23
25
  field: string;
24
26
  before: JsonValue;
25
27
  after: JsonValue;
28
+ actorId?: number | null;
26
29
  actorName: string | null;
30
+ /** The actor's versioned picture URL, or null without one (ADR 050). */
31
+ actorAvatarUrl?: string | null;
27
32
  createdAt: string;
28
33
  };
29
34
  export type RecordCollaborationState = {
@@ -58,12 +63,24 @@ export declare class RecordCollaboration {
58
63
  }): Promise<CommentEntry>;
59
64
  /** Authors edit or remove their own comments while they can still read the record. */
60
65
  editComment(name: string, id: number, comment: unknown, actor: Actor, body: unknown): Promise<void>;
66
+ /**
67
+ * Deleting a comment also withdraws its text from the notifications that quoted it and
68
+ * stops their pending e-mail and channel deliveries. Messages already delivered by e-mail
69
+ * or another channel cannot be recalled.
70
+ */
61
71
  deleteComment(name: string, id: number, comment: unknown, actor: Actor): Promise<void>;
72
+ /** Locks the actor's own live comment and returns the notifications quoting it. */
73
+ private ownComment;
74
+ /** Re-renders comment notifications with a neutral excerpt in place of the comment text. */
75
+ private rewriteNotifications;
62
76
  follow(name: string, id: number, actor: Actor, following: boolean): Promise<void>;
63
77
  /** Replaces the record's tags. Tagging changes how a record is found, so it needs update. */
64
78
  setTags(name: string, id: number, actor: Actor, input: unknown): Promise<string[]>;
65
79
  tags(name: string, id: number): Promise<string[]>;
66
- /** Tag vocabulary used on records of a resource the actor may list. */
80
+ /**
81
+ * Tag vocabulary used on records of a resource that the actor may view: a tag found only
82
+ * on records outside the actor's scope or rules, or on deleted records, is not suggested.
83
+ */
67
84
  tagOptions(name: string, actor: Actor): Promise<string[]>;
68
85
  /** Active users that may read the record, for the mention picker. */
69
86
  mentionCandidates(name: string, id: number, actor: Actor, search?: string): Promise<MentionCandidate[]>;
@@ -73,6 +90,7 @@ export declare class RecordCollaboration {
73
90
  */
74
91
  followerListener(module: string, resource: string, event: string): Listener;
75
92
  private label;
93
+ /** Pass the caller's transaction as `db` when one is held, so no second connection is taken. */
76
94
  private canView;
77
95
  /** Parsed after the record is authorized, so malformed ids never bypass the 403. */
78
96
  private commentId;
@@ -1,13 +1,18 @@
1
1
  import { subject } from '@casl/ability';
2
2
  import { jsonValue } from '../admin/contracts.js';
3
3
  import { AdulaError } from '../admin/errors.js';
4
- import { notifyWithTemplate } from '../core/message_templates.js';
4
+ import { insertTemplatedNotification, MessageTemplates, notifyWithTemplate, } from '../core/message_templates.js';
5
+ import { commentNotifications, DELETED_COMMENT_BODY, DELETED_COMMENT_TITLE, withdrawNotificationDelivery, } from '../database/schema.js';
5
6
  import { escapeLike } from '../core/like.js';
6
7
  import { canView, resourceLabel } from './shared.js';
8
+ import { avatarUrlFor, avatarVersionColumn } from '../core/user_avatars.js';
7
9
  const BODY_LIMIT = 5000;
8
10
  const MENTION_LIMIT = 20;
9
11
  const TAG_LIMIT = 20;
10
12
  const TAG_PATTERN = /^[\p{L}\p{N}][\p{L}\p{N} _-]{0,59}$/u;
13
+ /** Neutral excerpts that replace a comment's text in its notifications. */
14
+ const DELETED_EXCERPT = DELETED_COMMENT_BODY;
15
+ const EDITED_EXCERPT = 'عُدّل هذا التعليق؛ افتح السجل لقراءته.';
11
16
  /** Minimum permission level of a field for the current resource definition. */
12
17
  function fieldLevel(resource, key) {
13
18
  return Math.max(resource.fields[key]?.permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0);
@@ -41,7 +46,7 @@ export class RecordCollaboration {
41
46
  .whereNull('c.deleted_at')
42
47
  .orderBy('c.id', 'desc')
43
48
  .limit(51)
44
- .select('c.*', 'u.full_name as author_name');
49
+ .select('c.*', 'u.full_name as author_name', avatarVersionColumn(this.db, 'c.author_id'));
45
50
  const page = rows.slice(0, 50);
46
51
  const mentions = page.length
47
52
  ? await this.db('comment_mentions as m')
@@ -60,6 +65,7 @@ export class RecordCollaboration {
60
65
  body: String(row.body),
61
66
  authorId: Number(row.author_id),
62
67
  authorName: row.author_name ? String(row.author_name) : null,
68
+ authorAvatarUrl: avatarUrlFor(row.author_id, row.avatar_version),
63
69
  mentions: mentions
64
70
  .filter((mention) => Number(mention.comment_id) === Number(row.id))
65
71
  .map((mention) => ({ id: Number(mention.id), name: String(mention.full_name ?? '') })),
@@ -84,7 +90,7 @@ export class RecordCollaboration {
84
90
  .where({ 'f.resource': resource.name, 'f.record_id': id })
85
91
  .orderBy('f.id', 'desc')
86
92
  .limit(200)
87
- .select('f.*', 'a.created_at', 'u.full_name as actor_name');
93
+ .select('f.*', 'a.created_at', 'a.actor_id', 'u.full_name as actor_name', avatarVersionColumn(this.db, 'a.actor_id'));
88
94
  // Values are filtered per viewer: a private field's history is as private as the field.
89
95
  return rows
90
96
  .filter((row) => readableField(resource, record, ability, actor, String(row.field)))
@@ -94,7 +100,9 @@ export class RecordCollaboration {
94
100
  field: String(row.field),
95
101
  before: jsonValue(row.before),
96
102
  after: jsonValue(row.after),
103
+ actorId: row.actor_id === null ? null : Number(row.actor_id),
97
104
  actorName: row.actor_name ? String(row.actor_name) : null,
105
+ actorAvatarUrl: avatarUrlFor(row.actor_id, row.avatar_version),
98
106
  createdAt: new Date(row.created_at).toISOString(),
99
107
  }));
100
108
  }
@@ -114,31 +122,46 @@ export class RecordCollaboration {
114
122
  else
115
123
  throw new AdulaError(422, 'E_MENTION', 'لا يمكن الإشارة إلى مستخدم لا يملك صلاحية عرض السجل');
116
124
  }
125
+ // Followers are checked before the transaction, as mentions are: a check made while the
126
+ // transaction holds a connection would wait for a second one, and enough simultaneous
127
+ // comments would exhaust the pool. The transaction keeps only those still following.
128
+ const readers = [];
129
+ const candidates = await this.db('followers')
130
+ .where({ resource: name, record_id: id })
131
+ .whereNot('user_id', actor.id)
132
+ .whereNotIn('user_id', mentioned.length ? mentioned : [0])
133
+ .pluck('user_id');
134
+ for (const userId of candidates)
135
+ if (await this.canView(name, id, Number(userId)))
136
+ readers.push(Number(userId));
117
137
  return this.db.transaction(async (trx) => {
118
138
  const [row] = await trx('comments')
119
139
  .insert({ resource: name, record_id: id, author_id: actor.id, body })
120
140
  .returning('*');
141
+ const commentId = Number(row.id);
121
142
  if (mentioned.length)
122
143
  await trx('comment_mentions').insert(mentioned.map((userId) => ({ comment_id: row.id, user_id: userId })));
123
144
  await trx('followers')
124
145
  .insert({ resource: name, record_id: id, user_id: actor.id })
125
146
  .onConflict(['resource', 'record_id', 'user_id'])
126
147
  .ignore();
127
- const author = await trx('users').where('id', actor.id).first('full_name');
148
+ const author = await trx('users as u')
149
+ .where('u.id', actor.id)
150
+ .first('u.full_name', avatarVersionColumn(trx, 'u.id'));
128
151
  const authorName = author?.full_name ? String(author.full_name) : `مستخدم #${actor.id}`;
129
152
  const label = this.label(name);
153
+ const variables = { author: authorName, resource: label, id, excerpt: body.slice(0, 200) };
130
154
  for (const userId of mentioned)
131
- await notifyWithTemplate(trx, userId, 'comment.mentioned', { author: authorName, resource: label, id, excerpt: body.slice(0, 200) }, undefined, { resource: name, recordId: id });
132
- const followers = await trx('followers')
133
- .where({ resource: name, record_id: id })
134
- .whereNot('user_id', actor.id)
135
- .whereNotIn('user_id', mentioned.length ? mentioned : [0])
136
- .pluck('user_id');
137
- for (const userId of followers) {
138
- if (!(await this.canView(name, id, Number(userId))))
139
- continue;
140
- await notifyWithTemplate(trx, Number(userId), 'comment.created', { author: authorName, resource: label, id, excerpt: body.slice(0, 200) }, undefined, { resource: name, recordId: id });
141
- }
155
+ await insertTemplatedNotification(trx, userId, 'comment.mentioned', variables, undefined, { resource: name, recordId: id }, { commentId });
156
+ const followers = readers.length
157
+ ? await trx('followers')
158
+ .where({ resource: name, record_id: id })
159
+ .whereIn('user_id', readers)
160
+ .orderBy('user_id')
161
+ .pluck('user_id')
162
+ : [];
163
+ for (const userId of followers)
164
+ await insertTemplatedNotification(trx, Number(userId), 'comment.created', variables, undefined, { resource: name, recordId: id }, { commentId });
142
165
  const names = mentioned.length
143
166
  ? await trx('users').whereIn('id', mentioned).select('id', 'full_name')
144
167
  : [];
@@ -147,6 +170,7 @@ export class RecordCollaboration {
147
170
  body,
148
171
  authorId: actor.id,
149
172
  authorName: author?.full_name ? String(author.full_name) : null,
173
+ authorAvatarUrl: avatarUrlFor(actor.id, author?.avatar_version),
150
174
  mentions: names.map((user) => ({
151
175
  id: Number(user.id),
152
176
  name: String(user.full_name ?? ''),
@@ -164,22 +188,66 @@ export class RecordCollaboration {
164
188
  const text = typeof body === 'string' ? body.trim() : '';
165
189
  if (!text || text.length > BODY_LIMIT)
166
190
  throw new AdulaError(422, 'E_COMMENT_BODY', 'نص التعليق مطلوب ولا يتجاوز 5000 حرف');
167
- const updated = await this.db('comments')
168
- .where({ id: commentId, resource: name, record_id: id, author_id: actor.id })
169
- .whereNull('deleted_at')
170
- .update({ body: text, edited_at: this.db.fn.now() });
171
- if (!updated)
172
- throw new AdulaError(404, 'E_COMMENT_NOT_FOUND', 'التعليق غير موجود');
191
+ await this.db.transaction(async (trx) => {
192
+ // Read before the body changes: notifications written before 2.3.0 match by text.
193
+ const notifications = await this.ownComment(trx, name, id, commentId, actor);
194
+ await trx('comments').where('id', commentId).update({ body: text, edited_at: trx.fn.now() });
195
+ // The earlier excerpt is replaced by a neutral note rather than the new text, which
196
+ // would reach recipients who may since have lost access to the record.
197
+ await this.rewriteNotifications(trx, name, id, actor, notifications, EDITED_EXCERPT);
198
+ });
173
199
  }
200
+ /**
201
+ * Deleting a comment also withdraws its text from the notifications that quoted it and
202
+ * stops their pending e-mail and channel deliveries. Messages already delivered by e-mail
203
+ * or another channel cannot be recalled.
204
+ */
174
205
  async deleteComment(name, id, comment, actor) {
175
206
  await this.resources.access(name, id, actor);
176
207
  const commentId = this.commentId(comment);
177
- const deleted = await this.db('comments')
208
+ await this.db.transaction(async (trx) => {
209
+ const notifications = await this.ownComment(trx, name, id, commentId, actor);
210
+ await trx('comments').where('id', commentId).update({ deleted_at: trx.fn.now() });
211
+ await this.rewriteNotifications(trx, name, id, actor, notifications, DELETED_EXCERPT);
212
+ await withdrawNotificationDelivery(trx, notifications.map((row) => row.id));
213
+ });
214
+ }
215
+ /** Locks the actor's own live comment and returns the notifications quoting it. */
216
+ async ownComment(trx, name, id, commentId, actor) {
217
+ const row = await trx('comments')
178
218
  .where({ id: commentId, resource: name, record_id: id, author_id: actor.id })
179
219
  .whereNull('deleted_at')
180
- .update({ deleted_at: this.db.fn.now() });
181
- if (!deleted)
220
+ .forUpdate()
221
+ .first('id');
222
+ if (!row)
182
223
  throw new AdulaError(404, 'E_COMMENT_NOT_FOUND', 'التعليق غير موجود');
224
+ return commentNotifications(trx, commentId);
225
+ }
226
+ /** Re-renders comment notifications with a neutral excerpt in place of the comment text. */
227
+ async rewriteNotifications(trx, name, id, actor, notifications, excerpt) {
228
+ if (!notifications.length)
229
+ return;
230
+ const author = await trx('users').where('id', actor.id).first('full_name');
231
+ const variables = {
232
+ author: author?.full_name ? String(author.full_name) : `مستخدم #${actor.id}`,
233
+ resource: this.label(name),
234
+ id,
235
+ excerpt,
236
+ };
237
+ const templates = new MessageTemplates(trx);
238
+ for (const key of new Set(notifications.map((row) => row.key))) {
239
+ let text = { title: DELETED_COMMENT_TITLE, body: excerpt };
240
+ try {
241
+ const message = await templates.render(key, variables, trx);
242
+ text = { title: message.subject, body: message.body };
243
+ }
244
+ catch {
245
+ // An unknown key keeps the constant neutral text.
246
+ }
247
+ await trx('notifications')
248
+ .whereIn('id', notifications.filter((row) => row.key === key).map((row) => row.id))
249
+ .update(text);
250
+ }
183
251
  }
184
252
  async follow(name, id, actor, following) {
185
253
  await this.resources.access(name, id, actor);
@@ -206,8 +274,14 @@ export class RecordCollaboration {
206
274
  throw new AdulaError(422, 'E_TAGS', 'الوسم حروف وأرقام ومسافات فقط ولا يتجاوز 60 حرفاً');
207
275
  return value;
208
276
  })),
209
- ];
277
+ ].sort();
210
278
  await this.db.transaction(async (trx) => {
279
+ // Saves of one record's tags run one at a time, so the last save wins instead of the
280
+ // second insert failing on rows the first one added. Names are inserted in sorted
281
+ // order, so saves on different records cannot deadlock on new tag names.
282
+ await trx.raw('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', [
283
+ `adula.tags:${name}:${id}`,
284
+ ]);
211
285
  if (names.length)
212
286
  await trx('tags')
213
287
  .insert(names.map((tag) => ({ name: tag })))
@@ -228,17 +302,13 @@ export class RecordCollaboration {
228
302
  .pluck('tags.name');
229
303
  return names.map(String);
230
304
  }
231
- /** Tag vocabulary used on records of a resource the actor may list. */
305
+ /**
306
+ * Tag vocabulary used on records of a resource that the actor may view: a tag found only
307
+ * on records outside the actor's scope or rules, or on deleted records, is not suggested.
308
+ */
232
309
  async tagOptions(name, actor) {
233
310
  this.resources.describe(name, actor);
234
- const names = await this.db('taggables as t')
235
- .join('tags', 'tags.id', 't.tag_id')
236
- .where('t.resource', name)
237
- .distinct('tags.name')
238
- .orderBy('tags.name')
239
- .limit(200)
240
- .pluck('tags.name');
241
- return names.map(String);
311
+ return this.resources.tagNames(name, actor, 200);
242
312
  }
243
313
  /** Active users that may read the record, for the mention picker. */
244
314
  async mentionCandidates(name, id, actor, search = '') {
@@ -295,7 +365,8 @@ export class RecordCollaboration {
295
365
  deleted: 'تم حذف',
296
366
  };
297
367
  for (const userId of followers) {
298
- if (event !== 'deleted' && !(await this.canView(resource, id, Number(userId))))
368
+ // Checked on the event's transaction: it already holds a connection.
369
+ if (event !== 'deleted' && !(await this.canView(resource, id, Number(userId), trx)))
299
370
  continue;
300
371
  await notifyWithTemplate(trx, Number(userId), 'record.changed', { change: verbs[event] ?? 'تحديث', resource: this.label(resource), id }, undefined,
301
372
  // A deleted record has no page to open.
@@ -307,8 +378,9 @@ export class RecordCollaboration {
307
378
  label(name) {
308
379
  return resourceLabel(this.resources, name);
309
380
  }
310
- canView(name, id, userId) {
311
- return canView(this.db, this.resources, this.actors, name, id, userId);
381
+ /** Pass the caller's transaction as `db` when one is held, so no second connection is taken. */
382
+ canView(name, id, userId, db = this.db) {
383
+ return canView(db, this.resources, this.actors, name, id, userId);
312
384
  }
313
385
  /** Parsed after the record is authorized, so malformed ids never bypass the 403. */
314
386
  commentId(value) {
@@ -1,7 +1,12 @@
1
1
  import type { Knex } from 'knex';
2
2
  import type { Actor } from '../auth/ability.js';
3
3
  import type { ResourceService } from '../admin/resource_service.js';
4
- /** Loads the full actor (roles, permission level) of a user by id. */
4
+ /**
5
+ * Loads the full actor (roles, permission level) of a user by id. A loader may accept
6
+ * an optional second argument, the caller's connection (ActorStore does): canView passes
7
+ * its transaction there, so a check made while a transaction is held needs no second
8
+ * pool connection. A loader that ignores it reads on its own connection.
9
+ */
5
10
  export type ActorLoader = {
6
11
  load(id: number): Promise<Actor>;
7
12
  };
@@ -10,7 +15,10 @@ export type ActorLoader = {
10
15
  * record must pass the same ResourceService authorization that the user's own read
11
16
  * would. Used before notifying, mentioning or assigning someone, so these features
12
17
  * never reveal a record to a user who cannot open it.
18
+ *
19
+ * Every query runs on `db`: a caller holding a transaction passes it, so the check
20
+ * never waits for another pool connection while that transaction holds one.
13
21
  */
14
- export declare function canView(db: Knex, resources: Pick<ResourceService, 'permits'>, actors: ActorLoader, resource: string, id: number, userId: number): Promise<boolean>;
22
+ export declare function canView(db: Knex, resources: Pick<ResourceService, 'access'>, actors: ActorLoader, resource: string, id: number, userId: number): Promise<boolean>;
15
23
  /** The resource's display label, or its name when the resource is no longer registered. */
16
24
  export declare function resourceLabel(resources: Pick<ResourceService, 'label'>, name: string): string;
@@ -1,14 +1,27 @@
1
+ import { AdulaError } from '../admin/errors.js';
1
2
  /**
2
3
  * Whether a user may view a record: the account must exist and be active, and the
3
4
  * record must pass the same ResourceService authorization that the user's own read
4
5
  * would. Used before notifying, mentioning or assigning someone, so these features
5
6
  * never reveal a record to a user who cannot open it.
7
+ *
8
+ * Every query runs on `db`: a caller holding a transaction passes it, so the check
9
+ * never waits for another pool connection while that transaction holds one.
6
10
  */
7
11
  export async function canView(db, resources, actors, resource, id, userId) {
8
12
  const user = await db('users').where('id', userId).first('disabled_at');
9
13
  if (!user || user.disabled_at)
10
14
  return false;
11
- return resources.permits(resource, Number(id), await actors.load(userId));
15
+ const actor = await actors.load(userId, db);
16
+ try {
17
+ await resources.access(resource, Number(id), actor, 'view', db);
18
+ return true;
19
+ }
20
+ catch (error) {
21
+ if (error instanceof AdulaError && [403, 404].includes(error.status))
22
+ return false;
23
+ throw error;
24
+ }
12
25
  }
13
26
  /** The resource's display label, or its name when the resource is no longer registered. */
14
27
  export function resourceLabel(resources, name) {
@@ -109,6 +109,7 @@ export const SERVICES = {
109
109
  'openApiDocument',
110
110
  'apiClientSource',
111
111
  'ImportBatches',
112
+ 'xlsxImportAdapter',
112
113
  'renderPrintHtml',
113
114
  'htmlToPdf',
114
115
  ],
@@ -146,7 +147,6 @@ export const OUTSIDE_ADULAJS = [
146
147
  'Runtime plugins',
147
148
  'A visual workflow editor',
148
149
  'Multi-tenant SaaS in one database (one deployment per organization)',
149
- 'XLSX import until a maintained parser passes the dependency rule (GAP-006)',
150
150
  ];
151
151
  /** The capability catalog read by idea-review: generated, never hand-edited. */
152
152
  export function capabilityCatalog(options = {}) {
@@ -1,6 +1,7 @@
1
1
  import type { Settings } from '../services/settings.js';
2
2
  import type { Knex } from 'knex';
3
3
  import type { Field, Resource } from '../resource/types.js';
4
+ import type { Rule } from '../auth/ability.js';
4
5
  import type { WorkflowDefinition } from '../workflows/define_workflow.js';
5
6
  import type { RuntimeHealth } from '../core/health.js';
6
7
  export type Finding = {
@@ -39,6 +40,15 @@ export declare function diagnoseWorkflowRoles(workflows: readonly Pick<WorkflowD
39
40
  key: string | null;
40
41
  name: string;
41
42
  })[]): Finding;
43
+ /**
44
+ * A child declared with `scope: { from }` takes its unit from its parent, so creating or
45
+ * updating it needs `view` on the parent (ADR 029). List roles that may write such a child
46
+ * but have no rule that lets them view the parent: every create and update refuses them (#140).
47
+ */
48
+ export declare function diagnoseScopeParentRoles(resources: readonly Pick<Resource, 'name' | 'fields' | 'scope'>[], roles: readonly {
49
+ name: string;
50
+ rules: readonly Pick<Rule, 'subject' | 'action' | 'inverted'>[];
51
+ }[]): Finding;
42
52
  /** Events wait in the outbox until a worker publishes them; a stale backlog means none runs (#50). */
43
53
  export declare function diagnoseOutbox(health: Pick<RuntimeHealth, 'outbox'> & {
44
54
  heartbeats: Pick<RuntimeHealth['heartbeats'], 'worker'>;