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:
@@ -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`
|
- **Аудит запуска**: воркер пишет `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 (с проверкой существования пользователя)
|
- **Бэкап**: `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
|
### 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)
|
- **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`
|
- Формат архива: `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`, и здесь**
|
- `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`
|
- Файлы: `storage.downloadAll` кладёт в архив всё, кроме регенерируемых `.thumbs/` и `.cache/`; `.originals/` (оригиналы фото до ИИ-обработки) **входят** и восстанавливаются через `uploadTree`
|
||||||
- Restore: валидация всего через `normalizeRestoreData` (`backup-restore.js`), транзакция с `DELETE` в FK-безопасном порядке → `INSERT` → `setval` по `BACKUP_SEQUENCE_TABLES` → файлы → `sweepOrphanedUploads()` → `loadBans()` → `invalidateAll()`
|
- 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
|
- `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/chat.html` | Чат тьютор↔админ: список диалогов, лента сообщений, вложения (Ctrl+V) |
|
||||||
| `public/js/chat.js` | Логика чата: загрузка треда/сообщений, отправка, вставка файлов из буфера |
|
| `public/js/chat.js` | Логика чата: загрузка треда/сообщений, отправка, вставка файлов из буфера |
|
||||||
| `public/feedback.html` | Страница обратной связи (отзывы тьютора) |
|
| `public/feedback.html` | Страница обратной связи (отзывы тьютора) |
|
||||||
|
| `public/notes.html` | Заметки: сетка карточек 4 в ряд, инлайн-стили `.note-*`, модалка редактирования |
|
||||||
|
| `public/js/notes.js` | Заметки: рендер карточек, CRUD, drag-and-drop порядок (`bindDrag`/`persistNoteOrder`) |
|
||||||
| `public/js/feedback.js` | Логика обратной связи: список, модалка, выбор short_messages, ИИ-очередь |
|
| `public/js/feedback.js` | Логика обратной связи: список, модалка, выбор short_messages, ИИ-очередь |
|
||||||
| `scripts/backup.sh` | Host-level backup script (DB dump + storage export) |
|
| `scripts/backup.sh` | Host-level backup script (DB dump + storage export) |
|
||||||
| `scripts/restore.sh` | Host-level restore script (DB dump + storage import) |
|
| `scripts/restore.sh` | Host-level restore script (DB dump + storage import) |
|
||||||
|
|||||||
+14
-3
@@ -5,14 +5,14 @@ const BACKUP_FORMAT_VERSION = 2;
|
|||||||
const BACKUP_MIN_FORMAT_VERSION = 1;
|
const BACKUP_MIN_FORMAT_VERSION = 1;
|
||||||
const BACKUP_TABLES = [
|
const BACKUP_TABLES = [
|
||||||
'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_branches',
|
'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',
|
'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs',
|
||||||
'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications',
|
'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications',
|
||||||
'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments',
|
'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments',
|
||||||
'short_messages', 'feedbacks',
|
'short_messages', 'feedbacks',
|
||||||
];
|
];
|
||||||
const BACKUP_SEQUENCE_TABLES = [
|
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',
|
'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports',
|
||||||
'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages',
|
'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages',
|
||||||
'chat_attachments', 'short_messages', 'feedbacks',
|
'chat_attachments', 'short_messages', 'feedbacks',
|
||||||
@@ -547,7 +547,18 @@ function normalizeRestoreData(data) {
|
|||||||
value: optText(x.value, 8000),
|
value: optText(x.value, 8000),
|
||||||
updated_at: optTs(x.updated_at),
|
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 = {
|
module.exports = {
|
||||||
|
|||||||
+12
@@ -222,6 +222,18 @@ CREATE TABLE IF NOT EXISTS user_settings (
|
|||||||
PRIMARY KEY (user_id, key)
|
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 (
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
|||||||
@@ -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_token ON sessions(token);
|
||||||
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
|
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 (
|
CREATE TABLE IF NOT EXISTS api_keys (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
|||||||
+7
-2
@@ -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=dashboard] svg{color:#6366f1}
|
||||||
.sidebar nav a[data-nav=journal] svg{color:#0ea5e9}
|
.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=notifications] svg{color:#f59e0b}
|
||||||
.sidebar nav a[data-nav=students] svg{color:#14b8a6}
|
.sidebar nav a[data-nav=students] svg{color:#14b8a6}
|
||||||
.sidebar nav a[data-nav=groups] svg{color:#8b5cf6}
|
.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=files] svg{color:#f59e0b}
|
||||||
.sidebar nav a[data-nav=photos] svg{color:#0891b2}
|
.sidebar nav a[data-nav=photos] svg{color:#0891b2}
|
||||||
.sidebar nav a[data-nav=links] svg{color:#06b6d4}
|
.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 .info{flex:1;min-width:0}
|
||||||
.card .name{font-weight:600;font-size:.95rem}
|
.card .name{font-weight:600;font-size:.95rem}
|
||||||
.card .group{color:var(--accent);font-size:.8rem;margin-top:2px}
|
.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}
|
.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{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{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: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{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-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-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{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)}
|
.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 .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 .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 .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{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,.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)}
|
.journal-card .foot .edit:hover{color:var(--accent)}
|
||||||
|
|||||||
+13
-12
@@ -51,26 +51,27 @@ function buildSidebar(active) {
|
|||||||
{ page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard' },
|
{ page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard' },
|
||||||
{ page: 'journal', label: 'Журнал', icon: 'book-open' },
|
{ page: 'journal', label: 'Журнал', icon: 'book-open' },
|
||||||
{ page: 'lessons', label: 'Отчёты о занятиях', icon: 'notebook-pen' },
|
{ 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: 'students', label: 'Ученики', icon: 'graduation-cap' },
|
||||||
{ page: 'groups', label: 'Группы', icon: 'users' },
|
{ 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: 'photos', label: 'Фото', icon: 'Image' },
|
||||||
{ page: 'files', label: 'Файлы', icon: 'folder' },
|
{ page: 'files', label: 'Файлы', icon: 'folder' },
|
||||||
{ page: 'links', label: 'Ссылки', icon: 'link' },
|
{ page: 'links', label: 'Ссылки', icon: 'link' },
|
||||||
{ page: 'shorts', label: 'Короткие сообщения', icon: 'zap' },
|
|
||||||
{ page: 'trash', label: 'Корзина', icon: 'trash-2' },
|
{ page: 'trash', label: 'Корзина', icon: 'trash-2' },
|
||||||
|
{ page: 'notes', label: 'Заметки', icon: 'sticky-note' },
|
||||||
];
|
];
|
||||||
const adminNav = [
|
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: '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 userName = currentUser?.name || currentUser?.username || '';
|
||||||
const roleLabel = isAdmin() ? 'Администратор' : 'Тутор';
|
const roleLabel = isAdmin() ? 'Администратор' : 'Тутор';
|
||||||
@@ -1055,4 +1056,4 @@ document.addEventListener('click', e => {
|
|||||||
if (imgEl) { e.preventDefault(); showImg(imgEl.dataset.img); return; }
|
if (imgEl) { e.preventDefault(); showImg(imgEl.dataset.img); return; }
|
||||||
const out = e.target.closest('[data-action="logout"]');
|
const out = e.target.closest('[data-action="logout"]');
|
||||||
if (out) { e.preventDefault(); doLogout(); }
|
if (out) { e.preventDefault(); doLogout(); }
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,7 +6,9 @@
|
|||||||
<title>Обратная связь — WhatIDo</title>
|
<title>Обратная связь — WhatIDo</title>
|
||||||
<link rel="stylesheet" href="admin.css">
|
<link rel="stylesheet" href="admin.css">
|
||||||
<style>
|
<style>
|
||||||
.feedback-list { display:flex; flex-direction:column; gap:10px; }
|
.feedback-list { display:grid; grid-template-columns:repeat(2, minmax(0,1fr)); gap:10px; }
|
||||||
|
.feedback-list > .empty, .feedback-list > .muted { grid-column:1/-1; }
|
||||||
|
@media (max-width:1000px) { .feedback-list { grid-template-columns:1fr; } }
|
||||||
.feedback-item .ai-badge { margin-left:0; }
|
.feedback-item .ai-badge { margin-left:0; }
|
||||||
.feedback-item .btn-link.sent-on { background:var(--accent); color:#fff; border-color:var(--accent); }
|
.feedback-item .btn-link.sent-on { background:var(--accent); color:#fff; border-color:var(--accent); }
|
||||||
.shorts-list { display:flex; flex-direction:column; gap:6px; width:100%; max-height:220px; overflow:auto; padding:2px 0; }
|
.shorts-list { display:flex; flex-direction:column; gap:6px; width:100%; max-height:220px; overflow:auto; padding:2px 0; }
|
||||||
|
|||||||
@@ -0,0 +1,294 @@
|
|||||||
|
(async function() {
|
||||||
|
'use strict';
|
||||||
|
const API = location.origin;
|
||||||
|
let notes = [];
|
||||||
|
let editingId = null;
|
||||||
|
let dragId = null;
|
||||||
|
|
||||||
|
function hdr() {
|
||||||
|
const t = sessionStorage.getItem('authToken');
|
||||||
|
return t ? { 'X-Auth-Token': t } : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtTs(v) {
|
||||||
|
try { if (window.datetime && datetime.fmtDateTime) return datetime.fmtDateTime(v) || String(v); } catch (e) {}
|
||||||
|
return String(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function noteCardHtml(n) {
|
||||||
|
const color = /^#[0-9a-fA-F]{6}$/.test(n.color || '') ? n.color : '#2563eb';
|
||||||
|
const tags = n.tags ? n.tags.split(',').map(t => t.trim()).filter(Boolean) : [];
|
||||||
|
const tagsHtml = tags.length
|
||||||
|
? '<div class="note-tags">' + tags.map(t => '<span class="note-tag">' + esc(t) + '</span>').join('') + '</div>'
|
||||||
|
: '';
|
||||||
|
const body = n.note
|
||||||
|
? esc(n.note)
|
||||||
|
: '<span class="note-empty-note">Без текста</span>';
|
||||||
|
return '<div class="note-card" data-id="' + n.id + '" style="--ncolor:' + color + '">' +
|
||||||
|
'<div class="note-card-head">' +
|
||||||
|
'<span class="note-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>' +
|
||||||
|
'<div class="note-color-row" data-action="color" data-id="' + n.id + '">' +
|
||||||
|
'<input type="color" id="noteColorPicker-' + n.id + '" value="' + color + '" style="display:none">' +
|
||||||
|
'<span class="note-color-swatch" style="background:' + color + '" title="Изменить цвет"></span>' +
|
||||||
|
'</div>' +
|
||||||
|
'<div class="note-card-title">' + esc(n.title || 'Без заголовка') + '</div>' +
|
||||||
|
tagsHtml +
|
||||||
|
'</div>' +
|
||||||
|
'<div class="note-card-note">' + body + '</div>' +
|
||||||
|
'<div class="note-card-foot">' +
|
||||||
|
'<span class="note-card-time">' + esc(fmtTs(n.updated_at)) + '</span>' +
|
||||||
|
'<div class="note-card-actions">' +
|
||||||
|
'<button type="button" class="btn-link" data-action="edit" data-id="' + n.id + '">Изменить</button>' +
|
||||||
|
'<button type="button" class="btn-link danger" data-action="delete" data-id="' + n.id + '">Удалить</button>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderNotes() {
|
||||||
|
const el = document.getElementById('notesList');
|
||||||
|
if (!el) return;
|
||||||
|
if (!notes.length) {
|
||||||
|
el.innerHTML = '<div class="note-empty">Заметок пока нет. Нажмите «Новая заметка», чтобы создать первую заметку.</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.innerHTML = notes.map(noteCardHtml).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function persistNoteOrder() {
|
||||||
|
const els = Array.prototype.slice.call(document.querySelectorAll('#notesList .note-card'));
|
||||||
|
const order = els.map(function (el) { return parseInt(el.dataset.id, 10); });
|
||||||
|
if (JSON.stringify(order) === JSON.stringify(notes.map(function (n) { return n.id; }))) return;
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(API + '/api/notes/reorder', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()),
|
||||||
|
body: JSON.stringify({ ids: order })
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
showToast('Ошибка сети', true);
|
||||||
|
renderNotes();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json().catch(function () { return {}; });
|
||||||
|
showToast(data.error || 'Не удалось сохранить порядок заметок', true);
|
||||||
|
renderNotes();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
notes = order.map(function (id) {
|
||||||
|
return notes.find(function (n) { return n.id === id; });
|
||||||
|
}).filter(Boolean);
|
||||||
|
showToast('Порядок заметок сохранён');
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindDrag() {
|
||||||
|
const list = document.getElementById('notesList');
|
||||||
|
if (!list) return;
|
||||||
|
list.addEventListener('dragstart', function (e) {
|
||||||
|
const handle = e.target.closest('.note-drag');
|
||||||
|
if (!handle) { e.preventDefault(); return; }
|
||||||
|
const card = handle.closest('.note-card');
|
||||||
|
if (!card) return;
|
||||||
|
dragId = parseInt(card.dataset.id, 10);
|
||||||
|
card.classList.add('dragging');
|
||||||
|
e.dataTransfer.effectAllowed = 'move';
|
||||||
|
e.dataTransfer.setData('text/plain', String(dragId));
|
||||||
|
try { e.dataTransfer.setDragImage(card, 24, 24); } catch (err) {}
|
||||||
|
});
|
||||||
|
list.addEventListener('dragover', function (e) {
|
||||||
|
if (dragId == null) return;
|
||||||
|
e.preventDefault();
|
||||||
|
e.dataTransfer.dropEffect = 'move';
|
||||||
|
const target = e.target.closest('.note-card');
|
||||||
|
const dragged = list.querySelector('.note-card[data-id="' + dragId + '"]');
|
||||||
|
if (!target || !dragged || target === dragged || target.contains(dragged)) return;
|
||||||
|
const rect = target.getBoundingClientRect();
|
||||||
|
list.insertBefore(dragged, e.clientX > rect.left + rect.width / 2 ? target.nextSibling : target);
|
||||||
|
});
|
||||||
|
list.addEventListener('dragend', function (e) {
|
||||||
|
const card = e.target.closest('.note-card');
|
||||||
|
if (card) card.classList.remove('dragging');
|
||||||
|
if (dragId != null) persistNoteOrder();
|
||||||
|
dragId = null;
|
||||||
|
});
|
||||||
|
list.addEventListener('drop', function (e) { e.preventDefault(); });
|
||||||
|
}
|
||||||
|
|
||||||
|
function openModal(note) {
|
||||||
|
editingId = note ? note.id : null;
|
||||||
|
document.getElementById('notesModalTitle').textContent = note ? 'Редактировать заметку' : 'Новая заметка';
|
||||||
|
document.getElementById('notesTitle').value = note ? note.title : '';
|
||||||
|
document.getElementById('notesNote').value = note ? note.note : '';
|
||||||
|
document.getElementById('notesTags').value = note ? note.tags : '';
|
||||||
|
const color = note && /^#[0-9a-fA-F]{6}$/.test(note.color || '') ? note.color : '#2563eb';
|
||||||
|
document.getElementById('notesColor').value = color;
|
||||||
|
document.getElementById('notesColorPreview').style.background = color;
|
||||||
|
const row = document.getElementById('notesColorRow');
|
||||||
|
if (row) row.style.setProperty('--ncolor', color);
|
||||||
|
document.getElementById('notesModal').classList.add('open');
|
||||||
|
renderIcons();
|
||||||
|
setTimeout(() => document.getElementById('notesTitle').focus(), 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
const m = document.getElementById('notesModal');
|
||||||
|
if (m) m.classList.remove('open');
|
||||||
|
editingId = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveNote() {
|
||||||
|
const title = document.getElementById('notesTitle').value.trim();
|
||||||
|
const noteText = document.getElementById('notesNote').value.trim();
|
||||||
|
const rawTags = document.getElementById('notesTags').value.trim();
|
||||||
|
const tags = rawTags ? rawTags.split(',').map(t => t.trim()).filter(Boolean).slice(0, 10).join(', ') : '';
|
||||||
|
const color = document.getElementById('notesColor').value;
|
||||||
|
if (!title) { showToast('Укажите заголовок заметки', true); return; }
|
||||||
|
const payload = { title: title, note: noteText, tags: tags, color: color };
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
if (editingId) {
|
||||||
|
res = await fetch(API + '/api/notes/' + editingId, { method: 'PUT', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()), body: JSON.stringify(payload) });
|
||||||
|
} else {
|
||||||
|
res = await fetch(API + '/api/notes', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()), body: JSON.stringify(payload) });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showToast('Ошибка сети', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await res.json().catch(function () { return {}; });
|
||||||
|
if (!res.ok) {
|
||||||
|
showToast(data.error || 'Ошибка при сохранении', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const item = data.item || payload;
|
||||||
|
if (editingId) {
|
||||||
|
const idx = notes.findIndex(function (n) { return n.id === editingId; });
|
||||||
|
if (idx >= 0) notes[idx] = item;
|
||||||
|
showToast('Заметка обновлена');
|
||||||
|
} else {
|
||||||
|
notes.unshift(item);
|
||||||
|
showToast('Заметка сохранена');
|
||||||
|
}
|
||||||
|
renderNotes();
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeNote(id) {
|
||||||
|
if (!confirm('Удалить эту заметку?')) return;
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(API + '/api/notes/' + id, { method: 'DELETE', headers: hdr() });
|
||||||
|
} catch (e) {
|
||||||
|
showToast('Ошибка сети', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await res.json().catch(function () { return {}; });
|
||||||
|
if (!res.ok) {
|
||||||
|
showToast(data.error || 'Ошибка при удалении', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
notes = notes.filter(function (n) { return n.id !== id; });
|
||||||
|
renderNotes();
|
||||||
|
showToast('Заметка удалена');
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindModal() {
|
||||||
|
document.getElementById('notesModalClose').addEventListener('click', closeModal);
|
||||||
|
document.getElementById('notesCancel').addEventListener('click', closeModal);
|
||||||
|
document.getElementById('notesSave').addEventListener('click', saveNote);
|
||||||
|
const colorInput = document.getElementById('notesColor');
|
||||||
|
if (colorInput) {
|
||||||
|
colorInput.addEventListener('input', function (e) {
|
||||||
|
document.getElementById('notesColorPreview').style.background = e.target.value;
|
||||||
|
const row = document.getElementById('notesColorRow');
|
||||||
|
if (row) row.style.setProperty('--ncolor', e.target.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', function (e) {
|
||||||
|
if (e.key !== 'Escape') return;
|
||||||
|
const m = document.getElementById('notesModal');
|
||||||
|
if (m && m.classList.contains('open')) closeModal();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindPage() {
|
||||||
|
bindDrag();
|
||||||
|
document.addEventListener('click', async function (e) {
|
||||||
|
const editBtn = e.target.closest('[data-action="edit"]');
|
||||||
|
if (editBtn) {
|
||||||
|
const id = parseInt(editBtn.dataset.id, 10);
|
||||||
|
const note = notes.find(function (n) { return n.id === id; });
|
||||||
|
if (note) openModal(note);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const delBtn = e.target.closest('[data-action="delete"]');
|
||||||
|
if (delBtn) {
|
||||||
|
await removeNote(parseInt(delBtn.dataset.id, 10));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const colorRow = e.target.closest('[data-action="color"]');
|
||||||
|
if (colorRow) {
|
||||||
|
const picker = document.getElementById('noteColorPicker-' + parseInt(colorRow.dataset.id, 10));
|
||||||
|
if (picker) {
|
||||||
|
picker.click();
|
||||||
|
picker.onchange = async function () {
|
||||||
|
const id = parseInt(colorRow.dataset.id, 10);
|
||||||
|
const note = notes.find(function (n) { return n.id === id; });
|
||||||
|
if (!note) return;
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(API + '/api/notes/' + id, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()),
|
||||||
|
body: JSON.stringify({ title: note.title, note: note.note, tags: note.tags, color: picker.value })
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
showToast('Ошибка сети', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await res.json().catch(function () { return {}; });
|
||||||
|
if (!res.ok) { showToast(data.error || 'Ошибка при сохранении', true); return; }
|
||||||
|
const idx = notes.findIndex(function (n) { return n.id === id; });
|
||||||
|
if (idx >= 0) notes[idx] = data.item;
|
||||||
|
renderNotes();
|
||||||
|
showToast('Цвет обновлён');
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.target.closest('#notesNewBtn')) openModal(null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadNotes() {
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(API + '/api/notes', { headers: hdr() });
|
||||||
|
} catch (e) {
|
||||||
|
showToast('Ошибка сети при загрузке заметок', true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json().catch(function () { return {}; });
|
||||||
|
notes = data.items || [];
|
||||||
|
renderNotes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
if (!(await checkAuth())) return;
|
||||||
|
buildSidebar(document.body.dataset.page);
|
||||||
|
bindModal();
|
||||||
|
bindPage();
|
||||||
|
renderIcons();
|
||||||
|
await loadNotes();
|
||||||
|
}
|
||||||
|
|
||||||
|
init();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>Заметки — Админ-панель</title>
|
||||||
|
<link rel="stylesheet" href="admin.css">
|
||||||
|
<style>
|
||||||
|
.notes-list { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-top: 8px; align-items: stretch; }
|
||||||
|
@media (max-width: 1200px) { .notes-list { grid-template-columns: repeat(3, 1fr); } }
|
||||||
|
@media (max-width: 900px) { .notes-list { grid-template-columns: repeat(2, 1fr); } }
|
||||||
|
@media (max-width: 640px) { .notes-list { grid-template-columns: 1fr; } }
|
||||||
|
.note-card {
|
||||||
|
position: relative;
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-left: 4px solid;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
transition: box-shadow .15s, transform .15s, opacity .15s;
|
||||||
|
}
|
||||||
|
.note-card:hover { box-shadow: 0 8px 20px rgba(0,0,0,.08); }
|
||||||
|
.note-card.dragging { opacity: .4; border-style: dashed; }
|
||||||
|
.note-drag {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
flex: none;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: .85rem;
|
||||||
|
cursor: grab;
|
||||||
|
border-radius: 6px;
|
||||||
|
transition: color .15s, background .15s;
|
||||||
|
}
|
||||||
|
.note-drag:hover { color: var(--text); background: rgba(127,127,127,.15); }
|
||||||
|
.note-drag:active { cursor: grabbing; }
|
||||||
|
.note-card-title-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||||
|
.note-color-row { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.note-color-swatch { width: 18px; height: 18px; border-radius: 6px; border: 1px solid var(--border); flex: none; cursor: pointer; transition: transform .15s; }
|
||||||
|
.note-color-swatch:hover { transform: scale(1.15); }
|
||||||
|
.note-card-head { display: flex; align-items: flex-start; gap: 10px; flex-wrap: wrap; }
|
||||||
|
.note-card-title { font-weight: 600; font-size: .95rem; color: var(--ncolor); word-break: break-word; }
|
||||||
|
.note-tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.note-tag { font-size: .72rem; padding: 2px 8px; border-radius: 999px; background: rgba(37,99,235,.1); color: #1d4ed8; border: 1px solid rgba(37,99,235,.2); }
|
||||||
|
.note-card-note { font-size: .88rem; color: var(--text); line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
.note-empty-note { color: var(--muted); font-style: italic; font-size: .85rem; }
|
||||||
|
.note-card-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; border-top: 1px solid var(--border); padding-top: 10px; }
|
||||||
|
.note-card-time { font-size: .72rem; color: var(--muted); }
|
||||||
|
.note-card-actions { display: flex; gap: 6px; }
|
||||||
|
.note-card-actions button { font-size: .78rem; }
|
||||||
|
.note-empty { text-align: center; color: var(--muted); padding: 32px 16px; font-size: .9rem; border: 1px dashed var(--border); border-radius: 12px; }
|
||||||
|
.note-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||||
|
.note-modal-head h3 { margin: 0; font-size: 1.05rem; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body data-page="notes">
|
||||||
|
<div class="layout">
|
||||||
|
<div class="sidebar" id="sidebar"></div>
|
||||||
|
<div class="main">
|
||||||
|
<div class="page-head">
|
||||||
|
<h2>Заметки</h2>
|
||||||
|
<p class="page-sub">Личные заметки для каждого пользователя</p>
|
||||||
|
<button type="button" class="btn-primary" id="notesNewBtn"><i data-lucide="plus"></i> Новая заметка</button>
|
||||||
|
</div>
|
||||||
|
<div id="notesList" class="notes-list"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-overlay" id="notesModal">
|
||||||
|
<div class="edit-modal" style="max-width:560px">
|
||||||
|
<div class="note-modal-head">
|
||||||
|
<h3 id="notesModalTitle">Новая заметка</h3>
|
||||||
|
<button type="button" class="icon-btn" id="notesModalClose"><i data-lucide="x"></i></button>
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Заголовок</label>
|
||||||
|
<input id="notesTitle" class="settings-input" maxlength="200" placeholder="Краткое название заметки">
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Заметка</label>
|
||||||
|
<textarea id="notesNote" class="settings-input" rows="6" placeholder="Текст заметки"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Теги</label>
|
||||||
|
<input id="notesTags" class="settings-input" placeholder="через запятую: важно, учеба, запланировать">
|
||||||
|
<div class="hint">Теги разделяются запятой</div>
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Цвет</label>
|
||||||
|
<div class="note-color-row" id="notesColorRow">
|
||||||
|
<input id="notesColor" type="color" class="settings-input" value="#2563eb" style="width:56px;height:42px;padding:5px;border-radius:8px;cursor:pointer">
|
||||||
|
<span id="notesColorPreview" style="width:16px;height:16px;border-radius:6px;border:1px solid var(--border);flex:none;background:#2563eb"></span>
|
||||||
|
<div class="hint">Цвет заметки</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-foot">
|
||||||
|
<button type="button" class="btn-primary ghost" id="notesCancel">Отмена</button>
|
||||||
|
<button type="button" class="btn-primary" id="notesSave">Сохранить</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
<script src="vendor/lucide.min.js"></script>
|
||||||
|
<script src="js/datetime.js"></script>
|
||||||
|
<script src="admin.js"></script>
|
||||||
|
<script src="js/notes.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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');
|
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() {
|
async function ensureApiKeysTable() {
|
||||||
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
|
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
@@ -1764,6 +1780,7 @@ async function ensureFirstAdmin() {
|
|||||||
async function ensureUsersAndFirstAdmin() {
|
async function ensureUsersAndFirstAdmin() {
|
||||||
await ensureUserTables();
|
await ensureUserTables();
|
||||||
await ensureApiKeysTable();
|
await ensureApiKeysTable();
|
||||||
|
await ensureUserNotesTable();
|
||||||
await ensureFirstAdmin();
|
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) => {
|
app.put('/api/feedbacks/:id', requireAuth, async (req, res) => {
|
||||||
const id = parseInt(req.params.id, 10);
|
const id = parseInt(req.params.id, 10);
|
||||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||||
@@ -4125,7 +4289,7 @@ function sweepBackupStorage() {
|
|||||||
async function buildBackupArchive() {
|
async function buildBackupArchive() {
|
||||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
||||||
try {
|
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 groups ORDER BY id'),
|
||||||
pool.query('SELECT * FROM students ORDER BY id'),
|
pool.query('SELECT * FROM students ORDER BY id'),
|
||||||
pool.query('SELECT * FROM entries 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 short_messages ORDER BY id'),
|
||||||
pool.query('SELECT * FROM feedbacks 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_settings ORDER BY user_id, key'),
|
||||||
|
pool.query('SELECT * FROM user_notes ORDER BY id'),
|
||||||
]);
|
]);
|
||||||
const settings = {};
|
const settings = {};
|
||||||
st.rows.forEach(r => { settings[r.key] = r.value; });
|
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,
|
lesson_report_versions: lrv.rowCount, audit_log: al.rowCount, notifications: nt.rowCount,
|
||||||
notification_reads: nr.rowCount, banned_ips: bi.rowCount,
|
notification_reads: nr.rowCount, banned_ips: bi.rowCount,
|
||||||
chat_threads: ct.rowCount, chat_messages: cm.rowCount, chat_attachments: ca.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));
|
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||||
const files = await storage.downloadAll(path.join(staging, 'uploads'));
|
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 api_keys');
|
||||||
await client.query('DELETE FROM audit_log');
|
await client.query('DELETE FROM audit_log');
|
||||||
await client.query('DELETE FROM user_settings');
|
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 users');
|
||||||
await client.query('DELETE FROM branches');
|
await client.query('DELETE FROM branches');
|
||||||
for (const x of ndata.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]
|
[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) {
|
for (const x of ndata.user_branches) {
|
||||||
await client.query(
|
await client.query(
|
||||||
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',
|
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',
|
||||||
|
|||||||
Reference in New Issue
Block a user