adula 2.1.0 → 2.2.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 (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +4 -2
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -0,0 +1,106 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Action, RecordData, Resource, SerializedRecord } from '../../resource/types.js';
3
+ import { type Actor, type AdulaAbility } from '../../auth/ability.js';
4
+ import type { ResourceDescription, ResourceNavigation } from '../presentation.js';
5
+ import { type ResourceContext } from './shared.js';
6
+ /** Project navigation is derived from registered resources and the current actor. */
7
+ export declare function navigation(ctx: ResourceContext, actor: Actor): ResourceNavigation;
8
+ export declare function describe(ctx: ResourceContext, name: string, actor: Actor): ResourceDescription;
9
+ /** Authorizes one record for collaboration features; see ResourceService.access. */
10
+ export declare function access(ctx: ResourceContext, name: string, id: number, actor: Actor, action: Action, db: Knex): Promise<{
11
+ resource: Resource;
12
+ record: RecordData;
13
+ ability: AdulaAbility;
14
+ }>;
15
+ /** Whether a (possibly other) actor may perform an action on a record; never throws for denial. */
16
+ export declare function permits(ctx: ResourceContext, name: string, id: number, actor: Actor, action: Action): Promise<boolean>;
17
+ /** Display rows of the users and related records referenced by the given records. */
18
+ export declare function preload(ctx: ResourceContext, resource: Resource, records: RecordData[], actor: Actor): Promise<Record<string, SerializedRecord[]>>;
19
+ /** Formats record titles of one resource, loading the labels of its title lookups once. */
20
+ export declare function titler(ctx: ResourceContext, resource: Resource): Promise<(record: SerializedRecord) => string | null>;
21
+ /** Titles of records the actor may view; see ResourceService.titles. */
22
+ export declare function titles(ctx: ResourceContext, name: string, ids: readonly number[], actor: Actor): Promise<Map<number, string>>;
23
+ export declare function show(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
24
+ data: SerializedRecord;
25
+ permissions: Partial<Record<Action | "restore", boolean>>;
26
+ related: Record<string, SerializedRecord[]>;
27
+ }>;
28
+ /** Deferred relation reads re-authorize the parent and each child on every request. */
29
+ export declare function recordChildren(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<Record<string, {
30
+ rows: SerializedRecord[];
31
+ hasMore: boolean;
32
+ related?: Record<string, SerializedRecord[]>;
33
+ }>>;
34
+ /**
35
+ * The lines of a printed document (ADR 048): the named hasMany fields, up to `limit` rows
36
+ * each, with the display rows of the lines' own relations. See ResourceService.documentLines.
37
+ */
38
+ export declare function documentLines(ctx: ResourceContext, name: string, id: number, actor: Actor, keys: readonly string[], limit: number): Promise<Record<string, {
39
+ rows: SerializedRecord[];
40
+ hasMore: boolean;
41
+ related?: Record<string, SerializedRecord[]>;
42
+ }>>;
43
+ /** Active lookup labels for the lookup fields the actor may read on this resource. */
44
+ export declare function lookups(ctx: ResourceContext, name: string, actor: Actor): Promise<Record<string, {
45
+ value: string;
46
+ label: string;
47
+ }[]>>;
48
+ /** The last 50 recorded mutations of one record, after authorizing the record itself. */
49
+ export declare function activity(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
50
+ id: number;
51
+ action: Action;
52
+ fields: string[];
53
+ actorId: number;
54
+ actorName: string | null;
55
+ /**
56
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
57
+ * earlier releases still compile; they fall back to the actor id.
58
+ */
59
+ actorEmail: string | null;
60
+ createdAt: string;
61
+ }[]>;
62
+ /** Inline children and recent activity of one record from a single record read. */
63
+ export declare function details(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
64
+ children: Record<string, {
65
+ rows: SerializedRecord[];
66
+ hasMore: boolean;
67
+ related?: Record<string, SerializedRecord[]>;
68
+ }>;
69
+ activity: {
70
+ id: number;
71
+ action: Action;
72
+ fields: string[];
73
+ actorId: number;
74
+ actorName: string | null;
75
+ /**
76
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
77
+ * earlier releases still compile; they fall back to the actor id.
78
+ */
79
+ actorEmail: string | null;
80
+ createdAt: string;
81
+ }[];
82
+ }>;
83
+ /** show(), children() and activity() of one record from a single record read. */
84
+ export declare function recordPage(ctx: ResourceContext, name: string, id: number, actor: Actor): Promise<{
85
+ children: Record<string, {
86
+ rows: SerializedRecord[];
87
+ hasMore: boolean;
88
+ related?: Record<string, SerializedRecord[]>;
89
+ }>;
90
+ activity: {
91
+ id: number;
92
+ action: Action;
93
+ fields: string[];
94
+ actorId: number;
95
+ actorName: string | null;
96
+ /**
97
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
98
+ * earlier releases still compile; they fall back to the actor id.
99
+ */
100
+ actorEmail: string | null;
101
+ createdAt: string;
102
+ }[];
103
+ data: SerializedRecord;
104
+ permissions: Partial<Record<Action | "restore", boolean>>;
105
+ related: Record<string, SerializedRecord[]>;
106
+ }>;
@@ -0,0 +1,327 @@
1
+ import { subject } from '@casl/ability';
2
+ import { columnName } from '../../resource/define_resource.js';
3
+ import { buildAbility, canRecord } from '../../auth/ability.js';
4
+ import { accessibleBy } from '../../auth/sql.js';
5
+ import { fromRow, serialize } from '../contracts.js';
6
+ import { AdulaError, notFound } from '../errors.js';
7
+ import { formatTitle, titleFields } from '../record_title.js';
8
+ import { authorizeAction, canQueryField, columns, fieldLevel, find, hydrate, permissions, requireRecord, } from './shared.js';
9
+ /** Project navigation is derived from registered resources and the current actor. */
10
+ export function navigation(ctx, actor) {
11
+ const { registry } = ctx;
12
+ const ability = buildAbility(actor.rules, registry.all());
13
+ const children = new Set(registry
14
+ .all()
15
+ .flatMap((resource) => Object.values(resource.fields).flatMap((field) => field.type === 'hasMany' ? [field.resource] : [])));
16
+ return registry
17
+ .all()
18
+ .filter((resource) => !children.has(resource.name) &&
19
+ resource.actions.includes('view') &&
20
+ (!resource.scoped || actor.orgPaths.length > 0) &&
21
+ ability.can('view', resource.name))
22
+ .map((resource) => ({
23
+ name: resource.name,
24
+ label: resource.label.ar,
25
+ href: `/resources/${resource.name}`,
26
+ module: registry.owner(resource.name),
27
+ moduleLabel: registry.modules().find((module) => module.name === registry.owner(resource.name))?.label
28
+ .ar ?? registry.owner(resource.name),
29
+ }));
30
+ }
31
+ export function describe(ctx, name, actor) {
32
+ const resource = ctx.registry.get(name);
33
+ const ability = authorizeAction(ctx, resource, actor, 'view');
34
+ const serialized = new Set(resource.serialize ?? [...resource.list, ...resource.show]);
35
+ const fields = Object.entries(resource.fields)
36
+ .filter(([key]) => serialized.has(key) &&
37
+ actor.permissionLevel >= fieldLevel(resource, key) &&
38
+ ability.can('view', name, key))
39
+ .map(([key, field]) => ({
40
+ ...field,
41
+ key,
42
+ sortable: Boolean(field.sortable && canQueryField(resource, actor, ability, key)),
43
+ filterable: Boolean(field.filterable && canQueryField(resource, actor, ability, key)),
44
+ }));
45
+ const visible = new Set(fields.map((field) => field.key));
46
+ const searchable = Object.entries(resource.fields).filter(([, field]) => field.searchable);
47
+ return {
48
+ name,
49
+ label: resource.label.ar,
50
+ recordLabel: resource.recordLabel?.ar ?? null,
51
+ createLabel: resource.createLabel?.ar ?? null,
52
+ fields,
53
+ list: resource.list.filter((key) => visible.has(key)),
54
+ show: resource.show.filter((key) => visible.has(key)),
55
+ searchable: searchable.length > 0 &&
56
+ searchable.every(([key]) => canQueryField(resource, actor, ability, key)),
57
+ canCreate: resource.actions.includes('create') && ability.can('create', name),
58
+ scoped: resource.scoped,
59
+ submittable: Boolean(resource.submittable),
60
+ trash: resource.actions.includes('delete') && ability.can('delete', name),
61
+ exportable: true,
62
+ bulk: ['delete', 'submit', 'cancel', 'update'].some((action) => resource.actions.includes(action) && ability.can(action, name)),
63
+ ...(resource.printTemplates?.length
64
+ ? {
65
+ printTemplates: resource.printTemplates.map((template) => ({
66
+ key: template.key,
67
+ label: template.label,
68
+ })),
69
+ }
70
+ : {}),
71
+ };
72
+ }
73
+ /** Authorizes one record for collaboration features; see ResourceService.access. */
74
+ export async function access(ctx, name, id, actor, action, db) {
75
+ let resource;
76
+ try {
77
+ resource = ctx.registry.get(name);
78
+ }
79
+ catch {
80
+ throw notFound('الكيان غير موجود');
81
+ }
82
+ if (!Number.isSafeInteger(id) || id <= 0)
83
+ throw notFound();
84
+ const ability = authorizeAction(ctx, resource, actor, action);
85
+ const record = await find(db, resource, actor, ability, id);
86
+ requireRecord(ability, actor, resource, action, record);
87
+ return { resource, record, ability };
88
+ }
89
+ /** Whether a (possibly other) actor may perform an action on a record; never throws for denial. */
90
+ export async function permits(ctx, name, id, actor, action) {
91
+ try {
92
+ await access(ctx, name, id, actor, action, ctx.db);
93
+ return true;
94
+ }
95
+ catch (error) {
96
+ if (error instanceof AdulaError && [403, 404].includes(error.status))
97
+ return false;
98
+ throw error;
99
+ }
100
+ }
101
+ /** Display rows of the users and related records referenced by the given records. */
102
+ export async function preload(ctx, resource, records, actor) {
103
+ const { db, registry } = ctx;
104
+ const related = {};
105
+ const ability = buildAbility(actor.rules, registry.all());
106
+ for (const [key, field] of Object.entries(resource.fields)) {
107
+ if (field.type === 'user' && records.length) {
108
+ const ids = records
109
+ .filter((record) => key in serialize(resource, record, ability, actor))
110
+ .map((record) => record[key])
111
+ .filter((v) => v !== null && v !== undefined);
112
+ // A display name only: readers of the record need not read account e-mails.
113
+ if (ids.length) {
114
+ const users = await db('users')
115
+ .whereIn('id', [...new Set(ids)])
116
+ .select('id', 'full_name');
117
+ related[key] = users.map((row) => ({
118
+ id: Number(row.id),
119
+ fullName: String(row.full_name ?? ''),
120
+ }));
121
+ }
122
+ continue;
123
+ }
124
+ if ((field.type !== 'belongsTo' && field.type !== 'manyToMany') || !records.length)
125
+ continue;
126
+ const target = registry.get(field.resource);
127
+ if (!ability.can('view', target.name))
128
+ continue;
129
+ const ids = records
130
+ .filter((record) => key in serialize(resource, record, ability, actor))
131
+ // A manyToMany value is an array of ids; its related rows title every link.
132
+ .flatMap((record) => record[key])
133
+ .filter((v) => v !== null && v !== undefined);
134
+ if (!ids.length)
135
+ continue;
136
+ const query = accessibleBy(db(`${target.name} as r`).whereIn('r.id', ids).whereNull('r.deleted_at'), ability, actor, 'view', target).select(columns(target, ability));
137
+ if (target.scoped)
138
+ query.select('ou.path as org_path');
139
+ const rows = await query;
140
+ const targets = await hydrate(db, target, rows.map((r) => fromRow(r, target)), ctx.attachments);
141
+ const title = await titler(ctx, target);
142
+ related[key] = targets.map((r) => {
143
+ const row = serialize(target, r, ability, actor);
144
+ // `_title` cannot collide with a field key; clients label the relation with it.
145
+ return { ...row, _title: title(row) };
146
+ });
147
+ }
148
+ return related;
149
+ }
150
+ /** Formats record titles of one resource, loading the labels of its title lookups once. */
151
+ export async function titler(ctx, resource) {
152
+ const groups = titleFields(resource).flatMap((key) => {
153
+ const field = resource.fields[key];
154
+ return field.type === 'lookup' ? [field.group] : [];
155
+ });
156
+ const labels = new Map();
157
+ if (groups.length)
158
+ for (const row of await ctx
159
+ .db('lookups')
160
+ .whereIn('group', groups)
161
+ .select('group', 'key', 'label_ar'))
162
+ labels.set(`${row.group}\u0000${row.key}`, String(row.label_ar));
163
+ return (record) => formatTitle(resource, record, (group, key) => labels.get(`${group}\u0000${key}`));
164
+ }
165
+ /** Titles of records the actor may view; see ResourceService.titles. */
166
+ export async function titles(ctx, name, ids, actor) {
167
+ const result = new Map();
168
+ let resource;
169
+ try {
170
+ resource = ctx.registry.get(name);
171
+ }
172
+ catch {
173
+ return result;
174
+ }
175
+ const wanted = [...new Set(ids.filter((id) => Number.isSafeInteger(id) && id > 0))];
176
+ const ability = buildAbility(actor.rules, ctx.registry.all());
177
+ if (!wanted.length || !resource.actions.includes('view') || !ability.can('view', name))
178
+ return result;
179
+ const query = accessibleBy(ctx.db(`${resource.name} as r`).whereIn('r.id', wanted).whereNull('r.deleted_at'), ability, actor, 'view', resource).select(columns(resource, ability));
180
+ if (resource.scoped)
181
+ query.select('ou.path as org_path');
182
+ const rows = await query;
183
+ const records = rows.map((row) => fromRow(row, resource));
184
+ const title = await titler(ctx, resource);
185
+ for (const record of records) {
186
+ if (!canRecord(ability, actor, resource, 'view', record))
187
+ continue;
188
+ const text = title(serialize(resource, record, ability, actor));
189
+ if (text)
190
+ result.set(Number(record.id), text);
191
+ }
192
+ return result;
193
+ }
194
+ /** One viewable record, authorized for the actor. */
195
+ async function viewable(ctx, name, id, actor) {
196
+ const resource = ctx.registry.get(name);
197
+ const ability = authorizeAction(ctx, resource, actor, 'view');
198
+ const record = await find(ctx.db, resource, actor, ability, id);
199
+ requireRecord(ability, actor, resource, 'view', record);
200
+ return { resource, ability, record };
201
+ }
202
+ /** The serialized record with its permissions and related rows. */
203
+ async function presented(ctx, resource, record, actor, ability) {
204
+ const [hydrated] = await hydrate(ctx.db, resource, [record], ctx.attachments);
205
+ return {
206
+ data: serialize(resource, hydrated, ability, actor),
207
+ permissions: permissions(resource, record, actor, ability),
208
+ related: await preload(ctx, resource, [record], actor),
209
+ };
210
+ }
211
+ export async function show(ctx, name, id, actor) {
212
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
213
+ return presented(ctx, resource, record, actor, ability);
214
+ }
215
+ /** Deferred relation reads re-authorize the parent and each child on every request. */
216
+ export async function recordChildren(ctx, name, id, actor) {
217
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
218
+ return childrenOf(ctx, resource, record, actor, ability);
219
+ }
220
+ /**
221
+ * The lines of a printed document (ADR 048): the named hasMany fields, up to `limit` rows
222
+ * each, with the display rows of the lines' own relations. See ResourceService.documentLines.
223
+ */
224
+ export async function documentLines(ctx, name, id, actor, keys, limit) {
225
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
226
+ return childrenOf(ctx, resource, record, actor, ability, keys, { limit, related: true });
227
+ }
228
+ /** Inline children of an already authorized parent record. */
229
+ async function childrenOf(ctx, resource, parent, actor, ability, keys = resource.show, options = {}) {
230
+ const name = resource.name;
231
+ const id = Number(parent.id);
232
+ const limit = options.limit ?? 100;
233
+ // A line group is readable where the record exposes it (serialize, or list and show),
234
+ // or where the resource's own code print templates declare it (ADR 048). Declaring a
235
+ // group in a code print template is the resource author exposing it like a detail field:
236
+ // children() returns it to any caller that names it, not only to printing (the record
237
+ // page itself names `show`).
238
+ const exposed = new Set([
239
+ ...(resource.serialize ?? [...resource.list, ...resource.show]),
240
+ ...(resource.printTemplates ?? []).flatMap((template) => Object.keys(template.lines ?? {})),
241
+ ]);
242
+ const result = {};
243
+ for (const key of keys) {
244
+ const field = resource.fields[key];
245
+ if (field?.type !== 'hasMany' ||
246
+ !ability.can('view', subject(name, parent), key) ||
247
+ actor.permissionLevel < fieldLevel(resource, key))
248
+ continue;
249
+ if (!exposed.has(key))
250
+ continue;
251
+ const child = ctx.registry.get(field.resource);
252
+ if (!ability.can('view', child.name) || !child.actions.includes('view'))
253
+ continue;
254
+ const rows = await accessibleBy(ctx.db(`${child.name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', child)
255
+ .where(`r.${child.fields[field.foreignKey].column ?? columnName(field.foreignKey)}`, id)
256
+ .select([...columns(child, ability), ...(child.scoped ? ['ou.path as org_path'] : [])])
257
+ .orderBy('r.id')
258
+ .limit(limit + 1);
259
+ const hydrated = await hydrate(ctx.db, child, rows.slice(0, limit).map((row) => fromRow(row, child)), ctx.attachments);
260
+ result[key] = {
261
+ rows: hydrated.map((row) => serialize(child, row, ability, actor)),
262
+ hasMore: rows.length > limit,
263
+ ...(options.related ? { related: await preload(ctx, child, hydrated, actor) } : {}),
264
+ };
265
+ }
266
+ return result;
267
+ }
268
+ /** Active lookup labels for the lookup fields the actor may read on this resource. */
269
+ export async function lookups(ctx, name, actor) {
270
+ const options = {};
271
+ for (const field of describe(ctx, name, actor).fields) {
272
+ if (field.type !== 'lookup')
273
+ continue;
274
+ const rows = await ctx
275
+ .db('lookups')
276
+ .where({ group: field.group, active: true })
277
+ .orderBy(['sort', 'id'])
278
+ .select('key', 'label_ar');
279
+ options[field.key] = rows.map((row) => ({ value: row.key, label: row.label_ar }));
280
+ }
281
+ return options;
282
+ }
283
+ /** The last 50 recorded mutations of one record, after authorizing the record itself. */
284
+ export async function activity(ctx, name, id, actor) {
285
+ await viewable(ctx, name, id, actor);
286
+ return activityOf(ctx, name, id);
287
+ }
288
+ /** Inline children and recent activity of one record from a single record read. */
289
+ export async function details(ctx, name, id, actor) {
290
+ const { resource, ability, record } = await viewable(ctx, name, id, actor);
291
+ return {
292
+ children: await childrenOf(ctx, resource, record, actor, ability),
293
+ activity: await activityOf(ctx, name, id),
294
+ };
295
+ }
296
+ /** show(), children() and activity() of one record from a single record read. */
297
+ export async function recordPage(ctx, name, id, actor) {
298
+ const { resource, ability, record: found } = await viewable(ctx, name, id, actor);
299
+ return {
300
+ ...(await presented(ctx, resource, found, actor, ability)),
301
+ children: await childrenOf(ctx, resource, found, actor, ability),
302
+ activity: await activityOf(ctx, name, id),
303
+ };
304
+ }
305
+ async function activityOf(ctx, name, id) {
306
+ const rows = await ctx
307
+ .db('activities as a')
308
+ .leftJoin('users as u', 'u.id', 'a.actor_id')
309
+ .where({ 'a.resource': name, 'a.record_id': id })
310
+ .orderBy('a.id', 'desc')
311
+ .limit(50)
312
+ .select('a.id', 'a.action', 'a.changes', 'a.actor_id', 'a.created_at', 'u.full_name as actor_name');
313
+ return rows.map((row) => ({
314
+ id: Number(row.id),
315
+ action: String(row.action),
316
+ fields: Array.isArray(row.changes?.fields) ? row.changes.fields : [],
317
+ actorId: Number(row.actor_id),
318
+ // A display name only: record viewers need not be able to read account e-mails.
319
+ actorName: row.actor_name ? String(row.actor_name) : null,
320
+ /**
321
+ * @deprecated Always null. Kept so project-owned copies of resource-show from
322
+ * earlier releases still compile; they fall back to the actor id.
323
+ */
324
+ actorEmail: null,
325
+ createdAt: new Date(row.created_at).toISOString(),
326
+ }));
327
+ }
@@ -0,0 +1,77 @@
1
+ import type { Knex } from 'knex';
2
+ import type { ResourceRegistry } from '../../resource/registry.js';
3
+ import type { Action, RecordData, Resource } from '../../resource/types.js';
4
+ import { type Actor, type AdulaAbility } from '../../auth/ability.js';
5
+ import { type AttachmentPreviewOptions } from '../../attachments/attachment_service.js';
6
+ import type { RecordPermissions } from '../presentation.js';
7
+ /**
8
+ * What every resource operation needs: the database and the registered resources, plus
9
+ * the deployment's attachment preview settings for the summaries readers receive.
10
+ */
11
+ export type ResourceContext = {
12
+ db: Knex;
13
+ registry: ResourceRegistry;
14
+ attachments?: AttachmentPreviewOptions;
15
+ };
16
+ /**
17
+ * The permission level an actor needs to see or write a field: its own permissionLevel,
18
+ * and at least 1 when the resource lists it as hidden.
19
+ */
20
+ export declare function fieldLevel(resource: Resource, key: string): number;
21
+ /**
22
+ * Whether an actor may sort, filter or search by a field. Querying reveals values
23
+ * indirectly, so it needs unconditional view access at the field's level.
24
+ */
25
+ export declare function canQueryField(resource: Resource, actor: Actor, ability: AdulaAbility, key: string): boolean;
26
+ /** The actor's ability, after checking the resource offers the action and the actor holds it. */
27
+ export declare function authorizeAction(ctx: ResourceContext, resource: Resource, actor: Actor, action: Action): AdulaAbility;
28
+ /** Live rows of a resource inside the actor's organization scope. */
29
+ export declare function scopedQuery(db: Knex, resource: Resource, actor: Actor): Knex.QueryBuilder<any, {
30
+ _base: any;
31
+ _hasSelection: false;
32
+ _keys: never;
33
+ _aliases: {};
34
+ _single: false;
35
+ _intersectProps: {};
36
+ _unionProps: never;
37
+ }[]>;
38
+ /** The qualified columns the ability may read (or write). */
39
+ export declare function columns(resource: Resource, ability: AdulaAbility, write?: boolean, extra?: string[]): string[];
40
+ /** One live record within the actor's scope; 404 otherwise. */
41
+ export declare function find(db: Knex, resource: Resource, actor: Actor, ability: AdulaAbility, id: number, lock?: boolean): Promise<RecordData>;
42
+ /**
43
+ * Adds the linked ids of every manyToMany field (ascending arrays) to records read
44
+ * from the resource's table, so policies, serialization and audits see them like
45
+ * column values. Mutates and returns the records.
46
+ */
47
+ export declare function withLinks(db: Knex, resource: Resource, records: RecordData[]): Promise<RecordData[]>;
48
+ /**
49
+ * Applies a filter on a field without a plain column comparison: a multiSelect contains
50
+ * the value, a manyToMany links the id. Returns false for other fields.
51
+ */
52
+ export declare function collectionFilter(query: Knex.QueryBuilder, resource: Resource, key: string, value: unknown): boolean;
53
+ /** A live record regardless of any actor's scope, for system writes. */
54
+ export declare function findAny(db: Knex, resource: Resource, id: number, lock?: boolean): Promise<RecordData>;
55
+ /** Scope (404) and conditional rules (403) of one loaded record. */
56
+ export declare function requireRecord(ability: AdulaAbility, actor: Actor, resource: Resource, action: Action, record: RecordData): void;
57
+ /** Which of the resource's actions the actor may take on one record now. */
58
+ export declare function permissions(resource: Resource, record: RecordData, actor: Actor, ability: AdulaAbility): RecordPermissions;
59
+ /** Coerces every present field value to its stored representation (422 E_FIELD_VALUE). */
60
+ export declare function normalizeValues(resource: Resource, record: RecordData): void;
61
+ /** Stored attachment ids become summaries for readers; copies keep policy checks on raw rows. */
62
+ export declare function hydrate(db: Knex, resource: Resource, records: RecordData[], options?: AttachmentPreviewOptions): Promise<RecordData[]>;
63
+ export declare function hydrateOne(db: Knex, resource: Resource, record: RecordData, options?: AttachmentPreviewOptions): Promise<RecordData>;
64
+ /**
65
+ * Active users eligible for a user field: members of the unit at `path` or of one of
66
+ * its ancestors, or (without a path) users sharing organization scope with the actor.
67
+ * A system write on an unscoped resource passes no actor: any active member qualifies.
68
+ */
69
+ export declare function eligibleUsers(db: Knex, path: string | null, actor: Actor | null): Knex.QueryBuilder<any, {
70
+ _base: any;
71
+ _hasSelection: true;
72
+ _keys: string;
73
+ _aliases: {};
74
+ _single: false;
75
+ _intersectProps: {};
76
+ _unionProps: never;
77
+ }[]>;