Spaces:
Sleeping
Sleeping
| const chatForm = document.getElementById("chat-form"); | |
| const userInput = document.getElementById("user-input"); | |
| const chatBox = document.getElementById("chat-box"); | |
| const orderIdEl = document.getElementById("order_id"); | |
| const categoryEl = document.getElementById("category"); | |
| const sentimentEl = document.getElementById("sentiment"); | |
| const negativeBox = document.getElementById("negative-box"); | |
| let sentimentChart = null; | |
| // π§ Append User Message | |
| function appendUser(text) { | |
| chatBox.innerHTML += `<p class="user-msg">π§ You: ${text}</p>`; | |
| chatBox.scrollTop = chatBox.scrollHeight; | |
| } | |
| // π€ Append Bot Message | |
| function appendBot(text) { | |
| chatBox.innerHTML += `<p class="bot-msg">π€ Bot: ${text}</p>`; | |
| chatBox.scrollTop = chatBox.scrollHeight; | |
| } | |
| // β Send chat message | |
| chatForm.addEventListener("submit", async (e) => { | |
| e.preventDefault(); | |
| const text = userInput.value.trim(); | |
| const order_id = orderIdEl.value.trim(); | |
| if (!text) return; | |
| appendUser(text); | |
| userInput.value = ""; | |
| try { | |
| const res = await fetch("/chat", { | |
| method: "POST", | |
| headers: { "Content-Type": "application/x-www-form-urlencoded" }, | |
| body: new URLSearchParams({ user_input: text, order_id }) | |
| }); | |
| const data = await res.json(); | |
| if (data.error) { | |
| appendBot("Sorry, could not process your message."); | |
| return; | |
| } | |
| appendBot(data.reply); | |
| categoryEl.textContent = data.category || "β"; | |
| sentimentEl.textContent = `${data.sentiment || "β"} (${data.confidence || 0}%)`; | |
| await updateAnalytics(); | |
| await updateNegatives(); | |
| } catch (err) { | |
| console.error(err); | |
| appendBot("Network error β try again."); | |
| } | |
| }); | |
| // π Update Analytics Charts | |
| async function updateAnalytics() { | |
| const res = await fetch("/analytics"); | |
| const data = await res.json(); | |
| const ctx = document.getElementById("sentimentChart"); | |
| if (sentimentChart) sentimentChart.destroy(); | |
| sentimentChart = new Chart(ctx, { | |
| type: "pie", | |
| data: { | |
| labels: data.labels, | |
| datasets: [{ | |
| data: data.values, | |
| backgroundColor: ["#2ecc71", "#e74c3c", "#f1c40f"] | |
| }] | |
| } | |
| }); | |
| } | |
| // β οΈ Update Negative Messages Box | |
| async function updateNegatives() { | |
| if (!negativeBox) return; // Safety check | |
| const res = await fetch("/admin/negatives-data"); | |
| const data = await res.json(); | |
| negativeBox.innerHTML = data.length === 0 | |
| ? "<p>No negative messages yet.</p>" | |
| : data.map(msg => | |
| `<p class="neg-item">β οΈ <b>${msg.username}</b>: ${msg.message}</p>` | |
| ).join(""); | |
| } | |
| // auto-refresh negative messages | |
| setInterval(updateNegatives, 8000); | |