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,11 +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';
6
+ import { escapeLike } from '../core/like.js';
7
+ import { canView, resourceLabel } from './shared.js';
8
+ import { avatarUrlFor, avatarVersionColumn } from '../core/user_avatars.js';
5
9
  const BODY_LIMIT = 5000;
6
10
  const MENTION_LIMIT = 20;
7
11
  const TAG_LIMIT = 20;
8
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 = 'عُدّل هذا التعليق؛ افتح السجل لقراءته.';
9
16
  /** Minimum permission level of a field for the current resource definition. */
10
17
  function fieldLevel(resource, key) {
11
18
  return Math.max(resource.fields[key]?.permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0);
@@ -39,7 +46,7 @@ export class RecordCollaboration {
39
46
  .whereNull('c.deleted_at')
40
47
  .orderBy('c.id', 'desc')
41
48
  .limit(51)
42
- .select('c.*', 'u.full_name as author_name');
49
+ .select('c.*', 'u.full_name as author_name', avatarVersionColumn(this.db, 'c.author_id'));
43
50
  const page = rows.slice(0, 50);
44
51
  const mentions = page.length
45
52
  ? await this.db('comment_mentions as m')
@@ -58,6 +65,7 @@ export class RecordCollaboration {
58
65
  body: String(row.body),
59
66
  authorId: Number(row.author_id),
60
67
  authorName: row.author_name ? String(row.author_name) : null,
68
+ authorAvatarUrl: avatarUrlFor(row.author_id, row.avatar_version),
61
69
  mentions: mentions
62
70
  .filter((mention) => Number(mention.comment_id) === Number(row.id))
63
71
  .map((mention) => ({ id: Number(mention.id), name: String(mention.full_name ?? '') })),
@@ -82,7 +90,7 @@ export class RecordCollaboration {
82
90
  .where({ 'f.resource': resource.name, 'f.record_id': id })
83
91
  .orderBy('f.id', 'desc')
84
92
  .limit(200)
85
- .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'));
86
94
  // Values are filtered per viewer: a private field's history is as private as the field.
87
95
  return rows
88
96
  .filter((row) => readableField(resource, record, ability, actor, String(row.field)))
@@ -92,7 +100,9 @@ export class RecordCollaboration {
92
100
  field: String(row.field),
93
101
  before: jsonValue(row.before),
94
102
  after: jsonValue(row.after),
103
+ actorId: row.actor_id === null ? null : Number(row.actor_id),
95
104
  actorName: row.actor_name ? String(row.actor_name) : null,
105
+ actorAvatarUrl: avatarUrlFor(row.actor_id, row.avatar_version),
96
106
  createdAt: new Date(row.created_at).toISOString(),
97
107
  }));
98
108
  }
@@ -112,31 +122,46 @@ export class RecordCollaboration {
112
122
  else
113
123
  throw new AdulaError(422, 'E_MENTION', 'لا يمكن الإشارة إلى مستخدم لا يملك صلاحية عرض السجل');
114
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));
115
137
  return this.db.transaction(async (trx) => {
116
138
  const [row] = await trx('comments')
117
139
  .insert({ resource: name, record_id: id, author_id: actor.id, body })
118
140
  .returning('*');
141
+ const commentId = Number(row.id);
119
142
  if (mentioned.length)
120
143
  await trx('comment_mentions').insert(mentioned.map((userId) => ({ comment_id: row.id, user_id: userId })));
121
144
  await trx('followers')
122
145
  .insert({ resource: name, record_id: id, user_id: actor.id })
123
146
  .onConflict(['resource', 'record_id', 'user_id'])
124
147
  .ignore();
125
- 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'));
126
151
  const authorName = author?.full_name ? String(author.full_name) : `مستخدم #${actor.id}`;
127
152
  const label = this.label(name);
153
+ const variables = { author: authorName, resource: label, id, excerpt: body.slice(0, 200) };
128
154
  for (const userId of mentioned)
129
- await notifyWithTemplate(trx, userId, 'comment.mentioned', { author: authorName, resource: label, id, excerpt: body.slice(0, 200) }, undefined, { resource: name, recordId: id });
130
- const followers = await trx('followers')
131
- .where({ resource: name, record_id: id })
132
- .whereNot('user_id', actor.id)
133
- .whereNotIn('user_id', mentioned.length ? mentioned : [0])
134
- .pluck('user_id');
135
- for (const userId of followers) {
136
- if (!(await this.canView(name, id, Number(userId))))
137
- continue;
138
- await notifyWithTemplate(trx, Number(userId), 'comment.created', { author: authorName, resource: label, id, excerpt: body.slice(0, 200) }, undefined, { resource: name, recordId: id });
139
- }
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 });
140
165
  const names = mentioned.length
