Добавить общие события и множественный выбор в календарь

This commit is contained in:
dev
2026-11-24 13:50:38 +03:00
parent d7f4a4b457
commit 9960e2e8bd
8 changed files with 426 additions and 86 deletions
+1
View File
@@ -755,6 +755,7 @@ function normalizeRestoreData(data) {
const calendarEvents = (data.calendar_events || []).map(x => ({
id: reqInt(x.id),
user_id: reqInt(x.user_id),
is_common: x.is_common === true,
title: optText(x.title, 200) || '',
notes: optText(x.notes, 5000) || '',
location: optText(x.location, 200) || '',
+3 -2
View File
@@ -265,7 +265,7 @@ ok('calendar_events входят в бэкап и sequences', BACKUP_TABLES.incl
const calRestore = normalizeRestoreData({
...base,
calendar_events: [
{ id: 1, user_id: 1, title: 'Созвон', notes: 'n', location: 'Zoom', color: 'nope', starts_at: '2026-11-24T07:30:00.000Z', ends_at: '2026-11-24T08:30:00.000Z', all_day: false, repeat_rule: 'weekly', repeat_until: '2026-12-31', reminder_minutes: [10, 10, 999] },
{ id: 1, user_id: 1, is_common: true, title: 'Созвон', notes: 'n', location: 'Zoom', color: 'nope', starts_at: '2026-11-24T07:30:00.000Z', ends_at: '2026-11-24T08:30:00.000Z', all_day: false, repeat_rule: 'weekly', repeat_until: '2026-12-31', reminder_minutes: [10, 10, 999] },
{ id: 2, user_id: 1, title: 'Без времени' },
],
});
@@ -274,7 +274,8 @@ ok('calendar_events нормализуются: цвет/повтор/напом
calRestore.calendar_events[0].color === 'blue' &&
calRestore.calendar_events[0].repeat_rule === 'weekly' &&
calRestore.calendar_events[0].repeat_until === '2026-12-31' &&
calRestore.calendar_events[0].reminder_minutes.join(',') === '10',
calRestore.calendar_events[0].reminder_minutes.join(',') === '10' &&
calRestore.calendar_events[0].is_common === true,
calRestore.calendar_events);
console.log(failed ? `\n${failed} проверок провалено` : '\nBACKUP SELFTEST OK');
+2
View File
@@ -854,6 +854,7 @@ CREATE INDEX IF NOT EXISTS idx_post_lesson_task_closures_group_date ON post_less
CREATE TABLE IF NOT EXISTS calendar_events (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
is_common BOOLEAN NOT NULL DEFAULT false,
title VARCHAR(200) NOT NULL DEFAULT '',
notes TEXT NOT NULL DEFAULT '',
location VARCHAR(200) NOT NULL DEFAULT '',
@@ -870,4 +871,5 @@ CREATE TABLE IF NOT EXISTS calendar_events (
purge_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_calendar_events_user_start ON calendar_events(user_id, starts_at) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_calendar_events_common_start ON calendar_events(starts_at) WHERE deleted_at IS NULL AND is_common;
CREATE INDEX IF NOT EXISTS idx_calendar_events_purge ON calendar_events(purge_at) WHERE purge_at IS NOT NULL;
+2
View File
@@ -1160,5 +1160,7 @@ ALTER TABLE calendar_events ADD COLUMN IF NOT EXISTS repeat_until DATE;
ALTER TABLE calendar_events ADD COLUMN IF NOT EXISTS reminder_minutes INT[] NOT NULL DEFAULT '{}';
ALTER TABLE calendar_events ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE calendar_events ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ;
ALTER TABLE calendar_events ADD COLUMN IF NOT EXISTS is_common BOOLEAN NOT NULL DEFAULT false;
CREATE INDEX IF NOT EXISTS idx_calendar_events_user_start ON calendar_events(user_id, starts_at) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_calendar_events_common_start ON calendar_events(starts_at) WHERE deleted_at IS NULL AND is_common;
CREATE INDEX IF NOT EXISTS idx_calendar_events_purge ON calendar_events(purge_at) WHERE purge_at IS NOT NULL;
+157 -41
View File
@@ -32,6 +32,67 @@ function calError(status, message) {
return err;
}
function parseUserId(value) {
if (typeof value !== 'number' && typeof value !== 'string') return NaN;
const s = String(value).trim();
if (!/^\d+$/.test(s)) return NaN;
const n = Number(s);
return Number.isSafeInteger(n) && n > 0 ? n : NaN;
}
async function resolveCalendarUser(pool, value) {
const id = parseUserId(value);
if (Number.isNaN(id)) throw calError(400, 'Неверный пользователь');
const { rows } = await pool.query(
`SELECT id, COALESCE(NULLIF(name, ''), username) AS name
FROM users WHERE id = $1 AND is_active IS NOT FALSE`,
[id]
);
if (!rows.length) throw calError(404, 'Пользователь не найден');
return { id: rows[0].id, name: rows[0].name };
}
async function calendarTarget(pool, actor, value) {
const isAdmin = !!actor && actor.role === 'admin';
if (value == null || value === '') return { isAdmin, user: null };
const id = parseUserId(value);
if (Number.isNaN(id)) throw calError(400, 'Неверный пользователь');
if (!isAdmin) {
if (!actor || id !== parseUserId(actor.id)) throw calError(403, 'Нельзя назначить событие другому пользователю');
return { isAdmin, user: null };
}
return { isAdmin, user: await resolveCalendarUser(pool, id) };
}
async function calendarAudience(pool, actor, body) {
const data = body && typeof body === 'object' ? body : {};
const isAdmin = !!actor && actor.role === 'admin';
const isCommon = data.is_common === true;
if (isCommon && !isAdmin) throw calError(403, 'Общее событие может создать только администратор');
if (!isAdmin && data.user_ids != null) throw calError(403, 'Нельзя назначить событие другим пользователям');
if (isCommon) return { isAdmin, isCommon: true, users: [] };
if (Array.isArray(data.user_ids)) {
if (data.user_ids.length > 50) throw calError(400, 'Слишком много пользователей');
const users = [];
for (const raw of data.user_ids) {
const user = await resolveCalendarUser(pool, raw);
if (!users.some(u => u.id === user.id)) users.push(user);
}
return { isAdmin, isCommon: false, users };
}
const target = await calendarTarget(pool, actor, data.user_id);
return { isAdmin, isCommon: false, users: target.user ? [target.user] : [] };
}
async function listCalendarAssignableUsers(pool) {
const { rows } = await pool.query(
`SELECT id, COALESCE(NULLIF(name, ''), username) AS name, role
FROM users WHERE is_active IS NOT FALSE
ORDER BY COALESCE(NULLIF(name, ''), username), id`
);
return rows;
}
function addDaysIso(iso, n) {
const d = new Date(iso + 'T00:00:00Z');
d.setUTCDate(d.getUTCDate() + n);
@@ -127,6 +188,7 @@ function validateCalendarEvent(body, tz) {
notes,
location,
color,
is_common: data.is_common === true,
all_day: allDay,
starts_at: startsAt,
ends_at: endsAt,
@@ -146,6 +208,7 @@ async function ensureCalendarEventsTable(pool) {
await pool.query(`CREATE TABLE IF NOT EXISTS calendar_events (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
is_common BOOLEAN NOT NULL DEFAULT false,
title VARCHAR(200) NOT NULL DEFAULT '',
notes TEXT NOT NULL DEFAULT '',
location VARCHAR(200) NOT NULL DEFAULT '',
@@ -161,18 +224,27 @@ async function ensureCalendarEventsTable(pool) {
deleted_at TIMESTAMPTZ,
purge_at TIMESTAMPTZ
)`);
await pool.query('ALTER TABLE calendar_events ADD COLUMN IF NOT EXISTS is_common BOOLEAN NOT NULL DEFAULT false');
await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_events_user_start ON calendar_events(user_id, starts_at) WHERE deleted_at IS NULL');
await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_events_common_start ON calendar_events(starts_at) WHERE deleted_at IS NULL AND is_common');
await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_events_purge ON calendar_events(purge_at) WHERE purge_at IS NOT NULL');
}
async function listCalendarEvents(pool, { userId, fromIso, toIso, tz }) {
const params = [userId, fromIso, toIso];
async function listCalendarEvents(pool, { userId, isAdmin, targetUser, fromIso, toIso, tz }) {
const params = [fromIso, toIso];
let ownerClause = '';
const ownerId = targetUser ? targetUser.id : (isAdmin ? null : userId);
if (ownerId != null) {
params.push(ownerId);
ownerClause = ` AND (e.is_common OR e.user_id = $${params.length})`;
}
const bound = bindTz(`
SELECT e.id, e.title, e.notes, e.location, e.color, e.all_day,
SELECT e.id, e.user_id, e.is_common, COALESCE(NULLIF(u.name, ''), u.username) AS user_name, e.title, e.notes, e.location, e.color, e.all_day,
e.repeat_rule, e.repeat_until, e.reminder_minutes,
e.starts_at AS series_start, e.ends_at AS series_end,
occ.occ_start, occ.occ_end
FROM calendar_events e
LEFT JOIN users u ON u.id = e.user_id
CROSS JOIN LATERAL (
SELECT s.local_start AT TIME ZONE $TZ$ AS occ_start,
(s.local_start + (e.ends_at - e.starts_at)) AT TIME ZONE $TZ$ AS occ_end
@@ -180,7 +252,7 @@ async function listCalendarEvents(pool, { userId, fromIso, toIso, tz }) {
SELECT g AS local_start
FROM generate_series(
(e.starts_at AT TIME ZONE $TZ$),
(($3::date + 1)::timestamp),
(($2::date + 1)::timestamp),
CASE e.repeat_rule
WHEN 'daily' THEN interval '1 day'
WHEN 'weekly' THEN interval '1 week'
@@ -195,15 +267,17 @@ async function listCalendarEvents(pool, { userId, fromIso, toIso, tz }) {
SELECT e.starts_at, e.ends_at
WHERE e.repeat_rule = 'none'
) occ
WHERE e.user_id = $1
AND e.deleted_at IS NULL
AND occ.occ_end >= ($2::date::timestamp AT TIME ZONE $TZ$)
AND occ.occ_start < (($3::date + 1)::timestamp AT TIME ZONE $TZ$)
WHERE e.deleted_at IS NULL${ownerClause}
AND occ.occ_end >= ($1::date::timestamp AT TIME ZONE $TZ$)
AND occ.occ_start < (($2::date + 1)::timestamp AT TIME ZONE $TZ$)
ORDER BY occ.occ_start, e.id
`, params, tz);
const { rows } = await pool.query(bound.sql, bound.params);
return rows.map(r => ({
id: r.id,
user_id: r.user_id,
user_name: r.user_name || null,
is_common: r.is_common === true,
title: r.title,
notes: r.notes,
location: r.location,
@@ -220,60 +294,98 @@ async function listCalendarEvents(pool, { userId, fromIso, toIso, tz }) {
}));
}
async function createCalendarEvent(pool, { userId, data, tz }) {
const f = validateCalendarEvent(data, tz);
const { rows } = await pool.query(
`INSERT INTO calendar_events
(user_id, title, notes, location, color, starts_at, ends_at, all_day, repeat_rule, repeat_until, reminder_minutes)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
RETURNING *`,
[userId, f.title, f.notes, f.location, f.color, f.starts_at, f.ends_at, f.all_day, f.repeat_rule, f.repeat_until, f.reminder_minutes]
);
return rows[0];
function eventOwnerClause(params, { userId, isAdmin }) {
let clause = '';
if (!isAdmin) {
params.push(userId);
clause += ` AND user_id = $${params.length} AND NOT is_common`;
}
return clause;
}
async function updateCalendarEvent(pool, { userId, id, data, tz }) {
const f = validateCalendarEvent(data, tz);
async function createCalendarEvents(pool, { userId, audience, data, tz }) {
const f = validateCalendarEvent({ ...data, is_common: audience.isCommon }, tz);
const owners = audience.isCommon || !audience.users.length
? [userId]
: audience.users.map(u => u.id);
const client = await pool.connect();
try {
await client.query('BEGIN');
const items = [];
for (const ownerId of owners) {
const { rows } = await client.query(
`INSERT INTO calendar_events
(user_id, is_common, title, notes, location, color, starts_at, ends_at, all_day, repeat_rule, repeat_until, reminder_minutes)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
RETURNING *`,
[ownerId, f.is_common, f.title, f.notes, f.location, f.color, f.starts_at, f.ends_at, f.all_day, f.repeat_rule, f.repeat_until, f.reminder_minutes]
);
items.push(rows[0]);
}
await client.query('COMMIT');
return items;
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
async function updateCalendarEvent(pool, { userId, audience, id, data, tz }) {
const f = validateCalendarEvent({ ...data, is_common: audience.isCommon }, tz);
const params = [];
const sets = [];
const targetUser = audience.users[0];
if (targetUser && audience.isAdmin) {
params.push(targetUser.id);
sets.push(`user_id = $${params.length}`);
}
for (const [column, value] of Object.entries(f)) {
params.push(value);
sets.push(`${column} = $${params.length}`);
}
params.push(id);
const where = `id = $${params.length} AND deleted_at IS NULL` + eventOwnerClause(params, { userId, isAdmin: audience.isAdmin });
const { rows } = await pool.query(
`UPDATE calendar_events
SET title = $3, notes = $4, location = $5, color = $6, starts_at = $7, ends_at = $8,
all_day = $9, repeat_rule = $10, repeat_until = $11, reminder_minutes = $12, updated_at = now()
WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL
RETURNING *`,
[id, userId, f.title, f.notes, f.location, f.color, f.starts_at, f.ends_at, f.all_day, f.repeat_rule, f.repeat_until, f.reminder_minutes]
`UPDATE calendar_events SET ${sets.join(', ')}, updated_at = now() WHERE ${where} RETURNING *`,
params
);
if (!rows.length) throw calError(404, 'Событие не найдено');
return rows[0];
}
async function softDeleteCalendarEvent(pool, { userId, id, purgeDays }) {
async function softDeleteCalendarEvent(pool, { userId, isAdmin, id, purgeDays }) {
const days = Number.isInteger(purgeDays) && purgeDays >= 1 ? purgeDays : 30;
const params = [id];
params.push(days);
const dayIdx = params.length;
const where = `id = $1 AND deleted_at IS NULL` + eventOwnerClause(params, { userId, isAdmin });
const { rowCount } = await pool.query(
`UPDATE calendar_events
SET deleted_at = now(), purge_at = now() + make_interval(days => $3::int), updated_at = now()
WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL`,
[id, userId, days]
SET deleted_at = now(), purge_at = now() + make_interval(days => $${dayIdx}::int), updated_at = now()
WHERE ${where}`,
params
);
if (!rowCount) throw calError(404, 'Событие не найдено или уже удалено');
return true;
}
async function restoreCalendarEvent(pool, { userId, id }) {
async function restoreCalendarEvent(pool, { userId, isAdmin, id }) {
const params = [id];
const where = `id = $1 AND deleted_at IS NOT NULL` + eventOwnerClause(params, { userId, isAdmin });
const { rowCount } = await pool.query(
`UPDATE calendar_events
SET deleted_at = NULL, purge_at = NULL, updated_at = now()
WHERE id = $1 AND user_id = $2 AND deleted_at IS NOT NULL`,
[id, userId]
`UPDATE calendar_events SET deleted_at = NULL, purge_at = NULL, updated_at = now() WHERE ${where}`,
params
);
if (!rowCount) throw calError(404, 'Событие не найдено или не удалено');
return true;
}
async function deleteCalendarEventPermanent(pool, { userId, id }) {
const { rowCount } = await pool.query(
'DELETE FROM calendar_events WHERE id = $1 AND user_id = $2 AND deleted_at IS NOT NULL',
[id, userId]
);
async function deleteCalendarEventPermanent(pool, { userId, isAdmin, id }) {
const params = [id];
const where = `id = $1 AND deleted_at IS NOT NULL` + eventOwnerClause(params, { userId, isAdmin });
const { rowCount } = await pool.query(`DELETE FROM calendar_events WHERE ${where}`, params);
if (!rowCount) throw calError(404, 'Событие не найдено');
return true;
}
@@ -395,8 +507,12 @@ module.exports = {
ensureCalendarEventsTable,
normalizeCalendarRange,
validateCalendarEvent,
resolveCalendarUser,
calendarTarget,
calendarAudience,
listCalendarAssignableUsers,
listCalendarEvents,
createCalendarEvent,
createCalendarEvents,
updateCalendarEvent,
softDeleteCalendarEvent,
restoreCalendarEvent,
+28
View File
@@ -62,7 +62,23 @@
.cal-event{position:absolute;border-radius:6px;padding:2px 5px;font-size:.72rem;line-height:1.25;overflow:hidden;cursor:pointer;border-left:3px solid var(--ev);background:color-mix(in srgb,var(--ev) 16%,#fff);color:var(--text);z-index:3}
.cal-event:hover{filter:brightness(.97);z-index:4}
.cal-event.is-source{background:color-mix(in srgb,var(--ev) 10%,#fff);color:var(--muted)}
.cal-event.is-assigned,.cal-allday-chip.is-assigned,.cal-month-chip.is-assigned{border-left-style:dashed}
.cal-event.is-common{outline:1px dashed var(--ev);outline-offset:-3px}
.cal-allday-chip.is-common,.cal-month-chip.is-common{border-left-width:5px}
.cal-assignee{flex:1;min-width:0;border:1px solid var(--border);border-radius:9px;padding:8px}
.cal-assignee-common{display:flex;align-items:center;gap:7px;font-size:.8rem;font-weight:600;cursor:pointer}
.cal-assignee-common input{accent-color:var(--accent);margin:0}
.cal-assignee-bar{display:flex;align-items:center;gap:8px;margin:8px 0 6px}
.cal-assignee-bar .cal-today-btn{padding:4px 9px;font-size:.7rem}
.cal-assignee-hint{font-size:.7rem;color:var(--muted)}
.cal-assignee-list{max-height:132px;overflow:auto;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:2px 10px}
.cal-assignee-list label{display:flex;align-items:center;gap:6px;font-size:.76rem;cursor:pointer;padding:3px 2px;border-radius:6px;min-width:0}
.cal-assignee-list label:hover{background:var(--bg)}
.cal-assignee-list input{accent-color:var(--accent);margin:0}
.cal-assignee-list span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.cal-assignee.is-common .cal-assignee-bar,.cal-assignee.is-common .cal-assignee-list{opacity:.45;pointer-events:none}
.cal-event-time{font-weight:700;margin-right:4px}
.cal-owner{font-weight:700;opacity:.7}
.cal-event svg{width:11px;height:11px;vertical-align:-1px;margin-right:3px}
.cal-now{position:absolute;left:0;right:0;height:2px;background:#ef4444;z-index:5;pointer-events:none}
.cal-now::before{content:'';position:absolute;left:-4px;top:-3px;width:8px;height:8px;border-radius:50%;background:#ef4444}
@@ -146,6 +162,7 @@
<h2 id="calLabel"></h2>
</div>
<div class="cal-head-right">
<select class="settings-input cal-hidden" id="calUserFilter" style="width:auto;max-width:180px" aria-label="Календарь пользователя"></select>
<div class="cal-views" id="calViews">
<button class="cal-view-btn" data-view="day" type="button">День</button>
<button class="cal-view-btn" data-view="week" type="button">Неделя</button>
@@ -168,6 +185,17 @@
<button class="icon-btn" id="calCloseBtn" type="button" aria-label="Закрыть"><i data-lucide="x"></i></button>
</div>
<input class="cal-modal-title" id="calTitle" maxlength="200" placeholder="Добавьте заголовок" type="text">
<div class="cal-row cal-hidden" id="calAssigneeRow" style="align-items:flex-start">
<span class="cal-row-label" style="padding-top:6px">Кому</span>
<div class="cal-assignee" id="calAssigneeBox">
<label class="cal-assignee-common"><input type="checkbox" id="calAssigneeCommon"><span>Общее событие для всех</span></label>
<div class="cal-assignee-bar">
<button class="cal-today-btn" id="calAssigneeAllBtn" type="button">Выбрать всех</button>
<span class="cal-assignee-hint" id="calAssigneeHint"></span>
</div>
<div class="cal-assignee-list" id="calAssigneeList"></div>
</div>
</div>
<div class="cal-row">
<span class="cal-row-label">Начало</span>
<div class="cal-datetime">
+193 -24
View File
@@ -23,6 +23,7 @@
const state = {
view: 'week', anchorIso: '', items: [], sources: [], hidden: new Set(),
rangeFrom: '', rangeTo: '', grid: null, uidMap: new Map(), editor: null,
users: [], ownerFilter: '',
};
let nowTimer = null;
let drag = null;
@@ -49,6 +50,7 @@
localStorage.setItem('calView', state.view);
localStorage.setItem('calAnchor', state.anchorIso);
localStorage.setItem('calSources', JSON.stringify([...state.hidden]));
localStorage.setItem('calOwner', state.ownerFilter);
} catch {}
}
@@ -60,6 +62,7 @@
view = localStorage.getItem('calView') || '';
anchor = localStorage.getItem('calAnchor') || '';
hidden = JSON.parse(localStorage.getItem('calSources') || '[]');
state.ownerFilter = isAdmin() ? (localStorage.getItem('calOwner') || '') : '';
} catch {}
if (VIEWS.includes(view)) state.view = view;
if (dtIsoMatch(anchor)) state.anchorIso = anchor;
@@ -67,6 +70,37 @@
if (!state.anchorIso) state.anchorIso = todayIso();
}
function userLabel(u) {
return u.name || u.username || `#${u.id}`;
}
function userOption(u) {
return `<option value="${u.id}">${esc(userLabel(u))}${u.role === 'admin' ? ' (админ)' : ''}</option>`;
}
async function loadUsers() {
if (!isAdmin()) return;
try {
const data = await request('/api/calendar/users');
state.users = Array.isArray(data.items) ? data.items : [];
} catch (e) {
console.error('calendar users:', e);
state.users = [];
}
}
function renderUserFilter() {
const sel = document.getElementById('calUserFilter');
sel.classList.toggle('cal-hidden', !isAdmin());
if (!isAdmin()) return;
sel.innerHTML = '<option value="">Все пользователи</option>' + state.users.map(userOption).join('');
sel.value = state.ownerFilter;
if (sel.value !== state.ownerFilter) {
state.ownerFilter = sel.value;
saveState();
}
}
function weekBounds(iso) {
const dow = isoDow(iso);
if (dow < 0) return { from: iso, to: iso };
@@ -155,6 +189,10 @@
allDay: it.all_day === true, color: it.color,
notes: it.notes || '', location: it.location || '', repeat: it.repeat_rule || 'none',
repeatUntil: it.repeat_until, reminders: it.reminder_minutes || [],
ownerId: it.user_id || null, ownerName: it.user_name || '',
isCommon: it.is_common === true,
readOnly: it.is_common === true && !isAdmin(),
assigned: isAdmin() && it.is_common !== true && Number(it.user_id) !== Number(currentUser.id),
});
}
}
@@ -255,6 +293,15 @@
return meta ? `<i data-lucide="${meta.icon}"></i>` : '';
}
function eventOwnerLabel(seg) {
if (seg.isCommon) return '<span class="cal-owner">Общее: </span>';
return seg.assigned && seg.ownerName ? `<span class="cal-owner">${esc(seg.ownerName)}: </span>` : '';
}
function eventClass(base, seg) {
return `${base}${seg.isCommon ? ' is-common' : ''}${seg.assigned ? ' is-assigned' : ''}`;
}
function segmentHtml(seg, hours) {
const top = (seg.startMin - hours.start * 60) / 60 * HOUR_H;
const height = Math.max(20, (seg.endMin - seg.startMin) / 60 * HOUR_H - 2);
@@ -263,14 +310,16 @@
const style = `--ev:${colorHex(seg.color)};top:${Math.round(top)}px;height:${Math.round(height)}px;left:${left.toFixed(3)}%;width:${(width - 0.4).toFixed(3)}%`;
const time = height >= 34 ? `<span class="cal-event-time">${esc(fmtHmStr(hmFromMinutes(seg.startMin)))}</span>` : '';
const mark = seg.continued ? '↔ ' : '';
const owner = eventOwnerLabel(seg);
const title = `${mark}${esc(seg.title)}`;
const cls = seg.source === 'personal' ? 'cal-event' : 'cal-event is-source';
return `<div class="${cls}" style="${style}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${sourceIcon(seg)}${time}${title}</div>`;
const cls = seg.source === 'personal' ? eventClass('cal-event', seg) : 'cal-event is-source';
return `<div class="${cls}" style="${style}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${sourceIcon(seg)}${time}${owner}${title}</div>`;
}
function allDayHtml(seg) {
const cls = seg.source === 'personal' ? 'cal-allday-chip' : 'cal-allday-chip is-source';
return `<div class="${cls}" style="--ev:${colorHex(seg.color)}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${esc(seg.title)}</div>`;
const cls = seg.source === 'personal' ? eventClass('cal-allday-chip', seg) : 'cal-allday-chip is-source';
const owner = eventOwnerLabel(seg);
return `<div class="${cls}" style="--ev:${colorHex(seg.color)}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${owner}${esc(seg.title)}</div>`;
}
function nowTop(hours) {
@@ -345,8 +394,9 @@
html += `<span class="cal-month-num" data-open-day="${iso}">${iso === bounds.from ? `${Number(iso.slice(8, 10))} ${esc(fmtMonthYearIso(iso).split(' ')[0])}` : Number(iso.slice(8, 10))}</span>`;
segs.slice(0, 3).forEach(seg => {
const time = seg.allDay ? '' : `${esc(fmtHmStr(hmFromMinutes(seg.startMin)))} `;
const cls = seg.source === 'personal' ? 'cal-month-chip' : 'cal-month-chip is-source';
html += `<div class="${cls}" style="--ev:${colorHex(seg.color)}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${time}${esc(seg.title)}</div>`;
const cls = seg.source === 'personal' ? eventClass('cal-month-chip', seg) : 'cal-month-chip is-source';
const owner = eventOwnerLabel(seg);
html += `<div class="${cls}" style="--ev:${colorHex(seg.color)}" data-ev="${attrEsc(seg.uid)}" title="${attrEsc(seg.title)}">${time}${owner}${esc(seg.title)}</div>`;
});
if (segs.length > 3) html += `<div class="cal-more">+ ещё ${segs.length - 3}</div>`;
html += '</div>';
@@ -376,7 +426,7 @@
html += `<div class="cal-agenda-day"><div class="cal-agenda-date">${esc(fmtDateOnlyLongIso(day))}</div>`;
segs.forEach(seg => {
const time = seg.allDay ? 'Весь день' : `${fmtHmStr(hmFromMinutes(seg.startMin))} – ${fmtHmStr(hmFromMinutes(seg.endMin))}`;
const meta = [seg.location, seg.notes, seg.source !== 'personal' ? REPEAT_LABELS[seg.repeat] || '' : ''].filter(Boolean).join(' · ');
const meta = [seg.isCommon ? 'Общее событие' : (seg.assigned ? seg.ownerName : ''), seg.location, seg.notes, seg.source !== 'personal' ? REPEAT_LABELS[seg.repeat] || '' : ''].filter(Boolean).join(' · ');
html += `<div class="cal-agenda-row" data-ev="${attrEsc(seg.uid)}"><span class="cal-agenda-time">${esc(time)}</span><span class="cal-dot" style="--ev:${colorHex(seg.color)}"></span><div class="cal-agenda-body"><div class="cal-agenda-title">${esc(seg.title)}</div>${meta ? `<div class="cal-agenda-meta">${esc(meta)}</div>` : ''}</div></div>`;
});
html += '</div>';
@@ -430,8 +480,9 @@
}
function renderSide() {
const personalLabel = isAdmin() && !state.ownerFilter ? 'Все события' : 'Личный';
document.getElementById('calCalendars').innerHTML =
`<label class="cal-personal-row" style="--ev:${COLOR_HEX.blue}"><input type="checkbox" data-hidden="personal" ${state.hidden.has('personal') ? '' : 'checked'}><span class="cal-dot"></span><span class="cal-source-label">Личный</span></label>`;
`<label class="cal-personal-row" style="--ev:${COLOR_HEX.blue}"><input type="checkbox" data-hidden="personal" ${state.hidden.has('personal') ? '' : 'checked'}><span class="cal-dot"></span><span class="cal-source-label">${personalLabel}</span></label>`;
document.getElementById('calSources').innerHTML = state.sources.map(src => {
const meta = SOURCE_META[src.id] || {};
return `<label class="cal-source-row" style="--ev:${colorHex(src.color)}"><input type="checkbox" data-hidden="${attrEsc(src.id)}" ${state.hidden.has(src.id) ? '' : 'checked'}><span class="cal-dot"></span>${meta.icon ? `<i data-lucide="${meta.icon}"></i>` : ''}<span class="cal-source-label">${esc(meta.label || src.label || src.id)}</span><span class="cal-source-count">${(src.items || []).length}</span></label>`;
@@ -547,10 +598,41 @@
function renderColors() {
document.getElementById('calColors').innerHTML = COLORS.map(name =>
`<button class="cal-color${name === state.editor.color ? ' on' : ''}" type="button" data-color="${name}" style="--ev:${COLOR_HEX[name]}" aria-label="${name}"></button>`
`<button class="cal-color${name === state.editor.color ? ' on' : ''}" type="button" data-color="${name}" style="--ev:${COLOR_HEX[name]}" aria-label="${name}"${state.editor.readOnly ? ' disabled' : ''}></button>`
).join('');
}
function updateAssigneeHint() {
if (!state.editor || !isAdmin()) return;
const hint = document.getElementById('calAssigneeHint');
if (state.editor.isCommon) hint.textContent = 'Видно всем пользователям, включая новых';
else if (state.editor.id) hint.textContent = 'При редактировании можно выбрать одного пользователя';
else {
const count = state.editor.selectedUserIds.length;
hint.textContent = count ? `Выбрано пользователей: ${count}` : 'Выберите хотя бы одного пользователя';
}
}
function renderAssignee() {
const row = document.getElementById('calAssigneeRow');
row.classList.toggle('cal-hidden', !isAdmin());
if (!isAdmin() || !state.editor) return;
const editor = state.editor;
const selected = new Set(editor.selectedUserIds.map(Number));
const known = new Set(state.users.map(u => Number(u.id)));
document.getElementById('calAssigneeCommon').checked = editor.isCommon;
document.getElementById('calAssigneeBox').classList.toggle('is-common', editor.isCommon);
document.getElementById('calAssigneeList').innerHTML =
state.users.map(u => {
const id = Number(u.id);
return `<label><input type="checkbox" data-user="${id}"${selected.has(id) ? ' checked' : ''}><span>${esc(userLabel(u))}${u.role === 'admin' ? ' (админ)' : ''}</span></label>`;
}).join('') +
[...selected].filter(id => !known.has(id)).map(id =>
`<label title="Пользователь недоступен"><input type="checkbox" checked disabled><span>#${id} (недоступен)</span></label>`
).join('');
updateAssigneeHint();
}
function reminderLabel(n) {
if (n === 0) return 'в момент события';
if (n === 1440) return 'за 1 день';
@@ -561,7 +643,7 @@
function renderReminders() {
document.getElementById('calReminders').innerHTML = state.editor.reminders.map(n =>
`<span class="cal-rem-chip" data-rem="${n}" role="button" tabindex="0">${reminderLabel(n)} ×</span>`
`<span class="cal-rem-chip" data-rem="${n}" role="button" tabindex="0">${reminderLabel(n)}${state.editor.readOnly ? '' : ' ×'}</span>`
).join('');
}
@@ -571,14 +653,39 @@
document.getElementById('calRepeatUntilRow').classList.toggle('cal-hidden', document.getElementById('calRepeat').value === 'none');
}
function setEditorReadOnly(readOnly) {
const ids = ['calTitle', 'calStartDate', 'calStartTime', 'calEndDate', 'calEndTime', 'calAllDay',
'calRepeat', 'calRepeatUntil', 'calLocation', 'calNotes', 'calReminderAdd', 'calReminderAddBtn'];
ids.forEach(id => {
const el = document.getElementById(id);
if (el) el.disabled = readOnly;
});
document.getElementById('calSaveBtn').classList.toggle('cal-hidden', readOnly);
document.getElementById('calDeleteBtn').classList.add('cal-hidden');
if (!readOnly) document.getElementById('calDeleteBtn').classList.toggle('cal-hidden', !state.editor || !state.editor.id);
}
function openEditor(prefill) {
const p = prefill || {};
const admin = isAdmin();
const ownerId = p.ownerId ? Number(p.ownerId) : (currentUser ? Number(currentUser.id) : null);
const selectedUserIds = Array.isArray(p.selectedUserIds)
? [...new Set(p.selectedUserIds.map(Number))]
: (admin && ownerId ? [ownerId] : []);
state.editor = {
id: p.id || null,
ownerId,
isCommon: p.isCommon === true,
readOnly: p.readOnly === true,
selectedUserIds,
originalUserIds: [...selectedUserIds],
color: COLORS.includes(p.color) ? p.color : 'blue',
reminders: Array.isArray(p.reminders) ? [...p.reminders].sort((a, b) => a - b) : [],
};
document.getElementById('calModalTitle').textContent = p.id ? 'Событие' : 'Новое событие';
const title = state.editor.isCommon || state.editor.readOnly
? 'Общее событие'
: (p.id ? 'Событие' : 'Новое событие');
document.getElementById('calModalTitle').textContent = title;
document.getElementById('calTitle').value = p.title || '';
document.getElementById('calStartDate').value = p.dateStart || state.anchorIso;
document.getElementById('calStartTime').value = p.timeStart || '10:00';
@@ -589,13 +696,14 @@
document.getElementById('calRepeatUntil').value = p.repeatUntil || '';
document.getElementById('calLocation').value = p.location || '';
document.getElementById('calNotes').value = p.notes || '';
document.getElementById('calDeleteBtn').classList.toggle('cal-hidden', !p.id);
setEditorReadOnly(state.editor.readOnly);
renderAssignee();
renderColors();
renderReminders();
syncAllDay();
document.getElementById('calEventModal').classList.add('open');
renderIcons();
document.getElementById('calTitle').focus();
(state.editor.readOnly ? document.getElementById('calCancelBtn') : document.getElementById('calTitle')).focus();
}
function closeEditor() {
@@ -618,6 +726,7 @@
: dtToLocalInput(item.id && seriesEnd ? seriesEnd : new Date(item.end).toISOString());
openEditor({
id: item.id, title: item.title, color: item.color, notes: item.notes,
ownerId: item.ownerId, isCommon: item.isCommon, readOnly: item.readOnly,
location: item.location, repeat: item.repeat, repeatUntil: item.repeatUntil,
reminders: item.reminders, allDay: item.allDay,
dateStart: startLocal.slice(0, 10), timeStart: startLocal.slice(11, 16),
@@ -626,7 +735,8 @@
}
async function saveEditor() {
if (!state.editor) return;
if (!state.editor || state.editor.readOnly) return;
const editor = state.editor;
const title = document.getElementById('calTitle').value.trim();
if (!title) { showToast('Укажите заголовок события', true); return; }
const allDay = document.getElementById('calAllDay').checked;
@@ -649,23 +759,49 @@
showToast('Повторяющееся событие не может длиться больше 7 дней', true);
return;
}
if (state.editor.reminders.length > 5) { showToast('Не больше 5 напоминаний', true); return; }
if (editor.reminders.length > 5) { showToast('Не больше 5 напоминаний', true); return; }
const repeatUntil = repeat !== 'none' ? document.getElementById('calRepeatUntil').value : '';
if (repeatUntil && repeatUntil < startDate) { showToast('Повтор должен заканчиваться не раньше начала', true); return; }
const body = {
title, notes: document.getElementById('calNotes').value,
location: document.getElementById('calLocation').value,
color: state.editor.color, all_day: allDay, starts_at: startsAt, ends_at: endsAt,
color: editor.color, all_day: allDay, starts_at: startsAt, ends_at: endsAt,
repeat_rule: repeat, repeat_until: repeatUntil || null,
reminder_minutes: state.editor.reminders,
reminder_minutes: editor.reminders,
};
const id = state.editor.id;
if (isAdmin()) {
if (editor.isCommon) {
body.is_common = true;
} else {
const selected = [...new Set(editor.selectedUserIds.map(Number))].filter(n => Number.isInteger(n) && n > 0);
if (!selected.length) { showToast('Выберите пользователя', true); return; }
const unavailable = selected.filter(id => !state.users.some(u => Number(u.id) === id));
const unchanged = editor.id && selected.length === editor.originalUserIds.length &&
selected.every(id => editor.originalUserIds.includes(id));
if (unavailable.length) {
if (!(unavailable.length === selected.length && unchanged)) {
showToast('Выбранный пользователь недоступен', true);
return;
}
} else {
body.user_ids = selected;
}
}
}
const id = editor.id;
try {
await request(id ? `/api/calendar/events/${id}` : '/api/calendar/events', {
const result = await request(id ? `/api/calendar/events/${id}` : '/api/calendar/events', {
method: id ? 'PUT' : 'POST', body,
});
const count = id ? 1 : (Array.isArray(result.items) ? result.items.length : 1);
closeEditor();
showToast('Событие сохранено');
showToast(count > 1 ? `События сохранены: ${count}` : 'Событие сохранено');
if (!id && !editor.isCommon && state.ownerFilter &&
!editor.selectedUserIds.some(uid => String(uid) === state.ownerFilter)) {
state.ownerFilter = '';
saveState();
renderUserFilter();
}
await reload();
} catch (e) {
showToast(e.message, true);
@@ -673,7 +809,7 @@
}
async function removeEditor() {
if (!state.editor || !state.editor.id || !confirm('Удалить событие?')) return;
if (!state.editor || state.editor.readOnly || !state.editor.id || !confirm('Удалить событие?')) return;
try {
await request(`/api/calendar/events/${state.editor.id}`, { method: 'DELETE' });
closeEditor();
@@ -686,7 +822,9 @@
async function loadRange() {
const w = queryWindow();
const data = await request(`/api/calendar/events?from=${encodeURIComponent(w.from)}&to=${encodeURIComponent(w.to)}`);
let path = `/api/calendar/events?from=${encodeURIComponent(w.from)}&to=${encodeURIComponent(w.to)}`;
if (isAdmin() && state.ownerFilter) path += `&user_id=${encodeURIComponent(state.ownerFilter)}`;
const data = await request(path);
return { from: w.from, to: w.to, data };
}
@@ -734,6 +872,34 @@
const btn = e.target.closest('[data-view]');
if (btn) setView(btn.dataset.view);
});
document.getElementById('calUserFilter').addEventListener('change', e => {
state.ownerFilter = e.target.value;
saveState();
reload();
});
document.getElementById('calAssigneeCommon').addEventListener('change', e => {
if (!state.editor) return;
state.editor.isCommon = e.target.checked;
renderAssignee();
});
document.getElementById('calAssigneeAllBtn').addEventListener('click', () => {
if (!state.editor || state.editor.isCommon) return;
state.editor.selectedUserIds = state.users.map(u => Number(u.id));
renderAssignee();
});
document.getElementById('calAssigneeList').addEventListener('change', e => {
const input = e.target.closest('input[data-user]');
if (!input || input.disabled || !state.editor || state.editor.isCommon) return;
const uid = Number(input.dataset.user);
if (state.editor.id) {
state.editor.selectedUserIds = input.checked ? [uid] : [];
} else if (input.checked) {
if (!state.editor.selectedUserIds.includes(uid)) state.editor.selectedUserIds.push(uid);
} else {
state.editor.selectedUserIds = state.editor.selectedUserIds.filter(id => id !== uid);
}
renderAssignee();
});
document.getElementById('calNewBtn').addEventListener('click', () => openEditor({
dateStart: state.anchorIso, timeStart: '10:00', dateEnd: state.anchorIso, timeEnd: '11:00',
}));
@@ -791,17 +957,18 @@
document.getElementById('calRepeat').addEventListener('change', syncAllDay);
document.getElementById('calColors').addEventListener('click', e => {
const btn = e.target.closest('[data-color]');
if (!btn) return;
if (!btn || !state.editor || state.editor.readOnly) return;
state.editor.color = btn.dataset.color;
renderColors();
});
document.getElementById('calReminders').addEventListener('click', e => {
const chip = e.target.closest('[data-rem]');
if (!chip) return;
if (!chip || !state.editor || state.editor.readOnly) return;
state.editor.reminders = state.editor.reminders.filter(n => n !== Number(chip.dataset.rem));
renderReminders();
});
document.getElementById('calReminderAddBtn').addEventListener('click', () => {
if (!state.editor || state.editor.readOnly) return;
const n = Number(document.getElementById('calReminderAdd').value);
if (state.editor.reminders.length >= 5) { showToast('Не больше 5 напоминаний', true); return; }
if (!state.editor.reminders.includes(n)) state.editor.reminders.push(n);
@@ -830,8 +997,10 @@
async function init() {
if (!(await checkAuth())) return;
loadState();
await loadUsers();
buildSidebar(document.body.dataset.page);
bindUi();
renderUserFilter();
render();
await reload();
}
+40 -19
View File
@@ -122,8 +122,11 @@ const { ensureDigestTable, listDigests, createDigest, updateDigest, softDeleteDi
const {
ensureCalendarEventsTable,
normalizeCalendarRange,
calendarTarget,
calendarAudience,
listCalendarAssignableUsers,
listCalendarEvents,
createCalendarEvent,
createCalendarEvents,
updateCalendarEvent,
softDeleteCalendarEvent,
restoreCalendarEvent,
@@ -5580,18 +5583,28 @@ app.delete('/api/digests/:id/preview', requireAuth, async (req, res) => {
// --- Calendar ---
app.get('/api/calendar/users', apiLimiter, requireAuth, requireAdmin, async (req, res) => {
try {
res.json({ items: await listCalendarAssignableUsers(pool) });
} catch (e) {
console.error('calendar users:', e);
res.status(500).json({ error: 'Не удалось получить пользователей' });
}
});
app.get('/api/calendar/events', apiLimiter, requireAuth, async (req, res) => {
try {
const tz = await appTimezone();
const range = normalizeCalendarRange({ from: req.query.from, to: req.query.to, today: await appTodayIso() });
const scope = branchScope(req.user);
const target = await calendarTarget(pool, req.user, req.query.user_id);
const [items, sources] = await Promise.all([
listCalendarEvents(pool, { userId: req.user.id, ...range, tz }),
listCalendarEvents(pool, { userId: req.user.id, isAdmin: target.isAdmin, targetUser: target.user, ...range, tz }),
listWorkspaceSources(pool, { admin: scope.admin, branchIds: scope.ids, ...range, tz }),
]);
res.json({ items, sources });
} catch (e) {
if (e.status === 400) return res.status(400).json({ error: e.message });
if ([400, 403, 404].includes(e.status)) return res.status(e.status).json({ error: e.message });
console.error('calendar list:', e);
res.status(500).json({ error: 'Не удалось получить календарь' });
}
@@ -5599,11 +5612,17 @@ app.get('/api/calendar/events', apiLimiter, requireAuth, async (req, res) => {
app.post('/api/calendar/events', requireAuth, async (req, res) => {
try {
const item = await createCalendarEvent(pool, { userId: req.user.id, data: req.body, tz: await appTimezone() });
await logAudit(req, 'calendar.event.create', { id: item.id, title: item.title, starts_at: item.starts_at });
res.json({ item });
const audience = await calendarAudience(pool, req.user, req.body);
const items = await createCalendarEvents(pool, {
userId: req.user.id, audience, data: req.body, tz: await appTimezone(),
});
await logAudit(req, 'calendar.event.create', {
count: items.length, user_ids: items.map(x => x.user_id),
is_common: audience.isCommon, title: items[0].title, starts_at: items[0].starts_at,
});
res.json({ items, item: items[0] });
} catch (e) {
if (e.status === 400) return res.status(400).json({ error: e.message });
if ([400, 403, 404].includes(e.status)) return res.status(e.status).json({ error: e.message });
console.error('calendar create:', e);
res.status(500).json({ error: 'Не удалось создать событие' });
}
@@ -5613,12 +5632,14 @@ app.put('/api/calendar/events/:id', requireAuth, async (req, res) => {
try {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
const item = await updateCalendarEvent(pool, { userId: req.user.id, id, data: req.body, tz: await appTimezone() });
await logAudit(req, 'calendar.event.update', { id, title: item.title, starts_at: item.starts_at });
const audience = await calendarAudience(pool, req.user, req.body);
const item = await updateCalendarEvent(pool, {
userId: req.user.id, audience, id, data: req.body, tz: await appTimezone(),
});
await logAudit(req, 'calendar.event.update', { id, title: item.title, starts_at: item.starts_at, user_id: item.user_id, is_common: item.is_common });
res.json({ item });
} catch (e) {
if (e.status === 400) return res.status(400).json({ error: e.message });
if (e.status === 404) return res.status(404).json({ error: e.message });
if ([400, 403, 404].includes(e.status)) return res.status(e.status).json({ error: e.message });
console.error('calendar update:', e);
res.status(500).json({ error: 'Не удалось обновить событие' });
}
@@ -5628,11 +5649,11 @@ app.delete('/api/calendar/events/:id', requireAuth, async (req, res) => {
try {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
await softDeleteCalendarEvent(pool, { userId: req.user.id, id, purgeDays: await trashPurgeDays() });
await softDeleteCalendarEvent(pool, { userId: req.user.id, isAdmin: req.user.role === 'admin', id, purgeDays: await trashPurgeDays() });
await logAudit(req, 'calendar.event.delete', { id });
res.json({ ok: true });
} catch (e) {
if (e.status === 404) return res.status(404).json({ error: e.message });
if ([400, 403, 404].includes(e.status)) return res.status(e.status).json({ error: e.message });
console.error('calendar delete:', e);
res.status(500).json({ error: 'Не удалось удалить событие' });
}
@@ -5642,11 +5663,11 @@ app.put('/api/calendar/events/:id/restore', requireAuth, async (req, res) => {
try {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
await restoreCalendarEvent(pool, { userId: req.user.id, id });
await restoreCalendarEvent(pool, { userId: req.user.id, isAdmin: req.user.role === 'admin', id });
await logAudit(req, 'calendar.event.restore', { id });
res.json({ ok: true });
} catch (e) {
if (e.status === 404) return res.status(404).json({ error: e.message });
if ([400, 403, 404].includes(e.status)) return res.status(e.status).json({ error: e.message });
console.error('calendar restore:', e);
res.status(500).json({ error: 'Не удалось восстановить событие' });
}
@@ -5656,11 +5677,11 @@ app.delete('/api/calendar/events/:id/permanent', requireAuth, async (req, res) =
try {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
await deleteCalendarEventPermanent(pool, { userId: req.user.id, id });
await deleteCalendarEventPermanent(pool, { userId: req.user.id, isAdmin: req.user.role === 'admin', id });
await logAudit(req, 'calendar.event.permanent-delete', { id });
res.json({ ok: true });
} catch (e) {
if (e.status === 404) return res.status(404).json({ error: e.message });
if ([400, 403, 404].includes(e.status)) return res.status(e.status).json({ error: e.message });
console.error('calendar permanent delete:', e);
res.status(500).json({ error: 'Не удалось удалить событие навсегда' });
}
@@ -7873,8 +7894,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
const okUser = (await client.query('SELECT 1 FROM users WHERE id = $1', [x.user_id])).rowCount;
if (!okUser) continue;
await client.query(
'INSERT INTO calendar_events (id, user_id, title, notes, location, color, starts_at, ends_at, all_day, repeat_rule, repeat_until, reminder_minutes, created_at, updated_at, deleted_at, purge_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)',
[x.id, x.user_id, x.title, x.notes, x.location, x.color, x.starts_at, x.ends_at, x.all_day === true, x.repeat_rule, x.repeat_until || null, x.reminder_minutes || [], x.created_at || null, x.updated_at || null, x.deleted_at || null, x.purge_at || null]
'INSERT INTO calendar_events (id, user_id, is_common, title, notes, location, color, starts_at, ends_at, all_day, repeat_rule, repeat_until, reminder_minutes, created_at, updated_at, deleted_at, purge_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17)',
[x.id, x.user_id, x.is_common === true, x.title, x.notes, x.location, x.color, x.starts_at, x.ends_at, x.all_day === true, x.repeat_rule, x.repeat_until || null, x.reminder_minutes || [], x.created_at || null, x.updated_at || null, x.deleted_at || null, x.purge_at || null]
);
}
for (const x of (ndata.achievement_types || [])) {