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
package/build/index.js CHANGED
@@ -9,7 +9,7 @@ export { ActorStore } from './src/auth/actor_store.js';
9
9
  export { accessibleBy, authorizationSql, conditionSql } from './src/auth/sql.js';
10
10
  export { ACTOR_ID, resolveActorConditions } from './src/auth/conditions.js';
11
11
  export { ResourceService, canQueryField } from './src/admin/resource_service.js';
12
- export { EXPORT_ROW_LIMIT } from './src/admin/resource_service.js';
12
+ export { EXPORT_ROW_LIMIT, guardFormula } from './src/admin/resource_service.js';
13
13
  export { BulkActions, defineBulkActions, BULK_ID_LIMIT } from './src/lists/bulk_actions.js';
14
14
  export { Dashboards, defineDashboard } from './src/lists/dashboards.js';
15
15
  export { serialize, writableInput, selectedFields } from './src/admin/contracts.js';
@@ -28,6 +28,7 @@ export { WorkflowEngine, workflowListeners, slaState } from './src/workflows/eng
28
28
  export { WorkflowDelegations } from './src/workflows/delegations.js';
29
29
  export { ImportBatches, importCell, IMPORT_ROW_LIMIT } from './src/integrations/imports.js';
30
30
  export { csvImportAdapter, importFile } from './src/integrations/import_adapters.js';
31
+ export { guardXlsx, readXlsxTable, xlsxImportAdapter, XLSX_LIMITS, XLSX_MIME_TYPE, } from './src/integrations/xlsx.js';
31
32
  export { createImportModesSchema, createImportLeasesSchema } from './src/database/schema.js';
32
33
  export { openApiDocument } from './src/integrations/openapi.js';
33
34
  export { apiClientSource, apiClientDeclarations } from './src/integrations/api_client.js';
@@ -37,7 +38,7 @@ export { sanitizePrintHtml } from './src/core/html_sanitizer.js';
37
38
  export { parseTemplate } from './src/core/template_language.js';
38
39
  export { createPrintTemplatesSchema } from './src/database/schema.js';
39
40
  export { Webhooks, signWebhook, WEBHOOK_MAX_ATTEMPTS } from './src/integrations/webhooks.js';
40
- export { createOutboundPoster, isBlockedAddress, outboundErrorCategory, } from './src/integrations/outbound.js';
41
+ export { createOutboundPoster, createOutboundRequester, OutboundResponseTooLargeError, isBlockedAddress, outboundErrorCategory, } from './src/integrations/outbound.js';
41
42
  export { InboundWebhooks, inboundEventName, INBOUND_BODY_LIMIT, INBOUND_RETENTION_DAYS, } from './src/integrations/inbound_webhooks.js';
42
43
  export { MessageTemplates, DEFAULT_TEMPLATES, renderTemplate, notifyWithTemplate, deliverNotificationMail, listenForNotifications, } from './src/core/message_templates.js';
43
44
  export { Assignments } from './src/collaboration/assignments.js';
@@ -48,15 +49,21 @@ export { migrateStorage } from './src/attachments/storage_migrate.js';
48
49
  export { diagnoseAttachments } from './src/attachments/doctor.js';
49
50
  export { Settings, sequence, formatSequence, notify } from './src/services/settings.js';
50
51
  export { uiPreferences, validateUiPreferences, UI_PREFERENCES_KEY, DEFAULT_UI_PREFERENCES, } from './src/core/ui_preferences.js';
52
+ export { UserPreferences, definePreference, isPreferenceSetting, PREFERENCE_PREFIX, PREFERENCE_MAX_BYTES, } from './src/core/user_preferences.js';
51
53
  export { moveOrgUnit } from './src/org/org_service.js';
52
54
  export { publishOutbox, consumeEvent } from './src/events/outbox.js';
53
55
  export { AdonisJobs } from './src/events/adonis_jobs.js';
54
56
  export { recordMutation } from './src/events/record_mutation.js';
55
57
  export { assessBackup, verifyBackup } from './src/services/backup.js';
