odant-work 1.0.65 → 1.0.67
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 +56 -59
- package/{PROJECTS → $server/$folder/$class}/$domain/handlers/methods/restore/$handler/class.js +40 -24
- package/$server/$folder/$class/$structure/$server/handlers/methods/distro/$handler/class.js +0 -2
- package/$server/$folder/$class/$structure/handlers/methods/archive/$handler/class.js +27 -0
- package/$server/$folder/$class/$structure/handlers/pages/data/$handler/class.js +9 -0
- package/$server/$folder/$class/$structure/handlers/pages/data/$handler/data.js +310 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/class.js +1 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +160 -1
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +2 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/class.js +1 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/class.js +10 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/system.js +233 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent.js +289 -0
- package/$server/$folder/$class/$structure/handlers/pages/form/{search/$handler → system/$handler/tabs}/search.js +4 -1
- package/$server/$folder/$class/$structure/handlers/pages/form/{staff/$handler → system/$handler/tabs}/staff.js +122 -14
- package/$server/$folder/$class/handlers/pages/form/editor/$handler/class.js +3 -0
- package/$server/$folder/$class/handlers/pages/form/folder/$handler/class.js +10 -6
- package/$server/$folder/handlers/pages/form/$handler/form.js +27 -2
- package/$server/$folder/lib/dot/dot-math.js +1 -1
- package/$server/$folder/lib/dot/dot.js +19 -5
- package/$server/$folder/lib/explorer/explorer.js +29 -15
- package/$server/$folder/lib/node/node.js +49 -4
- package/$server/$folder/lib/security/users/users.js +68 -3
- package/$server/$folder/lib/tools/tools.js +3 -3
- package/$server/$folder/lib/tree/tree.js +29 -13
- package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/gantt/$handler/gantt.js" +293 -1
- package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/scheduler/$handler/scheduler.js" +234 -1
- package/ORGANIZATIONS/$domain/class.js +1 -0
- package/PROJECTS/$domain/class.js +1 -0
- package/package.json +1 -1
- package/sources/client/handler.js +27 -11
- package/sources/client.js +36 -0
- package/sources/data/api.js +25 -5
- package/sources/data/db.js +39 -0
- package/sources/data/scope.js +2 -1
- package/sources/host/websocket.js +22 -0
- package/sources/modules/agent/index.js +11 -1
- package/sources/modules/agent/node-rules.js +171 -0
- package/sources/modules/agent/resources.js +1 -0
- package/sources/modules/agent/scheduler.js +75 -17
- package/sources/modules/agent/triggers.js +486 -198
- package/sources/modules/agent/twin-bus.js +163 -0
- package/sources/server/access/gateway.js +3 -0
- package/sources/server/access/links.js +8 -4
- package/sources/server/access/policy.js +7 -2
- package/sources/server/access/workplaces.js +14 -5
- package/sources/server/chat-threads.js +640 -0
- package/sources/server/class/archive.js +4 -3
- package/sources/server/class/feed.js +59 -0
- package/sources/server/class/security.js +18 -3
- package/sources/server/handler.js +1 -2
- package/$server/$folder/$class/$structure/$base/handlers/methods/archive/$handler/class.js +0 -23
- package/$server/$folder/$class/$structure/$project/handlers/methods/archive/$handler/class.js +0 -23
- package/$server/$folder/$class/$structure/$server/handlers/pages/form/license/$handler/class.js +0 -9
- package/$server/$folder/$class/$structure/handlers/pages/form/database/$handler/class.js +0 -9
- package/$server/$folder/$class/$structure/handlers/pages/form/gantt/$handler/class.js +0 -27
- package/$server/$folder/$class/$structure/handlers/pages/form/gantt/$handler/gantt.js +0 -293
- package/$server/$folder/$class/$structure/handlers/pages/form/messengers/$handler/class.js +0 -5
- package/$server/$folder/$class/$structure/handlers/pages/form/scheduler/$handler/class.js +0 -27
- package/$server/$folder/$class/$structure/handlers/pages/form/scheduler/$handler/scheduler.js +0 -234
- package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/class.js +0 -5
- package/$server/$folder/$class/$structure/handlers/pages/form/staff/$handler/class.js +0 -5
- package/ORGANIZATIONS/$domain/handlers/methods/restore/$handler/class.js +0 -173
- /package/$server/$folder/$class/$structure/handlers/pages/form/{database/$handler → system/$handler/tabs}/database.js +0 -0
- /package/$server/$folder/$class/$structure/{$server/handlers/pages/form/license/$handler → handlers/pages/form/system/$handler/tabs}/license.js +0 -0
- /package/$server/$folder/$class/$structure/handlers/pages/form/{messengers/$handler → system/$handler/tabs}/messengers.js +0 -0
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ядро бесед мессенджера WORK (`chat_threads`, `chat_participants`, `chat_messages`):
|
|
3
|
+
* - kind = 'twin' : персональный диалог пользователя с Агентом узла ($server/$base/$project/$structure);
|
|
4
|
+
* хранится в work.db организации/проекта (или .data/work.db для корня $server).
|
|
5
|
+
* BOSS узла может просматривать взаимодействия пользователей/клиентов с этим Агентом.
|
|
6
|
+
* - kind = 'dm' : приватный диалог Человек ↔ Человек (включая диалог со своим $user-двойником);
|
|
7
|
+
* хранится в корневой .data/work.db и доступен строго двоим участникам.
|
|
8
|
+
* - kind = 'group' : тематическая группа людей; хранится в БД контекста создания.
|
|
9
|
+
*/
|
|
10
|
+
import crypto from 'node:crypto';
|
|
11
|
+
import * as LOGS from './logs.js';
|
|
12
|
+
import * as REFS from './access/refs.js';
|
|
13
|
+
import * as WORKPLACES from './access/workplaces.js';
|
|
14
|
+
import { dataDb, tx } from '../data/db.js';
|
|
15
|
+
import { DEV_MODE } from '../host/config.js';
|
|
16
|
+
|
|
17
|
+
function notifyChatEvent(uids, payload) {
|
|
18
|
+
import('../host/websocket.js')
|
|
19
|
+
.then(m => m.broadcastChatEvent?.(uids, payload))
|
|
20
|
+
.catch(() => {});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const ACCESS_DENIED = 'Доступ запрещён';
|
|
24
|
+
|
|
25
|
+
export function twinThreadId(nodePath, uid) {
|
|
26
|
+
const norm = String(nodePath || '/').trim().replace(/\/+$/, '') || '/';
|
|
27
|
+
return `twin:${norm}:${String(uid || '').trim()}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function dmThreadId(uid1, uid2) {
|
|
31
|
+
const pair = [String(uid1 || '').trim(), String(uid2 || '').trim()].sort();
|
|
32
|
+
return `dm:${pair[0]}|${pair[1]}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function rootDirOf() {
|
|
36
|
+
return globalThis.WORK?.real_dir || globalThis.WORK?.dir || process.cwd();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function dbForThreadStorage(storage, kind = '') {
|
|
40
|
+
if (kind === 'dm' || storage?.type === '$user')
|
|
41
|
+
return dataDb('', rootDirOf());
|
|
42
|
+
return LOGS.dbForStorage(storage);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function resolveActorUid(storage, params = {}) {
|
|
46
|
+
const uid = storage?.constructor?.resolveUid?.(params);
|
|
47
|
+
if (uid)
|
|
48
|
+
return uid;
|
|
49
|
+
if (typeof params?.uid === 'string' && params.uid.trim() && (DEV_MODE || !params?.session || params.session.$user === globalThis.WORK))
|
|
50
|
+
return params.uid.trim();
|
|
51
|
+
if (params?.session?.$user === globalThis.WORK)
|
|
52
|
+
return globalThis.WORK?.id || 'WORK';
|
|
53
|
+
return '';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function parseJsonSafe(raw, fallback) {
|
|
57
|
+
try {
|
|
58
|
+
return raw ? JSON.parse(raw) : fallback;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return fallback;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function normalizeAttachments(raw) {
|
|
66
|
+
let arr = raw;
|
|
67
|
+
if (typeof raw === 'string')
|
|
68
|
+
arr = parseJsonSafe(raw, []);
|
|
69
|
+
if (!Array.isArray(arr))
|
|
70
|
+
return [];
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const item of arr) {
|
|
73
|
+
if (!item) continue;
|
|
74
|
+
if (typeof item === 'string') {
|
|
75
|
+
const p = REFS.normPath(item);
|
|
76
|
+
if (p) out.push({ path: p, name: p.split('/').pop() || 'file' });
|
|
77
|
+
}
|
|
78
|
+
else if (typeof item === 'object' && item.path) {
|
|
79
|
+
const p = REFS.normPath(item.path);
|
|
80
|
+
if (p) out.push({ path: p, name: String(item.name || p.split('/').pop() || 'file') });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function normalizeMentions(raw) {
|
|
87
|
+
let arr = raw;
|
|
88
|
+
if (typeof raw === 'string')
|
|
89
|
+
arr = parseJsonSafe(raw, raw.split(',').map(s => s.trim()).filter(Boolean));
|
|
90
|
+
if (!Array.isArray(arr))
|
|
91
|
+
return [];
|
|
92
|
+
return [...new Set(arr.map(s => String(s || '').trim()).filter(Boolean))];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function formatMessageRow(r) {
|
|
96
|
+
if (!r) return null;
|
|
97
|
+
return {
|
|
98
|
+
id: Number(r.id),
|
|
99
|
+
threadId: r.thread_id,
|
|
100
|
+
sender: r.sender,
|
|
101
|
+
kind: r.kind || 'text',
|
|
102
|
+
content: r.content || '',
|
|
103
|
+
replyTo: r.reply_to != null ? Number(r.reply_to) : null,
|
|
104
|
+
mentions: parseJsonSafe(r.mentions, []),
|
|
105
|
+
attachments: parseJsonSafe(r.attachments, []),
|
|
106
|
+
taskPath: r.task_path || '',
|
|
107
|
+
meta: parseJsonSafe(r.meta, {}),
|
|
108
|
+
created: Number(r.created) || 0,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Открыть или создать беседу (twin на $structure, dm на $user, или group). */
|
|
113
|
+
export async function openThread(storage, params = {}) {
|
|
114
|
+
const uid = resolveActorUid(storage, params);
|
|
115
|
+
if (!uid)
|
|
116
|
+
throw new Error(ACCESS_DENIED);
|
|
117
|
+
|
|
118
|
+
const requestedKind = String(params.kind || '').trim();
|
|
119
|
+
const kind = requestedKind === 'group' ? 'group' : (storage?.type === '$user' || requestedKind === 'dm' ? 'dm' : 'twin');
|
|
120
|
+
const db = await dbForThreadStorage(storage, kind);
|
|
121
|
+
const now = Date.now();
|
|
122
|
+
|
|
123
|
+
if (kind === 'dm') {
|
|
124
|
+
const peerId = String(params.peerId || (storage?.type === '$user' ? storage.id : '')).trim();
|
|
125
|
+
if (!peerId)
|
|
126
|
+
throw new Error('Не указан собеседник (peerId)');
|
|
127
|
+
const threadId = dmThreadId(uid, peerId);
|
|
128
|
+
const title = String(params.title || '').trim();
|
|
129
|
+
tx(db, () => {
|
|
130
|
+
db.prepare(`
|
|
131
|
+
INSERT OR IGNORE INTO chat_threads (id, kind, node_path, title, created_by, created, updated)
|
|
132
|
+
VALUES (?, 'dm', '', ?, ?, ?, ?)
|
|
133
|
+
`).run(threadId, title, uid, now, now);
|
|
134
|
+
db.prepare(`
|
|
135
|
+
INSERT OR IGNORE INTO chat_participants (thread_id, uid, role, last_read_id, joined)
|
|
136
|
+
VALUES (?, ?, 'member', 0, ?)
|
|
137
|
+
`).run(threadId, uid, now);
|
|
138
|
+
if (peerId !== uid) {
|
|
139
|
+
db.prepare(`
|
|
140
|
+
INSERT OR IGNORE INTO chat_participants (thread_id, uid, role, last_read_id, joined)
|
|
141
|
+
VALUES (?, ?, 'member', 0, ?)
|
|
142
|
+
`).run(threadId, peerId, now);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
return getThreadWithMeta(db, threadId, uid);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (kind === 'group') {
|
|
149
|
+
const threadId = params.threadId && String(params.threadId).startsWith('group:')
|
|
150
|
+
? String(params.threadId)
|
|
151
|
+
: `group:${crypto.randomUUID()}`;
|
|
152
|
+
const nodePath = LOGS.feedPathOf(storage);
|
|
153
|
+
const title = String(params.title || 'Группа').trim();
|
|
154
|
+
let members = Array.isArray(params.participants)
|
|
155
|
+
? params.participants
|
|
156
|
+
: (typeof params.participants === 'string' ? parseJsonSafe(params.participants, []) : []);
|
|
157
|
+
members = [...new Set([uid, ...members.map(m => String(m || '').trim()).filter(Boolean)])];
|
|
158
|
+
tx(db, () => {
|
|
159
|
+
db.prepare(`
|
|
160
|
+
INSERT OR IGNORE INTO chat_threads (id, kind, node_path, title, created_by, created, updated)
|
|
161
|
+
VALUES (?, 'group', ?, ?, ?, ?, ?)
|
|
162
|
+
`).run(threadId, nodePath, title, uid, now, now);
|
|
163
|
+
for (const m of members) {
|
|
164
|
+
db.prepare(`
|
|
165
|
+
INSERT OR IGNORE INTO chat_participants (thread_id, uid, role, last_read_id, joined)
|
|
166
|
+
VALUES (?, ?, ?, 0, ?)
|
|
167
|
+
`).run(threadId, m, m === uid ? 'owner' : 'member', now);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
return getThreadWithMeta(db, threadId, uid);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// kind === 'twin': персональный диалог пользователя с Агентом узла ($server/$base/$project/$structure)
|
|
174
|
+
if (!DEV_MODE && params?.session && params.session.$user !== globalThis.WORK) {
|
|
175
|
+
const canSee = await storage.canSee?.(storage, params).catch(() => false);
|
|
176
|
+
const roles = await storage.roles?.(params).catch(() => []);
|
|
177
|
+
if (!canSee && !roles.length)
|
|
178
|
+
throw new Error(ACCESS_DENIED);
|
|
179
|
+
}
|
|
180
|
+
const nodePath = LOGS.feedPathOf(storage);
|
|
181
|
+
const threadId = twinThreadId(nodePath, uid);
|
|
182
|
+
const roles = await storage.roles?.(params).catch(() => []) || [];
|
|
183
|
+
const partRole = roles.includes('BOSS') ? 'owner' : (roles.includes('CLIENT') && !roles.includes('USER') ? 'client' : 'member');
|
|
184
|
+
const title = String(params.title || storage.DATA?.label || storage.label || storage.id || nodePath).trim();
|
|
185
|
+
tx(db, () => {
|
|
186
|
+
db.prepare(`
|
|
187
|
+
INSERT OR IGNORE INTO chat_threads (id, kind, node_path, title, created_by, created, updated)
|
|
188
|
+
VALUES (?, 'twin', ?, ?, ?, ?, ?)
|
|
189
|
+
`).run(threadId, nodePath, title, uid, now, now);
|
|
190
|
+
db.prepare(`
|
|
191
|
+
INSERT OR IGNORE INTO chat_participants (thread_id, uid, role, last_read_id, joined)
|
|
192
|
+
VALUES (?, ?, ?, 0, ?)
|
|
193
|
+
`).run(threadId, uid, partRole, now);
|
|
194
|
+
});
|
|
195
|
+
return getThreadWithMeta(db, threadId, uid);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function getThreadWithMeta(db, threadId, uid) {
|
|
199
|
+
const t = db.prepare('SELECT * FROM chat_threads WHERE id = ?').get(threadId);
|
|
200
|
+
if (!t) return null;
|
|
201
|
+
const parts = db.prepare('SELECT uid, role, last_read_id, joined FROM chat_participants WHERE thread_id = ?').all(threadId);
|
|
202
|
+
const mine = parts.find(p => p.uid === uid);
|
|
203
|
+
const lastReadId = Number(mine?.last_read_id) || 0;
|
|
204
|
+
const unreadRow = mine
|
|
205
|
+
? db.prepare('SELECT COUNT(*) AS cnt FROM chat_messages WHERE thread_id = ? AND id > ? AND sender != ?').get(threadId, lastReadId, uid)
|
|
206
|
+
: { cnt: 0 };
|
|
207
|
+
const lastMsg = db.prepare('SELECT * FROM chat_messages WHERE thread_id = ? ORDER BY id DESC LIMIT 1').get(threadId);
|
|
208
|
+
const countRow = db.prepare('SELECT COUNT(*) AS cnt FROM chat_messages WHERE thread_id = ?').get(threadId);
|
|
209
|
+
return {
|
|
210
|
+
id: t.id,
|
|
211
|
+
kind: t.kind,
|
|
212
|
+
nodePath: t.node_path,
|
|
213
|
+
title: t.title,
|
|
214
|
+
createdBy: t.created_by,
|
|
215
|
+
created: Number(t.created),
|
|
216
|
+
updated: Number(t.updated),
|
|
217
|
+
participants: parts.map(p => ({
|
|
218
|
+
uid: p.uid,
|
|
219
|
+
role: p.role,
|
|
220
|
+
lastReadId: Number(p.last_read_id) || 0,
|
|
221
|
+
joined: Number(p.joined) || 0,
|
|
222
|
+
})),
|
|
223
|
+
unreadCount: Number(unreadRow?.cnt) || 0,
|
|
224
|
+
messageCount: Number(countRow?.cnt) || 0,
|
|
225
|
+
lastMessage: formatMessageRow(lastMsg),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Список бесед: личных/своих (mine) либо всех взаимодействий с Агентом узла (audit, только BOSS). */
|
|
230
|
+
export async function listThreads(storage, params = {}) {
|
|
231
|
+
const uid = resolveActorUid(storage, params);
|
|
232
|
+
if (!uid)
|
|
233
|
+
throw new Error(ACCESS_DENIED);
|
|
234
|
+
|
|
235
|
+
const mode = params.mode === 'audit' ? 'audit' : 'mine';
|
|
236
|
+
const limit = Math.max(1, Math.min(200, Number(params.limit) || 100));
|
|
237
|
+
|
|
238
|
+
if (mode === 'audit') {
|
|
239
|
+
if (!(await storage._canViewLocalFeed?.(params)))
|
|
240
|
+
throw new Error(ACCESS_DENIED);
|
|
241
|
+
const db = await dbForThreadStorage(storage, 'twin');
|
|
242
|
+
const nodePath = LOGS.feedPathOf(storage);
|
|
243
|
+
const rows = db.prepare(`
|
|
244
|
+
SELECT id FROM chat_threads
|
|
245
|
+
WHERE kind = 'twin' AND node_path = ?
|
|
246
|
+
ORDER BY updated DESC
|
|
247
|
+
LIMIT ?
|
|
248
|
+
`).all(nodePath, limit);
|
|
249
|
+
return rows.map(r => getThreadWithMeta(db, r.id, uid)).filter(Boolean);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const kind = storage?.type === '$user' ? 'dm' : '';
|
|
253
|
+
const db = await dbForThreadStorage(storage, kind);
|
|
254
|
+
const nodeFilter = params.nodePath != null ? String(params.nodePath).trim() : '';
|
|
255
|
+
const rows = nodeFilter
|
|
256
|
+
? db.prepare(`
|
|
257
|
+
SELECT t.id FROM chat_threads t
|
|
258
|
+
JOIN chat_participants p ON p.thread_id = t.id
|
|
259
|
+
WHERE p.uid = ? AND t.node_path = ?
|
|
260
|
+
ORDER BY t.updated DESC
|
|
261
|
+
LIMIT ?
|
|
262
|
+
`).all(uid, nodeFilter, limit)
|
|
263
|
+
: db.prepare(`
|
|
264
|
+
SELECT t.id FROM chat_threads t
|
|
265
|
+
JOIN chat_participants p ON p.thread_id = t.id
|
|
266
|
+
WHERE p.uid = ?
|
|
267
|
+
ORDER BY t.updated DESC
|
|
268
|
+
LIMIT ?
|
|
269
|
+
`).all(uid, limit);
|
|
270
|
+
return rows.map(r => getThreadWithMeta(db, r.id, uid)).filter(Boolean);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Получить сообщения беседы с проверкой прав (участник или BOSS узла для twin-аудита). */
|
|
274
|
+
export async function listMessages(storage, params = {}) {
|
|
275
|
+
const uid = resolveActorUid(storage, params);
|
|
276
|
+
if (!uid)
|
|
277
|
+
throw new Error(ACCESS_DENIED);
|
|
278
|
+
|
|
279
|
+
const threadId = String(params.threadId || '').trim();
|
|
280
|
+
if (!threadId)
|
|
281
|
+
throw new Error('Не указан threadId');
|
|
282
|
+
|
|
283
|
+
const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
|
|
284
|
+
const db = await dbForThreadStorage(storage, kindHint);
|
|
285
|
+
const thread = getThreadWithMeta(db, threadId, uid);
|
|
286
|
+
if (!thread)
|
|
287
|
+
return { thread: null, messages: [] };
|
|
288
|
+
|
|
289
|
+
const isParticipant = thread.participants.some(p => p.uid === uid);
|
|
290
|
+
if (!isParticipant) {
|
|
291
|
+
// Чужой DM никогда не открывается; чужой twin-диалог узла открывается только BOSS этого узла
|
|
292
|
+
const canAuditTwin = thread.kind === 'twin'
|
|
293
|
+
&& thread.nodePath === LOGS.feedPathOf(storage)
|
|
294
|
+
&& await storage._canViewLocalFeed?.(params);
|
|
295
|
+
if (!canAuditTwin)
|
|
296
|
+
throw new Error(ACCESS_DENIED);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const limit = Math.max(1, Math.min(200, Number(params.limit) || 100));
|
|
300
|
+
const beforeId = Number(params.beforeId) || 0;
|
|
301
|
+
const rows = beforeId > 0
|
|
302
|
+
? db.prepare(`
|
|
303
|
+
SELECT * FROM chat_messages
|
|
304
|
+
WHERE thread_id = ? AND id < ?
|
|
305
|
+
ORDER BY id DESC
|
|
306
|
+
LIMIT ?
|
|
307
|
+
`).all(threadId, beforeId, limit)
|
|
308
|
+
: db.prepare(`
|
|
309
|
+
SELECT * FROM chat_messages
|
|
310
|
+
WHERE thread_id = ?
|
|
311
|
+
ORDER BY id DESC
|
|
312
|
+
LIMIT ?
|
|
313
|
+
`).all(threadId, limit);
|
|
314
|
+
|
|
315
|
+
rows.reverse();
|
|
316
|
+
return { thread, messages: rows.map(formatMessageRow) };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Отправить сообщение в беседу (создав её при необходимости) + выдать доступ к вложениям + WebSocket-рассылка. */
|
|
320
|
+
export async function sendMessage(storage, params = {}) {
|
|
321
|
+
const uid = resolveActorUid(storage, params);
|
|
322
|
+
if (!uid)
|
|
323
|
+
throw new Error(ACCESS_DENIED);
|
|
324
|
+
|
|
325
|
+
const isTwinBot = params.asTwin === true && (!params.session || params.session.$user === globalThis.WORK || DEV_MODE);
|
|
326
|
+
const sender = isTwinBot ? '$twin' : uid;
|
|
327
|
+
|
|
328
|
+
let threadId = String(params.threadId || '').trim();
|
|
329
|
+
const kindHint = threadId ? (threadId.startsWith('dm:') ? 'dm' : 'twin') : (storage?.type === '$user' || params.kind === 'dm' ? 'dm' : 'twin');
|
|
330
|
+
const db = await dbForThreadStorage(storage, kindHint);
|
|
331
|
+
|
|
332
|
+
let thread = threadId ? getThreadWithMeta(db, threadId, uid) : null;
|
|
333
|
+
if (!thread) {
|
|
334
|
+
thread = await openThread(storage, params);
|
|
335
|
+
threadId = thread.id;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const isParticipant = thread.participants.some(p => p.uid === uid);
|
|
339
|
+
if (!isParticipant && !isTwinBot)
|
|
340
|
+
throw new Error(ACCESS_DENIED);
|
|
341
|
+
|
|
342
|
+
const content = String(params.message ?? params.content ?? '');
|
|
343
|
+
const msgKind = String(params.kind || 'text').trim() || 'text';
|
|
344
|
+
const taskPath = String(params.taskPath || '').trim();
|
|
345
|
+
const replyTo = params.replyTo != null && Number.isFinite(Number(params.replyTo)) ? Number(params.replyTo) : null;
|
|
346
|
+
const mentions = normalizeMentions(params.mentions);
|
|
347
|
+
const attachments = normalizeAttachments(params.attachments);
|
|
348
|
+
const meta = (params.meta && typeof params.meta === 'object') ? params.meta : (typeof params.meta === 'string' ? parseJsonSafe(params.meta, {}) : {});
|
|
349
|
+
|
|
350
|
+
// Проверяем видимость вложений отправителем и выдаём участникам беседы доступ к конкретным файлам (Q8)
|
|
351
|
+
const attPaths = attachments.map(a => a.path);
|
|
352
|
+
if (taskPath)
|
|
353
|
+
attPaths.push(REFS.normPath(taskPath));
|
|
354
|
+
if (attPaths.length) {
|
|
355
|
+
await LOGS.assertIncludesVisible(attPaths, params);
|
|
356
|
+
for (const p of thread.participants) {
|
|
357
|
+
await REFS.addRow(p.uid, { time: Date.now(), includes: attPaths }, `chat:${threadId}`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const now = Date.now();
|
|
362
|
+
let insertedId = 0;
|
|
363
|
+
tx(db, () => {
|
|
364
|
+
const res = db.prepare(`
|
|
365
|
+
INSERT INTO chat_messages (thread_id, sender, kind, content, reply_to, mentions, attachments, task_path, meta, created)
|
|
366
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
367
|
+
`).run(
|
|
368
|
+
threadId,
|
|
369
|
+
sender,
|
|
370
|
+
msgKind,
|
|
371
|
+
content,
|
|
372
|
+
replyTo,
|
|
373
|
+
JSON.stringify(mentions),
|
|
374
|
+
JSON.stringify(attachments),
|
|
375
|
+
taskPath,
|
|
376
|
+
JSON.stringify(meta),
|
|
377
|
+
now
|
|
378
|
+
);
|
|
379
|
+
insertedId = Number(res.lastInsertRowid);
|
|
380
|
+
db.prepare('UPDATE chat_threads SET updated = ? WHERE id = ?').run(now, threadId);
|
|
381
|
+
if (!isTwinBot) {
|
|
382
|
+
db.prepare('UPDATE chat_participants SET last_read_id = MAX(last_read_id, ?) WHERE thread_id = ? AND uid = ?')
|
|
383
|
+
.run(insertedId, threadId, uid);
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
const saved = formatMessageRow(db.prepare('SELECT * FROM chat_messages WHERE id = ?').get(insertedId));
|
|
388
|
+
const notifyUids = thread.participants.map(p => p.uid);
|
|
389
|
+
notifyChatEvent(notifyUids, {
|
|
390
|
+
type: 'chat:message',
|
|
391
|
+
threadId,
|
|
392
|
+
kind: thread.kind,
|
|
393
|
+
nodePath: thread.nodePath,
|
|
394
|
+
message: saved,
|
|
395
|
+
});
|
|
396
|
+
if (!isTwinBot && thread.kind === 'twin') {
|
|
397
|
+
globalThis.__workPendingTriggers = (globalThis.__workPendingTriggers || 0) + 1;
|
|
398
|
+
import('../modules/agent/triggers.js')
|
|
399
|
+
.then(m => m.onChatEvent?.({ storage, thread, message: saved, params }))
|
|
400
|
+
.catch(() => {})
|
|
401
|
+
.finally(() => {
|
|
402
|
+
globalThis.__workPendingTriggers = Math.max(0, (globalThis.__workPendingTriggers || 1) - 1);
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
return saved;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Отметить беседу прочитанной и разослать событие по другим вкладкам пользователя. */
|
|
409
|
+
export async function markRead(storage, params = {}) {
|
|
410
|
+
const uid = resolveActorUid(storage, params);
|
|
411
|
+
if (!uid)
|
|
412
|
+
throw new Error(ACCESS_DENIED);
|
|
413
|
+
const threadId = String(params.threadId || '').trim();
|
|
414
|
+
if (!threadId)
|
|
415
|
+
throw new Error('Не указан threadId');
|
|
416
|
+
|
|
417
|
+
const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
|
|
418
|
+
const db = await dbForThreadStorage(storage, kindHint);
|
|
419
|
+
const part = db.prepare('SELECT last_read_id FROM chat_participants WHERE thread_id = ? AND uid = ?').get(threadId, uid);
|
|
420
|
+
if (!part)
|
|
421
|
+
return { ok: false, lastReadId: 0 };
|
|
422
|
+
|
|
423
|
+
const maxRow = db.prepare('SELECT COALESCE(MAX(id), 0) AS max_id FROM chat_messages WHERE thread_id = ?').get(threadId);
|
|
424
|
+
const targetId = params.lastMessageId != null ? Math.min(Number(params.lastMessageId) || 0, Number(maxRow?.max_id) || 0) : (Number(maxRow?.max_id) || 0);
|
|
425
|
+
const nextRead = Math.max(Number(part.last_read_id) || 0, targetId);
|
|
426
|
+
db.prepare('UPDATE chat_participants SET last_read_id = ? WHERE thread_id = ? AND uid = ?').run(nextRead, threadId, uid);
|
|
427
|
+
notifyChatEvent([uid], {
|
|
428
|
+
type: 'chat:read',
|
|
429
|
+
threadId,
|
|
430
|
+
uid,
|
|
431
|
+
lastReadId: nextRead,
|
|
432
|
+
});
|
|
433
|
+
return { ok: true, lastReadId: nextRead };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** Сводка непрочитанного для текущего пользователя в БД данного узла/сервера. */
|
|
437
|
+
export async function unreadSummary(storage, params = {}) {
|
|
438
|
+
const uid = resolveActorUid(storage, params);
|
|
439
|
+
if (!uid)
|
|
440
|
+
return { total: 0, byThread: {}, byNode: {}, byPeer: {} };
|
|
441
|
+
const db = await dbForThreadStorage(storage, params.kind || '');
|
|
442
|
+
const rows = db.prepare(`
|
|
443
|
+
SELECT t.id, t.kind, t.node_path,
|
|
444
|
+
(SELECT COUNT(*) FROM chat_messages m WHERE m.thread_id = t.id AND m.id > p.last_read_id AND m.sender != ?) AS unread
|
|
445
|
+
FROM chat_threads t
|
|
446
|
+
JOIN chat_participants p ON p.thread_id = t.id
|
|
447
|
+
WHERE p.uid = ?
|
|
448
|
+
`).all(uid, uid);
|
|
449
|
+
const byThread = {};
|
|
450
|
+
const byNode = {};
|
|
451
|
+
const byPeer = {};
|
|
452
|
+
let total = 0;
|
|
453
|
+
for (const r of rows) {
|
|
454
|
+
const cnt = Number(r.unread) || 0;
|
|
455
|
+
if (!cnt) continue;
|
|
456
|
+
total += cnt;
|
|
457
|
+
byThread[r.id] = cnt;
|
|
458
|
+
if (r.kind === 'twin' && r.node_path) {
|
|
459
|
+
byNode[r.node_path] = (byNode[r.node_path] || 0) + cnt;
|
|
460
|
+
}
|
|
461
|
+
else if (r.kind === 'dm') {
|
|
462
|
+
const parts = String(r.id).slice(3).split('|');
|
|
463
|
+
const peer = parts[0] === uid && parts[1] === uid ? uid : (parts[0] === uid ? parts[1] : parts[0]);
|
|
464
|
+
if (peer)
|
|
465
|
+
byPeer[peer] = (byPeer[peer] || 0) + cnt;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return { total, byThread, byNode, byPeer };
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Вычисляемый список контактов («Люди») для левого навигатора (Q18):
|
|
473
|
+
* - свой $user закреплён первым;
|
|
474
|
+
* - BOSS WORK (или DEV_MODE) видит всех /USERS;
|
|
475
|
+
* - обычный пользователь видит коллег из общих $base/$project и внешних клиентов/собеседников.
|
|
476
|
+
*/
|
|
477
|
+
export async function visibleContacts(storage, params = {}) {
|
|
478
|
+
const uid = resolveActorUid(storage, params);
|
|
479
|
+
const usersRoot = await globalThis.WORK?.get_item?.('/USERS').catch(() => null);
|
|
480
|
+
const allUserItems = usersRoot ? ((await usersRoot.items) || []).filter(u => u && u.id && u.id[0] !== '$') : [];
|
|
481
|
+
|
|
482
|
+
const userMap = new Map();
|
|
483
|
+
for (const u of allUserItems) {
|
|
484
|
+
await u.init?.catch?.(() => {});
|
|
485
|
+
userMap.set(u.id, {
|
|
486
|
+
id: u.id,
|
|
487
|
+
path: u.path || `/USERS/${u.id}`,
|
|
488
|
+
label: u.DATA?.label || u.label || u.id,
|
|
489
|
+
icon: u.DATA?.icon || u.icon || '',
|
|
490
|
+
online: Boolean(u.online),
|
|
491
|
+
self: u.id === uid,
|
|
492
|
+
external: false,
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const isWorkBoss = uid && globalThis.WORK
|
|
497
|
+
? (DEV_MODE || !params?.session || params.session.$user === globalThis.WORK || await globalThis.WORK._isWorkBoss?.(params).catch(() => false))
|
|
498
|
+
: Boolean(DEV_MODE);
|
|
499
|
+
|
|
500
|
+
const visibleIds = new Set();
|
|
501
|
+
const externalOnlyIds = new Set();
|
|
502
|
+
if (uid && userMap.has(uid))
|
|
503
|
+
visibleIds.add(uid);
|
|
504
|
+
|
|
505
|
+
if (isWorkBoss) {
|
|
506
|
+
for (const id of userMap.keys())
|
|
507
|
+
visibleIds.add(id);
|
|
508
|
+
}
|
|
509
|
+
else if (uid) {
|
|
510
|
+
// Ищем коллег по всем $base и $project, где участвует текущий пользователь
|
|
511
|
+
const collectFromContainer = async (domainPath) => {
|
|
512
|
+
const dom = await globalThis.WORK?.get_item?.(domainPath).catch(() => null);
|
|
513
|
+
const containers = dom ? ((await dom.items) || []).filter(c => c && c.id && c.id[0] !== '$') : [];
|
|
514
|
+
for (const base of containers) {
|
|
515
|
+
const units = [base];
|
|
516
|
+
const sub = await base.items?.catch?.(() => []) || [];
|
|
517
|
+
for (const s of sub) {
|
|
518
|
+
if (s?.type === '$structure')
|
|
519
|
+
units.push(s);
|
|
520
|
+
}
|
|
521
|
+
let callerInBase = false;
|
|
522
|
+
const internalSet = new Set();
|
|
523
|
+
const externalSet = new Set();
|
|
524
|
+
for (const u of units) {
|
|
525
|
+
await u.init?.catch?.(() => {});
|
|
526
|
+
const sec = u.DATA?.['#security'] || {};
|
|
527
|
+
const roles = await u.roles?.(params).catch(() => []) || [];
|
|
528
|
+
if (roles.length)
|
|
529
|
+
callerInBase = true;
|
|
530
|
+
for (const id of Array.isArray(sec.BOSS) ? sec.BOSS : []) {
|
|
531
|
+
if (!WORKPLACES.isPseudoUser(id)) internalSet.add(id);
|
|
532
|
+
}
|
|
533
|
+
for (const id of Array.isArray(sec.USER) ? sec.USER : []) {
|
|
534
|
+
if (!WORKPLACES.isPseudoUser(id)) internalSet.add(id);
|
|
535
|
+
}
|
|
536
|
+
const { places } = WORKPLACES.normalizeSecurity(sec);
|
|
537
|
+
for (const { node } of WORKPLACES.walkPlaces(places)) {
|
|
538
|
+
for (const id of node.USERS || []) {
|
|
539
|
+
if (WORKPLACES.isPseudoUser(id)) continue;
|
|
540
|
+
if (node.external) externalSet.add(id);
|
|
541
|
+
else internalSet.add(id);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
if (callerInBase) {
|
|
546
|
+
for (const id of internalSet) {
|
|
547
|
+
visibleIds.add(id);
|
|
548
|
+
externalOnlyIds.delete(id);
|
|
549
|
+
}
|
|
550
|
+
for (const id of externalSet) {
|
|
551
|
+
if (!visibleIds.has(id)) {
|
|
552
|
+
visibleIds.add(id);
|
|
553
|
+
externalOnlyIds.add(id);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
await collectFromContainer('/ORGANIZATIONS');
|
|
560
|
+
await collectFromContainer('/PROJECTS');
|
|
561
|
+
|
|
562
|
+
// Добавляем всех собеседников из открытых DM/групп в .data/work.db
|
|
563
|
+
try {
|
|
564
|
+
const db = await dataDb('', rootDirOf());
|
|
565
|
+
const dmPeers = db.prepare(`
|
|
566
|
+
SELECT DISTINCT p2.uid FROM chat_participants p1
|
|
567
|
+
JOIN chat_participants p2 ON p2.thread_id = p1.thread_id
|
|
568
|
+
WHERE p1.uid = ? AND p2.uid != ?
|
|
569
|
+
`).all(uid, uid);
|
|
570
|
+
for (const r of dmPeers)
|
|
571
|
+
visibleIds.add(r.uid);
|
|
572
|
+
}
|
|
573
|
+
catch { /* ignore */ }
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const out = [];
|
|
577
|
+
if (uid && userMap.has(uid))
|
|
578
|
+
out.push(userMap.get(uid));
|
|
579
|
+
for (const id of visibleIds) {
|
|
580
|
+
if (id === uid) continue;
|
|
581
|
+
const entry = userMap.get(id);
|
|
582
|
+
if (!entry) continue;
|
|
583
|
+
out.push({
|
|
584
|
+
...entry,
|
|
585
|
+
external: externalOnlyIds.has(id),
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
return out;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Подтвердить или отклонить карточку действия (kind = 'approval') в беседе.
|
|
593
|
+
*/
|
|
594
|
+
export async function resolveApproval(storage, params = {}) {
|
|
595
|
+
const uid = resolveActorUid(storage, params);
|
|
596
|
+
if (!uid)
|
|
597
|
+
throw new Error(ACCESS_DENIED);
|
|
598
|
+
const threadId = String(params.threadId || '').trim();
|
|
599
|
+
const messageId = Number(params.messageId);
|
|
600
|
+
const action = params.action === 'approve' ? 'approve' : (params.action === 'reject' ? 'reject' : '');
|
|
601
|
+
if (!threadId || !Number.isFinite(messageId) || !action)
|
|
602
|
+
throw new Error('Требуются threadId, messageId и action (approve|reject)');
|
|
603
|
+
|
|
604
|
+
const kindHint = threadId.startsWith('dm:') ? 'dm' : 'twin';
|
|
605
|
+
const db = await dbForThreadStorage(storage, kindHint);
|
|
606
|
+
const thread = getThreadWithMeta(db, threadId, uid);
|
|
607
|
+
if (!thread)
|
|
608
|
+
throw new Error('Беседа не найдена');
|
|
609
|
+
|
|
610
|
+
const isParticipant = thread.participants.some(p => p.uid === uid);
|
|
611
|
+
const isBoss = thread.kind === 'twin'
|
|
612
|
+
&& thread.nodePath === LOGS.feedPathOf(storage)
|
|
613
|
+
&& await storage._canViewLocalFeed?.(params);
|
|
614
|
+
if (!isParticipant && !isBoss)
|
|
615
|
+
throw new Error(ACCESS_DENIED);
|
|
616
|
+
|
|
617
|
+
const row = db.prepare('SELECT * FROM chat_messages WHERE id = ? AND thread_id = ?').get(messageId, threadId);
|
|
618
|
+
if (!row)
|
|
619
|
+
throw new Error('Сообщение не найдено');
|
|
620
|
+
if (row.kind !== 'approval')
|
|
621
|
+
throw new Error('Сообщение не является карточкой подтверждения');
|
|
622
|
+
const meta = parseJsonSafe(row.meta, {});
|
|
623
|
+
if (meta.status && meta.status !== 'pending')
|
|
624
|
+
return { ok: true, alreadyResolved: true, message: formatMessageRow(row) };
|
|
625
|
+
|
|
626
|
+
const nextMeta = {
|
|
627
|
+
...meta,
|
|
628
|
+
status: action === 'approve' ? 'approved' : 'rejected',
|
|
629
|
+
resolvedBy: uid,
|
|
630
|
+
resolvedAt: Date.now(),
|
|
631
|
+
};
|
|
632
|
+
db.prepare('UPDATE chat_messages SET meta = ? WHERE id = ?').run(JSON.stringify(nextMeta), messageId);
|
|
633
|
+
const updated = formatMessageRow(db.prepare('SELECT * FROM chat_messages WHERE id = ?').get(messageId));
|
|
634
|
+
notifyChatEvent(thread.participants.map(p => p.uid), {
|
|
635
|
+
type: 'chat:action',
|
|
636
|
+
threadId,
|
|
637
|
+
message: updated,
|
|
638
|
+
});
|
|
639
|
+
return { ok: true, message: updated };
|
|
640
|
+
}
|
|
@@ -96,8 +96,10 @@ export const classArchiveMethods = {
|
|
|
96
96
|
*/
|
|
97
97
|
async import_archive(params = {}) {
|
|
98
98
|
await this.init;
|
|
99
|
-
|
|
100
|
-
|
|
99
|
+
const expectedMeta = this.DATA?.archiveType
|
|
100
|
+
|| (this.id === 'PROJECTS' ? '$project' : this.id === 'ORGANIZATIONS' ? '$base' : '');
|
|
101
|
+
if (this.type !== '$domain' || (expectedMeta !== '$base' && expectedMeta !== '$project'))
|
|
102
|
+
throw new Error('Загрузка из архива выполняется в домене с archiveType ($base или $project)');
|
|
101
103
|
await this.assertAccess(params, this.constructor.ACCESS_LEVEL.ADMIN);
|
|
102
104
|
|
|
103
105
|
let buf = null;
|
|
@@ -146,7 +148,6 @@ export const classArchiveMethods = {
|
|
|
146
148
|
if (!fileEntries.length)
|
|
147
149
|
throw new Error('Архив пуст');
|
|
148
150
|
|
|
149
|
-
const expectedMeta = this.id === 'PROJECTS' ? '$project' : '$base';
|
|
150
151
|
// Проверим, лежат ли файлы сразу в корне ($base/class.js или $project/class.js) или в одной общей папке
|
|
151
152
|
let prefix = '';
|
|
152
153
|
let folderFromZip = '';
|