odant-work 1.0.71 → 1.0.73

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.
Files changed (28) hide show
  1. package/#system/package-manifest.json +30 -27
  2. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/calendar.js +1004 -1011
  3. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +51 -23
  4. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/class.js +7 -90
  5. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/email.js +913 -705
  6. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/methods/refresh/$method/class.js +30 -1
  7. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/class.js +10 -0
  8. package/$server/$folder/$class/$structure/handlers/pages/form/{system/$handler/tabs → search/$handler}/search.js +14 -0
  9. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/system.js +53 -30
  10. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/staff.js +1 -1
  11. package/$server/$folder/$class/ai/skills/email-mailbox.md +10 -7
  12. package/$server/$folder/$class/ai/skills/meeting-minutes.md +1 -1
  13. package/$server/$folder/$file/$eml/triggers/on_save/$trigger/class.js +17 -1
  14. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/voice-ui.js +5 -5
  15. package/$server/$folder/lib/calendar-form/calendar-form.js +482 -296
  16. package/$server/$folder/lib/tree/tree.js +1 -1
  17. package/oda/oda.js +8 -4
  18. package/package.json +1 -1
  19. package/sources/client.js +42 -6
  20. package/sources/host/email-utils.js +25 -1
  21. package/sources/modules/agent/index.js +3 -1
  22. package/sources/modules/agent/node-rules.js +60 -3
  23. package/sources/modules/agent/scheduler.js +7 -0
  24. package/sources/modules/agent/tools/calendar-mail.js +273 -0
  25. package/sources/server/access/gateway.js +3 -0
  26. package/sources/server/chat-threads.js +77 -23
  27. package/sources/server/class/feed.js +46 -0
  28. package/sources/server/class/mail-calendar.js +867 -0
