odant-work 1.0.101 → 1.0.103
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/$server/$folder/$class/$structure/$department/ai/config.js +9 -0
- package/$server/$folder/$class/$structure/$department/ai/system.md +11 -0
- package/$server/$folder/$class/$structure/$department/class.js +9 -0
- package/$server/$folder/$class/$structure/$project/ai/config.js +9 -0
- package/$server/$folder/$class/$structure/$project/ai/system.md +12 -0
- package/$server/$folder/$class/$structure/$project/class.js +4 -1
- package/$server/$folder/$class/$structure/$project/handlers/pages/site/$handler/class.js +1 -1
- package/$server/$folder/$class/$structure/$server/ai/config.js +9 -0
- package/$server/$folder/$class/$structure/$server/ai/system.md +10 -0
- package/$server/$folder/$class/$structure/$server/class.js +2 -0
- package/$server/$folder/$class/$structure/$user/ai/config.js +9 -0
- package/$server/$folder/$class/$structure/$user/ai/system.md +8 -0
- package/$server/$folder/$class/$structure/$user/class.js +2 -0
- package/$server/$folder/$class/$structure/ai/system.md +1 -1
- package/$server/$folder/$class/$structure/class.js +4 -2
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js +17 -6
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +91 -22
- package/$server/$folder/$class/$structure/handlers/pages/form/system/agent/$handler/class.js +132 -3
- package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +2 -2
- package/$server/$folder/$class/$structure/handlers/pages/site/$handler/class.js +2 -1
- package/$server/$folder/$class/ai/system.md +2 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +38 -8
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +22 -31
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +32 -0
- package/$server/$folder/handlers/pages/form/$handler/class.js +47 -5
- package/$server/$folder/lib/chat-item/chat-item.js +14 -2
- package/$server/$folder/lib/consultant/consultant.js +81 -4
- package/$server/$folder/lib/explorer/explorer.js +20 -11
- package/$server/$folder/lib/icon/icon.js +1 -1
- package/$server/$folder/lib/node/node.js +3 -3
- package/$server/$folder/lib/site-loc/site-loc.js +8 -3
- package/$server/$folder/lib/tree/tree.js +8 -8
- package/AGENTS.md +3 -3
- package/autostart.bat +28 -0
- package/autostart.sh +17 -0
- package/package.json +1 -1
- package/run.mjs +19 -0
- package/scripts/autostart.mjs +281 -0
- package/scripts/import-bis.mjs +5 -5
- package/scripts/import-delovaya.mjs +5 -5
- package/scripts/watchdog.mjs +496 -0
- package/sources/client/class.js +1 -1
- package/sources/client.js +141 -8
- package/sources/data/api.js +1 -1
- package/sources/data/classes.js +2 -1
- package/sources/data/schema.js +2 -0
- package/sources/host/auth-methods.js +3 -1
- package/sources/host/auto-updater.js +23 -1
- package/sources/host/http-server.js +5 -3
- package/sources/host/push.js +43 -14
- package/sources/host/websocket.js +52 -3
- package/sources/modules/agent/index.js +38 -10
- package/sources/modules/agent/node-rules.js +353 -9
- package/sources/modules/agent/scheduler.js +7 -0
- package/sources/modules/agent/scope.js +8 -6
- package/sources/modules/agent/session.js +38 -8
- package/sources/modules/agent/tools/work/access.js +1 -1
- package/sources/modules/agent/tools/work/classes.js +1 -1
- package/sources/modules/agent/triggers.js +1 -1
- package/sources/modules/agent/twin-bus.js +2 -1
- package/sources/modules/notify/index.js +5 -2
- package/sources/modules/trainer/local-engine.js +3 -1
- package/sources/modules/user-profile/user-profile.js +129 -0
- package/sources/server/access/gateway.js +5 -3
- package/sources/server/access/links.js +9 -6
- package/sources/server/chat-threads.js +1 -1
- package/sources/server/class/base-template.js +3 -2
- package/sources/server/class/feed.js +36 -0
- package/sources/server/class/scaffold.js +137 -0
- package/sources/server/class/search.js +2 -2
- package/sources/server/class/security.js +1 -1
- package/sources/server/class.js +5 -3
- package/sources/server/folder.js +10 -6
- package/sources/server/logs.js +14 -0
- package/sources/server/node.js +1 -1
- package/sources/server/server.js +50 -1
- package/sources/server/user.js +45 -0
- package/sources/work.js +7 -0
- package/start.bat +25 -0
- package/start.sh +27 -0
- package/stop.bat +25 -0
- package/stop.sh +16 -0
- package/sw.js +3 -11
|
@@ -284,7 +284,7 @@ export default {
|
|
|
284
284
|
if (!it || ('isPlace' in Object(it) && it.isPlace))
|
|
285
285
|
return '';
|
|
286
286
|
const t = it.type;
|
|
287
|
-
if (t === '$project' || t === '$structure' || t === '$server' || t === '$domain')
|
|
287
|
+
if ((it.DATA?.isStructure && !it.DATA?.isUser && t !== '$user') || t === '$project' || t === '$structure' || t === '$server' || t === '$domain')
|
|
288
288
|
return '';
|
|
289
289
|
const c = isLinkNode(it) ? it.objectCount : it.DATA?.objectCount;
|
|
290
290
|
return (typeof c === 'number' && c > 0) ? c.toLocaleString('ru-RU') : '';
|
|
@@ -357,7 +357,7 @@ export default {
|
|
|
357
357
|
return false;
|
|
358
358
|
const t = it.type;
|
|
359
359
|
const isNetServer = t === '$node' && it.id !== 'NODES';
|
|
360
|
-
return t === '$project' || t === '$structure' || t === '$server' || isNetServer || it.id === 'PROJECTS';
|
|
360
|
+
return (it.DATA?.isStructure && !it.DATA?.isUser && t !== '$user') || t === '$project' || t === '$structure' || t === '$server' || isNetServer || it.id === 'PROJECTS';
|
|
361
361
|
},
|
|
362
362
|
// пользователи в строке дерева не показываются (шум и запросы на каждую строку); свойство оставлено для совместимости биндов
|
|
363
363
|
showUsers: false,
|
|
@@ -431,7 +431,7 @@ export default {
|
|
|
431
431
|
return 24;
|
|
432
432
|
const t = this.$item?.type;
|
|
433
433
|
const isNetServer = t === '$node' && this.$item?.id !== 'NODES';
|
|
434
|
-
if(this.isUser || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer)
|
|
434
|
+
if(this.isUser || this.$item?.DATA?.isStructure || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer)
|
|
435
435
|
return 48;
|
|
436
436
|
if(t === '$module' || t === '$provider' || t === '$mcp')
|
|
437
437
|
return 32;
|
|
@@ -10,8 +10,13 @@ export const STRUCTURE_TYPES = Object.freeze(['$structure', '$project']);
|
|
|
10
10
|
* @param {string} type Тип элемента ($project, $structure, …)
|
|
11
11
|
* @returns {string}
|
|
12
12
|
*/
|
|
13
|
-
export function structureKind(
|
|
14
|
-
|
|
13
|
+
export function structureKind(typeOrItem) {
|
|
14
|
+
if (typeOrItem && typeof typeOrItem === 'object') {
|
|
15
|
+
if (typeOrItem.DATA?.isProject) return 'org';
|
|
16
|
+
if (typeOrItem.DATA?.isDepartment) return 'unit';
|
|
17
|
+
typeOrItem = typeOrItem.type;
|
|
18
|
+
}
|
|
19
|
+
switch (typeOrItem) {
|
|
15
20
|
case '$project': return 'org';
|
|
16
21
|
case '$structure': return 'unit';
|
|
17
22
|
default: return '';
|
|
@@ -20,7 +25,7 @@ export function structureKind(type) {
|
|
|
20
25
|
|
|
21
26
|
/** Узел оргструктуры (есть сайт, участвует в навигации). */
|
|
22
27
|
export function isStructureNode(item) {
|
|
23
|
-
return !!item && STRUCTURE_TYPES.includes(item.type);
|
|
28
|
+
return !!item && (STRUCTURE_TYPES.includes(item.type) || item.DATA?.isProject === true || item.DATA?.isDepartment === true);
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
function _encodeVal(v) {
|
|
@@ -53,8 +53,8 @@ function filterMainTreeItems(items, parent) {
|
|
|
53
53
|
return items.filter(f => f && !f.DATA?.objects);
|
|
54
54
|
if (isMainTreeLeaf(parent))
|
|
55
55
|
return [];
|
|
56
|
-
if (parent.type === '$project' || parent.type === '$structure')
|
|
57
|
-
return items.filter(f => f && (f.type === '$structure' || f.type === '$project'));
|
|
56
|
+
if (parent.type === '$project' || parent.type === '$structure' || parent.DATA?.isProject || parent.DATA?.isDepartment)
|
|
57
|
+
return items.filter(f => f && (f.type === '$structure' || f.type === '$project' || f.DATA?.isDepartment || f.DATA?.isProject));
|
|
58
58
|
if (parent.type === '$provider')
|
|
59
59
|
return items.filter(f => f?.type === '$ai');
|
|
60
60
|
return items.filter(f => f && !f.DATA?.objects);
|
|
@@ -76,7 +76,7 @@ export function knownHasItems(it, pdp = {}) {
|
|
|
76
76
|
return false;
|
|
77
77
|
if (it.DATA?.mainTree === true && typeof it.DATA?.hasItems === 'boolean')
|
|
78
78
|
return it.DATA.hasItems;
|
|
79
|
-
if (it.type === '$project' || it.type === '$structure')
|
|
79
|
+
if (it.type === '$project' || it.type === '$structure' || it.DATA?.isProject || it.DATA?.isDepartment)
|
|
80
80
|
return undefined;
|
|
81
81
|
}
|
|
82
82
|
// __version — реактивная зависимость: после события changed флаг удаляется и пересчитывается по items
|
|
@@ -861,7 +861,7 @@ ODA({is: 'oda-tree-node',
|
|
|
861
861
|
return false;
|
|
862
862
|
const t = it.type;
|
|
863
863
|
const isNetServer = t === '$node' && it.id !== 'NODES';
|
|
864
|
-
return it instanceof CORE.$user || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer;
|
|
864
|
+
return it instanceof CORE.$user || it.DATA?.isStructure === true || t === '$user' || t === '$project' || t === '$structure' || t === '$server' || isNetServer;
|
|
865
865
|
},
|
|
866
866
|
get isMediumIconNode() {
|
|
867
867
|
return this.isModule;
|
|
@@ -884,7 +884,7 @@ ODA({is: 'oda-tree-node',
|
|
|
884
884
|
return false;
|
|
885
885
|
const t = it.type;
|
|
886
886
|
// $server (корень WORK) и $project — тоже наследники $structure: на них показываем BOSS.
|
|
887
|
-
return t === '$project' || t === '$structure' || t === '$server';
|
|
887
|
+
return (it.DATA?.isStructure === true && !it.DATA?.isUser && t !== '$user') || t === '$project' || t === '$structure' || t === '$server';
|
|
888
888
|
},
|
|
889
889
|
get isModule() {
|
|
890
890
|
const it = this.$item;
|
|
@@ -892,7 +892,7 @@ ODA({is: 'oda-tree-node',
|
|
|
892
892
|
},
|
|
893
893
|
get isToggleableUser() {
|
|
894
894
|
const it = this.$item;
|
|
895
|
-
if (!it || isLinkNode(it) || it.type !== '$user')
|
|
895
|
+
if (!it || isLinkNode(it) || it.type !== '$user' || it.DATA?.usersContainer === true)
|
|
896
896
|
return false;
|
|
897
897
|
if (globalThis.WORK?.uid && it.id === globalThis.WORK.uid)
|
|
898
898
|
return false;
|
|
@@ -900,7 +900,7 @@ ODA({is: 'oda-tree-node',
|
|
|
900
900
|
return Boolean(globalThis.WORK?.DEV_MODE || tree?._isRootBoss);
|
|
901
901
|
},
|
|
902
902
|
get isModuleBlocked() {
|
|
903
|
-
if (!this.isModule && this.$item?.type !== '$user')
|
|
903
|
+
if (!this.isModule && (this.$item?.type !== '$user' || this.$item?.DATA?.usersContainer === true))
|
|
904
904
|
return false;
|
|
905
905
|
this.$item.__version;
|
|
906
906
|
if (this.$item?.type === '$user')
|
|
@@ -930,7 +930,7 @@ ODA({is: 'oda-tree-node',
|
|
|
930
930
|
return false;
|
|
931
931
|
this.$item.__version;
|
|
932
932
|
const t = this.$item?.type;
|
|
933
|
-
if (t !== '$structure' && t !== '$project' && t !== '$server')
|
|
933
|
+
if ((!this.$item?.DATA?.isStructure && t !== '$structure' && t !== '$project' && t !== '$server') || this.$item?.DATA?.isUser || t === '$user')
|
|
934
934
|
return false;
|
|
935
935
|
return !!this.$item?.DATA?.hasSecurity;
|
|
936
936
|
},
|
package/AGENTS.md
CHANGED
|
@@ -30,9 +30,9 @@
|
|
|
30
30
|
2. **Установка.** Модуль ставится в структуру и работает для неё и всех структур ниже. Копия ниже продолжает копию выше и меняет только своё.
|
|
31
31
|
3. **Владение.** Агент, роли, навыки и память есть только у структуры. Модуль поставляет классы данных, инструменты, подключения и модели. Класс данных хранит объекты в базе ближайшего проекта.
|
|
32
32
|
|
|
33
|
-
- **Дерево и типы:** всё — папка или файл единого дерева; адрес узла — его путь. Папка с метапапкой `$тип` — класс: `class.js` (свойства), `readme.md` (контракт), `handlers/`. Ветки типов: `$structure` (кто действует: `$server`, `$project`, `$
|
|
33
|
+
- **Дерево и типы:** всё — папка или файл единого дерева; адрес узла — его путь. Папка с метапапкой `$тип` — класс: `class.js` (свойства), `readme.md` (контракт), `handlers/`. Ветки типов: `$structure` (абстрактный базовый тип; кто действует: `$server`, `$project`, `$department`, `$user`), `$module` (что установлено, в т. ч. `$mcp` и `$provider` с моделями `$ai`), `$data` (где хранятся объекты); `$class` абстрактен. `/X/~/…` отдаёт собранное по слоям: `/X/~/class.js`, `/X/~/readme.md`, `/X/~/handlers/…`.
|
|
34
34
|
- **Ссылки:** только `ancestor` (узел продолжает другой) и `types` (примеси) в `class.js`; из пути ничего не вычисляется.
|
|
35
|
-
- **Роли:** встроенная одна — `BOSS` (единственный владелец узла и поддерева на `$server`, `$project` и `$
|
|
35
|
+
- **Роли:** встроенная одна — `BOSS` (единственный владелец узла и поддерева на `$server`, `$project` и `$department`, наследуется вниз). Остальные — записи `#security.ROLES` только подразделений `$department` (`USERS`, права `LINKS`, маркер `external`), а не дочерние классы.
|
|
36
36
|
- **Учёт:** `$catalog` (листья хранят объекты, группы агрегируют), `$virtual` (`turnover`/`balance` + `OVERLAY`), `$struct` (`table: true` — таблица), `$operation` — двойная запись (Дебет + Кредит в `$account` + `logs`); проведённое исправляется только сторно; поля справочника-аналитики — субаналитики.
|
|
37
37
|
- **Ядро и дерево:** ядро (`sources/`, `oda/`, `run.mjs`, `#system/`) меняется только по явной задаче доработки движка через `developer`-контур (тесты, отложенный перезапуск). Остальное — дерево, включая системный типизатор `/$server/$folder`; оно меняется штатно, без git. Правки типизатора и модулей уровня WORK — только извне проектов, с подтверждением, проверкой последствий и сбросом кэша.
|
|
38
38
|
- **Арены инструментов:** дерево — WORK-инструментами (`ls/read/find/write/edit/delete`, `create_class/update_class/move_class/delete_class`), файлы ОС вне WORK — `os_*`; `shell` не служит обходом WORK-ограничений.
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
## Дополнительно для сессий разработки (OpenCode / репозиторий)
|
|
49
49
|
|
|
50
50
|
1. Актуальность рабочей копии: ветка **`main`** (`git pull origin main`; при использовании SVN — `svn update`).
|
|
51
|
-
2. Демо-база организации (
|
|
51
|
+
2. Демо-база организации (`<Проект>/$project/#system/work.db`): `node scripts/demo-seed.mjs`.
|
|
52
52
|
3. Документация: канон — **`docs/architecture.md`** (при расхождении он главнее кода и остальных документов; меняет его только владелец проекта). Справочно: **`docs/use-cases.md`**, **`docs/work-mcp.md`**, **`docs/autonomous-install-and-licensing.md`**, **`docs/halogen-provider.md`**, **`docs/chrome-extension.md`**, **`sources/data/progress.md`** (исторические спецификации — в `docs/archive/`).
|
|
53
53
|
4. Протокол экономии токенов/кэша: основная модель **`Gemini 4 Argon`** (`opencode/gemini-4-argon`), не менять модель внутри длинной сессии, разведку делегировать субагенту `explore`, сжимать (`/compact`) на границах этапов. В начале сессии выдать короткий блок **«Рекомендация на шаг»**.
|
|
54
54
|
5. Принцип единого UI: единая форма объектов — `form/objects` (и карточка `form/object` с `designMode`), выборщик класса — `item-class-picker`; `form/builder` удалён (модель данных меняется через ИИ-инструменты `create_class`/`update_class` и вкладку «Система → Реквизиты»).
|
package/autostart.bat
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
@echo off
|
|
2
|
+
setlocal
|
|
3
|
+
set "WORK_DIR=%~dp0"
|
|
4
|
+
if "%WORK_DIR:~-1%"=="\" set "WORK_DIR=%WORK_DIR:~0,-1%"
|
|
5
|
+
pushd "%WORK_DIR%" >nul
|
|
6
|
+
|
|
7
|
+
where node >nul 2>nul
|
|
8
|
+
if errorlevel 1 (
|
|
9
|
+
echo [WORK] Node.js не найден в PATH.
|
|
10
|
+
popd >nul
|
|
11
|
+
exit /b 1
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
set "AS_SCRIPT=%WORK_DIR%\scripts\autostart.mjs"
|
|
15
|
+
if not exist "%AS_SCRIPT%" set "AS_SCRIPT=%WORK_DIR%\node_modules\odant-work\scripts\autostart.mjs"
|
|
16
|
+
if not exist "%AS_SCRIPT%" (
|
|
17
|
+
echo [WORK] Не найден scripts\autostart.mjs
|
|
18
|
+
popd >nul
|
|
19
|
+
exit /b 1
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
set "ACTION=%~1"
|
|
23
|
+
if "%ACTION%"=="" set "ACTION=install"
|
|
24
|
+
|
|
25
|
+
node "%AS_SCRIPT%" "%ACTION%" "--root=%WORK_DIR%"
|
|
26
|
+
set "RC=%ERRORLEVEL%"
|
|
27
|
+
popd >nul
|
|
28
|
+
exit /b %RC%
|
package/autostart.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env sh
|
|
2
|
+
set -eu
|
|
3
|
+
WORK_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
|
4
|
+
cd "$WORK_DIR"
|
|
5
|
+
|
|
6
|
+
if ! command -v node >/dev/null 2>&1; then
|
|
7
|
+
echo "[WORK] Node.js не найден в PATH." >&2
|
|
8
|
+
exit 1
|
|
9
|
+
fi
|
|
10
|
+
|
|
11
|
+
AS_SCRIPT="$WORK_DIR/scripts/autostart.mjs"
|
|
12
|
+
if [ ! -f "$AS_SCRIPT" ]; then
|
|
13
|
+
AS_SCRIPT="$WORK_DIR/node_modules/odant-work/scripts/autostart.mjs"
|
|
14
|
+
fi
|
|
15
|
+
|
|
16
|
+
ACTION="${1:-install}"
|
|
17
|
+
exec node "$AS_SCRIPT" "$ACTION" "--root=$WORK_DIR"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odant-work",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.103",
|
|
4
4
|
"description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "sources/work.js",
|
package/run.mjs
CHANGED
|
@@ -80,6 +80,25 @@ if (!isPackageActual()) {
|
|
|
80
80
|
const workRoot = path.resolve(process.cwd());
|
|
81
81
|
const pkgRoot = path.resolve(currentDirectory);
|
|
82
82
|
|
|
83
|
+
const cliArgs = process.argv.slice(2);
|
|
84
|
+
const autostartArg = cliArgs.find(a => a === '--autostart' || a.startsWith('--autostart='));
|
|
85
|
+
if (autostartArg) {
|
|
86
|
+
const action = autostartArg.includes('=') ? (autostartArg.split('=')[1] || 'install') : 'install';
|
|
87
|
+
const { runAutostartCommand } = await import('./scripts/autostart.mjs');
|
|
88
|
+
await runAutostartCommand(action, { workRoot });
|
|
89
|
+
process.exit(0);
|
|
90
|
+
}
|
|
91
|
+
if (cliArgs.includes('--stop')) {
|
|
92
|
+
const { stopWork } = await import('./scripts/watchdog.mjs');
|
|
93
|
+
const ok = await stopWork({ workRoot });
|
|
94
|
+
process.exit(ok ? 0 : 1);
|
|
95
|
+
}
|
|
96
|
+
if (cliArgs.includes('--status')) {
|
|
97
|
+
const { printStatus } = await import('./scripts/watchdog.mjs');
|
|
98
|
+
await printStatus({ workRoot });
|
|
99
|
+
process.exit(0);
|
|
100
|
+
}
|
|
101
|
+
|
|
83
102
|
/**
|
|
84
103
|
* Если запуск выполнен через `npx odant-work` или из `node_modules/odant-work` в рабочей папке (например, D:\WORK),
|
|
85
104
|
* автоматически разворачиваем или безопасно обновляем рабочую директорию из установленного пакета.
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Настройка автозапуска ODANT-WORK при перезагрузке ОС:
|
|
4
|
+
* - Windows: Планировщик заданий (`schtasks`, задача `ODANT-WORK` -> `scripts/watchdog.mjs --boot`,
|
|
5
|
+
* сначала при старте ОС под SYSTEM; если нет прав администратора — при входе пользователя).
|
|
6
|
+
* - Linux : `systemd` (`odant-work.service` с `Restart=on-failure`, системный юнит для root или `--user` для обычного пользователя);
|
|
7
|
+
* если `systemd` недоступен — `crontab @reboot` через `scripts/watchdog.mjs --boot`.
|
|
8
|
+
*
|
|
9
|
+
* Использование:
|
|
10
|
+
* node scripts/autostart.mjs [install|remove|status] [--root=...]
|
|
11
|
+
*/
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import childProcess from 'node:child_process';
|
|
16
|
+
import { pathToFileURL } from 'node:url';
|
|
17
|
+
import { resolveEntryScript, resolveWorkRoot } from './watchdog.mjs';
|
|
18
|
+
|
|
19
|
+
const WIN_TASK_NAME = 'ODANT-WORK';
|
|
20
|
+
const LINUX_UNIT_NAME = 'odant-work.service';
|
|
21
|
+
|
|
22
|
+
function runCmd(cmd, args, opts = {}) {
|
|
23
|
+
return childProcess.spawnSync(cmd, args, {
|
|
24
|
+
encoding: 'utf8',
|
|
25
|
+
stdio: opts.stdio || ['ignore', 'pipe', 'pipe'],
|
|
26
|
+
windowsHide: true,
|
|
27
|
+
...opts,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function buildWindowsTaskCommand(nodePath, watchdogPath, workRoot) {
|
|
32
|
+
return `"${nodePath}" "${watchdogPath}" --boot "--root=${workRoot}"`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function configureWindowsTaskOptions() {
|
|
36
|
+
const ps = [
|
|
37
|
+
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command',
|
|
38
|
+
`$t = Get-ScheduledTask -TaskName '${WIN_TASK_NAME}' -ErrorAction SilentlyContinue; `
|
|
39
|
+
+ `if ($t) { $s = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1); Set-ScheduledTask -TaskName '${WIN_TASK_NAME}' -Settings $s | Out-Null }`,
|
|
40
|
+
];
|
|
41
|
+
runCmd('powershell', ps);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function installWindows(workRoot) {
|
|
45
|
+
const watchdogPath = path.resolve(import.meta.dirname, 'watchdog.mjs');
|
|
46
|
+
const tr = buildWindowsTaskCommand(process.execPath, watchdogPath, workRoot);
|
|
47
|
+
|
|
48
|
+
// 1. Попытка системной задачи при старте ОС (до входа пользователя)
|
|
49
|
+
let res = runCmd('schtasks', [
|
|
50
|
+
'/Create', '/TN', WIN_TASK_NAME,
|
|
51
|
+
'/TR', tr,
|
|
52
|
+
'/SC', 'ONSTART',
|
|
53
|
+
'/RU', 'SYSTEM',
|
|
54
|
+
'/RL', 'HIGHEST',
|
|
55
|
+
'/F',
|
|
56
|
+
]);
|
|
57
|
+
if (res.status === 0) {
|
|
58
|
+
configureWindowsTaskOptions();
|
|
59
|
+
console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" установлена на старт ОС (SYSTEM, ONSTART).`);
|
|
60
|
+
return { ok: true, platform: 'win32', scope: 'system', trigger: 'ONSTART' };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// 2. Fallback без прав администратора — при входе текущего пользователя
|
|
64
|
+
res = runCmd('schtasks', [
|
|
65
|
+
'/Create', '/TN', WIN_TASK_NAME,
|
|
66
|
+
'/TR', tr,
|
|
67
|
+
'/SC', 'ONLOGON',
|
|
68
|
+
'/RL', 'LIMITED',
|
|
69
|
+
'/F',
|
|
70
|
+
]);
|
|
71
|
+
if (res.status === 0) {
|
|
72
|
+
configureWindowsTaskOptions();
|
|
73
|
+
console.log(`[autostart] Windows: нет прав администратора для ONSTART — установлена задача "${WIN_TASK_NAME}" при входе пользователя (ONLOGON).`);
|
|
74
|
+
console.log('[autostart] Для запуска до входа пользователя выполните скрипт от имени администратора.');
|
|
75
|
+
return { ok: true, platform: 'win32', scope: 'user', trigger: 'ONLOGON' };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const errText = (res.stderr || res.stdout || '').trim() || `exit ${res.status}`;
|
|
79
|
+
throw new Error(`Не удалось создать задачу Планировщика Windows: ${errText}`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function removeWindows() {
|
|
83
|
+
const res = runCmd('schtasks', ['/Delete', '/TN', WIN_TASK_NAME, '/F']);
|
|
84
|
+
if (res.status === 0) {
|
|
85
|
+
console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" удалена.`);
|
|
86
|
+
return { ok: true, removed: true };
|
|
87
|
+
}
|
|
88
|
+
const msg = (res.stderr || res.stdout || '').trim();
|
|
89
|
+
if (/cannot find|не удается найти/i.test(msg)) {
|
|
90
|
+
console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" не была установлена.`);
|
|
91
|
+
return { ok: true, removed: false };
|
|
92
|
+
}
|
|
93
|
+
throw new Error(`Ошибка удаления задачи "${WIN_TASK_NAME}": ${msg || res.status}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function statusWindows() {
|
|
97
|
+
const res = runCmd('schtasks', ['/Query', '/TN', WIN_TASK_NAME, '/FO', 'LIST', '/V']);
|
|
98
|
+
if (res.status === 0) {
|
|
99
|
+
console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" установлена.`);
|
|
100
|
+
const lines = String(res.stdout || '').split(/\r?\n/).filter(l => /TaskName|Статус|Status|Schedule Type|Тип расписания|Run As User|Запуск от имени|Task To Run|Выполнить/i.test(l));
|
|
101
|
+
for (const l of lines)
|
|
102
|
+
console.log(' ' + l.trim());
|
|
103
|
+
return { installed: true, platform: 'win32' };
|
|
104
|
+
}
|
|
105
|
+
console.log(`[autostart] Windows: автозапуск не настроен (задача "${WIN_TASK_NAME}" отсутствует).`);
|
|
106
|
+
return { installed: false, platform: 'win32' };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function buildSystemdUnit({ nodePath, entryScript, workRoot, user = '' } = {}) {
|
|
110
|
+
const lines = [
|
|
111
|
+
'[Unit]',
|
|
112
|
+
'Description=ODANT-WORK Platform Server',
|
|
113
|
+
'After=network-online.target',
|
|
114
|
+
'Wants=network-online.target',
|
|
115
|
+
'',
|
|
116
|
+
'[Service]',
|
|
117
|
+
'Type=simple',
|
|
118
|
+
`WorkingDirectory=${workRoot}`,
|
|
119
|
+
`ExecStart="${nodePath}" "${entryScript}"`,
|
|
120
|
+
'Restart=on-failure',
|
|
121
|
+
'RestartSec=3',
|
|
122
|
+
'Environment=WORK_NO_BROWSER=1',
|
|
123
|
+
'KillSignal=SIGTERM',
|
|
124
|
+
'TimeoutStopSec=15',
|
|
125
|
+
];
|
|
126
|
+
if (user)
|
|
127
|
+
lines.push(`User=${user}`);
|
|
128
|
+
lines.push('', '[Install]', 'WantedBy=multi-user.target', '');
|
|
129
|
+
return lines.join('\n');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function hasSystemd() {
|
|
133
|
+
if (!fs.existsSync('/run/systemd/system'))
|
|
134
|
+
return false;
|
|
135
|
+
const r = runCmd('systemctl', ['--version']);
|
|
136
|
+
return r.status === 0;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isRootLinux() {
|
|
140
|
+
return typeof process.getuid === 'function' && process.getuid() === 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function installLinuxCron(workRoot) {
|
|
144
|
+
const watchdogPath = path.resolve(import.meta.dirname, 'watchdog.mjs');
|
|
145
|
+
const marker = `# odant-work-autostart:${workRoot}`;
|
|
146
|
+
const cronLine = `@reboot "${process.execPath}" "${watchdogPath}" --boot "--root=${workRoot}" ${marker}`;
|
|
147
|
+
const cur = runCmd('crontab', ['-l']);
|
|
148
|
+
const existing = (cur.status === 0 ? cur.stdout : '')
|
|
149
|
+
.split(/\r?\n/)
|
|
150
|
+
.filter(l => l.trim() && !l.includes(marker));
|
|
151
|
+
existing.push(cronLine);
|
|
152
|
+
const put = childProcess.spawnSync('crontab', ['-'], {
|
|
153
|
+
input: existing.join('\n') + '\n',
|
|
154
|
+
encoding: 'utf8',
|
|
155
|
+
});
|
|
156
|
+
if (put.status !== 0)
|
|
157
|
+
throw new Error(`Не удалось обновить crontab: ${(put.stderr || put.stdout || '').trim()}`);
|
|
158
|
+
console.log(`[autostart] Linux (cron @reboot): добавлена запись автозапуска с watchdog для ${workRoot}.`);
|
|
159
|
+
return { ok: true, platform: 'linux', mode: 'cron' };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function installLinux(workRoot) {
|
|
163
|
+
const entryScript = resolveEntryScript(workRoot);
|
|
164
|
+
if (hasSystemd()) {
|
|
165
|
+
if (isRootLinux()) {
|
|
166
|
+
const unitPath = `/etc/systemd/system/${LINUX_UNIT_NAME}`;
|
|
167
|
+
fs.writeFileSync(unitPath, buildSystemdUnit({ nodePath: process.execPath, entryScript, workRoot }), 'utf8');
|
|
168
|
+
const r1 = runCmd('systemctl', ['daemon-reload']);
|
|
169
|
+
const r2 = runCmd('systemctl', ['enable', '--now', LINUX_UNIT_NAME]);
|
|
170
|
+
if (r1.status !== 0 || r2.status !== 0)
|
|
171
|
+
throw new Error(`Ошибка systemctl: ${(r2.stderr || r1.stderr || '').trim()}`);
|
|
172
|
+
console.log(`[autostart] Linux (systemd): установлен системный юнит ${unitPath} (Restart=on-failure).`);
|
|
173
|
+
return { ok: true, platform: 'linux', mode: 'systemd-system', unitPath };
|
|
174
|
+
}
|
|
175
|
+
const userDir = path.join(os.homedir(), '.config', 'systemd', 'user');
|
|
176
|
+
fs.mkdirSync(userDir, { recursive: true });
|
|
177
|
+
const unitPath = path.join(userDir, LINUX_UNIT_NAME);
|
|
178
|
+
const userUnit = buildSystemdUnit({ nodePath: process.execPath, entryScript, workRoot })
|
|
179
|
+
.replace('WantedBy=multi-user.target', 'WantedBy=default.target');
|
|
180
|
+
fs.writeFileSync(unitPath, userUnit, 'utf8');
|
|
181
|
+
runCmd('systemctl', ['--user', 'daemon-reload']);
|
|
182
|
+
const r = runCmd('systemctl', ['--user', 'enable', '--now', LINUX_UNIT_NAME]);
|
|
183
|
+
if (r.status === 0) {
|
|
184
|
+
const userName = os.userInfo().username;
|
|
185
|
+
runCmd('loginctl', ['enable-linger', userName]);
|
|
186
|
+
console.log(`[autostart] Linux (systemd --user): установлен пользовательский юнит ${unitPath}.`);
|
|
187
|
+
console.log('[autostart] Для системного юнита (до входа пользователя) запустите от root.');
|
|
188
|
+
return { ok: true, platform: 'linux', mode: 'systemd-user', unitPath };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return installLinuxCron(workRoot);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function removeLinux(workRoot) {
|
|
195
|
+
let removed = false;
|
|
196
|
+
if (hasSystemd()) {
|
|
197
|
+
if (isRootLinux() && fs.existsSync(`/etc/systemd/system/${LINUX_UNIT_NAME}`)) {
|
|
198
|
+
runCmd('systemctl', ['disable', '--now', LINUX_UNIT_NAME]);
|
|
199
|
+
fs.rmSync(`/etc/systemd/system/${LINUX_UNIT_NAME}`, { force: true });
|
|
200
|
+
runCmd('systemctl', ['daemon-reload']);
|
|
201
|
+
removed = true;
|
|
202
|
+
}
|
|
203
|
+
const userUnit = path.join(os.homedir(), '.config', 'systemd', 'user', LINUX_UNIT_NAME);
|
|
204
|
+
if (fs.existsSync(userUnit)) {
|
|
205
|
+
runCmd('systemctl', ['--user', 'disable', '--now', LINUX_UNIT_NAME]);
|
|
206
|
+
fs.rmSync(userUnit, { force: true });
|
|
207
|
+
runCmd('systemctl', ['--user', 'daemon-reload']);
|
|
208
|
+
removed = true;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const marker = `# odant-work-autostart:${workRoot}`;
|
|
212
|
+
const cur = runCmd('crontab', ['-l']);
|
|
213
|
+
if (cur.status === 0 && cur.stdout.includes(marker)) {
|
|
214
|
+
const filtered = cur.stdout.split(/\r?\n/).filter(l => l.trim() && !l.includes(marker));
|
|
215
|
+
childProcess.spawnSync('crontab', ['-'], { input: filtered.length ? filtered.join('\n') + '\n' : '', encoding: 'utf8' });
|
|
216
|
+
removed = true;
|
|
217
|
+
}
|
|
218
|
+
console.log(removed
|
|
219
|
+
? '[autostart] Linux: автозапуск удалён.'
|
|
220
|
+
: '[autostart] Linux: автозапуск не был настроен.');
|
|
221
|
+
return { ok: true, removed };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function statusLinux(workRoot) {
|
|
225
|
+
if (hasSystemd()) {
|
|
226
|
+
if (fs.existsSync(`/etc/systemd/system/${LINUX_UNIT_NAME}`)) {
|
|
227
|
+
const st = runCmd('systemctl', ['is-enabled', LINUX_UNIT_NAME]);
|
|
228
|
+
const act = runCmd('systemctl', ['is-active', LINUX_UNIT_NAME]);
|
|
229
|
+
console.log(`[autostart] Linux (systemd system): enabled=${(st.stdout || '').trim()}, active=${(act.stdout || '').trim()}`);
|
|
230
|
+
return { installed: true, mode: 'systemd-system' };
|
|
231
|
+
}
|
|
232
|
+
const userUnit = path.join(os.homedir(), '.config', 'systemd', 'user', LINUX_UNIT_NAME);
|
|
233
|
+
if (fs.existsSync(userUnit)) {
|
|
234
|
+
const st = runCmd('systemctl', ['--user', 'is-enabled', LINUX_UNIT_NAME]);
|
|
235
|
+
const act = runCmd('systemctl', ['--user', 'is-active', LINUX_UNIT_NAME]);
|
|
236
|
+
console.log(`[autostart] Linux (systemd --user): enabled=${(st.stdout || '').trim()}, active=${(act.stdout || '').trim()}`);
|
|
237
|
+
return { installed: true, mode: 'systemd-user' };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const marker = `# odant-work-autostart:${workRoot}`;
|
|
241
|
+
const cur = runCmd('crontab', ['-l']);
|
|
242
|
+
if (cur.status === 0 && cur.stdout.includes(marker)) {
|
|
243
|
+
console.log('[autostart] Linux (cron @reboot): автозапуск настроен.');
|
|
244
|
+
return { installed: true, mode: 'cron' };
|
|
245
|
+
}
|
|
246
|
+
console.log('[autostart] Linux: автозапуск не настроен.');
|
|
247
|
+
return { installed: false };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export async function runAutostartCommand(action = 'status', { workRoot = resolveWorkRoot() } = {}) {
|
|
251
|
+
const act = String(action || 'status').toLowerCase();
|
|
252
|
+
if (process.platform === 'win32') {
|
|
253
|
+
if (act === 'install' || act === 'on' || act === 'enable')
|
|
254
|
+
return installWindows(workRoot);
|
|
255
|
+
if (act === 'remove' || act === 'uninstall' || act === 'off' || act === 'disable')
|
|
256
|
+
return removeWindows();
|
|
257
|
+
return statusWindows();
|
|
258
|
+
}
|
|
259
|
+
if (process.platform === 'linux') {
|
|
260
|
+
if (act === 'install' || act === 'on' || act === 'enable')
|
|
261
|
+
return installLinux(workRoot);
|
|
262
|
+
if (act === 'remove' || act === 'uninstall' || act === 'off' || act === 'disable')
|
|
263
|
+
return removeLinux(workRoot);
|
|
264
|
+
return statusLinux(workRoot);
|
|
265
|
+
}
|
|
266
|
+
throw new Error(`Автозапуск поддерживается на Windows и Linux (текущая ОС: ${process.platform})`);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const isMain = process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
|
|
270
|
+
if (isMain) {
|
|
271
|
+
const args = process.argv.slice(2);
|
|
272
|
+
const rootArg = args.find(a => a.startsWith('--root='))?.slice(7) || '';
|
|
273
|
+
const action = args.find(a => !a.startsWith('-')) || 'install';
|
|
274
|
+
try {
|
|
275
|
+
await runAutostartCommand(action, { workRoot: resolveWorkRoot(rootArg) });
|
|
276
|
+
}
|
|
277
|
+
catch (err) {
|
|
278
|
+
console.error('[autostart]', err?.message || err);
|
|
279
|
+
process.exit(1);
|
|
280
|
+
}
|
|
281
|
+
}
|
package/scripts/import-bis.mjs
CHANGED
|
@@ -124,8 +124,8 @@ export function scaffoldBisClasses() {
|
|
|
124
124
|
}
|
|
125
125
|
}`);
|
|
126
126
|
|
|
127
|
-
// 1.2. Подразделения ($
|
|
128
|
-
writeClassJs('accounting', '$
|
|
127
|
+
// 1.2. Подразделения ($department) и рабочие места (ROLES + LINKS)
|
|
128
|
+
writeClassJs('accounting', '$department', `{
|
|
129
129
|
icon: "icons:account-balance",
|
|
130
130
|
label: "Бухгалтерия",
|
|
131
131
|
"#security": {
|
|
@@ -229,7 +229,7 @@ export function scaffoldBisClasses() {
|
|
|
229
229
|
}
|
|
230
230
|
}`);
|
|
231
231
|
|
|
232
|
-
writeClassJs('orders', '$
|
|
232
|
+
writeClassJs('orders', '$department', `{
|
|
233
233
|
icon: "icons:shopping-cart",
|
|
234
234
|
label: "Заказы и договоры",
|
|
235
235
|
"#security": {
|
|
@@ -254,7 +254,7 @@ export function scaffoldBisClasses() {
|
|
|
254
254
|
}
|
|
255
255
|
}`);
|
|
256
256
|
|
|
257
|
-
writeClassJs('hr', '$
|
|
257
|
+
writeClassJs('hr', '$department', `{
|
|
258
258
|
icon: "icons:supervisor-account",
|
|
259
259
|
label: "Кадры и делопроизводство",
|
|
260
260
|
"#security": {
|
|
@@ -277,7 +277,7 @@ export function scaffoldBisClasses() {
|
|
|
277
277
|
}
|
|
278
278
|
}`);
|
|
279
279
|
|
|
280
|
-
writeClassJs('development', '$
|
|
280
|
+
writeClassJs('development', '$department', `{
|
|
281
281
|
icon: "carbon:code",
|
|
282
282
|
label: "Разработка и выставки",
|
|
283
283
|
"#security": {
|
|
@@ -240,8 +240,8 @@ export function scaffoldDelovayaClasses() {
|
|
|
240
240
|
}
|
|
241
241
|
}`);
|
|
242
242
|
|
|
243
|
-
// 2.2. Подразделения ($
|
|
244
|
-
writeClassJs('accounting', '$
|
|
243
|
+
// 2.2. Подразделения ($department) и рабочие места (ROLES + LINKS)
|
|
244
|
+
writeClassJs('accounting', '$department', `{
|
|
245
245
|
icon: "icons:account-balance",
|
|
246
246
|
label: "Бухгалтерия",
|
|
247
247
|
"#security": {
|
|
@@ -322,7 +322,7 @@ export function scaffoldDelovayaClasses() {
|
|
|
322
322
|
}
|
|
323
323
|
}`);
|
|
324
324
|
|
|
325
|
-
writeClassJs('orders', '$
|
|
325
|
+
writeClassJs('orders', '$department', `{
|
|
326
326
|
icon: "icons:shopping-cart",
|
|
327
327
|
label: "Отдел заказов",
|
|
328
328
|
"#security": {
|
|
@@ -344,7 +344,7 @@ export function scaffoldDelovayaClasses() {
|
|
|
344
344
|
}
|
|
345
345
|
}`);
|
|
346
346
|
|
|
347
|
-
writeClassJs('hr', '$
|
|
347
|
+
writeClassJs('hr', '$department', `{
|
|
348
348
|
icon: "icons:supervisor-account",
|
|
349
349
|
label: "Отдел кадров",
|
|
350
350
|
"#security": {
|
|
@@ -363,7 +363,7 @@ export function scaffoldDelovayaClasses() {
|
|
|
363
363
|
}
|
|
364
364
|
}`);
|
|
365
365
|
|
|
366
|
-
writeClassJs('research', '$
|
|
366
|
+
writeClassJs('research', '$department', `{
|
|
367
367
|
icon: "carbon:analytics",
|
|
368
368
|
label: "Маркетинговые исследования",
|
|
369
369
|
"#security": {
|