farewell: дата, тумблер ИИ и готовый текст в модалке, прошлый отзыв тумблером
This commit is contained in:
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
|
||||
+23
-5
@@ -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;
|
||||
}
|
||||
|
||||
+42
-23
@@ -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 @@
|
||||
<button type="button" class="icon-btn" id="fwSettingsBtn" title="Модель и промпт прощального сообщения"><i data-lucide="settings"></i></button>
|
||||
</div>
|
||||
<form id="fwForm" class="settings-stack" autocomplete="off">
|
||||
<div class="settings-field">
|
||||
<label>Фамилия Имя <span style="color:#ef4444">*</span></label>
|
||||
<input type="text" id="fwResident" class="settings-input" required maxlength="200" placeholder="Иванов Иван" list="fwResidentList" autocomplete="off">
|
||||
<datalist id="fwResidentList"></datalist>
|
||||
<div class="fw-top-row">
|
||||
<div class="settings-field">
|
||||
<label>Дата отзыва</label>
|
||||
<input type="date" id="fwDate" class="settings-input">
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Фамилия Имя <span style="color:#ef4444">*</span></label>
|
||||
<input type="text" id="fwResident" class="settings-input" required maxlength="200" placeholder="Иванов Иван" list="fwResidentList" autocomplete="off">
|
||||
<datalist id="fwResidentList"></datalist>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Тема</label>
|
||||
<input type="text" id="fwTopic" class="settings-input" maxlength="500" placeholder="Тема / повод прощального сообщения" autocomplete="off">
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Тема</label>
|
||||
<input type="text" id="fwTopic" class="settings-input" maxlength="500" placeholder="Тема / повод прощального сообщения" autocomplete="off">
|
||||
<label>Текст прощального сообщения</label>
|
||||
<textarea id="fwText" class="settings-input" rows="8" maxlength="100000" placeholder="Готовый текст — сохранится как есть при выключенном ИИ; при включённом ИИ это черновик, который модель переработает"></textarea>
|
||||
<div class="hint">Выключенный ИИ — текст сохраняется без обработки</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<button type="button" class="btn-primary ghost" id="fwPickBtn" style="text-align:left"><i data-lucide="list-checks"></i> Выберите отзывы для прощального сообщения (отмечены все)</button>
|
||||
<div id="fwFeedbacksWrap" style="display:none;margin-top:8px">
|
||||
<div class="shorts-list" id="fwFeedbacksList"></div>
|
||||
<div class="hint">Эти отзывы будут переданы модели как контекст</div>
|
||||
<div class="settings-stack-grid" style="align-items:start;grid-template-columns:repeat(3,minmax(0,1fr))">
|
||||
<div class="settings-field">
|
||||
<label>Прошлый отзыв</label>
|
||||
<label class="toggle" style="align-items:center;margin:0">
|
||||
<input type="checkbox" id="fwPastCheck" checked>
|
||||
<span class="toggle-track"><span class="toggle-thumb"></span></span>
|
||||
<span class="toggle-text">Добавить</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="fwAiCheck">Сгенерировать отзыв ИИ</label>
|
||||
<label class="toggle" style="align-items:center">
|
||||
<input type="checkbox" id="fwAiCheck" checked>
|
||||
<span class="toggle-track"><span class="toggle-thumb"></span></span>
|
||||
<span class="toggle-text"><small>Отправить в очередь</small></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Модель ИИ</label>
|
||||
<select id="fwModel" class="settings-input"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
@@ -292,11 +316,6 @@
|
||||
<button type="button" class="icon-btn" id="fwSettingsClose" title="Закрыть"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<div class="settings-stack">
|
||||
<div class="settings-field">
|
||||
<label>Модель ИИ</label>
|
||||
<select id="fwModel" class="settings-input"></select>
|
||||
<div class="hint">Пусто или «Нативная» — активная модель системы. Выбор сохраняется кнопкой «Сохранить» и подставляется в новые прощальные</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Шаблон промпта</label>
|
||||
<div class="fb-tpl-row">
|
||||
@@ -316,8 +335,8 @@
|
||||
<div class="fb-key"><code>{resident}</code><span>фамилия и имя ученика</span></div>
|
||||
<div class="fb-key"><code>{topic}</code><span>тема прощального сообщения</span></div>
|
||||
<div class="fb-key"><code>{wishes}</code><span>содержимое поля «Шаблон / пожелания» из модалки прощального</span></div>
|
||||
<div class="fb-key"><code>{feedbacks}</code><span>отзывы, отмеченные галочками: хронологически от старого к новому, каждая запись с датой [ДД.ММ.ГГГГ] — основа содержания</span></div>
|
||||
<div class="fb-key"><code>{context}</code><span>весь контекст целиком: ученик, тема, выбранные отзывы о занятиях, прежнее прощальное сообщение</span></div>
|
||||
<div class="fb-key"><code>{feedbacks}</code><span>прошлые отправленные отзывы об ученике (тумблер «Прошлый отзыв»): хронологически от старого к новому, каждая запись с датой [ДД.ММ.ГГГГ] — основа содержания</span></div>
|
||||
<div class="fb-key"><code>{context}</code><span>весь контекст целиком: ученик, тема, дата, прошлые отзывы о занятиях, прежнее прощальное сообщение, черновик автора</span></div>
|
||||
</div>
|
||||
<div class="hint">Клик по ключу вставляет его в шаблон по позиции курсора. Если шаблон содержит хотя бы один ключ — данные подставляются по ним, и блок «КОНТЕКСТ» автоматически не добавляется. Без ключей контекст уйдёт в модель отдельным сообщением.</div>
|
||||
</div>
|
||||
|
||||
+29
-59
@@ -1181,17 +1181,7 @@
|
||||
ta.setSelectionRange(start + token.length, start + token.length);
|
||||
fwPromptTextSync();
|
||||
});
|
||||
document.getElementById('fwPickBtn').addEventListener('click', () => {
|
||||
const wrap = document.getElementById('fwFeedbacksWrap');
|
||||
if (!wrap) return;
|
||||
if (wrap.style.display === 'none') {
|
||||
const resident = document.getElementById('fwResident').value.trim();
|
||||
if (resident && !fwFbItems.length) loadFwFeedbacks(resident);
|
||||
wrap.style.display = '';
|
||||
} else {
|
||||
wrap.style.display = 'none';
|
||||
}
|
||||
});
|
||||
document.getElementById('fwAiCheck').addEventListener('change', updateFwSubmitLabel);
|
||||
document.getElementById('fwResident').addEventListener('input', onFwResidentChange);
|
||||
document.getElementById('fwTemplateBtns').addEventListener('click', e => {
|
||||
const btn = e.target.closest('[data-fw-template]');
|
||||
@@ -1466,7 +1456,6 @@
|
||||
});
|
||||
|
||||
// --- Прощальное сообщение (farewell) ---
|
||||
let fwFbItems = [];
|
||||
let fwResidentTimer = null;
|
||||
|
||||
function openFarewellModal() {
|
||||
@@ -1487,17 +1476,25 @@
|
||||
function resetFarewellForm() {
|
||||
document.getElementById('fwResident').value = '';
|
||||
document.getElementById('fwTopic').value = '';
|
||||
document.getElementById('fwText').value = '';
|
||||
document.getElementById('fwPrompt').value = '';
|
||||
fwFbItems = [];
|
||||
const list = document.getElementById('fwFeedbacksList');
|
||||
if (list) list.innerHTML = '';
|
||||
const wrap = document.getElementById('fwFeedbacksWrap');
|
||||
if (wrap) wrap.style.display = 'none';
|
||||
document.getElementById('fwDate').value = todayIso();
|
||||
document.getElementById('fwPastCheck').checked = true;
|
||||
document.getElementById('fwAiCheck').checked = true;
|
||||
const btns = document.getElementById('fwTemplateBtns');
|
||||
if (btns) btns.innerHTML = '';
|
||||
updateFwSubmitLabel();
|
||||
hideFwStatus();
|
||||
syncFwModels(true);
|
||||
}
|
||||
function updateFwSubmitLabel() {
|
||||
const chk = document.getElementById('fwAiCheck');
|
||||
const btn = document.getElementById('fwSubmit');
|
||||
if (!btn) return;
|
||||
const on = !!(chk && chk.checked);
|
||||
btn.innerHTML = on ? '<i data-lucide="send"></i> Отправить в очередь' : '<i data-lucide="check"></i> Сохранить';
|
||||
if (window.lucide) lucide.createIcons();
|
||||
}
|
||||
function syncFwModels(reset) {
|
||||
const src = document.getElementById('fbModel');
|
||||
const dst = document.getElementById('fwModel');
|
||||
@@ -1630,53 +1627,22 @@
|
||||
const name = document.getElementById('fwResident').value.trim();
|
||||
clearTimeout(fwResidentTimer);
|
||||
if (!name) {
|
||||
fwFbItems = [];
|
||||
const wrap = document.getElementById('fwFeedbacksWrap');
|
||||
if (wrap) wrap.style.display = 'none';
|
||||
const list = document.getElementById('fwFeedbacksList');
|
||||
if (list) list.innerHTML = '';
|
||||
const btns = document.getElementById('fwTemplateBtns');
|
||||
if (btns) btns.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
fwResidentTimer = setTimeout(() => {
|
||||
loadFwFeedbacks(name);
|
||||
applyFwResidentAutoDate();
|
||||
loadFwTemplates(name);
|
||||
}, 300);
|
||||
}
|
||||
async function loadFwFeedbacks(resident) {
|
||||
const list = document.getElementById('fwFeedbacksList');
|
||||
const wrap = document.getElementById('fwFeedbacksWrap');
|
||||
if (!list || !wrap) return;
|
||||
const exact = normName(resident);
|
||||
try {
|
||||
const q = encodeURIComponent(resident);
|
||||
const [ra, rb] = await Promise.all([
|
||||
fetch(`${API}/api/feedbacks?resident=${q}&limit=100`, { headers: hdr() }),
|
||||
fetch(`${API}/api/feedbacks?resident=${q}&limit=100&status=sent`, { headers: hdr() }),
|
||||
]);
|
||||
const ja = ra.ok ? await ra.json() : { items: [] };
|
||||
const jb = rb.ok ? await rb.json() : { items: [] };
|
||||
const seen = new Set();
|
||||
fwFbItems = [...(ja.items || []), ...(jb.items || [])].filter(f => {
|
||||
if (!f || seen.has(f.id)) return false;
|
||||
seen.add(f.id);
|
||||
return normName(f.resident) === exact;
|
||||
}).sort((x, y) => (y.id - x.id)).slice(0, 60);
|
||||
if (!fwFbItems.length) {
|
||||
list.innerHTML = '<div class="hint">Отзывов по этому ученику не найдено</div>';
|
||||
wrap.style.display = '';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = fwFbItems.map(f => {
|
||||
const text = (f.text || '').replace(/\s+/g, ' ').slice(0, 160);
|
||||
return `<div class="fw-fb-item"><input type="checkbox" name="fwFeedback" value="${f.id}" checked><label><span class="fw-fb-line1">${escapeHtml(f.feedback_date || '')} – ${escapeHtml(f.topic || '-')}</span><span class="fw-fb-line2">${escapeHtml(text)}</span></label></div>`;
|
||||
}).join('');
|
||||
wrap.style.display = '';
|
||||
} catch (e) {
|
||||
list.innerHTML = '<div class="hint">Ошибка загрузки отзывов</div>';
|
||||
wrap.style.display = '';
|
||||
}
|
||||
function applyFwResidentAutoDate() {
|
||||
const idEl = document.getElementById('fwDate');
|
||||
if (!idEl) return;
|
||||
const k = normName(document.getElementById('fwResident').value);
|
||||
if (!k || !residentGroups.has(k)) return;
|
||||
const last = residentLastDates.get(k) || '';
|
||||
idEl.value = (last && last >= weekAgoIso()) ? last : todayIso();
|
||||
}
|
||||
async function loadFwTemplates(resident) {
|
||||
const wrap = document.getElementById('fwTemplateBtns');
|
||||
@@ -1696,11 +1662,14 @@
|
||||
e.preventDefault();
|
||||
const resident = document.getElementById('fwResident').value.trim();
|
||||
if (!resident) { showFwStatus('Укажите фамилию и имя ученика'); return; }
|
||||
const ids = [...document.querySelectorAll('#fwFeedbacksList input[name="fwFeedback"]:checked')].map(i => parseInt(i.value, 10)).filter(Number.isInteger);
|
||||
const aiCheck = document.getElementById('fwAiCheck').checked;
|
||||
const body = {
|
||||
resident,
|
||||
topic: document.getElementById('fwTopic').value.trim() || null,
|
||||
source_feedback_ids: ids,
|
||||
message_date: document.getElementById('fwDate').value || null,
|
||||
past_review: document.getElementById('fwPastCheck').checked,
|
||||
ai_check: aiCheck,
|
||||
text: document.getElementById('fwText').value.trim() || null,
|
||||
prompt: document.getElementById('fwPrompt').value.trim() || null,
|
||||
ai_profile: document.getElementById('fwModel').value || null,
|
||||
};
|
||||
@@ -1709,7 +1678,7 @@
|
||||
try {
|
||||
const r = await fetch(`${API}/api/farewells`, { method: 'POST', headers: { ...hdr(), 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!r.ok) { showFwStatus(j.error || 'Не удалось отправить в очередь'); if (btn) btn.disabled = false; return; }
|
||||
if (!r.ok) { showFwStatus(j.error || 'Не удалось сохранить'); if (btn) btn.disabled = false; return; }
|
||||
closeFarewellModal();
|
||||
loadFarewells();
|
||||
} catch (e2) {
|
||||
@@ -1762,6 +1731,7 @@
|
||||
${actions}
|
||||
</div>
|
||||
${f.resident ? `<div class="lesson-group">${escapeHtml(f.resident)}</div>` : ''}
|
||||
${f.message_date ? `<div class="lesson-topic">Дата отзыва: ${escapeHtml(fmtDate(f.message_date))}</div>` : ''}
|
||||
${f.topic ? `<div class="lesson-topic">${escapeHtml(f.topic)}</div>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user