-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessChatAI.js
More file actions
334 lines (274 loc) · 11.7 KB
/
ProcessChatAI.js
File metadata and controls
334 lines (274 loc) · 11.7 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
$(document).ready(function() {
// instantiate WireTabs if defined
if (typeof ProcessWire.config.JqueryWireTabs === 'object') {
$('body.ProcessChatAI #pw-content-body').WireTabs({
items: $(".WireTab"),
id: 'chatai-tabs'
});
} else {
console.log(typeof ProcessWire.config.JqueryWireTabs)
}
});
document.addEventListener('DOMContentLoaded', function () {
var form = document.querySelector('form[name="chat-ai-settings"], form#chat-ai-settings');
if (!form) return;
var activeSubmit = null;
var actionLabels = {
rag_run_reindex: {
normal: 'Running re-index...',
dryRun: 'Running dry run...'
},
rag_run_remove: {
normal: 'Running bulk removal...',
dryRun: 'Checking matched pages...'
}
};
form.addEventListener('click', function (event) {
var button = event.target.closest('input[type="submit"], button[type="submit"]');
if (!button || !form.contains(button)) return;
if (button.name && actionLabels[button.name]) {
activeSubmit = button;
}
});
form.addEventListener('submit', function (event) {
if (event.submitter && event.submitter.name && actionLabels[event.submitter.name]) {
activeSubmit = event.submitter;
}
if (!activeSubmit || !actionLabels[activeSubmit.name]) return;
var labels = actionLabels[activeSubmit.name];
var dryRun = false;
if (activeSubmit.name === 'rag_run_reindex') {
dryRun = !!form.querySelector('[name="rag_dry_run"]:checked');
} else if (activeSubmit.name === 'rag_run_remove') {
dryRun = !!form.querySelector('[name="rag_remove_dry_run"]:checked');
}
activeSubmit.value = dryRun ? labels.dryRun : labels.normal;
activeSubmit.setAttribute('aria-busy', 'true');
if (!form.querySelector('input[type="hidden"][data-chatai-submit="' + activeSubmit.name + '"]')) {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = activeSubmit.name;
hidden.value = '1';
hidden.setAttribute('data-chatai-submit', activeSubmit.name);
form.appendChild(hidden);
}
requestAnimationFrame(function () {
activeSubmit.disabled = true;
});
});
});
/* Dashboard Components */
document.addEventListener('DOMContentLoaded', function () {
if (typeof Chart === 'undefined') return;
var hasChart = (typeof Chart !== 'undefined');
var eventsChart = null;
var elEvents = document.getElementById('chatai-chart-events');
var t = window.chatAIDashboard || {};
// Range links
var picker = document.querySelector('.chatai-range-picker');
var rangeLinks = picker ? picker.querySelectorAll('.chatai-range-link') : null;
// Volume chart
var volumeCanvas = document.getElementById('chatai-chart-volume');
var volumeChart = null;
function reloadKpis(days) {
if (!t.kpiUrl) return;
var url = t.kpiUrl + '&days=' + encodeURIComponent(days);
fetch(url, { credentials: 'same-origin' })
.then(function(res) {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(function(s) {
if (!s) return;
setText('kpi-chats', s.total_chats);
setText('kpi-chats-note', `in the last ${s.range_days} days`);
setText('kpi-messages', s.total_messages);
var ec = (parseInt(s.total_errors || 0, 10) + parseInt(s.total_cutoffs || 0, 10));
setText('kpi-errors-cutoffs', ec);
setText('kpi-errors-cutoffs-note', 'Errors: ' + (s.total_errors || 0) + ', cutoffs: ' + (s.total_cutoffs || 0));
setText('kpi-blocked', s.total_blocked || 0);
setText('kpi-blocked-note', 'Blocked: ' + (s.total_blocked || 0) + ', rate limited: ' + (s.rate_limited || 0));
updateEventsChart({
reply: s.total_replies,
cutoff: s.total_cutoffs,
blocked: s.total_blocked,
rate_limit: s.rate_limited
});
})
.catch(function(err) {
console.error('ChatAI: failed to load KPI snapshot:', err);
});
}
function setText(id, v) {
var el = document.getElementById(id);
if (el) el.textContent = (v === null || typeof v === 'undefined') ? '' : String(v);
}
function loadVolumeData(days) {
if (!t.volumeUrl || !volumeCanvas) return;
var url = t.volumeUrl + '&days=' + encodeURIComponent(days);
fetch(url, { credentials: 'same-origin' })
.then(function (res) {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(function (data) {
if (!data || !data.labels || !data.totals) return;
var ctx = volumeCanvas.getContext('2d');
if (!volumeChart) {
volumeChart = new Chart(ctx, {
type: 'line',
data: {
labels: data.labels,
datasets: [{
label: t.requestsLabel || 'Requests',
data: data.totals,
tension: 0.25
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: 'bottom'
}
},
scales: {
x: { ticks: { maxRotation: 0 } },
y: {
beginAtZero: true,
ticks: { precision: 0 }
}
}
}
});
} else {
volumeChart.data.labels = data.labels;
volumeChart.data.datasets[0].data = data.totals;
volumeChart.update();
}
})
.catch(function (err) {
console.error('ChatAI: failed to load volume data:', err);
});
}
// var eventsChart = null;
function normalizeEventSummary(summary) {
summary = summary || {};
return {
reply: parseInt(summary.reply, 10) || 0,
cutoff: parseInt(summary.cutoff, 10) || 0,
blocked: parseInt(summary.blocked, 10) || 0,
rate_limit: parseInt(summary.rate_limit, 10) || 0
};
}
function mapEventLabel(key) {
if (key === 'reply') return t.replyLabel || 'Replies';
if (key === 'cutoff') return t.cutoffLabel || 'Cutoffs';
if (key === 'blocked') return t.blockedLabel || 'Blocked';
if (key === 'rate_limit') return t.rateLimitedLabel || 'Rate limited';
if (key === 'no_data') return t.noDataLabel || 'No data';
return key;
}
function updateEventsChart(summary) {
if (typeof Chart === 'undefined') return;
var eventsCanvas = document.getElementById('chatai-chart-events');
if (!eventsCanvas) return;
var ctx = eventsCanvas.getContext('2d');
var s = normalizeEventSummary(summary);
// Stable order
var keys = ['reply', 'cutoff', 'blocked', 'rate_limit'];
var values = keys.map(function (k) { return s[k] || 0; });
var hasAny = values.some(function (v) { return v > 0; });
// Use DISPLAY labels in chart.data.labels so the legend is correct with zero custom logic
var finalKeys = hasAny ? keys : ['no_data'];
var finalLabels = finalKeys.map(function (k) { return mapEventLabel(k); });
var finalValues = hasAny ? values : [1];
if (!eventsChart) {
eventsChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: finalLabels,
datasets: [{
data: finalValues
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
cutout: '60%',
plugins: {
legend: {
display: true,
position: 'right'
},
tooltip: {
callbacks: {
// Keep tooltips tidy in the "no data" case
label: function (ctx) {
if (!hasAny) return mapEventLabel('no_data');
var label = (ctx.label != null) ? String(ctx.label) : '';
var val = (ctx.raw != null) ? ctx.raw : '';
return label + ': ' + val;
}
}
}
}
}
});
return;
}
// Update existing
eventsChart.data.labels = finalLabels;
eventsChart.data.datasets[0].data = finalValues;
eventsChart.update();
}
function reloadInsights(days) {
if (!t.insightsUrl) return;
var url = t.insightsUrl + '&days=' + encodeURIComponent(days);
var body = document.querySelector('#chatai-dashboard-insights .InputfieldContent');
if (!body) return;
fetch(url, { credentials: 'same-origin' })
.then(function (res) {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(function (data) {
if (!data || typeof data.html !== 'string') return;
body.innerHTML = data.html;
})
.catch(function (err) {
console.error('ChatAI: failed to load insights:', err);
});
}
function buildExportUrl(days) {
if (!t.obslogExportUrl) return null;
return t.obslogExportUrl + '&days=' + encodeURIComponent(days);
}
// Wire range links
if (rangeLinks && rangeLinks.length) {
rangeLinks.forEach(function (link) {
link.addEventListener('click', function (ev) {
ev.preventDefault();
var days = parseInt(link.getAttribute('data-range'), 10) || 7;
// active state
rangeLinks.forEach(function (a) {
a.classList.remove('is-active');
});
link.classList.add('is-active');
// reload range-dependent pieces
loadVolumeData(days);
reloadInsights(days);
reloadKpis(days)
});
});
// Initial load based on the currently active link
var active = document.querySelector('.chatai-range-link.is-active');
var initialDays = active ? parseInt(active.getAttribute('data-range'), 10) || 7 : 7;
loadVolumeData(initialDays);
reloadInsights(initialDays);
}
// Event types doughnut chart (initial render)
updateEventsChart(window.chatAIEventSummary || {});
});