58
+ export { BACKUP_ARCHIVE_EXTENSION, BACKUP_ARCHIVE_FILES, BackupArchiveError, createOpenStream, createSealStream, openBackupArchive, parseBackupKey, sealBackupArchive, } from './src/backups/archive.js';
59
+ export { BackupProviderError, googleDriveProvider, oneDriveProvider, } from './src/backups/providers.js';
60
+ export { BACKUP_FAILURE_MESSAGES, CloudBackups } from './src/backups/cloud_backups.js';
56
61
  export { ActivityAdmin, logActivity } from './src/core/activity.js';
57
62
  export { RolesAdmin, ALL_SUBJECT_LABEL } from './src/core/roles.js';
58
63
  export { seedModules } from './src/core/module_seed.js';
59
64
  export { UsersAdmin } from './src/core/users.js';
65
+ export { UserAvatars, avatarUrl, avatarUrlFor, avatarVersionColumn, avatarHeaders, } from './src/core/user_avatars.js';
66
+ export { prepareAvatarImage, AVATAR_LIMITS } from './src/core/avatar_image.js';
60
67
  export { UserInvitations } from './src/core/user_invitations.js';
61
68
  export { OrgUnitsAdmin } from './src/core/org_units.js';
62
69
  export { SavedViews } from './src/core/saved_views.js';
@@ -65,7 +72,7 @@ export { SettingsAdmin, isProtectedSetting, parseSettingValue, SETTING_SCOPES, P
65
72
  export { LookupsAdmin } from './src/core/lookups.js';
66
73
  export { SequencesAdmin } from './src/core/sequences.js';
67
74
  export { runtimeHealth, isBackupStale, backupStale, heartbeat, HEARTBEAT_MAX_AGE_MS, BACKUP_MAX_AGE_MS, } from './src/core/health.js';
68
- export { MailDeliveryTest, MAIL_TEST_KEY } from './src/core/mail_test.js';
75
+ export { MailDeliveryTest, MAIL_TEST_KEY, classifyMailFailure, } from './src/core/mail_test.js';
69
76
  export { InitialSetup } from './src/core/setup.js';
70
77
  export { administratorExists, grantInstallAdministrator, resolveInstallAdministrator, } from './src/core/administrators.js';
71
78
  export { ADULA_VERSION } from './src/version.js';
@@ -75,3 +82,11 @@ export { defineSyncJob, SyncJobs, SyncJobError, syncErrorCategory, SYNC_DEFAULT_
75
82
  export { createNotificationChannelsSchema, createChannelConfirmationsSchema, } from './src/database/schema.js';
76
83
  export { NotificationChannels, HttpChannelSettings, ChannelDeliveryError, inAppChannel, mailChannel, httpNotificationChannel, phoneAddress, IN_APP_CHANNEL, MAIL_CHANNEL, CHANNEL_MAX_ATTEMPTS, HTTP_CHANNEL_SETTING_KEY, HTTP_CHANNEL_KINDS, CHANNEL_KIND_LABELS, } from './src/core/notification_channels.js';
77
84
  export { isSealedSetting } from './src/core/settings.js';
85
+ export { parseResourceToolArgs, runResourceTool, resourceToolError, RESOURCE_READ_SCHEMA, RESOURCE_WRITE_SCHEMA, } from './src/admin/resource_tools.js';
86
+ export { Assistant } from './src/ai/assistant.js';
87
+ export { AssistantSettings, ASSISTANT_LIMITS } from './src/ai/settings.js';
88
+ export { MailSettings, MAIL_SETTINGS_KEY } from './src/core/mail_settings.js';
89
+ export { createChatClient, AssistantError } from './src/ai/client.js';
90
+ export { Appearance, APPEARANCE_LOGO_OWNER, APPEARANCE_SETTING_KEY, APPEARANCE_TEXT_LIMITS, BASE_LOGO_RECORD, dateIn, } from './src/appearance/appearance.js';
91
+ export { checkPrimaryColor, contrast, derivePrimaryTheme, normalizeColor, WCAG_AA, } from './src/appearance/colors.js';
92
+ export { LOGO_LIMITS, detectLogoType, logoHeaders, prepareLogoImage, } from './src/appearance/logo.js';
@@ -47,19 +47,23 @@ export function createResourceController(resolveRuntime, renderList, renderForm,
47
47
  }
48
48
  async export(ctx) {
49
49
  return this.#execute(ctx, async ({ resources, actor }, resource) => {
50
+ const format = exportFormat(ctx);
50
51
  const { search, sort, direction, filters, tag } = this.#listOptions(ctx);
51
- const file = await resources.export(resource.name, actor, {
52
+ const options = {
52
53
  search,
53
54
  sort,
54
55
  direction,
55
56
  filters,
56
57
  tag,
57
58
  trashed: ctx.request.input('trashed') === 'true' || ctx.request.input('trashed') === true,
58
- });
59
- ctx.response.header('Content-Type', 'text/csv; charset=utf-8');
59
+ };
60
+ const file = format === 'xlsx'
61
+ ? await resources.exportXlsx(resource.name, actor, options)
62
+ : await resources.export(resource.name, actor, options);
63
+ ctx.response.header('Content-Type', format === 'xlsx' ? XLSX_CONTENT_TYPE : 'text/csv; charset=utf-8');
60
64
  ctx.response.header('Content-Disposition', `attachment; filename="${file.asciiFilename}"; filename*=UTF-8''${rfc5987(file.filename)}`);
61
65
  ctx.response.header('Cache-Control', 'no-store');
62
- ctx.response.send(file.content);
66
+ ctx.response.send(typeof file.content === 'string' ? file.content : Buffer.from(file.content));
63
67
  });
64
68
  }
