/
bibi
/
sber
Обзор
Документация
Войти
/
bibi
/
sber
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
child
note.js
305 строк
11 KB
bibi
upload files
25 июн 2025, 15:44
25 июн 2025, 15:44
1902bdd
Код
Авторство
О чём код?
// Инициализация при загрузке страницы document.addEventListener("DOMContentLoaded", () => { // Элементы интерфейса const chatBox = document.getElementById("chat-box"); const userInput = document.getElementById("user-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(() => { addMessageToChat( "bot", "Привет! Я бот для профориентации. Давайте начнем тестирование. Ответьте на несколько вопросов, и я помогу определить ваши профессиональные склонности." ); }, 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"; } }); document .getElementById("send-btn") .addEventListener("click", async function () { const userText = document.getElementById("user-input").value; if (!userText) { alert("Введите текст!"); return; } addMessageToChat("user", userText); userInput.value = ""; userInput.focus(); try { const loadingMsg = addMessageToChat("bot", "Думаю..."); const currentUser = localStorage.getItem("currentUser") || "Гость"; const response = await fetch( "http://176.109.111.236:5678/webhook-test/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, }), } ); chatBox.removeChild(loadingMsg); if (response.ok) { const data = await response.json(); addMessageToChat("bot", data.response); if (data.summary) { summaryBox.innerHTML = data.summary; } } else { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error) { console.error("Ошибка:", error); addMessageToChat( "bot", "Извините, произошла ошибка. Пожалуйста, попробуйте позже." ); } }); document .getElementById("summary-btn") .addEventListener("click", async function () { try { const loadingMsg = addMessageToChat("bot", "Думаю..."); const currentUser = localStorage.getItem("currentUser") || "Гость"; const response = await fetch( "http://176.109.111.236:5678/webhook-test/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({ sessionId: currentUser, }), } ); chatBox.removeChild(loadingMsg); if (response.ok) { const data = await response.json(); summaryBox.innerHTML = data.summary; } else { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error) { console.error("Ошибка:", error); addMessageToChat( "bot", "Извините, произошла ошибка. Пожалуйста, попробуйте позже." ); } }); document .getElementById("send-link-btn") .addEventListener("click", async function () { const userLink = document.getElementById("link-input").value; if (!userLink) { alert("Введите текст!"); return; } addMessageToChat("user", userLink); userInput.value = ""; userInput.focus(); try { const currentUser = localStorage.getItem("currentUser") || "Гость"; const response = await fetch( "http://176.109.111.236:5678/webhook-test/test", { 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({ testLink: userLink, }), } ); const responseData = await response.json(); if (response.ok) { alert("Данные отправлены в n8n!"); } else { alert("Ошибка отправки"); } } catch (error) { console.error("Ошибка:", error); } sendMessage(); }); // ============== Функции чата ============== function addMessageToChat(sender, text) { const messageElement = document.createElement("div"); messageElement.classList.add("message"); messageElement.classList.add( sender === "bot" ? "bot-message" : "user-message" ); messageElement.textContent = text; 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"; } else { usernameDisplay.textContent = "Гость"; loginBtn.style.display = "inline-block"; logoutBtn.style.display = "none"; } } 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 = ""; } 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}!`); } function logoutUser() { localStorage.removeItem("currentUser"); checkAuthStatus(); } });