Compare commits

..

1 Commits
main ... pages

View File

@ -96,8 +96,16 @@ const knowledgeBase = {
} }
}; };
// === История чата в localStorage === // === История чата в localStorage (ключ уникальный для этого чата) ===
let chatHistory = JSON.parse(localStorage.getItem('chatHistory') || '[]'); const STORAGE_KEY = 'zakupkiChatHistory_v1';
let chatHistory = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
// Миграция: если есть старая история без ключа версии — очищаем
const oldHistory = localStorage.getItem('chatHistory');
if (oldHistory) {
localStorage.removeItem('chatHistory');
chatHistory = [];
}
// === Инициализация === // === Инициализация ===
function init() { function init() {
@ -124,7 +132,7 @@ function sendMessage() {
const userMsg = { const userMsg = {
role: 'user', role: 'user',
text: question, text: question,
time: new Date().toISOString() time: Date.now()
}; };
chatHistory.push(userMsg); chatHistory.push(userMsg);
@ -133,12 +141,12 @@ function sendMessage() {
const assistantMsg = { const assistantMsg = {
role: 'assistant', role: 'assistant',
text: response, text: response,
time: new Date().toISOString() time: Date.now()
}; };
chatHistory.push(assistantMsg); chatHistory.push(assistantMsg);
// Сохраняем и рисуем // Сохраняем и рисуем
localStorage.setItem('chatHistory', JSON.stringify(chatHistory)); localStorage.setItem(STORAGE_KEY, JSON.stringify(chatHistory));
input.value = ''; input.value = '';
renderMessages(); renderMessages();
scrollToBottom(); scrollToBottom();
@ -183,14 +191,18 @@ function renderMessages() {
} }
chatHistory.forEach(msg => { chatHistory.forEach(msg => {
// Проверка на битые сообщения
if (!msg || !msg.text || !msg.time) return;
const div = document.createElement('div'); const div = document.createElement('div');
div.className = `chat-message ${msg.role}`; div.className = `chat-message ${msg.role}`;
const time = new Date(msg.time).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }); const date = new Date(msg.time);
const time = isNaN(date.getTime()) ? '' : date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
div.innerHTML = ` div.innerHTML = `
<div class="chat-bubble">${escapeHtml(msg.text)}</div> <div class="chat-bubble">${escapeHtml(msg.text)}</div>
<div class="message-time">${time}</div> ${time ? `<div class="message-time">${time}</div>` : ''}
`; `;
container.appendChild(div); container.appendChild(div);
}); });