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,7 +1,8 @@
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
- import type { ActorLoader } from './record_collaboration.js';
4
+ import { type ActorLoader } from './shared.js';
5
+ import { type SlaState } from '../workflows/sla.js';
5
6
  export type AssignmentStatus = 'open' | 'done' | 'cancelled';
6
7
  export type Assignment = {
7
8
  id: number;
@@ -12,8 +13,12 @@ export type Assignment = {
12
13
  recordTitle: string | null;
13
14
  assigneeId: number;
14
15
  assigneeName: string | null;
16
+ /** The assignee's versioned picture URL, or null without one (ADR 050). */
17
+ assigneeAvatarUrl?: string | null;
15
18
  assignedBy: number | null;
16
19
  assignedByName: string | null;
20
+ /** Who assigned it: their versioned picture URL, or null without one (ADR 050). */
21
+ assignedByAvatarUrl?: string | null;
17
22
  kind: string;
18
23
  title: string;
19
24
  note: string | null;
@@ -34,11 +39,29 @@ export type Assignment = {
34
39
  canCancel: boolean;
35
40
  /** An open approval step waiting for this user's decision (WorkflowEngine.decide). 1.2; optional for compatibility. */
36
41
  canDecide?: boolean;
42
+ /**
43
+ * The approver the viewer acts for through a delegation (ADR 044): the delegator of an
44
+ * approval routed to the viewer, or a delegator's own pending approval. Null otherwise.
45
+ */
46
+ onBehalfOf?: {
47
+ id: number;
48
+ name: string | null;
49
+ } | null;
50
+ /** The SLA deadline of an approval with one (ISO time); dueOn stays its calendar date. */
51
+ dueAt?: string | null;
52
+ /**
53
+ * The SLA state of an open item: an approval's SLA deadline (dueAt), or a manual task's
54
+ * due date (dueOn), overdue after its last day in the system time zone. Null otherwise.
55
+ */
56
+ sla?: SlaState | null;
37
57
  };
38
58
  export type AssignmentPage = {
39
59
  data: Assignment[];
40
60
  nextCursor: string | null;
41
- /** Open items of every kind. */
61
+ /**
62
+ * Open items of every kind the user may act on, on records they can still read: the
63
+ * number of items the open list shows (counted over the newest 1000 records).
64
+ */
42
65
  open: number;
43
66
  /** Open approval steps among them. 1.2; optional for compatibility. */
44
67
  approvals?: number;
@@ -51,6 +74,10 @@ export type AssignmentPage = {
51
74
  export type CloseNotePolicy = 'optional' | 'required';
52
75
  export type AssignmentOptions = {
53
76
  closeNote?: CloseNotePolicy;
77
+ /** Test hook: the clock for delegation dates and SLA states. */
78
+ now?: () => Date;
79
+ /** The system time zone whose calendar days delegation ranges use (default UTC). */
80
+ timeZone?: string;
54
81
  };
55
82
  /**
56
83
  * Assignments put a record on someone's "my tasks" list. Assigning needs update
@@ -58,6 +85,7 @@ export type AssignmentOptions = {
58
85
  * re-checks the record so lost access hides the task instead of leaking it.
59
86
  */
60
87
  export declare class Assignments {
88
+ #private;
61
89
  private db;
62
90
  private resources;
63
91
  private actors;
@@ -90,7 +118,23 @@ export declare class Assignments {
90
118
  * assignee cannot mark it done; module code closes it with close() (#51).
91
119
  */
92
120
  managed?: boolean;
121
+ /** Workflow approvals routed to a delegate keep the original approver (ADR 044). */
122
+ onBehalfOf?: number | null;
123
+ delegationId?: number | null;
124
+ /** SLA deadline and its due-soon reminder time; escalatedAt marks a reassignment. */
125
+ dueAt?: Date | null;
126
+ dueSoonAt?: Date | null;
127
+ escalatedAt?: Date | null;
93
128
  }): Promise<any>;
129
+ /**
130
+ * The numbers the open list shows: every item the user may act on today, own or held
131
+ * through a delegation (ADR 044), on records the user can still open. The «مهامي» badge
132
+ * reads this, so the badge and the list agree (#156).
133
+ */
134
+ openCounts(actor: Actor): Promise<{
135
+ open: number;
136
+ approvals: number;
137
+ }>;
94
138
  /** The signed-in user's own tasks, open first; records they can no longer read are hidden. */
95
139
  mine(actor: Actor, options?: {
96
140
  status?: string;
@@ -119,11 +163,24 @@ export declare class Assignments {
119
163
  reason?: string;
120
164
  trx?: Knex.Transaction;
121
165
  }): Promise<number>;
166
+ /**
167
+ * Closes one locked open assignment row for complete() (by hand) and close() (by
168
+ * module code, `system`): records the outcome, writes the record's activity entry
169
+ * when the task is managed or closed by the system, and notifies the other party —
170
+ * the assigner when done, the assignee when cancelled — unless that is the closer.
171
+ */
172
+ private finish;
122
173
  private query;
123
174
  private present;
124
175
  /** Adds record titles in one read per resource, under the viewer's field access. */
125
176
  private titled;
177
+ /** The delegations in force today that make the user act for someone else. */
178
+ private scope;
179
+ private now;
180
+ private today;
126
181
  private closeNote;
127
182
  private label;
183
+ /** permits() on a given connection: denial (403/404) is false, other errors propagate. */
184
+ private viewable;
128
185
  private canView;
129
186
  }
@@ -1,9 +1,17 @@
1
1
  import { AdulaError } from '../admin/errors.js';
2
2
  import { notifyWithTemplate } from '../core/message_templates.js';
3
+ import { canView, resourceLabel } from './shared.js';
4
+ import { actionableBy, delegationActive } from '../workflows/delegations.js';
5
+ import { assertTimeZone, calendarDate } from '../workflows/calendar.js';
6
+ import { slaState } from '../workflows/sla.js';
7
+ import { canonicalDate } from '../resource/values.js';
8
+ import { avatarUrlFor, avatarVersionColumn } from '../core/user_avatars.js';
9
+ const NO_DELEGATION = { delegations: new Set(), delegators: new Set() };
3
10
  const TITLE_LIMIT = 200;
4
11
  const NOTE_LIMIT = 2000;
5
12
  const REASON_LIMIT = 500;
6
- 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;
7
15
  function dateOnly(value) {
8
16
  if (value === null || value === undefined)
9
17
  return null;
@@ -26,6 +34,8 @@ export class Assignments {
26
34
  this.resources = resources;
27
35
  this.actors = actors;
28
36
  this.options = options;
37
+ if (options.timeZone)
38
+ assertTimeZone(options.timeZone);
29
39
  }
30
40
  async forRecord(name, id, actor) {
31
41
  await this.resources.access(name, id, actor);
@@ -33,7 +43,8 @@ export class Assignments {
33
43
  .where({ 'a.resource': name, 'a.record_id': id })
34
44
  .orderByRaw("(a.status = 'open') DESC, a.id DESC")
35
45
  .limit(100);
36
- return this.titled(rows.map((row) => this.present(row, actor)), actor);
46
+ const scope = await this.scope(actor.id);
47
+ return this.titled(rows.map((row) => this.present(row, actor, scope)), actor);
37
48
  }
38
49
  async assign(name, id, actor, input) {
39
50
  await this.resources.access(name, id, actor, 'update');
@@ -52,11 +63,10 @@ export class Assignments {
52
63
  throw new AdulaError(422, 'E_ASSIGNMENT_NOTE', 'الملاحظة لا تتجاوز 2000 حرف');
53
64
  const dueOn = input.dueOn === undefined || input.dueOn === null || input.dueOn === ''
54
65
  ? null
55
- : typeof input.dueOn === 'string' &&
56
- DATE.test(input.dueOn) &&
57
- !Number.isNaN(Date.parse(input.dueOn))
58
- ? input.dueOn
59
- : 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;
60
70
  if (dueOn === undefined)
61
71
  throw new AdulaError(422, 'E_ASSIGNMENT_DUE', 'تاريخ الاستحقاق غير صالح');
62
72
  if (!(await this.canView(name, id, assigneeId)))
@@ -90,6 +100,12 @@ export class Assignments {
90
100
  workflow_run_id: input.workflowRunId ?? null,
91
101
  workflow_step: input.workflowStep ?? null,
92
102
  managed: input.managed ?? false,
103
+ on_behalf_of: input.onBehalfOf ?? null,
104
+ delegation_id: input.delegationId ?? null,
105
+ due_at: input.dueAt ?? null,
106
+ due_soon_at: input.dueSoonAt ?? null,
107
+ escalated_at: input.escalatedAt ?? null,
108
+ reminded_at: input.escalatedAt ?? null,
93
109
  })
94
110
  .returning('id');
95
111
  await notifyWithTemplate(trx, input.assigneeId, input.kind === 'approval' ? 'assignment.approval' : 'assignment.created', {
@@ -102,13 +118,56 @@ export class Assignments {
102
118
  };
103
119
  return 'isTransaction' in db && db.isTransaction ? insert(db) : this.db.transaction(insert);
104
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
+ }
105
156
  /** The signed-in user's own tasks, open first; records they can no longer read are hidden. */
106
157
  async mine(actor, options = {}) {
107
158
  const status = options.status === 'done' || options.status === 'all' ? options.status : 'open';
108
159
  const limit = Math.max(1, Math.min(100, Math.floor(Number(options.limit) || 50)));
109
- const query = this.query().where('a.assignee_id', actor.id).orderBy('a.id', 'desc');
160
+ const today = this.today();
161
+ const query = this.query().orderBy('a.id', 'desc');
162
+ // Open items include approvals held through a delegation in force today (ADR 044);
163
+ // closed ones are the user's own, those decided for them and those they decided.
110
164
  if (status === 'open')
111
- query.where('a.status', 'open');
165
+ query.where('a.status', 'open').modify(actionableBy(this.db, actor.id, today));
166
+ else
167
+ query.where((own) => own
168
+ .where('a.assignee_id', actor.id)
169
+ .orWhere('a.on_behalf_of', actor.id)
170
+ .orWhere('a.completed_by', actor.id));
112
171
  if (status === 'done')
113
172
  query.whereNot('a.status', 'open');
114
173
  if (options.kind === 'approval')
@@ -121,7 +180,19 @@ export class Assignments {
121
180
  if (!Number.isSafeInteger(last) || last <= 0)
122
181
  throw new AdulaError(422, 'E_CURSOR', 'مؤشر الصفحة غير صالح');
123
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
+ };
124
194
  const data = [];
195
+ const scope = await this.scope(actor.id);
125
196
  let more = true;
126
197
  // Access is re-checked per record; scan bounded batches to fill the page.
127
198
  for (let round = 0; round < 10 && more && data.length < limit; round++) {
@@ -139,18 +210,16 @@ export class Assignments {
139
210
  break;
140
211
  }
141
212
  last = Number(row.id);
142
- if (await this.resources.permits(row.resource, Number(row.record_id), actor))
143
- data.push(this.present(row, actor));
213
+ if (await viewable(String(row.resource), Number(row.record_id)))
214
+ data.push(this.present(row, actor, scope));
144
215
  }
145
216
  }
146
- const [{ count, approvals }] = await this.db('assignments')
147
- .where({ assignee_id: actor.id, status: 'open' })
148
- .select(this.db.raw('count(*) as count'), this.db.raw('count(workflow_run_id) as approvals'));
217
+ const { open, approvals } = await this.#counts(actor, today, viewable);
149
218
  return {
150
219
  data: await this.titled(data, actor),
151
220
  nextCursor: more && last !== null ? String(last) : null,
152
- open: Number(count),
153
- approvals: Number(approvals),
221
+ open,
222
+ approvals,
154
223
  };
155
224
  }
156
225
  /**
@@ -171,7 +240,9 @@ export class Assignments {
171
240
  if (!row)
172
241
  throw new AdulaError(404, 'E_ASSIGNMENT_NOT_FOUND', 'المهمة غير موجودة');
173
242
  const involved = row.assignee_id === actor.id || row.assigned_by === actor.id;
174
- 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)))
175
246
  throw new AdulaError(404, 'E_ASSIGNMENT_NOT_FOUND', 'المهمة غير موجودة');
176
247
  if (row.workflow_run_id)
177
248
  throw new AdulaError(409, 'E_ASSIGNMENT_WORKFLOW', 'تُحسم خطوات الموافقة من صندوق الموافقات');
@@ -183,31 +254,8 @@ export class Assignments {
183
254
  throw new AdulaError(409, 'E_ASSIGNMENT_CLOSED', 'المهمة مغلقة بالفعل');
184
255
  if (!note && this.closeNote(row) === 'required')
185
256
  throw new AdulaError(422, 'E_ASSIGNMENT_NOTE', 'اكتب ملاحظة الإغلاق قبل إغلاق المهمة');
186
- await trx('assignments')
187
- .where('id', id)
188
- .update({
189
- status: outcome,
190
- completed_at: trx.fn.now(),
191
- completed_by: actor.id,
192
- close_reason: note || null,
193
- });
194
257
  // A managed task closed by hand leaves the note in the record's history.
195
- if (row.managed)
196
- await trx('activities').insert({
197
- resource: row.resource,
198
- record_id: row.record_id,
199
- actor_id: actor.id,
200
- action: 'assignment_closed',
201
- changes: JSON.stringify({
202
- fields: [],
203
- assignmentId: id,
204
- outcome,
205
- reason: note,
206
- }),
207
- });
208
- const notify = outcome === 'done' ? row.assigned_by : row.assignee_id;
209
- if (notify && notify !== actor.id)
210
- await notifyWithTemplate(trx, notify, outcome === 'done' ? 'assignment.done' : 'assignment.cancelled', { title: row.title, resource: this.label(row.resource), id: row.record_id }, undefined, { resource: String(row.resource), recordId: Number(row.record_id) });
258
+ await this.finish(trx, row, actor.id, outcome, note, false);
211
259
  });
212
260
  }
213
261
  /**
@@ -231,43 +279,79 @@ export class Assignments {
231
279
  .whereNull('workflow_run_id')
232
280
  .forUpdate()
233
281
  .orderBy('id');
234
- for (const row of rows) {
235
- await trx('assignments').where('id', row.id).update({
236
- status: outcome,
237
- completed_at: trx.fn.now(),
238
- completed_by: options.actorId,
239
- close_reason: reason,
240
- });
241
- await trx('activities').insert({
242
- resource,
243
- record_id: recordId,
244
- actor_id: options.actorId,
245
- action: 'assignment_closed',
246
- changes: JSON.stringify({
282
+ for (const row of rows)
283
+ await this.finish(trx, row, options.actorId, outcome, reason, true);
284
+ return rows.length;
285
+ };
286
+ return options.trx ? run(options.trx) : this.db.transaction(run);
287
+ }
288
+ /**
289
+ * Closes one locked open assignment row for complete() (by hand) and close() (by
290
+ * module code, `system`): records the outcome, writes the record's activity entry
291
+ * when the task is managed or closed by the system, and notifies the other party —
292
+ * the assigner when done, the assignee when cancelled — unless that is the closer.
293
+ */
294
+ async finish(trx, row, actorId, outcome, reason, system) {
295
+ await trx('assignments')
296
+ .where('id', row.id)
297
+ .update({
298
+ status: outcome,
299
+ completed_at: trx.fn.now(),
300
+ completed_by: actorId,
301
+ close_reason: reason || null,
302
+ });
303
+ if (system || row.managed)
304
+ await trx('activities').insert({
305
+ resource: row.resource,
306
+ record_id: row.record_id,
307
+ actor_id: actorId,
308
+ action: 'assignment_closed',
309
+ changes: JSON.stringify(system
310
+ ? {
247
311
  fields: [],
248
312
  system: true,
249
313
  assignmentId: Number(row.id),
250
314
  outcome,
251
315
  ...(reason ? { reason } : {}),
252
- }),
253
- });
254
- const notify = outcome === 'done' ? row.assigned_by : row.assignee_id;
255
- if (notify && notify !== options.actorId)
256
- await notifyWithTemplate(trx, notify, outcome === 'done' ? 'assignment.done' : 'assignment.cancelled', { title: row.title, resource: this.label(row.resource), id: row.record_id }, undefined, { resource: String(row.resource), recordId: Number(row.record_id) });
257
- }
258
- return rows.length;
259
- };
260
- return options.trx ? run(options.trx) : this.db.transaction(run);
316
+ }
317
+ : { fields: [], assignmentId: Number(row.id), outcome, reason: reason ?? '' }),
318
+ });
319
+ const notify = outcome === 'done' ? row.assigned_by : row.assignee_id;
320
+ if (notify && notify !== actorId)
321
+ await notifyWithTemplate(trx, notify, outcome === 'done' ? 'assignment.done' : 'assignment.cancelled', { title: row.title, resource: this.label(row.resource), id: row.record_id }, undefined, { resource: String(row.resource), recordId: Number(row.record_id) });
261
322
  }
262
323
  query(db = this.db) {
263
324
  return db('assignments as a')
264
325
  .leftJoin('users as u', 'u.id', 'a.assignee_id')
265
326
  .leftJoin('users as b', 'b.id', 'a.assigned_by')
266
327
  .leftJoin('workflow_runs as wr', 'wr.id', 'a.workflow_run_id')
267
- .select('a.*', 'u.full_name as assignee_name', 'b.full_name as assigned_by_name', 'wr.status as run_status', 'wr.current_step as run_step');
328
+ .leftJoin('users as ob', 'ob.id', 'a.on_behalf_of')
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()));
268
330
  }
