odant-work 1.0.83 → 1.0.85

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.
@@ -714,24 +714,54 @@ export async function getNodeStaffContext(storage, params = {}) {
714
714
  if (!WORK)
715
715
  return { users: [], structures: [], networkNodes: [], inheritedBoss: null, baseClasses: [], systemModules: [], basePath: '' };
716
716
 
717
- // 1. Пользователи /USERS
717
+ // 1. Пользователи /USERS (плоский список + иерархия, если есть подпапки)
718
718
  const users = [];
719
+ const usersTree = [];
719
720
  const userMap = new Map();
720
721
  const uRoot = (await WORK.get_item('/USERS').catch(() => null)) || (await WORK.get_item('/users').catch(() => null));
721
- const uItems = await Promise.resolve(uRoot?.items).catch(() => []) || [];
722
- for (const u of uItems) {
723
- if (!u?.id || u.id[0] === '$')
724
- continue;
725
- await u.init?.catch?.(() => {});
726
- const entry = {
727
- id: u.id,
728
- label: u.DATA?.label || u.label || u.id,
729
- icon: u.DATA?.icon || u.icon || '',
730
- iconColor: u.iconColor || '',
731
- };
732
- users.push(entry);
733
- userMap.set(u.id, entry);
734
- }
722
+ const walkUsers = async (container, depth = 0) => {
723
+ if (!container || depth > 4)
724
+ return [];
725
+ const items = await Promise.resolve(container.items).catch(() => []) || [];
726
+ const out = [];
727
+ for (const u of items) {
728
+ if (!u?.id || u.id[0] === '$')
729
+ continue;
730
+ await u.init?.catch?.(() => {});
731
+ const t = u.type;
732
+ if (t === '$user' || (!t && !u.items)) {
733
+ const entry = {
734
+ id: u.id,
735
+ path: u.path || `/USERS/${u.id}`,
736
+ type: '$user',
737
+ label: u.DATA?.label || u.label || u.id,
738
+ icon: u.DATA?.icon || u.icon || '',
739
+ iconColor: u.iconColor || '',
740
+ children: [],
741
+ };
742
+ users.push({ id: entry.id, label: entry.label, icon: entry.icon, iconColor: entry.iconColor });
743
+ userMap.set(entry.id, entry);
744
+ out.push(entry);
745
+ }
746
+ else if (['$domain', '$folder', '$group', '$structure'].includes(t)) {
747
+ const children = await walkUsers(u, depth + 1);
748
+ if (children.length) {
749
+ out.push({
750
+ id: u.id,
751
+ path: u.path || '',
752
+ type: t,
753
+ label: u.DATA?.label || u.label || u.id,
754
+ icon: u.DATA?.icon || u.icon || 'odant:folder',
755
+ iconColor: '',
756
+ children,
757
+ });
758
+ }
759
+ }
760
+ }
761
+ return out;
762
+ };
763
+ if (uRoot)
764
+ usersTree.push(...await walkUsers(uRoot, 0));
735
765
 
736
766
  // 2. Унаследованный руководитель (BOSS) вверх по дереву (включая корень '/')
737
767
  let inheritedBoss = null;
@@ -753,7 +783,7 @@ export async function getNodeStaffContext(storage, params = {}) {
753
783
  const resolved = cleanIds.slice(0, 1).map(uid => {
754
784
  const found = userMap.get(uid);
755
785
  return found
756
- ? { ...found, missing: false }
786
+ ? { id: found.id, label: found.label, icon: found.icon, iconColor: found.iconColor, missing: false }
757
787
  : { id: uid, label: `${uid} (не найден в /USERS)`, icon: 'icons:person', iconColor: '', missing: true };
758
788
  });
759
789
  const ancPath = anc.path || '/';
@@ -768,14 +798,73 @@ export async function getNodeStaffContext(storage, params = {}) {
768
798
  }
769
799
  catch { /* ignore */ }
770
800
 
771
- // 3. Подразделения и серверы сети
772
- const [structRes, netRes] = await Promise.all([
773
- listNodeStructures(storage, params).catch(() => ({ structures: [] })),
801
+ // 3. Подразделения (деревья /ORGANIZATIONS и /PROJECTS + плоский structures) и серверы сети
802
+ const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
803
+ const flatStructures = [];
804
+ const seenStructPaths = new Set();
805
+ const walkStructureDomain = async (domainPath) => {
806
+ const rootNode = await WORK.get_item(domainPath).catch(() => null);
807
+ if (!rootNode)
808
+ return [];
809
+ const visit = async (node, depth = 0) => {
810
+ if (!node || depth > 5)
811
+ return null;
812
+ await node.init?.catch?.(() => {});
813
+ if (!node.id || node.id[0] === '$')
814
+ return null;
815
+ if (!['$base', '$project', '$structure'].includes(node.type))
816
+ return null;
817
+ // Проверяем видимость для текущего пользователя (не показываем чужие скрытые организации)
818
+ if (typeof node.canSee === 'function') {
819
+ const ok = await node.canSee(node, params).catch(() => false);
820
+ if (!ok)
821
+ return null;
822
+ }
823
+ const p = String(node.path || '').replace(/\/+$/, '') || '/';
824
+ const entry = {
825
+ id: node.id,
826
+ path: p,
827
+ label: node.DATA?.label || node.label || node.id,
828
+ type: node.type,
829
+ icon: node.DATA?.icon || node.icon || (node.type === '$base' ? 'odant:base' : node.type === '$project' ? 'odant:project' : 'odant:structure'),
830
+ isSelf: p === selfPath,
831
+ children: [],
832
+ };
833
+ if (p !== selfPath && !seenStructPaths.has(p)) {
834
+ seenStructPaths.add(p);
835
+ flatStructures.push({ path: p, id: entry.id, label: entry.label, type: entry.type, icon: entry.icon });
836
+ }
837
+ const items = await Promise.resolve(node.items).catch(() => []) || [];
838
+ for (const ch of items) {
839
+ if (!ch || ch.id?.[0] === '$')
840
+ continue;
841
+ await ch.init?.catch?.(() => {});
842
+ if (['$base', '$project', '$structure'].includes(ch.type)) {
843
+ const built = await visit(ch, depth + 1);
844
+ if (built)
845
+ entry.children.push(built);
846
+ }
847
+ }
848
+ return entry;
849
+ };
850
+ const items = await Promise.resolve(rootNode.items).catch(() => []) || [];
851
+ const res = [];
852
+ for (const ch of items) {
853
+ if (!ch || ch.id?.[0] === '$')
854
+ continue;
855
+ const built = await visit(ch, 0);
856
+ if (built)
857
+ res.push(built);
858
+ }
859
+ return res;
860
+ };
861
+ const [organizationsTree, projectsTree, netRes] = await Promise.all([
862
+ walkStructureDomain('/ORGANIZATIONS').catch(() => []),
863
+ walkStructureDomain('/PROJECTS').catch(() => []),
774
864
  listNodeNetworkNodes(storage, params).catch(() => ({ nodes: [] })),
775
865
  ]);
776
866
 
777
867
  // 4. Полное дерево всех классов, установленных в вышестоящий $base ($project)
778
- const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
779
868
  const baseMatch = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
780
869
  const basePath = baseMatch ? baseMatch[1] : '';
781
870
  const modRootPath = basePath ? `${basePath}/MODULES` : '/MODULES';
@@ -846,7 +935,10 @@ export async function getNodeStaffContext(storage, params = {}) {
846
935
 
847
936
  return {
848
937
  users,
849
- structures: structRes.structures || [],
938
+ usersTree,
939
+ structures: flatStructures,
940
+ organizationsTree,
941
+ projectsTree,
850
942
  networkNodes: netRes.nodes || [],
851
943
  inheritedBoss,
852
944
  basePath,
@@ -153,6 +153,8 @@ export async function verifyNodeRequest(request) {
153
153
  const principal = Object.freeze({
154
154
  kind: 'node',
155
155
  id: nodeId,
156
+ nodePath: node.item?.path || '',
157
+ actorId: actor || '',
156
158
  actor: actor ? actor + '@' + nodeId : undefined,
157
159
  actorLabel: actorLabel || undefined,
158
160
  roles: Object.freeze(roles),
@@ -21,21 +21,24 @@ const STRUCTURE_METAS = WORKPLACES.STRUCTURE_META_NAMES;
21
21
 
22
22
  const SKIP_DIRS = new Set(['node_modules', '.git', '.svn', 'sources', 'oda', 'tests', 'docs', 'torus', 'DATA', 'INDEX', 'logs']);
23
23
 
24
- let cache = null;
24
+ let setsCache = null;
25
25
  let structCache = null;
26
26
 
27
27
  /** Сбросить реестр (после save структуры). */
28
28
  export function reset() {
29
- cache = null;
29
+ setsCache = null;
30
30
  structCache = null;
31
31
  }
32
32
 
33
- /** Все ссылки всех подразделений: [{ structure, place, id, access, scope? }].
34
- * place — путь места в дереве ROLES ('heads/ceo'), null — общая ссылка #security.LINKS;
35
- * scope — видимость данных по ссылке, без него — умолчание по типу класса (sources/data/scope.js). */
36
- async function collect() {
37
- if (cache)
38
- return cache;
33
+ /**
34
+ * Все наборы ссылок подразделений:
35
+ * [{ structure, place, external, links: [{ id, access, scope? }] }].
36
+ * Хранение наборами (по ролям) позволяет вычислять эффективный доступ внутри каждой роли
37
+ * по правилу наиболее специфичного пути (переопределение вниз, вплоть до `none`).
38
+ */
39
+ async function collectSets() {
40
+ if (setsCache)
41
+ return setsCache;
39
42
  const out = [];
40
43
  const structs = new Set();
41
44
  const root = process.cwd();
@@ -72,12 +75,13 @@ async function collect() {
72
75
  continue;
73
76
  structs.add(clsPath);
74
77
  const { common, places } = WORKPLACES.normalizeSecurity(g.DATA?.['#security']);
75
- for (const l of common)
76
- out.push({ structure: clsPath, place: null, id: l.id, access: l.access, ...(l.scope ? { scope: l.scope } : {}) });
78
+ if (common.length)
79
+ out.push({ structure: clsPath, place: null, external: false, links: common });
77
80
  for (const { node, trail } of WORKPLACES.walkPlaces(places)) {
81
+ if (!node.LINKS.length)
82
+ continue;
78
83
  const place = WORKPLACES.trailKey(trail);
79
- for (const l of node.LINKS)
80
- out.push({ structure: clsPath, place, id: l.id, access: l.access, ...(l.scope ? { scope: l.scope } : {}), ...(node.external ? { external: true } : {}) });
84
+ out.push({ structure: clsPath, place, external: Boolean(node.external), links: node.LINKS });
81
85
  }
82
86
  }
83
87
  catch { /* нет доступа */ }
@@ -86,81 +90,100 @@ async function collect() {
86
90
  stack.push(sub);
87
91
  }
88
92
  }
89
- cache = out;
93
+ setsCache = out;
90
94
  structCache = [...structs];
91
95
  return out;
92
96
  }
93
97
 
94
98
  async function collectStructures() {
95
99
  if (!structCache)
96
- await collect();
100
+ await collectSets();
97
101
  return structCache || [];
98
102
  }
99
103
 
100
- /** Ссылки, покрывающие путь (на класс или его предка). */
101
- export async function covering(path) {
102
- const p = String(path || '');
104
+ /** Ссылки, эффективно покрывающие путь (с учётом переопределений вниз и исключений `none`). */
105
+ export async function covering(clsPath) {
106
+ const p = String(clsPath || '');
103
107
  if (!p.startsWith('/'))
104
108
  return [];
105
- return (await collect()).filter(e => p === e.id || p.startsWith(e.id + '/'));
109
+ const out = [];
110
+ for (const set of await collectSets()) {
111
+ const eff = WORKPLACES.resolveLinkInSet(set.links, p);
112
+ if (!eff || eff.access === 'none')
113
+ continue;
114
+ out.push({
115
+ structure: set.structure,
116
+ place: set.place,
117
+ id: eff.link.id,
118
+ access: eff.access,
119
+ ...(eff.link.scope ? { scope: eff.link.scope } : {}),
120
+ ...(set.external ? { external: true } : {}),
121
+ });
122
+ }
123
+ return out;
106
124
  }
107
125
 
108
- const rank = { read: 1, write: 2, admin: 3 };
126
+ const rank = WORKPLACES.ACCESS_RANK;
109
127
 
110
128
  function takeRank(best, level) {
111
- return level && (rank[level] || 0) > (rank[best] || 0) ? level : best;
129
+ if (!level || level === 'none')
130
+ return best;
131
+ return (rank[level] || 0) > (rank[best] || 0) ? level : best;
112
132
  }
113
133
 
114
134
  /**
115
- * Уровень доступа по ссылкам подразделений (без прямых назначений).
116
- * Ссылка действует на класс и его поддерево, кроме структурных типов.
117
- * Место даёт свой access участникам; вышестоящее место и BOSS видят
118
- * ссылки вложенных мест на чтение; общая ссылка — всем назначенным.
135
+ * Единый субъект проверки прав по ссылкам (учитывает локального пользователя,
136
+ * цифровой двойник подразделения и удалённые субъекты /NODES).
119
137
  */
120
138
  function linkSubject(cls, params = {}) {
121
- const uid = cls.constructor.resolveUid(params);
122
- const nodePath = params?.session?.twinCall?.fromPath || '';
123
- const nodeOnly = Boolean(params?.session?.twinRoleOnly);
124
- return nodePath ? { uid, nodePath, nodeOnly } : uid;
139
+ return WORKPLACES.buildSubject(cls.constructor.resolveUid(params), params);
125
140
  }
126
141
 
142
+ /**
143
+ * Уровень доступа по ссылкам подразделений (без прямых назначений):
144
+ * 'read' | 'write' | 'create' | 'delete' | 'admin' | null.
145
+ * Внутри одной роли действует правило наиболее специфичного пути (переопределение вниз, вплоть до `none`);
146
+ * между разными ролями права объединяются по максимуму.
147
+ */
127
148
  export async function linkLevel(cls, params = {}) {
128
149
  if (NO_LINK_TYPES.has(cls.type))
129
150
  return null;
130
151
  const subject = linkSubject(cls, params);
131
- const uid = cls.constructor.resolveUid(params);
152
+ const seenStruct = new Map();
132
153
  let best = null;
133
154
  for (const { structure, place, access } of await covering(cls.path)) {
134
- let g;
135
- try {
136
- g = await globalThis.WORK.get_item(structure);
155
+ if (!seenStruct.has(structure)) {
156
+ seenStruct.set(structure, (async () => {
157
+ const g = await structureItem(structure);
158
+ if (!g)
159
+ return null;
160
+ const roles = await g.roles(params).catch(() => []);
161
+ if (!roles.length)
162
+ return null;
163
+ const sec = g.DATA?.['#security'];
164
+ return { roles, sec, memberTrails: WORKPLACES.memberTrailKeys(sec, subject) };
165
+ })());
137
166
  }
138
- catch { continue; }
139
- if (Array.isArray(g))
140
- g = g.at(-1);
141
- if (!(g instanceof FS.$class))
142
- continue;
143
- const roles = await g.roles(params).catch(() => []);
144
- if (!roles.length)
167
+ const s = await seenStruct.get(structure);
168
+ if (!s)
145
169
  continue;
146
- const sec = g.DATA?.['#security'];
147
170
  if (place) {
148
- if (WORKPLACES.memberTrailKeys(sec, subject).includes(place))
171
+ if (s.memberTrails.includes(place))
149
172
  best = takeRank(best, access);
150
- else if (!params?.session?.twinRoleOnly && WORKPLACES.isAncestorPlaceMember(sec, uid, place))
173
+ else if (!params?.session?.twinRoleOnly && WORKPLACES.isAncestorPlaceMember(s.sec, subject, place))
151
174
  best = takeRank(best, 'read');
152
- else if (!params?.session?.twinRoleOnly && roles.includes('BOSS'))
175
+ else if (!params?.session?.twinRoleOnly && s.roles.includes('BOSS'))
153
176
  best = takeRank(best, 'read');
154
177
  }
155
- else if (!params?.session?.twinRoleOnly && (roles.includes('BOSS') || roles.includes('USER'))) {
156
- best = takeRank(best, roles.includes('BOSS') && access === 'write' ? 'admin' : access);
178
+ else if (!params?.session?.twinRoleOnly && (s.roles.includes('BOSS') || s.roles.includes('USER'))) {
179
+ best = takeRank(best, s.roles.includes('BOSS') && WORKPLACES.hasAccess(access, 'write') ? 'admin' : access);
157
180
  }
158
181
  }
159
182
  return best;
160
183
  }
161
184
 
162
185
  /**
163
- * Доступ пользователя к прикладному классу ('admin'|'write'|'read'|null):
186
+ * Доступ пользователя к прикладному классу ('admin'|'delete'|'create'|'write'|'read'|null):
164
187
  * прямые назначения плюс ссылки рабочих мест (кроме структурных типов).
165
188
  */
166
189
  export async function dataAccess(cls, params = {}) {
@@ -174,7 +197,7 @@ export async function dataAccess(cls, params = {}) {
174
197
  /** Доступ по назначениям самого класса (роли #security, системные — и унаследованные сверху), без ссылок мест. */
175
198
  export async function directAccess(cls, params = {}) {
176
199
  let best = null;
177
- const uid = cls.constructor.resolveUid(params);
200
+ const subject = linkSubject(cls, params);
178
201
  const roles = await cls.roles(params);
179
202
  const declared = cls._declaredRolesSync();
180
203
  for (const r of roles) {
@@ -183,8 +206,8 @@ export async function directAccess(cls, params = {}) {
183
206
  continue;
184
207
  if (r === 'BOSS')
185
208
  best = takeRank(best, 'admin');
186
- else if (WORKPLACES.matchesUserList(cls._roleIds(r, declared), uid))
187
- best = takeRank(best, 'write');
209
+ else if (WORKPLACES.matchesUserList(cls._roleIds(r, declared), subject))
210
+ best = takeRank(best, 'delete');
188
211
  else
189
212
  best = takeRank(best, 'read');
190
213
  }
@@ -206,28 +229,27 @@ async function structureItem(path) {
206
229
 
207
230
  /**
208
231
  * Ссылки рабочих мест на класс, его предков и его поддерево — с отношением пользователя
209
- * к каждой, для видимости данных по scope (sources/data/scope.js). Ссылка ниже класса
210
- * открывает сводный отчёт предка по своей ветке.
211
- * relation: 'admin' — ADMIN подразделения (запись по ссылке на запись); 'member' — своё место
212
- * или общая ссылка; 'ancestor' — ссылка вложенного места (чтение); 'boss' — BOSS подразделения (чтение).
213
- * @returns {Promise<Array<{ structure, place, id, access, scope, relation, places: string[], labels: object }>>}
214
- * places — места пользователя в подразделении, labels — названия мест подразделения (путь → label)
232
+ * к каждой, для видимости данных по scope (sources/data/scope.js).
233
+ * Учитывает RWCD, переопределение вниз по дереву классов и исключения `deniedPaths` (`none` или понижение ниже `minAccess`).
215
234
  */
216
- export async function scopeLinks(cls, params = {}) {
235
+ export async function scopeLinks(cls, params = {}, minAccess = 'read') {
217
236
  if (NO_LINK_TYPES.has(cls.type))
218
237
  return [];
219
- const uid = cls.constructor.resolveUid(params);
220
- const p = String(cls.path || '');
238
+ const subject = linkSubject(cls, params);
239
+ const p = String(cls.path || '').replace(/\/+$/, '');
221
240
  if (!p.startsWith('/'))
222
241
  return [];
223
242
  const out = [];
224
243
  const seen = new Map();
225
- for (const e of await collect()) {
226
- if (p !== e.id && !p.startsWith(e.id + '/') && !e.id.startsWith(p + '/'))
244
+ for (const set of await collectSets()) {
245
+ const eff = WORKPLACES.resolveLinkInSet(set.links, p);
246
+ const subLinks = set.links.filter(l => l.id.startsWith(p + '/') && l.access !== 'none');
247
+ if ((!eff || eff.access === 'none') && !subLinks.length)
227
248
  continue;
228
- if (!seen.has(e.structure)) {
229
- seen.set(e.structure, (async () => {
230
- const g = await structureItem(e.structure);
249
+
250
+ if (!seen.has(set.structure)) {
251
+ seen.set(set.structure, (async () => {
252
+ const g = await structureItem(set.structure);
231
253
  const roles = g ? await g.roles(params).catch(() => []) : [];
232
254
  if (!roles.length)
233
255
  return null;
@@ -235,23 +257,67 @@ export async function scopeLinks(cls, params = {}) {
235
257
  const labels = {};
236
258
  for (const { node, trail } of WORKPLACES.walkPlaces(WORKPLACES.normalizeSecurity(sec).places))
237
259
  labels[WORKPLACES.trailKey(trail)] = node.label;
238
- return { roles, sec, labels, places: WORKPLACES.memberTrailKeys(sec, linkSubject(cls, params)) };
260
+ return { roles, sec, labels, places: WORKPLACES.memberTrailKeys(sec, subject) };
239
261
  })());
240
262
  }
241
- const s = await seen.get(e.structure);
263
+ const s = await seen.get(set.structure);
242
264
  if (!s)
243
265
  continue;
244
- const base = { structure: e.structure, place: e.place, id: e.id, scope: e.scope ?? null, ...(e.external ? { external: true } : {}), places: s.places, labels: s.labels };
245
- if (!e.place) {
266
+
267
+ const relations = [];
268
+ if (!set.place) {
246
269
  if (s.roles.includes('BOSS') || s.roles.includes('USER'))
247
- out.push({ ...base, access: e.access, relation: 'member' });
270
+ relations.push({ relation: 'member', downgrade: false });
271
+ }
272
+ else {
273
+ if (s.places.includes(set.place))
274
+ relations.push({ relation: 'member', downgrade: false });
275
+ else if (WORKPLACES.isAncestorPlaceMember(s.sec, subject, set.place))
276
+ relations.push({ relation: 'ancestor', downgrade: true });
277
+ if (s.roles.includes('BOSS'))
278
+ relations.push({ relation: 'boss', downgrade: true });
279
+ }
280
+ if (!relations.length)
281
+ continue;
282
+
283
+ for (const { relation, downgrade } of relations) {
284
+ const reqForDenied = downgrade ? 'read' : minAccess;
285
+ if (eff && eff.access !== 'none') {
286
+ const deniedPaths = WORKPLACES.deniedSubpathsInSet(set.links, p, reqForDenied);
287
+ out.push({
288
+ structure: set.structure,
289
+ place: set.place,
290
+ id: eff.link.id,
291
+ access: downgrade ? 'read' : eff.access,
292
+ scope: eff.link.scope ?? null,
293
+ ...(set.external ? { external: true } : {}),
294
+ places: s.places,
295
+ labels: s.labels,
296
+ relation,
297
+ ...(deniedPaths.length ? { deniedPaths } : {}),
298
+ });
299
+ }
300
+ for (const sl of subLinks) {
301
+ const slAccess = downgrade ? 'read' : sl.access;
302
+ const effAccess = eff && eff.access !== 'none' ? (downgrade ? 'read' : eff.access) : null;
303
+ // Если родительская ссылка уже покрывает подветку с тем же или лучшим уровнем и тем же scope — дубль не нужен
304
+ if (effAccess && (rank[effAccess] || 0) >= (rank[slAccess] || 0) && (eff.link.scope ?? null) === (sl.scope ?? null))
305
+ continue;
306
+ const deniedPaths = WORKPLACES.deniedSubpathsInSet(set.links, sl.id, reqForDenied);
307
+ out.push({
308
+ structure: set.structure,
309
+ place: set.place,
310
+ id: sl.id,
311
+ access: slAccess,
312
+ scope: sl.scope ?? null,
313
+ ...(set.external ? { external: true } : {}),
314
+ places: s.places,
315
+ labels: s.labels,
316
+ relation,
317
+ ...(deniedPaths.length ? { deniedPaths } : {}),
318
+ });
319
+ }
248
320
  }
249
- else if (s.places.includes(e.place))
250
- out.push({ ...base, access: e.access, relation: 'member' });
251
- else if (WORKPLACES.isAncestorPlaceMember(s.sec, uid, e.place))
252
- out.push({ ...base, access: 'read', relation: 'ancestor' });
253
- if (s.roles.includes('BOSS'))
254
- out.push({ ...base, access: 'read', relation: 'boss' });
255
321
  }
256
322
  return out;
257
323
  }
@@ -283,24 +349,26 @@ export async function grants(cls, item, params) {
283
349
  }
284
350
 
285
351
  /**
286
- * Путь — строгий предок какой-то ссылки, элемент — на цепочке к ней
352
+ * Путь — строгий предок какой-то разрешённой ссылки, элемент — на цепочке к ней
287
353
  * (сам класс, путь к ссылке или её поддерево), и у пользователя есть роль
288
354
  * в подразделении ссылки. Даёт только каркас для цепочек (см. grants).
289
355
  */
290
- export async function isLinkAncestor(path, params = {}, itemPath = null) {
291
- const p = String(path || '');
356
+ export async function isLinkAncestor(clsPath, params = {}, itemPath = null) {
357
+ const p = String(clsPath || '');
292
358
  if (!p.startsWith('/') || p === '/')
293
359
  return false;
294
360
  const item = itemPath == null ? p : String(itemPath);
295
- for (const { structure, id } of await collect()) {
296
- if (!id.startsWith(p + '/'))
297
- continue;
298
- // Боковые ветки — мимо: элемент обязан лежать на цепочке.
299
- if (item !== p && id !== item && !id.startsWith(item + '/') && !item.startsWith(id + '/'))
361
+ for (const set of await collectSets()) {
362
+ const match = set.links.some(l => {
363
+ if (l.access === 'none' || !l.id.startsWith(p + '/'))
364
+ return false;
365
+ return item === p || l.id === item || l.id.startsWith(item + '/') || item.startsWith(l.id + '/');
366
+ });
367
+ if (!match)
300
368
  continue;
301
369
  let g;
302
370
  try {
303
- g = await globalThis.WORK.get_item(structure);
371
+ g = await globalThis.WORK.get_item(set.structure);
304
372
  }
305
373
  catch { continue; }
306
374
  if (Array.isArray(g))
@@ -316,13 +384,13 @@ export async function isLinkAncestor(path, params = {}, itemPath = null) {
316
384
  return false;
317
385
  }
318
386
 
319
- /** Запись в прикладной класс по ссылкам. */
320
- export async function grantsWrite(cls, params) {
387
+ /** Запись в прикладной класс по ссылкам (уровень `write` и выше, или заданный `requiredLevel`). */
388
+ export async function grantsWrite(cls, params, requiredLevel = 'write') {
321
389
  if (NO_LINK_TYPES.has(cls.type))
322
390
  return false;
323
391
  try {
324
392
  const level = await linkLevel(cls, params);
325
- return level === 'write' || level === 'admin';
393
+ return WORKPLACES.hasAccess(level, requiredLevel);
326
394
  }
327
395
  catch { return false; }
328
396
  }