141
166
  ? await trx('users').whereIn('id', mentioned).select('id', 'full_name')
142
167
  : [];
@@ -145,6 +170,7 @@ export class RecordCollaboration {
145
170
  body,
146
171
  authorId: actor.id,
147
172
  authorName: author?.full_name ? String(author.full_name) : null,
173
+ authorAvatarUrl: avatarUrlFor(actor.id, author?.avatar_version),
148
174
  mentions: names.map((user) => ({
149
175
  id: Number(user.id),
150
176
  name: String(user.full_name ?? ''),
@@ -162,22 +188,66 @@ export class RecordCollaboration {
162
188
  const text = typeof body === 'string' ? body.trim() : '';
163
189
  if (!text || text.length > BODY_LIMIT)
164
190
  throw new AdulaError(422, 'E_COMMENT_BODY', 'نص التعليق مطلوب ولا يتجاوز 5000 حرف');
165
- const updated = await this.db('comments')
166
- .where({ id: commentId, resource: name, record_id: id, author_id: actor.id })
167
- .whereNull('deleted_at')
168
- .update({ body: text, edited_at: this.db.fn.now() });
169
- if (!updated)
170
- 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
+ });
171
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
+ */
172
205
  async deleteComment(name, id, comment, actor) {
173
206
  await this.resources.access(name, id, actor);
174
207
  const commentId = this.commentId(comment);
175
- 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')
176
218
  .where({ id: commentId, resource: name, record_id: id, author_id: actor.id })
177
219
  .whereNull('deleted_at')
178
- .update({ deleted_at: this.db.fn.now() });
179
- if (!deleted)
220
+ .forUpdate()
221
+ .first('id');
222
+ if (!row)
180
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
+ }
181
251
  }
182
252
  async follow(name, id, actor, following) {
183
253
  await this.resources.access(name, id, actor);
@@ -204,8 +274,14 @@ export class RecordCollaboration {
204
274
  throw new AdulaError(422, 'E_TAGS', 'الوسم حروف وأرقام ومسافات فقط ولا يتجاوز 60 حرفاً');
205
275
  return value;
206
276
  })),
207
- ];
277
+ ].sort();
208
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
+ ]);
209
285
  if (names.length)
210
286
  await trx('tags')
211
287
  .insert(names.map((tag) => ({ name: tag })))
@@ -226,17 +302,13 @@ export class RecordCollaboration {
226
302
  .pluck('tags.name');
227
303
  return names.map(String);
228
304
  }
229
- /** 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
+ */
230
309
  async tagOptions(name, actor) {
231
310
  this.resources.describe(name, actor);
232
- const names = await this.db('taggables as t')
233
- .join('tags', 'tags.id', 't.tag_id')
234
- .where('t.resource', name)
235
- .distinct('tags.name')
236
- .orderBy('tags.name')
237
- .limit(200)
238
- .pluck('tags.name');
239
- return names.map(String);
311
+ return this.resources.tagNames(name, actor, 200);
240
312
  }
241
313
  /** Active users that may read the record, for the mention picker. */
