notes: AI titles for new notes, personal-only access, modal polish

- new note created without a title gets one generated by a background
  worker (createNoteTitleWorker, ai_status column, wake channel,
  notes_changed SSE event, settings toggle notes_ai_enabled)
- notes are strictly personal: list/update/delete/reorder always scoped
  to req.user.id, admin no longer sees other users' notes (403)
- notes modal: focus goes to the text body, random color for new notes,
  ctrl+enter hint, tags hint styling, empty-title 400 fix (optText)
- backup/restore: user_notes.ai_status normalized and restored
This commit is contained in:
dev
2026-10-08 21:47:37 +03:00
parent f226c3f144
commit b5d1fd0948
10 changed files with 427 additions and 34 deletions
+84 -27
View File
@@ -6,7 +6,7 @@ const { ipKeyGenerator } = require('express-rate-limit');
const helmet = require('helmet');
const bcrypt = require('bcrypt');
const heicConvert = require('heic-convert');
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter } = require('./worker');
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker } = require('./worker');
const { createZipWriter, renderStudentReport } = require('./student-report');
const { createStorage, mimeFor } = require('./storage');
@@ -24,6 +24,7 @@ const {
optInt,
reqStr,
optStr,
optText,
optTs,
reqTs,
optDate,
@@ -134,6 +135,7 @@ const AI_WAKE_CHANNEL = 'whatido:wake:ai';
const PHOTO_WAKE_CHANNEL = 'whatido:wake:photo';
const LESSON_AI_WAKE_CHANNEL = 'whatido:wake:lesson-ai';
const FEEDBACK_WAKE_CHANNEL = 'whatido:wake:feedback';
const NOTE_AI_WAKE_CHANNEL = 'whatido:wake:note-ai';
function createWorkerBus(channel) {
return {
@@ -172,7 +174,7 @@ function dispatchEvent(payload) {
writeFrame('feedback_status', payload);
return;
}
if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed')) {
if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed' || payload.type === 'notes_changed')) {
writeFrame(payload.type, { ts: Date.now() });
return;
}
@@ -206,6 +208,11 @@ function broadcastFeedbackChanged() {
.catch(err => console.error('Publish failed:', err.message));
}
function broadcastNotesChanged() {
cache.publish(EVENTS_CHANNEL, { type: 'notes_changed' })
.catch(err => console.error('Publish failed:', err.message));
}
function broadcastAiStatus(payload) {
cache.publish(EVENTS_CHANNEL, { type: 'ai_status', ...payload })
.catch(err => console.error('Publish failed:', err.message));
@@ -1747,11 +1754,15 @@ async function ensureUserNotesTable() {
tags TEXT NOT NULL DEFAULT '',
color VARCHAR(7) NOT NULL DEFAULT '#2563eb',
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()
)`);
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('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("INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING");
}
async function ensureApiKeysTable() {
@@ -3288,15 +3299,22 @@ app.put('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
const NOTE_TITLE_MAX = 200;
const NOTE_TEXT_MAX = 100000;
const NOTE_TAGS_MAX = 10;
const NOTES_AI_DEFAULT_PROMPT = 'Ты придумываешь короткий заголовок для личной заметки пользователя. Тебе дадут текст заметки и, возможно, теги.\n' +
'Требования к заголовку:\n' +
'- 2–6 слов, максимум 60 символов\n' +
'- отражает суть заметки, без воды и общих слов\n' +
'- пишется с большой буквы, без кавычек, без точки в конце\n' +
'- язык заголовка совпадает с языком заметки\n' +
'Верни только сам заголовок, ничего больше.';
async function findNote(user, id) {
const { rows } = await pool.query(
`SELECT id, user_id, title, note, tags, color, created_at, updated_at
`SELECT id, user_id, title, note, tags, color, ai_status, 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) {
if (note.user_id !== user.id) {
const e = new Error('Forbidden');
e.forbidden = true;
throw e;
@@ -3306,14 +3324,12 @@ async function findNote(user, id) {
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
`SELECT id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at
FROM user_notes
${where ? `WHERE ${where}` : ''}
WHERE user_id = $1
ORDER BY sort_order ASC, updated_at DESC`,
params
[req.user.id]
);
res.json({ items: rows });
} catch (e) {
@@ -3324,8 +3340,9 @@ app.get('/api/notes', requireAuth, async (req, res) => {
app.post('/api/notes', requireAuth, async (req, res) => {
try {
const title = optStr(req.body?.title, NOTE_TITLE_MAX) || '';
const note = optStr(req.body?.note, NOTE_TEXT_MAX) || '';
const title = optText(req.body?.title, NOTE_TITLE_MAX);
const note = optText(req.body?.note, NOTE_TEXT_MAX);
if (!title && !note) return res.status(400).json({ error: 'Заполните текст заметки' });
let tags = '';
if (req.body?.tags !== undefined && req.body.tags !== null) {
const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean);
@@ -3333,13 +3350,15 @@ app.post('/api/notes', requireAuth, async (req, res) => {
}
let color = String(req.body?.color || '#2563eb').trim();
if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = '#2563eb';
const aiWanted = !title && (await getSetting('notes_ai_enabled', 'true')) !== 'false';
const { rows } = await pool.query(
`INSERT INTO user_notes (user_id, title, note, tags, color, sort_order)
`INSERT INTO user_notes (user_id, title, note, tags, color, sort_order, ai_status)
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]
COALESCE((SELECT MIN(sort_order) FROM user_notes WHERE user_id = $1), 1) - 1, $6)
RETURNING id, user_id, title, note, tags, color, sort_order, ai_status, created_at, updated_at`,
[req.user.id, title, note, tags, color, aiWanted ? 'pending' : 'none']
);
if (aiWanted) wakeNoteAiWorker();
res.json({ item: rows[0] });
} catch (e) {
if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
@@ -3363,9 +3382,10 @@ app.put('/api/notes/reorder', requireAuth, async (req, res) => {
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]);
const { rowCount } = 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');
@@ -3391,8 +3411,9 @@ 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: 'Нет доступа' });
const title = optStr(req.body?.title, NOTE_TITLE_MAX) || '';
const text = optStr(req.body?.note, NOTE_TEXT_MAX) || '';
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: 'Заполните текст заметки' });
let tags = '';
if (req.body?.tags !== undefined && req.body.tags !== null) {
const list = String(req.body.tags).split(',').map(t => t.trim()).filter(Boolean);
@@ -3400,12 +3421,14 @@ app.put('/api/notes/:id', requireAuth, async (req, res) => {
}
let color = String(req.body?.color || note.color).trim();
if (!/^#[0-9a-fA-F]{6}$/.test(color)) color = note.color;
const aiWanted = !title && (await getSetting('notes_ai_enabled', 'true')) !== 'false';
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]
`UPDATE user_notes SET title=$1, note=$2, tags=$3, color=$4, ai_status=$6, updated_at=now()
WHERE id=$5 AND user_id=$7
RETURNING id, user_id, title, note, tags, color, ai_status, created_at, updated_at`,
[title, text, tags, color, id, title ? 'none' : (aiWanted ? 'pending' : 'none'), req.user.id]
);
if (aiWanted) wakeNoteAiWorker();
res.json({ item: rows[0] });
} catch (e) {
if (e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
@@ -3422,10 +3445,11 @@ 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', [id]);
await pool.query('DELETE FROM user_notes WHERE id = $1 AND user_id = $2', [id, req.user.id]);
await logAudit(req, 'note.delete', { id });
res.json({ ok: true });
} catch (e) {
if (e.forbidden) return res.status(403).json({ error: 'Нет доступа' });
console.error('notes delete:', e);
res.status(500).json({ error: 'Не удалось удалить заметку' });
}
@@ -3859,6 +3883,9 @@ app.put('/api/settings', requireAdmin, async (req, res) => {
if (key === 'lesson_ai_enabled' && !['true', 'false'].includes(String(value))) {
return res.status(400).json({ error: 'lesson_ai_enabled должен быть true или false' });
}
if (key === 'notes_ai_enabled' && !['true', 'false'].includes(String(value))) {
return res.status(400).json({ error: 'notes_ai_enabled должен быть true или false' });
}
if (key === 'lesson_ai_prompt' && String(value).length > 8000) {
return res.status(400).json({ error: 'lesson_ai_prompt длиннее 8000 символов' });
}
@@ -4143,6 +4170,7 @@ let entryAutoChecker = null;
let photoWorker = null;
let lessonAiChecker = null;
let feedbackWorker = null;
let noteAiWorker = null;
function wakeLessonAiWorker() {
if (lessonAiChecker) lessonAiChecker.notify();
@@ -4152,6 +4180,24 @@ function wakeFeedbackWorker() {
if (feedbackWorker) feedbackWorker.notify();
}
function wakeNoteAiWorker() {
if (noteAiWorker) noteAiWorker.notify();
}
async function onNoteAiDone({ row, status, title, error }) {
try {
broadcastNotesChanged();
if (!logAudit) return;
if (status === 'done') {
await logAudit(null, 'note.ai.title', { id: row.id, title: String(title || '').slice(0, 200) });
} else if (status === 'error') {
await logAudit(null, 'note.ai.error', { id: row.id, error: String(error || '').slice(0, 500) });
}
} catch (e) {
console.error('Note AI onDone error:', e.message);
}
}
async function onLessonAiDone({ row, status, text, aiText, error }) {
invalidateLessonReports();
cache.publish(EVENTS_CHANNEL, {
@@ -4603,8 +4649,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, 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]
'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]
);
}
for (const x of ndata.user_branches) {
@@ -9853,4 +9899,15 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
});
feedbackWorker.start();
console.log('Feedback AI worker started');
noteAiWorker = createNoteTitleWorker({
pool,
getSetting,
logAudit,
aiUrl: AI_URL,
defaultPrompt: NOTES_AI_DEFAULT_PROMPT,
bus: createWorkerBus(NOTE_AI_WAKE_CHANNEL),
onDone: onNoteAiDone,
});
noteAiWorker.start();
console.log('Note title AI worker started');
})();