Прощальные сообщения: модалка на странице отзывов + очередь ИИ
- lib/farewell.js: таблица farewell_messages, create/list/templates/retry, дефолтный промпт - worker.js: createFarewellWorker (очередь pending/processing/done/error, 3 попытки) - server.js: роуты /api/farewells*, SSE farewell_status, уведомления farewell.ai.*, бэкап/restore - feedback.html/js: кнопка и модалка прощального (выбор отзывов ученика, шаблоны-даты, модель/промпт через настройки), список прощальных с retry - db/init.sql + migration.sql: DDL и сиды; backup-restore.js: таблица в бэкапе
This commit is contained in:
+160
@@ -0,0 +1,160 @@
|
||||
const FAREWELL_AI_DEFAULT_PROMPT = [
|
||||
'Ты пишешь прощальное сообщение об ученике образовательного центра — итоговый текст, который зачитывается или отправляется при завершении обучения.',
|
||||
'Пиши по-русски, тёплым, но деловым тоном, от лица центра. Обращение — к коллегам/родителям/ученику, без выдуманных фактов.',
|
||||
'Опирайся только на переданный контекст (отзывы о занятиях, тема, прошлые прощальные сообщения). Не выдумывай события и имена.',
|
||||
'Если дано пожелание (шаблон) — сохрани его смысл и стиль, аккуратно причешите текст: грамотность, порядок мыслей, без канцелярита.',
|
||||
'Объём — 3–6 абзацев максимум. В ответе — только готовый текст прощального сообщения, без пояснений и без Markdown-разметки.',
|
||||
].join('\n');
|
||||
|
||||
const FAREWELL_RESIDENT_MAX = 200;
|
||||
const FAREWELL_TOPIC_MAX = 500;
|
||||
const FAREWELL_PROMPT_MAX = 15000;
|
||||
|
||||
function cleanInts(arr) {
|
||||
if (!Array.isArray(arr)) return [];
|
||||
const out = [];
|
||||
for (const v of arr) {
|
||||
const n = parseInt(v, 10);
|
||||
if (Number.isInteger(n) && n > 0 && !out.includes(n)) out.push(n);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function ensureFarewellTable(pool) {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS farewell_messages (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
resident TEXT NOT NULL,
|
||||
topic TEXT,
|
||||
source_feedback_ids INT[] NOT NULL DEFAULT '{}'::int[],
|
||||
template_id BIGINT REFERENCES farewell_messages(id) ON DELETE SET NULL,
|
||||
template_text TEXT,
|
||||
prompt TEXT,
|
||||
ai_profile TEXT,
|
||||
ai_status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||
text TEXT,
|
||||
ai_error TEXT,
|
||||
ai_prompt TEXT,
|
||||
ai_model TEXT,
|
||||
ai_duration_ms INTEGER,
|
||||
author_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS source_feedback_ids INT[] NOT NULL DEFAULT '{}'::int[]`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS template_id BIGINT`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS template_text TEXT`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS prompt TEXT`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_profile TEXT`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_status VARCHAR(20) NOT NULL DEFAULT 'pending'`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS text TEXT`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_error TEXT`);
|
||||
await pool.query(`ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_prompt TEXT`);
|
||||
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 updated_at TIMESTAMPTZ NOT NULL DEFAULT now()`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_farewell_resident ON farewell_messages (resident)`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_farewell_pending ON farewell_messages (id) WHERE ai_status = 'pending'`);
|
||||
}
|
||||
|
||||
async function createFarewell(pool, data) {
|
||||
const resident = String(data.resident || '').trim();
|
||||
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 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);
|
||||
|
||||
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`;
|
||||
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[])`;
|
||||
}
|
||||
const r = await pool.query(sql, params);
|
||||
const have = new Set(r.rows.map(x => x.id));
|
||||
const missing = ids.filter(id => !have.has(id));
|
||||
if (missing.length) { const e = new Error('Среди выбранных отзывов есть недоступные'); e.status = 403; throw e; }
|
||||
}
|
||||
|
||||
let templateId = parseInt(data.templateId, 10) || null;
|
||||
let templateText = null;
|
||||
if (templateId) {
|
||||
const params = [templateId];
|
||||
let sql = `SELECT text FROM farewell_messages WHERE id = $1 AND ai_status = 'done'`;
|
||||
if (!data.isAdmin) { params.push(data.authorId); sql += ` AND author_id = $${params.length}`; }
|
||||
const r = await pool.query(sql, params);
|
||||
if (!r.rows.length) { templateId = null; templateText = null; }
|
||||
else templateText = r.rows[0].text || null;
|
||||
}
|
||||
|
||||
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]
|
||||
);
|
||||
return ins.rows[0];
|
||||
}
|
||||
|
||||
async function listFarewells(pool, { isAdmin, userId, limit, offset, resident }) {
|
||||
const lim = Math.min(Math.max(parseInt(limit, 10) || 20, 1), 100);
|
||||
const off = Math.max(parseInt(offset, 10) || 0, 0);
|
||||
const params = [];
|
||||
const cond = [];
|
||||
if (!isAdmin) { params.push(userId); cond.push(`author_id = $${params.length}`); }
|
||||
const res = String(resident || '').trim();
|
||||
if (res) { params.push('%' + res + '%'); cond.push(`resident ILIKE $${params.length}`); }
|
||||
const where = cond.length ? 'WHERE ' + cond.join(' AND ') : '';
|
||||
const total = await pool.query(`SELECT count(*)::int AS n FROM farewell_messages ${where}`, params);
|
||||
params.push(lim, off);
|
||||
const rows = await pool.query(
|
||||
`SELECT * FROM farewell_messages ${where} ORDER BY id DESC LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
||||
params
|
||||
);
|
||||
return { items: rows.rows, total: total.rows[0].n };
|
||||
}
|
||||
|
||||
async function listFarewellTemplates(pool, { isAdmin, userId, resident, limit }) {
|
||||
const lim = Math.min(Math.max(parseInt(limit, 10) || 5, 1), 5);
|
||||
const res = String(resident || '').trim();
|
||||
if (!res) return [];
|
||||
const params = ['%' + res + '%'];
|
||||
let sql = `SELECT id, resident, topic, created_at, text FROM farewell_messages WHERE resident ILIKE $1 AND ai_status = 'done' AND COALESCE(text, '') <> ''`;
|
||||
if (!isAdmin) { params.push(userId); sql += ` AND author_id = $${params.length}`; }
|
||||
params.push(lim);
|
||||
sql += ` ORDER BY id DESC LIMIT $${params.length}`;
|
||||
const r = await pool.query(sql, params);
|
||||
return r.rows;
|
||||
}
|
||||
|
||||
async function findFarewell(pool, id) {
|
||||
const r = await pool.query('SELECT * FROM farewell_messages WHERE id = $1', [id]);
|
||||
return r.rows[0] || null;
|
||||
}
|
||||
|
||||
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}`); }
|
||||
const r = await pool.query(`UPDATE farewell_messages SET ${sets.join(', ')} WHERE id = $1 RETURNING *`, params);
|
||||
return r.rows[0] || null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FAREWELL_AI_DEFAULT_PROMPT,
|
||||
FAREWELL_RESIDENT_MAX,
|
||||
FAREWELL_TOPIC_MAX,
|
||||
FAREWELL_PROMPT_MAX,
|
||||
ensureFarewellTable,
|
||||
createFarewell,
|
||||
listFarewells,
|
||||
listFarewellTemplates,
|
||||
findFarewell,
|
||||
setFarewellStatus,
|
||||
};
|
||||
Reference in New Issue
Block a user