odant-work 1.0.82 → 1.0.84

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.
@@ -141,7 +141,7 @@ export default {
141
141
  <div class="card" ~for="links" @tap="openLink($for.item)" :title="$for.item.path">
142
142
  <oda-icon :icon="$for.item.icon || 'bootstrap:database'" :icon-size="28"></oda-icon>
143
143
  <div class="name">{{$for.item.label}}</div>
144
- <span class="chip">{{$for.item.access === 'read' ? 'чтение' : 'работа'}}</span>
144
+ <span class="chip">{{$for.item.access === 'delete' ? 'удаление' : $for.item.access === 'create' ? 'создание' : $for.item.access === 'write' ? 'правка' : 'чтение'}}</span>
145
145
  </div>
146
146
  </div>
147
147
  </section>
@@ -186,11 +186,16 @@ ODA({is: 'work-form',
186
186
  max-width: 100%;
187
187
  flex-shrink: 1;
188
188
  }
189
- .call-btn {
189
+ .consultant-btn {
190
190
  border-radius: 50%;
191
191
  margin-right: 12px;
192
192
  flex-shrink: 0;
193
193
  }
194
+ .call-btn {
195
+ border-radius: 50%;
196
+ margin-right: 32px;
197
+ flex-shrink: 0;
198
+ }
194
199
  .view-selector {
195
200
  justify-content: space-between;
196
201
  overflow-x: auto;
@@ -208,9 +213,12 @@ ODA({is: 'work-form',
208
213
  flex-wrap: wrap;
209
214
  padding-bottom: max(4px, var(--safe-bottom, 0px)) !important;
210
215
  }
211
- @media (max-width: 768px) {
216
+ @media (max-width: 520px) {
217
+ .consultant-btn {
218
+ margin-right: 8px;
219
+ }
212
220
  .call-btn {
213
- margin-right: 2px;
221
+ margin-right: 16px;
214
222
  }
215
223
  .form-header-inner {
216
224
  margin: 2px;
@@ -225,7 +233,7 @@ ODA({is: 'work-form',
225
233
  <div center flex horizontal class="form-header-inner">
226
234
  <item-node-explorer no-flex :$item="rootItem"></item-node-explorer>
227
235
  <div flex></div>
228
- <oda-button ~if="showConsultantBtn" id="consultantBtn" shadow icon="bootstrap:robot" @tap="askConsultant" title="Спросить ИИ-консультанта по текущей форме" :icon-size info-invert style="border-radius: 50%; margin-right: 4px; flex-shrink: 0;"></oda-button>
236
+ <oda-button ~if="showConsultantBtn" id="consultantBtn" shadow icon="bootstrap:robot" @tap="askConsultant" title="Спросить ИИ-консультанта по текущей форме" :icon-size info class="consultant-btn"></oda-button>
229
237
  <oda-button shadow icon="communication:call" @tap="call" title="Call..." :icon-size success class="call-btn"></oda-button>
230
238
  <slot name="top-panel"></slot>
231
239
  <div class="view-selector" no-flex horizontal>
@@ -73,7 +73,7 @@ export default {
73
73
  if (this.$item?.type === '$virtual')
74
74
  return 'carbon:filter';
75
75
  if (this._bossUsers)
76
- return this._bossUsers.then(list => bossAvatarInfo(list[0]).icon);
76
+ return Promise.resolve(this._bossUsers).then(list => bossAvatarInfo(Array.isArray(list) ? list[0] : null).icon);
77
77
  return this.$item?.subIcon;
78
78
  }
79
79
  return Promise.resolve(this.online).then(res => res ? 'unicon:check-circle' : '');
@@ -86,7 +86,7 @@ export default {
86
86
  if (this.$item?.type === '$virtual')
87
87
  return '#ede9fe';
88
88
  if (this._bossUsers)
89
- return this._bossUsers.then(list => bossAvatarInfo(list[0]).color);
89
+ return Promise.resolve(this._bossUsers).then(list => bossAvatarInfo(Array.isArray(list) ? list[0] : null).color);
90
90
  return '';
91
91
  }
92
92
  return Promise.resolve(this.online).then(res => res ? 'lime' : '');
@@ -96,8 +96,8 @@ export default {
96
96
  $def: '',
97
97
  get() {
98
98
  if (this._bossUsers) {
99
- return this._bossUsers.then(list => {
100
- if (!list.length)
99
+ return Promise.resolve(this._bossUsers).then(list => {
100
+ if (!Array.isArray(list) || !list.length)
101
101
  return '';
102
102
  const names = list.map(u => bossAvatarInfo(u).label).filter(Boolean);
103
103
  return names.length ? 'Руководитель: ' + names.join(', ') : '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.82",
3
+ "version": "1.0.84",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -44,7 +44,7 @@ import { DataError } from './errors.js';
44
44
  import { localDay } from './time.js';
45
45
  import { buildWorkspace } from './workspace.js';
46
46
  import * as SQL_INSPECTOR from './sql-inspector.js';
47
- import { normalizeSecurity, walkPlaces, trailKey } from '../server/access/workplaces.js';
47
+ import { normalizeSecurity, walkPlaces, trailKey, hasAccess } from '../server/access/workplaces.js';
48
48
 
49
49
  /** Ссылки рабочих мест — модулем по требованию: links.js тянет сервер, который сам импортирует этот модуль. */
50
50
  const linksModule = () => import('../server/access/links.js');
@@ -375,35 +375,36 @@ function reportAccount(db, cls, ref) {
375
375
  * админ WORK, назначение в самом классе (роль #security, системные — и сверху); для чтения —
376
376
  * и класс, открытый гостям. Для записи назначение должно давать запись.
377
377
  */
378
- async function fullAccess(item, p, write) {
378
+ async function fullAccess(item, p, requiredLevel = 'read') {
379
+ const req = typeof requiredLevel === 'boolean' ? (requiredLevel ? 'write' : 'read') : (requiredLevel || 'read');
379
380
  if (!p?.session || DEV_MODE || p.session.$user === globalThis.WORK)
380
381
  return true;
381
382
  const users = item.DATA?.['#security']?.USER;
382
- if (!write && Array.isArray(users) && (users.includes('GUEST') || users.includes('GUESTS')))
383
+ if (req === 'read' && Array.isArray(users) && (users.includes('GUEST') || users.includes('GUESTS')))
383
384
  return true;
384
385
  if (await item._isWorkBoss?.(p).catch(() => false))
385
386
  return true;
386
387
  const level = await (await linksModule()).directAccess(item, p).catch(() => null);
387
- return write ? level === 'write' || level === 'admin' : level != null;
388
+ return hasAccess(level, req);
388
389
  }
389
390
 
390
391
  /**
391
392
  * Видимость вызова: { full, links — ссылки рабочих мест пользователя на класс, его предков
392
- * и поддерево, grants — права (null — всё, [] — ничего) }. Для записи — только ссылки на запись.
393
+ * и поддерево, grants — права (null — всё, [] — ничего) }.
394
+ * Для write/create/delete — только ссылки с достаточным уровнем RWCD.
393
395
  */
394
- async function scopeOf(item, p, db, cls, write) {
395
- const full = await fullAccess(item, p, write);
396
+ async function scopeOf(item, p, db, cls, requiredLevel = 'read') {
397
+ const req = typeof requiredLevel === 'boolean' ? (requiredLevel ? 'write' : 'read') : (requiredLevel || 'read');
398
+ const full = await fullAccess(item, p, req);
396
399
  const uid = item.constructor.resolveUid?.(p);
397
- const links = await (await linksModule()).scopeLinks(item, p).catch(() => []);
398
- return { full, links, grants: full ? null : scopeGrants(db, cls, links, { uid, write }) };
400
+ const links = await (await linksModule()).scopeLinks(item, p, req).catch(() => []);
401
+ return { full, links, grants: full ? null : scopeGrants(db, cls, links, { uid, minAccess: req }) };
399
402
  }
400
403
 
401
404
  const admin = async (item, p) => item.assertAccess(p, item.constructor.ACCESS_LEVEL.ADMIN);
402
405
 
403
406
  /**
404
- * Обёртка метода: права, БД, класс вызова, видимость (`vis` — права scope.js).
405
- * Чтение: страница класса видна (предок ссылки — как каркас цепочки) и есть хоть одна видимая
406
- * ветка: ссылка на класс, его предка или ниже.
407
+ * Обёртка метода: права RWCD (`read`/`write`/`create`/`delete`/`admin`), БД, класс вызова, видимость (`vis`).
407
408
  */
408
409
  function method(level, fn) {
409
410
  return async (item, p = {}) => {
@@ -412,8 +413,10 @@ function method(level, fn) {
412
413
  let uid = null;
413
414
  if (level === 'read')
414
415
  await item.assertAccess(p, item.constructor.ACCESS_LEVEL.READ);
415
- else if (level === 'write')
416
- uid = await item._assertDataWrite(p);
416
+ else if (level === 'write' || level === 'create' || level === 'delete')
417
+ uid = typeof item._assertDataAccess === 'function'
418
+ ? await item._assertDataAccess(level, p)
419
+ : await item._assertDataWrite(p);
417
420
  else
418
421
  await admin(item, p);
419
422
  const basePath = resolveBasePath(item, p);
@@ -421,7 +424,7 @@ function method(level, fn) {
421
424
  const cls = await classOf(db, item, basePath);
422
425
  const scope = level === 'admin'
423
426
  ? { full: true, links: [], grants: null }
424
- : await scopeOf(item, p, db, cls, level === 'write');
427
+ : await scopeOf(item, p, db, cls, level);
425
428
  if (scope.grants?.length === 0)
426
429
  throw new Error('Доступ запрещён');
427
430
  return fn({ db, cls, item, p, uid, scope, vis: scope.grants });
@@ -834,9 +837,9 @@ export const DATA_METHODS = Object.freeze({
834
837
 
835
838
  /**
836
839
  * Создать объект в листе: { post|body, time?, unit?, place?, ext_of?, valid_from? }.
837
- * Подразделение и место — из мест записи пользователя: не указаны — единственные доступные.
840
+ * Требует уровень C (create) или выше.
838
841
  */
839
- db_create: { level: 'write', fn: method('write', async ({ db, cls, item, p, uid, scope }) => {
842
+ db_create: { level: 'write', fn: method('create', async ({ db, cls, item, p, uid, scope }) => {
840
843
  const at = await writePlace(db, cls, p, scope);
841
844
  const obj = createObject(db, {
842
845
  cid: cls.cid, body: bodyOf(p) ?? {}, time: p.time, unit: at.unit, place: at.place,
@@ -861,7 +864,7 @@ export const DATA_METHODS = Object.freeze({
861
864
  /** Версии объекта: { id }. */
862
865
  db_versions: { level: 'read', fn: method('read', async ({ db, cls, p, vis }) => objectVersions(db, await visibleObject(db, cls, p.id, vis, p))) },
863
866
 
864
- /** Изменить объект: { id, post|body, replace?, time?, valid_from?, version? }. */
867
+ /** Изменить объект (уровень W и выше): { id, post|body, replace?, time?, valid_from?, version? }. */
865
868
  db_update: { level: 'write', fn: method('write', ({ db, cls, item, p, uid, vis }) => {
866
869
  const obj = updateObject(db, {
867
870
  id: ownObject(db, cls, p.id, vis), body: bodyOf(p), replace: flag(p.replace), time: p.time,
@@ -872,11 +875,11 @@ export const DATA_METHODS = Object.freeze({
872
875
  return obj;
873
876
  }) },
874
877
 
875
- /** Удалить объект (отметка): { id, version? }. */
876
- db_delete: { level: 'write', fn: method('write', ({ db, cls, p, uid, vis }) => deleteObject(db, { id: ownObject(db, cls, p.id, vis), version: p.version, author: uid })) },
878
+ /** Удалить объект (отметка, уровень D): { id, version? }. */
879
+ db_delete: { level: 'write', fn: method('delete', ({ db, cls, p, uid, vis }) => deleteObject(db, { id: ownObject(db, cls, p.id, vis), version: p.version, author: uid })) },
877
880
 
878
- /** Восстановить удалённый: { id }. */
879
- db_restore: { level: 'write', fn: method('write', ({ db, cls, p, uid, vis }) => restoreObject(db, { id: ownObject(db, cls, p.id, vis), author: uid })) },
881
+ /** Восстановить удалённый (уровень D): { id }. */
882
+ db_restore: { level: 'write', fn: method('delete', ({ db, cls, p, uid, vis }) => restoreObject(db, { id: ownObject(db, cls, p.id, vis), author: uid })) },
880
883
 
881
884
  /** Выборка объектов класса (с потомками): параметры queryObjects; `names` — названия объектов по ссылкам. */
882
885
  db_query: { level: 'read', fn: method('read', ({ db, cls, p, vis }) => {
@@ -975,8 +978,8 @@ export const DATA_METHODS = Object.freeze({
975
978
  });
976
979
  }) },
977
980
 
978
- /** Удалить собственный HTML-шаблон печатной формы из класса операции: { name }. */
979
- db_print_delete: { level: 'write', fn: method('write', async ({ db, cls, p }) => deletePrintTemplate(db, {
981
+ /** Удалить собственный HTML-шаблон печатной формы из класса операции (уровень D): { name }. */
982
+ db_print_delete: { level: 'write', fn: method('delete', async ({ db, cls, p }) => deletePrintTemplate(db, {
980
983
  ref: cls.cid,
981
984
  name: p.name,
982
985
  root: process.cwd(),
@@ -23,6 +23,7 @@
23
23
  import { getClass, descendants } from './classes.js';
24
24
  import { FAMILY } from './schema.js';
25
25
  import { DataError } from './errors.js';
26
+ import { hasAccess } from '../server/access/workplaces.js';
26
27
 
27
28
  export const SCOPES = Object.freeze(['own', 'place', 'unit', 'all']);
28
29
 
@@ -68,10 +69,11 @@ function rowsOf(db, link, scope, uid) {
68
69
  * @param {object} [opts] { uid, write — только ссылки с правом записи }
69
70
  * @returns {Array<object>|null} null — видно всё
70
71
  */
71
- export function scopeGrants(db, cls, links, { uid, write = false } = {}) {
72
+ export function scopeGrants(db, cls, links, { uid, write = false, minAccess = null } = {}) {
73
+ const req = minAccess || (write ? 'write' : 'read');
72
74
  const grants = new Map();
73
75
  for (const l of links || []) {
74
- if (write && l.access !== 'write' && l.access !== 'admin')
76
+ if (!hasAccess(l.access, req))
75
77
  continue;
76
78
  let branch = null, type = cls.type;
77
79
  if (!under(cls.path, l.id)) {
@@ -84,11 +86,25 @@ export function scopeGrants(db, cls, links, { uid, write = false } = {}) {
84
86
  if (FAMILY[c.type])
85
87
  type = c.type;
86
88
  }
89
+ const excludeSet = new Set();
90
+ for (const dp of l.deniedPaths || []) {
91
+ const dc = getClass(db, dp);
92
+ if (!dc)
93
+ continue;
94
+ for (const cid of descendants(db, dc.cid))
95
+ excludeSet.add(cid);
96
+ }
97
+ if (branch && excludeSet.size) {
98
+ branch = branch.filter(cid => !excludeSet.has(cid));
99
+ if (!branch.length)
100
+ continue;
101
+ }
87
102
  const defScope = l.external ? 'own' : defaultScope(type);
88
103
  const rows = rowsOf(db, l, SCOPES.includes(l.scope) ? l.scope : defScope, uid);
89
- if (!branch && !Object.keys(rows).length)
104
+ const excludeCids = !branch && excludeSet.size ? [...excludeSet] : null;
105
+ if (!branch && !excludeCids && !Object.keys(rows).length)
90
106
  return null;
91
- const g = branch ? { cids: branch, ...rows } : rows;
107
+ const g = { ...(branch ? { cids: branch } : {}), ...(excludeCids ? { excludeCids } : {}), ...rows };
92
108
  grants.set(JSON.stringify(g), g);
93
109
  }
94
110
  return [...grants.values()];
@@ -96,7 +112,7 @@ export function scopeGrants(db, cls, links, { uid, write = false } = {}) {
96
112
 
97
113
  /** Права без веток (чтение реестра через виртуальный справочник, проводки объекта). */
98
114
  export function withoutBranches(grants) {
99
- return grants && grants.map(({ cids, ...rows }) => rows);
115
+ return grants && grants.map(({ cids, excludeCids, ...rows }) => rows);
100
116
  }
101
117
 
102
118
  /**
@@ -107,7 +123,16 @@ export function entryGrants(grants, family, objectCid) {
107
123
  if (grants == null)
108
124
  return null;
109
125
  const out = [];
110
- for (const { cids, ...rows } of grants) {
126
+ for (const { cids, excludeCids, ...rows } of grants) {
127
+ if (excludeCids?.length) {
128
+ if (family === 'account')
129
+ out.push({ ...(cids ? { accounts: cids } : {}), excludeAccounts: excludeCids, ...rows });
130
+ else if (family === 'operation')
131
+ out.push({ ...(cids ? { ops: cids } : {}), excludeOps: excludeCids, ...rows });
132
+ else if (objectCid === undefined || !excludeCids.includes(objectCid))
133
+ out.push(rows);
134
+ continue;
135
+ }
111
136
  if (!cids)
112
137
  out.push(rows);
113
138
  else if (family === 'account')
@@ -125,6 +150,11 @@ function inList(col, list) {
125
150
  return values.length ? [`${col} IN (${values.map(() => '?').join(',')})`, values] : ['0', []];
126
151
  }
127
152
 
153
+ function notInList(col, list) {
154
+ const values = [...new Set(list.map(String))];
155
+ return values.length ? [`${col} NOT IN (${values.map(() => '?').join(',')})`, values] : ['1', []];
156
+ }
157
+
128
158
  /** Условия строк (подразделения, места, автор) на таблицу с колонками unit/place/author. */
129
159
  function rowParts(g, alias, entries) {
130
160
  const parts = [];
@@ -159,7 +189,11 @@ function anyOf(grants, partsOf) {
159
189
 
160
190
  /** Условие видимости объектов (алиас таблицы `o`): [sql, args] или null — без ограничений. */
161
191
  export function objectCond(grants, alias = 'o') {
162
- return anyOf(grants, g => [...(g.cids ? [inList(`${alias}.cid`, g.cids)] : []), ...rowParts(g, alias, false)]);
192
+ return anyOf(grants, g => [
193
+ ...(g.cids ? [inList(`${alias}.cid`, g.cids)] : []),
194
+ ...(g.excludeCids?.length ? [notInList(`${alias}.cid`, g.excludeCids)] : []),
195
+ ...rowParts(g, alias, false),
196
+ ]);
163
197
  }
164
198
 
165
199
  /**
@@ -173,8 +207,14 @@ export function entryCond(grants, accCols = ['e.debit_cid', 'e.credit_cid']) {
173
207
  const c = accCols.map(col => inList(col, g.accounts));
174
208
  parts.push([`(${c.map(x => x[0]).join(' OR ')})`, c.flatMap(x => x[1])]);
175
209
  }
210
+ if (g.excludeAccounts?.length) {
211
+ const c = accCols.map(col => notInList(col, g.excludeAccounts));
212
+ parts.push([`(${c.map(x => x[0]).join(' AND ')})`, c.flatMap(x => x[1])]);
213
+ }
176
214
  if (g.ops)
177
215
  parts.push(inList('e.op_cid', g.ops));
216
+ if (g.excludeOps?.length)
217
+ parts.push(notInList('e.op_cid', g.excludeOps));
178
218
  return [...parts, ...rowParts(g, 'e', true)];
179
219
  });
180
220
  }
@@ -198,7 +238,7 @@ export function visibleUnits(grants) {
198
238
  * на класс или его предка. ADMIN подразделения — любое его место (`any`).
199
239
  * @returns {Array<{ unit, unit_label, place, place_label, any? }>}
200
240
  */
201
- export function writeContexts(db, cls, links) {
241
+ export function writeContexts(db, cls, links, minAccess = 'create') {
202
242
  const out = new Map();
203
243
  const add = (l, place, any = false) => {
204
244
  const unit = unitOf(db, l.structure);
@@ -217,7 +257,7 @@ export function writeContexts(db, cls, links) {
217
257
  });
218
258
  };
219
259
  for (const l of links || []) {
220
- if ((l.access !== 'write' && l.access !== 'admin') || !under(cls.path, l.id))
260
+ if (!hasAccess(l.access, minAccess) || !under(cls.path, l.id))
221
261
  continue;
222
262
  if (l.relation === 'admin')
223
263
  add(l, null, true);
@@ -11,19 +11,21 @@
11
11
  */
12
12
  import { getClass, children } from './classes.js';
13
13
  import { FAMILY } from './schema.js';
14
- import { normalizeSecurity, walkPlaces, trailKey, memberTrailKeys } from '../server/access/workplaces.js';
14
+ import { normalizeSecurity, walkPlaces, trailKey, memberTrailKeys, ACCESS_RANK } from '../server/access/workplaces.js';
15
15
 
16
- const RANK = { read: 1, write: 2 };
16
+ const RANK = ACCESS_RANK;
17
17
  const SCOPE_RANK = { null: 0, own: 1, place: 2, unit: 3, all: 4 };
18
18
  const LIMIT_CLASSES = 5000;
19
19
 
20
- /** Права на ссылку: у BOSS и вышестоящего места — только чтение. */
21
- const readOnly = links => links.map(l => ({ ...l, access: 'read' }));
20
+ /** Права на ссылку: у BOSS и вышестоящего места — только чтение (явный none остаётся скрытым). */
21
+ const readOnly = links => links.filter(l => l.access !== 'none').map(l => ({ ...l, access: 'read' }));
22
22
 
23
- /** Слияние ссылок по id: выше доступ, при равном — шире видимость. */
23
+ /** Слияние ссылок по id: выше доступ, при равном — шире видимость; явные none отфильтровываются. */
24
24
  function mergeLinks(...lists) {
25
25
  const out = new Map();
26
26
  for (const l of lists.flat()) {
27
+ if (!l || l.access === 'none')
28
+ continue;
27
29
  const cur = out.get(l.id);
28
30
  const better = !cur
29
31
  || (RANK[l.access] ?? 0) > (RANK[cur.access] ?? 0)
@@ -34,7 +36,7 @@ function mergeLinks(...lists) {
34
36
  return [...out.values()];
35
37
  }
36
38
 
37
- const ownLinks = node => node.LINKS.map(l => ({ id: l.id, access: l.access, scope: l.scope ?? null }));
39
+ const ownLinks = node => node.LINKS.filter(l => l.access !== 'none').map(l => ({ id: l.id, access: l.access, scope: l.scope ?? null }));
38
40
 
39
41
  /**
40
42
  * Подразделения и места пользователя с меню.
@@ -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),