File size: 4,046 Bytes
2f2549b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
console.log("script.js loaded");

document.addEventListener("DOMContentLoaded", () => {
    console.log("DOM ready");

    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");

    function getCSRFToken() {
        const el = document.querySelector('[name=csrfmiddlewaretoken]');
        return el ? el.value : "";
    }

    function appendUser(text) {
        chatBox.innerHTML += `<p class="user-msg">🧑 ${text}</p>`;
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    function appendBot(text) {
        chatBox.innerHTML += `<p class="bot-msg">🤖 ${text}</p>`;
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    // ================= CHAT =================
    if (chatForm) {
        chatForm.addEventListener("submit", async (e) => {
            e.preventDefault();

            const text = userInput.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",
                        "X-CSRFToken": getCSRFToken()
                    },
                    body: new URLSearchParams({
                        user_input: text,
                        order_id: orderIdEl ? orderIdEl.value : ""
                    })
                });

                const data = await res.json();
                console.log("chat response:", data);

                appendBot(data.reply);

                if (categoryEl) categoryEl.textContent = data.category;
                if (sentimentEl) {
                    sentimentEl.textContent =
                        `${data.sentiment} (${data.confidence}%)`;
                }

                updateAnalytics();
                updateNegatives();

            } catch (err) {
                console.error(err);
                appendBot("Network error");
            }
        });
    }
});

// ================= ANALYTICS =================
async function updateAnalytics() {
    try {
        const res = await fetch("/analytics/");
        const data = await res.json();

        console.log("analytics data:", data);

        const canvas = document.getElementById("sentimentChart");
        if (!canvas || typeof Chart === "undefined") return;

        // 🔥 HARD RESET (NO destroy() CALL)
        if (window.sentimentChart) {
            window.sentimentChart = null;
        }

        window.sentimentChart = new Chart(canvas, {
            type: "pie",
            data: {
                labels: data.labels,
                datasets: [{
                    data: data.values,
                    backgroundColor: ["#2ecc71", "#e74c3c", "#f1c40f"]
                }]
            }
        });

    } catch (err) {
        console.error("analytics error:", err);
    }
}

// ================= RECENT NEGATIVES =================
async function updateNegatives() {
    try {
        const box = document.getElementById("negative-box");
        if (!box) return;

        const res = await fetch("/recent-negatives/");
        const data = await res.json();

        box.innerHTML = data.length === 0
            ? "<p>No negative messages</p>"
            : data.map(n =>
                `<p>⚠️ <b>${n.username}</b>: ${n.message}</p>`
            ).join("");

    } catch (err) {
        console.error("negatives error:", err);
    }
}

// ================= AUTO REFRESH =================
setInterval(() => {
    updateAnalytics();
    updateNegatives();
}, 5000);