diff --git a/backup-restore.js b/backup-restore.js index 314d44f..f398280 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -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) || '', diff --git a/backup.selftest.js b/backup.selftest.js index d1a5782..9f18cc9 100644 --- a/backup.selftest.js +++ b/backup.selftest.js @@ -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'); diff --git a/db/init.sql b/db/init.sql index a4d0d90..1050478 100644 --- a/db/init.sql +++ b/db/init.sql @@ -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; diff --git a/db/migration.sql b/db/migration.sql index 515ded5..8ec4a83 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -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; diff --git a/lib/calendar.js b/lib/calendar.js index b871425..e8c91ce 100644 --- a/lib/calendar.js +++ b/lib/calendar.js @@ -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, diff --git a/public/calendar.html b/public/calendar.html index eeaffec..aab0338 100644 --- a/public/calendar.html +++ b/public/calendar.html @@ -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 @@