/
bibi
/
sber
Обзор
Документация
Войти
/
bibi
/
sber
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
note.js
506 строк
18 KB
bibi
upload files
27 июн 2025, 14:13
27 июн 2025, 14:13
ed09dea
Код
Авторство
О чём код?
// Инициализация при загрузке страницы document.addEventListener("DOMContentLoaded", () => { // Элементы интерфейса const chatBox = document.getElementById("chat-box"); const userInput = document.getElementById("user-input"); const linkInput = document.getElementById("link-input"); const sendBtn = document.getElementById("send-btn"); const loginBtn = document.getElementById("login-btn"); const logoutBtn = document.getElementById("logout-btn"); const summaryBox = document.getElementById("summary-box"); const usernameDisplay = document.getElementById("username-display"); // Добавьте в самое начало вашего скрипта: const WEBHOOK_URL = "http://176.109.111.236:5678/webhook-test/invoke_n8n_agent"; // Элементы авторизации const authModal = document.getElementById("auth-modal"); const closeModal = document.querySelector(".close"); const tabs = document.querySelectorAll(".tab"); const loginForm = document.getElementById("login-form"); const registerForm = document.getElementById("register-form"); const loginSubmit = document.getElementById("login-submit"); const registerSubmit = document.getElementById("register-submit"); const loginError = document.getElementById("login-error"); const registerError = document.getElementById("register-error"); // Проверяем, авторизован ли пользователь checkAuthStatus(); // Приветственное сообщение от бота setTimeout(() => { const currentUser = localStorage.getItem("currentUser"); if (currentUser) { addMessageToChat( "bot", "Привет! Я бот для профориентации, расскажи мне о себе и я помогу тебе с выбором профессии" ); } else { addMessageToChat( "bot", "Привет! Я бот для профориентации. Войдите, чтобы начать общаться." ); // Блокируем поля ввода для гостей userInput.setAttribute("readonly", true); linkInput.setAttribute("readonly", true); userInput.placeholder = "Войдите, чтобы отправлять сообщения"; linkInput.placeholder = "Войдите, чтобы отправлять ссылки"; } }, 1000); // ============== Обработчики чата ============== // ============== Обработчики авторизации ============== loginBtn.addEventListener("click", () => (authModal.style.display = "flex")); closeModal.addEventListener( "click", () => (authModal.style.display = "none") ); logoutBtn.addEventListener("click", logoutUser); // Переключение между вкладками Вход/Регистрация tabs.forEach((tab) => { tab.addEventListener("click", () => { tabs.forEach((t) => t.classList.remove("active")); tab.classList.add("active"); if (tab.dataset.tab === "login") { loginForm.style.display = "block"; registerForm.style.display = "none"; } else { loginForm.style.display = "none"; registerForm.style.display = "block"; } }); }); // Обработчики форм loginSubmit.addEventListener("click", loginUser); registerSubmit.addEventListener("click", registerUser); // Закрытие модального окна при клике вне его window.addEventListener("click", (e) => { if (e.target === authModal) { authModal.style.display = "none"; } }); // Обработка нажатия Enter в основном чате userInput.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendBtn.click(); } }); // Обработка нажатия Enter для ссылок linkInput.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); document.getElementById("send-link-btn").click(); } }); // Обработка нажатия Enter в форме логина document.getElementById("login-username").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); loginUser(); } }); document.getElementById("login-password").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); loginUser(); } }); // Обработка нажатия Enter в форме регистрации document .getElementById("register-username") .addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); registerUser(); } }); document .getElementById("register-password") .addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); registerUser(); } }); document .getElementById("register-confirm") .addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); registerUser(); } }); document .getElementById("send-btn") .addEventListener("click", async function () { const currentUser = localStorage.getItem("currentUser"); if (!currentUser) { alert("Войдите, чтобы отправлять сообщения"); return; } const userText = document.getElementById("user-input").value; if (!userText) { alert("Введите текст!"); return; } addMessageToChat("user", userText); userInput.value = ""; userInput.focus(); try { const loadingMsg = addMessageToChat("bot", "Думаю..."); const response = await fetch( "http://176.109.111.236:7070/webhook/webhook", { method: "POST", headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", "Content-Type": "application/json", }, body: JSON.stringify({ chatInput: userText, sessionId: currentUser, }), } ); console.log(response); chatBox.removeChild(loadingMsg); if (response.ok) { const data = await response.json(); console.log(data); addMessageToChat("bot", data.output); if (data.summary) { summaryBox.innerHTML = data.summary; } } else { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error) { console.error("Ошибка:", error); addMessageToChat( "bot", 'Извините, произошла ошибка, возможно у нас нет данных о вас. Расскажите о себе или пройдите тест <a href="https://careertest.ru/tests/" target="_blank" style="color: #0066cc; text-decoration: underline;">https://careertest.ru/tests/</a>' ); } }); document .getElementById("summary-btn") .addEventListener("click", async function () { const currentUser = localStorage.getItem("currentUser"); if (!currentUser) { alert("Войдите, чтобы видеть сводку"); return; } try { summaryBox.innerHTML = "Думаю..."; const response = await fetch( "http://176.109.111.236:7070/webhook/summary", { method: "POST", headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", "Content-Type": "application/json", }, body: JSON.stringify({ sessionId: currentUser, }), } ); if (response.ok) { const data = await response.json(); let formattedText = data.output; // Заголовки (### Заголовок) formattedText = formattedText.replace( /### (.*?)(\n|$)/g, "<h3>$1</h3>" ); // Полужирный текст (**текст**) formattedText = formattedText.replace( /\*\*(.*?)\*\*/g, "<strong>$1</strong>" ); // Курсив (*текст*) formattedText = formattedText.replace(/\*(.*?)\*/g, "<em>$1</em>"); // Списки formattedText = formattedText.replace( /- (.*?)(\n|$)/g, "<li>$1</li>" ); formattedText = formattedText.replace( /(<li>.*<\/li>)/g, "<ul>$1</ul>" ); // Ссылки ([текст](URL)) formattedText = formattedText.replace( /\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank" style="color: #0066cc; text-decoration: underline;">$1</a>' ); // Переносы строк formattedText = formattedText.replace(/\n/g, "<br>"); // Код (`код`) formattedText = formattedText.replace( /`(.*?)`/g, '<code style="background: #f0f0f0; padding: 2px 5px; border-radius: 3px;">$1</code>' ); summaryBox.innerHTML = formattedText; } else { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error) { console.error("Ошибка:", error); addMessageToChat( "bot", 'Извините, произошла ошибка, возможно у нас нет данных о вас. Расскажите о себе или пройдите тест <a href="https://careertest.ru/tests/" target="_blank" style="color: #0066cc; text-decoration: underline;">https://careertest.ru/tests/</a>' ); } }); document .getElementById("send-link-btn") .addEventListener("click", async function () { const currentUser = localStorage.getItem("currentUser"); if (!currentUser) { alert("Войдите, чтобы отправлять ссылки"); return; } const userLink = document.getElementById("link-input").value; if (!userLink) { alert("Введите ссылку!"); return; } addMessageToChat("user", userLink); linkInput.value = ""; linkInput.focus(); try { const response = await fetch( "http://176.109.111.236:7070/webhook/analytic", { method: "POST", headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", "Content-Type": "application/json", }, body: JSON.stringify({ chatInput: userLink, sessionId: currentUser, }), } ); const responseData = await response.json(); if (response.ok) { alert("Данные отправлены в n8n!"); } else { alert("Ошибка отправки"); } } catch (error) { console.error("Ошибка:", error); } }); // ============== Функции чата ============== function addMessageToChat(sender, text) { const messageElement = document.createElement("div"); messageElement.classList.add("message"); messageElement.classList.add( sender === "bot" ? "bot-message" : "user-message" ); // Форматирование сообщений бота if (sender === "bot") { // Преобразование Markdown в HTML let formattedText = text; // Заголовки (### Заголовок) formattedText = formattedText.replace(/### (.*?)(\n|$)/g, "<h3>$1</h3>"); // Полужирный текст (**текст**) formattedText = formattedText.replace( /\*\*(.*?)\*\*/g, "<strong>$1</strong>" ); // Курсив (*текст*) formattedText = formattedText.replace(/\*(.*?)\*/g, "<em>$1</em>"); // Списки formattedText = formattedText.replace(/- (.*?)(\n|$)/g, "<li>$1</li>"); formattedText = formattedText.replace(/(<li>.*<\/li>)/g, "<ul>$1</ul>"); // Ссылки ([текст](URL)) formattedText = formattedText.replace( /\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank" style="color: #0066cc; text-decoration: underline;">$1</a>' ); // Переносы строк formattedText = formattedText.replace(/\n/g, "<br>"); // Код (`код`) formattedText = formattedText.replace( /`(.*?)`/g, '<code style="background: #f0f0f0; padding: 2px 5px; border-radius: 3px;">$1</code>' ); messageElement.innerHTML = formattedText; } else { // Сообщения пользователя без форматирования (только переносы строк) messageElement.innerHTML = text.replace(/\n/g, "<br>"); } chatBox.appendChild(messageElement); chatBox.scrollTop = chatBox.scrollHeight; return messageElement; } // ============== Функции авторизации ============== function checkAuthStatus() { const currentUser = localStorage.getItem("currentUser"); if (currentUser) { usernameDisplay.textContent = currentUser; loginBtn.style.display = "none"; logoutBtn.style.display = "inline-block"; // Разблокируем поля ввода userInput.removeAttribute("readonly"); linkInput.removeAttribute("readonly"); userInput.placeholder = "Введите ваше сообщение..."; linkInput.placeholder = "Введите ссылку..."; } else { usernameDisplay.textContent = "Гость"; loginBtn.style.display = "inline-block"; logoutBtn.style.display = "none"; // Блокируем поля ввода userInput.setAttribute("readonly", true); linkInput.setAttribute("readonly", true); userInput.placeholder = "Войдите, чтобы отправлять сообщения"; linkInput.placeholder = "Войдите, чтобы отправлять ссылки"; } } function loginUser() { const username = document.getElementById("login-username").value.trim(); const password = document.getElementById("login-password").value; if (!username || !password) { loginError.textContent = "Заполните все поля!"; return; } const users = JSON.parse(localStorage.getItem("users")) || []; const user = users.find( (u) => u.username === username && u.password === password ); if (user) { localStorage.setItem("currentUser", username); authModal.style.display = "none"; checkAuthStatus(); loginError.textContent = ""; // Добавляем приветствие после входа addMessageToChat("bot", `Добро пожаловать, ${username}!`); addMessageToChat( "bot", "Я бот для профориентации, расскажи мне о себе и я помогу тебе с выбором профессии." ); } else { loginError.textContent = "Неверный ник или пароль!"; } } function registerUser() { const username = document.getElementById("register-username").value.trim(); const password = document.getElementById("register-password").value; const confirmPassword = document.getElementById("register-confirm").value; // Валидация if (!username || !password || !confirmPassword) { registerError.textContent = "Заполните все поля!"; return; } if (password !== confirmPassword) { registerError.textContent = "Пароли не совпадают!"; return; } // Проверка существующего пользователя const users = JSON.parse(localStorage.getItem("users") || "[]"); if (users.some((u) => u.username === username)) { registerError.textContent = "Пользователь с таким ником уже существует!"; return; } // Сохранение нового пользователя users.push({ username, password }); localStorage.setItem("users", JSON.stringify(users)); localStorage.setItem("currentUser", username); // Обновление интерфейса authModal.style.display = "none"; checkAuthStatus(); registerError.textContent = ""; // Автоматический вход addMessageToChat("bot", `Добро пожаловать, ${username}!`); addMessageToChat( "bot", "Я бот для профориентации, расскажи мне о себе и я помогу тебе с выбором профессии." ); } function logoutUser() { localStorage.removeItem("currentUser"); checkAuthStatus(); // Добавляем сообщение при выходе addMessageToChat( "bot", "Вы вышли из системы. Войдите, чтобы продолжить общение." ); } });