242
314
  async mentionCandidates(name, id, actor, search = '') {
@@ -254,8 +326,12 @@ export class RecordCollaboration {
254
326
  .offset(offset)
255
327
  .limit(page)
256
328
  .select('id', 'full_name');
329
+ // Names match by substring; e-mail only by exact (case-insensitive) equality so
330
+ // the picker cannot be used to enumerate addresses prefix by prefix.
257
331
  if (term)
258
- query.where((where) => where.whereILike('full_name', `%${term}%`).orWhereILike('email', `${term}%`));
332
+ query.where((where) => where
333
+ .whereILike('full_name', `%${escapeLike(term)}%`)
334
+ .orWhereRaw('lower(email) = lower(?)', [term]));
259
335
  const users = await query;
260
336
  for (const user of users) {
261
337
  if (result.length >= 10)
@@ -274,8 +350,7 @@ export class RecordCollaboration {
274
350
  */
275
351
  followerListener(module, resource, event) {
276
352
  return {
277
- name: `adula.followers.${module}.${resource}.${event}`,
278
- event: `${module}.${resource}.${event}`,
353
+ ...followerKey(module, resource, event),
279
354
  handle: async (domainEvent, trx) => {
280
355
  const id = Number(domainEvent.payload.id);
281
356
  const actorId = Number(domainEvent.payload.actorId);
@@ -290,7 +365,8 @@ export class RecordCollaboration {
290
365
  deleted: 'تم حذف',
291
366
  };
292
367
  for (const userId of followers) {
293
- 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)))
294
370
  continue;
295
371
  await notifyWithTemplate(trx, Number(userId), 'record.changed', { change: verbs[event] ?? 'تحديث', resource: this.label(resource), id }, undefined,
296
372
  // A deleted record has no page to open.
@@ -300,18 +376,11 @@ export class RecordCollaboration {
300
376
  };
301
377
  }
302
378
  label(name) {
303
- try {
304
- return this.resources.label(name);
305
- }
306
- catch {
307
- return name;
308
- }
379
+ return resourceLabel(this.resources, name);
309
380
  }
310
- async canView(name, id, userId) {
311
- const disabled = await this.db('users').where('id', userId).first('disabled_at');
312
- if (!disabled || disabled.disabled_at)
313
- return false;
314
- return this.resources.permits(name, id, await this.actors.load(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);
315
384
  }
316
385
  /** Parsed after the record is authorized, so malformed ids never bypass the 403. */
317
386
  commentId(value) {
@@ -335,13 +404,19 @@ export class RecordCollaboration {
335
404
  ];
336
405
  }
337
406
  }
407
+ /** The listener name and domain event of a follower notification. */
408
+ function followerKey(module, resource, event) {
409
+ return {
410
+ name: `adula.followers.${module}.${resource}.${event}`,
411
+ event: `${module}.${resource}.${event}`,
412
+ };
413
+ }
338
414
  /** Follower notifications for every registered resource's update and document events. */
339
415
  export function followerListeners(registry, collaboration) {
340
416
  return registry.all().flatMap((resource) => ['updated', 'submitted', 'cancelled', 'deleted'].map((event) => {
341
417
  const module = registry.owner(resource.name);
342
418
  return {
343
- name: `adula.followers.${module}.${resource.name}.${event}`,
344
- event: `${module}.${resource.name}.${event}`,
419
+ ...followerKey(module, resource.name, event),
345
420
  handle: (domainEvent, trx) => collaboration().followerListener(module, resource.name, event).handle(domainEvent, trx),
346
421
  };
347
422
  }));
@@ -0,0 +1,24 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Actor } from '../auth/ability.js';
3
+ import type { ResourceService } from '../admin/resource_service.js';
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
+ */
10
+ export type ActorLoader = {
11
+ load(id: number): Promise<Actor>;
12
+ };
13
+ /**
14
+ * Whether a user may view a record: the account must exist and be active, and the
15
+ * record must pass the same ResourceService authorization that the user's own read
16
+ * would. Used before notifying, mentioning or assigning someone, so these features
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.
21
+ */
22
+ export declare function canView(db: Knex, resources: Pick<ResourceService, 'access'>, actors: ActorLoader, resource: string, id: number, userId: number): Promise<boolean>;
23
+ /** The resource's display label, or its name when the resource is no longer registered. */
24
+ export declare function resourceLabel(resources: Pick<ResourceService, 'label'>, name: string): string;
@@ -0,0 +1,34 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ /**
3
+ * Whether a user may view a record: the account must exist and be active, and the
4
+ * record must pass the same ResourceService authorization that the user's own read
5
+ * would. Used before notifying, mentioning or assigning someone, so these features
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.
10
+ */
11
+ export async function canView(db, resources, actors, resource, id, userId) {
12
+ const user = await db('users').where('id', userId).first('disabled_at');
13
+ if (!user || user.disabled_at)
14
+ return false;
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
+ }
25
+ }
26
+ /** The resource's display label, or its name when the resource is no longer registered. */
27
+ export function resourceLabel(resources, name) {
28
+ try {
29
+ return resources.label(name);
30
+ }
31
+ catch {
32
+ return String(name);
33
+ }
34
+ }
@@ -0,0 +1,72 @@
1
+ import type { Label } from '../resource/types.js';
2
+ /**
3
+ * Names an application (module) may not take: AdulaJS framework areas, URL segments of
4
+ * the generated application, and tables the core and the host application own. An
5
+ * application's example resource and table share its name, so a collision would shadow
6
+ * a framework table or route.
7
+ */
8
+ export declare const RESERVED_APP_NAMES: readonly string[];
9
+ /** Longest application name: its table, indexes and role keys must fit PostgreSQL limits. */
10
+ export declare const APP_NAME_MAX_LENGTH = 40;
11
+ export type AppOptions = {
12
+ name: string;
13
+ labelAr?: string;
14
+ labelEn?: string;
15
+ };
16
+ export type AppPlan = {
17
+ name: string;
18
+ label: Label;
19
+ /** New files relative to the application root, module definition included. */
20
+ files: Record<string, string>;
21
+ /** Empty module folders created next to the files. */
22
+ directories: string[];
23
+ /** start/modules.ts after registering the application. */
24
+ modules: {
25
+ path: string;
26
+ source: string;
27
+ };
28
+ };
29
+ /** Validates an application name: an SQL-safe slug that is neither reserved nor too long. */
30
+ export declare function appName(value: string): string;
31
+ /** leave_requests → Leave requests */
32
+ export declare function defaultEnglishLabel(name: string): string;
33
+ /** The default roles an application ships, in the shape module definitions declare. */
34
+ export declare function appDefaultRoles(name: string, labelAr: string): ({
35
+ key: string;
36
+ name: string;
37
+ permissionLevel: number;
38
+ rules: {
39
+ subject: string;
40
+ action: "update" | "view" | "create" | "delete";
41
+ }[];
42
+ } | {
43
+ key: string;
44
+ name: string;
45
+ rules: ({
46
+ subject: string;
47
+ action: string;
48
+ conditions?: undefined;
49
+ } | {
50
+ subject: string;
51
+ action: string;
52
+ conditions: {
53
+ createdBy: string;
54
+ };
55
+ })[];
56
+ permissionLevel?: undefined;
57
+ })[];
58
+ /** The module definition of a new application, in the project's Prettier layout. */
59
+ export declare function appModuleSource(name: string, label: Label): string;
60
+ /**
61
+ * A functional smoke test: an administrator opens the example resource list and the
62
+ * navigation carries the application's menu group.
63
+ */
64
+ export declare function appSmokeTestSource(name: string, label: Label): string;
65
+ /**
66
+ * Plans a new application (module) without writing: its module definition with bilingual
67
+ * labels and default roles, one example resource from the resource generator, the empty
68
+ * module folders, a smoke test and its registration in start/modules.ts.
69
+ */
70
+ export declare function planApp(root: string, options: AppOptions): Promise<AppPlan>;
71
+ /** Writes a plan; files are created exclusively, start/modules.ts is changed last. */
72
+ export declare function writeAppPlan(root: string, plan: AppPlan): Promise<void>;