Добавить общие события и множественный выбор в календарь
This commit is contained in:
+157
-41
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user