Календарь: история действий с отменой для админа
This commit is contained in:
@@ -442,9 +442,10 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
|
||||
- **Конвенция `all_day`** — локальная полночь дня начала → локальные `23:59` того же дня; на клиенте `dtInputToIso('<date>T00:00')` / `dtInputToIso('<date>T23:59')`; в сетке такие события идут в строку «Весь день», а не в часовую сетку. Событие через полночь режется по дням (`↔` в плашке), а не рисуется за пределами колонки
|
||||
- **Повторение** — `none|daily|weekly|monthly|yearly` + опциональный `repeat_until DATE`. Разворачивание серии — **на сервере** в `listCalendarEvents()` SQL через `generate_series` + `LATERAL`; генерация начинается от локального начала серии (`starts_at AT TIME ZONE $TZ$`), а не от начала окна, иначе съедет фаза недельных/месячных повторов. Границы окна для `TIMESTAMPTZ` — только `$TZ$` + `bindTz`, зона приходит из `appTimezone()`. Редактирование/удаление меняет всю серию (исключений в MVP нет); клиент при редактировании должен подставлять `starts_at`/`ends_at` серии, а не дату конкретного вхождения. Месячное повторение 31-го числа в коротких месяцах прыгает по правилам Postgres — допустимо
|
||||
- **Read-only источники «Из системы»** — `groups` (занятия по `day_of_week`/`time_start`/`time_end`), `lesson_reports` (DATE + TIME), `digests` (опубликованные, не скрытые `hide_at`). Список приходит в `{ sources }` того же `GET /api/calendar/events`, цвета `green`/`purple`/`orange`, клик ведёт в `groups.html` / `lessons.html` / `digest.html`, а не в редактор. Не-admin фильтруется `branchScope` (пустой список филиалов → `1 = 0`); digests видны всем авторизованным. Чекбоксы источников и личного календаря хранятся в `localStorage.calSources` как список **скрытых** id (включая `personal`); вид и якорь — `calView`/`calAnchor`
|
||||
- **REST вместо SSE** — `/api/events` уже занят SSE, календарные роуты только `/api/calendar/events*` (`apiLimiter` только на GET). Нового SSE-канала и Redis-кэша нет: данных мало, а инвалидация на каждую мутацию — лишний риск и лишнее соединение в бюджете HTTP/1.1. Все даты/время на клиенте — только хелперы `public/js/datetime.js`: `todayIso`, `isoAddDays`, `isoDow`, `fmtHmStr`, `fmtDateOnlyLongIso`, `fmtDayMonthIso`, `fmtMonthYearIso`, `dtToLocalInput`, `dtInputToIso`. Прямых `toLocale*`/`new Date('YYYY-MM-DD')` в `calendar.js` быть не должно; «сейчас» и красная линия — по зоне приложения (`nowHm()`), обновляются раз в минуту
|
||||
- **REST вместо SSE** — `/api/events` уже занят SSE, календарные роуты только `/api/calendar/events*` и admin-роуты `/api/calendar/history*` (`apiLimiter` только на GET). Нового SSE-канала и Redis-кэша нет: данных мало, а инвалидация на каждую мутацию — лишний риск и лишнее соединение в бюджете HTTP/1.1. Все даты/время на клиенте — только хелперы `public/js/datetime.js`: `todayIso`, `isoAddDays`, `isoDow`, `fmtHmStr`, `fmtDateOnlyLongIso`, `fmtDayMonthIso`, `fmtMonthYearIso`, `dtToLocalInput`, `dtInputToIso`. Прямых `toLocale*`/`new Date('YYYY-MM-DD')` в `calendar.js` быть не должно; «сейчас» и красная линия — по зоне приложения (`nowHm()`), обновляются раз в минуту
|
||||
- **Бэкап** — `calendar_events` в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, выгружается в `buildBackupArchive`, нормализуется в `backup-restore.js` (цвет/повтор/напоминания по allowlist, `deleted_at`/`purge_at` сохраняются), в restore удаляется до `DELETE FROM users` и вставляется после пользователей с проверкой владельца; проверка — `backup.selftest.js`
|
||||
- **Напоминания** — `reminder_minutes` (0/5/10/15/30/60/120/1440, максимум 5) доставляются воркером `createCalendarReminderWorker` из `lib/calendar.js`: тик раз в 60 с, окно 24 ч назад, зона через `bindTz`/`appTimezone()`. Дедупликация — таблица `calendar_reminder_sent(event_id, user_id, occurrence_at, minutes)`, строки старше 7 суток чистятся; при ошибке доставки запись удаляется, чтобы тик мог повторить. Удалённые события и прошедшие вхождения не отправляются. Уведомление персональное (`userId` владельца, иконка `bell-ring`, `link: 'calendar.html'`), идёт через общий SSE уведомлений; новый SSE-канал и Redis-кэш не заводятся. Производная таблица `calendar_reminder_sent` в бэкап не входит
|
||||
- **История действий** — таблица `calendar_action_log` (`event_ids INT[]`, `user_id` с `ON DELETE SET NULL` + снимок `user_name`, `action`, `before_state`/`after_state` JSONB со снимками событий, `created_at`). Логируются действия **всех** пользователей, но читать историю и отменять может только админ: `GET /api/calendar/history?limit=&offset=&user_id=`, `GET /api/calendar/history/:id`, `POST /api/calendar/history/:id/undo` — все под `requireAdmin`. Типы: `created|updated|deleted|restored|permanent_deleted|undone`; запись пишется внутри `lib/calendar.js` в тех же транзакциях, что и мутация (актор передаётся из роута как `actor: req.user`), одна строка на HTTP-действие (создание для нескольких пользователей — одна запись с несколькими снимками). Отмена любой записи — `undoCalendarAction()`: состояние приводится к `before_state` (создание → мягкое удаление, удаление → restore, физическое удаление → вставка строки с тем же id и `setval`), сама отмена тоже пишется как `undone`. Панель в `.cal-side` видна только админу, показывает 10 последних действий, подсказка справа, «Вся история» — модалка с постраничной загрузкой и фильтром по автору, клик по строке — модалка «Было/Стало» с кнопкой отмены. DDL — в `db/init.sql`, `db/migration.sql` и `ensureCalendarEventsTable()`; таблица входит в бэкап/restore и проверяется в `backup.selftest.js`
|
||||
|
||||
### 4. API Patterns
|
||||
- **Middleware**: `requireAuth` — читает `X-Auth-Token`, 401 без валидной активной сессии. `requireAdmin` — самодостаточный (внутри вызывает `requireAuth`, если `req.user` ещё нет), 403 при `role !== 'admin'`. `optionalAuth` — для публичных страниц с персонализацией
|
||||
|
||||
+38
-3
@@ -23,14 +23,14 @@ const BACKUP_TABLES = [
|
||||
'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications',
|
||||
'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments',
|
||||
'short_messages', 'feedbacks', 'feedback_versions', 'bookmarks', 'student_face_refs', 'photo_faces',
|
||||
'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', 'digests', 'digest_images', 'farewell_messages', 'calendar_events',
|
||||
'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', 'digests', 'digest_images', 'farewell_messages', 'calendar_events', 'calendar_action_log',
|
||||
];
|
||||
const BACKUP_SEQUENCE_TABLES = [
|
||||
'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos',
|
||||
'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports',
|
||||
'lesson_report_versions', 'feedback_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages',
|
||||
'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces',
|
||||
'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', 'digests', 'digest_images', 'farewell_messages', 'calendar_events',
|
||||
'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', 'digests', 'digest_images', 'farewell_messages', 'calendar_events', 'calendar_action_log',
|
||||
];
|
||||
|
||||
function isSupportedBackupVersion(data) {
|
||||
@@ -777,6 +777,41 @@ function normalizeRestoreData(data) {
|
||||
deleted_at: optTs(x.deleted_at),
|
||||
purge_at: optTs(x.purge_at),
|
||||
})).filter(x => x.starts_at && x.ends_at);
|
||||
const calendarHistoryActions = ['created', 'updated', 'deleted', 'restored', 'permanent_deleted', 'undone'];
|
||||
const calendarSnapshotRestore = value => (Array.isArray(value) ? value : [])
|
||||
.filter(e => e && typeof e === 'object' && !Array.isArray(e)).slice(0, 60).map(e => ({
|
||||
id: reqInt(e.id),
|
||||
user_id: optInt(e.user_id, 1, Number.MAX_SAFE_INTEGER),
|
||||
user_name: optText(e.user_name, 200),
|
||||
is_common: e.is_common === true,
|
||||
title: optText(e.title, 200),
|
||||
notes: optText(e.notes, 5000),
|
||||
location: optText(e.location, 200),
|
||||
color: calendarColors.includes(e.color) ? e.color : 'blue',
|
||||
starts_at: optTs(e.starts_at),
|
||||
ends_at: optTs(e.ends_at),
|
||||
all_day: e.all_day === true,
|
||||
repeat_rule: calendarRepeat.includes(e.repeat_rule) ? e.repeat_rule : 'none',
|
||||
repeat_until: optDate(e.repeat_until),
|
||||
reminder_minutes: Array.isArray(e.reminder_minutes)
|
||||
? [...new Set(e.reminder_minutes.map(Number).filter(n => calendarReminders.includes(n)))].sort((a, b) => a - b).slice(0, 5)
|
||||
: [],
|
||||
deleted_at: optTs(e.deleted_at),
|
||||
purge_at: optTs(e.purge_at),
|
||||
created_at: optTs(e.created_at),
|
||||
updated_at: optTs(e.updated_at),
|
||||
})).filter(x => x.starts_at && x.ends_at);
|
||||
const calendarActionLog = (data.calendar_action_log || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
event_ids: Array.isArray(x.event_ids) ? x.event_ids.map(Number).filter(n => Number.isInteger(n) && n > 0).slice(0, 60) : [],
|
||||
user_id: optInt(x.user_id, 1, Number.MAX_SAFE_INTEGER),
|
||||
user_name: optText(x.user_name, 200),
|
||||
action: calendarHistoryActions.includes(x.action) ? x.action : 'updated',
|
||||
title: optText(x.title, 500),
|
||||
before_state: calendarSnapshotRestore(x.before_state),
|
||||
after_state: calendarSnapshotRestore(x.after_state),
|
||||
created_at: optTs(x.created_at),
|
||||
})).filter(x => x.id > 0 && x.before_state.length + x.after_state.length > 0);
|
||||
const sidebarItems = (data.sidebar_items || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
kind: ['item','divider','group'].includes(x.kind) ? x.kind : 'item',
|
||||
@@ -813,7 +848,7 @@ function normalizeRestoreData(data) {
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
})).filter(x => x.source_id && x.photo_path);
|
||||
return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, farewell_messages, bookmarks, calendar_events: calendarEvents, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages, doc_files: docFiles, sidebar_items: sidebarItems, digests, digest_images: digestImages };
|
||||
return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, farewell_messages, bookmarks, calendar_events: calendarEvents, calendar_action_log: calendarActionLog, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages, doc_files: docFiles, sidebar_items: sidebarItems, digests, digest_images: digestImages };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -301,5 +301,24 @@ ok('calendar_events нормализуются: цвет/повтор/напом
|
||||
calRestore.calendar_events[0].is_common === true,
|
||||
calRestore.calendar_events);
|
||||
|
||||
ok('calendar_action_log входит в бэкап и sequences', BACKUP_TABLES.includes('calendar_action_log') && BACKUP_SEQUENCE_TABLES.includes('calendar_action_log'));
|
||||
const calLogRestore = normalizeRestoreData({
|
||||
...base,
|
||||
calendar_action_log: [
|
||||
{ id: 1, event_ids: [1], user_id: 1, user_name: 'Админ', action: 'created', title: 'Созвон', before_state: [], after_state: [{ id: 1, user_id: 1, title: 'Созвон', color: 'nope', starts_at: '2026-11-24T07:30:00.000Z', ends_at: '2026-11-24T08:30:00.000Z', repeat_rule: 'weekly', reminder_minutes: [10, 999], created_at: '2026-11-24T07:00:00.000Z', updated_at: '2026-11-24T07:05:00.000Z' }], created_at: '2026-11-24T07:30:00.000Z' },
|
||||
{ id: 2, event_ids: [2], action: 'bogus', before_state: [], after_state: [] },
|
||||
{ id: 3, event_ids: [], before_state: [], after_state: [] },
|
||||
],
|
||||
});
|
||||
ok('calendar_action_log нормализуется: action/snapshot/actor',
|
||||
calLogRestore.calendar_action_log.length === 1 &&
|
||||
calLogRestore.calendar_action_log[0].action === 'created' &&
|
||||
calLogRestore.calendar_action_log[0].user_name === 'Админ' &&
|
||||
calLogRestore.calendar_action_log[0].after_state[0].color === 'blue' &&
|
||||
calLogRestore.calendar_action_log[0].after_state[0].reminder_minutes.join(',') === '10' &&
|
||||
calLogRestore.calendar_action_log[0].after_state[0].created_at === '2026-11-24T07:00:00.000Z' &&
|
||||
calLogRestore.calendar_action_log[0].after_state[0].updated_at === '2026-11-24T07:05:00.000Z',
|
||||
calLogRestore.calendar_action_log);
|
||||
|
||||
console.log(failed ? `\n${failed} проверок провалено` : '\nBACKUP SELFTEST OK');
|
||||
process.exit(failed ? 1 : 0);
|
||||
+14
@@ -896,3 +896,17 @@ CREATE TABLE IF NOT EXISTS calendar_reminder_sent (
|
||||
UNIQUE (event_id, user_id, occurrence_at, minutes)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_reminder_sent_sent_at ON calendar_reminder_sent(sent_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS calendar_action_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
event_ids INT[] NOT NULL DEFAULT '{}',
|
||||
user_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
user_name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
action VARCHAR(30) NOT NULL,
|
||||
title VARCHAR(500) NOT NULL DEFAULT '',
|
||||
before_state JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
after_state JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_created ON calendar_action_log(id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_user ON calendar_action_log(user_id, id DESC);
|
||||
|
||||
@@ -1186,3 +1186,17 @@ CREATE TABLE IF NOT EXISTS calendar_reminder_sent (
|
||||
UNIQUE (event_id, user_id, occurrence_at, minutes)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_reminder_sent_sent_at ON calendar_reminder_sent(sent_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS calendar_action_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
event_ids INT[] NOT NULL DEFAULT '{}',
|
||||
user_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
user_name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
action VARCHAR(30) NOT NULL,
|
||||
title VARCHAR(500) NOT NULL DEFAULT '',
|
||||
before_state JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
after_state JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_created ON calendar_action_log(id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_calendar_action_log_user ON calendar_action_log(user_id, id DESC);
|
||||
|
||||
+275
-49
@@ -31,6 +31,8 @@ const CALENDAR_SOURCE_META = {
|
||||
lesson_reports: { label: 'Отчёты о занятиях', color: 'purple', link: 'lessons.html' },
|
||||
digests: { label: 'Дайджест', color: 'orange', link: 'digest.html' },
|
||||
};
|
||||
const CALENDAR_HISTORY_ACTIONS = ['created', 'updated', 'deleted', 'restored', 'permanent_deleted', 'undone'];
|
||||
const CALENDAR_HISTORY_LIMIT = 100;
|
||||
|
||||
function calError(status, message) {
|
||||
const err = new Error(message);
|
||||
@@ -258,6 +260,208 @@ async function ensureCalendarEventsTable(pool) {
|
||||
UNIQUE (event_id, user_id, occurrence_at, minutes)
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_reminder_sent_sent_at ON calendar_reminder_sent(sent_at)');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS calendar_action_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
event_ids INT[] NOT NULL DEFAULT '{}',
|
||||
user_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
user_name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
action VARCHAR(30) NOT NULL,
|
||||
title VARCHAR(500) NOT NULL DEFAULT '',
|
||||
before_state JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
after_state JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_action_log_created ON calendar_action_log(id DESC)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_action_log_user ON calendar_action_log(user_id, id DESC)');
|
||||
}
|
||||
|
||||
function isoOrNull(value) {
|
||||
if (value == null || value === '') return null;
|
||||
const d = value instanceof Date ? value : new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
||||
}
|
||||
|
||||
function isoDateOrNull(value) {
|
||||
if (value == null || value === '') return null;
|
||||
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
||||
return String(value).slice(0, 10) || null;
|
||||
}
|
||||
|
||||
function calendarSnapshot(row) {
|
||||
if (!row) return null;
|
||||
return {
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
user_name: row.user_name || null,
|
||||
is_common: row.is_common === true,
|
||||
title: row.title || '',
|
||||
notes: row.notes || '',
|
||||
location: row.location || '',
|
||||
color: row.color || 'blue',
|
||||
starts_at: isoOrNull(row.starts_at),
|
||||
ends_at: isoOrNull(row.ends_at),
|
||||
all_day: row.all_day === true,
|
||||
repeat_rule: row.repeat_rule || 'none',
|
||||
repeat_until: isoDateOrNull(row.repeat_until),
|
||||
reminder_minutes: Array.isArray(row.reminder_minutes) ? row.reminder_minutes.map(Number) : [],
|
||||
deleted_at: isoOrNull(row.deleted_at),
|
||||
purge_at: isoOrNull(row.purge_at),
|
||||
created_at: isoOrNull(row.created_at),
|
||||
updated_at: isoOrNull(row.updated_at),
|
||||
};
|
||||
}
|
||||
|
||||
async function recordCalendarAction(db, { action, actor, before, after }) {
|
||||
if (!CALENDAR_HISTORY_ACTIONS.includes(action) || !actor) return null;
|
||||
const beforeRows = (Array.isArray(before) ? before : []).map(calendarSnapshot).filter(Boolean);
|
||||
const afterRows = (Array.isArray(after) ? after : []).map(calendarSnapshot).filter(Boolean);
|
||||
if (!beforeRows.length && !afterRows.length) return null;
|
||||
const eventIds = [...new Set([...beforeRows, ...afterRows].map(x => x.id).filter(Number.isInteger))];
|
||||
const title = (afterRows[0] || beforeRows[0] || {}).title || '';
|
||||
const { rows } = await db.query(
|
||||
`INSERT INTO calendar_action_log (event_ids, user_id, user_name, action, title, before_state, after_state)
|
||||
VALUES ($1::int[], $2, $3, $4, $5, $6::jsonb, $7::jsonb)
|
||||
RETURNING id, created_at`,
|
||||
[eventIds, Number(actor.id) || null, String(actor.name || actor.username || '').slice(0, 200), action, title.slice(0, 500), JSON.stringify(beforeRows), JSON.stringify(afterRows)]
|
||||
);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
async function withCalendarTransaction(pool, fn) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await fn(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHistorySnapshot(snap) {
|
||||
const id = Number(snap && snap.id);
|
||||
const userId = Number(snap && snap.user_id);
|
||||
const startsAt = isoOrNull(snap && snap.starts_at);
|
||||
const endsAt = isoOrNull(snap && snap.ends_at);
|
||||
if (!Number.isInteger(id) || id < 1 || !Number.isInteger(userId) || userId < 1 ||
|
||||
!startsAt || !endsAt || Date.parse(endsAt) <= Date.parse(startsAt)) {
|
||||
throw calError(409, 'Снимок события повреждён — отмена недоступна');
|
||||
}
|
||||
const reminders = Array.isArray(snap.reminder_minutes)
|
||||
? [...new Set(snap.reminder_minutes.map(Number).filter(n => CALENDAR_REMINDERS.includes(n)))].slice(0, CALENDAR_REMINDERS_MAX)
|
||||
: [];
|
||||
return {
|
||||
id,
|
||||
user_id: userId,
|
||||
is_common: snap.is_common === true,
|
||||
title: String(snap.title || '').slice(0, CALENDAR_TITLE_MAX),
|
||||
notes: String(snap.notes || '').slice(0, CALENDAR_NOTES_MAX),
|
||||
location: String(snap.location || '').slice(0, CALENDAR_LOCATION_MAX),
|
||||
color: CALENDAR_COLORS.includes(snap.color) ? snap.color : 'blue',
|
||||
starts_at: startsAt,
|
||||
ends_at: endsAt,
|
||||
all_day: snap.all_day === true,
|
||||
repeat_rule: CALENDAR_REPEAT.includes(snap.repeat_rule) ? snap.repeat_rule : 'none',
|
||||
repeat_until: isIsoDate(snap.repeat_until) ? snap.repeat_until : null,
|
||||
reminder_minutes: reminders,
|
||||
deleted_at: isoOrNull(snap.deleted_at),
|
||||
purge_at: isoOrNull(snap.purge_at),
|
||||
created_at: isoOrNull(snap.created_at),
|
||||
updated_at: isoOrNull(snap.updated_at),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadCalendarEventForActor(db, { userId, isAdmin, id }) {
|
||||
const params = [id];
|
||||
const where = 'id = $1' + eventOwnerClause(params, { userId, isAdmin });
|
||||
const { rows } = await db.query(`SELECT * FROM calendar_events WHERE ${where}`, params);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function listCalendarActions(pool, { limit, offset, userId }) {
|
||||
const take = Math.min(Math.max(Number.isInteger(limit) ? limit : 10, 1), CALENDAR_HISTORY_LIMIT);
|
||||
const skip = Math.max(Number.isInteger(offset) ? offset : 0, 0);
|
||||
const params = [take, skip];
|
||||
let where = '';
|
||||
if (userId) {
|
||||
params.push(userId);
|
||||
where = `WHERE user_id = $${params.length}`;
|
||||
}
|
||||
const [rows, total] = await Promise.all([
|
||||
pool.query(`SELECT id, event_ids, user_id, user_name, action, title, before_state, after_state, created_at
|
||||
FROM calendar_action_log ${where} ORDER BY id DESC LIMIT $1 OFFSET $2`, params),
|
||||
pool.query(`SELECT count(*)::int AS total FROM calendar_action_log ${where}`, userId ? [userId] : []),
|
||||
]);
|
||||
return { items: rows.rows, total: total.rows[0] ? total.rows[0].total : 0 };
|
||||
}
|
||||
|
||||
async function getCalendarAction(pool, id) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, event_ids, user_id, user_name, action, title, before_state, after_state, created_at
|
||||
FROM calendar_action_log WHERE id = $1`, [id]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function undoCalendarAction(pool, { id, purgeDays, actor }) {
|
||||
const log = await getCalendarAction(pool, id);
|
||||
if (!log) throw calError(404, 'Запись истории не найдена');
|
||||
const before = (Array.isArray(log.before_state) ? log.before_state : []).filter(x => x && x.id).map(normalizeHistorySnapshot);
|
||||
const after = (Array.isArray(log.after_state) ? log.after_state : []).filter(x => x && x.id).map(normalizeHistorySnapshot);
|
||||
if (!before.length && !after.length) throw calError(409, 'Отмена недоступна для этого действия');
|
||||
const beforeMap = new Map(before.map(x => [x.id, x]));
|
||||
const hardRemove = log.action === 'undone' && !before.length && after.length > 0;
|
||||
const days = Number.isInteger(purgeDays) && purgeDays >= 1 ? purgeDays : 30;
|
||||
return withCalendarTransaction(pool, async client => {
|
||||
for (const snap of after) {
|
||||
if (beforeMap.has(snap.id)) continue;
|
||||
if (hardRemove) {
|
||||
await client.query('DELETE FROM calendar_events WHERE id = $1', [snap.id]);
|
||||
continue;
|
||||
}
|
||||
const { rowCount } = await client.query(
|
||||
`UPDATE calendar_events
|
||||
SET deleted_at = now(), purge_at = now() + make_interval(days => $2::int), updated_at = now()
|
||||
WHERE id = $1 AND deleted_at IS NULL`, [snap.id, days]
|
||||
);
|
||||
if (!rowCount) throw calError(409, 'Состояние календаря изменилось, отмена недоступна');
|
||||
}
|
||||
for (const snap of beforeMap.values()) {
|
||||
const okUser = await client.query('SELECT 1 FROM users WHERE id = $1', [snap.user_id]);
|
||||
if (!okUser.rowCount) throw calError(409, 'Пользователь события удалён — отмена недоступна');
|
||||
const values = [
|
||||
snap.user_id, snap.is_common, snap.title, snap.notes, snap.location,
|
||||
snap.color, snap.starts_at, snap.ends_at, snap.all_day,
|
||||
snap.repeat_rule, snap.repeat_until, snap.reminder_minutes,
|
||||
snap.deleted_at, snap.purge_at, snap.created_at || new Date().toISOString(),
|
||||
snap.updated_at || new Date().toISOString(), snap.id,
|
||||
];
|
||||
const exists = await client.query('SELECT 1 FROM calendar_events WHERE id = $1', [snap.id]);
|
||||
if (exists.rowCount) {
|
||||
const { rowCount } = await client.query(
|
||||
`UPDATE calendar_events SET user_id=$1, is_common=$2, 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,
|
||||
deleted_at=$13, purge_at=$14, created_at=$15, updated_at=$16 WHERE id=$17`, values
|
||||
);
|
||||
if (!rowCount) throw calError(409, 'Состояние календаря изменилось, отмена недоступна');
|
||||
} else {
|
||||
await client.query(
|
||||
`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, deleted_at, purge_at, created_at, updated_at)
|
||||
VALUES ($17,$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)`, values
|
||||
);
|
||||
await client.query(`SELECT setval(pg_get_serial_sequence('calendar_events', 'id'), GREATEST((SELECT MAX(id) FROM calendar_events), 1))`);
|
||||
}
|
||||
}
|
||||
await recordCalendarAction(client, {
|
||||
action: 'undone', actor, before: log.after_state, after: log.before_state,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
async function listCalendarEvents(pool, { userId, isAdmin, targetUser, fromIso, toIso, tz }) {
|
||||
@@ -333,7 +537,7 @@ function eventOwnerClause(params, { userId, isAdmin }) {
|
||||
return clause;
|
||||
}
|
||||
|
||||
async function createCalendarEvents(pool, { userId, audience, data, tz }) {
|
||||
async function createCalendarEvents(pool, { userId, actor, audience, data, tz }) {
|
||||
const f = validateCalendarEvent({ ...data, is_common: audience.isCommon }, tz);
|
||||
const owners = audience.isCommon || !audience.users.length
|
||||
? [userId]
|
||||
@@ -352,6 +556,7 @@ async function createCalendarEvents(pool, { userId, audience, data, tz }) {
|
||||
);
|
||||
items.push(rows[0]);
|
||||
}
|
||||
await recordCalendarAction(client, { action: 'created', actor, before: [], after: items });
|
||||
await client.query('COMMIT');
|
||||
return items;
|
||||
} catch (e) {
|
||||
@@ -362,62 +567,80 @@ async function createCalendarEvents(pool, { userId, audience, data, tz }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function updateCalendarEvent(pool, { userId, audience, id, data, tz }) {
|
||||
async function updateCalendarEvent(pool, { userId, actor, 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 ${sets.join(', ')}, updated_at = now() WHERE ${where} RETURNING *`,
|
||||
params
|
||||
);
|
||||
if (!rows.length) throw calError(404, 'Событие не найдено');
|
||||
return rows[0];
|
||||
return withCalendarTransaction(pool, async client => {
|
||||
const before = await loadCalendarEventForActor(client, { userId, isAdmin: audience.isAdmin, id });
|
||||
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 client.query(
|
||||
`UPDATE calendar_events SET ${sets.join(', ')}, updated_at = now() WHERE ${where} RETURNING *`,
|
||||
params
|
||||
);
|
||||
if (!rows.length) throw calError(404, 'Событие не найдено');
|
||||
await recordCalendarAction(client, { action: 'updated', actor, before: [before], after: rows[0] });
|
||||
return rows[0];
|
||||
});
|
||||
}
|
||||
|
||||
async function softDeleteCalendarEvent(pool, { userId, isAdmin, id, purgeDays }) {
|
||||
async function softDeleteCalendarEvent(pool, { userId, actor, 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 => $${dayIdx}::int), updated_at = now()
|
||||
WHERE ${where}`,
|
||||
params
|
||||
);
|
||||
if (!rowCount) throw calError(404, 'Событие не найдено или уже удалено');
|
||||
return true;
|
||||
return withCalendarTransaction(pool, async client => {
|
||||
const before = await loadCalendarEventForActor(client, { userId, isAdmin, id });
|
||||
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 client.query(
|
||||
`UPDATE calendar_events
|
||||
SET deleted_at = now(), purge_at = now() + make_interval(days => $${dayIdx}::int), updated_at = now()
|
||||
WHERE ${where}`,
|
||||
params
|
||||
);
|
||||
if (!rowCount) throw calError(404, 'Событие не найдено или уже удалено');
|
||||
const after = await loadCalendarEventForActor(client, { userId, isAdmin, id });
|
||||
await recordCalendarAction(client, { action: 'deleted', actor, before: [before], after: [after] });
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
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 ${where}`,
|
||||
params
|
||||
);
|
||||
if (!rowCount) throw calError(404, 'Событие не найдено или не удалено');
|
||||
return true;
|
||||
async function restoreCalendarEvent(pool, { userId, actor, isAdmin, id }) {
|
||||
return withCalendarTransaction(pool, async client => {
|
||||
const before = await loadCalendarEventForActor(client, { userId, isAdmin, id });
|
||||
const params = [id];
|
||||
const where = `id = $1 AND deleted_at IS NOT NULL` + eventOwnerClause(params, { userId, isAdmin });
|
||||
const { rowCount } = await client.query(
|
||||
`UPDATE calendar_events SET deleted_at = NULL, purge_at = NULL, updated_at = now() WHERE ${where}`,
|
||||
params
|
||||
);
|
||||
if (!rowCount) throw calError(404, 'Событие не найдено или не удалено');
|
||||
const after = await loadCalendarEventForActor(client, { userId, isAdmin, id });
|
||||
await recordCalendarAction(client, { action: 'restored', actor, before: [before], after: [after] });
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
async function deleteCalendarEventPermanent(pool, { userId, actor, isAdmin, id }) {
|
||||
return withCalendarTransaction(pool, async client => {
|
||||
const before = await loadCalendarEventForActor(client, { userId, isAdmin, id });
|
||||
const params = [id];
|
||||
const where = `id = $1 AND deleted_at IS NOT NULL` + eventOwnerClause(params, { userId, isAdmin });
|
||||
const { rowCount } = await client.query(`DELETE FROM calendar_events WHERE ${where}`, params);
|
||||
if (!rowCount) throw calError(404, 'Событие не найдено');
|
||||
await recordCalendarAction(client, { action: 'permanent_deleted', actor, before: [before], after: [] });
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function branchClause(expr, admin, branchIds, params) {
|
||||
@@ -686,5 +909,8 @@ module.exports = {
|
||||
softDeleteCalendarEvent,
|
||||
restoreCalendarEvent,
|
||||
deleteCalendarEventPermanent,
|
||||
listCalendarActions,
|
||||
getCalendarAction,
|
||||
undoCalendarAction,
|
||||
listWorkspaceSources,
|
||||
};
|
||||
|
||||
@@ -128,6 +128,26 @@
|
||||
.cal-modal-foot{display:flex;align-items:center;gap:8px;margin-top:4px}
|
||||
.cal-modal-foot .btn-primary:last-child{margin-left:auto}
|
||||
.cal-danger{color:#dc2626;border:1px solid #fecaca;background:var(--card);border-radius:9px;padding:9px 13px;font-size:.8rem;font-weight:600;cursor:pointer}
|
||||
.cal-hist-list{display:flex;flex-direction:column;gap:3px}
|
||||
.cal-hist-row{padding:6px 7px;border:1px solid transparent;border-radius:8px;cursor:pointer;display:flex;flex-direction:column;gap:2px}
|
||||
.cal-hist-row:hover{background:var(--bg);border-color:var(--border)}
|
||||
.cal-hist-time{font-size:.68rem;color:var(--muted);font-variant-numeric:tabular-nums}
|
||||
.cal-hist-text{font-size:.78rem;line-height:1.3;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.cal-hist-more{border:none;background:transparent;color:var(--accent);font-size:.75rem;font-weight:600;cursor:pointer;padding:6px 2px;text-align:left}
|
||||
.cal-hist-empty{font-size:.75rem;color:var(--muted)}
|
||||
.cal-hist-tooltip{position:fixed;z-index:10000;max-width:320px;background:var(--card);border:1px solid var(--border);border-radius:9px;box-shadow:0 8px 24px rgba(0,0,0,.18);padding:8px 10px;font-size:.76rem;line-height:1.45;pointer-events:none}
|
||||
.cal-hist-modal{max-width:720px;max-height:min(82vh,760px);overflow:auto;gap:12px;padding:20px}
|
||||
.cal-hist-filters{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
|
||||
.cal-hist-filters select{width:auto;max-width:230px}
|
||||
.cal-hist-full{display:flex;flex-direction:column;gap:4px}
|
||||
.cal-hist-item{padding:8px 10px;border:1px solid var(--border);border-radius:9px;cursor:pointer}
|
||||
.cal-hist-item:hover{border-color:var(--accent);background:var(--bg)}
|
||||
.cal-hist-item-head{display:flex;justify-content:space-between;gap:10px;font-size:.8rem;font-weight:600}
|
||||
.cal-hist-item-meta{font-size:.72rem;color:var(--muted);margin-top:2px}
|
||||
.cal-hist-diff{width:100%;border-collapse:collapse;font-size:.8rem}
|
||||
.cal-hist-diff th,.cal-hist-diff td{border:1px solid var(--border);padding:6px 9px;text-align:left;vertical-align:top;word-break:break-word}
|
||||
.cal-hist-diff th{width:130px;color:var(--muted);font-weight:600;background:var(--bg)}
|
||||
.cal-hist-diff .changed td{background:rgba(37,99,235,.07)}
|
||||
.cal-hidden{display:none!important}
|
||||
@media(max-width:900px){
|
||||
.cal-main{padding:10px}
|
||||
@@ -156,6 +176,11 @@
|
||||
<h4>Из системы</h4>
|
||||
<div id="calSources"></div>
|
||||
</div>
|
||||
<div class="cal-side-block cal-hist-block cal-hidden" id="calHistoryBlock">
|
||||
<h4>Действия</h4>
|
||||
<div class="cal-hist-list" id="calHistoryList"></div>
|
||||
<button class="cal-hist-more" id="calHistoryAllBtn" type="button">Вся история →</button>
|
||||
</div>
|
||||
<div class="cal-side-foot">Напоминания приходят в уведомления в выбранное время до события.</div>
|
||||
</aside>
|
||||
<section class="cal-view">
|
||||
@@ -263,6 +288,37 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="calHistoryModal">
|
||||
<div class="edit-modal cal-hist-modal" role="dialog" aria-modal="true" aria-label="История действий календаря">
|
||||
<div class="cal-modal-head">
|
||||
<h3>История действий</h3>
|
||||
<button class="icon-btn" id="calHistoryCloseBtn" type="button" aria-label="Закрыть"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<div class="cal-hist-filters">
|
||||
<select class="settings-input" id="calHistoryUser" aria-label="Пользователь"><option value="">Все пользователи</option></select>
|
||||
<span class="cal-hist-empty" id="calHistoryTotal"></span>
|
||||
</div>
|
||||
<div class="cal-hist-full" id="calHistoryFull"></div>
|
||||
<button class="cal-hist-more" id="calHistoryMoreBtn" type="button">Показать ещё</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="calActionModal">
|
||||
<div class="edit-modal cal-hist-modal" role="dialog" aria-modal="true" aria-label="Действие в календаре">
|
||||
<div class="cal-modal-head">
|
||||
<h3 id="calActionTitle">Действие</h3>
|
||||
<button class="icon-btn" id="calActionCloseBtn" type="button" aria-label="Закрыть"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<div class="cal-hist-empty" id="calActionMeta"></div>
|
||||
<div id="calActionDiff"></div>
|
||||
<div class="cal-modal-foot">
|
||||
<button class="btn-primary ghost" id="calActionCancelBtn" type="button">Закрыть</button>
|
||||
<button class="cal-danger" id="calActionUndoBtn" type="button">Отменить действие</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cal-hist-tooltip cal-hidden" id="calHistTip"></div>
|
||||
<div class="toast" id="toast"></div>
|
||||
<script src="vendor/lucide.min.js"></script>
|
||||
<script src="js/datetime.js"></script>
|
||||
|
||||
@@ -27,6 +27,17 @@
|
||||
rangeFrom: '', rangeTo: '', grid: null, uidMap: new Map(), editor: null,
|
||||
users: [], ownerFilter: '',
|
||||
};
|
||||
const HISTORY_LABELS = {
|
||||
created: 'Добавлено событие', updated: 'Изменено событие', deleted: 'Удалено событие',
|
||||
restored: 'Восстановлено событие', permanent_deleted: 'Удалено навсегда', undone: 'Отменено действие',
|
||||
};
|
||||
const HISTORY_FIELDS = [
|
||||
['title', 'Заголовок'], ['user_name', 'Владелец'], ['is_common', 'Общее событие'],
|
||||
['starts_at', 'Начало'], ['ends_at', 'Окончание'], ['all_day', 'Весь день'],
|
||||
['repeat_rule', 'Повтор'], ['repeat_until', 'Повтор до'], ['location', 'Место'],
|
||||
['notes', 'Заметки'], ['reminder_minutes', 'Напоминания'], ['deleted_at', 'Состояние'],
|
||||
];
|
||||
const historyState = { side: [], total: 0, full: [], fullTotal: 0, fullOffset: 0, userId: '', detailId: null, detailCount: 0, fullLoading: false, fullSeq: 0 };
|
||||
let calWeekStart = CAL_WEEK_START_DEFAULT;
|
||||
let calDayStart = CAL_DAY_START_DEFAULT;
|
||||
let calDayEnd = CAL_DAY_END_DEFAULT;
|
||||
@@ -832,6 +843,7 @@
|
||||
saveState();
|
||||
renderUserFilter();
|
||||
}
|
||||
await refreshHistory();
|
||||
await reload();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
@@ -844,6 +856,7 @@
|
||||
await request(`/api/calendar/events/${state.editor.id}`, { method: 'DELETE' });
|
||||
closeEditor();
|
||||
showToast('Событие удалено');
|
||||
await refreshHistory();
|
||||
await reload();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
@@ -890,7 +903,288 @@
|
||||
reload();
|
||||
}
|
||||
|
||||
function historyAuthor(item) {
|
||||
if (item.user_name) return item.user_name;
|
||||
const found = state.users.find(u => Number(u.id) === Number(item.user_id));
|
||||
return found ? userLabel(found) : (item.user_id ? `#${item.user_id}` : 'Система');
|
||||
}
|
||||
|
||||
function historyLabel(item) {
|
||||
return HISTORY_LABELS[item.action] || 'Изменение события';
|
||||
}
|
||||
|
||||
function historyLine(item) {
|
||||
return `${historyLabel(item)}: ${item.title || 'без названия'}`;
|
||||
}
|
||||
|
||||
function historyTooltip(item) {
|
||||
return `${historyAuthor(item)} — ${historyLine(item)} — ${fmtDateTime(item.created_at)}`;
|
||||
}
|
||||
|
||||
function renderHistorySide() {
|
||||
const block = document.getElementById('calHistoryBlock');
|
||||
if (!isAdmin()) { block.classList.add('cal-hidden'); return; }
|
||||
block.classList.remove('cal-hidden');
|
||||
hideHistoryTip();
|
||||
const list = document.getElementById('calHistoryList');
|
||||
if (!historyState.side.length) {
|
||||
list.innerHTML = '<div class="cal-hist-empty">Действий пока нет</div>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = historyState.side.slice(0, 10).map(item =>
|
||||
`<div class="cal-hist-row" data-log-id="${item.id}" data-tip="${attrEsc(historyTooltip(item))}">` +
|
||||
`<span class="cal-hist-time">${esc(fmtDateTime(item.created_at))}</span>` +
|
||||
`<span class="cal-hist-text">${esc(historyLine(item))}</span></div>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
async function loadHistorySide() {
|
||||
if (!isAdmin()) return;
|
||||
document.getElementById('calHistoryBlock').classList.remove('cal-hidden');
|
||||
try {
|
||||
const data = await request('/api/calendar/history?limit=10');
|
||||
historyState.side = Array.isArray(data.items) ? data.items : [];
|
||||
historyState.total = Number(data.total) || 0;
|
||||
renderHistorySide();
|
||||
} catch (e) {
|
||||
console.error('calendar history:', e);
|
||||
document.getElementById('calHistoryList').innerHTML = '<div class="cal-hist-empty">Не удалось загрузить историю</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function initHistoryUserFilter() {
|
||||
if (!isAdmin()) return;
|
||||
const select = document.getElementById('calHistoryUser');
|
||||
select.innerHTML = '<option value="">Все пользователи</option>' +
|
||||
state.users.map(u => `<option value="${attrEsc(u.id)}">${esc(userLabel(u))}</option>`).join('');
|
||||
select.value = historyState.userId && state.users.some(u => String(u.id) === historyState.userId)
|
||||
? historyState.userId : '';
|
||||
historyState.userId = select.value;
|
||||
}
|
||||
|
||||
function renderHistoryFull() {
|
||||
const box = document.getElementById('calHistoryFull');
|
||||
hideHistoryTip();
|
||||
if (!historyState.full.length) {
|
||||
box.innerHTML = `<div class="cal-hist-empty">${historyState.userId ? 'Ничего не найдено' : 'Действий пока нет'}</div>`;
|
||||
} else {
|
||||
box.innerHTML = historyState.full.map(item =>
|
||||
`<div class="cal-hist-item" data-log-id="${item.id}" data-tip="${attrEsc(historyTooltip(item))}">` +
|
||||
`<div class="cal-hist-item-head"><span>${esc(historyLine(item))}</span>` +
|
||||
`<span>${esc(fmtDateTime(item.created_at))}</span></div>` +
|
||||
`<div class="cal-hist-item-meta">${esc(historyAuthor(item))}</div></div>`
|
||||
).join('');
|
||||
}
|
||||
document.getElementById('calHistoryTotal').textContent = `Всего: ${historyState.fullTotal}`;
|
||||
document.getElementById('calHistoryMoreBtn').classList.toggle('cal-hidden', historyState.full.length >= historyState.fullTotal);
|
||||
}
|
||||
|
||||
async function loadHistoryFull(reset) {
|
||||
if (historyState.fullLoading && !reset) return;
|
||||
const seq = ++historyState.fullSeq;
|
||||
historyState.fullLoading = true;
|
||||
document.getElementById('calHistoryMoreBtn').disabled = true;
|
||||
if (reset) {
|
||||
historyState.fullOffset = 0;
|
||||
historyState.full = [];
|
||||
}
|
||||
const params = new URLSearchParams({ limit: '50', offset: String(historyState.fullOffset) });
|
||||
if (historyState.userId) params.set('user_id', historyState.userId);
|
||||
try {
|
||||
const data = await request(`/api/calendar/history?${params.toString()}`);
|
||||
if (seq !== historyState.fullSeq) return;
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
historyState.full = historyState.full.concat(items);
|
||||
historyState.fullTotal = Number(data.total) || 0;
|
||||
historyState.fullOffset = historyState.full.length;
|
||||
renderHistoryFull();
|
||||
} catch (e) {
|
||||
if (seq === historyState.fullSeq) showToast(e.message || 'Не удалось загрузить историю', true);
|
||||
} finally {
|
||||
if (seq === historyState.fullSeq) {
|
||||
historyState.fullLoading = false;
|
||||
document.getElementById('calHistoryMoreBtn').disabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function openHistoryModal() {
|
||||
if (!isAdmin()) return;
|
||||
document.getElementById('calHistoryModal').classList.add('open');
|
||||
renderIcons();
|
||||
await loadHistoryFull(true);
|
||||
}
|
||||
|
||||
function closeHistoryModal() {
|
||||
document.getElementById('calHistoryModal').classList.remove('open');
|
||||
hideHistoryTip();
|
||||
}
|
||||
|
||||
function closeActionModal() {
|
||||
document.getElementById('calActionModal').classList.remove('open');
|
||||
historyState.detailId = null;
|
||||
historyState.detailCount = 0;
|
||||
hideHistoryTip();
|
||||
}
|
||||
|
||||
function showHistoryTip(el) {
|
||||
const tip = document.getElementById('calHistTip');
|
||||
tip.textContent = el.dataset.tip || '';
|
||||
tip.classList.remove('cal-hidden');
|
||||
const box = el.getBoundingClientRect();
|
||||
const size = tip.getBoundingClientRect();
|
||||
let left = box.right + 10;
|
||||
if (left + size.width > window.innerWidth - 8) left = Math.max(8, box.left - size.width - 10);
|
||||
let top = box.top;
|
||||
if (top + size.height > window.innerHeight - 8) top = Math.max(8, window.innerHeight - size.height - 8);
|
||||
tip.style.left = `${left}px`;
|
||||
tip.style.top = `${top}px`;
|
||||
}
|
||||
|
||||
function hideHistoryTip() {
|
||||
document.getElementById('calHistTip').classList.add('cal-hidden');
|
||||
}
|
||||
|
||||
function historyReminders(value) {
|
||||
if (Array.isArray(value)) return value.map(Number).filter(n => Number.isInteger(n));
|
||||
if (typeof value === 'string') {
|
||||
const direct = Number(value);
|
||||
if (Number.isInteger(direct)) return [direct];
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
if (Array.isArray(parsed)) return parsed.map(Number).filter(n => Number.isInteger(n));
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return Number.isInteger(value) ? [value] : [];
|
||||
}
|
||||
|
||||
function historyFieldValue(snap, key) {
|
||||
if (!snap) return '—';
|
||||
if (key === 'starts_at' || key === 'ends_at') return snap[key] ? fmtDateTime(snap[key]) : '—';
|
||||
if (key === 'repeat_until') return snap.repeat_until ? fmtDateOnlyIso(snap.repeat_until) : '—';
|
||||
if (key === 'repeat_rule') return REPEAT_LABELS[snap.repeat_rule] || snap.repeat_rule || '—';
|
||||
if (key === 'is_common' || key === 'all_day') return snap[key] ? 'Да' : 'Нет';
|
||||
if (key === 'deleted_at') return snap.deleted_at ? 'Удалено' : 'Активно';
|
||||
if (key === 'reminder_minutes') {
|
||||
const values = historyReminders(snap.reminder_minutes);
|
||||
return values.length
|
||||
? values.map(n => n === 0 ? 'в момент события' : `за ${n} мин`).join(', ')
|
||||
: 'Нет';
|
||||
}
|
||||
if (key === 'user_name') {
|
||||
if (snap.user_name) return snap.user_name;
|
||||
const found = state.users.find(u => Number(u.id) === Number(snap.user_id));
|
||||
return found ? userLabel(found) : (snap.user_id ? `#${snap.user_id}` : '—');
|
||||
}
|
||||
return snap[key] ? String(snap[key]) : '—';
|
||||
}
|
||||
|
||||
function renderActionPair(before, after, terminal, index, total) {
|
||||
const snap = after || before || {};
|
||||
const rows = HISTORY_FIELDS.map(([key, label]) => {
|
||||
const was = historyFieldValue(before, key);
|
||||
const now = terminal ? (key === 'deleted_at' ? 'Удалено навсегда' : '—') : historyFieldValue(after, key);
|
||||
return `<tr class="${was === now ? '' : 'changed'}"><th>${esc(label)}</th><td>${esc(was)}</td><td>${esc(now)}</td></tr>`;
|
||||
}).join('');
|
||||
const heading = total > 1
|
||||
? `<div class="cal-hist-item-meta">Событие ${index + 1}: ${esc(snap.title || 'без названия')}</div>` : '';
|
||||
const status = terminal ? '<div class="cal-hist-item-meta">Событие удалено навсегда</div>' : '';
|
||||
return heading + status +
|
||||
`<table class="cal-hist-diff"><thead><tr><th></th><th>Было</th><th>Стало</th></tr></thead><tbody>${rows}</tbody></table>`;
|
||||
}
|
||||
|
||||
function renderActionDetail(item) {
|
||||
const beforeList = Array.isArray(item.before_state) ? item.before_state : [];
|
||||
const afterList = Array.isArray(item.after_state) ? item.after_state : [];
|
||||
const terminal = item.action === 'permanent_deleted' && !afterList.length;
|
||||
const pairs = terminal
|
||||
? beforeList.map(b => [b, null])
|
||||
: Array.from({ length: Math.max(beforeList.length, afterList.length) }, (_, i) => [beforeList[i] || null, afterList[i] || null]);
|
||||
document.getElementById('calActionTitle').textContent = historyLabel(item);
|
||||
document.getElementById('calActionMeta').textContent =
|
||||
`${historyAuthor(item)} · ${fmtDateTime(item.created_at)}` + (pairs.length > 1 ? ` · Событий: ${pairs.length}` : '');
|
||||
document.getElementById('calActionDiff').innerHTML = pairs.length
|
||||
? pairs.map(([before, after], i) => renderActionPair(before, after, terminal, i, pairs.length)).join('')
|
||||
: '<div class="cal-hist-empty">Изменений не зафиксировано</div>';
|
||||
historyState.detailId = item.id;
|
||||
historyState.detailCount = pairs.length;
|
||||
document.getElementById('calActionModal').classList.add('open');
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
async function openAction(id) {
|
||||
try {
|
||||
const item = await request(`/api/calendar/history/${id}`);
|
||||
renderActionDetail(item);
|
||||
} catch (e) {
|
||||
showToast(e.message || 'Не удалось открыть действие', true);
|
||||
}
|
||||
}
|
||||
|
||||
async function undoAction() {
|
||||
const id = historyState.detailId;
|
||||
const count = historyState.detailCount;
|
||||
const text = count > 1
|
||||
? `Отменить это действие? ${count} события вернутся к предыдущему состоянию.`
|
||||
: 'Отменить это действие? Событие вернётся к предыдущему состоянию.';
|
||||
if (!id || !confirm(text)) return;
|
||||
try {
|
||||
await request(`/api/calendar/history/${id}/undo`, { method: 'POST' });
|
||||
closeActionModal();
|
||||
showToast('Действие отменено');
|
||||
await refreshHistory();
|
||||
await reload();
|
||||
} catch (e) {
|
||||
showToast(e.message || 'Не удалось отменить действие', true);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshHistory() {
|
||||
await loadHistorySide();
|
||||
if (document.getElementById('calHistoryModal').classList.contains('open')) await loadHistoryFull(true);
|
||||
}
|
||||
|
||||
function bindHistoryList(el) {
|
||||
el.addEventListener('click', e => {
|
||||
const row = e.target.closest('[data-log-id]');
|
||||
if (row) openAction(Number(row.dataset.logId));
|
||||
});
|
||||
el.addEventListener('mouseover', e => {
|
||||
const row = e.target.closest('[data-log-id]');
|
||||
if (row) showHistoryTip(row);
|
||||
});
|
||||
el.addEventListener('mouseout', e => {
|
||||
const row = e.target.closest('[data-log-id]');
|
||||
if (row && !row.contains(e.relatedTarget)) hideHistoryTip();
|
||||
});
|
||||
}
|
||||
|
||||
function bindHistoryUi() {
|
||||
if (!isAdmin()) return;
|
||||
bindHistoryList(document.getElementById('calHistoryList'));
|
||||
bindHistoryList(document.getElementById('calHistoryFull'));
|
||||
document.getElementById('calHistoryAllBtn').addEventListener('click', openHistoryModal);
|
||||
document.getElementById('calHistoryCloseBtn').addEventListener('click', closeHistoryModal);
|
||||
document.getElementById('calHistoryModal').addEventListener('click', e => {
|
||||
if (e.target.id === 'calHistoryModal') closeHistoryModal();
|
||||
});
|
||||
document.getElementById('calHistoryUser').addEventListener('change', e => {
|
||||
historyState.userId = e.target.value;
|
||||
loadHistoryFull(true);
|
||||
});
|
||||
document.getElementById('calHistoryMoreBtn').addEventListener('click', () => loadHistoryFull(false));
|
||||
document.getElementById('calActionCloseBtn').addEventListener('click', closeActionModal);
|
||||
document.getElementById('calActionCancelBtn').addEventListener('click', closeActionModal);
|
||||
document.getElementById('calActionModal').addEventListener('click', e => {
|
||||
if (e.target.id === 'calActionModal') closeActionModal();
|
||||
});
|
||||
document.getElementById('calActionUndoBtn').addEventListener('click', undoAction);
|
||||
}
|
||||
|
||||
function bindUi() {
|
||||
bindHistoryUi();
|
||||
document.getElementById('calToday').addEventListener('click', () => {
|
||||
state.anchorIso = todayIso();
|
||||
saveState();
|
||||
@@ -1011,6 +1305,8 @@
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape') {
|
||||
if (drag) cancelDrag();
|
||||
else if (document.getElementById('calActionModal').classList.contains('open')) closeActionModal();
|
||||
else if (document.getElementById('calHistoryModal').classList.contains('open')) closeHistoryModal();
|
||||
else if (document.getElementById('calEventModal').classList.contains('open')) closeEditor();
|
||||
return;
|
||||
}
|
||||
@@ -1029,11 +1325,13 @@
|
||||
await loadCalendarSettings();
|
||||
loadState();
|
||||
await loadUsers();
|
||||
initHistoryUserFilter();
|
||||
buildSidebar(document.body.dataset.page);
|
||||
bindUi();
|
||||
renderUserFilter();
|
||||
render();
|
||||
await reload();
|
||||
await loadHistorySide();
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
@@ -138,6 +138,9 @@ const {
|
||||
softDeleteCalendarEvent,
|
||||
restoreCalendarEvent,
|
||||
deleteCalendarEventPermanent,
|
||||
listCalendarActions,
|
||||
getCalendarAction,
|
||||
undoCalendarAction,
|
||||
listWorkspaceSources,
|
||||
createCalendarReminderWorker,
|
||||
} = require('./lib/calendar');
|
||||
@@ -5617,6 +5620,52 @@ app.get('/api/calendar/users', apiLimiter, requireAuth, requireAdmin, async (req
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/calendar/history', apiLimiter, requireAuth, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const limit = req.query.limit == null ? 10 : parseInt(req.query.limit, 10);
|
||||
const offset = req.query.offset == null ? 0 : parseInt(req.query.offset, 10);
|
||||
if (!Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(offset) || offset < 0) {
|
||||
return res.status(400).json({ error: 'Invalid pagination' });
|
||||
}
|
||||
let userId = null;
|
||||
if (req.query.user_id != null && req.query.user_id !== '') {
|
||||
userId = parseInt(req.query.user_id, 10);
|
||||
if (!Number.isInteger(userId) || userId < 1) return res.status(400).json({ error: 'Invalid user_id' });
|
||||
}
|
||||
res.json(await listCalendarActions(pool, { limit, offset, userId }));
|
||||
} catch (e) {
|
||||
console.error('calendar history:', e);
|
||||
res.status(500).json({ error: 'Не удалось получить историю календаря' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/calendar/history/:id', apiLimiter, requireAuth, requireAdmin, 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 getCalendarAction(pool, id);
|
||||
if (!item) return res.status(404).json({ error: 'Запись истории не найдена' });
|
||||
res.json(item);
|
||||
} catch (e) {
|
||||
console.error('calendar history item:', e);
|
||||
res.status(500).json({ error: 'Не удалось получить действие' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/calendar/history/:id/undo', requireAuth, requireAdmin, 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 undoCalendarAction(pool, { id, purgeDays: await trashPurgeDays(), actor: req.user });
|
||||
await logAudit(req, 'calendar.history.undo', { id });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
if ([400, 403, 404, 409].includes(e.status)) return res.status(e.status).json({ error: e.message });
|
||||
console.error('calendar history undo:', e);
|
||||
res.status(500).json({ error: 'Не удалось отменить действие' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/calendar/events', apiLimiter, requireAuth, async (req, res) => {
|
||||
try {
|
||||
const tz = await appTimezone();
|
||||
@@ -5639,7 +5688,7 @@ app.post('/api/calendar/events', requireAuth, async (req, res) => {
|
||||
try {
|
||||
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(),
|
||||
userId: req.user.id, actor: req.user, audience, data: req.body, tz: await appTimezone(),
|
||||
});
|
||||
await logAudit(req, 'calendar.event.create', {
|
||||
count: items.length, user_ids: items.map(x => x.user_id),
|
||||
@@ -5659,7 +5708,7 @@ app.put('/api/calendar/events/:id', requireAuth, async (req, res) => {
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
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(),
|
||||
userId: req.user.id, actor: req.user, 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 });
|
||||
@@ -5674,7 +5723,7 @@ 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, isAdmin: req.user.role === 'admin', id, purgeDays: await trashPurgeDays() });
|
||||
await softDeleteCalendarEvent(pool, { userId: req.user.id, actor: req.user, isAdmin: req.user.role === 'admin', id, purgeDays: await trashPurgeDays() });
|
||||
await logAudit(req, 'calendar.event.delete', { id });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
@@ -5688,7 +5737,7 @@ 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, isAdmin: req.user.role === 'admin', id });
|
||||
await restoreCalendarEvent(pool, { userId: req.user.id, actor: req.user, isAdmin: req.user.role === 'admin', id });
|
||||
await logAudit(req, 'calendar.event.restore', { id });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
@@ -5702,7 +5751,7 @@ 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, isAdmin: req.user.role === 'admin', id });
|
||||
await deleteCalendarEventPermanent(pool, { userId: req.user.id, actor: req.user, isAdmin: req.user.role === 'admin', id });
|
||||
await logAudit(req, 'calendar.event.permanent-delete', { id });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
@@ -7535,7 +7584,7 @@ function backupUploadGuard(req, res, next) {
|
||||
async function buildBackupArchive() {
|
||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
||||
try {
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi, fm, ce] = await Promise.all([
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi, fm, ce, cal] = await Promise.all([
|
||||
pool.query('SELECT * FROM groups ORDER BY id'),
|
||||
pool.query('SELECT * FROM students ORDER BY id'),
|
||||
pool.query('SELECT * FROM entries ORDER BY id'),
|
||||
@@ -7578,6 +7627,7 @@ async function buildBackupArchive() {
|
||||
pool.query('SELECT * FROM digest_images ORDER BY id'),
|
||||
pool.query('SELECT * FROM farewell_messages ORDER BY id'),
|
||||
pool.query('SELECT * FROM calendar_events ORDER BY id'),
|
||||
pool.query('SELECT * FROM calendar_action_log ORDER BY id'),
|
||||
]);
|
||||
const settings = {};
|
||||
st.rows.forEach(r => { settings[r.key] = r.value; });
|
||||
@@ -7601,6 +7651,7 @@ async function buildBackupArchive() {
|
||||
doc_files: df.rowCount, sidebar_items: si.rowCount,
|
||||
digests: dg.rowCount, digest_images: dgi.rowCount, farewell_messages: fm.rowCount,
|
||||
calendar_events: ce.rowCount,
|
||||
calendar_action_log: cal.rowCount,
|
||||
},
|
||||
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows, student_work_marks: swm.rows,
|
||||
achievement_types: atr.rows, student_achievements: sar.rows,
|
||||
@@ -7608,6 +7659,7 @@ async function buildBackupArchive() {
|
||||
doc_files: df.rows, sidebar_items: si.rows,
|
||||
digests: dg.rows, digest_images: dgi.rows, farewell_messages: fm.rows,
|
||||
calendar_events: ce.rows,
|
||||
calendar_action_log: cal.rows,
|
||||
};
|
||||
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||
const files = await storage.downloadAll(path.join(staging, 'uploads'));
|
||||
@@ -7882,6 +7934,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await client.query('DELETE FROM user_settings');
|
||||
await client.query('DELETE FROM user_notes');
|
||||
await client.query('DELETE FROM calendar_events');
|
||||
await client.query('DELETE FROM calendar_action_log');
|
||||
await client.query('DELETE FROM bookmarks');
|
||||
await client.query('DELETE FROM achievement_types');
|
||||
await client.query('DELETE FROM photo_faces');
|
||||
@@ -7936,6 +7989,16 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
[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.calendar_action_log || [])) {
|
||||
const okUser = x.user_id == null || (await client.query('SELECT 1 FROM users WHERE id = $1', [x.user_id])).rowCount;
|
||||
if (!okUser) continue;
|
||||
await client.query(
|
||||
'INSERT INTO calendar_action_log (id, event_ids, user_id, user_name, action, title, before_state, after_state, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8::jsonb,$9)',
|
||||
[x.id, x.event_ids || [], x.user_id || null, x.user_name || '', x.action, x.title || '',
|
||||
JSON.stringify(Array.isArray(x.before_state) ? x.before_state : []),
|
||||
JSON.stringify(Array.isArray(x.after_state) ? x.after_state : []), x.created_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.achievement_types || [])) {
|
||||
await client.query(
|
||||
'INSERT INTO achievement_types (id, name, sort_order, is_active, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6)',
|
||||
|
||||
Reference in New Issue
Block a user