odant-work 1.0.78 → 1.0.79

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.78",
3
+ "version": "1.0.79",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -703,6 +703,222 @@ export async function listNodeNetworkNodes(storage, params = {}) {
703
703
  return { nodes: out };
704
704
  }
705
705
 
706
+ /**
707
+ * Единый контекст для вкладки «Пользователи» и «Классы и модули» подразделения / $base:
708
+ * реальные пользователи, подразделения, серверы сети, унаследованный BOSS,
709
+ * полное дерево классов вышестоящего $base и доступные модули /MODULES.
710
+ */
711
+ export async function getNodeStaffContext(storage, params = {}) {
712
+ await assertBoss(storage, params);
713
+ const WORK = globalThis.WORK;
714
+ if (!WORK)
715
+ return { users: [], structures: [], networkNodes: [], inheritedBoss: null, baseClasses: [], systemModules: [], basePath: '' };
716
+
717
+ // 1. Пользователи /USERS
718
+ const users = [];
719
+ const userMap = new Map();
720
+ 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
+ }
735
+
736
+ // 2. Унаследованный руководитель (BOSS) вверх по дереву (включая корень '/')
737
+ let inheritedBoss = null;
738
+ try {
739
+ const chain = [];
740
+ for (let anc = storage?.$parent; anc; anc = anc.$parent) {
741
+ if (anc instanceof FS.$class)
742
+ chain.push(anc);
743
+ }
744
+ if (!chain.some(a => a === WORK || a.path === '/'))
745
+ chain.push(WORK);
746
+ for (const anc of chain) {
747
+ await anc.init?.catch?.(() => {});
748
+ const localIds = typeof anc._roleIds === 'function'
749
+ ? anc._roleIds('BOSS')
750
+ : (Array.isArray(anc.DATA?.['#security']?.BOSS) ? anc.DATA['#security'].BOSS : []);
751
+ const cleanIds = (Array.isArray(localIds) ? localIds : []).filter(v => typeof v === 'string' && v.trim());
752
+ if (cleanIds.length) {
753
+ const resolved = cleanIds.slice(0, 1).map(uid => {
754
+ const found = userMap.get(uid);
755
+ return found
756
+ ? { ...found, missing: false }
757
+ : { id: uid, label: `${uid} (не найден в /USERS)`, icon: 'icons:person', iconColor: '', missing: true };
758
+ });
759
+ const ancPath = anc.path || '/';
760
+ inheritedBoss = {
761
+ fromPath: ancPath,
762
+ fromLabel: anc.DATA?.label || anc.label || anc.id || (ancPath === '/' ? 'WORK' : ancPath),
763
+ users: resolved,
764
+ };
765
+ break;
766
+ }
767
+ }
768
+ }
769
+ catch { /* ignore */ }
770
+
771
+ // 3. Подразделения и серверы сети
772
+ const [structRes, netRes] = await Promise.all([
773
+ listNodeStructures(storage, params).catch(() => ({ structures: [] })),
774
+ listNodeNetworkNodes(storage, params).catch(() => ({ nodes: [] })),
775
+ ]);
776
+
777
+ // 4. Полное дерево всех классов, установленных в вышестоящий $base ($project)
778
+ const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
779
+ const baseMatch = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
780
+ const basePath = baseMatch ? baseMatch[1] : '';
781
+ const modRootPath = basePath ? `${basePath}/MODULES` : '/MODULES';
782
+ const baseClasses = [];
783
+ const installedModIds = new Set();
784
+
785
+ const walkClasses = async (node, depth = 0) => {
786
+ if (!node || depth > 7)
787
+ return null;
788
+ await node.init?.catch?.(() => {});
789
+ if (!node.id || node.id[0] === '$')
790
+ return null;
791
+ const t = node.type;
792
+ const isAllowed = DATA_CLASS_TYPES.has(t) || t === '$module' || t === '$domain' || t === '$class' || t === '$folder';
793
+ if (!isAllowed)
794
+ return null;
795
+ if (t === '$module')
796
+ installedModIds.add(node.id);
797
+ const items = await Promise.resolve(node.items).catch(() => []) || [];
798
+ const children = [];
799
+ for (const ch of items) {
800
+ if (!ch || ch.id?.[0] === '$')
801
+ continue;
802
+ const built = await walkClasses(ch, depth + 1);
803
+ if (built)
804
+ children.push(built);
805
+ }
806
+ return {
807
+ id: node.id,
808
+ path: node.path,
809
+ label: node.DATA?.label || node.label || node.id,
810
+ type: t,
811
+ icon: node.DATA?.icon || node.icon || (t === '$module' ? 'odant:module' : 'odant:class'),
812
+ children,
813
+ };
814
+ };
815
+
816
+ const modRootItem = await WORK.get_item(modRootPath).catch(() => null);
817
+ if (modRootItem) {
818
+ const modKids = await Promise.resolve(modRootItem.items).catch(() => []) || [];
819
+ for (const mk of modKids) {
820
+ if (!mk || mk.id?.[0] === '$')
821
+ continue;
822
+ const built = await walkClasses(mk, 0);
823
+ if (built)
824
+ baseClasses.push(built);
825
+ }
826
+ }
827
+
828
+ // 5. Доступные эталонные модули в корневом /MODULES
829
+ const systemModules = [];
830
+ const sysModRoot = await WORK.get_item('/MODULES').catch(() => null);
831
+ if (sysModRoot) {
832
+ const sysKids = await Promise.resolve(sysModRoot.items).catch(() => []) || [];
833
+ for (const sm of sysKids) {
834
+ if (!sm || sm.id?.[0] === '$' || sm.type !== '$module')
835
+ continue;
836
+ await sm.init?.catch?.(() => {});
837
+ systemModules.push({
838
+ id: sm.id,
839
+ path: sm.path,
840
+ label: sm.DATA?.label || sm.label || sm.id,
841
+ icon: sm.DATA?.icon || sm.icon || 'odant:module',
842
+ installed: installedModIds.has(sm.id),
843
+ });
844
+ }
845
+ }
846
+
847
+ return {
848
+ users,
849
+ structures: structRes.structures || [],
850
+ networkNodes: netRes.nodes || [],
851
+ inheritedBoss,
852
+ basePath,
853
+ modRootPath,
854
+ baseClasses,
855
+ systemModules,
856
+ };
857
+ }
858
+
859
+ /**
860
+ * Подключить эталонный модуль из `/MODULES/<id>` в `<$base>/MODULES`.
861
+ */
862
+ export async function installBaseModule(storage, params = {}) {
863
+ await assertBoss(storage, params);
864
+ const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
865
+ const modId = String(post.moduleId || post.id || '').trim();
866
+ if (!modId || /[\\/.$#]/.test(modId))
867
+ throw new Error('Укажите корректный идентификатор модуля');
868
+ const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
869
+ const baseMatch = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
870
+ if (!baseMatch)
871
+ throw new Error('Подключение модулей выполняется в контексте организации или проекта');
872
+ const baseItem = await globalThis.WORK.get_item(baseMatch[1]).catch(() => null);
873
+ if (!baseItem)
874
+ throw new Error('Не найден корневой объект организации');
875
+ let modDomain = await globalThis.WORK.get_item(`${baseMatch[1]}/MODULES`).catch(() => null);
876
+ if (!modDomain && typeof baseItem.create === 'function') {
877
+ await baseItem.create({ ...params, id: 'MODULES', type: '$domain', label: 'Модули' });
878
+ modDomain = await globalThis.WORK.get_item(`${baseMatch[1]}/MODULES`).catch(() => null);
879
+ }
880
+ if (!modDomain)
881
+ throw new Error('Не найден домен MODULES');
882
+ const exists = await globalThis.WORK.get_item(`${baseMatch[1]}/MODULES/${modId}`).catch(() => null);
883
+ if (exists)
884
+ return { ok: true, alreadyInstalled: true, path: exists.path };
885
+ await modDomain.create({ ...params, id: modId, type: '$module' });
886
+ await recordBossSettingTask(storage, params, {
887
+ title: `Подключён модуль «${modId}»`,
888
+ summary: `В ${baseMatch[1]} подключён модуль /MODULES/${modId}.`,
889
+ });
890
+ return { ok: true, path: `${baseMatch[1]}/MODULES/${modId}` };
891
+ }
892
+
893
+ /**
894
+ * Создать новый класс или подкласс внутри `<$base>/MODULES`.
895
+ */
896
+ export async function createBaseClass(storage, params = {}) {
897
+ await assertBoss(storage, params);
898
+ const post = (typeof params.post === 'string' ? JSON.parse(params.post) : params.post) || params;
899
+ const parentPath = String(post.parentPath || '').trim();
900
+ const id = String(post.id || post.label || '').trim();
901
+ const label = String(post.label || id).trim();
902
+ const type = String(post.type || '$catalog').trim();
903
+ if (!id)
904
+ throw new Error('Укажите название класса');
905
+ const selfPath = String(storage?.path || '/').replace(/\/+$/, '') || '/';
906
+ const baseMatch = /^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+)/.exec(selfPath);
907
+ if (!baseMatch)
908
+ throw new Error('Создание класса выполняется в контексте организации или проекта');
909
+ const modPrefix = `${baseMatch[1]}/MODULES`;
910
+ const targetParentPath = parentPath && parentPath.startsWith(modPrefix) ? parentPath : modPrefix;
911
+ const parentItem = await globalThis.WORK.get_item(targetParentPath).catch(() => null);
912
+ if (!parentItem || typeof parentItem.create !== 'function')
913
+ throw new Error('Не найден родительский контейнер: ' + targetParentPath);
914
+ await parentItem.create({ ...params, id, label, type });
915
+ await recordBossSettingTask(storage, params, {
916
+ title: `Создан класс «${label}» (${type})`,
917
+ summary: `В ${targetParentPath} создан класс «${label}» типа ${type}.`,
918
+ });
919
+ return { ok: true, path: `${targetParentPath}/${id}` };
920
+ }
921
+
706
922
  /**
707
923
  * Последние выполненные задачи `.task` подразделения (для повторения по расписанию).
708
924
  */
@@ -46,7 +46,7 @@ export const MEMBERS = Object.freeze({
46
46
  mail_draft_save: L.WRITE, mail_send: L.WRITE, mail_state: L.WRITE, mail_refresh: L.WRITE,
47
47
  calendar_list: L.READ, calendar_save: L.WRITE,
48
48
  agent_rules_list: L.READ, agent_rule_save: L.ADMIN, agent_schedule_save: L.ADMIN, agent_proactivity_save: L.ADMIN,
49
- agent_system_get: L.READ, agent_system_save: L.ADMIN, agent_available_classes: L.READ, agent_structures_list: L.READ, agent_network_nodes: L.READ, agent_tasks_list: L.READ,
49
+ agent_system_get: L.READ, agent_system_save: L.ADMIN, agent_available_classes: L.READ, agent_structures_list: L.READ, agent_network_nodes: L.READ, agent_staff_context: L.READ, agent_base_module_install: L.ADMIN, agent_base_class_create: L.ADMIN, agent_tasks_list: L.READ,
50
50
  security_update: L.ADMIN,
51
51
  roles: L.READ, members: L.READ, is_data_type: L.READ, reset: L.READ,
52
52
  work_zone: L.READ, places: L.READ,
@@ -130,6 +130,7 @@ export function normalizePlaces(raw, seen = new Set(), depth = 0) {
130
130
  label: typeof r.label === 'string' && r.label ? r.label : id,
131
131
  icon: typeof r.icon === 'string' ? r.icon : '',
132
132
  ...(r.external ? { external: true } : {}),
133
+ ...(r.readonly ? { readonly: true } : {}),
133
134
  USERS: Array.isArray(r.USERS) ? r.USERS.filter(u => typeof u === 'string') : [],
134
135
  LINKS: links,
135
136
  ROLES: normalizePlaces(r.ROLES, seen, depth + 1),
@@ -254,6 +254,24 @@ export const classFeedMethods = {
254
254
  return listNodeNetworkNodes(this, params);
255
255
  },
256
256
 
257
+ /** Единый контекст для вкладки «Пользователи» и «Классы и модули» (только BOSS). */
258
+ async agent_staff_context(params = {}) {
259
+ const { getNodeStaffContext } = await import('../../modules/agent/node-rules.js');
260
+ return getNodeStaffContext(this, params);
261
+ },
262
+
263
+ /** Подключить эталонный модуль из /MODULES в организацию/проект (только BOSS). */
264
+ async agent_base_module_install(params = {}) {
265
+ const { installBaseModule } = await import('../../modules/agent/node-rules.js');
266
+ return installBaseModule(this, params);
267
+ },
268
+
269
+ /** Создать новый класс внутри модулей организации/проекта (только BOSS). */
270
+ async agent_base_class_create(params = {}) {
271
+ const { createBaseClass } = await import('../../modules/agent/node-rules.js');
272
+ return createBaseClass(this, params);
273
+ },
274
+
257
275
  /** Список последних выполненных задач (.task) узла для повторения по расписанию (только BOSS). */
258
276
  async agent_tasks_list(params = {}) {
259
277
  const { listNodeTasks } = await import('../../modules/agent/node-rules.js');