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.
This commit is contained in:
dev
2026-10-17 00:17:00 +03:00
parent 9ae54da2e4
commit 2f8c2da280
12 changed files with 303 additions and 71 deletions
+122 -41
View File
@@ -1469,6 +1469,7 @@ async function purgeScheduledDeletions() {
}
const sres = await pool.query('DELETE FROM short_messages WHERE purge_at IS NOT NULL AND purge_at <= now()');
const scount = sres.rowCount;
await pool.query('DELETE FROM user_notes WHERE purge_at IS NOT NULL AND purge_at <= now()');
const fbres = await pool.query('DELETE FROM feedbacks WHERE purge_at IS NOT NULL AND purge_at <= now()');
const fbcount = fbres.rowCount;
const bires = await pool.query('DELETE FROM broken_images WHERE purge_at IS NOT NULL AND purge_at <= now()');
@@ -2556,12 +2557,17 @@ async function ensureUserNotesTable() {
sort_order INT NOT NULL DEFAULT 0,
ai_status VARCHAR(20) NOT NULL DEFAULT 'none',
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
updated_at TIMESTAMPTZ DEFAULT now(),
deleted_at TIMESTAMPTZ,
purge_at TIMESTAMPTZ
)`);
await pool.query('ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0');
await pool.query("ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS ai_status VARCHAR(20) NOT NULL DEFAULT 'none'");
await pool.query('ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ');
await pool.query('ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ');
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_notes_user_id ON user_notes(user_id)');
await pool.query(`CREATE INDEX IF NOT EXISTS idx_user_notes_pending ON user_notes(ai_status, id) WHERE ai_status = 'pending'`);
await pool.query('CREATE INDEX IF NOT EXISTS idx_user_notes_deleted ON user_notes(deleted_at)');
await pool.query("INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING");
}
@@ -4433,7 +4439,7 @@ const NOTES_AI_DEFAULT_PROMPT = 'Ты придумываешь короткий
async function findNote(user, id) {
const { rows } = await pool.query(
`SELECT id, user_id, title, note, tags, color, ai_status, created_at, updated_at
`SELECT id, user_id, title, note, tags, color, ai_status, created_at, updated_at, deleted_at, purge_at
FROM user_notes WHERE id = $1`, [id]
);
const note = rows[0];
@@ -4448,10 +4454,12 @@ async function findNote(user, id) {
app.get('/api/notes', requireAuth, async (req, res) => {
try {
const showDeleted = req.query.deleted === '1' || req.query.deleted === 'true';
const where = showDeleted ? 'deleted_at IS NOT NULL' : 'deleted_at IS NULL';
const { rows } = await pool.query(
`SELECT id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at
`SELECT id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at, deleted_at, purge_at
FROM user_notes
WHERE user_id = $1
WHERE user_id = $1 AND ${where}
ORDER BY sort_order ASC, updated_at DESC`,
[req.user.id]
);
@@ -4507,7 +4515,7 @@ app.put('/api/notes/reorder', requireAuth, async (req, res) => {
await client.query('BEGIN');
for (let i = 0; i < ids.length; i++) {
const { rowCount } = await client.query(
'UPDATE user_notes SET sort_order = $1 WHERE id = $2 AND user_id = $3',
'UPDATE user_notes SET sort_order = $1 WHERE id = $2 AND user_id = $3 AND deleted_at IS NULL',
[i + 1, ids[i], req.user.id]
);
if (!rowCount) throw { http: 404, message: 'Заметка не найдена' };
@@ -4535,6 +4543,7 @@ app.put('/api/notes/:id', requireAuth, async (req, res) => {
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: 'Нет доступа' });
if (note.deleted_at) return res.status(400).json({ error: 'Заметка удалена' });
const title = optText(req.body?.title, NOTE_TITLE_MAX);
const text = optText(req.body?.note, NOTE_TEXT_MAX);
if (!title && !text) return res.status(400).json({ error: 'Заполните текст заметки' });
@@ -4569,8 +4578,14 @@ app.delete('/api/notes/:id', requireAuth, async (req, res) => {
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 AND user_id = $2', [id, req.user.id]);
await logAudit(req, 'note.delete', { id });
const days = await trashPurgeDays();
const { rowCount } = await pool.query(
`UPDATE user_notes SET deleted_at = now(), purge_at = now() + ($1 || ' days')::interval
WHERE id = $2 AND user_id = $3 AND deleted_at IS NULL`,
[String(days), id, req.user.id]
);
if (!rowCount) return res.status(404).json({ error: 'Заметка не найдена или уже удалена' });
await logAudit(req, 'note.delete', { id, purge_days: days });
res.json({ ok: true });
} catch (e) {
if (e.forbidden) return res.status(403).json({ error: 'Нет доступа' });
@@ -4579,6 +4594,48 @@ app.delete('/api/notes/:id', requireAuth, async (req, res) => {
}
});
app.put('/api/notes/:id/restore', 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 { rowCount } = await pool.query(
'UPDATE user_notes SET deleted_at = NULL, purge_at = NULL WHERE id = $1 AND user_id = $2 AND deleted_at IS NOT NULL',
[id, req.user.id]
);
if (!rowCount) return res.status(404).json({ error: 'Заметка не найдена или не удалена' });
await logAudit(req, 'note.restore', { id });
res.json({ ok: true });
} catch (e) {
if (e.forbidden) return res.status(403).json({ error: 'Нет доступа' });
console.error('notes restore:', e);
res.status(500).json({ error: 'Не удалось восстановить заметку' });
}
});
app.delete('/api/notes/:id/permanent', 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 { rowCount } = await pool.query(
'DELETE FROM user_notes WHERE id = $1 AND user_id = $2 AND deleted_at IS NOT NULL',
[id, req.user.id]
);
if (!rowCount) return res.status(404).json({ error: 'Заметка не найдена или не удалена' });
await logAudit(req, 'note.permanent-delete', { id });
res.json({ ok: true });
} catch (e) {
if (e.forbidden) return res.status(403).json({ error: 'Нет доступа' });
console.error('notes permanent delete:', e);
res.status(500).json({ error: 'Не удалось удалить заметку' });
}
});
// --- Bookmarks (закладки: admin + tutors) ---
const BOOKMARK_TITLE_MAX = 200;
const BOOKMARK_DESC_MAX = 500;
@@ -5382,6 +5439,23 @@ app.put('/api/user-settings', requireAuth, async (req, res) => {
}
});
app.post('/api/user-settings/models/test', requireAuth, aiLimiter, async (req, res) => {
const raw = req.body && req.body.model;
if (!raw || typeof raw !== 'object') return res.status(400).json({ error: 'model required' });
let model;
try {
const list = JSON.parse(normalizeFeedbackModels(JSON.stringify([{
id: 'probe', name: 'probe',
base_url: raw.base_url, model: raw.model,
api_key: raw.api_key, max_tokens: raw.max_tokens
}])));
model = list[0];
} catch (e) {
return res.status(400).json({ error: e.message || 'Некорректные данные модели' });
}
res.json(await probeAiModel(model));
});
const logoUpload = upload.single('logo');
app.post('/api/settings/logo', requireAdmin, (req, res, next) => {
logoUpload(req, res, (err) => {
@@ -5482,6 +5556,7 @@ const PHOTO_AI_DEVICE_PREFS = ['auto', 'cuda', 'cpu'];
const PHOTO_AI_DEFAULT_STRENGTH = 0.7;
const AI_MODEL = process.env.AI_MODEL || 'qwen2.5-1.5b-instruct-q4_k_m.gguf';
const AI_CALL_TIMEOUT_MS = Math.max(5000, parseInt(process.env.AI_REQUEST_TIMEOUT_MS || '120000', 10) || 120000);
const AI_MODEL_TEST_TIMEOUT_MS = Math.max(3000, parseInt(process.env.AI_MODEL_TEST_TIMEOUT_MS || '15000', 10) || 15000);
const AI_DEFAULT_PROMPT = process.env.AI_PROMPT || 'Ты — редактор текстов. Исправь ТОЛЬКО грамматические, орфографические и пунктуационные ошибки в тексте. Приведи к правильному регистру буквы. НЕ меняй слова, структуру предложений, стиль или смысл текста. Верни ТОЛЬКО исправленный текст без пояснений.';
let entryAutoChecker = null;
let photoWorker = null;
@@ -5606,6 +5681,43 @@ function normalizeOpenAiBase(base) {
return b;
}
async function probeAiModel(model) {
const base = normalizeOpenAiBase(model.base_url);
if (!base) return { ok: false, latency_ms: 0, error: 'Некорректный base_url (нужен http/https)' };
const startedAt = Date.now();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), AI_MODEL_TEST_TIMEOUT_MS);
try {
const headers = { 'Content-Type': 'application/json' };
if (model.api_key) headers.Authorization = `Bearer ${model.api_key}`;
const r = await fetch(`${base}/chat/completions`, {
method: 'POST',
headers,
signal: controller.signal,
body: JSON.stringify({
model: model.model,
messages: [{ role: 'user', content: 'Ответь одним словом: ок' }],
max_tokens: 8,
temperature: 0,
}),
});
const latency_ms = Date.now() - startedAt;
if (!r.ok) {
const t = await r.text().catch(() => '');
return { ok: false, latency_ms, error: `HTTP ${r.status}${t ? ': ' + t.slice(0, 200) : ''}` };
}
const d = await r.json();
const sample = (d.choices?.[0]?.message?.content || '').trim();
return { ok: true, latency_ms, sample: sample.slice(0, 120) };
} catch (e) {
const latency_ms = Date.now() - startedAt;
const timeout = `Таймаут ${Math.round(AI_MODEL_TEST_TIMEOUT_MS / 1000)} с`;
return { ok: false, latency_ms, error: e.name === 'AbortError' ? timeout : (e.message || 'unreachable') };
} finally {
clearTimeout(timer);
}
}
async function aiComplete(systemPrompt, userText, maxTokensOverride, profileOverride) {
const profile = profileOverride || await getActiveAiProfile();
let url = `${AI_URL.replace(/\/+$/, '')}/v1/chat/completions`;
@@ -6003,8 +6115,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
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, ai_status, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)',
[x.id, x.user_id, x.title, x.note, x.tags, x.color, x.sort_order, x.ai_status || 'none', x.created_at || null, x.updated_at || null]
'INSERT INTO user_notes (id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at, deleted_at, purge_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)',
[x.id, x.user_id, x.title, x.note, x.tags, x.color, x.sort_order, x.ai_status || 'none', x.created_at || null, x.updated_at || null, x.deleted_at || null, x.purge_at || null]
);
}
for (const x of (ndata.bookmarks || [])) {
@@ -11436,38 +11548,7 @@ app.post('/api/ai/profiles/activate', requireAdmin, async (req, res) => {
app.post('/api/ai/profiles/test', requireAdmin, async (req, res) => {
const v = validateProfileBody(req.body);
if (v.error) return res.status(400).json({ error: v.error });
const base = normalizeOpenAiBase(v.base_url);
const startedAt = Date.now();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15000);
try {
const headers = { 'Content-Type': 'application/json' };
if (v.api_key) headers.Authorization = `Bearer ${v.api_key}`;
const r = await fetch(`${base}/chat/completions`, {
method: 'POST',
headers,
signal: controller.signal,
body: JSON.stringify({
model: v.model,
messages: [{ role: 'user', content: 'Ответь одним словом: ок' }],
max_tokens: 8,
temperature: 0,
}),
});
const latency_ms = Date.now() - startedAt;
if (!r.ok) {
const t = await r.text().catch(() => '');
return res.json({ ok: false, latency_ms, error: `HTTP ${r.status}${t ? ': ' + t.slice(0, 200) : ''}` });
}
const d = await r.json();
const sample = (d.choices?.[0]?.message?.content || '').trim();
res.json({ ok: true, latency_ms, sample: sample.slice(0, 120) });
} catch (e) {
const latency_ms = Date.now() - startedAt;
res.json({ ok: false, latency_ms, error: e.name === 'AbortError' ? 'Таймаут 15 с' : (e.message || 'unreachable') });
} finally {
clearTimeout(timer);
}
res.json(await probeAiModel(v));
});
app.get('/api/ai/queue', requireAdmin, async (_, res) => {