odant-work 1.0.79 → 1.0.81
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/#system/package-manifest.json +14 -12
- package/$server/$folder/lib/explorer/explorer.js +56 -1
- package/$server/$folder/lib/node/node.js +266 -0
- package/$server/$folder/lib/support/support.js +1232 -0
- package/package.json +1 -1
- package/sources/client/folder.js +4 -0
- package/sources/host/auto-updater.js +79 -14
- package/sources/modules/support/index.js +414 -0
- package/sources/server/access/gateway.js +5 -2
- package/sources/server/class.js +11 -0
- package/sources/server/server.js +85 -6
- package/sources/work.js +9 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odant-work",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.81",
|
|
4
4
|
"description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "sources/work.js",
|
package/sources/client/folder.js
CHANGED
|
@@ -272,11 +272,15 @@ export class $folder extends $item {
|
|
|
272
272
|
|| method.startsWith('trainer_')
|
|
273
273
|
|| method.startsWith('provider_')
|
|
274
274
|
|| method.startsWith('license_')
|
|
275
|
+
|| method.startsWith('support_')
|
|
275
276
|
|| method.startsWith('messenger_')
|
|
276
277
|
|| method.startsWith('distro_')
|
|
277
278
|
|| method.startsWith('agent_')
|
|
278
279
|
|| method === 'security_update'
|
|
279
280
|
|| method === 'export_distro'
|
|
281
|
+
|| method === 'version_status'
|
|
282
|
+
|| method === 'version_update_restart'
|
|
283
|
+
|| method === 'restart_server'
|
|
280
284
|
))
|
|
281
285
|
|| (method === 'logs' && params.mode && params.mode !== 'folder' && params.mode !== 'files');
|
|
282
286
|
return WORK.fetch?.(this.short || '/', method, params, post_data).then(res => {
|
|
@@ -21,10 +21,11 @@ import { spawn } from 'node:child_process';
|
|
|
21
21
|
|
|
22
22
|
export const PACKAGE_NAME = 'odant-work';
|
|
23
23
|
export const DEFAULT_NPM_REGISTRY = process.env.WORK_NPM_REGISTRY || 'https://registry.npmjs.org';
|
|
24
|
-
export const DEFAULT_CHECK_INTERVAL_MS =
|
|
24
|
+
export const DEFAULT_CHECK_INTERVAL_MS = 10 * 60_000; // каждые 10 минут
|
|
25
25
|
|
|
26
26
|
const MANIFEST_REL_PATH = '#system/package-manifest.json';
|
|
27
27
|
const STATE_REL_PATH = '#system/auto-update.json';
|
|
28
|
+
const RUNNING_VERSIONS = new Map();
|
|
28
29
|
|
|
29
30
|
/**
|
|
30
31
|
* Сравнить две semver-версии (например, "1.0.4" и "1.0.3").
|
|
@@ -279,7 +280,7 @@ export function loadAutoUpdateState(rootDir = '.') {
|
|
|
279
280
|
enabled: true,
|
|
280
281
|
packageName: PACKAGE_NAME,
|
|
281
282
|
registryUrl: DEFAULT_NPM_REGISTRY,
|
|
282
|
-
|
|
283
|
+
checkIntervalMinutes: 10,
|
|
283
284
|
lastCheckAt: null,
|
|
284
285
|
lastUpdateAt: null,
|
|
285
286
|
lastVersionFrom: null,
|
|
@@ -314,6 +315,48 @@ export function saveAutoUpdateState(patch = {}, rootDir = '.') {
|
|
|
314
315
|
return next;
|
|
315
316
|
}
|
|
316
317
|
|
|
318
|
+
/**
|
|
319
|
+
* Запомнить (при первом обращении) и вернуть версию пакета, с которой стартовал текущий процесс.
|
|
320
|
+
*/
|
|
321
|
+
export function getRunningVersion(rootDir = '.') {
|
|
322
|
+
const absRoot = path.resolve(rootDir);
|
|
323
|
+
if (!RUNNING_VERSIONS.has(absRoot))
|
|
324
|
+
RUNNING_VERSIONS.set(absRoot, readLocalPackageVersion(absRoot));
|
|
325
|
+
return RUNNING_VERSIONS.get(absRoot);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Текущий статус версий (без сетевого запроса):
|
|
330
|
+
* запущенная в памяти, версия на диске и последняя известная из npm.
|
|
331
|
+
*/
|
|
332
|
+
export function getVersionStatus({ rootDir = '.' } = {}) {
|
|
333
|
+
const absRoot = path.resolve(rootDir);
|
|
334
|
+
const runningVersion = getRunningVersion(absRoot);
|
|
335
|
+
const diskVersion = readLocalPackageVersion(absRoot);
|
|
336
|
+
const state = loadAutoUpdateState(absRoot);
|
|
337
|
+
const npmVersion = state.latestAvailableVersion ? String(state.latestAvailableVersion) : '';
|
|
338
|
+
|
|
339
|
+
let latestVersion = runningVersion;
|
|
340
|
+
if (compareSemver(diskVersion, latestVersion) > 0)
|
|
341
|
+
latestVersion = diskVersion;
|
|
342
|
+
if (npmVersion && compareSemver(npmVersion, latestVersion) > 0)
|
|
343
|
+
latestVersion = npmVersion;
|
|
344
|
+
|
|
345
|
+
const updateAvailable = compareSemver(latestVersion, runningVersion) > 0;
|
|
346
|
+
const needsDownload = Boolean(npmVersion && compareSemver(npmVersion, diskVersion) > 0);
|
|
347
|
+
return {
|
|
348
|
+
packageName: state.packageName || PACKAGE_NAME,
|
|
349
|
+
runningVersion,
|
|
350
|
+
diskVersion,
|
|
351
|
+
latestVersion,
|
|
352
|
+
npmVersion: npmVersion || null,
|
|
353
|
+
updateAvailable,
|
|
354
|
+
needsDownload,
|
|
355
|
+
checkedAt: state.lastCheckAt || null,
|
|
356
|
+
lastError: state.lastError || null,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
317
360
|
/**
|
|
318
361
|
* Проверить наличие более свежей версии пакета odant-work в npm registry.
|
|
319
362
|
*/
|
|
@@ -323,40 +366,50 @@ export async function checkForNpmUpdates({
|
|
|
323
366
|
packageName,
|
|
324
367
|
fetchImpl = globalThis.fetch,
|
|
325
368
|
} = {}) {
|
|
326
|
-
const
|
|
369
|
+
const absRoot = path.resolve(rootDir);
|
|
370
|
+
const runningVersion = getRunningVersion(absRoot);
|
|
371
|
+
const state = loadAutoUpdateState(absRoot);
|
|
327
372
|
const pkgName = packageName || state.packageName || PACKAGE_NAME;
|
|
328
373
|
const regUrl = String(registryUrl || state.registryUrl || DEFAULT_NPM_REGISTRY).replace(/\/+$/, '');
|
|
329
|
-
const currentVersion = readLocalPackageVersion(
|
|
374
|
+
const currentVersion = readLocalPackageVersion(absRoot);
|
|
330
375
|
const now = Date.now();
|
|
331
376
|
|
|
332
377
|
const metaUrl = `${regUrl}/${encodeURIComponent(pkgName)}/latest`;
|
|
333
378
|
const res = await fetchImpl(metaUrl, {
|
|
334
|
-
headers: { 'Accept': 'application/json' },
|
|
379
|
+
headers: { 'Accept': 'application/json', 'Cache-Control': 'no-cache' },
|
|
335
380
|
});
|
|
336
381
|
if (!res.ok) {
|
|
337
382
|
const errText = await res.text().catch(() => '');
|
|
338
383
|
const errMsg = `npm registry (${metaUrl}) ответил HTTP ${res.status}: ${errText.slice(0, 160)}`;
|
|
339
|
-
saveAutoUpdateState({ lastCheckAt: now, lastError: errMsg },
|
|
384
|
+
saveAutoUpdateState({ lastCheckAt: now, lastError: errMsg }, absRoot);
|
|
340
385
|
throw new Error(errMsg);
|
|
341
386
|
}
|
|
342
387
|
|
|
343
388
|
const meta = await res.json();
|
|
344
|
-
const
|
|
345
|
-
|
|
389
|
+
const npmVersion = String(meta.version || currentVersion);
|
|
390
|
+
let latestVersion = npmVersion;
|
|
391
|
+
if (compareSemver(currentVersion, latestVersion) > 0)
|
|
392
|
+
latestVersion = currentVersion;
|
|
393
|
+
const diskNeedsUpdate = compareSemver(npmVersion, currentVersion) > 0;
|
|
394
|
+
const updateAvailable = compareSemver(latestVersion, runningVersion) > 0 || diskNeedsUpdate;
|
|
346
395
|
const tarballUrl = String(meta.dist?.tarball || '');
|
|
347
396
|
const shasum = String(meta.dist?.shasum || '');
|
|
348
397
|
|
|
349
398
|
const updatedState = saveAutoUpdateState({
|
|
350
399
|
lastCheckAt: now,
|
|
351
|
-
latestAvailableVersion:
|
|
400
|
+
latestAvailableVersion: npmVersion,
|
|
352
401
|
updateAvailable,
|
|
353
402
|
lastError: null,
|
|
354
|
-
},
|
|
403
|
+
}, absRoot);
|
|
355
404
|
|
|
356
405
|
return {
|
|
357
406
|
packageName: pkgName,
|
|
407
|
+
runningVersion,
|
|
358
408
|
currentVersion,
|
|
409
|
+
diskVersion: currentVersion,
|
|
359
410
|
latestVersion,
|
|
411
|
+
npmVersion,
|
|
412
|
+
diskNeedsUpdate,
|
|
360
413
|
updateAvailable,
|
|
361
414
|
tarballUrl,
|
|
362
415
|
shasum,
|
|
@@ -751,7 +804,14 @@ export async function checkAndApplyNpmUpdate({
|
|
|
751
804
|
installDeps = false,
|
|
752
805
|
} = {}) {
|
|
753
806
|
const check = await checkForNpmUpdates({ rootDir, registryUrl, packageName, fetchImpl });
|
|
754
|
-
if (!check.
|
|
807
|
+
if (!check.diskNeedsUpdate) {
|
|
808
|
+
if (compareSemver(check.latestVersion, check.runningVersion) > 0) {
|
|
809
|
+
return {
|
|
810
|
+
updated: true,
|
|
811
|
+
alreadyOnDisk: true,
|
|
812
|
+
...check,
|
|
813
|
+
};
|
|
814
|
+
}
|
|
755
815
|
return {
|
|
756
816
|
updated: false,
|
|
757
817
|
...check,
|
|
@@ -810,14 +870,16 @@ export async function checkAndApplyNpmUpdate({
|
|
|
810
870
|
let updateTimer = null;
|
|
811
871
|
|
|
812
872
|
/**
|
|
813
|
-
* Запустить фоновую периодическую проверку
|
|
873
|
+
* Запустить фоновую периодическую проверку обновлений из npm (по умолчанию каждые 10 мин, только проверка).
|
|
814
874
|
*/
|
|
815
875
|
export function startAutoUpdateDaemon({
|
|
816
876
|
rootDir = '.',
|
|
817
877
|
intervalMs,
|
|
818
878
|
runOnStart = true,
|
|
879
|
+
autoApply = process.env.WORK_AUTO_APPLY === '1',
|
|
819
880
|
fetchImpl = globalThis.fetch,
|
|
820
881
|
} = {}) {
|
|
882
|
+
getRunningVersion(rootDir);
|
|
821
883
|
ensurePackageManifest(rootDir);
|
|
822
884
|
const state = loadAutoUpdateState(rootDir);
|
|
823
885
|
if (updateTimer) {
|
|
@@ -828,7 +890,10 @@ export function startAutoUpdateDaemon({
|
|
|
828
890
|
try {
|
|
829
891
|
const cur = loadAutoUpdateState(rootDir);
|
|
830
892
|
if (!cur.enabled) return;
|
|
831
|
-
|
|
893
|
+
if (autoApply)
|
|
894
|
+
await checkAndApplyNpmUpdate({ rootDir, fetchImpl, installDeps: true });
|
|
895
|
+
else
|
|
896
|
+
await checkForNpmUpdates({ rootDir, fetchImpl });
|
|
832
897
|
}
|
|
833
898
|
catch (err) {
|
|
834
899
|
console.warn('[auto-updater]', err?.message || err);
|
|
@@ -838,7 +903,7 @@ export function startAutoUpdateDaemon({
|
|
|
838
903
|
const bootTimer = setTimeout(runCheck, 5_000);
|
|
839
904
|
bootTimer.unref?.();
|
|
840
905
|
}
|
|
841
|
-
const period = Number(intervalMs || (state.
|
|
906
|
+
const period = Number(intervalMs || (state.checkIntervalMinutes ? state.checkIntervalMinutes * 60_000 : DEFAULT_CHECK_INTERVAL_MS));
|
|
842
907
|
updateTimer = setInterval(runCheck, period);
|
|
843
908
|
updateTimer.unref?.();
|
|
844
909
|
return updateTimer;
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Серверный модуль службы поддержки и встроенного Remote Desktop в WORK (sources/modules/support/index.js).
|
|
3
|
+
*
|
|
4
|
+
* Связывает локальный сервер WORK с work.odant.org через приватные методы сервера:
|
|
5
|
+
* - подписывает обращения из #system/owner-token.json и #system/license.json (не раскрывая их браузеру);
|
|
6
|
+
* - работает как для лицензированных серверов (SLA), так и для гостевых/пробных установок;
|
|
7
|
+
* - изолирует тикеты по автору (USER видит только свои, BOSS корня — все по серверу);
|
|
8
|
+
* - проксирует медиавложения и сигналинг/кадры Remote Desktop, исключая проблемы CORS в ЛВС.
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { DEV_MODE } from '../../host/config.js';
|
|
13
|
+
import { getVersionStatus } from '../../host/auto-updater.js';
|
|
14
|
+
import {
|
|
15
|
+
DEFAULT_LICENSE_HUB_URL,
|
|
16
|
+
loadOwnerTokenBinding,
|
|
17
|
+
loadLocalLicense,
|
|
18
|
+
getHardwareIdentity,
|
|
19
|
+
} from '../license/index.js';
|
|
20
|
+
|
|
21
|
+
const SYSTEM_DIR = './#system';
|
|
22
|
+
const SUPPORT_STORE_FILE = 'support-tickets.json';
|
|
23
|
+
|
|
24
|
+
function parseBody(params = {}) {
|
|
25
|
+
if (params.post && typeof params.post === 'string') {
|
|
26
|
+
try { return JSON.parse(params.post); }
|
|
27
|
+
catch { return {}; }
|
|
28
|
+
}
|
|
29
|
+
if (params.post && typeof params.post === 'object')
|
|
30
|
+
return params.post;
|
|
31
|
+
return params;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function resolveSystemDir(storage) {
|
|
35
|
+
const rootDir = path.resolve(storage?.dir || process.cwd());
|
|
36
|
+
return path.join(rootDir, '#system');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function readLocalTicketsStore(systemDir = SYSTEM_DIR) {
|
|
40
|
+
const file = path.join(systemDir, SUPPORT_STORE_FILE);
|
|
41
|
+
try {
|
|
42
|
+
if (fs.existsSync(file)) {
|
|
43
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
44
|
+
if (raw && Array.isArray(raw.tickets))
|
|
45
|
+
return raw;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch { /* ignore */ }
|
|
49
|
+
return { tickets: [] };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function writeLocalTicketsStore(systemDir = SYSTEM_DIR, storeObj = { tickets: [] }) {
|
|
53
|
+
fs.mkdirSync(systemDir, { recursive: true });
|
|
54
|
+
const file = path.join(systemDir, SUPPORT_STORE_FILE);
|
|
55
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
56
|
+
fs.writeFileSync(tmp, JSON.stringify(storeObj, null, 2), 'utf8');
|
|
57
|
+
fs.renameSync(tmp, file);
|
|
58
|
+
return storeObj;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function resolveHubUrl(systemDir = SYSTEM_DIR, override = '') {
|
|
62
|
+
if (override)
|
|
63
|
+
return String(override).replace(/\/+$/, '');
|
|
64
|
+
if (process.env.WORK_SUPPORT_HUB_URL)
|
|
65
|
+
return String(process.env.WORK_SUPPORT_HUB_URL).replace(/\/+$/, '');
|
|
66
|
+
const binding = loadOwnerTokenBinding(systemDir);
|
|
67
|
+
if (binding?.hubUrl)
|
|
68
|
+
return String(binding.hubUrl).replace(/\/+$/, '');
|
|
69
|
+
const lic = loadLocalLicense(undefined, { systemDir });
|
|
70
|
+
if (lic?.hubUrl)
|
|
71
|
+
return String(lic.hubUrl).replace(/\/+$/, '');
|
|
72
|
+
return String(DEFAULT_LICENSE_HUB_URL).replace(/\/+$/, '');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function resolveUserContext(storage, params = {}) {
|
|
76
|
+
const uid = storage?.constructor?.resolveUid?.(params) || '';
|
|
77
|
+
if (!uid)
|
|
78
|
+
throw new Error('Требуется вход в систему WORK');
|
|
79
|
+
const roles = typeof storage?.roles === 'function'
|
|
80
|
+
? await storage.roles(params).catch(() => [])
|
|
81
|
+
: [];
|
|
82
|
+
const isBoss = Boolean(DEV_MODE || roles.includes('BOSS'));
|
|
83
|
+
|
|
84
|
+
let userName = uid;
|
|
85
|
+
let userEmail = '';
|
|
86
|
+
try {
|
|
87
|
+
const uItem = await globalThis.WORK?.get_item?.(`/USERS/${uid}`).catch(() => null);
|
|
88
|
+
if (uItem) {
|
|
89
|
+
await uItem.init?.catch?.(() => {});
|
|
90
|
+
userName = uItem.DATA?.label || uItem.label || uid;
|
|
91
|
+
userEmail = uItem.DATA?.email || '';
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch { /* ignore */ }
|
|
95
|
+
return { uid, isBoss, userName: String(userName || uid), userEmail: String(userEmail || '') };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function createSupportTicketFromWork(storage, params = {}, { fetchImpl = globalThis.fetch } = {}) {
|
|
99
|
+
const { uid, userName, userEmail } = await resolveUserContext(storage, params);
|
|
100
|
+
const body = parseBody(params);
|
|
101
|
+
const text = String(body.text || '').trim();
|
|
102
|
+
const attachments = Array.isArray(body.attachments) ? body.attachments : [];
|
|
103
|
+
if (!text && !attachments.length)
|
|
104
|
+
throw new Error('Опишите проблему или приложите скриншот / видео');
|
|
105
|
+
|
|
106
|
+
const rootDir = path.resolve(storage?.dir || process.cwd());
|
|
107
|
+
const systemDir = path.join(rootDir, '#system');
|
|
108
|
+
const hubUrl = resolveHubUrl(systemDir, body.hubUrl);
|
|
109
|
+
const binding = loadOwnerTokenBinding(systemDir);
|
|
110
|
+
const lic = loadLocalLicense(undefined, { systemDir });
|
|
111
|
+
const hw = getHardwareIdentity();
|
|
112
|
+
const ver = getVersionStatus({ rootDir });
|
|
113
|
+
|
|
114
|
+
const techContext = body.includeTech !== false
|
|
115
|
+
? {
|
|
116
|
+
...(body.techContext && typeof body.techContext === 'object' ? body.techContext : {}),
|
|
117
|
+
version: ver.runningVersion,
|
|
118
|
+
diskVersion: ver.diskVersion,
|
|
119
|
+
serverId: hw.serverId,
|
|
120
|
+
hwid: hw.hwid,
|
|
121
|
+
}
|
|
122
|
+
: null;
|
|
123
|
+
|
|
124
|
+
const payload = {
|
|
125
|
+
ownerToken: binding?.token || '',
|
|
126
|
+
licenseId: lic?.unlicensed ? '' : (lic?.licenseId || ''),
|
|
127
|
+
serverId: hw.serverId,
|
|
128
|
+
serverName: storage?.DATA?.label || storage?.label || 'WORK',
|
|
129
|
+
customerName: lic?.customer?.name || binding?.email || storage?.DATA?.label || 'Сервер WORK',
|
|
130
|
+
userId: uid,
|
|
131
|
+
userName: body.userName || userName,
|
|
132
|
+
userEmail: body.userEmail || userEmail || binding?.email || '',
|
|
133
|
+
text: text || 'Скриншот / запись проблемы без текстового описания',
|
|
134
|
+
techContext,
|
|
135
|
+
attachments,
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const res = await fetchImpl(`${hubUrl}/api/support/tickets`, {
|
|
139
|
+
method: 'POST',
|
|
140
|
+
headers: { 'Content-Type': 'application/json' },
|
|
141
|
+
body: JSON.stringify(payload),
|
|
142
|
+
});
|
|
143
|
+
const data = await res.json().catch(() => ({}));
|
|
144
|
+
if (!res.ok || !data.ticket)
|
|
145
|
+
throw new Error(data.error || `Сервер поддержки ответил HTTP ${res.status}`);
|
|
146
|
+
|
|
147
|
+
const ticket = data.ticket;
|
|
148
|
+
const accessKey = String(ticket.ticketAccessKey || '');
|
|
149
|
+
const sanitized = { ...ticket };
|
|
150
|
+
delete sanitized.ticketAccessKey;
|
|
151
|
+
|
|
152
|
+
const store = readLocalTicketsStore(systemDir);
|
|
153
|
+
const now = Date.now();
|
|
154
|
+
store.tickets.unshift({
|
|
155
|
+
ticketId: sanitized.ticketId,
|
|
156
|
+
ticketAccessKey: accessKey,
|
|
157
|
+
hubUrl,
|
|
158
|
+
createdByUid: uid,
|
|
159
|
+
createdByName: payload.userName,
|
|
160
|
+
createdAt: sanitized.createdAt || now,
|
|
161
|
+
lastReadByUid: { [uid]: now },
|
|
162
|
+
cached: sanitized,
|
|
163
|
+
});
|
|
164
|
+
writeLocalTicketsStore(systemDir, store);
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
ok: true,
|
|
168
|
+
ticket: { ...sanitized, unreadCount: 0, own: true },
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function listSupportTicketsForWork(storage, params = {}, { fetchImpl = globalThis.fetch } = {}) {
|
|
173
|
+
const { uid, isBoss } = await resolveUserContext(storage, params);
|
|
174
|
+
const rootDir = path.resolve(storage?.dir || process.cwd());
|
|
175
|
+
const systemDir = path.join(rootDir, '#system');
|
|
176
|
+
const defaultHubUrl = resolveHubUrl(systemDir);
|
|
177
|
+
const store = readLocalTicketsStore(systemDir);
|
|
178
|
+
|
|
179
|
+
const visibleRecs = store.tickets.filter(rec => rec && (isBoss || rec.createdByUid === uid));
|
|
180
|
+
if (!visibleRecs.length) {
|
|
181
|
+
return { ok: true, tickets: [], unreadTotal: 0, remoteRequests: 0, isBoss, hubUrl: defaultHubUrl };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Группируем по hubUrl и синхронизируем свежие статусы/сообщения с work.odant.org
|
|
185
|
+
const byHub = new Map();
|
|
186
|
+
for (const rec of visibleRecs) {
|
|
187
|
+
const u = String(rec.hubUrl || defaultHubUrl).replace(/\/+$/, '');
|
|
188
|
+
if (!byHub.has(u)) byHub.set(u, []);
|
|
189
|
+
byHub.get(u).push(rec);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
let syncError = '';
|
|
193
|
+
const syncedById = new Map();
|
|
194
|
+
for (const [hubUrl, recs] of byHub.entries()) {
|
|
195
|
+
try {
|
|
196
|
+
const res = await fetchImpl(`${hubUrl}/api/support/tickets/sync`, {
|
|
197
|
+
method: 'POST',
|
|
198
|
+
headers: { 'Content-Type': 'application/json' },
|
|
199
|
+
body: JSON.stringify({
|
|
200
|
+
tickets: recs.map(r => ({ ticketId: r.ticketId, ticketAccessKey: r.ticketAccessKey })),
|
|
201
|
+
}),
|
|
202
|
+
signal: AbortSignal.timeout(8000),
|
|
203
|
+
});
|
|
204
|
+
const data = await res.json().catch(() => ({}));
|
|
205
|
+
if (res.ok && Array.isArray(data.tickets)) {
|
|
206
|
+
for (const t of data.tickets) {
|
|
207
|
+
if (t?.ticketId) syncedById.set(t.ticketId, t);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
else if (!res.ok) {
|
|
211
|
+
syncError = data.error || `HTTP ${res.status}`;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
syncError = String(err?.message || err);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
let changed = false;
|
|
220
|
+
let unreadTotal = 0;
|
|
221
|
+
let remoteRequests = 0;
|
|
222
|
+
const tickets = [];
|
|
223
|
+
|
|
224
|
+
for (const rec of visibleRecs) {
|
|
225
|
+
const fresh = syncedById.get(rec.ticketId);
|
|
226
|
+
if (fresh) {
|
|
227
|
+
rec.cached = fresh;
|
|
228
|
+
changed = true;
|
|
229
|
+
}
|
|
230
|
+
const t = fresh || rec.cached || { ticketId: rec.ticketId, status: 'open', messages: [] };
|
|
231
|
+
const lastRead = Number(rec.lastReadByUid?.[uid] || 0);
|
|
232
|
+
const unreadCount = (t.messages || []).filter(m =>
|
|
233
|
+
(m.from === 'support' || m.role === 'engineer') && Number(m.time || 0) > lastRead
|
|
234
|
+
).length;
|
|
235
|
+
unreadTotal += unreadCount;
|
|
236
|
+
if (t.remote?.state === 'requested')
|
|
237
|
+
remoteRequests++;
|
|
238
|
+
tickets.push({
|
|
239
|
+
...t,
|
|
240
|
+
unreadCount,
|
|
241
|
+
own: rec.createdByUid === uid,
|
|
242
|
+
createdByUid: rec.createdByUid,
|
|
243
|
+
createdByName: rec.createdByName || t.userName || rec.createdByUid,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (changed)
|
|
248
|
+
writeLocalTicketsStore(systemDir, store);
|
|
249
|
+
|
|
250
|
+
tickets.sort((a, b) => Number(b.createdAt || 0) - Number(a.createdAt || 0));
|
|
251
|
+
return {
|
|
252
|
+
ok: true,
|
|
253
|
+
tickets,
|
|
254
|
+
unreadTotal,
|
|
255
|
+
remoteRequests,
|
|
256
|
+
isBoss,
|
|
257
|
+
hubUrl: defaultHubUrl,
|
|
258
|
+
...(syncError ? { syncError } : {}),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function findAuthorizedRecord(systemDir, ticketId, uid, isBoss) {
|
|
263
|
+
const store = readLocalTicketsStore(systemDir);
|
|
264
|
+
const rec = store.tickets.find(r => r?.ticketId === ticketId);
|
|
265
|
+
if (!rec)
|
|
266
|
+
throw new Error('Обращение не найдено на этом сервере');
|
|
267
|
+
if (!isBoss && rec.createdByUid !== uid)
|
|
268
|
+
throw new Error('Нет доступа к чужому обращению');
|
|
269
|
+
return { store, rec };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export async function replySupportTicketFromWork(storage, params = {}, { fetchImpl = globalThis.fetch } = {}) {
|
|
273
|
+
const { uid, isBoss, userName } = await resolveUserContext(storage, params);
|
|
274
|
+
const body = parseBody(params);
|
|
275
|
+
const ticketId = String(body.ticketId || params.ticketId || '').trim();
|
|
276
|
+
const text = String(body.text || '').trim();
|
|
277
|
+
const attachments = Array.isArray(body.attachments) ? body.attachments : [];
|
|
278
|
+
if (!ticketId)
|
|
279
|
+
throw new Error('Не указан номер обращения');
|
|
280
|
+
if (!text && !attachments.length)
|
|
281
|
+
throw new Error('Введите сообщение или приложите файл');
|
|
282
|
+
|
|
283
|
+
const systemDir = resolveSystemDir(storage);
|
|
284
|
+
const { store, rec } = findAuthorizedRecord(systemDir, ticketId, uid, isBoss);
|
|
285
|
+
const hubUrl = resolveHubUrl(systemDir, rec.hubUrl);
|
|
286
|
+
|
|
287
|
+
const res = await fetchImpl(`${hubUrl}/api/support/tickets/${encodeURIComponent(ticketId)}/message`, {
|
|
288
|
+
method: 'POST',
|
|
289
|
+
headers: { 'Content-Type': 'application/json' },
|
|
290
|
+
body: JSON.stringify({
|
|
291
|
+
ticketAccessKey: rec.ticketAccessKey,
|
|
292
|
+
author: userName,
|
|
293
|
+
userId: uid,
|
|
294
|
+
text,
|
|
295
|
+
attachments,
|
|
296
|
+
}),
|
|
297
|
+
});
|
|
298
|
+
const data = await res.json().catch(() => ({}));
|
|
299
|
+
if (!res.ok || !data.ticket)
|
|
300
|
+
throw new Error(data.error || `Ошибка отправки сообщения (HTTP ${res.status})`);
|
|
301
|
+
|
|
302
|
+
rec.cached = data.ticket;
|
|
303
|
+
rec.lastReadByUid ??= {};
|
|
304
|
+
rec.lastReadByUid[uid] = Date.now();
|
|
305
|
+
writeLocalTicketsStore(systemDir, store);
|
|
306
|
+
return { ok: true, ticket: { ...data.ticket, unreadCount: 0, own: rec.createdByUid === uid } };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function markSupportTicketRead(storage, params = {}) {
|
|
310
|
+
const { uid, isBoss } = await resolveUserContext(storage, params);
|
|
311
|
+
const body = parseBody(params);
|
|
312
|
+
const ticketId = String(body.ticketId || params.ticketId || '').trim();
|
|
313
|
+
const systemDir = resolveSystemDir(storage);
|
|
314
|
+
const store = readLocalTicketsStore(systemDir);
|
|
315
|
+
const now = Date.now();
|
|
316
|
+
let changed = false;
|
|
317
|
+
for (const rec of store.tickets) {
|
|
318
|
+
if (!rec) continue;
|
|
319
|
+
if (!isBoss && rec.createdByUid !== uid) continue;
|
|
320
|
+
if (!ticketId || rec.ticketId === ticketId) {
|
|
321
|
+
rec.lastReadByUid ??= {};
|
|
322
|
+
rec.lastReadByUid[uid] = now;
|
|
323
|
+
changed = true;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (changed)
|
|
327
|
+
writeLocalTicketsStore(systemDir, store);
|
|
328
|
+
return { ok: true };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export async function fetchSupportMediaFromWork(storage, params = {}, { fetchImpl = globalThis.fetch } = {}) {
|
|
332
|
+
const { uid, isBoss } = await resolveUserContext(storage, params);
|
|
333
|
+
const ticketId = String(params.ticketId || '').trim();
|
|
334
|
+
const file = path.basename(String(params.file || '').trim());
|
|
335
|
+
if (!ticketId || !file)
|
|
336
|
+
throw new Error('Не указаны параметры медиафайла');
|
|
337
|
+
const systemDir = resolveSystemDir(storage);
|
|
338
|
+
const { rec } = findAuthorizedRecord(systemDir, ticketId, uid, isBoss);
|
|
339
|
+
const hubUrl = resolveHubUrl(systemDir, rec.hubUrl);
|
|
340
|
+
const url = `${hubUrl}/api/support/media/${encodeURIComponent(ticketId)}/${encodeURIComponent(file)}?key=${encodeURIComponent(rec.ticketAccessKey)}`;
|
|
341
|
+
const res = await fetchImpl(url);
|
|
342
|
+
if (!res.ok)
|
|
343
|
+
throw new Error(`Не удалось загрузить вложение (HTTP ${res.status})`);
|
|
344
|
+
const mime = res.headers.get('content-type') || 'application/octet-stream';
|
|
345
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
346
|
+
return {
|
|
347
|
+
ok: true,
|
|
348
|
+
mime,
|
|
349
|
+
dataUrl: `data:${mime};base64,${buf.toString('base64')}`,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export async function relaySupportRemoteFromWork(storage, params = {}, { fetchImpl = globalThis.fetch } = {}) {
|
|
354
|
+
const { uid, isBoss } = await resolveUserContext(storage, params);
|
|
355
|
+
const body = parseBody(params);
|
|
356
|
+
const ticketId = String(body.ticketId || params.ticketId || '').trim();
|
|
357
|
+
if (!ticketId)
|
|
358
|
+
throw new Error('Не указан номер обращения');
|
|
359
|
+
const systemDir = resolveSystemDir(storage);
|
|
360
|
+
const { rec } = findAuthorizedRecord(systemDir, ticketId, uid, isBoss);
|
|
361
|
+
const hubUrl = resolveHubUrl(systemDir, rec.hubUrl);
|
|
362
|
+
|
|
363
|
+
const payload = { ...body, ticketAccessKey: rec.ticketAccessKey };
|
|
364
|
+
delete payload.ticketId;
|
|
365
|
+
|
|
366
|
+
const res = await fetchImpl(`${hubUrl}/api/support/remote/${encodeURIComponent(ticketId)}/client`, {
|
|
367
|
+
method: 'POST',
|
|
368
|
+
headers: { 'Content-Type': 'application/json' },
|
|
369
|
+
body: JSON.stringify(payload),
|
|
370
|
+
});
|
|
371
|
+
const data = await res.json().catch(() => ({}));
|
|
372
|
+
if (!res.ok)
|
|
373
|
+
throw new Error(data.error || `Ошибка сигналинга Remote Desktop (HTTP ${res.status})`);
|
|
374
|
+
return data;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export const SUPPORT_METHODS = Object.freeze({
|
|
378
|
+
support_list: {
|
|
379
|
+
level: 'user',
|
|
380
|
+
fn: async function (p = {}) {
|
|
381
|
+
return listSupportTicketsForWork(this, p);
|
|
382
|
+
},
|
|
383
|
+
},
|
|
384
|
+
support_create: {
|
|
385
|
+
level: 'user',
|
|
386
|
+
fn: async function (p = {}) {
|
|
387
|
+
return createSupportTicketFromWork(this, p);
|
|
388
|
+
},
|
|
389
|
+
},
|
|
390
|
+
support_reply: {
|
|
391
|
+
level: 'user',
|
|
392
|
+
fn: async function (p = {}) {
|
|
393
|
+
return replySupportTicketFromWork(this, p);
|
|
394
|
+
},
|
|
395
|
+
},
|
|
396
|
+
support_mark_read: {
|
|
397
|
+
level: 'user',
|
|
398
|
+
fn: async function (p = {}) {
|
|
399
|
+
return markSupportTicketRead(this, p);
|
|
400
|
+
},
|
|
401
|
+
},
|
|
402
|
+
support_media: {
|
|
403
|
+
level: 'user',
|
|
404
|
+
fn: async function (p = {}) {
|
|
405
|
+
return fetchSupportMediaFromWork(this, p);
|
|
406
|
+
},
|
|
407
|
+
},
|
|
408
|
+
support_remote: {
|
|
409
|
+
level: 'user',
|
|
410
|
+
fn: async function (p = {}) {
|
|
411
|
+
return relaySupportRemoteFromWork(this, p);
|
|
412
|
+
},
|
|
413
|
+
},
|
|
414
|
+
});
|
|
@@ -18,6 +18,7 @@ import { audit } from './audit.js';
|
|
|
18
18
|
import { DATA_METHODS } from '../../data/api.js';
|
|
19
19
|
import { TRAINER_METHODS } from '../../modules/trainer/index.js';
|
|
20
20
|
import { LICENSE_METHODS } from '../../modules/license/index.js';
|
|
21
|
+
import { SUPPORT_METHODS } from '../../modules/support/index.js';
|
|
21
22
|
import { NOTIFY_METHODS } from '../../modules/notify/index.js';
|
|
22
23
|
import { INVITE_METHODS } from './invites.js';
|
|
23
24
|
import { KLADR_METHODS } from '../../modules/kladr/index.js';
|
|
@@ -77,6 +78,8 @@ export const MEMBERS = Object.freeze({
|
|
|
77
78
|
...Object.fromEntries(Object.entries(TRAINER_METHODS).map(([name, m]) => [name, m.level])),
|
|
78
79
|
// лицензирование ПАК WORK (sources/modules/license/index.js)
|
|
79
80
|
...Object.fromEntries(Object.entries(LICENSE_METHODS).map(([name, m]) => [name, m.level])),
|
|
81
|
+
// служба поддержки и Remote Desktop (sources/modules/support/index.js)
|
|
82
|
+
...Object.fromEntries(Object.entries(SUPPORT_METHODS).map(([name, m]) => [name, m.level])),
|
|
80
83
|
// каналы уведомлений Telegram / MAX (sources/modules/notify/index.js)
|
|
81
84
|
...Object.fromEntries(Object.entries(NOTIFY_METHODS).map(([name, m]) => [name, m.level])),
|
|
82
85
|
// одноразовые приглашения пользователей на рабочие места (sources/server/access/invites.js)
|
|
@@ -85,10 +88,10 @@ export const MEMBERS = Object.freeze({
|
|
|
85
88
|
...Object.fromEntries(Object.entries(KLADR_METHODS).map(([name, m]) => [name, m.level])),
|
|
86
89
|
remove_push_subscription: L.WRITE, send_push_notification: L.WRITE,
|
|
87
90
|
// администрирование
|
|
88
|
-
delete: L.ADMIN, npm: L.ADMIN, restart_normal: L.ADMIN, read_secret: L.ADMIN,
|
|
91
|
+
delete: L.ADMIN, npm: L.ADMIN, restart_normal: L.ADMIN, restart_server: L.ADMIN, read_secret: L.ADMIN,
|
|
89
92
|
save_secret: L.ADMIN, clear_rag: L.ADMIN, security_log: L.ADMIN, agent_panel: L.ADMIN,
|
|
90
93
|
set_enabled: L.ADMIN, export_archive: L.READ, import_archive: L.ADMIN, delete_log_entry: L.WRITE,
|
|
91
|
-
distro_info: L.READ, export_distro: L.READ,
|
|
94
|
+
distro_info: L.READ, export_distro: L.READ, version_status: L.READ, version_update_restart: L.ADMIN,
|
|
92
95
|
});
|
|
93
96
|
|
|
94
97
|
/** Никогда не вызываются снаружи, даже если объявлены в class.js. */
|
package/sources/server/class.js
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
findProviderPreset,
|
|
31
31
|
} from '../modules/trainer/index.js';
|
|
32
32
|
import { LICENSE_METHODS } from '../modules/license/index.js';
|
|
33
|
+
import { SUPPORT_METHODS } from '../modules/support/index.js';
|
|
33
34
|
import { NOTIFY_METHODS, resolveBotForPoint, sanitizeBotForUi } from '../modules/notify/index.js';
|
|
34
35
|
import { INVITE_METHODS } from './access/invites.js';
|
|
35
36
|
import { KLADR_METHODS } from '../modules/kladr/index.js';
|
|
@@ -899,6 +900,16 @@ for (const [name, m] of Object.entries(LICENSE_METHODS)) {
|
|
|
899
900
|
configurable: true,
|
|
900
901
|
});
|
|
901
902
|
}
|
|
903
|
+
// методы службы поддержки и Remote Desktop (support_*)
|
|
904
|
+
for (const [name, m] of Object.entries(SUPPORT_METHODS)) {
|
|
905
|
+
Object.defineProperty($class.prototype, name, {
|
|
906
|
+
value: function (params = {}) {
|
|
907
|
+
return m.fn.call(this, params);
|
|
908
|
+
},
|
|
909
|
+
writable: true,
|
|
910
|
+
configurable: true,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
902
913
|
// методы мессенджеров и уведомлений точки (messenger_*)
|
|
903
914
|
for (const [name, m] of Object.entries(NOTIFY_METHODS)) {
|
|
904
915
|
Object.defineProperty($class.prototype, name, {
|