/** * =============================================================================== * FILE: modules/web_api/static/js/chat/topics.js * ROLE: Управление списком сессий чатов (до 15), мгновенный "Новый чат" * и стильное встроенное подтверждение удаления без alert/confirm. * =============================================================================== */ window.TopicsManager = (function() { let activeSessionId = localStorage.getItem("scud_active_chat_session") || "session_main"; let sessionsCache = []; let pendingDeleteSessionId = null; function getActiveSessionId() { return activeSessionId; } async function init() { await loadTopics(); await loadTopicHistory(activeSessionId); } async function loadTopics() { const container = document.getElementById("topics-list-container"); const badge = document.getElementById("topics-count-badge"); if (!container) return; try { const res = await fetch("/api/v1/chat/sessions", { headers: AuthManager.getAuthHeaders() }); if (!res.ok) { if (res.status === 401) return; container.innerHTML = `
Ошибка загрузки чатов (${res.status})
`; return; } const data = await res.json(); sessionsCache = data.sessions || []; if (sessionsCache.length === 0) { await createDefaultTopic(); return; } const exists = sessionsCache.some(s => s.id === activeSessionId); if (!exists && sessionsCache.length > 0) { activeSessionId = sessionsCache[0].id; localStorage.setItem("scud_active_chat_session", activeSessionId); } if (badge) { badge.innerText = `${sessionsCache.length}/15`; } renderTopicsList(); } catch (err) { console.error("Ошибка загрузки списка чатов:", err); container.innerHTML = `
Ошибка соединения с сервером
`; } } async function createDefaultTopic() { try { const res = await fetch("/api/v1/chat/sessions", { method: "POST", headers: { ...AuthManager.getAuthHeaders(), "Content-Type": "application/json" }, body: JSON.stringify({ session_id: "session_main", title: "Основной чат" }) }); if (res.ok) { activeSessionId = "session_main"; localStorage.setItem("scud_active_chat_session", activeSessionId); await loadTopics(); } } catch (e) { console.error("Не удалось создать базовый чат:", e); } } function renderTopicsList() { const container = document.getElementById("topics-list-container"); if (!container) return; if (sessionsCache.length === 0) { container.innerHTML = `
Нет активных чатов
`; return; } container.innerHTML = sessionsCache.map(session => { const isActive = session.id === activeSessionId; const activeClasses = isActive ? "bg-indigo-50 border-indigo-200 text-indigo-900 shadow-xs" : "bg-white hover:bg-slate-50 border-slate-200 text-slate-700"; const title = escapeHtml(session.title || "Новый чат"); const timeStr = session.updated_at ? (session.updated_at.split(" ")[1] || "").slice(0, 5) : ""; return `
${title}
${timeStr ? `${timeStr}` : 'Недавно'}
`; }).join(""); } async function switchTopic(sessionId) { if (!sessionId || sessionId === activeSessionId) return; activeSessionId = sessionId; localStorage.setItem("scud_active_chat_session", activeSessionId); renderTopicsList(); await loadTopicHistory(sessionId); } async function loadTopicHistory(sessionId) { const container = document.getElementById("chat-messages-container"); if (!container) return; container.innerHTML = `
Загрузка сообщений...
`; try { const res = await fetch(`/api/v1/chat/history?session_id=${encodeURIComponent(sessionId)}&limit=50`, { headers: AuthManager.getAuthHeaders() }); if (res.ok) { const data = await res.json(); const history = data.history || []; container.innerHTML = ""; container.insertAdjacentHTML("beforeend", `
ИИ-ассистент SCUD Orion AI
Чат готов к работе. Вы можете задать вопрос по кадровому аудиту, сформировать срез или прикрепить документ.
`); for (const msg of history) { if (msg.role === "user") { appendUserMessage(msg.content); } else if (msg.role === "assistant") { appendAssistantMessage(msg.content); } } container.scrollTop = container.scrollHeight; } else { container.innerHTML = `
Не удалось загрузить историю диалога
`; } } catch (e) { console.error("Ошибка загрузки истории сообщений:", e); container.innerHTML = `
Ошибка соединения при загрузке истории
`; } } async function createNewTopic() { if (sessionsCache.length >= 15) { alert("Достигнут лимит параллельных диалогов (максимум 15 чатов). Удалите неактуальные чаты."); return; } const newSessionId = `chat_${Date.now().toString(36)}`; try { const res = await fetch("/api/v1/chat/sessions", { method: "POST", headers: { ...AuthManager.getAuthHeaders(), "Content-Type": "application/json" }, body: JSON.stringify({ session_id: newSessionId, title: "Новый чат" }) }); if (res.ok) { activeSessionId = newSessionId; localStorage.setItem("scud_active_chat_session", activeSessionId); await loadTopics(); await loadTopicHistory(activeSessionId); const input = document.getElementById("user-input"); if (input) input.focus(); } } catch (err) { console.error("Ошибка создания чата:", err); } } function askDeleteTopic(sessionId, title) { pendingDeleteSessionId = sessionId; const modal = document.getElementById("confirm-modal"); const msgEl = document.getElementById("confirm-modal-message"); if (msgEl) msgEl.innerText = `Удалить диалог «${title}» и всю историю сообщений?`; if (modal) modal.classList.remove("hidden"); } function hideDeleteModal() { pendingDeleteSessionId = null; const modal = document.getElementById("confirm-modal"); if (modal) modal.classList.add("hidden"); } async function executeDeleteTopic() { if (!pendingDeleteSessionId) return; const sessionId = pendingDeleteSessionId; hideDeleteModal(); try { const res = await fetch(`/api/v1/chat/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE", headers: AuthManager.getAuthHeaders() }); if (res.ok) { sessionsCache = sessionsCache.filter(s => s.id !== sessionId); if (activeSessionId === sessionId) { activeSessionId = sessionsCache.length > 0 ? sessionsCache[0].id : "session_main"; localStorage.setItem("scud_active_chat_session", activeSessionId); await loadTopicHistory(activeSessionId); } await loadTopics(); } } catch (e) { console.error("Ошибка удаления чата:", e); } } // ⭐️ Делегирование событий на document: срабатывает всегда, даже если модалка загрузилась позже! document.addEventListener("click", (e) => { if (e.target.closest("#confirm-modal-btn-cancel")) { hideDeleteModal(); } else if (e.target.closest("#confirm-modal-btn-ok")) { executeDeleteTopic(); } }); function openRenameModal(sessionId, currentTitle) { const modal = document.getElementById("rename-topic-modal"); const idInput = document.getElementById("rename-topic-session-id"); const titleInput = document.getElementById("rename-topic-input"); if (idInput) idInput.value = sessionId; if (titleInput) { titleInput.value = currentTitle; setTimeout(() => { titleInput.focus(); titleInput.select(); }, 50); } if (modal) modal.classList.remove("hidden"); } function closeRenameModal() { const modal = document.getElementById("rename-topic-modal"); if (modal) modal.classList.add("hidden"); } async function submitRenameModal(event) { if (event) event.preventDefault(); const sessionId = document.getElementById("rename-topic-session-id")?.value; const newTitle = document.getElementById("rename-topic-input")?.value.trim(); if (!sessionId || !newTitle) return; closeRenameModal(); try { const res = await fetch('/api/v1/chat/sessions/' + encodeURIComponent(sessionId), { method: 'PATCH', headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' }, body: JSON.stringify({ title: newTitle }) }); if (res.ok) { await loadTopics(); } else { console.error("Ошибка сохранения названия темы"); } } catch (e) { console.error("Ошибка сети при переименовании темы:", e); } } return { init, loadTopics, getActiveSessionId, switchTopic, createNewTopic, askDeleteTopic, openRenameModal, closeRenameModal, submitRenameModal }; })();