Заметки
+Личные заметки для каждого пользователя
+ +diff --git a/AGENTS.md b/AGENTS.md index 4eddaa7..31d2d5f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -201,6 +201,15 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo - **Аудит запуска**: воркер пишет `feedback.ai.run` (id, status, attempt, model, profile, duration_ms, prompt ≤12000, input ≤6000, output ≤6000, changed, len_before/len_after) или `feedback.ai.error` (id, attempt, error ≤500, prompt, input) — `feedback.ai.generate` из `onFeedbackDone` удалён как дублирующий. `PUT /api/feedbacks/:id` пишет `feedback.update` (id, ai_check, ai_profile); `feedback.create` включает `ai_profile` - **Бэкап**: `user_settings` входит в `BACKUP_TABLES`, дамп в `buildBackupArchive`, нормализацию в `normalizeRestoreData`, `DELETE` перед `DELETE FROM users` и `INSERT` после `users` в restore (с проверкой существования пользователя) +### 3i. Заметки (`server.js`, `public/notes.html`, `public/js/notes.js`) +- **Таблица `user_notes`** (`id`, `user_id`, `title`, `note`, `tags`, `color`, `sort_order`, `created_at`, `updated_at`) — личные заметки. Схема в трёх местах: `db/init.sql`, `db/migration.sql` и `ensureUserNotesTable()` в `server.js` (включая `ALTER TABLE ... ADD COLUMN IF NOT EXISTS` для существующих БД) +- **Порядок карточек хранится в `user_notes.sort_order`** (`INT NOT NULL DEFAULT 0`). GET сортирует `ORDER BY sort_order ASC, updated_at DESC` (старые строки с нулём деградируют в сортировку по `updated_at`, поведение не меняется). Новая заметка получает `MIN(sort_order) - 1` своего пользователя, чтобы встать первой +- **Reorder**: `PUT /api/notes/reorder` `{ ids: [...] }` под `requireAuth` — **регистрируется до `PUT /api/notes/:id`**, иначе `parseInt('reorder')` даст 400 вместо маршрута. Транзакция: позиция `i+1` пишется по каждому id; для не-admin — только `WHERE ... AND user_id = $3`, чужой id → откат + 404. Аудит `note.reorder`. `updated_at` reorder **не трогает** +- **Доступ**: `GET /api/notes` отдаёт админу все заметки, не-admin — только свои (`user_id = $1`); админский список может содержать записи разных пользователей, reorder это допускает (общая нумерация не ломает чужие относительные порядки) +- **UI**: `public/notes.html` — сетка `.notes-list` (4 колонки, брейкпоинты 1200/900/640 — как у `.journal-cards`). Ручка перетаскивания — `.note-drag` (`⠿`, `draggable="true"`) в шапке карточки: карточка целиком намеренно **не** draggable, иначе нельзя выделять текст заметки мышью. Обработчики `dragstart`/`dragover`/`dragend`/`drop` висят на контейнере `#notesList` (`bindDrag()` в `public/js/notes.js`) и переживают перерисовку `innerHTML` +- **Сохранение порядка**: `persistNoteOrder()` сравнивает порядок id в DOM с `notes[]` (пустая серия — без запроса), шлёт `PUT /api/notes/reorder` и на успехе перестраивает `notes[]` по DOM, на ошибке — `renderNotes()` для отката визуала +- **Бэкап**: `user_notes` входит в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, `normalizeRestoreData` (пустые `title`/`tags`/`note` валидируются через `optText`, не `optStr` — тот бросает исключение на пустой строке), `DELETE` перед `DELETE FROM users` и `INSERT` с проверкой пользователя в restore + --- ### 4. API Patterns @@ -241,10 +250,10 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo - **Scripts**: `scripts/backup.sh`, `scripts/restore.sh` (host-level) - Формат архива: `tar.gz` с `data.json` + `uploads/`. Версия формата — `BACKUP_FORMAT_VERSION` в `backup-restore.js` (сейчас `2`), принимаются версии `1..2`; версия пишется в `data.json.version` и возвращается в ответе `POST /api/backup` и `POST /api/restore` - `data.json` содержит `version`, `created_at`, `app` (версия/коммит), `counts` (строки по таблицам + `files`) и сами данные. Таблицы перечислены в `BACKUP_TABLES` — **при добавлении таблицы править её и в `buildBackupArchive`, и здесь** -- `sessions` в бэкап **не входит** намеренно: после restore все токены должны умереть. `audit_log`, `notifications`, `notification_reads`, `banned_ips`, `user_settings` — входят +- `sessions` в бэкап **не входит** намеренно: после restore все токены должны умереть. `audit_log`, `notifications`, `notification_reads`, `banned_ips`, `user_settings`, `user_notes` — входят - Файлы: `storage.downloadAll` кладёт в архив всё, кроме регенерируемых `.thumbs/` и `.cache/`; `.originals/` (оригиналы фото до ИИ-обработки) **входят** и восстанавливаются через `uploadTree` - Restore: валидация всего через `normalizeRestoreData` (`backup-restore.js`), транзакция с `DELETE` в FK-безопасном порядке → `INSERT` → `setval` по `BACKUP_SEQUENCE_TABLES` → файлы → `sweepOrphanedUploads()` → `loadBans()` → `invalidateAll()` -- **Колонки, которые normalizeRestoreData обязана сохранять**: `groups.deleted_at`/`purge_at`, `entries.purge_at`. Потеря `deleted_at` воскрешает мягко удалённые группы как активные — это не «мелочь», а порча данных +- **Колонки, которые normalizeRestoreData обязана сохранять**: `groups.deleted_at`/`purge_at`, `entries.purge_at`. Потеря `deleted_at` воскрешает мягко удалённые группы как активные — это не «мелочь», а порча данных. `user_notes.sort_order` терять нельзя тоже: без неё порядок карточек схлопнется в сортировку по `updated_at` - `sweepOrphanedUploads()` считает ссылками фото из `entries.photo_path`/`photo_original_path`, `project_files.path`, `group_photos`, `entry_photos`, `student_photos`, `modules.photo_path`, `students.photo_path`, `groups.cover_path`, `photo_jobs.before_path`/`after_path`, `settings.system_logo`. Новая колонка с путём к файлу → добавить сюда, иначе sweep снесёт файл сразу после restore --- @@ -410,6 +419,8 @@ guards against. | `public/chat.html` | Чат тьютор↔админ: список диалогов, лента сообщений, вложения (Ctrl+V) | | `public/js/chat.js` | Логика чата: загрузка треда/сообщений, отправка, вставка файлов из буфера | | `public/feedback.html` | Страница обратной связи (отзывы тьютора) | +| `public/notes.html` | Заметки: сетка карточек 4 в ряд, инлайн-стили `.note-*`, модалка редактирования | +| `public/js/notes.js` | Заметки: рендер карточек, CRUD, drag-and-drop порядок (`bindDrag`/`persistNoteOrder`) | | `public/js/feedback.js` | Логика обратной связи: список, модалка, выбор short_messages, ИИ-очередь | | `scripts/backup.sh` | Host-level backup script (DB dump + storage export) | | `scripts/restore.sh` | Host-level restore script (DB dump + storage import) | diff --git a/backup-restore.js b/backup-restore.js index 5ea17f2..9c87bc1 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -5,14 +5,14 @@ const BACKUP_FORMAT_VERSION = 2; const BACKUP_MIN_FORMAT_VERSION = 1; const BACKUP_TABLES = [ 'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_branches', - 'user_settings', + 'user_settings', 'user_notes', 'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications', 'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments', 'short_messages', 'feedbacks', ]; const BACKUP_SEQUENCE_TABLES = [ - 'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'group_photos', + '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', 'audit_log', 'notifications', 'chat_threads', 'chat_messages', 'chat_attachments', 'short_messages', 'feedbacks', @@ -547,7 +547,18 @@ function normalizeRestoreData(data) { value: optText(x.value, 8000), updated_at: optTs(x.updated_at), })); - return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, 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 }; + const user_notes = (data.user_notes || []).map(x => ({ + id: reqInt(x.id), + user_id: reqInt(x.user_id), + title: optText(x.title, 200) || '', + note: optText(x.note, 100000) || '', + tags: optText(x.tags, 50000) || '', + color: optText(x.color, 7) || '#2563eb', + sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0, + created_at: optTs(x.created_at), + updated_at: optTs(x.updated_at), + })); + 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 }; } module.exports = { diff --git a/db/init.sql b/db/init.sql index 3d3ecce..23b4c15 100644 --- a/db/init.sql +++ b/db/init.sql @@ -222,6 +222,18 @@ CREATE TABLE IF NOT EXISTS user_settings ( PRIMARY KEY (user_id, key) ); +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() +); + CREATE TABLE IF NOT EXISTS sessions ( id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, diff --git a/db/migration.sql b/db/migration.sql index 88ae0f8..2590676 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -176,6 +176,19 @@ CREATE TABLE IF NOT EXISTS sessions ( CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token); CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at); +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', + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); + +ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0; + CREATE TABLE IF NOT EXISTS api_keys ( id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, diff --git a/public/admin.css b/public/admin.css index 0e84069..08c5ab2 100644 --- a/public/admin.css +++ b/public/admin.css @@ -39,9 +39,13 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b .sidebar nav a[data-nav=dashboard] svg{color:#6366f1} .sidebar nav a[data-nav=journal] svg{color:#0ea5e9} +.sidebar nav a[data-nav=lessons] svg{color:#f97316} .sidebar nav a[data-nav=notifications] svg{color:#f59e0b} .sidebar nav a[data-nav=students] svg{color:#14b8a6} .sidebar nav a[data-nav=groups] svg{color:#8b5cf6} +.sidebar nav a[data-nav=feedback] svg{color:#f43f5e} +.sidebar nav a[data-nav=shorts] svg{color:#eab308} +.sidebar nav a[data-nav=chat] svg{color:#22c55e} .sidebar nav a[data-nav=files] svg{color:#f59e0b} .sidebar nav a[data-nav=photos] svg{color:#0891b2} .sidebar nav a[data-nav=links] svg{color:#06b6d4} @@ -102,13 +106,14 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b .card .info{flex:1;min-width:0} .card .name{font-weight:600;font-size:.95rem} .card .group{color:var(--accent);font-size:.8rem;margin-top:2px} -.card .desc{color:var(--muted);font-size:.85rem;margin-top:8px;line-height:1.4;white-space:pre-wrap} +.card .desc{color:var(--muted);font-size:.85rem;margin-top:8px;line-height:1.4;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word} .card .time{color:var(--muted);font-size:.75rem;margin-top:8px} .entry-files{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-top:8px} .entry-files .f-item{display:flex;align-items:center;gap:2px;background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:2px;min-width:0} .entry-files .f-item:hover{border-color:var(--accent)} .entry-files .f-item a{display:inline-flex;align-items:center;gap:4px;color:var(--text);text-decoration:none;padding:2px 6px;font-size:.75rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0} .entry-files .f-item a:hover{color:var(--accent)} +.entry-files .f-link{display:block;max-width:100%;color:var(--text);text-decoration:none;padding:2px 6px;font-size:.75rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .entry-files .f-item a::before{content:'📎'} .entry-files .f-detach{flex-shrink:0;background:none;border:none;color:var(--muted);cursor:pointer;font-size:.75rem;line-height:1;padding:2px 5px;border-radius:4px} .entry-files .f-detach:hover{color:#ef4444;background:rgba(239,68,68,.1)} @@ -138,7 +143,7 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b .journal-card .no-photo svg *{fill:currentColor} .journal-card .body{padding:12px 14px;display:flex;flex-direction:column;gap:6px;flex:1;min-width:0} .journal-card .name{font-weight:600;font-size:.95rem} -.journal-card .desc{color:var(--muted);font-size:.85rem;line-height:1.4;white-space:pre-wrap;flex:1} +.journal-card .desc{color:var(--muted);font-size:.85rem;line-height:1.4;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;flex:1} .journal-card .foot{display:flex;justify-content:space-between;align-items:center;gap:8px;padding:10px 14px;border-top:1px solid var(--border);color:var(--muted);font-size:.75rem} .journal-card .foot .edit,.journal-card .foot .del{background:none;border:none;color:var(--muted);cursor:pointer;font-size:1rem;padding:4px} .journal-card .foot .edit:hover{color:var(--accent)} diff --git a/public/admin.js b/public/admin.js index 70daee9..443f98c 100644 --- a/public/admin.js +++ b/public/admin.js @@ -51,26 +51,27 @@ function buildSidebar(active) { { page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard' }, { page: 'journal', label: 'Журнал', icon: 'book-open' }, { page: 'lessons', label: 'Отчёты о занятиях', icon: 'notebook-pen' }, - { page: 'feedback', label: 'Обратная связь', icon: 'message-square-heart' }, - { page: 'notifications', label: 'Уведомления', icon: 'bell', badge: true }, - { page: 'chat', label: 'Чаты', icon: 'messages-square', chatBadge: true }, { page: 'students', label: 'Ученики', icon: 'graduation-cap' }, { page: 'groups', label: 'Группы', icon: 'users' }, + { page: 'feedback', label: 'Обратная связь', icon: 'message-square-heart' }, + { page: 'shorts', label: 'Короткие сообщения', icon: 'zap' }, + { page: 'chat', label: 'Чаты', icon: 'messages-square', chatBadge: true }, + { page: 'notifications', label: 'Уведомления', icon: 'bell', badge: true }, { page: 'photos', label: 'Фото', icon: 'Image' }, { page: 'files', label: 'Файлы', icon: 'folder' }, { page: 'links', label: 'Ссылки', icon: 'link' }, - { page: 'shorts', label: 'Короткие сообщения', icon: 'zap' }, { page: 'trash', label: 'Корзина', icon: 'trash-2' }, + { page: 'notes', label: 'Заметки', icon: 'sticky-note' }, ]; const adminNav = [ - { page: 'modules', label: 'Темы модулей', icon: 'layers' }, - { page: 'branches', label: 'Филиалы', icon: 'building-2' }, - { page: 'users', label: 'Пользователи', icon: 'user-cog' }, - { page: 'apikeys', label: 'API-ключи', icon: 'key-round' }, - { page: 'worker', label: 'Воркер ИИ', icon: 'bot' }, - { page: 'audit', label: 'Аудит', icon: 'scroll-text' }, - { page: 'bans', label: 'Блокировки', icon: 'shield-off' }, { page: 'settings', label: 'Настройки', icon: 'settings' }, + { page: 'modules', label: 'Темы модулей', icon: 'layers' }, + { page: 'users', label: 'Пользователи', icon: 'user-cog' }, + { page: 'branches', label: 'Филиалы', icon: 'building-2' }, + { page: 'audit', label: 'Аудит', icon: 'scroll-text' }, + { page: 'worker', label: 'Воркер ИИ', icon: 'bot' }, + { page: 'apikeys', label: 'API-ключи', icon: 'key-round' }, + { page: 'bans', label: 'Блокировки', icon: 'shield-off' }, ]; const userName = currentUser?.name || currentUser?.username || ''; const roleLabel = isAdmin() ? 'Администратор' : 'Тутор'; @@ -1055,4 +1056,4 @@ document.addEventListener('click', e => { if (imgEl) { e.preventDefault(); showImg(imgEl.dataset.img); return; } const out = e.target.closest('[data-action="logout"]'); if (out) { e.preventDefault(); doLogout(); } -}); \ No newline at end of file +}); diff --git a/public/feedback.html b/public/feedback.html index 6244e02..0388611 100644 --- a/public/feedback.html +++ b/public/feedback.html @@ -6,7 +6,9 @@
Личные заметки для каждого пользователя
+ +