65
69
  async restore(ctx) {
@@ -226,6 +230,16 @@ export function createResourceController(resolveRuntime, renderList, renderForm,
226
230
  };
227
231
  }
228
232
  /** RFC 5987 ext-value encoding of a UTF-8 file name. */
233
+ const XLSX_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
234
+ /** `?format=csv|xlsx`, or an Accept header naming the spreadsheet type; CSV by default. */
235
+ function exportFormat(ctx) {
236
+ const format = ctx.request.input('format');
237
+ if (format === undefined || format === null || format === '')
238
+ return (ctx.request.header('accept') ?? '').includes('spreadsheetml') ? 'xlsx' : 'csv';
239
+ if (format === 'csv' || format === 'xlsx')
240
+ return format;
241
+ throw new AdulaError(422, 'E_EXPORT_FORMAT', 'صيغة التصدير غير مدعومة');
242
+ }
229
243
  function rfc5987(value) {
230
244
  return encodeURIComponent(value).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
231
245
  }
@@ -38,6 +38,7 @@ export declare function editor(ctx: ResourceContext, name: string, actor: Actor,
38
38
  options: Record<string, {
39
39
  value: string;
40
40
  label: string;
41
+ avatarUrl?: string | null;
41
42
  }[]>;
42
43
  relationSearch: Record<string, boolean>;
43
44
  orgUnits: {
@@ -6,6 +6,7 @@ import { fromRow, serialize } from '../contracts.js';
6
6
  import { AdulaError, documentLocked, forbiddenField, invalidCursor } from '../errors.js';
7
7
  import { attachmentLimit, fieldValue } from '../../resource/values.js';
8
8
  import { escapeLike } from '../../core/like.js';
9
+ import { avatarUrlFor, avatarVersionColumn } from '../../core/user_avatars.js';
9
10
  import { labelText } from '../../languages/catalog.js';
10
11
  import { authorizeAction, columns, eligibleUsers, fieldLevel, find, hydrate, hydrateOne, requireRecord, } from './shared.js';
11
12
  import { describe, show, titler } from './read.js';
@@ -32,8 +33,10 @@ export async function editor(ctx, name, actor, id, request = {}) {
32
33
  ability.can(action, record ? subject(name, record) : name, key));
33
34
  })
34
35
  .map((key) => editorField(key, resource.fields[key]));
36
+ // User choices also carry the person's picture (null without one, ADR 050).
35
37
  const options = {};
