farewell: корзина, отметка отправки, быстрое редактирование, карточки списка
This commit is contained in:
@@ -607,6 +607,9 @@ function normalizeRestoreData(data) {
|
||||
ai_model: optStr(r.ai_model, 200),
|
||||
ai_duration_ms: optInt(r.ai_duration_ms, 0, 86400000),
|
||||
author_id: optInt(r.author_id),
|
||||
sent_at: optTs(r.sent_at),
|
||||
deleted_at: optTs(r.deleted_at),
|
||||
purge_at: optTs(r.purge_at),
|
||||
created_at: optTs(r.created_at),
|
||||
updated_at: optTs(r.updated_at),
|
||||
}));
|
||||
|
||||
@@ -680,6 +680,9 @@ CREATE TABLE IF NOT EXISTS farewell_messages (
|
||||
ai_model TEXT,
|
||||
ai_duration_ms INTEGER,
|
||||
author_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
sent_at TIMESTAMPTZ,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
purge_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
@@ -889,6 +889,9 @@ ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_prompt TEXT;
|
||||
ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_model TEXT;
|
||||
ALTER TABLE farewell_messages ADD COLUMN IF NOT EXISTS ai_duration_ms INTEGER;
|
||||
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 updated_at TIMESTAMPTZ DEFAULT now();
|
||||
|
||||
|
||||
|
||||
+69
-8
@@ -38,6 +38,9 @@ async function ensureFarewellTable(pool) {
|
||||
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()
|
||||
)
|
||||
@@ -54,6 +57,9 @@ 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 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'`);
|
||||
@@ -87,7 +93,7 @@ async function createFarewell(pool, data) {
|
||||
let templateText = null;
|
||||
if (templateId) {
|
||||
const params = [templateId];
|
||||
let sql = `SELECT text FROM farewell_messages WHERE id = $1 AND ai_status = 'done'`;
|
||||
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; }
|
||||
@@ -102,19 +108,24 @@ async function createFarewell(pool, data) {
|
||||
return ins.rows[0];
|
||||
}
|
||||
|
||||
async function listFarewells(pool, { isAdmin, userId, limit, offset, resident }) {
|
||||
async function listFarewells(pool, { isAdmin, userId, limit, offset, resident, deleted }) {
|
||||
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}`); }
|
||||
if (!isAdmin) { params.push(userId); cond.push(`f.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);
|
||||
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');
|
||||
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 * FROM farewell_messages ${where} ORDER BY id DESC LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
||||
`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 };
|
||||
@@ -125,7 +136,7 @@ async function listFarewellTemplates(pool, { isAdmin, userId, resident, limit })
|
||||
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, '') <> ''`;
|
||||
let sql = `SELECT id, resident, topic, created_at, text FROM farewell_messages WHERE resident ILIKE $1 AND ai_status = 'done' AND COALESCE(text, '') <> '' AND deleted_at IS NULL`;
|
||||
if (!isAdmin) { params.push(userId); sql += ` AND author_id = $${params.length}`; }
|
||||
params.push(lim);
|
||||
sql += ` ORDER BY id DESC LIMIT $${params.length}`;
|
||||
@@ -146,6 +157,50 @@ async function setFarewellStatus(pool, id, status, extra) {
|
||||
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,
|
||||
@@ -157,4 +212,10 @@ module.exports = {
|
||||
listFarewellTemplates,
|
||||
findFarewell,
|
||||
setFarewellStatus,
|
||||
updateFarewellText,
|
||||
setFarewellSent,
|
||||
farewellForUser,
|
||||
deleteFarewell,
|
||||
restoreFarewell,
|
||||
deleteFarewellPermanent,
|
||||
};
|
||||
|
||||
+39
-1
@@ -64,6 +64,13 @@
|
||||
#fbPromptModal { overflow:auto; align-items:flex-start; padding:4vh 16px; }
|
||||
#fbPromptModal > .edit-modal { margin:auto; }
|
||||
#fbQuickModal { z-index:105; }
|
||||
#fwQuickModal { z-index:105; }
|
||||
.fw-text { position:relative; max-height:130px; overflow:hidden; }
|
||||
.fw-text.open { max-height:none; }
|
||||
.fw-text:not(.open)::after { content:''; position:absolute; left:0; right:0; bottom:0; height:30px; background:linear-gradient(rgba(255,255,255,0), var(--card)); pointer-events:none; }
|
||||
.fw-text-more { display:none; align-self:flex-end; font-size:.72rem; padding:2px 8px; }
|
||||
.fw-text-more.visible { display:inline-flex; }
|
||||
.fb-ai-pop .fb-ai-sep { border-top:1px solid var(--border); margin-top:4px; padding-top:10px; }
|
||||
#fbImgbbModal { z-index:110; }
|
||||
#fwSettingsModal { z-index:105; overflow:auto; align-items:flex-start; padding:4vh 16px; }
|
||||
#fwSettingsModal > .edit-modal { margin:auto; }
|
||||
@@ -150,7 +157,9 @@
|
||||
<div class="hint" id="feedbackState" style="margin-bottom:12px"></div>
|
||||
<div class="feedback-list" id="feedbackList"><div class="empty">Загрузка…</div></div>
|
||||
<div class="pager" id="pager"></div>
|
||||
<div class="hint" id="farewellState" style="margin:20px 0 8px;font-weight:600">Прощальные сообщения</div>
|
||||
<div class="hint" id="farewellState" style="margin:20px 0 8px;font-weight:600;display:flex;align-items:center;gap:14px;flex-wrap:wrap">Прощальные сообщения
|
||||
<label class="toggle" style="font-weight:400"><input type="checkbox" id="fwDeletedToggle"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text">Удалённые</span></label>
|
||||
</div>
|
||||
<div class="feedback-list" id="farewellList"><div class="empty">Пока нет прощальных сообщений</div></div>
|
||||
</main>
|
||||
</div>
|
||||
@@ -485,6 +494,35 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="fwQuickModal">
|
||||
<div class="edit-modal" style="max-width:760px;width:96%;max-height:92dvh;overflow-y:auto">
|
||||
<div class="fb-modal-head">
|
||||
<h3>Быстрое редактирование прощального сообщения</h3>
|
||||
<button type="button" class="icon-btn" id="fwQuickClose" title="Закрыть"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<div class="settings-stack">
|
||||
<div class="fb-quick-head" id="fwQuickHead">
|
||||
<div id="fwQuickPhotoWrap"></div>
|
||||
<div class="fb-quick-meta">
|
||||
<div class="fb-quick-resident" id="fwQuickResident">—</div>
|
||||
<div class="fb-quick-topic" id="fwQuickTopic" hidden></div>
|
||||
<div class="fb-quick-date" id="fwQuickDate"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Текст прощального сообщения</label>
|
||||
<textarea id="fwQuickText" class="settings-input" rows="8" maxlength="100000" placeholder="Текст прощального сообщения"></textarea>
|
||||
<div class="hint" id="fwQuickTextHint">0 / 100000</div>
|
||||
</div>
|
||||
<div class="card-foot" style="justify-content:flex-end;gap:8px">
|
||||
<button type="button" class="btn-primary ghost" id="fwQuickCancel">Отмена</button>
|
||||
<button type="button" class="btn-primary" id="fwQuickSave">Сохранить</button>
|
||||
<button type="button" class="btn-primary" id="fwQuickSaveSend" style="background:#fff;color:#333;border:1px solid #ccc">сохр и отпр</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="vendor/lucide.min.js"></script>
|
||||
<script src="js/datetime.js"></script>
|
||||
<script src="admin.js"></script>
|
||||
|
||||
+171
-16
@@ -23,13 +23,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
function fbAuthorHtml(f) {
|
||||
function fbAuthorHtml(f, label) {
|
||||
const name = String(f.author_name || f.author_username || '').trim();
|
||||
if (!name) return '';
|
||||
const av = f.author_avatar
|
||||
? `<span class="fb-author-av"><img src="${escapeHtml(thumbSrc(f.author_avatar))}" alt="" loading="lazy"></span>`
|
||||
: `<span class="fb-author-av">${escapeHtml(name.charAt(0).toUpperCase())}</span>`;
|
||||
return `<span class="fb-author" title="Автор отзыва: ${escapeHtml(name)}">${av}<span class="fb-author-name">${escapeHtml(name)}</span></span>`;
|
||||
return `<span class="fb-author" title="${escapeHtml(label || 'Автор отзыва')}: ${escapeHtml(name)}">${av}<span class="fb-author-name">${escapeHtml(name)}</span></span>`;
|
||||
}
|
||||
|
||||
function fbItemHtml(f) {
|
||||
@@ -1197,7 +1197,48 @@
|
||||
const btn = e.target.closest('[data-fw-template]');
|
||||
if (btn) document.getElementById('fwPrompt').value = btn.dataset.fwText || '';
|
||||
});
|
||||
document.getElementById('farewellList').addEventListener('click', e => {
|
||||
document.getElementById('farewellList').addEventListener('click', async e => {
|
||||
const moreBtn = e.target.closest('[data-fw-more]');
|
||||
if (moreBtn) {
|
||||
const wrap = moreBtn.previousElementSibling;
|
||||
if (wrap && wrap.classList.contains('fw-text')) {
|
||||
const open = wrap.classList.toggle('open');
|
||||
moreBtn.textContent = open ? 'Свернуть' : 'Показать полностью';
|
||||
}
|
||||
return;
|
||||
}
|
||||
const aiinfo = e.target.closest('[data-aiinfo]');
|
||||
if (aiinfo) {
|
||||
const pop = document.getElementById(`fwAiPop-${aiinfo.dataset.aiinfo}`);
|
||||
if (pop) { const wasOpen = !pop.hidden; closeAiPops(); pop.hidden = wasOpen; }
|
||||
return;
|
||||
}
|
||||
const sentBtn = e.target.closest('[data-sent]');
|
||||
if (sentBtn) {
|
||||
const id = parseInt(sentBtn.dataset.sent, 10);
|
||||
if (!id) return;
|
||||
const f = fwItems.find(x => parseInt(x.id, 10) === id);
|
||||
const next = !(f && f.sent_at);
|
||||
try { const r = await fetch(`${API}/api/farewells/${id}/sent`, { method:'PUT', headers: {...hdr(), 'Content-Type':'application/json'}, body: JSON.stringify({ sent: next }) }); if (r.ok) loadFarewells(); } catch (e2) {}
|
||||
return;
|
||||
}
|
||||
const quickBtn = e.target.closest('[data-quick]'); if (quickBtn) { openFwQuickModal(parseInt(quickBtn.dataset.quick, 10)); return; }
|
||||
const del = e.target.closest('[data-del]'); if (del) {
|
||||
const id = parseInt(del.dataset.id || del.dataset.del, 10);
|
||||
if (!id) return;
|
||||
const row = fwItems.find(x => parseInt(x.id, 10) === id);
|
||||
const perm = !!(row && row.deleted_at);
|
||||
if (!confirm(perm ? 'Удалить прощальное сообщение навсегда? Это действие нельзя отменить.' : 'Удалить прощальное сообщение?')) return;
|
||||
const url = perm ? `${API}/api/farewells/${id}/permanent` : `${API}/api/farewells/${id}`;
|
||||
try { const r = await fetch(url, { method: 'DELETE', headers: hdr() }); if (r.ok) loadFarewells(); } catch (e2) {}
|
||||
return;
|
||||
}
|
||||
const restore = e.target.closest('[data-restore]'); if (restore) {
|
||||
const id = parseInt(restore.dataset.restore, 10);
|
||||
if (!id) return;
|
||||
try { const r = await fetch(`${API}/api/farewells/${id}/restore`, { method: 'PUT', headers: hdr() }); if (r.ok) loadFarewells(); } catch (e2) {}
|
||||
return;
|
||||
}
|
||||
const btn = e.target.closest('[data-fw-retry]');
|
||||
if (!btn) return;
|
||||
btn.disabled = true;
|
||||
@@ -1205,6 +1246,16 @@
|
||||
.then(r => { if (r.ok) loadFarewells(); else btn.disabled = false; })
|
||||
.catch(() => { btn.disabled = false; });
|
||||
});
|
||||
const fwQuickClose = document.getElementById('fwQuickClose');
|
||||
if (fwQuickClose) {
|
||||
fwQuickClose.addEventListener('click', closeFwQuickModal);
|
||||
document.getElementById('fwQuickCancel').addEventListener('click', closeFwQuickModal);
|
||||
document.getElementById('fwQuickSave').addEventListener('click', () => saveFwQuick(false));
|
||||
document.getElementById('fwQuickSaveSend').addEventListener('click', () => saveFwQuick(true));
|
||||
document.getElementById('fwQuickText').addEventListener('input', setFwTextHint);
|
||||
document.getElementById('fwQuickModal').addEventListener('click', e => { if (e.target.id === 'fwQuickModal') closeFwQuickModal(); });
|
||||
document.getElementById('fwDeletedToggle').addEventListener('change', loadFarewells);
|
||||
}
|
||||
loadFarewells();
|
||||
document.getElementById('fbPromptText').addEventListener('input', promptTextSync);
|
||||
document.getElementById('fbPromptTpl').addEventListener('change', e => {
|
||||
@@ -1666,38 +1717,142 @@
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
function fwGroupName(resident) {
|
||||
const gid = residentGroups.get(normName(resident));
|
||||
if (!gid) return '';
|
||||
const sel = document.getElementById('fbGroupFilter');
|
||||
const opt = sel ? sel.querySelector(`option[value="${gid}"]`) : null;
|
||||
return opt ? opt.textContent : '';
|
||||
}
|
||||
|
||||
function fwAiInfoHtml(f) {
|
||||
const srcCount = Array.isArray(f.source_feedback_ids) ? f.source_feedback_ids.length : 0;
|
||||
const ctx = `<div class="fb-ai-row fb-ai-sep"><span>Отзывов в контексте</span><b>${srcCount}</b></div>`;
|
||||
return fbAiInfoHtml(f) + ctx;
|
||||
}
|
||||
|
||||
function fwItemHtml(f) {
|
||||
const when = f.created_at ? fmtTs(f.created_at) : '';
|
||||
const srcCount = Array.isArray(f.source_feedback_ids) ? f.source_feedback_ids.length : 0;
|
||||
const retry = f.ai_status === 'error' ? `<button type="button" class="btn-xs" data-fw-retry="${f.id}">Повторить</button>` : '';
|
||||
const body = (f.ai_status === 'done' && f.text)
|
||||
? `<div class="lesson-text" style="white-space:pre-wrap">${linkifyTextHtml(f.text)}</div>`
|
||||
: (f.ai_status === 'error' ? `<div class="fb-ai-err">${escapeHtml(f.ai_error || 'Ошибка обработки')}</div>` : '');
|
||||
return `<div class="lesson-item feedback-item">
|
||||
<div class="fb-card-group-row">
|
||||
<div class="lesson-author">${escapeHtml(f.resident || '')}</div>
|
||||
<div class="lesson-when">${escapeHtml(when)}</div>
|
||||
<div class="lesson-actions">${aiBadge(f.ai_status)}${retry}</div>
|
||||
const hasAiInfo = f.ai_status !== 'none' || !!f.ai_prompt;
|
||||
const aiDone = f.ai_status === 'done';
|
||||
const aiMade = aiDone ? ' fb-ai-made' : '';
|
||||
const del = f.deleted_at ? ' style="opacity:.5"' : '';
|
||||
const retry = f.ai_status === 'error' && !f.deleted_at ? `<button type="button" class="btn-link" data-fw-retry="${f.id}">Повторить</button>` : '';
|
||||
const actions = (hasAiInfo || retry || !f.deleted_at) ? `<div class="lesson-actions">
|
||||
${hasAiInfo ? `<button type="button" class="btn-link" data-aiinfo="${f.id}">AI</button>` : ''}
|
||||
${retry}
|
||||
${f.deleted_at ? '' : `<button type="button" class="btn-link" data-sent="${f.id}">${f.sent_at ? 'Вернуть' : 'Отправлено'}</button>`}
|
||||
${f.deleted_at ? '' : `<button type="button" class="icon-btn" data-quick="${f.id}" title="Быстрое редактирование"><i data-lucide="zap"></i></button>`}
|
||||
<button type="button" class="icon-btn danger" data-del="${f.id}" title="${f.deleted_at ? 'Удалить навсегда' : 'Удалить'}"><i data-lucide="trash-2"></i></button>
|
||||
${f.deleted_at ? `<button type="button" class="btn-link" data-restore="${f.id}">Восстановить</button>` : ''}
|
||||
</div>` : '';
|
||||
const body = (aiDone && f.text)
|
||||
? `<div class="fw-text"><div class="lesson-text">${linkifyTextHtml(f.text)}</div></div>
|
||||
<button type="button" class="btn-link fw-text-more" data-fw-more>Показать полностью</button>`
|
||||
: (f.ai_status === 'error' && !f.deleted_at ? `<div class="fb-ai-err">${escapeHtml(f.ai_error || 'Ошибка обработки')}</div>` : '');
|
||||
const gname = fwGroupName(f.resident);
|
||||
return `<div class="lesson-item feedback-item${aiMade}" data-id="${f.id}"${del}>
|
||||
${f.deleted_at ? `<div class="fb-card-meta"><span class="lesson-badge">Удалено</span></div>` : ''}
|
||||
<div class="fb-card-resident">
|
||||
${cardResidentPhoto(f.resident)}
|
||||
<div class="fb-card-info">
|
||||
<div class="fb-card-group-row">
|
||||
${gname ? `<span class="lesson-author">${escapeHtml(gname)}</span>` : ''}
|
||||
<span class="lesson-when">${escapeHtml(when)}</span>
|
||||
${actions}
|
||||
</div>
|
||||
${f.resident ? `<div class="lesson-group">${escapeHtml(f.resident)}</div>` : ''}
|
||||
${f.topic ? `<div class="lesson-topic">${escapeHtml(f.topic)}</div>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
${f.topic ? `<div class="fb-card-info"><span class="lesson-topic">${escapeHtml(f.topic)}</span></div>` : ''}
|
||||
${body}
|
||||
<div class="fb-card-foot"><span class="hint">Отзывов в контексте: ${srcCount}${f.ai_model ? ' · модель: ' + escapeHtml(f.ai_model) : ''}</span></div>
|
||||
<div class="fb-card-foot">
|
||||
${aiBadge(f.ai_status)}
|
||||
${f.sent_at ? '<span class="ai-badge ai-badge-sent">Отправлено</span>' : ''}
|
||||
${fbAuthorHtml(f, 'Автор прощального сообщения')}
|
||||
</div>
|
||||
<div class="fb-ai-pop" id="fwAiPop-${f.id}" hidden>${fwAiInfoHtml(f)}</div>
|
||||
</div>`;
|
||||
}
|
||||
let fwItems = [];
|
||||
async function loadFarewells() {
|
||||
const el = document.getElementById('farewellList');
|
||||
if (!el) return;
|
||||
const q = new URLSearchParams({ limit: '10' });
|
||||
const dt = document.getElementById('fwDeletedToggle');
|
||||
if (dt && dt.checked) q.set('deleted', '1');
|
||||
try {
|
||||
const r = await fetch(`${API}/api/farewells?limit=10`, { headers: hdr() });
|
||||
const r = await fetch(`${API}/api/farewells?${q}`, { headers: hdr() });
|
||||
if (!r.ok) { el.innerHTML = '<div class="empty">Ошибка загрузки прощальных сообщений</div>'; return; }
|
||||
const j = await r.json();
|
||||
const items = j.items || [];
|
||||
fwItems = items;
|
||||
el.innerHTML = items.length ? items.map(fwItemHtml).join('') : '<div class="empty">Пока нет прощальных сообщений</div>';
|
||||
el.querySelectorAll('.fw-text').forEach(w => {
|
||||
if (w.scrollHeight > w.clientHeight + 2) { const b = w.nextElementSibling; if (b && b.classList.contains('fw-text-more')) b.classList.add('visible'); }
|
||||
});
|
||||
if (window.lucide) lucide.createIcons();
|
||||
} catch (e) {
|
||||
el.innerHTML = '<div class="empty">Ошибка сети</div>';
|
||||
}
|
||||
}
|
||||
|
||||
let quickFarewell = null;
|
||||
function setFwTextHint() {
|
||||
const ta = document.getElementById('fwQuickText');
|
||||
const hint = document.getElementById('fwQuickTextHint');
|
||||
if (ta && hint) hint.textContent = `${ta.value.length} / 100000`;
|
||||
}
|
||||
async function openFwQuickModal(id) {
|
||||
const m = document.getElementById('fwQuickModal');
|
||||
const f = fwItems.find(x => parseInt(x.id, 10) === id);
|
||||
if (!m || !f) return;
|
||||
quickFarewell = f;
|
||||
m.classList.add('open');
|
||||
try { await loadStudentPhotos(); } catch (e) {}
|
||||
const wrap = document.getElementById('fwQuickPhotoWrap');
|
||||
if (wrap) wrap.innerHTML = cardResidentPhoto(f.resident);
|
||||
const res = document.getElementById('fwQuickResident');
|
||||
if (res) res.textContent = f.resident || 'Резидент не указан';
|
||||
const topic = document.getElementById('fwQuickTopic');
|
||||
if (topic) { topic.textContent = f.topic || ''; topic.hidden = !f.topic; }
|
||||
const date = document.getElementById('fwQuickDate');
|
||||
if (date) date.textContent = fmtTs(f.created_at);
|
||||
const ta = document.getElementById('fwQuickText');
|
||||
if (ta) ta.value = f.text || '';
|
||||
setFwTextHint();
|
||||
if (window.lucide) lucide.createIcons();
|
||||
}
|
||||
function closeFwQuickModal() {
|
||||
const m = document.getElementById('fwQuickModal');
|
||||
if (m) m.classList.remove('open');
|
||||
quickFarewell = null;
|
||||
}
|
||||
async function saveFwQuick(send) {
|
||||
if (!quickFarewell) return;
|
||||
const ta = document.getElementById('fwQuickText');
|
||||
if (!ta) return;
|
||||
const id = quickFarewell.id;
|
||||
const btn = send ? document.getElementById('fwQuickSaveSend') : document.getElementById('fwQuickSave');
|
||||
const prev = btn ? btn.textContent : '';
|
||||
try {
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Сохранение...'; }
|
||||
const r = await fetch(`${API}/api/farewells/${id}`, { method: 'PUT', headers: {...hdr(), 'Content-Type':'application/json'}, body: JSON.stringify({ text: ta.value.trim() }) });
|
||||
if (r.ok) {
|
||||
if (send) {
|
||||
try { await fetch(`${API}/api/farewells/${id}/sent`, { method:'PUT', headers: {...hdr(), 'Content-Type':'application/json'}, body: JSON.stringify({ sent: true }) }); } catch (e) {}
|
||||
}
|
||||
closeFwQuickModal(); loadFarewells(); return;
|
||||
}
|
||||
const err = await r.json().catch(() => null);
|
||||
alert((err && err.error) || `Ошибка ${r.status}`);
|
||||
} catch (e) {
|
||||
alert('Ошибка сети');
|
||||
} finally {
|
||||
if (btn) { btn.disabled = false; btn.textContent = prev; }
|
||||
}
|
||||
}
|
||||
|
||||
let liveSource = null, liveReconnectTimer = null; function connectFeedbackLive() {
|
||||
if (liveSource) { liveSource.close(); liveSource = null; }
|
||||
const connect = () => {
|
||||
|
||||
@@ -67,7 +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 { ensureFarewellTable, createFarewell, listFarewells, listFarewellTemplates, findFarewell, setFarewellStatus, updateFarewellText, setFarewellSent, farewellForUser, deleteFarewell, restoreFarewell, deleteFarewellPermanent, 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 {
|
||||
@@ -1738,6 +1738,8 @@ async function purgeScheduledDeletions() {
|
||||
await pool.query('DELETE FROM user_notes WHERE purge_at IS NOT NULL AND purge_at <= now()');
|
||||
const fbres = await pool.query('DELETE FROM feedbacks WHERE purge_at IS NOT NULL AND purge_at <= now()');
|
||||
const fbcount = fbres.rowCount;
|
||||
const fwres = await pool.query('DELETE FROM farewell_messages WHERE purge_at IS NOT NULL AND purge_at <= now()');
|
||||
const fwcount = fwres.rowCount;
|
||||
const bires = await pool.query('DELETE FROM broken_images WHERE purge_at IS NOT NULL AND purge_at <= now()');
|
||||
const bicount = bires.rowCount;
|
||||
const strefs = await pool.query('SELECT id FROM students WHERE purge_at IS NOT NULL AND purge_at <= now()');
|
||||
@@ -1760,7 +1762,7 @@ async function purgeScheduledDeletions() {
|
||||
if (fbcount) invalidateFeedbacks();
|
||||
if (stcount) invalidateStudents();
|
||||
if (bicount) invalidateAll();
|
||||
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount, students: stcount, broken_images: bicount };
|
||||
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount, farewell_messages: fwcount, students: stcount, broken_images: bicount };
|
||||
}
|
||||
|
||||
function safeUnlink(relPath) {
|
||||
@@ -6209,6 +6211,7 @@ app.get('/api/farewells', requireAuth, async (req, res) => {
|
||||
limit: req.query.limit,
|
||||
offset: req.query.offset,
|
||||
resident: req.query.resident,
|
||||
deleted: req.query.deleted === '1' || req.query.deleted === 'true',
|
||||
});
|
||||
res.json({ items, total });
|
||||
} catch (err) {
|
||||
@@ -6247,12 +6250,106 @@ app.post('/api/farewells/:id/ai/retry', requireAuth, async (req, res) => {
|
||||
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: 'Нет доступа' });
|
||||
if (row.deleted_at) return res.status(400).json({ error: 'Прощальное сообщение удалено' });
|
||||
await setFarewellStatus(pool, id, 'pending', { aiError: null });
|
||||
logAudit(req, 'farewell.ai.retry', { farewell_id: id });
|
||||
wakeFarewellWorker();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.put('/api/farewells/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const { row, notFound, forbidden } = await farewellForUser(pool, id, req.user);
|
||||
if (notFound) return res.status(404).json({ error: 'Not found' });
|
||||
if (forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
if (row.deleted_at) return res.status(400).json({ error: 'Прощальное сообщение удалено' });
|
||||
const text = typeof req.body?.text === 'string' ? req.body.text.slice(0, 100000) : null;
|
||||
if (text == null) return res.status(400).json({ error: 'Некорректный текст' });
|
||||
if (!text.trim()) return res.status(400).json({ error: 'Введите текст сообщения' });
|
||||
const upd = await updateFarewellText(pool, id, text.trim());
|
||||
if (!upd) return res.status(400).json({ error: 'Прощальное сообщение удалено' });
|
||||
logAudit(req, 'farewell.update', { farewell_id: id });
|
||||
res.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/farewells/:id/sent', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const { row, notFound, forbidden } = await farewellForUser(pool, id, req.user);
|
||||
if (notFound) return res.status(404).json({ error: 'Not found' });
|
||||
if (forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
if (row.deleted_at) return res.status(400).json({ error: 'Прощальное сообщение удалено' });
|
||||
const sent = typeof req.body?.sent === 'boolean' ? req.body.sent : null;
|
||||
if (sent === null) return res.status(400).json({ error: 'Некорректный статус' });
|
||||
const upd = await setFarewellSent(pool, id, sent);
|
||||
if (!upd) return res.status(400).json({ error: 'Прощальное сообщение удалено' });
|
||||
logAudit(req, 'farewell.sent', { farewell_id: id, sent });
|
||||
res.json({ ok: true, sent });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/farewells/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const { notFound, forbidden } = await farewellForUser(pool, id, req.user);
|
||||
if (notFound) return res.status(404).json({ error: 'Not found' });
|
||||
if (forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const days = await trashPurgeDays();
|
||||
const ok = await deleteFarewell(pool, id, days);
|
||||
if (!ok) return res.status(404).json({ error: 'Уже удалено' });
|
||||
logAudit(req, 'farewell.delete', { farewell_id: id });
|
||||
res.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/farewells/:id/restore', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const { notFound, forbidden } = await farewellForUser(pool, id, req.user);
|
||||
if (notFound) return res.status(404).json({ error: 'Not found' });
|
||||
if (forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const ok = await restoreFarewell(pool, id);
|
||||
if (!ok) return res.status(404).json({ error: 'Не удалено' });
|
||||
logAudit(req, 'farewell.restore', { farewell_id: id });
|
||||
res.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/farewells/:id/permanent', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||
const { notFound, forbidden } = await farewellForUser(pool, id, req.user);
|
||||
if (notFound) return res.status(404).json({ error: 'Not found' });
|
||||
if (forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const ok = await deleteFarewellPermanent(pool, id);
|
||||
if (!ok) return res.status(404).json({ error: 'Не удалено' });
|
||||
logAudit(req, 'farewell.permanent-delete', { farewell_id: id });
|
||||
res.json({ ok: true });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Internal error' });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
app.delete('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
|
||||
if (req.params.id === String(req.user.id)) {
|
||||
@@ -7931,8 +8028,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, 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]
|
||||
'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]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.audit_log) {
|
||||
|
||||
@@ -1695,7 +1695,7 @@ function createFarewellWorker(opts) {
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const q = `SELECT * FROM farewell_messages
|
||||
WHERE ai_status = 'pending'
|
||||
WHERE ai_status = 'pending' AND deleted_at IS NULL
|
||||
ORDER BY id ASC
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1`;
|
||||
@@ -1893,7 +1893,7 @@ function createFarewellWorker(opts) {
|
||||
|
||||
async function resetStale() {
|
||||
try {
|
||||
await pool.query(`UPDATE farewell_messages SET ai_status='pending', ai_error=NULL WHERE ai_status='processing'`);
|
||||
await pool.query(`UPDATE farewell_messages SET ai_status='pending', ai_error=NULL WHERE ai_status='processing' AND deleted_at IS NULL`);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user