adula 2.0.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.
- package/README.md +149 -18
- package/build/agent/AGENTS.template.md +4 -4
- package/build/agent/capabilities.md +22 -11
- package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
- package/build/agent/skills/idea-review/SKILL.md +2 -2
- package/build/commands/adula_outbox.d.ts +10 -0
- package/build/commands/adula_outbox.js +11 -0
- package/build/commands/adula_restore_reconcile.d.ts +10 -0
- package/build/commands/adula_restore_reconcile.js +34 -0
- package/build/commands/adula_runtime_health.d.ts +10 -0
- package/build/commands/adula_runtime_health.js +27 -0
- package/build/commands/adula_uploads_prune.d.ts +10 -0
- package/build/commands/adula_uploads_prune.js +16 -0
- package/build/commands/app.d.ts +10 -0
- package/build/commands/app.js +64 -0
- package/build/commands/backup_create.d.ts +11 -0
- package/build/commands/backup_create.js +99 -0
- package/build/commands/backup_restore_files.d.ts +11 -0
- package/build/commands/backup_restore_files.js +44 -0
- package/build/commands/backup_restore_test.d.ts +12 -0
- package/build/commands/backup_restore_test.js +185 -0
- package/build/commands/backup_services.d.ts +31 -0
- package/build/commands/backup_services.js +6 -0
- package/build/commands/backup_verify.d.ts +9 -0
- package/build/commands/backup_verify.js +59 -0
- package/build/commands/backup_verify_snapshot.d.ts +10 -0
- package/build/commands/backup_verify_snapshot.js +37 -0
- package/build/commands/client.d.ts +16 -0
- package/build/commands/client.js +71 -0
- package/build/commands/doctor.js +4 -1
- package/build/commands/install.d.ts +8 -0
- package/build/commands/install.js +63 -45
- package/build/commands/main.d.ts +3 -2
- package/build/commands/main.js +26 -0
- package/build/commands/module_add.js +4 -20
- package/build/commands/resource.d.ts +2 -0
- package/build/commands/resource.js +12 -3
- package/build/commands/resource_migration.d.ts +15 -0
- package/build/commands/resource_migration.js +72 -0
- package/build/commands/resource_snapshot.d.ts +2 -0
- package/build/commands/resource_snapshot.js +3 -0
- package/build/commands/sla_evaluate.d.ts +14 -0
- package/build/commands/sla_evaluate.js +16 -0
- package/build/commands/ui.js +5 -3
- package/build/commands/ui_css.d.ts +9 -0
- package/build/commands/ui_css.js +19 -0
- package/build/commands/upgrade.d.ts +1 -1
- package/build/commands/upgrade.js +1 -1
- package/build/configure.js +1 -1
- package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
- package/build/database/migrations/1770000000020_two_factor.js +10 -0
- package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
- package/build/database/migrations/1770000000041_import_modes.js +10 -0
- package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
- package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
- package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
- package/build/database/migrations/1770000000043_notification_channels.js +10 -0
- package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
- package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
- package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
- package/build/database/migrations/1770000000045_import_leases.js +10 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
- package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
- package/build/database/migrations/1770000000049_print_templates.js +10 -0
- package/build/index.d.ts +56 -10
- package/build/index.js +34 -6
- package/build/providers/adula_provider.d.ts +2 -0
- package/build/providers/adula_provider.js +7 -0
- package/build/src/admin/contracts.js +1 -1
- package/build/src/admin/controller.d.ts +14 -1
- package/build/src/admin/controller.js +77 -13
- package/build/src/admin/errors.d.ts +32 -0
- package/build/src/admin/errors.js +63 -1
- package/build/src/admin/presentation.d.ts +21 -2
- package/build/src/admin/resource/editor.d.ts +59 -0
- package/build/src/admin/resource/editor.js +323 -0
- package/build/src/admin/resource/export.d.ts +37 -0
- package/build/src/admin/resource/export.js +181 -0
- package/build/src/admin/resource/lifecycle.d.ts +21 -0
- package/build/src/admin/resource/lifecycle.js +91 -0
- package/build/src/admin/resource/query.d.ts +100 -0
- package/build/src/admin/resource/query.js +508 -0
- package/build/src/admin/resource/read.d.ts +106 -0
- package/build/src/admin/resource/read.js +327 -0
- package/build/src/admin/resource/shared.d.ts +77 -0
- package/build/src/admin/resource/shared.js +222 -0
- package/build/src/admin/resource/trash.d.ts +10 -0
- package/build/src/admin/resource/trash.js +56 -0
- package/build/src/admin/resource/write.d.ts +57 -0
- package/build/src/admin/resource/write.js +574 -0
- package/build/src/admin/resource_service.d.ts +66 -193
- package/build/src/admin/resource_service.js +69 -1345
- package/build/src/attachments/attachment_service.d.ts +46 -2
- package/build/src/attachments/attachment_service.js +96 -4
- package/build/src/auth/conditions.d.ts +5 -0
- package/build/src/auth/conditions.js +26 -3
- package/build/src/auth/sql.js +17 -5
- package/build/src/auth/two_factor.d.ts +96 -0
- package/build/src/auth/two_factor.js +259 -0
- package/build/src/collaboration/assignments.d.ts +36 -1
- package/build/src/collaboration/assignments.js +132 -66
- package/build/src/collaboration/record_collaboration.d.ts +2 -3
- package/build/src/collaboration/record_collaboration.js +19 -16
- package/build/src/collaboration/shared.d.ts +16 -0
- package/build/src/collaboration/shared.js +21 -0
- package/build/src/commands/app_scaffold.d.ts +72 -0
- package/build/src/commands/app_scaffold.js +285 -0
- package/build/src/commands/capabilities.js +34 -8
- package/build/src/commands/doctor.d.ts +14 -2
- package/build/src/commands/doctor.js +50 -5
- package/build/src/commands/gap_report.d.ts +1 -1
- package/build/src/commands/gap_report.js +2 -2
- package/build/src/commands/generator.d.ts +37 -1
- package/build/src/commands/generator.js +61 -18
- package/build/src/commands/snapshot.d.ts +10 -13
- package/build/src/commands/snapshot.js +31 -14
- package/build/src/commands/source_markers.d.ts +10 -0
- package/build/src/commands/source_markers.js +29 -0
- package/build/src/core/activity.d.ts +2 -0
- package/build/src/core/activity.js +7 -1
- package/build/src/core/administrators.d.ts +38 -0
- package/build/src/core/administrators.js +129 -0
- package/build/src/core/html_sanitizer.d.ts +20 -0
- package/build/src/core/html_sanitizer.js +261 -0
- package/build/src/core/like.d.ts +5 -0
- package/build/src/core/like.js +5 -0
- package/build/src/core/lookups.d.ts +80 -0
- package/build/src/core/lookups.js +319 -0
- package/build/src/core/message_templates.d.ts +7 -2
- package/build/src/core/message_templates.js +72 -11
- package/build/src/core/module_seed.js +2 -1
- package/build/src/core/notification_channels.d.ts +235 -0
- package/build/src/core/notification_channels.js +660 -0
- package/build/src/core/roles.js +2 -2
- package/build/src/core/saved_views.d.ts +8 -1
- package/build/src/core/saved_views.js +36 -2
- package/build/src/core/sequences.d.ts +32 -0
- package/build/src/core/sequences.js +97 -0
- package/build/src/core/settings.d.ts +5 -0
- package/build/src/core/settings.js +19 -2
- package/build/src/core/template_language.d.ts +61 -0
- package/build/src/core/template_language.js +141 -0
- package/build/src/core/ui_preferences.d.ts +4 -0
- package/build/src/core/ui_preferences.js +4 -1
- package/build/src/core/user_invitations.d.ts +5 -1
- package/build/src/core/user_invitations.js +7 -1
- package/build/src/core/users.js +1 -1
- package/build/src/database/calendar_days.d.ts +19 -0
- package/build/src/database/calendar_days.js +36 -0
- package/build/src/database/schema.d.ts +155 -2
- package/build/src/database/schema.js +531 -59
- package/build/src/database/schema_diff.d.ts +56 -0
- package/build/src/database/schema_diff.js +157 -0
- package/build/src/events/record_mutation.d.ts +2 -1
- package/build/src/events/record_mutation.js +1 -0
- package/build/src/integrations/api_client.d.ts +37 -0
- package/build/src/integrations/api_client.js +552 -0
- package/build/src/integrations/import_adapters.d.ts +37 -0
- package/build/src/integrations/import_adapters.js +35 -0
- package/build/src/integrations/imports.d.ts +118 -16
- package/build/src/integrations/imports.js +406 -73
- package/build/src/integrations/openapi.d.ts +3 -1
- package/build/src/integrations/openapi.js +454 -31
- package/build/src/integrations/outbound.d.ts +51 -0
- package/build/src/integrations/outbound.js +195 -0
- package/build/src/integrations/print.d.ts +21 -1
- package/build/src/integrations/print.js +63 -21
- package/build/src/integrations/print_templates.d.ts +216 -0
- package/build/src/integrations/print_templates.js +1015 -0
- package/build/src/integrations/sync_jobs.d.ts +139 -0
- package/build/src/integrations/sync_jobs.js +416 -0
- package/build/src/integrations/webhooks.d.ts +12 -12
- package/build/src/integrations/webhooks.js +34 -43
- package/build/src/languages/ar.d.ts +11 -0
- package/build/src/languages/ar.js +336 -0
- package/build/src/languages/ar_ui.d.ts +332 -0
- package/build/src/languages/ar_ui.js +333 -0
- package/build/src/languages/catalog.d.ts +66 -0
- package/build/src/languages/catalog.js +152 -0
- package/build/src/languages/en.d.ts +7 -0
- package/build/src/languages/en.js +330 -0
- package/build/src/languages/en_ui.d.ts +3 -0
- package/build/src/languages/en_ui.js +328 -0
- package/build/src/languages/validation.d.ts +26 -0
- package/build/src/languages/validation.js +60 -0
- package/build/src/lists/bulk_actions.d.ts +89 -0
- package/build/src/lists/bulk_actions.js +268 -0
- package/build/src/lists/dashboards.d.ts +96 -0
- package/build/src/lists/dashboards.js +241 -0
- package/build/src/mcp/tools.js +1 -1
- package/build/src/resource/define_resource.d.ts +18 -1
- package/build/src/resource/define_resource.js +205 -18
- package/build/src/resource/definition.d.ts +44 -0
- package/build/src/resource/definition.js +171 -0
- package/build/src/resource/registry.js +15 -4
- package/build/src/resource/types.d.ts +304 -16
- package/build/src/resource/values.d.ts +56 -1
- package/build/src/resource/values.js +237 -5
- package/build/src/services/settings.d.ts +2 -0
- package/build/src/services/settings.js +5 -1
- package/build/src/upgrade/legacy.js +2 -2
- package/build/src/workflows/calendar.d.ts +9 -0
- package/build/src/workflows/calendar.js +44 -0
- package/build/src/workflows/define_workflow.d.ts +48 -3
- package/build/src/workflows/define_workflow.js +57 -13
- package/build/src/workflows/delegations.d.ts +93 -0
- package/build/src/workflows/delegations.js +287 -0
- package/build/src/workflows/engine.d.ts +69 -4
- package/build/src/workflows/engine.js +441 -83
- package/build/src/workflows/sla.d.ts +15 -0
- package/build/src/workflows/sla.js +8 -0
- package/build/stubs/resource_contract.txt +12 -1
- package/package.json +5 -2
|
@@ -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
|
+
}[]>;
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { columnName, joinTable } from '../../resource/define_resource.js';
|
|
2
|
+
import { buildAbility, canRecord, inOrgScope, } from '../../auth/ability.js';
|
|
3
|
+
import { conditionSql } from '../../auth/sql.js';
|
|
4
|
+
import { fromRow, selectedFields } from '../contracts.js';
|
|
5
|
+
import { AdulaError, forbiddenAction, notFound } from '../errors.js';
|
|
6
|
+
import { fieldValue, isMultipleAttachment } from '../../resource/values.js';
|
|
7
|
+
import { isAttachmentId, loadAttachments, } from '../../attachments/attachment_service.js';
|
|
8
|
+
/**
|
|
9
|
+
* The permission level an actor needs to see or write a field: its own permissionLevel,
|
|
10
|
+
* and at least 1 when the resource lists it as hidden.
|
|
11
|
+
*/
|
|
12
|
+
export function fieldLevel(resource, key) {
|
|
13
|
+
return Math.max(resource.fields[key].permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Whether an actor may sort, filter or search by a field. Querying reveals values
|
|
17
|
+
* indirectly, so it needs unconditional view access at the field's level.
|
|
18
|
+
*/
|
|
19
|
+
export function canQueryField(resource, actor, ability, key) {
|
|
20
|
+
const level = fieldLevel(resource, key);
|
|
21
|
+
// Conditional field rules cannot safely authorize a global sort/search.
|
|
22
|
+
return (actor.permissionLevel >= level &&
|
|
23
|
+
ability.can('view', resource.name, key) &&
|
|
24
|
+
!ability.rules.some((rule) => rule.conditions &&
|
|
25
|
+
(!rule.fields || rule.fields.includes(key)) &&
|
|
26
|
+
(rule.subject === resource.name || rule.subject === 'all')));
|
|
27
|
+
}
|
|
28
|
+
/** The actor's ability, after checking the resource offers the action and the actor holds it. */
|
|
29
|
+
export function authorizeAction(ctx, resource, actor, action) {
|
|
30
|
+
const ability = buildAbility(actor.rules, ctx.registry.all());
|
|
31
|
+
if (!resource.actions.includes(action) || !ability.can(action, resource.name))
|
|
32
|
+
throw forbiddenAction();
|
|
33
|
+
for (const rule of ability.rulesFor(action, resource.name))
|
|
34
|
+
conditionSql(rule.conditions, resource);
|
|
35
|
+
return ability;
|
|
36
|
+
}
|
|
37
|
+
/** Live rows of a resource inside the actor's organization scope. */
|
|
38
|
+
export function scopedQuery(db, resource, actor) {
|
|
39
|
+
const query = db(`${resource.name} as r`).whereNull('r.deleted_at');
|
|
40
|
+
if (resource.scoped) {
|
|
41
|
+
query.join('org_units as ou', 'ou.id', 'r.org_unit_id').where((scope) => {
|
|
42
|
+
if (!actor.orgPaths.length)
|
|
43
|
+
scope.whereRaw('FALSE');
|
|
44
|
+
actor.orgPaths.forEach((path) => scope.orWhereRaw('ou.path <@ ?::ltree', [path]));
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return query;
|
|
48
|
+
}
|
|
49
|
+
/** The qualified columns the ability may read (or write). */
|
|
50
|
+
export function columns(resource, ability, write = false, extra = []) {
|
|
51
|
+
return selectedFields(resource, ability, { write, extra }).map((key) => `r.${resource.fields[key]?.column ?? columnName(key)}`);
|
|
52
|
+
}
|
|
53
|
+
/** One live record within the actor's scope; 404 otherwise. */
|
|
54
|
+
export async function find(db, resource, actor, ability, id, lock = false) {
|
|
55
|
+
const query = scopedQuery(db, resource, actor)
|
|
56
|
+
.where('r.id', id)
|
|
57
|
+
.select(columns(resource, ability, lock));
|
|
58
|
+
if (resource.scoped)
|
|
59
|
+
query.select('ou.path as org_path');
|
|
60
|
+
if (lock)
|
|
61
|
+
query.forUpdate('r');
|
|
62
|
+
const row = await query.first();
|
|
63
|
+
if (!row)
|
|
64
|
+
throw notFound();
|
|
65
|
+
const [record] = await withLinks(db, resource, [fromRow(row, resource)]);
|
|
66
|
+
return record;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Adds the linked ids of every manyToMany field (ascending arrays) to records read
|
|
70
|
+
* from the resource's table, so policies, serialization and audits see them like
|
|
71
|
+
* column values. Mutates and returns the records.
|
|
72
|
+
*/
|
|
73
|
+
export async function withLinks(db, resource, records) {
|
|
74
|
+
if (!records.length)
|
|
75
|
+
return records;
|
|
76
|
+
for (const [key, field] of Object.entries(resource.fields)) {
|
|
77
|
+
if (field.type !== 'manyToMany')
|
|
78
|
+
continue;
|
|
79
|
+
const join = joinTable(resource.name, key, field);
|
|
80
|
+
const rows = await db(join.table)
|
|
81
|
+
.whereIn(join.owner, records.map((record) => Number(record.id)))
|
|
82
|
+
.orderBy(join.target)
|
|
83
|
+
.select(`${join.owner} as owner`, `${join.target} as target`);
|
|
84
|
+
const links = new Map();
|
|
85
|
+
for (const row of rows) {
|
|
86
|
+
const list = links.get(Number(row.owner)) ?? [];
|
|
87
|
+
list.push(Number(row.target));
|
|
88
|
+
links.set(Number(row.owner), list);
|
|
89
|
+
}
|
|
90
|
+
for (const record of records)
|
|
91
|
+
record[key] = links.get(Number(record.id)) ?? [];
|
|
92
|
+
}
|
|
93
|
+
return records;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Applies a filter on a field without a plain column comparison: a multiSelect contains
|
|
97
|
+
* the value, a manyToMany links the id. Returns false for other fields.
|
|
98
|
+
*/
|
|
99
|
+
export function collectionFilter(query, resource, key, value) {
|
|
100
|
+
const field = resource.fields[key];
|
|
101
|
+
if (field?.type === 'multiSelect') {
|
|
102
|
+
const column = `r.${field.column ?? columnName(key)}`;
|
|
103
|
+
if (value === null)
|
|
104
|
+
query.where((q) => q.whereNull(column).orWhereRaw("?? = '[]'::jsonb", [column]));
|
|
105
|
+
else
|
|
106
|
+
query.whereRaw('?? @> ?::jsonb', [column, JSON.stringify([value])]);
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
if (field?.type === 'manyToMany') {
|
|
110
|
+
const join = joinTable(resource.name, key, field);
|
|
111
|
+
const links = (exists) => {
|
|
112
|
+
exists.from(join.table).whereRaw('?? = r.id', [`${join.table}.${join.owner}`]);
|
|
113
|
+
if (value !== null)
|
|
114
|
+
exists.where(`${join.table}.${join.target}`, value);
|
|
115
|
+
};
|
|
116
|
+
if (value === null)
|
|
117
|
+
query.whereNotExists(links);
|
|
118
|
+
else
|
|
119
|
+
query.whereExists(links);
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
/** A live record regardless of any actor's scope, for system writes. */
|
|
125
|
+
export async function findAny(db, resource, id, lock = false) {
|
|
126
|
+
const query = db(`${resource.name} as r`).whereNull('r.deleted_at').where('r.id', id);
|
|
127
|
+
query.select(selectedFields(resource, buildAbility([], []), { write: true }).map((key) => `r.${resource.fields[key]?.column ?? columnName(key)}`));
|
|
128
|
+
if (resource.scoped)
|
|
129
|
+
query.leftJoin('org_units as ou', 'ou.id', 'r.org_unit_id').select('ou.path as org_path');
|
|
130
|
+
if (lock)
|
|
131
|
+
query.forUpdate('r');
|
|
132
|
+
const row = await query.first();
|
|
133
|
+
if (!row)
|
|
134
|
+
throw notFound();
|
|
135
|
+
const [record] = await withLinks(db, resource, [fromRow(row, resource)]);
|
|
136
|
+
return record;
|
|
137
|
+
}
|
|
138
|
+
/** Scope (404) and conditional rules (403) of one loaded record. */
|
|
139
|
+
export function requireRecord(ability, actor, resource, action, record) {
|
|
140
|
+
if (resource.scoped && !inOrgScope(record.orgPath, actor.orgPaths))
|
|
141
|
+
throw notFound();
|
|
142
|
+
if (!canRecord(ability, actor, resource, action, record))
|
|
143
|
+
throw forbiddenAction();
|
|
144
|
+
}
|
|
145
|
+
/** Which of the resource's actions the actor may take on one record now. */
|
|
146
|
+
export function permissions(resource, record, actor, ability) {
|
|
147
|
+
return Object.fromEntries(resource.actions.map((action) => [
|
|
148
|
+
action,
|
|
149
|
+
canRecord(ability, actor, resource, action, record) &&
|
|
150
|
+
(!resource.submittable ||
|
|
151
|
+
!['update', 'delete', 'submit'].includes(action) ||
|
|
152
|
+
record.docStatus === 0) &&
|
|
153
|
+
(action !== 'cancel' || (resource.submittable && record.docStatus === 1)) &&
|
|
154
|
+
(action !== 'amend' || (resource.submittable && record.docStatus === 2)),
|
|
155
|
+
]));
|
|
156
|
+
}
|
|
157
|
+
/** Coerces every present field value to its stored representation (422 E_FIELD_VALUE). */
|
|
158
|
+
export function normalizeValues(resource, record) {
|
|
159
|
+
for (const [key, field] of Object.entries(resource.fields)) {
|
|
160
|
+
if (!(key in record))
|
|
161
|
+
continue;
|
|
162
|
+
try {
|
|
163
|
+
record[key] = fieldValue(field, record[key]);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
throw new AdulaError(422, 'E_FIELD_VALUE', `${key}: ${error.message}`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** Stored attachment ids become summaries for readers; copies keep policy checks on raw rows. */
|
|
171
|
+
export async function hydrate(db, resource, records, options = {}) {
|
|
172
|
+
const keys = Object.keys(resource.fields).filter((key) => resource.fields[key].type === 'attachment');
|
|
173
|
+
if (!keys.length || !records.length)
|
|
174
|
+
return records;
|
|
175
|
+
// A multiple field holds an ordered array of ids: its summaries keep that order.
|
|
176
|
+
const ids = records.flatMap((record) => keys.flatMap((key) => (Array.isArray(record[key]) ? record[key] : [record[key]])));
|
|
177
|
+
const summaries = await loadAttachments(db, ids.filter(isAttachmentId), options);
|
|
178
|
+
return records.map((record) => {
|
|
179
|
+
const copy = { ...record };
|
|
180
|
+
for (const key of keys) {
|
|
181
|
+
if (!(key in copy))
|
|
182
|
+
continue;
|
|
183
|
+
const value = copy[key];
|
|
184
|
+
if (isMultipleAttachment(resource.fields[key]))
|
|
185
|
+
copy[key] = (Array.isArray(value) ? value : [])
|
|
186
|
+
.map((id) => (isAttachmentId(id) ? summaries.get(id) : undefined))
|
|
187
|
+
.filter((summary) => summary !== undefined);
|
|
188
|
+
else
|
|
189
|
+
copy[key] = isAttachmentId(value) ? (summaries.get(value) ?? null) : null;
|
|
190
|
+
}
|
|
191
|
+
return copy;
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
export async function hydrateOne(db, resource, record, options = {}) {
|
|
195
|
+
const [hydrated] = await hydrate(db, resource, [record], options);
|
|
196
|
+
return hydrated;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Active users eligible for a user field: members of the unit at `path` or of one of
|
|
200
|
+
* its ancestors, or (without a path) users sharing organization scope with the actor.
|
|
201
|
+
* A system write on an unscoped resource passes no actor: any active member qualifies.
|
|
202
|
+
*/
|
|
203
|
+
export function eligibleUsers(db, path, actor) {
|
|
204
|
+
return db('users as u')
|
|
205
|
+
.whereNull('u.disabled_at')
|
|
206
|
+
.whereExists((members) => {
|
|
207
|
+
members
|
|
208
|
+
.from('user_org_units as m')
|
|
209
|
+
.join('org_units as o', 'o.id', 'm.org_unit_id')
|
|
210
|
+
.whereRaw('m.user_id = u.id');
|
|
211
|
+
if (path !== null)
|
|
212
|
+
members.whereRaw('?::ltree <@ o.path', [path]);
|
|
213
|
+
else if (actor)
|
|
214
|
+
members.where((scope) => {
|
|
215
|
+
if (!actor.orgPaths.length)
|
|
216
|
+
scope.whereRaw('FALSE');
|
|
217
|
+
for (const own of actor.orgPaths)
|
|
218
|
+
scope.orWhereRaw('o.path <@ ?::ltree', [own]).orWhereRaw('o.path @> ?::ltree', [own]);
|
|
219
|
+
});
|
|
220
|
+
})
|
|
221
|
+
.distinct();
|
|
222
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
import type { Actor } from '../../auth/ability.js';
|
|
3
|
+
import { type ResourceContext } from './shared.js';
|
|
4
|
+
/**
|
|
5
|
+
* Clears deleted_at of a soft-deleted record; see ResourceService.restore. Restore is
|
|
6
|
+
* authorized by the actor's delete rule (ADR 046): the resource must offer delete, the
|
|
7
|
+
* actor must hold it, and its conditions and organization scope are evaluated on the
|
|
8
|
+
* deleted record (404 outside the scope, 403 when a condition refuses).
|
|
9
|
+
*/
|
|
10
|
+
export declare function restore(ctx: ResourceContext, name: string, id: number, actor: Actor, transaction?: Knex.Transaction): Promise<import("../../resource/types.js").SerializedRecord>;
|