@@ -0,0 +1,867 @@
1
+ /**
2
+ * Серверное ядро Почты (.eml) и Календаря (.ics) для структурных узлов WORK ($server/$base/$project/$structure/$user).
3
+ * Используется как UI-формами (form/email, form/calendar), так и инструментами ИИ-агента.
4
+ */
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import * as LOGS from '../logs.js';
8
+ import { DEV_MODE } from '../../host/config.js';
9
+ import { parseEml, parseJsonEml } from '../../host/email-utils.js';
10
+
11
+ const ACCESS_DENIED = 'Доступ запрещён';
12
+
13
+ function parseJsonSafe(raw, fallback = null) {
14
+ if (raw && typeof raw === 'object')
15
+ return raw;
16
+ if (typeof raw !== 'string' || !raw)
17
+ return fallback;
18
+ try {
19
+ const parsed = JSON.parse(raw);
20
+ return parsed && typeof parsed === 'object' ? parsed : fallback;
21
+ }
22
+ catch {
23
+ return fallback;
24
+ }
25
+ }
26
+
27
+ function parsePostBody(params = {}) {
28
+ if (params.post && typeof params.post === 'object')
29
+ return params.post;
30
+ if (typeof params.post === 'string' && params.post.trim()) {
31
+ return parseJsonSafe(params.post, {});
32
+ }
33
+ return params;
34
+ }
35
+
36
+ function resolveActorUid(storage, params = {}) {
37
+ const uid = storage?.constructor?.resolveUid?.(params);
38
+ if (uid)
39
+ return uid;
40
+ if (typeof params?.uid === 'string' && params.uid.trim() && (DEV_MODE || !params?.session || params.session.$user === globalThis.WORK))
41
+ return params.uid.trim();
42
+ if (params?.session?.$user === globalThis.WORK)
43
+ return globalThis.WORK?.id || 'WORK';
44
+ return '';
45
+ }
46
+
47
+ async function assertReadAccess(storage, params = {}) {
48
+ if (!storage)
49
+ throw new Error('Узел не задан');
50
+ if (DEV_MODE || !params?.session || params.session.$user === globalThis.WORK)
51
+ return { uid: resolveActorUid(storage, params), isBoss: true, roles: ['BOSS'] };
52
+ const uid = resolveActorUid(storage, params);
53
+ if (!uid)
54
+ throw new Error(ACCESS_DENIED);
55
+ if (storage.type === '$user') {
56
+ if (storage.id !== uid)
57
+ throw new Error(ACCESS_DENIED);
58
+ return { uid, isBoss: true, roles: ['BOSS', 'USER'] };
59
+ }
60
+ const roles = await storage.roles?.(params).catch(() => []) || [];
61
+ const isBoss = roles.includes('BOSS');
62
+ const isUser = roles.includes('USER');
63
+ const isClientOnly = roles.includes('CLIENT') && !isBoss && !isUser;
64
+ if (isClientOnly)
65
+ throw new Error(ACCESS_DENIED);
66
+ const canSee = await storage.canSee?.(storage, params).catch(() => false);
67
+ if (!isBoss && !isUser && !canSee)
68
+ throw new Error(ACCESS_DENIED);
69
+ return { uid, isBoss, roles };
70
+ }
71
+
72
+ async function assertWriteAccess(storage, params = {}) {
73
+ const access = await assertReadAccess(storage, params);
74
+ if (DEV_MODE || !params?.session || params.session.$user === globalThis.WORK)
75
+ return access;
76
+ if (storage.type === '$user')
77
+ return access;
78
+ const canWrite = access.isBoss || access.roles.includes('USER') || (await storage.canWrite?.(storage, params).catch(() => false));
79
+ if (!canWrite)
80
+ throw new Error(ACCESS_DENIED);
81
+ return access;
82
+ }
83
+
84
+ async function loadRawEmlFile(filePath, params = {}) {
85
+ if (!filePath)
86
+ return '';
87
+ try {
88
+ const item = await globalThis.WORK?.get_item?.(filePath).catch(() => null);
89
+ if (item?.load) {
90
+ const txt = await item.load({ encoding: 'utf-8', session: params.session }).catch(() => '');
91
+ if (txt) return String(txt);
92
+ }
93
+ if (item?.dir && fs.existsSync(item.dir))
94
+ return fs.readFileSync(item.dir, 'utf-8');
95
+ }
96
+ catch { /* fallback */ }
97
+ return '';
98
+ }
99
+
100
+ function parseEmlPayload(raw = '') {
101
+ const json = parseJsonEml(raw);
102
+ if (json && Object.keys(json).length && (json.box || json.subject || json.from || json.to || json.body != null || json.html != null))
103
+ return { kind: 'json', data: json };
104
+ const rfc = parseEml(raw);
105
+ return {
106
+ kind: 'rfc',
107
+ data: {
108
+ subject: rfc.headers.subject || '(без темы)',
109
+ from: rfc.headers.from || '',
110
+ to: rfc.headers.to || '',
111
+ cc: rfc.headers.cc || '',
112
+ date: rfc.headers.date || '',
113
+ body: rfc.body || '',
114
+ html: '',
115
+ messageId: rfc.headers['message-id'] || '',
116
+ box: 'inbox',
117
+ read: true,
118
+ attachments: [],
119
+ },
120
+ };
121
+ }
122
+
123
+ function buildMailSummary(row, meta, json = null) {
124
+ const date = meta.date || json?.date || row.time || '';
125
+ const sortTime = date ? new Date(date).getTime() : (Number(row.time) || 0);
126
+ const box = meta.box || json?.box || 'inbox';
127
+ const uid = meta.uid || json?.uid || '';
128
+ return {
129
+ path: row.path,
130
+ logsFilePath: row.logsFilePath || '',
131
+ uid,
132
+ subject: meta.subject || json?.subject || '(без темы)',
133
+ from: meta.from || json?.from || '',
134
+ to: meta.to || json?.to || '',
135
+ cc: meta.cc || json?.cc || '',
136
+ date,
137
+ sortTime: Number.isFinite(sortTime) ? sortTime : (Number(row.time) || 0),
138
+ origTime: Number(row.time) || (Number.isFinite(sortTime) ? sortTime : Date.now()),
139
+ status: meta.status || json?.status || '',
140
+ error: meta.error || json?.error || '',
141
+ box,
142
+ prevBox: meta.prevBox || json?.prevBox || '',
143
+ address: meta.mailbox || json?.mailbox || '',
144
+ messageId: meta.messageId || json?.messageId || '',
145
+ read: meta.read != null ? Boolean(meta.read) : (json?.read != null ? Boolean(json.read) : (box !== 'inbox')),
146
+ attachmentsCount: Number(meta.attachmentsCount ?? json?.attachments?.length ?? 0) || 0,
147
+ snippet: String(meta.snippet || json?.body || '').replace(/\s+/g, ' ').trim().slice(0, 140),
148
+ };
149
+ }
150
+
151
+ function bareEmailAddress(v) {
152
+ const s = String(v || '').trim();
153
+ const m = s.match(/<([^>]+)>/);
154
+ return (m ? m[1] : s).trim();
155
+ }
156
+
157
+ function validateEmailsList(raw, { required = false } = {}) {
158
+ const list = String(raw || '').split(/[,;]/).map(s => s.trim()).filter(Boolean);
159
+ if (!list.length) {
160
+ if (required)
161
+ throw new Error('Укажите получателя');
162
+ return '';
163
+ }
164
+ const bad = list.filter(a => !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(bareEmailAddress(a)));
165
+ if (bad.length)
166
+ throw new Error('Некорректный адрес: ' + bad.join(', '));
167
+ return list.join(', ');
168
+ }
169
+
170
+ function newUid() {
171
+ return crypto.randomUUID ? crypto.randomUUID() : (Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10));
172
+ }
173
+
174
+ async function readMailSettingsSafe(storage) {
175
+ const { readEmailSettings } = await import('../../../$server/$folder/lib/email/settings.js');
176
+ return readEmailSettings(storage);
177
+ }
178
+
179
+ /** Публичный список настроенных адресов узла (без паролей и секретов). */
180
+ export async function mailAccounts(storage, params = {}) {
181
+ const access = await assertReadAccess(storage, params);
182
+ const settings = await readMailSettingsSafe(storage);
183
+ const accounts = [];
184
+ for (const [key, box] of Object.entries(settings?.mailboxes || {})) {
185
+ const address = String(box?.auth?.user || box?.address || key || '').trim();
186
+ if (!address)
187
+ continue;
188
+ accounts.push({
189
+ address,
190
+ label: box?.label || address,
191
+ hasImap: Boolean(box?.imap?.host),
192
+ hasSmtp: Boolean(box?.smtp?.host),
193
+ });
194
+ }
195
+ const canConfigure = DEV_MODE || !params?.session || access.isBoss || storage.type === '$user';
196
+ return {
197
+ accounts,
198
+ canConfigure,
199
+ autoRefresh: storage?.DATA?.mailAutoRefresh !== false,
200
+ };
201
+ }
202
+
203
+ /** Единый плоский список писем узла с фильтрацией, поиском и счётчиками непрочитанных по папкам. */
204
+ export async function mailList(storage, params = {}) {
205
+ await assertReadAccess(storage, params);
206
+ const body = parsePostBody(params);
207
+ const boxFilter = String(body.box || params.box || 'all').toLowerCase();
208
+ const addressFilter = String(body.address || params.address || '').trim().toLowerCase();
209
+ const q = String(body.q || params.q || '').trim().toLowerCase();
210
+ const unreadOnly = body.unreadOnly === true || body.unreadOnly === '1' || params.unreadOnly === true || params.unreadOnly === '1';
211
+ const limit = Math.max(1, Math.min(500, Number(body.limit || params.limit) || 200));
212
+
213
+ const allDates = await LOGS.datesList(storage, { nonEmpty: 1, ext: 'eml', ...params }).catch(() => []);
214
+ const dates = Array.isArray(allDates) ? allDates.slice(0, 120) : [];
215
+ const rows = dates.length
216
+ ? await LOGS.loadBodies(storage, { days: dates, ext: 'eml', ...params }).catch(() => [])
217
+ : [];
218
+
219
+ const seen = new Set();
220
+ const items = [];
221
+ for (const row of rows || []) {
222
+ let meta = parseJsonSafe(row.content, null);
223
+ let fullJson = null;
224
+ if (!meta || (!meta.box && !meta.deleted)) {
225
+ const raw = await loadRawEmlFile(row.path, params);
226
+ if (!raw)
227
+ continue;
228
+ const parsed = parseEmlPayload(raw);
229
+ fullJson = parsed.data;
230
+ meta = parsed.data;
231
+ }
232
+ const key = meta.uid ? `uid:${meta.uid}` : `path:${row.path}`;
233
+ if (seen.has(key))
234
+ continue;
235
+ seen.add(key);
236
+
237
+ if (meta.deleted === true || meta.box === 'deleted')
238
+ continue;
239
+ items.push(buildMailSummary(row, meta, fullJson));
240
+ }
241
+
242
+ items.sort((a, b) => (b.sortTime || 0) - (a.sortTime || 0));
243
+
244
+ const countsByBox = { inbox: 0, drafts: 0, outbox: 0, trash: 0 };
245
+ const unreadByBox = { inbox: 0, drafts: 0, outbox: 0, trash: 0 };
246
+ for (const it of items) {
247
+ if (addressFilter && String(it.address || '').toLowerCase() !== addressFilter)
248
+ continue;
249
+ const b = countsByBox[it.box] !== undefined ? it.box : 'inbox';
250
+ countsByBox[b]++;
251
+ if (!it.read)
252
+ unreadByBox[b]++;
253
+ }
254
+
255
+ const filtered = items.filter(it => {
256
+ if (boxFilter !== 'all' && it.box !== boxFilter)
257
+ return false;
258
+ if (addressFilter && String(it.address || '').toLowerCase() !== addressFilter)
259
+ return false;
260
+ if (unreadOnly && it.read)
261
+ return false;
262
+ if (q) {
263
+ const hay = `${it.subject}\n${it.from}\n${it.to}\n${it.cc}\n${it.snippet}`.toLowerCase();
264
+ if (!hay.includes(q))
265
+ return false;
266
+ }
267
+ return true;
268
+ }).slice(0, limit);
269
+
270
+ return {
271
+ messages: filtered,
272
+ countsByBox,
273
+ unreadByBox,
274
+ total: filtered.length,
275
+ };
276
+ }
277
+
278
+ async function resolveEmlByTarget(storage, params = {}) {
279
+ const body = parsePostBody(params);
280
+ const targetPath = String(body.path || params.path || '').trim();
281
+ const targetUid = String(body.uid || params.uid || '').trim();
282
+ if (targetPath) {
283
+ const listRes = await mailList(storage, { ...params, box: 'all', limit: 500 });
284
+ const found = listRes.messages.find(m => m.path === targetPath || (targetUid && m.uid === targetUid));
285
+ return { summary: found, path: found?.path || targetPath };
286
+ }
287
+ if (targetUid) {
288
+ const listRes = await mailList(storage, { ...params, box: 'all', limit: 500 });
289
+ const found = listRes.messages.find(m => m.uid === targetUid);
290
+ if (found)
291
+ return { summary: found, path: found.path };
292
+ }
293
+ return { summary: null, path: '' };
294
+ }
295
+
296
+ /** Прочитать полное письмо (.eml) и при необходимости отметить прочитанным. */
297
+ export async function mailRead(storage, params = {}) {
298
+ await assertReadAccess(storage, params);
299
+ const body = parsePostBody(params);
300
+ const { summary, path: filePath } = await resolveEmlByTarget(storage, params);
301
+ if (!filePath)
302
+ throw new Error('Письмо не найдено');
303
+
304
+ const raw = await loadRawEmlFile(filePath, params);
305
+ if (!raw)
306
+ throw new Error('Не удалось прочитать файл письма');
307
+
308
+ const parsed = parseEmlPayload(raw);
309
+ const d = parsed.data || {};
310
+ const msg = {
311
+ path: filePath,
312
+ uid: summary?.uid || d.uid || '',
313
+ subject: d.subject || summary?.subject || '(без темы)',
314
+ from: d.from || summary?.from || '',
315
+ to: d.to || summary?.to || '',
316
+ cc: d.cc || summary?.cc || '',
317
+ date: d.date || summary?.date || '',
318
+ sortTime: summary?.sortTime || (d.date ? new Date(d.date).getTime() : Date.now()),
319
+ origTime: summary?.origTime || (d.date ? new Date(d.date).getTime() : Date.now()),
320
+ body: d.body ?? '',
321
+ html: d.html ?? '',
322
+ box: summary?.box || d.box || 'inbox',
323
+ prevBox: summary?.prevBox || d.prevBox || '',
324
+ address: summary?.address || d.mailbox || '',
325
+ status: summary?.status || d.status || '',
326
+ error: summary?.error || d.error || '',
327
+ messageId: d.messageId || summary?.messageId || '',
328
+ read: summary ? summary.read : (d.read !== false),
329
+ attachments: Array.isArray(d.attachments) ? d.attachments : [],
330
+ };
331
+
332
+ const wantMarkRead = body.markRead !== false && params.markRead !== false;
333
+ if (wantMarkRead && !msg.read && msg.box === 'inbox') {
334
+ try {
335
+ await mailState(storage, { ...params, path: filePath, uid: msg.uid, read: true });
336
+ msg.read = true;
337
+ }
338
+ catch { /* read-only user still reads */ }
339
+ }
340
+ return msg;
341
+ }
342
+
343
+ /** Сохранить или обновить черновик письма в папке drafts. */
344
+ export async function mailDraftSave(storage, params = {}) {
345
+ await assertWriteAccess(storage, params);
346
+ const body = parsePostBody(params);
347
+ const { accounts } = await mailAccounts(storage, params);
348
+ const address = String(body.from || body.mailbox || accounts[0]?.address || 'drafts').trim();
349
+ const uid = String(body.uid || newUid()).trim();
350
+ const nowIso = new Date().toISOString();
351
+ const nowMs = Number(body.origTime) || Date.now();
352
+ const attachments = Array.isArray(body.attachments) ? body.attachments : [];
353
+
354
+ const json = {
355
+ uid,
356
+ subject: String(body.subject || '').trim() || '(без темы)',
357
+ from: String(body.from || address),
358
+ to: String(body.to || '').trim(),
359
+ cc: String(body.cc || '').trim(),
360
+ date: nowIso,
361
+ body: String(body.body || ''),
362
+ html: String(body.html || ''),
363
+ inReplyTo: String(body.inReplyTo || ''),
364
+ status: 'draft',
365
+ box: 'drafts',
366
+ mailbox: address,
367
+ read: true,
368
+ attachments,
369
+ };
370
+
371
+ const meta = {
372
+ uid,
373
+ subject: json.subject,
374
+ from: json.from,
375
+ to: json.to,
376
+ cc: json.cc,
377
+ date: nowIso,
378
+ box: 'drafts',
379
+ mailbox: address,
380
+ status: 'draft',
381
+ read: true,
382
+ attachmentsCount: attachments.length,
383
+ snippet: json.body.slice(0, 140),
384
+ };
385
+
386
+ const saved = await storage.save_file({
387
+ filename: `draft-${uid}.eml`,
388
+ folder: address || 'drafts',
389
+ encoding: 'utf-8',
390
+ time: nowMs,
391
+ feed: 'point',
392
+ message: JSON.stringify(meta),
393
+ post: JSON.stringify(json),
394
+ session: params.session,
395
+ });
396
+ return {
397
+ ok: true,
398
+ uid,
399
+ path: saved?.path || '',
400
+ message: { ...meta, path: saved?.path || '', origTime: nowMs, sortTime: Date.parse(nowIso) },
401
+ };
402
+ }
403
+
404
+ /** Отправить письмо через штатный SMTP-конвейер (outbound.eml -> $eml/on_save). */
405
+ export async function mailSend(storage, params = {}) {
406
+ await assertWriteAccess(storage, params);
407
+ const body = parsePostBody(params);
408
+ const { accounts } = await mailAccounts(storage, params);
409
+ const address = String(body.from || body.mailbox || accounts[0]?.address || '').trim();
410
+ if (!address)
411
+ throw new Error('Сначала настройте почтовый ящик');
412
+
413
+ const to = validateEmailsList(body.to, { required: true });
414
+ const cc = validateEmailsList(body.cc, { required: false });
415
+ const uid = String(body.draftUid || body.uid || newUid()).trim();
416
+ const nowIso = new Date().toISOString();
417
+ const attachments = Array.isArray(body.attachments) ? body.attachments : [];
418
+
419
+ const eml = {
420
+ uid,
421
+ subject: String(body.subject || '').trim() || '(без темы)',
422
+ from: address,
423
+ to,
424
+ ...(cc ? { cc } : {}),
425
+ date: nowIso,
426
+ body: String(body.body || ''),
427
+ html: String(body.html || ''),
428
+ ...(body.inReplyTo ? { inReplyTo: String(body.inReplyTo) } : {}),
429
+ status: 'pending',
430
+ box: 'outbox',
431
+ mailbox: address,
432
+ read: true,
433
+ attachments,
434
+ };
435
+
436
+ const meta = {
437
+ uid,
438
+ subject: eml.subject,
439
+ from: eml.from,
440
+ to: eml.to,
441
+ cc: eml.cc || '',
442
+ date: nowIso,
443
+ box: 'outbox',
444
+ mailbox: address,
445
+ status: 'pending',
446
+ read: true,
447
+ attachmentsCount: attachments.length,
448
+ snippet: eml.body.slice(0, 140),
449
+ };
450
+
451
+ const saved = await storage.save_file({
452
+ filename: 'outbound.eml',
453
+ folder: address,
454
+ encoding: 'utf-8',
455
+ feed: 'point',
456
+ message: JSON.stringify(meta),
457
+ post: JSON.stringify(eml),
458
+ session: params.session,
459
+ });
460
+
461
+ return { ok: true, uid, path: saved?.path || '', status: 'sent_queued' };
462
+ }
463
+
464
+ /** Изменить статус письма: read/unread, в корзину, восстановить, удалить навсегда. */
465
+ export async function mailState(storage, params = {}) {
466
+ await assertWriteAccess(storage, params);
467
+ const body = parsePostBody(params);
468
+ const { summary, path: filePath } = await resolveEmlByTarget(storage, params);
469
+ if (!filePath)
470
+ throw new Error('Письмо не найдено');
471
+
472
+ const raw = await loadRawEmlFile(filePath, params);
473
+ if (!raw)
474
+ throw new Error('Файл письма не найден');
475
+
476
+ const parsed = parseEmlPayload(raw);
477
+ const json = { ...(parsed.data || {}) };
478
+ const uid = summary?.uid || json.uid || newUid();
479
+ json.uid = uid;
480
+ const origTime = summary?.origTime || (json.date ? new Date(json.date).getTime() : Date.now());
481
+ const curBox = summary?.box || json.box || 'inbox';
482
+
483
+ if (typeof body.read === 'boolean')
484
+ json.read = body.read;
485
+
486
+ if (body.deletePermanent) {
487
+ json.box = 'deleted';
488
+ json.deleted = true;
489
+ }
490
+ else if (body.restore) {
491
+ json.box = summary?.prevBox || json.prevBox || 'inbox';
492
+ delete json.prevBox;
493
+ delete json.deleted;
494
+ }
495
+ else if (body.box && body.box !== curBox) {
496
+ if (body.box === 'trash' && curBox !== 'trash')
497
+ json.prevBox = curBox;
498
+ json.box = String(body.box);
499
+ delete json.deleted;
500
+ }
501
+
502
+ const meta = {
503
+ uid,
504
+ subject: json.subject || summary?.subject || '(без темы)',
505
+ from: json.from || summary?.from || '',
506
+ to: json.to || summary?.to || '',
507
+ cc: json.cc || summary?.cc || '',
508
+ date: json.date || summary?.date || new Date(origTime).toISOString(),
509
+ box: json.box || curBox,
510
+ ...(json.prevBox ? { prevBox: json.prevBox } : {}),
511
+ ...(json.deleted ? { deleted: true } : {}),
512
+ mailbox: json.mailbox || summary?.address || '',
513
+ status: json.status || summary?.status || '',
514
+ ...(json.error ? { error: json.error } : {}),
515
+ read: json.read !== false,
516
+ messageId: json.messageId || summary?.messageId || '',
517
+ attachmentsCount: Array.isArray(json.attachments) ? json.attachments.length : (summary?.attachmentsCount || 0),
518
+ snippet: String(json.body || '').replace(/\s+/g, ' ').trim().slice(0, 140),
519
+ };
520
+
521
+ await storage.save_file({
522
+ filename: `state-${uid}.eml`,
523
+ folder: meta.mailbox || 'mail',
524
+ encoding: 'utf-8',
525
+ time: origTime,
526
+ feed: 'point',
527
+ message: JSON.stringify(meta),
528
+ post: JSON.stringify(json),
529
+ session: params.session,
530
+ });
531
+
532
+ return { ok: true, uid, box: meta.box, read: meta.read, deleted: Boolean(json.deleted) };
533
+ }
534
+
535
+ /** Запросить свежие входящие письма с IMAP-сервера узла. */
536
+ export async function mailRefresh(storage, params = {}) {
537
+ await assertWriteAccess(storage, params);
538
+ const handler = await storage.get_item?.('/~/handlers/pages/form/email/$handler/methods/refresh/$method').catch(() => null);
539
+ if (handler && typeof handler.execute === 'function')
540
+ return handler.execute(params);
541
+ const mod = await import('../../../$server/$folder/$class/$structure/handlers/pages/form/email/$handler/methods/refresh/$method/class.js');
542
+ return mod.default.execute.call({ $context: { $context: storage } }, params);
543
+ }
544
+
545
+ // ==================== Календарь (.ics + задачи + расписания ИИ) ====================
546
+
547
+ function addStepByRecurrence(date, recurrence) {
548
+ const d = new Date(date.getTime());
549
+ switch (recurrence) {
550
+ case 'daily': d.setDate(d.getDate() + 1); break;
551
+ case 'weekly': d.setDate(d.getDate() + 7); break;
552
+ case 'monthly': d.setMonth(d.getMonth() + 1); break;
553
+ case 'yearly': d.setFullYear(d.getFullYear() + 1); break;
554
+ default: return null;
555
+ }
556
+ return d;
557
+ }
558
+
559
+ function expandCalendarEvent(ev, fromMs, toMs) {
560
+ const startMs = Date.parse(ev.start);
561
+ const endMs = Date.parse(ev.end);
562
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs)
563
+ return [];
564
+ const dur = endMs - startMs;
565
+ const rec = String(ev.recurrence || 'none').toLowerCase();
566
+ if (!rec || rec === 'none') {
567
+ if (endMs > fromMs && startMs <= toMs)
568
+ return [{ ...ev, isOccurrence: false }];
569
+ return [];
570
+ }
571
+ const untilMs = ev.recurrenceUntil ? Date.parse(ev.recurrenceUntil) : toMs;
572
+ const hardLimit = Math.min(toMs, Number.isFinite(untilMs) ? untilMs : toMs);
573
+ const out = [];
574
+ let cur = new Date(startMs);
575
+ for (let guard = 0; guard < 400; guard++) {
576
+ const s = cur.getTime();
577
+ const e = s + dur;
578
+ if (s > hardLimit)
579
+ break;
580
+ if (e > fromMs && s <= toMs) {
581
+ out.push({
582
+ ...ev,
583
+ start: new Date(s).toISOTimezoneString?.() || new Date(s).toISOString(),
584
+ end: new Date(e).toISOTimezoneString?.() || new Date(e).toISOString(),
585
+ masterStart: ev.start,
586
+ masterEnd: ev.end,
587
+ isOccurrence: s !== startMs,
588
+ });
589
+ }
590
+ const next = addStepByRecurrence(cur, rec);
591
+ if (!next || next.getTime() <= cur.getTime())
592
+ break;
593
+ cur = next;
594
+ }
595
+ return out;
596
+ }
597
+
598
+ function formatDayLocal(ms) {
599
+ const d = new Date(ms);
600
+ const pad = n => String(n).padStart(2, '0');
601
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
602
+ }
603
+
604
+ function computeFreeSlots(events, fromDay, toDay) {
605
+ const slots = [];
606
+ const cur = new Date(`${fromDay}T00:00:00`);
607
+ const end = new Date(`${toDay}T00:00:00`);
608
+ for (let guard = 0; guard < 31 && cur <= end; guard++) {
609
+ const dayStr = formatDayLocal(cur.getTime());
610
+ const workStart = new Date(`${dayStr}T09:00:00`).getTime();
611
+ const workEnd = new Date(`${dayStr}T18:00:00`).getTime();
612
+ const busy = [];
613
+ for (const ev of events) {
614
+ if (ev.kind === 'schedule')
615
+ continue;
616
+ const s = Date.parse(ev.start);
617
+ const e = Date.parse(ev.end);
618
+ if (!Number.isFinite(s) || !Number.isFinite(e) || e <= workStart || s >= workEnd)
619
+ continue;
620
+ busy.push([Math.max(workStart, s), Math.min(workEnd, e)]);
621
+ }
622
+ busy.sort((a, b) => a[0] - b[0]);
623
+ let cursor = workStart;
624
+ const dayFree = [];
625
+ for (const [bs, be] of busy) {
626
+ if (bs > cursor)
627
+ dayFree.push({ start: new Date(cursor).toISOString(), end: new Date(bs).toISOString(), minutes: Math.round((bs - cursor) / 60000) });
628
+ cursor = Math.max(cursor, be);
629
+ }
630
+ if (cursor < workEnd)
631
+ dayFree.push({ start: new Date(cursor).toISOString(), end: new Date(workEnd).toISOString(), minutes: Math.round((workEnd - cursor) / 60000) });
632
+ slots.push({ day: dayStr, free: dayFree.filter(s => s.minutes >= 15) });
633
+ cur.setDate(cur.getDate() + 1);
634
+ }
635
+ return slots;
636
+ }
637
+
638
+ /** Список событий календаря (с развёрнутыми повторениями), плюс опционально задачи и расписания ИИ. */
639
+ export async function calendarList(storage, params = {}) {
640
+ const access = await assertReadAccess(storage, params);
641
+ const body = parsePostBody(params);
642
+ const todayStr = formatDayLocal(Date.now());
643
+ const fromDay = String(body.from || params.from || todayStr).slice(0, 10);
644
+ const toDay = String(body.to || params.to || fromDay).slice(0, 10);
645
+ const fromMs = Date.parse(`${fromDay}T00:00:00`);
646
+ const toMs = Date.parse(`${toDay}T23:59:59.999`);
647
+ if (!Number.isFinite(fromMs) || !Number.isFinite(toMs))
648
+ throw new Error('Некорректный диапазон дат from/to');
649
+
650
+ const includeTasks = body.includeTasks === true || body.includeTasks === '1' || params.includeTasks === true || params.includeTasks === '1';
651
+ const includeSchedules = body.includeSchedules === true || body.includeSchedules === '1' || params.includeSchedules === true || params.includeSchedules === '1';
652
+ const withFreeSlots = body.withFreeSlots === true || body.withFreeSlots === '1' || params.withFreeSlots === true || params.withFreeSlots === '1';
653
+ const attendeeFilter = Array.isArray(body.attendees) ? body.attendees : (typeof body.attendee === 'string' && body.attendee ? [body.attendee] : []);
654
+
655
+ const allDates = await LOGS.datesList(storage, { nonEmpty: 1, ext: 'ics', ...params }).catch(() => []);
656
+ const icsRows = allDates?.length
657
+ ? await LOGS.loadBodies(storage, { days: allDates, ext: 'ics', ...params }).catch(() => [])
658
+ : [];
659
+
660
+ const latest = new Map();
661
+ for (const row of icsRows || []) {
662
+ const content = parseJsonSafe(row.content, null);
663
+ if (!content)
664
+ continue;
665
+ const key = content.uid ? String(content.uid) : `path:${row.path}`;
666
+ if (!latest.has(key))
667
+ latest.set(key, { row, content });
668
+ }
669
+
670
+ const events = [];
671
+ for (const { row, content } of latest.values()) {
672
+ if (content.status === 'cancelled' || !content.start || !content.end)
673
+ continue;
674
+ const attendees = Array.isArray(content.attendees) ? content.attendees : [];
675
+ const organizer = content.organizer || row.sender || '';
676
+ // Права просмотра в отделе: BOSS видит всё; USER — свои, где он участник, или общие без списка участников
677
+ if (!access.isBoss && storage.type !== '$user') {
678
+ const visible = organizer === access.uid
679
+ || attendees.includes(access.uid)
680
+ || attendees.length === 0;
681
+ if (!visible)
682
+ continue;
683
+ }
684
+ if (attendeeFilter.length) {
685
+ const hit = attendeeFilter.some(u => u === organizer || attendees.includes(u));
686
+ if (!hit)
687
+ continue;
688
+ }
689
+ const baseEvent = {
690
+ kind: 'event',
691
+ uid: content.uid || `file:${row.path}`,
692
+ summary: content.summary ?? '',
693
+ location: content.location ?? '',
694
+ description: content.description ?? '',
695
+ start: content.start,
696
+ end: content.end,
697
+ allDay: Boolean(content.allDay),
698
+ attendees,
699
+ externalEmails: Array.isArray(content.externalEmails) ? content.externalEmails : [],
700
+ recurrence: content.recurrence || 'none',
701
+ reminderMin: Number(content.reminderMin) || 0,
702
+ category: content.category || 'meeting',
703
+ organizer,
704
+ sourceNodePath: content.sourceNodePath || '',
705
+ path: row.path,
706
+ logsFilePath: row.logsFilePath || '',
707
+ row,
708
+ };
709
+ events.push(...expandCalendarEvent(baseEvent, fromMs, toMs));
710
+ }
711
+
712
+ if (includeTasks) {
713
+ const taskRows = await LOGS.loadBodies(storage, { from: fromDay, to: toDay, ext: 'task', ...params }).catch(() => []);
714
+ const seenTasks = new Set();
715
+ for (const row of taskRows || []) {
716
+ if (!row?.path || seenTasks.has(row.path))
717
+ continue;
718
+ seenTasks.add(row.path);
719
+ if (!access.isBoss && storage.type !== '$user' && row.sender !== access.uid && !(Array.isArray(row.receivers) && row.receivers.includes(access.uid)))
720
+ continue;
721
+ const tMs = Number(row.time) || Date.now();
722
+ const startIso = new Date(tMs).toISOString();
723
+ const endIso = new Date(tMs + 30 * 60_000).toISOString();
724
+ events.push({
725
+ kind: 'task',
726
+ uid: `task:${row.path}`,
727
+ summary: String(row.content || 'Задача').slice(0, 120),
728
+ start: startIso,
729
+ end: endIso,
730
+ allDay: false,
731
+ category: 'task',
732
+ path: row.path,
733
+ organizer: row.sender || '',
734
+ attendees: Array.isArray(row.receivers) ? row.receivers : [],
735
+ });
736
+ }
737
+ }
738
+
739
+ if (includeSchedules) {
740
+ try {
741
+ const { listSchedules } = await import('../../modules/agent/scheduler.js');
742
+ const nodePath = LOGS.feedPathOf(storage);
743
+ const scheds = await listSchedules({ nodePath }).catch(() => []);
744
+ for (const s of scheds) {
745
+ if (!s.enabled || !s.next)
746
+ continue;
747
+ const nextMs = Number(s.next);
748
+ if (nextMs >= fromMs && nextMs <= toMs) {
749
+ events.push({
750
+ kind: 'schedule',
751
+ uid: `sched:${s.id}`,
752
+ summary: s.label || 'Расписание ИИ',
753
+ description: s.prompt || '',
754
+ start: new Date(nextMs).toISOString(),
755
+ end: new Date(nextMs + 30 * 60_000).toISOString(),
756
+ allDay: false,
757
+ category: 'ai',
758
+ scheduleId: s.id,
759
+ });
760
+ }
761
+ }
762
+ }
763
+ catch { /* ignore */ }
764
+ }
765
+
766
+ events.sort((a, b) => String(a.start).localeCompare(String(b.start)));
767
+
768
+ return {
769
+ from: fromDay,
770
+ to: toDay,
771
+ events,
772
+ ...(withFreeSlots ? { freeSlots: computeFreeSlots(events, fromDay, toDay) } : {}),
773
+ };
774
+ }
775
+
776
+ /** Создать, обновить, перенести или отменить событие календаря (.ics) + синхронизация участникам в /USERS/<uid>. */
777
+ export async function calendarSave(storage, params = {}) {
778
+ const access = await assertWriteAccess(storage, params);
779
+ const body = parsePostBody(params);
780
+ const uid = String(body.uid || newUid()).trim();
781
+ const status = body.status === 'cancelled' ? 'cancelled' : 'confirmed';
782
+ const start = String(body.start || '').trim();
783
+ const end = String(body.end || '').trim();
784
+ if (!start || !end)
785
+ throw new Error('Укажите дату начала и окончания события');
786
+ const startMs = Date.parse(start);
787
+ const endMs = Date.parse(end);
788
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs)
789
+ throw new Error('Время окончания должно быть позже времени начала');
790
+
791
+ const attendees = [...new Set((Array.isArray(body.attendees) ? body.attendees : []).map(s => String(s || '').trim()).filter(Boolean))];
792
+ const externalEmails = [...new Set((Array.isArray(body.externalEmails) ? body.externalEmails : []).map(s => String(s || '').trim()).filter(Boolean))];
793
+
794
+ const payload = {
795
+ uid,
796
+ summary: String(body.summary || 'Встреча').trim(),
797
+ location: String(body.location || '').trim(),
798
+ description: String(body.description || '').trim(),
799
+ start,
800
+ end,
801
+ allDay: Boolean(body.allDay),
802
+ attendees,
803
+ externalEmails,
804
+ recurrence: String(body.recurrence || 'none').trim(),
805
+ reminderMin: Number(body.reminderMin) || 0,
806
+ category: String(body.category || 'meeting').trim(),
807
+ organizer: String(body.organizer || access.uid || '').trim(),
808
+ sourceNodePath: String(body.sourceNodePath || storage.path || '/'),
809
+ status,
810
+ time: startMs,
811
+ };
812
+
813
+ const msg = {
814
+ uid,
815
+ summary: payload.summary,
816
+ location: payload.location,
817
+ description: payload.description,
818
+ start: payload.start,
819
+ end: payload.end,
820
+ allDay: payload.allDay,
821
+ attendees: payload.attendees,
822
+ externalEmails: payload.externalEmails,
823
+ recurrence: payload.recurrence,
824
+ reminderMin: payload.reminderMin,
825
+ category: payload.category,
826
+ organizer: payload.organizer,
827
+ sourceNodePath: payload.sourceNodePath,
828
+ status: payload.status,
829
+ time: payload.time,
830
+ };
831
+
832
+ const saved = await storage.save_file({
833
+ filename: `${uid}.ics`,
834
+ encoding: 'utf-8',
835
+ time: startMs,
836
+ feed: 'point',
837
+ message: JSON.stringify(msg),
838
+ post: JSON.stringify(payload),
839
+ session: params.session,
840
+ });
841
+
842
+ // Зеркалируем приглашение в личные календари приглашённых сотрудников (/USERS/<attUid>)
843
+ const mirrored = [];
844
+ if (attendees.length && globalThis.WORK?.$users) {
845
+ const usersRoot = await globalThis.WORK.$users;
846
+ for (const attUid of attendees) {
847
+ if (storage.type === '$user' && storage.id === attUid)
848
+ continue;
849
+ const userCab = await usersRoot.get_item?.('//' + attUid).catch(() => null);
850
+ if (!userCab || typeof userCab.save_file !== 'function')
851
+ continue;
852
+ await userCab.save_file({
853
+ filename: `${uid}.ics`,
854
+ encoding: 'utf-8',
855
+ time: startMs,
856
+ feed: 'point',
857
+ message: JSON.stringify(msg),
858
+ post: JSON.stringify(payload),
859
+ // системное зеркало приглашения в личный календарь приглашённого
860
+ session: { uid: attUid, $user: globalThis.WORK },
861
+ }).catch(() => {});
862
+ mirrored.push(attUid);
863
+ }
864
+ }
865
+
866
+ return { ok: true, uid, path: saved?.path || '', event: payload, mirrored };
867
+ }