From 7e88247ced2277996d2e313cb64f2b8f0724f092 Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 12 Nov 2026 14:37:30 +0300 Subject: [PATCH] =?UTF-8?q?farewell:=20=D0=B4=D0=B0=D1=82=D0=B0,=20=D1=82?= =?UTF-8?q?=D1=83=D0=BC=D0=B1=D0=BB=D0=B5=D1=80=20=D0=98=D0=98=20=D0=B8=20?= =?UTF-8?q?=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D1=8B=D0=B9=20=D1=82=D0=B5=D0=BA?= =?UTF-8?q?=D1=81=D1=82=20=D0=B2=20=D0=BC=D0=BE=D0=B4=D0=B0=D0=BB=D0=BA?= =?UTF-8?q?=D0=B5,=20=D0=BF=D1=80=D0=BE=D1=88=D0=BB=D1=8B=D0=B9=20=D0=BE?= =?UTF-8?q?=D1=82=D0=B7=D1=8B=D0=B2=20=D1=82=D1=83=D0=BC=D0=B1=D0=BB=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backup-restore.js | 1 + db/init.sql | 1 + db/migration.sql | 1 + lib/farewell.js | 28 +++++++++++--- public/feedback.html | 65 +++++++++++++++++++++----------- public/js/feedback.js | 88 ++++++++++++++----------------------------- server.js | 10 +++-- worker.js | 5 +++ 8 files changed, 109 insertions(+), 90 deletions(-) diff --git a/backup-restore.js b/backup-restore.js index dac7bba..f7d3eb0 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -595,6 +595,7 @@ function normalizeRestoreData(data) { id: reqInt(r.id), resident: reqStr(r.resident, 200), topic: optStr(r.topic), + message_date: optDate(r.message_date), source_feedback_ids: Array.isArray(r.source_feedback_ids) ? r.source_feedback_ids.map(v => reqInt(v)) : [], template_id: optInt(r.template_id), template_text: optText(r.template_text, 100000), diff --git a/db/init.sql b/db/init.sql index 7ec1410..8ab20e5 100644 --- a/db/init.sql +++ b/db/init.sql @@ -668,6 +668,7 @@ CREATE TABLE IF NOT EXISTS farewell_messages ( id BIGSERIAL PRIMARY KEY, resident TEXT NOT NULL, topic TEXT, + message_date DATE, source_feedback_ids INT[] NOT NULL DEFAULT '{}'::int[], template_id BIGINT REFERENCES farewell_messages(id) ON DELETE SET NULL, template_text TEXT, diff --git a/db/migration.sql b/db/migration.sql index 9040c5d..f6db538 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -892,6 +892,7 @@ ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS author_id INT; ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS sent_at TIMESTAMPTZ; ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ; +ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS message_date DATE; ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT now(); diff --git a/lib/farewell.js b/lib/farewell.js index 3ba6119..ef30a5b 100644 --- a/lib/farewell.js +++ b/lib/farewell.js @@ -26,6 +26,7 @@ async function ensureFarewellTable(pool) { id BIGSERIAL PRIMARY KEY, resident TEXT NOT NULL, topic TEXT, + message_date DATE, source_feedback_ids INT[] NOT NULL DEFAULT '{}'::int[], template_id BIGINT REFERENCES farewell_messages(id) ON DELETE SET NULL, template_text TEXT, @@ -57,6 +58,7 @@ async function ensureFarewellTable(pool) { await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_model TEXT`); await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_duration_ms INTEGER`); await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS author_id INTEGER`); + await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS message_date DATE`); await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS sent_at TIMESTAMPTZ`); await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`); await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ`); @@ -70,11 +72,26 @@ async function createFarewell(pool, data) { if (!resident) { const e = new Error('Укажите фамилию и имя ученика'); e.status = 400; throw e; } if (resident.length > FAREWELL_RESIDENT_MAX) { const e = new Error('Слишком длинное имя ученика'); e.status = 400; throw e; } const topic = String(data.topic || '').trim().slice(0, FAREWELL_TOPIC_MAX) || null; + const messageDate = /^\d{4}-\d{2}-\d{2}$/.test(String(data.messageDate || '')) ? String(data.messageDate) : null; + const text = String(data.text || '').trim().slice(0, 100000) || null; const prompt = String(data.prompt || '').trim().slice(0, FAREWELL_PROMPT_MAX) || null; const aiProfile = String(data.aiProfile || '').trim().slice(0, 100) || null; - const ids = cleanInts(data.sourceFeedbackIds); + const aiCheck = data.aiCheck !== false; + let ids = cleanInts(data.sourceFeedbackIds); + + if (aiCheck && data.pastReview && !ids.length) { + const params = [resident]; + let sql = `SELECT id FROM feedbacks WHERE resident = $1 AND sent_at IS NOT NULL AND deleted_at IS NULL`; + if (Array.isArray(data.branchIds)) { + if (!data.branchIds.length) { const e = new Error('Нет доступных филиалов'); e.status = 403; throw e; } + params.push(data.branchIds); + sql += ` AND branch_id = ANY($${params.length}::int[])`; + } + sql += ` ORDER BY feedback_date DESC, id DESC LIMIT 10`; + const r = await pool.query(sql, params); + ids = r.rows.map(x => x.id).reverse(); + } - let accessible = ids; if (ids.length) { const params = [ids]; let sql = `SELECT id FROM feedbacks WHERE id = ANY($1::int[]) AND deleted_at IS NULL`; @@ -101,9 +118,9 @@ async function createFarewell(pool, data) { } const ins = await pool.query( - `INSERT INTO farewell_messages (resident, topic, source_feedback_ids, template_id, template_text, prompt, ai_profile, ai_status, author_id) - VALUES ($1, $2, $3::int[], $4, $5, $6, $7, 'pending', $8) RETURNING *`, - [resident, topic, ids, templateId, templateText, prompt, aiProfile, data.authorId || null] + `INSERT INTO farewell_messages (resident, topic, message_date, source_feedback_ids, template_id, template_text, prompt, ai_profile, ai_status, text, author_id) + VALUES ($1, $2, $3, $4::int[], $5, $6, $7, $8, $9, $10, $11) RETURNING *`, + [resident, topic, messageDate, ids, templateId, templateText, prompt, aiProfile, aiCheck ? 'pending' : 'none', text, data.authorId || null] ); return ins.rows[0]; } @@ -153,6 +170,7 @@ async function setFarewellStatus(pool, id, status, extra) { const sets = ['ai_status = $2', 'updated_at = now()']; const params = [id, status]; if (extra && extra.aiError !== undefined) { params.push(extra.aiError || null); sets.push(`ai_error = $${params.length}`); } + if (extra && extra.clearPrompt) sets.push('ai_prompt = NULL'); const r = await pool.query(`UPDATE farewell_messages SET ${sets.join(', ')} WHERE id = $1 RETURNING *`, params); return r.rows[0] || null; } diff --git a/public/feedback.html b/public/feedback.html index f7cc48b..c3b5f5e 100644 --- a/public/feedback.html +++ b/public/feedback.html @@ -56,6 +56,9 @@ .fb-top-row { display:grid; grid-template-columns:repeat(4, minmax(0,1fr)); gap:12px; margin-bottom:12px; } @media (max-width:700px) { .fb-top-row { grid-template-columns:1fr; gap:8px; } } .fb-top-row .settings-field { display:flex; flex-direction:column; gap:5px; min-width:0; } + .fw-top-row { display:grid; grid-template-columns:repeat(3, minmax(0,1fr)); gap:12px; margin-bottom:12px; } + @media (max-width:700px) { .fw-top-row { grid-template-columns:1fr; gap:8px; } } + .fw-top-row .settings-field { display:flex; flex-direction:column; gap:5px; min-width:0; } .fb-top-row .fb-mark-wrap { width:100%; } #fbResidentPhoto[hidden] { display:none; } .fb-resident-photo { width:34px; height:34px; flex:none; border-radius:50%; overflow:hidden; border:1px solid var(--border); background:var(--bg); cursor:pointer; display:inline-flex; align-items:center; justify-content:center; position:relative; } @@ -78,11 +81,6 @@ .fw-tpl-btns:empty { display:none; } .fw-tpl-btn { font-size:.78rem; padding:4px 10px; border:1px solid var(--border); border-radius:999px; background:rgba(127,127,127,.08); color:var(--text); cursor:pointer; } .fw-tpl-btn:hover, .fw-tpl-btn.active { border-color:var(--accent); color:var(--accent); } - .fw-fb-line1 { display:block; font-size:.78rem; color:var(--muted); } - .fw-fb-line2 { display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; overflow-wrap:anywhere; font-size:.84rem; } - .fw-fb-item { display:flex; align-items:flex-start; gap:8px; padding:8px 10px; border:1px solid var(--border); border-radius:10px; background:rgba(127,127,127,.05); margin-bottom:6px; } - .fw-fb-item input { margin-top:3px; flex:none; } - .fw-fb-item label { min-width:0; flex:1; cursor:pointer; } .fw-ai-pop pre { margin:0; max-height:260px; overflow:auto; white-space:pre-wrap; word-break:break-word; font-size:12px; line-height:1.45; background:rgba(127,127,127,.08); border:1px solid var(--border); border-radius:8px; padding:8px 10px; } .feedback-item { position:relative; } .feedback-item.fb-ai-made { background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 130 100'%3E%3Ctext x='128' y='92' text-anchor='end' font-family='Arial,Helvetica,sans-serif' font-weight='800' font-size='104' fill='%23808080' fill-opacity='0.1'%3EAI%3C/text%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right 6px bottom 2px; background-size:auto 148px; } @@ -254,20 +252,46 @@
-
- - - +
+
+ + +
+
+ + + +
+
+ + +
- - + + +
Выключенный ИИ — текст сохраняется без обработки
-
- -
diff --git a/server.js b/server.js index 5359972..b897d86 100644 --- a/server.js +++ b/server.js @@ -6226,10 +6226,14 @@ app.post('/api/farewells', requireAuth, async (req, res) => { const row = await createFarewell(pool, { resident: req.body?.resident, topic: req.body?.topic, + messageDate: req.body?.message_date, sourceFeedbackIds: req.body?.source_feedback_ids, templateId: req.body?.template_id, prompt: req.body?.prompt, aiProfile: req.body?.ai_profile, + aiCheck: req.body?.ai_check, + text: req.body?.text, + pastReview: req.body?.past_review, authorId: req.user.id, isAdmin: req.user.role === 'admin', branchIds: bs.ids || null, @@ -6251,7 +6255,7 @@ app.post('/api/farewells/:id/ai/retry', requireAuth, async (req, res) => { if (!row) return res.status(404).json({ error: 'Not found' }); if (req.user.role !== 'admin' && row.author_id !== req.user.id) return res.status(403).json({ error: 'Нет доступа' }); if (row.deleted_at) return res.status(400).json({ error: 'Прощальное сообщение удалено' }); - await setFarewellStatus(pool, id, 'pending', { aiError: null }); + await setFarewellStatus(pool, id, 'pending', { aiError: null, clearPrompt: row.ai_status === 'error' }); logAudit(req, 'farewell.ai.retry', { farewell_id: id }); wakeFarewellWorker(); res.json({ ok: true }); @@ -8028,8 +8032,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b const okUser = x.author_id == null || (await client.query('SELECT 1 FROM users WHERE id = $1', [x.author_id])).rowCount; const okTpl = x.template_id == null || x.template_id === x.id || (await client.query('SELECT 1 FROM farewell_messages WHERE id = $1', [x.template_id])).rowCount; await client.query( - 'INSERT INTO farewell_messages (id, resident, topic, source_feedback_ids, template_id, template_text, prompt, ai_profile, ai_status, text, ai_error, ai_prompt, ai_model, ai_duration_ms, author_id, sent_at, deleted_at, purge_at, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,COALESCE($19, now()),COALESCE($20, now()))', - [x.id, x.resident, x.topic, Array.isArray(x.source_feedback_ids) ? x.source_feedback_ids : [], okTpl ? x.template_id : null, x.template_text, x.prompt, x.ai_profile, x.ai_status || 'pending', x.text, x.ai_error, x.ai_prompt, x.ai_model, x.ai_duration_ms, okUser ? x.author_id : null, x.sent_at, x.deleted_at, x.purge_at, x.created_at, x.updated_at] + 'INSERT INTO farewell_messages (id, resident, topic, message_date, source_feedback_ids, template_id, template_text, prompt, ai_profile, ai_status, text, ai_error, ai_prompt, ai_model, ai_duration_ms, author_id, sent_at, deleted_at, purge_at, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,COALESCE($20, now()),COALESCE($21, now()))', + [x.id, x.resident, x.topic, x.message_date, Array.isArray(x.source_feedback_ids) ? x.source_feedback_ids : [], okTpl ? x.template_id : null, x.template_text, x.prompt, x.ai_profile, x.ai_status || 'pending', x.text, x.ai_error, x.ai_prompt, x.ai_model, x.ai_duration_ms, okUser ? x.author_id : null, x.sent_at, x.deleted_at, x.purge_at, x.created_at, x.updated_at] ); } for (const x of ndata.audit_log) { diff --git a/worker.js b/worker.js index f9216bb..c5438fc 100644 --- a/worker.js +++ b/worker.js @@ -1757,10 +1757,15 @@ function createFarewellWorker(opts) { let context = ''; context += `Ученик: ${row.resident || ''}\n`; context += `Тема: ${row.topic || 'не указана'}\n`; + if (row.message_date) context += `Дата прощального сообщения: ${fmtDateRu(row.message_date)}\n`; context += feedbacksBlock + '\n'; if (row.template_text && String(row.template_text).trim()) { context += `Прошлое прощальное сообщение (шаблон):\n${String(row.template_text).slice(0, FEEDBACK_TEXT_CAP)}\n`; } + const draft = row.ai_prompt == null ? String(row.text || '').trim() : ''; + if (draft) { + context += `Черновик автора прощального сообщения (возьми за основу, аккуратно переработай: грамотность, порядок мыслей, стиль):\n${draft.slice(0, FEEDBACK_TEXT_CAP)}\n`; + } let systemPrompt = await resolveFarewellPrompt(row); if (!systemPrompt) systemPrompt = 'Напиши прощальное сообщение об ученике по переданному контексту. Только готовый текст, без пояснений.'; const wish = String(row.prompt || '').trim();