Files
WhatIDo/lib/farewell.js
T

240 lines
12 KiB
JavaScript

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,
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,
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,
sent_at TIMESTAMPTZ,
deleted_at TIMESTAMPTZ,
purge_at TIMESTAMPTZ,
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 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`);
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 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 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();
}
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' AND deleted_at IS NULL`;
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, 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];
}
async function listFarewells(pool, { isAdmin, userId, limit, offset, resident, deleted, sent }) {
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(`f.author_id = $${params.length}`); }
const res = String(resident || '').trim();
if (res) { params.push('%' + res + '%'); cond.push(`f.resident ILIKE $${params.length}`); }
cond.push(deleted ? 'f.deleted_at IS NOT NULL' : 'f.deleted_at IS NULL');
if (sent === true) cond.push('f.sent_at IS NOT NULL');
else if (sent === false) cond.push('f.sent_at IS NULL');
const where = 'WHERE ' + cond.join(' AND ');
const total = await pool.query(`SELECT count(*)::int AS n FROM farewell_messages f ${where}`, params);
params.push(lim, off);
const rows = await pool.query(
`SELECT f.*, u.name AS author_name, u.username AS author_username, u.avatar AS author_avatar
FROM farewell_messages f
LEFT JOIN users u ON u.id = f.author_id
${where}
ORDER BY f.id DESC LIMIT $${params.length - 1} OFFSET $${params.length}`,
params
);
return { items: rows.rows, total: total.rows[0].n };
}
async function listFarewellTemplates(pool, { userId, limit }) {
const lim = Math.min(Math.max(parseInt(limit, 10) || 10, 1), 20);
const r = await pool.query(
`SELECT id, resident, topic, created_at, text FROM farewell_messages
WHERE author_id = $1 AND ai_status = 'done' AND COALESCE(text, '') <> '' AND deleted_at IS NULL
ORDER BY id DESC LIMIT $2`,
[userId, lim]
);
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}`); }
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;
}
async function updateFarewellText(pool, id, text) {
const r = await pool.query(
`UPDATE farewell_messages SET text = $2, updated_at = now() WHERE id = $1 AND deleted_at IS NULL RETURNING *`,
[id, text]
);
return r.rows[0] || null;
}
async function setFarewellSent(pool, id, sent) {
const r = await pool.query(
`UPDATE farewell_messages SET sent_at = $2, updated_at = now() WHERE id = $1 AND deleted_at IS NULL RETURNING *`,
[id, sent ? new Date() : null]
);
return r.rows[0] || null;
}
async function farewellForUser(pool, id, user) {
const row = await findFarewell(pool, id);
if (!row) return { notFound: true };
if (user && user.role !== 'admin' && row.author_id !== user.id) return { forbidden: true };
return { row };
}
async function deleteFarewell(pool, id, days) {
const r = await pool.query(
`UPDATE farewell_messages SET deleted_at = now(), purge_at = now() + ($2 || ' days')::interval WHERE id = $1 AND deleted_at IS NULL`,
[id, String(days)]
);
return r.rowCount > 0;
}
async function restoreFarewell(pool, id) {
const r = await pool.query(
`UPDATE farewell_messages SET deleted_at = NULL, purge_at = NULL WHERE id = $1 AND deleted_at IS NOT NULL`,
[id]
);
return r.rowCount > 0;
}
async function deleteFarewellPermanent(pool, id) {
const r = await pool.query(`DELETE FROM farewell_messages WHERE id = $1 AND deleted_at IS NOT NULL`, [id]);
return r.rowCount > 0;
}
module.exports = {
FAREWELL_AI_DEFAULT_PROMPT,
FAREWELL_RESIDENT_MAX,
FAREWELL_TOPIC_MAX,
FAREWELL_PROMPT_MAX,
ensureFarewellTable,
createFarewell,
listFarewells,
listFarewellTemplates,
findFarewell,
setFarewellStatus,
updateFarewellText,
setFarewellSent,
farewellForUser,
deleteFarewell,
restoreFarewell,
deleteFarewellPermanent,
};