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
@@ -1,6 +1,7 @@
1
1
  import { AdulaError } from '../admin/errors.js';
2
2
  import { logActivity } from './activity.js';
3
3
  import { UI_PREFERENCES_KEY, validateUiPreferences } from './ui_preferences.js';
4
+ import { isPreferenceSetting } from './user_preferences.js';
4
5
  export const SETTING_SCOPES = ['system', 'org_unit', 'user'];
5
6
  // Written by install, scheduler, worker and backup verification; never by the settings screen.
6
7
  export const PROTECTED_SETTING_KEYS = [
@@ -14,14 +15,16 @@ export function isProtectedSetting(key) {
14
15
  return (PROTECTED_SETTING_KEYS.includes(key) ||
15
16
  key.startsWith('backup.') ||
16
17
  key.startsWith('setup.') ||
18
+ // Written by the appearance section (ADR 053), which validates colours and texts.
19
+ key.startsWith('appearance.') ||
17
20
  isSealedSetting(key));
18
21
  }
19
22
  /**
20
- * Settings that hold a sealed secret (`channels.*`, written by their own section). The
21
- * settings screen lists them read-only and never returns the sealed value.
23
+ * Settings that hold a sealed secret (`channels.*`, `ai.*`, `mail.smtp`, written by their own
24
+ * section). The settings screen lists them read-only and never returns the sealed value.
22
25
  */
23
26
  export function isSealedSetting(key) {
24
- return key.startsWith('channels.');
27
+ return key.startsWith('channels.') || key.startsWith('ai.') || key === 'mail.smtp';
25
28
  }
26
29
  function presentValue(key, value) {
27
30
  if (!isSealedSetting(key) || !value || typeof value !== 'object' || Array.isArray(value))
@@ -58,6 +61,9 @@ function toRow(row) {
58
61
  readOnly: isProtectedSetting(String(row.key)),
59
62
  };
60
63
  }
64
+ function reserved() {
65
+ throw new AdulaError(403, 'E_SETTING_RESERVED', 'هذا المفتاح تفضيل شخصي يضبطه المستخدم من حسابه');
66
+ }
61
67
  export class SettingsAdmin {
62
68
  db;
63
69
  constructor(db) {
@@ -67,11 +73,14 @@ export class SettingsAdmin {
67
73
  const rows = await this.db('settings')
68
74
  .where({ scope: settingScope(scope), scope_id: scopeId })
69
75
  .orderBy('key');
70
- return rows.map(toRow);
76
+ // A user's own interface preferences are private to that user (ADR 049).
77
+ return rows.filter((row) => !isPreferenceSetting(String(row.key))).map(toRow);
71
78
  }
72
79
  async upsert(actorId, input) {
73
80
  const key = settingKey(input.key);
74
81
  const scope = settingScope(input.scope);
82
+ if (isPreferenceSetting(key))
83
+ reserved();
75
84
  if (key === UI_PREFERENCES_KEY) {
76
85
  if (scope !== 'system')
77
86
  throw new AdulaError(422, 'E_SETTING_SCOPE', 'تفضيلات الواجهة تُضبط على مستوى النظام');
@@ -104,6 +113,8 @@ export class SettingsAdmin {
104
113
  const row = await trx('settings').where('id', id).first();
105
114
  if (!row)
106
115
  throw new AdulaError(404, 'E_SETTING_NOT_FOUND', 'الإعداد غير موجود');
116
+ if (isPreferenceSetting(row.key))
117
+ reserved();
107
118
  if (isProtectedSetting(row.key))
108
119
  throw new AdulaError(403, 'E_SETTING_READ_ONLY', 'هذا المفتاح تشغيلي للقراءة فقط');
109
120
  await trx('settings').where('id', id).delete();
@@ -3,12 +3,18 @@ export type CalendarSystem = 'gregory' | 'islamic-umalqura';
3
3
  export type CalendarPreference = CalendarSystem | 'both';
4
4
  /** Latin (0-9) or Arabic-Indic (٠-٩) digits in printed documents. */
5
5
  export type DigitsPreference = 'latn' | 'arab';
6
+ /** Where the workspace navigation sits: a side panel or a bar of tabs above the page. */
7
+ export type NavigationLayout = 'sidebar' | 'top';
6
8
  export type UiPreferences = {
7
9
  calendar: CalendarPreference;
8
10
  confirmDialogClose: boolean;
9
11
  pageTransitions: boolean;
10
12
  /** Optional for values stored before it existed; absent means 'latn'. */
11
13
  digits?: DigitsPreference;
14
+ /** The system's navigation layout; absent means 'sidebar'. */
15
+ layout?: NavigationLayout;
16
+ /** Lets each user choose their own layout from the account menu; absent means false. */
17
+ layoutUserChoice?: boolean;
12
18
  };
13
19
  export declare const UI_PREFERENCES_KEY = "ui.preferences";
14
20
  export declare const DEFAULT_UI_PREFERENCES: UiPreferences;
@@ -6,7 +6,14 @@ export const DEFAULT_UI_PREFERENCES = {
6
6
  confirmDialogClose: true,
7
7
  pageTransitions: true,
8
8
  };
9
- const PREFERENCE_KEYS = ['calendar', 'confirmDialogClose', 'pageTransitions', 'digits'];
9
+ const PREFERENCE_KEYS = [
10
+ 'calendar',
11
+ 'confirmDialogClose',
12
+ 'pageTransitions',
13
+ 'digits',
14
+ 'layout',
15
+ 'layoutUserChoice',
16
+ ];
10
17
  export function validateUiPreferences(value) {
11
18
  const input = value;
12
19
  if (!input ||
@@ -16,6 +23,8 @@ export function validateUiPreferences(value) {
16
23
  typeof input.confirmDialogClose !== 'boolean' ||
17
24
  typeof input.pageTransitions !== 'boolean' ||
18
25
  (input.digits !== undefined && !['latn', 'arab'].includes(input.digits)) ||
26
+ (input.layout !== undefined && !['sidebar', 'top'].includes(input.layout)) ||
27
+ (input.layoutUserChoice !== undefined && typeof input.layoutUserChoice !== 'boolean') ||
19
28
  Object.keys(input).some((key) => !PREFERENCE_KEYS.includes(key)))
20
29
  throw new AdulaError(422, 'E_UI_PREFERENCES', 'اختر تقويمًا صالحًا وحدد خيارات تأكيد الإغلاق والانتقالات');
21
30
  return {
@@ -23,6 +32,8 @@ export function validateUiPreferences(value) {
23
32
  confirmDialogClose: input.confirmDialogClose,
24
33
  pageTransitions: input.pageTransitions,
25
34
  ...(input.digits === undefined ? {} : { digits: input.digits }),
35
+ ...(input.layout === undefined ? {} : { layout: input.layout }),
36
+ ...(input.layoutUserChoice === undefined ? {} : { layoutUserChoice: input.layoutUserChoice }),
26
37
  };
27
38
  }
28
39
  export async function uiPreferences(db) {
@@ -0,0 +1,79 @@
1
+ import type { Knex } from 'knex';
2
+ import type { AvatarImage } from './avatar_image.js';
3
+ /**
4
+ * A profile picture is one `attachments` row bound to this owner (ADR 050). The name is not
5
+ * a registered resource, so `/attachments/:id` never serves it, pruning never removes it,
6
+ * and backups and `adula:storage:migrate` carry it like every other bound file.
7
+ */
8
+ export declare const AVATAR_OWNER: Readonly<{
9
+ resource: "core_users";
10
+ field: "avatar";
11
+ }>;
12
+ export type AvatarRecord = {
13
+ userId: number;
14
+ /** The attachment row id; it changes with every upload and is never reused. */
15
+ version: number;
16
+ disk: string;
17
+ path: string;
18
+ size: number;
19
+ mimeType: string;
20
+ width: number;
21
+ height: number;
22
+ };
23
+ /** A file the host deletes from its disk after the transaction committed. */
24
+ export type RemovedAvatarFile = {
25
+ disk: string;
26
+ path: string;
27
+ };
28
+ type Change = {
29
+ userId: number;
30
+ actorId: number;
31
+ impersonatorId?: number | null;
32
+ /** True on the administration page: the actor manages another user's picture. */
33
+ administered?: boolean;
34
+ };
35
+ /** The URL of a user's picture; with a version, the response may be cached for good. */
36
+ export declare function avatarUrl(userId: number, version?: number | null): string;
37
+ /**
38
+ * A select column with the current picture version of the user in `userColumn`, as `alias`.
39
+ * It belongs in the query that already resolves the person's name, so a list of people costs
40
+ * no query per row (the `attachments (resource, record_id, field)` index serves it).
41
+ */
42
+ export declare function avatarVersionColumn(db: Knex, userColumn: string, alias?: string): Knex.Raw<any>;
43
+ /**
44
+ * The versioned picture URL of a user, or null when they have none: the page then shows the
45
+ * initials and requests nothing, so a user without a picture costs no 404.
46
+ */
47
+ export declare function avatarUrlFor(userId: unknown, version: unknown): string | null;
48
+ /**
49
+ * Response headers of a profile picture: the stored, allow-listed type only, no sniffing and
50
+ * no script. A versioned URL never changes its bytes, so it is cached privately for a year;
51
+ * the plain URL is revalidated after five minutes with the version as its ETag.
52
+ */
53
+ export declare function avatarHeaders(avatar: AvatarRecord, options?: {
54
+ immutable?: boolean;
55
+ }): Record<string, string>;
56
+ export declare class UserAvatars {
57
+ #private;
58
+ private db;
59
+ constructor(db: Knex);
60
+ find(userId: number): Promise<AvatarRecord | null>;
61
+ /** The current picture version of each user that has one, in one query. */
62
+ versions(userIds: readonly number[]): Promise<Map<number, number>>;
63
+ /**
64
+ * Records a stored, sanitized picture as the user's avatar and retires the previous one in
65
+ * the same transaction. The host has already written `path` to `disk`; it deletes the
66
+ * returned files after the commit.
67
+ */
68
+ replace(change: Change & {
69
+ disk: string;
70
+ path: string;
71
+ image: AvatarImage;
72
+ }): Promise<{
73
+ avatar: AvatarRecord;
74
+ removed: RemovedAvatarFile[];
75
+ }>;
76
+ /** Removes the user's picture; nothing happens when there is none. */
77
+ remove(change: Change): Promise<RemovedAvatarFile[]>;
78
+ }
79
+ export {};
@@ -0,0 +1,186 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ import { logActivity } from './activity.js';
3
+ import { registerUpload, isAttachmentId } from '../attachments/attachment_service.js';
4
+ /**
5
+ * A profile picture is one `attachments` row bound to this owner (ADR 050). The name is not
6
+ * a registered resource, so `/attachments/:id` never serves it, pruning never removes it,
7
+ * and backups and `adula:storage:migrate` carry it like every other bound file.
8
+ */
9
+ export const AVATAR_OWNER = Object.freeze({ resource: 'core_users', field: 'avatar' });
10
+ /**
11
+ * What happens to the previous picture when a user replaces or removes it. 'delete' removes
12
+ * the row and the file (a personal photo does not outlive its removal); 'keep' soft-deletes
13
+ * the row and keeps the file, as field attachments do (ADR 047).
14
+ */
15
+ const REMOVED_PICTURES = 'delete';
16
+ /** The URL of a user's picture; with a version, the response may be cached for good. */
17
+ export function avatarUrl(userId, version) {
18
+ return version ? `/users/${userId}/avatar?v=${version}` : `/users/${userId}/avatar`;
19
+ }
20
+ /**
21
+ * A select column with the current picture version of the user in `userColumn`, as `alias`.
22
+ * It belongs in the query that already resolves the person's name, so a list of people costs
23
+ * no query per row (the `attachments (resource, record_id, field)` index serves it).
24
+ */
25
+ export function avatarVersionColumn(db, userColumn, alias = 'avatar_version') {
26
+ return db.raw(`(select max(av.id) from attachments av where av.resource = ? and av.field = ? and av.deleted_at is null and av.record_id = ??) as ??`, [AVATAR_OWNER.resource, AVATAR_OWNER.field, userColumn, alias]);
27
+ }
28
+ /**
29
+ * The versioned picture URL of a user, or null when they have none: the page then shows the
30
+ * initials and requests nothing, so a user without a picture costs no 404.
31
+ */
32
+ export function avatarUrlFor(userId, version) {
33
+ const id = Number(userId);
34
+ const current = Number(version);
35
+ return Number.isSafeInteger(id) && id > 0 && Number.isSafeInteger(current) && current > 0
36
+ ? avatarUrl(id, current)
37
+ : null;
38
+ }
39
+ /**
40
+ * Response headers of a profile picture: the stored, allow-listed type only, no sniffing and
41
+ * no script. A versioned URL never changes its bytes, so it is cached privately for a year;
42
+ * the plain URL is revalidated after five minutes with the version as its ETag.
43
+ */
44
+ export function avatarHeaders(avatar, options = {}) {
45
+ return {
46
+ 'Content-Type': avatar.mimeType === 'image/webp' ? 'image/webp' : 'image/png',
47
+ 'Content-Length': String(avatar.size),
48
+ 'Content-Disposition': 'inline',
49
+ 'X-Content-Type-Options': 'nosniff',
50
+ 'Content-Security-Policy': "default-src 'none'; sandbox",
51
+ 'Cross-Origin-Resource-Policy': 'same-origin',
52
+ 'ETag': `"avatar-${avatar.version}"`,
53
+ 'Cache-Control': options.immutable
54
+ ? 'private, max-age=31536000, immutable'
55
+ : 'private, max-age=300',
56
+ };
57
+ }
58
+ const live = (db) => db('attachments')
59
+ .where('resource', AVATAR_OWNER.resource)
60
+ .where('field', AVATAR_OWNER.field)
61
+ .whereNull('deleted_at');
62
+ function fromRow(row) {
63
+ const data = (row.data ?? {});
64
+ return {
65
+ userId: Number(row.record_id),
66
+ version: Number(row.id),
67
+ disk: String(row.disk),
68
+ path: String(row.path),
69
+ size: Number(row.size),
70
+ mimeType: String(row.mime_type),
71
+ width: Number(data.width ?? 0),
72
+ height: Number(data.height ?? 0),
73
+ };
74
+ }
75
+ export class UserAvatars {
76
+ db;
77
+ constructor(db) {
78
+ this.db = db;
79
+ }
80
+ async find(userId) {
81
+ if (!isAttachmentId(userId))
82
+ return null;
83
+ const row = await live(this.db).where('record_id', userId).orderBy('id', 'desc').first();
84
+ return row ? fromRow(row) : null;
85
+ }
86
+ /** The current picture version of each user that has one, in one query. */
87
+ async versions(userIds) {
88
+ const ids = [...new Set(userIds.filter(isAttachmentId))];
89
+ const versions = new Map();
90
+ if (!ids.length)
91
+ return versions;
92
+ const rows = await live(this.db)
93
+ .whereIn('record_id', ids)
94
+ .groupBy('record_id')
95
+ .select('record_id')
96
+ .max('id as max');
97
+ for (const row of rows)
98
+ versions.set(Number(row.record_id), Number(row.max));
99
+ return versions;
100
+ }
101
+ /**
102
+ * Records a stored, sanitized picture as the user's avatar and retires the previous one in
103
+ * the same transaction. The host has already written `path` to `disk`; it deletes the
104
+ * returned files after the commit.
105
+ */
106
+ async replace(change) {
107
+ return this.db.transaction(async (trx) => {
108
+ await this.#lock(trx, change);
109
+ const row = await registerUpload(trx, {
110
+ disk: change.disk,
111
+ path: change.path,
112
+ name: change.path.split('/').at(-1) ?? '',
113
+ originalName: `avatar.${change.image.extname}`,
114
+ size: change.image.bytes.length,
115
+ mimeType: change.image.mimeType,
116
+ extname: change.image.extname,
117
+ data: { width: change.image.width, height: change.image.height },
118
+ uploadedBy: change.actorId,
119
+ impersonatorId: change.impersonatorId,
120
+ resource: AVATAR_OWNER.resource,
121
+ field: AVATAR_OWNER.field,
122
+ });
123
+ const [bound] = await trx('attachments')
124
+ .where('id', row.id)
125
+ .update({ record_id: change.userId })
126
+ .returning('*');
127
+ const { removed } = await this.#retire(trx, change.userId, row.id);
128
+ await this.#log(trx, change, 'avatar_updated', {
129
+ version: row.id,
130
+ width: change.image.width,
131
+ height: change.image.height,
132
+ });
133
+ return { avatar: fromRow(bound), removed };
134
+ });
135
+ }
136
+ /** Removes the user's picture; nothing happens when there is none. */
137
+ async remove(change) {
138
+ return this.db.transaction(async (trx) => {
139
+ await this.#lock(trx, change);
140
+ const { count, removed } = await this.#retire(trx, change.userId);
141
+ if (count)
142
+ await this.#log(trx, change, 'avatar_removed', {});
143
+ return removed;
144
+ });
145
+ }
146
+ /** One change per user at a time; the row lock also proves the user exists. */
147
+ async #lock(trx, change) {
148
+ if (!isAttachmentId(change.userId) || !isAttachmentId(change.actorId))
149
+ throw new AdulaError(404, 'E_USER_NOT_FOUND', 'المستخدم غير موجود');
150
+ if (!change.administered && change.actorId !== change.userId)
151
+ throw new AdulaError(403, 'E_FORBIDDEN', 'ليس لديك صلاحية لهذا الإجراء');
152
+ const user = await trx('users').where('id', change.userId).forUpdate().first('id');
153
+ if (!user)
154
+ throw new AdulaError(404, 'E_USER_NOT_FOUND', 'المستخدم غير موجود');
155
+ }
156
+ async #retire(trx, userId, exceptId) {
157
+ const previous = live(trx).where('record_id', userId);
158
+ if (exceptId)
159
+ previous.whereNot('id', exceptId);
160
+ const rows = await previous.select('id', 'disk', 'path');
161
+ const count = rows.length;
162
+ if (!count)
163
+ return { count, removed: [] };
164
+ const ids = rows.map((row) => Number(row.id));
165
+ if (REMOVED_PICTURES === 'keep') {
166
+ await trx('attachments').whereIn('id', ids).update({ deleted_at: trx.fn.now() });
167
+ return { count, removed: [] };
168
+ }
169
+ await trx('attachments').whereIn('id', ids).delete();
170
+ return {
171
+ count,
172
+ removed: rows.map((row) => ({ disk: String(row.disk), path: String(row.path) })),
173
+ };
174
+ }
175
+ #log(trx, change, action, changes) {
176
+ return logActivity(trx, {
177
+ // The user's own changes sit with their account activity, like profile_updated.
178
+ resource: change.administered ? 'core.users' : 'users',
179
+ recordId: change.userId,
180
+ actorId: change.actorId,
181
+ impersonatorId: change.impersonatorId,
182
+ action,
183
+ changes,
184
+ });
185
+ }
186
+ }
@@ -0,0 +1,36 @@
1
+ import type { Knex } from 'knex';
2
+ import type { JsonValue } from '../resource/types.js';
3
+ /**
4
+ * One per-user interface preference (ADR 049): the sidebar state, the navigation layout, the
5
+ * theme, an arrangement. The application declares its keys once; each key validates its own
6
+ * value, so a stored value is always one the interface understands.
7
+ */
8
+ export type PreferenceDefinition<T extends JsonValue = JsonValue> = {
9
+ /** Lower camel segments joined by dots: `shell.sidebar`, `overview.layout`. */
10
+ key: string;
11
+ default: T;
12
+ /** Returns the normalized value, or throws `AdulaError(422, 'E_PREFERENCE_VALUE', …)`. */
13
+ validate: (value: unknown) => T;
14
+ };
15
+ /** Preferences live in `settings` with scope `user`; this prefix keeps them apart. */
16
+ export declare const PREFERENCE_PREFIX = "preference.";
17
+ /** Upper bound for one stored value, in UTF-8 bytes. */
18
+ export declare const PREFERENCE_MAX_BYTES = 4096;
19
+ export declare function definePreference<T extends JsonValue>(definition: PreferenceDefinition<T>): PreferenceDefinition<T>;
20
+ /** True for a settings key that stores a user's own preference. */
21
+ export declare function isPreferenceSetting(key: string): boolean;
22
+ export declare class UserPreferences {
23
+ #private;
24
+ private db;
25
+ private report;
26
+ constructor(db: Knex, definitions: PreferenceDefinition[], report?: (key: string, error: unknown) => void);
27
+ /** Boot check: keys are well formed and unique, and every default passes its validator. */
28
+ static validate(definitions: PreferenceDefinition[]): void;
29
+ keys(): string[];
30
+ /** Every registered preference of the user, defaults filled in. */
31
+ all(userId: number): Promise<Record<string, JsonValue>>;
32
+ get<T extends JsonValue = JsonValue>(userId: number, key: string): Promise<T>;
33
+ set<T extends JsonValue = JsonValue>(userId: number, key: string, value: unknown): Promise<T>;
34
+ /** Removes the stored value; the user sees the default again. */
35
+ reset<T extends JsonValue = JsonValue>(userId: number, key: string): Promise<T>;
36
+ }
@@ -0,0 +1,125 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ /** Preferences live in `settings` with scope `user`; this prefix keeps them apart. */
3
+ export const PREFERENCE_PREFIX = 'preference.';
4
+ /** Upper bound for one stored value, in UTF-8 bytes. */
5
+ export const PREFERENCE_MAX_BYTES = 4096;
6
+ const KEY = /^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/;
7
+ // The settings key column accepts at most 100 characters, prefix included.
8
+ const MAX_KEY_LENGTH = 100 - PREFERENCE_PREFIX.length;
9
+ export function definePreference(definition) {
10
+ if (!KEY.test(definition.key) || definition.key.length > MAX_KEY_LENGTH)
11
+ throw new Error(`Invalid preference key "${definition.key}"`);
12
+ return definition;
13
+ }
14
+ /** True for a settings key that stores a user's own preference. */
15
+ export function isPreferenceSetting(key) {
16
+ return key.startsWith(PREFERENCE_PREFIX);
17
+ }
18
+ function invalid() {
19
+ throw new AdulaError(422, 'E_PREFERENCE_VALUE', 'قيمة التفضيل غير صالحة');
20
+ }
21
+ function sized(value) {
22
+ const text = JSON.stringify(value);
23
+ if (text === undefined)
24
+ invalid();
25
+ if (Buffer.byteLength(text, 'utf8') > PREFERENCE_MAX_BYTES)
26
+ throw new AdulaError(422, 'E_PREFERENCE_TOO_LARGE', 'قيمة التفضيل أكبر من المسموح');
27
+ return text;
28
+ }
29
+ function userScope(userId) {
30
+ if (!Number.isSafeInteger(userId) || userId <= 0)
31
+ throw new Error('Invalid user id');
32
+ return String(userId);
33
+ }
34
+ export class UserPreferences {
35
+ db;
36
+ report;
37
+ #definitions = new Map();
38
+ constructor(db, definitions, report = () => { }) {
39
+ this.db = db;
40
+ this.report = report;
41
+ UserPreferences.validate(definitions);
42
+ for (const definition of definitions)
43
+ this.#definitions.set(definition.key, definition);
44
+ }
45
+ /** Boot check: keys are well formed and unique, and every default passes its validator. */
46
+ static validate(definitions) {
47
+ const seen = new Set();
48
+ for (const definition of definitions) {
49
+ definePreference(definition);
50
+ if (seen.has(definition.key))
51
+ throw new Error(`Duplicate preference "${definition.key}"`);
52
+ seen.add(definition.key);
53
+ sized(definition.default);
54
+ const normalized = definition.validate(definition.default);
55
+ if (JSON.stringify(normalized) !== JSON.stringify(definition.default))
56
+ throw new Error(`The default of preference "${definition.key}" does not validate`);
57
+ }
58
+ }
59
+ keys() {
60
+ return [...this.#definitions.keys()];
61
+ }
62
+ /** Every registered preference of the user, defaults filled in. */
63
+ async all(userId) {
64
+ const keys = this.keys();
65
+ const rows = keys.length
66
+ ? await this.db('settings')
67
+ .where({ scope: 'user', scope_id: userScope(userId) })
68
+ .whereIn('key', keys.map((key) => PREFERENCE_PREFIX + key))
69
+ .select('key', 'value')
70
+ : [];
71
+ const stored = new Map(rows.map((row) => [String(row.key), row.value]));
72
+ const result = {};
73
+ for (const [key, definition] of this.#definitions)
74
+ result[key] = this.#read(definition, stored.get(PREFERENCE_PREFIX + key));
75
+ return result;
76
+ }
77
+ async get(userId, key) {
78
+ const definition = this.#definition(key);
79
+ const row = await this.db('settings')
80
+ .where({ key: PREFERENCE_PREFIX + key, scope: 'user', scope_id: userScope(userId) })
81
+ .first('value');
82
+ return this.#read(definition, row?.value);
83
+ }
84
+ async set(userId, key, value) {
85
+ const definition = this.#definition(key);
86
+ sized(value);
87
+ const normalized = definition.validate(value);
88
+ await this.db('settings')
89
+ .insert({
90
+ key: PREFERENCE_PREFIX + key,
91
+ scope: 'user',
92
+ scope_id: userScope(userId),
93
+ value: sized(normalized),
94
+ })
95
+ .onConflict(['key', 'scope', 'scope_id'])
96
+ .merge(['value']);
97
+ return normalized;
98
+ }
99
+ /** Removes the stored value; the user sees the default again. */
100
+ async reset(userId, key) {
101
+ const definition = this.#definition(key);
102
+ await this.db('settings')
103
+ .where({ key: PREFERENCE_PREFIX + key, scope: 'user', scope_id: userScope(userId) })
104
+ .delete();
105
+ return definition.default;
106
+ }
107
+ #definition(key) {
108
+ const definition = this.#definitions.get(key);
109
+ if (!definition)
110
+ throw new AdulaError(404, 'E_PREFERENCE_UNKNOWN', 'التفضيل غير معروف');
111
+ return definition;
112
+ }
113
+ // A value stored by an older release that no longer validates falls back to the default.
114
+ #read(definition, value) {
115
+ if (value === undefined || value === null)
116
+ return definition.default;
117
+ try {
118
+ return definition.validate(value);
119
+ }
120
+ catch (error) {
121
+ this.report(definition.key, error);
122
+ return definition.default;
123
+ }
124
+ }
125
+ }
@@ -14,6 +14,8 @@ export type UserOrgUnit = {
14
14
  export type UserSummary = {
15
15
  id: number;
16
16
  fullName: string | null;
17
+ /** The user's versioned picture URL, or null without one (ADR 050). */
18
+ avatarUrl?: string | null;
17
19
  email: string;
18
20
  disabledAt: string | null;
19
21
  roles: UserRoleAssignment[];
@@ -2,6 +2,7 @@ import { AdulaError } from '../admin/errors.js';
2
2
  import { logActivity, pageLimit } from './activity.js';
3
3
  import { administrationGuard } from './administration_guard.js';
4
4
  import { escapeLike } from './like.js';
5
+ import { avatarUrlFor, avatarVersionColumn } from './user_avatars.js';
5
6
  const RESOURCE = 'core.users';
6
7
  /** Host applications own the users table; AdulaJS expects id, email, full_name and disabled_at. */
7
8
  export class UsersAdmin {
@@ -12,7 +13,7 @@ export class UsersAdmin {
12
13
  async list(options = {}) {
13
14
  const limit = pageLimit(options.limit);
14
15
  const query = this.db('users')
15
- .select('id', 'email', 'full_name', 'disabled_at')
16
+ .select('id', 'email', 'full_name', 'disabled_at', avatarVersionColumn(this.db, 'users.id'))
16
17
  .orderBy('id')
17
18
  .limit(limit + 1);
18
19
  const search = options.search?.trim();
@@ -138,7 +139,7 @@ export class UsersAdmin {
138
139
  }
139
140
  async find(db, id) {
140
141
  const user = await db('users')
141
- .select('id', 'email', 'full_name', 'disabled_at')
142
+ .select('id', 'email', 'full_name', 'disabled_at', avatarVersionColumn(db, 'users.id'))
142
143
  .where('id', id)
143
144
  .first();
144
145
  if (!user)
@@ -163,6 +164,7 @@ export class UsersAdmin {
163
164
  return rows.map((row) => ({
164
165
  id: row.id,
165
166
  fullName: row.full_name ?? null,
167
+ avatarUrl: avatarUrlFor(row.id, row.avatar_version),
166
168
  email: row.email,
167
169
  disabledAt: row.disabled_at ? new Date(row.disabled_at).toISOString() : null,
168
170
  roles: roles
@@ -203,3 +203,49 @@ export declare function createWorkflowDelegationSlaSchema(db: Knex): Promise<voi
203
203
  * Templates are deployment-wide, like message_templates.
204
204
  */
205
205
  export declare function createPrintTemplatesSchema(db: Knex): Promise<void>;
206
+ /** Template keys of the notifications that quote a comment's text. */
207
+ export declare const COMMENT_NOTIFICATION_KEYS: readonly ["comment.mentioned", "comment.created"];
208
+ export declare const DELETED_COMMENT_TITLE = "\u062A\u0639\u0644\u064A\u0642 \u0645\u062D\u0630\u0648\u0641";
209
+ export declare const DELETED_COMMENT_BODY = "\u062D\u064F\u0630\u0641 \u0647\u0630\u0627 \u0627\u0644\u062A\u0639\u0644\u064A\u0642.";
210
+ /**
211
+ * Ids and template keys of the notifications that quote a comment: those naming it
212
+ * (comment_id, 2.3.0) and those written before notifications named their comment. A
213
+ * comment's notifications were inserted in its own transaction, so their created_at equals
214
+ * the comment's (both now()), and they quote its text from the start: the first 100
215
+ * characters are matched, which the 200-unit excerpt always contains. Read before a
216
+ * comment's body changes. `comment` is one comment id, or 'deleted' for every deleted one.
217
+ */
218
+ export declare function commentNotifications(db: Knex, comment: number | 'deleted'): Promise<{
219
+ id: number;
220
+ key: string;
221
+ }[]>;
222
+ /**
223
+ * Stops what has not been sent yet of the given notifications: pending e-mail is skipped
224
+ * and pending channel deliveries are withdrawn (a channel worker re-checks the pending
225
+ * state before it sends, so a claimed delivery is not sent either).
226
+ */
227
+ export declare function withdrawNotificationDelivery(db: Knex, ids: number[]): Promise<void>;
228
+ /**
229
+ * Comment notifications name their comment (2.3.0), so deleting or editing the comment
230
+ * withdraws the quoted text. Notifications of comments deleted before this migration are
231
+ * found by their transaction time and quoted text, and withdrawn here.
232
+ */
233
+ export declare function createCommentNotificationsSchema(db: Knex): Promise<void>;
234
+ /** Replaces the quoted text of every deleted comment's notifications with a neutral note. */
235
+ export declare function withdrawDeletedCommentNotifications(db: Knex): Promise<void>;
236
+ /**
237
+ * The built-in assistant (ADR 052): conversation metadata (never message text), pending
238
+ * write proposals awaiting the user's confirmation, and per-user daily token usage.
239
+ */
240
+ export declare function createAssistantSchema(db: Knex): Promise<void>;
241
+ /**
242
+ * Cloud and downloadable backups (ADR 051): one connection per destination with its refresh
243
+ * token sealed by the host's SecretBox, and one row per backup run.
244
+ */
245
+ export declare function createCloudBackupsSchema(db: Knex): Promise<void>;
246
+ /**
247
+ * Appearance occasions (ADR 053): dated overrides of the base identity, which is the system
248
+ * setting `appearance.identity`. Logos are `attachments` rows, so only the id is kept here.
249
+ * Overlapping ranges are refused by the service under a table lock.
250
+ */
251
+ export declare function createAppearanceSchema(db: Knex): Promise<void>;