feat(notes): личные заметки с drag-and-drop сортировкой
- Новая страница notes.html и контроллер public/js/notes.js - Таблица user_notes (id, user_id, title, note, tags, color, sort_order) - Сохранение порядка карточек через PUT /api/notes/reorder - Личные заметки администратора видны всем, тьюторы — только своим - Поддержка user_notes в бэкапе и восстановлении (backup-restore.js) - Обновлена документация AGENTS.md
This commit is contained in:
@@ -1726,6 +1726,22 @@ async function ensureUserTables() {
|
||||
await pool.query('ALTER TABLE groups ADD COLUMN IF NOT EXISTS tutor_id INT REFERENCES users(id) ON DELETE SET NULL');
|
||||
}
|
||||
|
||||
async function ensureUserNotesTable() {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS user_notes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
title VARCHAR(200) NOT NULL DEFAULT '',
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
tags TEXT NOT NULL DEFAULT '',
|
||||
color VARCHAR(7) NOT NULL DEFAULT '#2563eb',
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
)`);
|
||||
await pool.query('ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_notes_user_id ON user_notes(user_id)');
|
||||
}
|
||||
|
||||
async function ensureApiKeysTable() {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -1764,6 +1780,7 @@ async function ensureFirstAdmin() {
|
||||
async function ensureUsersAndFirstAdmin() {
|
||||
await ensureUserTables();
|
||||
await ensureApiKeysTable();
|
||||
await ensureUserNotesTable();
|
||||
await ensureFirstAdmin();
|
||||
}
|
||||
|
||||
@@ -3255,6 +3272,153 @@ app.put('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// --- Notes (per-user, private) ---
|
||||
const NOTE_TITLE_MAX = 200;
|
||||
const NOTE_TEXT_MAX = 100000;
|
||||
const NOTE_TAGS_MAX = 10;
|
||||
|
||||
async function findNote(user, id) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, user_id, title, note, tags, color, created_at, updated_at
|
||||
FROM user_notes WHERE id = $1`, [id]
|
||||
);
|
||||
const note = rows[0];
|
||||
if (!note) return null;
|
||||
if (user.role !== 'admin' && note.user_id !== user.id) {
|
||||
const e = new Error('Forbidden');
|
||||
e.forbidden = true;
|
||||
throw e;
|
||||
}
|
||||
return note;
|
||||
}
|
||||
|
||||
app.get('/api/notes', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const where = req.user.role === 'admin' ? '' : 'user_id = $1';
|
||||
const params = req.user.role === 'admin' ? [] : [req.user.id];
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, user_id, title, note, tags, color, sort_order, created_at, updated_at
|
||||
FROM user_notes
|
||||
${where ? `WHERE ${where}` : ''}
|
||||
ORDER BY sort_order ASC, updated_at DESC`,
|
||||
params
|
||||
);
|
||||
res.json({ items: rows });
|
||||
} catch (e) {
|
||||
console.error('notes list:', e);
|
||||
res.status(500).json({ error: 'Не удалось получить заметки' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/notes', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const title = reqStr(req.body?.title, NOTE_TITLE_MAX);
|
||||
const note = optStr(req.body?.note, NOTE_TEXT_MAX) || '';
|
||||
let tags = '';
|
||||
if (req.body?.tags !== undefined && req.body.tags !== null) {
|
||||
const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean);
|
||||
tags = list.slice(0, NOTE_TAGS_MAX).join(', ');
|
||||
}
|
||||
let color = String(req.body?.color || '#2563eb').trim();
|
||||
if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = '#2563eb';
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO user_notes (user_id, title, note, tags, color, sort_order)
|
||||
VALUES ($1, $2, $3, $4, $5,
|
||||
COALESCE((SELECT MIN(sort_order) FROM user_notes WHERE user_id = $1), 1) - 1)
|
||||
RETURNING id, user_id, title, note, tags, color, sort_order, created_at, updated_at`,
|
||||
[req.user.id, title, note, tags, color]
|
||||
);
|
||||
res.json({ item: rows[0] });
|
||||
} catch (e) {
|
||||
if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
|
||||
console.error('notes create:', e);
|
||||
res.status(500).json({ error: 'Не удалось создать заметку' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/notes/reorder', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const raw = Array.isArray(req.body?.ids) ? req.body.ids : null;
|
||||
if (!raw || raw.some(id => !Number.isInteger(Number(id)))) {
|
||||
return res.status(400).json({ error: 'Некорректный порядок заметок' });
|
||||
}
|
||||
const ids = raw.map(id => Number(id));
|
||||
if (ids.some(id => id < 1)) return res.status(400).json({ error: 'Некорректный порядок заметок' });
|
||||
if (new Set(ids).size !== ids.length) {
|
||||
return res.status(400).json({ error: 'Порядок заметок содержит дубликаты' });
|
||||
}
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const { rowCount } = req.user.role === 'admin'
|
||||
? await client.query('UPDATE user_notes SET sort_order = $1 WHERE id = $2', [i + 1, ids[i]])
|
||||
: await client.query('UPDATE user_notes SET sort_order = $1 WHERE id = $2 AND user_id = $3', [i + 1, ids[i], req.user.id]);
|
||||
if (!rowCount) throw { http: 404, message: 'Заметка не найдена' };
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
await logAudit(req, 'note.reorder', { order: ids });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
if (e.http) return res.status(e.http).json({ error: e.message });
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('notes reorder:', e);
|
||||
res.status(500).json({ error: 'Не удалось сохранить порядок заметок' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/notes/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const note = await findNote(req.user, id);
|
||||
if (!note) return res.status(404).json({ error: 'Not found' });
|
||||
if (note.forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const title = reqStr(req.body?.title, NOTE_TITLE_MAX);
|
||||
const text = optStr(req.body?.note, NOTE_TEXT_MAX) || '';
|
||||
let tags = '';
|
||||
if (req.body?.tags !== undefined && req.body.tags !== null) {
|
||||
const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean);
|
||||
tags = list.slice(0, NOTE_TAGS_MAX).join(', ');
|
||||
}
|
||||
let color = String(req.body?.color || note.color).trim();
|
||||
if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = note.color;
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE user_notes SET title=$1, note=$2, tags=$3, color=$4, updated_at=now()
|
||||
WHERE id=$5
|
||||
RETURNING id, user_id, title, note, tags, color, created_at, updated_at`,
|
||||
[title, text, tags, color, id]
|
||||
);
|
||||
res.json({ item: rows[0] });
|
||||
} catch (e) {
|
||||
if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
|
||||
if (e.forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
console.error('notes update:', e);
|
||||
res.status(500).json({ error: 'Не удалось обновить заметку' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/notes/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const note = await findNote(req.user, id);
|
||||
if (!note) return res.status(404).json({ error: 'Not found' });
|
||||
if (note.forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
await pool.query('DELETE FROM user_notes WHERE id = $1', [id]);
|
||||
await logAudit(req, 'note.delete', { id });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error('notes delete:', e);
|
||||
res.status(500).json({ error: 'Не удалось удалить заметку' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/feedbacks/:id', requireAuth, async (req, res) => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
@@ -4125,7 +4289,7 @@ function sweepBackupStorage() {
|
||||
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] = 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] = 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'),
|
||||
@@ -4152,6 +4316,7 @@ async function buildBackupArchive() {
|
||||
pool.query('SELECT * FROM short_messages ORDER BY id'),
|
||||
pool.query('SELECT * FROM feedbacks ORDER BY id'),
|
||||
pool.query('SELECT * FROM user_settings ORDER BY user_id, key'),
|
||||
pool.query('SELECT * FROM user_notes ORDER BY id'),
|
||||
]);
|
||||
const settings = {};
|
||||
st.rows.forEach(r => { settings[r.key] = r.value; });
|
||||
@@ -4167,9 +4332,9 @@ async function buildBackupArchive() {
|
||||
lesson_report_versions: lrv.rowCount, audit_log: al.rowCount, notifications: nt.rowCount,
|
||||
notification_reads: nr.rowCount, banned_ips: bi.rowCount,
|
||||
chat_threads: ct.rowCount, chat_messages: cm.rowCount, chat_attachments: ca.rowCount,
|
||||
short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount,
|
||||
short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount, user_notes: un.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,
|
||||
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,
|
||||
};
|
||||
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||
const files = await storage.downloadAll(path.join(staging, 'uploads'));
|
||||
@@ -4350,6 +4515,7 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
await client.query('DELETE FROM api_keys');
|
||||
await client.query('DELETE FROM audit_log');
|
||||
await client.query('DELETE FROM user_settings');
|
||||
await client.query('DELETE FROM user_notes');
|
||||
await client.query('DELETE FROM users');
|
||||
await client.query('DELETE FROM branches');
|
||||
for (const x of ndata.branches) {
|
||||
@@ -4372,6 +4538,14 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
[x.user_id, x.key, x.value, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.user_notes || [])) {
|
||||
const okUser = (await client.query('SELECT 1 FROM users WHERE id = $1', [x.user_id])).rowCount;
|
||||
if (!okUser) continue;
|
||||
await client.query(
|
||||
'INSERT INTO user_notes (id, user_id, title, note, tags, color, sort_order, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)',
|
||||
[x.id, x.user_id, x.title, x.note, x.tags, x.color, x.sort_order, x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.user_branches) {
|
||||
await client.query(
|
||||
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',
|
||||
|
||||
Reference in New Issue
Block a user