269
- present(row, actor) {
331
+ present(row, actor, scope = NO_DELEGATION) {
270
332
  const open = row.status === 'open';
333
+ const assignee = Number(row.assignee_id);
334
+ // The same rules as actionableBy (ADR 044): a delegate never holds an approval of a
335
+ // run they started, and a row routed through an ended delegation follows its approver.
336
+ const routed = row.delegation_id !== null && row.delegation_id !== undefined;
337
+ const ownRun = row.run_started_by !== null && Number(row.run_started_by) === actor.id;
338
+ const own = assignee === actor.id &&
339
+ (!routed || (scope.delegations.has(Number(row.delegation_id)) && !ownRun));
340
+ const original = row.on_behalf_of !== null && Number(row.on_behalf_of) === actor.id;
341
+ const delegated = Boolean(row.workflow_run_id) &&
342
+ !ownRun &&
343
+ !original &&
344
+ (routed
345
+ ? !row.delegation_active && scope.delegators.has(Number(row.on_behalf_of))
346
+ : scope.delegators.has(assignee));
347
+ // Whose approval the viewer holds: the delegator of a routed one, or a delegator's own.
348
+ const behalf = own && row.on_behalf_of
349
+ ? { id: Number(row.on_behalf_of), name: row.on_behalf_of_name ?? null }
350
+ : delegated
351
+ ? routed
352
+ ? { id: Number(row.on_behalf_of), name: row.on_behalf_of_name ?? null }
353
+ : { id: assignee, name: row.assignee_name ? String(row.assignee_name) : null }
354
+ : null;
271
355
  return {
272
356
  id: Number(row.id),
273
357
  resource: String(row.resource),
@@ -276,8 +360,10 @@ export class Assignments {
276
360
  recordTitle: null,
277
361
  assigneeId: Number(row.assignee_id),
278
362
  assigneeName: row.assignee_name ? String(row.assignee_name) : null,
363
+ assigneeAvatarUrl: avatarUrlFor(row.assignee_id, row.assignee_avatar),
279
364
  assignedBy: row.assigned_by === null ? null : Number(row.assigned_by),
280
365
  assignedByName: row.assigned_by_name ? String(row.assigned_by_name) : null,
366
+ assignedByAvatarUrl: avatarUrlFor(row.assigned_by, row.assigned_by_avatar),
281
367
  kind: String(row.kind),
282
368
  title: String(row.title),
283
369
  note: row.note === null ? null : String(row.note),
@@ -297,7 +383,19 @@ export class Assignments {
297
383
  Boolean(row.workflow_run_id) &&
298
384
  row.run_status === 'waiting' &&
299
385
  row.run_step === row.workflow_step &&
300
- Number(row.assignee_id) === actor.id,
386
+ (own || original || delegated),
387
+ onBehalfOf: behalf,
388
+ dueAt: row.due_at ? new Date(row.due_at).toISOString() : 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,
301
399
  };
302
400
  }
303
401
  /** Adds record titles in one read per resource, under the viewer's field access. */
@@ -313,21 +411,45 @@ export class Assignments {
313
411
  }
314
412
  return list;
315
413
  }
414
+ /** The delegations in force today that make the user act for someone else. */
415
+ async scope(actorId) {
416
+ const today = this.today();
417
+ const rows = await this.db('workflow_delegations')
418
+ .where('delegate_id', actorId)
419
+ .whereNull('revoked_at')
420
+ .where('starts_on', '<=', today)
421
+ .where('ends_on', '>=', today)
422
+ .select('id', 'delegator_id');
423
+ return {
424
+ delegations: new Set(rows.map((row) => Number(row.id))),
425
+ delegators: new Set(rows.map((row) => Number(row.delegator_id))),
426
+ };
427
+ }
428
+ now() {
429
+ return this.options.now?.() ?? new Date();
430
+ }
431
+ today() {
432
+ return calendarDate(this.now(), this.options.timeZone);
433
+ }
316
434
  closeNote(row) {
317
435
  return row.managed || this.options.closeNote === 'required' ? 'required' : 'optional';
318
436
  }
319
437
  label(name) {
438
+ return resourceLabel(this.resources, name);
439
+ }
440
+ /** permits() on a given connection: denial (403/404) is false, other errors propagate. */
441
+ async viewable(row, actor, db) {
320
442
  try {
321
- return this.resources.label(name);
443
+ await this.resources.access(String(row.resource), Number(row.record_id), actor, 'view', db);
444
+ return true;
322
445
  }
323
- catch {
324
- return name;
446
+ catch (error) {
447
+ if (error instanceof AdulaError && (error.status === 403 || error.status === 404))
448
+ return false;
449
+ throw error;
325
450
  }
326
451
  }
327
- async canView(name, id, userId) {
328
- const user = await this.db('users').where('id', userId).first('disabled_at');
329
- if (!user || user.disabled_at)
330
- return false;
331
- return this.resources.permits(name, id, await this.actors.load(userId));
452
+ canView(name, id, userId) {
453
+ return canView(this.db, this.resources, this.actors, name, id, userId);
332
454
  }
333
455
  }
@@ -3,14 +3,15 @@ import type { Actor } from '../auth/ability.js';
3
3
  import type { ResourceService } from '../admin/resource_service.js';
4
4
  import type { JsonValue, Resource } from '../resource/types.js';
5
5
  import type { Listener } from '../events/outbox.js';
6
- export type ActorLoader = {
7
- load(id: number): Promise<Actor>;
8
- };
6
+ import { type ActorLoader } from './shared.js';
7
+ export type { ActorLoader } from './shared.js';
9
8
  export type CommentEntry = {
10
9
  id: number;
11
10
  body: string;
12
11
  authorId: number;
13
12
  authorName: string | null;
13
+ /** The author's versioned picture URL, or null without one (ADR 050). */
14
+ authorAvatarUrl?: string | null;
14
15
  mentions: {
15
16
  id: number;
16
17
  name: string;
@@ -24,7 +25,10 @@ export type FieldChangeEntry = {
24
25
  field: string;
25
26
  before: JsonValue;
26
27
  after: JsonValue;
28
+ actorId?: number | null;
27
29
  actorName: string | null;
30
+ /** The actor's versioned picture URL, or null without one (ADR 050). */
31
+ actorAvatarUrl?: string | null;
28
32
  createdAt: string;
29
33
  };
30
34
  export type RecordCollaborationState = {
@@ -59,12 +63,24 @@ export declare class RecordCollaboration {
59
63
  }): Promise<CommentEntry>;
60
64
  /** Authors edit or remove their own comments while they can still read the record. */
61
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
+ */
62
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;
63
76
  follow(name: string, id: number, actor: Actor, following: boolean): Promise<void>;
64
77
  /** Replaces the record's tags. Tagging changes how a record is found, so it needs update. */
65
78
  setTags(name: string, id: number, actor: Actor, input: unknown): Promise<string[]>;
66
79
  tags(name: string, id: number): Promise<string[]>;
67
- /** 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
+ */
68
84
  tagOptions(name: string, actor: Actor): Promise<string[]>;
69
85
  /** Active users that may read the record, for the mention picker. */
70
86
  mentionCandidates(name: string, id: number, actor: Actor, search?: string): Promise<MentionCandidate[]>;
@@ -74,6 +90,7 @@ export declare class RecordCollaboration {
74
90
  */
75
91
  followerListener(module: string, resource: string, event: string): Listener;
76
92
  private label;
93
+ /** Pass the caller's transaction as `db` when one is held, so no second connection is taken. */
77
94
  private canView;
78
95
  /** Parsed after the record is authorized, so malformed ids never bypass the 403. */
79
96
  private commentId;