36
38
  const relationSearch = {};
39
+ const onlyChoice = new Map();
37
40
  const inline = {};
38
41
  for (const field of fields) {
39
42
  if (field.type === 'hasMany' && field.inline) {
@@ -98,6 +101,11 @@ export async function editor(ctx, name, actor, id, request = {}) {
98
101
  value: String(row.id),
99
102
  label: title(row) ?? `#${row.id}`,
100
103
  }));
104
+ if (field.type === 'belongsTo' &&
105
+ field.required &&
106
+ page.data.length === 1 &&
107
+ page.meta.nextCursor === null)
108
+ onlyChoice.set(field.key, Number(page.data[0].id));
101
109
  const value = record?.[field.key];
102
110
  // Current values outside the first page keep a labelled choice when still viewable.
103
111
  for (const selected of Array.isArray(value) ? value : [value]) {
@@ -127,11 +135,14 @@ export async function editor(ctx, name, actor, id, request = {}) {
127
135
  options[field.key] = [];
128
136
  const selected = record?.[field.key];
129
137
  if (selected !== null && selected !== undefined) {
130
- const current = await db('users').where('id', Number(selected)).first('id', 'full_name');
138
+ const current = await db('users as u')
139
+ .where('u.id', Number(selected))
140
+ .first('u.id', 'u.full_name', avatarVersionColumn(db, 'u.id'));
131
141
  if (current)
132
142
  options[field.key].push({
133
143
  value: String(current.id),
134
144
  label: String(current.full_name || `#${current.id}`),
145
+ avatarUrl: avatarUrlFor(current.id, current.avatar_version),
135
146
  });
136
147
  }
137
148
  }
@@ -186,12 +197,16 @@ export async function editor(ctx, name, actor, id, request = {}) {
186
197
  // The unit is chosen later in the form; saving checks the record's unit.
187
198
  const user = await eligibleUsers(db, null, actor)
188
199
  .where('u.id', Number(value))
189
- .first('u.id', 'u.full_name');
200
+ .first('u.id', 'u.full_name', avatarVersionColumn(db, 'u.id'));
190
201
  if (!user)
191
202
  continue;
192
203
  const choices = options[field.key] ?? (options[field.key] = []);
193
204
  if (!choices.some((option) => option.value === String(user.id)))
194
- choices.push({ value: String(user.id), label: String(user.full_name || `#${user.id}`) });
205
+ choices.push({
206
+ value: String(user.id),
207
+ label: String(user.full_name || `#${user.id}`),
208
+ avatarUrl: avatarUrlFor(user.id, user.avatar_version),
209
+ });
195
210
  }
196
211
  if (field.type === 'lookup' || field.type === 'belongsTo') {
197
212
  const choices = options[field.key] ?? [];
@@ -217,6 +232,12 @@ export async function editor(ctx, name, actor, id, request = {}) {
217
232
  }
218
233
  defaults[field.key] = value;
219
234
  }
235
+ // A required belongsTo whose actor can choose only one record starts on it (#115, ADR 030);
236
+ // saving still authorizes the reference.
237
+ if (id === undefined)
238
+ for (const [key, only] of onlyChoice)
239
+ if (defaults[key] === undefined)
240
+ defaults[key] = only;
220
241
  return {
221
242
  mode: action,
222
243
  name,
@@ -303,7 +324,7 @@ async function userOptions(ctx, name, key, actor, options) {
303
324
  .where('u.id', '>', after)
304
325
  .orderBy('u.id')
305
326
  .limit(51)
306
- .select('u.id', 'u.full_name');
327
+ .select('u.id', 'u.full_name', avatarVersionColumn(ctx.db, 'u.id'));
307
328
  if (options.search)
308
329
  query.whereILike('u.full_name', `%${escapeLike(options.search)}%`);
309
330
  const rows = await query;
@@ -311,6 +332,7 @@ async function userOptions(ctx, name, key, actor, options) {
311
332
  data: rows.slice(0, 50).map((row) => ({
312
333
  value: String(row.id),
313
334
  label: String(row.full_name || `#${row.id}`),
335
+ avatarUrl: avatarUrlFor(row.id, row.avatar_version),
314
336
  })),
315
337
  nextCursor: rows.length > 50 ? String(rows[49].id) : null,
316
338
  };
@@ -14,13 +14,24 @@ export type CsvExport = {
14
14
  asciiFilename: string;
15
15
  rows: number;
16
16
  };
17
+ /** An xlsx export; the same file names as CsvExport with the .xlsx extension. */
18
+ export type XlsxExport = {
19
+ content: Uint8Array;
20
+ filename: string;
21
+ asciiFilename: string;
22
+ rows: number;
23
+ };
17
24
  /**
18
- * The currently filtered list as CSV; see ResourceService.export. Rows are read page by
19
- * page through list(), so the actor's rules, organization scope, field redaction and the
20
- * soft-delete filter are exactly the list's. More than EXPORT_ROW_LIMIT matching rows is
21
- * 422 E_EXPORT_LIMIT and nothing is produced.
25
+ * The currently filtered list as CSV; see ResourceService.export. The rows, limit and audit
26
+ * come from collectExport.
22
27
  */
23
28
  export declare function exportCsv(ctx: ResourceContext, name: string, actor: Actor, options?: ExportOptions): Promise<CsvExport>;
29
+ /**
30
+ * The currently filtered list as an Excel workbook (one right-to-left sheet, bold header),
31
+ * with the same rows, columns, limit and audit as exportCsv. Numbers, amounts and dates are
32
+ * typed cells; other values are text, guarded like CSV against formula evaluation.
33
+ */
34
+ export declare function exportXlsx(ctx: ResourceContext, name: string, actor: Actor, options?: ExportOptions): Promise<XlsxExport>;
24
35
  /**
25
36
  * The display text of one stored value: lookup and option labels, titles, names, «نعم/لا»,
26
37
  * ISO dates. Several values (multiSelect, manyToMany) are joined with «، » as lists show them.
@@ -35,3 +46,9 @@ export declare function cellText(field: Field, value: JsonValue | undefined, res
35
46
  * apostrophe so spreadsheets do not evaluate it as a formula.
36
47
  */
37
48
  export declare function csvCell(text: string, guard: boolean): string;
49
+ /**
50
+ * Prefixes an apostrophe to text a spreadsheet would evaluate as a formula: a leading tab or
51
+ * carriage return, or = + - @ (also full width) as the first non-whitespace character. CSV
52
+ * export, xlsx export and xlsx templates share this one rule.
53
+ */
54
+ export declare function guardFormula(text: string): string;
@@ -1,3 +1,4 @@
1
+ import writeXlsxFile from 'write-excel-file/node';
1
2
  import { AdulaError } from '../errors.js';
2
3
  import { labelText, translate } from '../../languages/catalog.js';
3
4
  import { logActivity } from '../../core/activity.js';
@@ -8,12 +9,11 @@ export const EXPORT_ROW_LIMIT = 5000;
8
9
  const PAGE_SIZE = 100;
9
10
  const ACTIVITY_RESOURCE = 'core.exports';
10
11
  /**
11
- * The currently filtered list as CSV; see ResourceService.export. Rows are read page by
12
- * page through list(), so the actor's rules, organization scope, field redaction and the
13
- * soft-delete filter are exactly the list's. More than EXPORT_ROW_LIMIT matching rows is
14
- * 422 E_EXPORT_LIMIT and nothing is produced.
12
+ * The currently filtered list, read page by page through list(), so the actor's rules,
13
+ * organization scope, field redaction and the soft-delete filter are exactly the list's.
14
+ * More than EXPORT_ROW_LIMIT matching rows is 422 E_EXPORT_LIMIT and nothing is produced.
15
15
  */
16
- export async function exportCsv(ctx, name, actor, options = {}) {
16
+ async function collectExport(ctx, name, actor, options) {
17
17
  const resource = ctx.registry.get(name);
18
18
  const description = describe(ctx, name, actor);
19
19
  const readable = new Map(description.fields.map((field) => [field.key, field]));
@@ -70,44 +70,114 @@ export async function exportCsv(ctx, name, actor, options = {}) {
70
70
  lookup: (group, entry) => lookupLabels.get(`${group}\u0000${entry}`),
71
71
  title: (id) => titles.get(key)?.get(id),
72
72
  });
73
+ const rows = records.map((record) => keys.map((key) => {
74
+ const field = resource.fields[key];
75
+ return { field, text: display(key, field, record[key]), raw: record[key] };
76
+ }));
77
+ const audit = async (format) => {
78
+ await logActivity(ctx.db, {
79
+ resource: ACTIVITY_RESOURCE,
80
+ recordId: 0,
81
+ actorId: actor.id,
82
+ impersonatorId: actor.impersonatorId,
83
+ action: 'exported',
84
+ changes: {
85
+ resource: name,
86
+ format,
87
+ query: {
88
+ ...(options.search ? { search: options.search } : {}),
89
+ ...(options.sort ? { sort: options.sort } : {}),
90
+ ...(options.direction ? { direction: options.direction } : {}),
91
+ ...(options.filters && Object.keys(options.filters).length
92
+ ? { filters: options.filters }
93
+ : {}),
94
+ ...(options.tag ? { tag: options.tag } : {}),
95
+ ...(options.trashed ? { trashed: true } : {}),
96
+ },
97
+ rows: records.length,
98
+ },
99
+ });
100
+ };
101
+ return { resource, keys, rows, audit };
102
+ }
103
+ /**
104
+ * The currently filtered list as CSV; see ResourceService.export. The rows, limit and audit
105
+ * come from collectExport.
106
+ */
107
+ export async function exportCsv(ctx, name, actor, options = {}) {
108
+ const { resource, keys, rows, audit } = await collectExport(ctx, name, actor, options);
73
109
  const lines = [
74
110
  keys.map((key) => csvCell(labelText(resource.fields[key].label), true)).join(','),
75
- ...records.map((record) => keys
76
- .map((key) => {
77
- const field = resource.fields[key];
78
- return csvCell(display(key, field, record[key]), textual(field));
79
- })
80
- .join(',')),
111
+ ...rows.map((row) => row.map((cell) => csvCell(cell.text, textual(cell.field))).join(',')),
81
112
  ];
82
- await logActivity(ctx.db, {
83
- resource: ACTIVITY_RESOURCE,
84
- recordId: 0,
85
- actorId: actor.id,
86
- impersonatorId: actor.impersonatorId,
87
- action: 'exported',
88
- changes: {
89
- resource: name,
90
- query: {
91
- ...(options.search ? { search: options.search } : {}),
92
- ...(options.sort ? { sort: options.sort } : {}),
93
- ...(options.direction ? { direction: options.direction } : {}),
94
- ...(options.filters && Object.keys(options.filters).length
95
- ? { filters: options.filters }
96
- : {}),
97
- ...(options.tag ? { tag: options.tag } : {}),
98
- ...(options.trashed ? { trashed: true } : {}),
99
- },
100
- rows: records.length,
101
- },
102
- });
113
+ await audit('csv');
103
114
  const day = new Date().toISOString().slice(0, 10);
104
115
  return {
105
116
  content: `\uFEFF${lines.join('\r\n')}\r\n`,
106
117
  filename: `${labelText(resource.label)}-${day}.csv`,
107
118
  asciiFilename: `${name}-${day}.csv`,
108
- rows: records.length,
119
+ rows: rows.length,
109
120
  };
110
121
  }
122
+ /**
123
+ * The currently filtered list as an Excel workbook (one right-to-left sheet, bold header),
124
+ * with the same rows, columns, limit and audit as exportCsv. Numbers, amounts and dates are
125
+ * typed cells; other values are text, guarded like CSV against formula evaluation.
126
+ */
127
+ export async function exportXlsx(ctx, name, actor, options = {}) {
128
+ const { resource, keys, rows, audit } = await collectExport(ctx, name, actor, options);
129
+ const header = keys.map((key) => ({
130
+ value: guardFormula(labelText(resource.fields[key].label)),
131
+ fontWeight: 'bold',
132
+ }));
133
+ const data = [header, ...rows.map((row) => row.map(xlsxCell))];
134
+ const content = await writeXlsxFile(data, {
135
+ sheet: sheetName(labelText(resource.label)),
136
+ rightToLeft: true,
137
+ stickyRowsCount: 1,
138
+ }).toBuffer();
139
+ await audit('xlsx');
140
+ const day = new Date().toISOString().slice(0, 10);
141
+ return {
142
+ content: new Uint8Array(content.buffer, content.byteOffset, content.byteLength),
143
+ filename: `${labelText(resource.label)}-${day}.xlsx`,
144
+ asciiFilename: `${name}-${day}.xlsx`,
145
+ rows: rows.length,
146
+ };
147
+ }
148
+ /** Excel sheet names: at most 31 characters, none of [ ] : * ? / \, not quoted. */
149
+ function sheetName(label) {
150
+ const clean = label
151
+ .replace(/[[\]:*?/\\]/g, ' ')
152
+ .trim()
153
+ .replace(/^'+|'+$/g, '')
154
+ .slice(0, 31)
155
+ .trim();
156
+ return clean || 'Sheet1';
157
+ }
158
+ const NUMERIC = new Set(['integer', 'decimal', 'percent']);
159
+ /** One typed xlsx cell; anything that is not a safe number or date stays guarded text. */
160
+ function xlsxCell({ field, text, raw }) {
161
+ if (raw === null || raw === undefined || raw === '')
162
+ return null;
163
+ if (NUMERIC.has(field.type)) {
164
+ const value = typeof raw === 'number' ? raw : Number(raw);
165
+ if (Number.isFinite(value) && String(raw).trim() !== '')
166
+ return value;
167
+ }
168
+ if (field.type === 'money' && /^-?\d+$/.test(String(raw))) {
169
+ const minor = BigInt(String(raw));
170
+ const limit = BigInt(Number.MAX_SAFE_INTEGER);
171
+ if (minor <= limit && minor >= -limit)
172
+ return { value: Number(minor) / 100, type: Number, format: '#,##0.00' };
173
+ }
174
+ if (field.type === 'date' && typeof raw === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(raw)) {
175
+ const date = new Date(`${raw}T00:00:00.000Z`);
176
+ if (!Number.isNaN(date.getTime()))
177
+ return { value: date, type: Date, format: 'yyyy-mm-dd' };
178
+ }
179
+ return text === '' ? null : guardFormula(text);
180
+ }
111
181
  function exportLimit() {
112
182
  return new AdulaError(422, 'E_EXPORT_LIMIT', 'عدد السجلات المطابقة يتجاوز حد التصدير (5000 سجل). ضيّق التصفية ثم أعد المحاولة.');
113
183
  }
@@ -129,7 +199,8 @@ export function cellText(field, value, resolve) {
129
199
  return resolve.lookup(field.group, String(value)) ?? String(value);
130
200
  case 'belongsTo':
131
201
  case 'user':
132
- return resolve.title(Number(value)) ?? `#${value}`;
202
+ // A record the reader may not view is never named, not even by its id.
203
+ return resolve.title(Number(value)) ?? translate('list.value.unavailable');
133
204
  case 'enum':
134
205
  return optionText(field.options, value);
135
206
  case 'multiSelect':
@@ -138,7 +209,9 @@ export function cellText(field, value, resolve) {
138
209
  : optionText(field.options, value);
139
210
  case 'manyToMany':
140
211
  return Array.isArray(value)
141
- ? value.map((id) => resolve.title(Number(id)) ?? `#${id}`).join('، ')
212
+ ? value
213
+ .map((id) => resolve.title(Number(id)) ?? translate('list.value.unavailable'))
214
+ .join('، ')
142
215
  : String(value);
143
216
  case 'money':
144
217
  return moneyText(String(value));
@@ -176,6 +249,14 @@ const FORMULA_START = /^(?:[\t\r]|\s*[=+\-@\uFF1D\uFF0B\uFF0D\uFF20])/;
176
249
  * apostrophe so spreadsheets do not evaluate it as a formula.
177
250
  */
178
251
  export function csvCell(text, guard) {
179
- const safe = guard && FORMULA_START.test(text) ? `'${text}` : text;
252
+ const safe = guard ? guardFormula(text) : text;
180
253
  return `"${safe.replaceAll('"', '""')}"`;
181
254
  }
255
+ /**
256
+ * Prefixes an apostrophe to text a spreadsheet would evaluate as a formula: a leading tab or
257
+ * carriage return, or = + - @ (also full width) as the first non-whitespace character. CSV
258
+ * export, xlsx export and xlsx templates share this one rule.
259
+ */
260
+ export function guardFormula(text) {
261
+ return FORMULA_START.test(text) ? `'${text}` : text;
262
+ }
@@ -8,6 +8,8 @@ export type ParentWrite = {
8
8
  name: string;
9
9
  id: number;
10
10
  action: 'create' | 'update' | 'amend';
11
+ /** Set by the inline row's persist() when it created the row or changed a value. */
12
+ changed?: boolean;
11
13
  };
12
14
  /** Optimistic lock of versioned resources (409 E_VERSION_CONFLICT). */
13
15
  export declare function requireVersion(resource: Resource, existing: RecordData, version: unknown): void;
@@ -1,4 +1,4 @@
1
- import type { Field, JsonValue } from '../../resource/types.js';
1
+ import type { Field, JsonValue, SerializedRecord } from '../../resource/types.js';
2
2
  import { type Actor } from '../../auth/ability.js';
3
3
  import { type Conditions } from '../../auth/conditions.js';
4
4
  import { type ResourceContext } from './shared.js';
@@ -36,6 +36,11 @@ export type ListOptions = {
36
36
  * row's permissions carry `restore` (ADR 046).
37
37
  */
38
38
  trashed?: boolean;
39
+ /**
40
+ * Only these records, under the same authorization as the whole list: the row a dialog just
41
+ * created, pinned at the top of the list it was created from.
42
+ */
43
+ ids?: number[];
39
44
  };
40
45
  /** A scalar filter operand: equality, or one value of an operator. */
41
46
  export type ListFilterScalar = string | number | boolean | null;
@@ -81,8 +86,14 @@ export declare function filterCondition(key: string, field: Field, value: unknow
81
86
  * so callers can refuse an oversized request with one bounded query.
82
87
  */
83
88
  export declare function countUpTo(ctx: ResourceContext, name: string, actor: Actor, options: ListOptions, max: number): Promise<number>;
89
+ /**
90
+ * Distinct tag names on records list() would return to the actor, for tag suggestions
91
+ * (RecordCollaboration.tagOptions): the same rules, organization scope and soft-delete
92
+ * filter apply, so a suggestion never names a tag found only on records the actor cannot see.
93
+ */
94
+ export declare function tagNames(ctx: ResourceContext, name: string, actor: Actor, limit: number): Promise<string[]>;
84
95
  export declare function list(ctx: ResourceContext, name: string, actor: Actor, options?: ListOptions): Promise<{
85
- data: import("../../resource/types.js").SerializedRecord[];
96
+ data: SerializedRecord[];
86
97
  permissions: {
87
98
  [k: string]: Partial<Record<import("../../resource/types.js").Action | "restore", boolean>>;
88
99
  };
@@ -91,7 +102,7 @@ export declare function list(ctx: ResourceContext, name: string, actor: Actor, o
91
102
  estimatedTotal: number | undefined;
92
103
  nextCursor: string | null;
93
104
  };
94
- related: Record<string, import("../../resource/types.js").SerializedRecord[]>;
105
+ related: Record<string, SerializedRecord[]>;
95
106
  }>;
96
107
  /** Counts and totals over viewable records; see ResourceService.aggregate. */
97
108
  export declare function aggregate(ctx: ResourceContext, name: string, actor: Actor, options?: AggregateOptions): Promise<{