Files
dev 2f8c2da280 feat(notes,profile): trash for notes and personal model connection check
Notes:
- soft delete via deleted_at/purge_at with trashPurgeDays(), restore and
  permanent-delete routes, ?deleted=1 list switch
- GET /api/notes now always returns only own notes (admin included)
- purge user_notes in purgeScheduledDeletions(), skip deleted rows in
  reorder and in the note title worker
- deleted_at/purge_at in init.sql, migration.sql, ensureUserNotesTable(),
  normalizeRestoreData and restore-insert

Profile:
- POST /api/user-settings/models/test probes a personal model from the
  client payload (works before save), shared probeAiModel() with the admin
  profile test, AI_MODEL_TEST_TIMEOUT_MS env in .env.example/compose
- "Проверить" button in the model list and in the model form
- password fields: autocomplete hints, values cleared on every toggle

Notes page: #notesDeleted trash toggle, deleted card state, restore/permanent
actions; fmtTs() uses the global fmtDateTime() instead of the non-existent
window.datetime.
2026-10-17 00:17:00 +03:00

410 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(async function() {
'use strict';
const API = location.origin;
let notes = [];
let editingId = null;
let deletedMode = false;
let dragId = null;
let saving = false;
const NOTE_COLORS = ['#2563eb', '#4f46e5', '#7c3aed', '#db2777', '#dc2626', '#ea580c', '#ca8a04', '#16a34a', '#0d9488', '#0891b2'];
function randomColor() {
return NOTE_COLORS[Math.floor(Math.random() * NOTE_COLORS.length)];
}
function hdr() {
const t = sessionStorage.getItem('authToken');
return t ? { 'X-Auth-Token': t } : {};
}
function esc(s) {
return String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;');
}
function fmtTs(v) {
try { if (typeof fmtDateTime === 'function') return 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>';
const generating = !n.title && (n.ai_status === 'pending' || n.ai_status === 'processing');
const titleHtml = n.title
? esc(n.title)
: generating
? '<span class="note-empty-note">Заголовок генерируется…</span>'
: esc('Без заголовка');
return '<div class="note-card' + (deletedMode ? ' note-card--deleted' : '') + '" data-id="' + n.id + '" style="--ncolor:' + color + '">' +
'<div class="note-card-head">' +
(deletedMode ? '' :
'<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">' + titleHtml + '</div>' +
(deletedMode ? '<span class="note-del-badge">Удалено</span>' : '') +
tagsHtml +
'</div>' +
'<div class="note-card-note">' + body + '</div>' +
'<div class="note-card-foot">' +
'<span class="note-card-time">' + (deletedMode ? 'Удалено: ' : '') + esc(fmtTs(deletedMode ? n.deleted_at : n.updated_at)) + '</span>' +
'<div class="note-card-actions">' + actionsHtml(n) + '</div>' +
'</div>' +
'</div>';
}
function actionsHtml(n) {
if (deletedMode) {
return '<button type="button" class="btn-link" data-action="restore" data-id="' + n.id + '">Восстановить</button>' +
'<button type="button" class="btn-link danger" data-action="permanent" data-id="' + n.id + '">Удалить навсегда</button>';
}
return '<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>';
}
function renderNotes() {
const el = document.getElementById('notesList');
if (!el) return;
if (!notes.length) {
el.innerHTML = deletedMode
? '<div class="note-empty">В корзине нет заметок</div>'
: '<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 : randomColor();
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('notesNote').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 && !noteText) { showToast('Заполните текст заметки', true); return; }
if (saving) return;
const payload = { title: title, note: noteText, tags: tags, color: color };
let res;
saving = true;
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) {
saving = false;
showToast('Ошибка сети', true);
return;
}
saving = false;
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('Заметка перемещена в корзину');
}
async function restoreNote(id) {
if (!confirm('Восстановить заметку из корзины?')) return;
let res;
try {
res = await fetch(API + '/api/notes/' + id + '/restore', { method: 'PUT', 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('Заметка восстановлена');
}
async function permanentNote(id) {
if (!confirm('Удалить заметку навсегда? Действие необратимо.')) return;
let res;
try {
res = await fetch(API + '/api/notes/' + id + '/permanent', { 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) {
const m = document.getElementById('notesModal');
const open = m && m.classList.contains('open');
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && open) {
e.preventDefault();
saveNote();
return;
}
if (e.key === 'Escape' && 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 restoreBtn = e.target.closest('[data-action="restore"]');
if (restoreBtn) {
await restoreNote(parseInt(restoreBtn.dataset.id, 10));
return;
}
const permBtn = e.target.closest('[data-action="permanent"]');
if (permBtn) {
await permanentNote(parseInt(permBtn.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);
});
const delToggle = document.getElementById('notesDeleted');
if (delToggle) {
delToggle.addEventListener('change', function () {
deletedMode = delToggle.checked;
const newBtn = document.getElementById('notesNewBtn');
if (newBtn) newBtn.style.display = deletedMode ? 'none' : '';
loadNotes();
});
}
}
async function loadNotes() {
let res;
try {
res = await fetch(API + '/api/notes' + (deletedMode ? '?deleted=1' : ''), { headers: hdr() });
} catch (e) {
showToast('Ошибка сети при загрузке заметок', true);
return;
}
if (res.ok) {
const data = await res.json().catch(function () { return {}; });
notes = data.items || [];
renderNotes();
}
}
let liveSource = null;
let liveReconnectTimer = null;
let liveReloadTimer = null;
function connectNotesLive() {
if (liveSource) { liveSource.close(); liveSource = null; }
const connect = () => {
const t = sessionStorage.getItem('authToken');
if (!t) return;
liveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
const scheduleReload = () => {
if (liveReloadTimer) clearTimeout(liveReloadTimer);
liveReloadTimer = setTimeout(() => { liveReloadTimer = null; loadNotes(); }, 300);
};
liveSource.addEventListener('notes_changed', scheduleReload);
liveSource.onerror = () => {
if (liveSource) { liveSource.close(); liveSource = null; }
if (liveReconnectTimer) clearTimeout(liveReconnectTimer);
liveReconnectTimer = setTimeout(connect, 5000);
};
};
connect();
window.addEventListener('beforeunload', () => { if (liveSource) liveSource.close(); });
}
async function init() {
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
bindModal();
bindPage();
renderIcons();
await loadNotes();
connectNotesLive();
}
init();
})();