Прощальные сообщения: модалка на странице отзывов + очередь ИИ
- 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:
@@ -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, createNoteTitleWorker, createFaceScanWorker, createDigestPublisher } = require('./worker');
|
||||
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, createDigestPublisher, createFarewellWorker } = require('./worker');
|
||||
const { createZipWriter, renderStudentReport } = require('./student-report');
|
||||
|
||||
const { createStorage, mimeFor } = require('./storage');
|
||||
@@ -67,6 +67,7 @@ const { lessonReportWriteBlocked } = require('./lib/lesson-reports');
|
||||
const { groupOwnedBy } = require('./lib/groups');
|
||||
const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes');
|
||||
const { resolveImgbbEndpoint, friendlyApiError } = require('./lib/feedback-imgbb');
|
||||
const { ensureFarewellTable, createFarewell, listFarewells, listFarewellTemplates, findFarewell, setFarewellStatus, FAREWELL_AI_DEFAULT_PROMPT } = require('./lib/farewell');
|
||||
const { aiHttpErrorFromResponse, aiHttpErrorText, aiHttpErrorDetail } = require('./lib/ai-errors');
|
||||
const { findBrokenFaceRefs, scanAllBrokenFaceRefs, cleanupAllBrokenFaceRefs, deleteFaceRef } = require('./lib/photo-cleanup');
|
||||
const {
|
||||
@@ -222,6 +223,7 @@ 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';
|
||||
const FAREWELL_WAKE_CHANNEL = 'whatido:wake:farewell';
|
||||
const FACE_SCAN_WAKE_CHANNEL = 'whatido:wake:face-scan';
|
||||
|
||||
function createWorkerBus(channel) {
|
||||
@@ -261,6 +263,10 @@ function dispatchEvent(payload) {
|
||||
writeFrame('feedback_status', payload);
|
||||
return;
|
||||
}
|
||||
if (payload && payload.type === 'farewell_status') {
|
||||
writeFrame('farewell_status', payload);
|
||||
return;
|
||||
}
|
||||
if (payload && payload.type === 'face_scan_status') {
|
||||
writeFrame('face_scan_status', {
|
||||
source_type: payload.source_type,
|
||||
@@ -367,6 +373,8 @@ const NOTIFY_TYPES = {
|
||||
'lesson.ai.formatted': { label: 'Отчёт оформлен по шаблону', hint: 'ИИ привёл текст отчёта о занятии к деловому виду', icon: 'file-check', level: 'info', enabled: false, admin: false },
|
||||
'feedback.ai.ready': { label: 'Отзыв сгенерирован', hint: 'ИИ сформировал отзыв по результатам занятия', icon: 'message-square-heart', level: 'info', enabled: true, admin: false },
|
||||
'feedback.ai.error': { label: 'Ошибка генерации отзыва', hint: 'ИИ не смог обработать отзыв после всех попыток', icon: 'message-square-x', level: 'warning', enabled: true, admin: false },
|
||||
'farewell.ai.done': { label: 'Прощальное сообщение готово', hint: 'ИИ сформировал прощальное сообщение об ученике', icon: 'mail-x', level: 'info', enabled: true, admin: true },
|
||||
'farewell.ai.error': { label: 'Ошибка прощального сообщения', hint: 'ИИ не смог сформировать прощальное сообщение после всех попыток', icon: 'mail-warning', level: 'warning', enabled: true, admin: true },
|
||||
'face.scan.done': { label: 'Найдены лица на фото', hint: 'Фоновая проверка нашла лица на загруженном фото. Сколько именно — в тексте уведомления', icon: 'scan-face', level: 'info', enabled: false, admin: false },
|
||||
'face.recognized': { label: 'Ученики распознаны на фото', hint: 'Фоновая проверка сопоставила лица с эталонами и назвала учеников', icon: 'user-round-check', level: 'info', enabled: true, admin: false },
|
||||
'face.scan.error': { label: 'Ошибка проверки лиц', hint: 'Сервис face-id недоступен или очередь проверки исчерпала попытки', icon: 'scan-search', level: 'warning', enabled: true, admin: false },
|
||||
@@ -2948,6 +2956,7 @@ async function ensureUsersAndFirstAdmin() {
|
||||
await ensureDocsTables(pool);
|
||||
await ensureBackupTicketsTable(pool);
|
||||
await ensureDigestTable(pool);
|
||||
await ensureFarewellTable(pool);
|
||||
await ensureFirstAdmin();
|
||||
}
|
||||
|
||||
@@ -6177,6 +6186,74 @@ app.post('/api/feedbacks/requeue-failed', requireAuth, requireAdmin, async (req,
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/farewells/templates', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const items = await listFarewellTemplates(pool, {
|
||||
isAdmin: req.user.role === 'admin',
|
||||
userId: req.user.id,
|
||||
resident: req.query.resident,
|
||||
limit: 5,
|
||||
});
|
||||
res.json({ items });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/farewells', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const { items, total } = await listFarewells(pool, {
|
||||
isAdmin: req.user.role === 'admin',
|
||||
userId: req.user.id,
|
||||
limit: req.query.limit,
|
||||
offset: req.query.offset,
|
||||
resident: req.query.resident,
|
||||
});
|
||||
res.json({ items, total });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/farewells', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const bs = branchScope(req.user);
|
||||
const row = await createFarewell(pool, {
|
||||
resident: req.body?.resident,
|
||||
topic: req.body?.topic,
|
||||
sourceFeedbackIds: req.body?.source_feedback_ids,
|
||||
templateId: req.body?.template_id,
|
||||
prompt: req.body?.prompt,
|
||||
aiProfile: req.body?.ai_profile,
|
||||
authorId: req.user.id,
|
||||
isAdmin: req.user.role === 'admin',
|
||||
branchIds: bs.ids || null,
|
||||
});
|
||||
logAudit(req, 'farewell.create', { farewell_id: row.id, resident: row.resident, sources: (row.source_feedback_ids || []).length });
|
||||
wakeFarewellWorker();
|
||||
res.status(201).json(row);
|
||||
} catch (err) {
|
||||
const status = err.status || 500;
|
||||
if (status === 500) console.error(err);
|
||||
res.status(status).json({ error: err.message || 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/farewells/:id/ai/retry', requireAuth, async (req, res) => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const row = await findFarewell(pool, id);
|
||||
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: 'Нет доступа' });
|
||||
await setFarewellStatus(pool, id, 'pending', { aiError: null });
|
||||
logAudit(req, 'farewell.ai.retry', { farewell_id: id });
|
||||
wakeFarewellWorker();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
|
||||
app.delete('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
|
||||
if (req.params.id === String(req.user.id)) {
|
||||
return res.status(400).json({ error: 'Нельзя удалить самого себя' });
|
||||
@@ -6855,6 +6932,11 @@ let feedbackWorker = null;
|
||||
let noteAiWorker = null;
|
||||
let faceScanWorker = null;
|
||||
let digestPublisher = null;
|
||||
let farewellWorker = null;
|
||||
|
||||
function wakeFarewellWorker() {
|
||||
if (farewellWorker) farewellWorker.notify();
|
||||
}
|
||||
|
||||
function wakeFaceScanWorker() {
|
||||
if (faceScanWorker) faceScanWorker.notify();
|
||||
@@ -7086,6 +7168,42 @@ async function onFeedbackDone({ row, status, text, aiText, error }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onFarewellDone({ row, status, text, error }) {
|
||||
cache.publish(EVENTS_CHANNEL, {
|
||||
type: 'farewell_status',
|
||||
id: row.id,
|
||||
ai_status: status,
|
||||
status,
|
||||
error: error || null,
|
||||
text: text === undefined ? null : text,
|
||||
ts: Date.now()
|
||||
}).catch(() => {});
|
||||
if (status === 'done') {
|
||||
try {
|
||||
await pushNotification({
|
||||
type: 'farewell.ai.done',
|
||||
title: `Прощальное сообщение готово: ${row.resident || 'ученик'}`,
|
||||
body: String(text || '').slice(0, 300),
|
||||
link: 'feedback.html',
|
||||
target: { farewell_id: row.id, resident: row.resident || null },
|
||||
adminOnly: true,
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
if (status === 'error') {
|
||||
try {
|
||||
await pushNotification({
|
||||
type: 'farewell.ai.error',
|
||||
title: `Не удалось создать прощальное сообщение: ${row.resident || 'ученик'}`,
|
||||
body: String(error || 'Ошибка обработки').slice(0, 300),
|
||||
link: 'feedback.html',
|
||||
target: { farewell_id: row.id, resident: row.resident || null },
|
||||
adminOnly: true,
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
async function aiCorrectText(text, profileOverride) {
|
||||
try {
|
||||
const systemPrompt = await getAiPrompt();
|
||||
@@ -7145,7 +7263,7 @@ function backupUploadGuard(req, res, next) {
|
||||
async function buildBackupArchive() {
|
||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
||||
try {
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi] = await Promise.all([
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi, fm] = await Promise.all([
|
||||
pool.query('SELECT * FROM groups ORDER BY id'),
|
||||
pool.query('SELECT * FROM students ORDER BY id'),
|
||||
pool.query('SELECT * FROM entries ORDER BY id'),
|
||||
@@ -7186,6 +7304,7 @@ async function buildBackupArchive() {
|
||||
pool.query('SELECT * FROM student_achievements ORDER BY id'),
|
||||
pool.query('SELECT * FROM digests ORDER BY id'),
|
||||
pool.query('SELECT * FROM digest_images ORDER BY id'),
|
||||
pool.query('SELECT * FROM farewell_messages ORDER BY id'),
|
||||
]);
|
||||
const settings = {};
|
||||
st.rows.forEach(r => { settings[r.key] = r.value; });
|
||||
@@ -7207,13 +7326,13 @@ async function buildBackupArchive() {
|
||||
achievement_types: atr.rowCount, student_achievements: sar.rowCount,
|
||||
doc_sections: ds.rowCount, doc_articles: da.rowCount, doc_images: di.rowCount,
|
||||
doc_files: df.rowCount, sidebar_items: si.rowCount,
|
||||
digests: dg.rowCount, digest_images: dgi.rowCount,
|
||||
digests: dg.rowCount, digest_images: dgi.rowCount, farewell_messages: fm.rowCount,
|
||||
},
|
||||
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows, student_work_marks: swm.rows,
|
||||
achievement_types: atr.rows, student_achievements: sar.rows,
|
||||
doc_sections: ds.rows, doc_articles: da.rows, doc_images: di.rows,
|
||||
doc_files: df.rows, sidebar_items: si.rows,
|
||||
digests: dg.rows, digest_images: dgi.rows,
|
||||
digests: dg.rows, digest_images: dgi.rows, farewell_messages: fm.rows,
|
||||
};
|
||||
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||
const files = await storage.downloadAll(path.join(staging, 'uploads'));
|
||||
@@ -7467,6 +7586,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await client.query('DELETE FROM chat_messages');
|
||||
await client.query('DELETE FROM chat_threads');
|
||||
await client.query('DELETE FROM short_messages');
|
||||
await client.query('DELETE FROM farewell_messages');
|
||||
await client.query('DELETE FROM student_work_marks');
|
||||
await client.query('DELETE FROM project_files');
|
||||
await client.query('DELETE FROM lesson_report_versions');
|
||||
@@ -7795,6 +7915,14 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
[x.id, okFb ? x.feedback_id : null, x.text || '', x.source || 'manual', okUser ? x.author_id : null, x.created_at]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.farewell_messages || [])) {
|
||||
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, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,COALESCE($16, now()),COALESCE($17, 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.created_at, x.updated_at]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.audit_log) {
|
||||
const okUser = x.user_id == null || (await client.query('SELECT 1 FROM users WHERE id = $1', [x.user_id])).rowCount;
|
||||
await client.query(
|
||||
@@ -15482,6 +15610,17 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
|
||||
});
|
||||
feedbackWorker.start();
|
||||
console.log('Feedback AI worker started');
|
||||
farewellWorker = createFarewellWorker({
|
||||
pool,
|
||||
getSetting,
|
||||
logAudit,
|
||||
aiUrl: AI_URL,
|
||||
defaultPrompt: FAREWELL_AI_DEFAULT_PROMPT,
|
||||
bus: createWorkerBus(FAREWELL_WAKE_CHANNEL),
|
||||
onDone: onFarewellDone,
|
||||
});
|
||||
farewellWorker.start();
|
||||
console.log('Farewell AI worker started');
|
||||
noteAiWorker = createNoteTitleWorker({
|
||||
pool,
|
||||
getSetting,
|
||||
|
||||
Reference in New Issue
Block a user