Календарь: история действий с отменой для админа
This commit is contained in:
+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,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user