path:
/logs.js
48.72 KB | plain
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
// Fixed single-quote syntax break error
const ESC_MAP = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
let config = {
endpoint: "/kidang.fcgi",
otpTable: "otp",
// Disabled until the backend action-required table/schema exists. Keeping this
// enabled causes kidang.fcgi?table=action to return HTTP 500 on maa-1.
actionTable: null,
defaultRangeHours: 48, // 2 days
// Incoming timestamps represent local wall-clock time from the sender/receiver.
// Neutralise the browser timezone offset for display so dates don't appear ahead.
displayTimestampsAsLocalWallClock: false,
};
const trackedDevices = new Set();
const trackedCategories = new Set(); // Caches categories dynamically to prevent dropdown flickering
const defaultLogsSettings = { theme: "auto", ambientGlow: true };
let logsSettings = loadLogsSettings();
function loadLogsSettings() {
try {
return { ...defaultLogsSettings, ...(JSON.parse(localStorage.getItem("logs_settings")) || {}) };
} catch (e) {
return { ...defaultLogsSettings };
}
}
function persistLogsSettings() {
localStorage.setItem("logs_settings", JSON.stringify(logsSettings));
}
const tvaControlConfig = {
title: "OPERATIONS",
blinkMs: 1100,
aliases: {
bookingAgeDays: "refillSpreadDays",
bookingSpreadDays: "refillSpreadDays",
bpclDeposit: "bpclDepositLakhs",
},
ambientGlow: { enabled: logsSettings.ambientGlow !== false, alpha: 0.14, radius: 74, blur: 42 },
warningLevels: [
{
key: "amber",
label: "AMBER ALERT",
priority: 1,
showAxis: true,
dominance: 0.6,
axisAlpha: 0.52,
axisWidth: 1.45,
axisTheme: { light: { alpha: 0.8, width: 2.2 } },
axisDash: [3, 5],
glowAlpha: 0.12,
},
{
key: "red",
label: "CRITICAL",
priority: 2,
showAxis: true,
dominance: 0.7,
axisAlpha: 0.42,
axisWidth: 1.45,
axisDash: [6, 6],
glowAlpha: 0.16,
},
{
key: "double-red",
label: "DOUBLE RED",
priority: 3,
showAxis: false,
dominance: 0.7,
borderBlink: true,
glowAlpha: 0.18,
glowRadius: 88,
glowBlur: 54,
},
],
colors: {
amber: "#ffcc00",
red: "#ff0055",
critical: "#ff0055",
"double-red": "#ff1a1a",
doubleRed: "#ff1a1a",
disabled: "#777777",
},
staleAlpha: 0.35,
charts: [
{
key: "operations",
label: "OPERATIONS",
parameters: [
"complaintsOpen",
"invoiceActions",
"deliveryPersonLeave",
"refillSpreadDays",
"pendencyDays",
"bpclDepositLakhs",
],
},
{ key: "compliance", label: "COMPLIANCE", parameters: ["safetyClinicDone"] },
{ key: "excellence", label: "EXCELLENCE", parameters: ["tenKgSales", "fiveKgSales"] },
],
parameters: [
{
key: "complaintsOpen",
label: "Complaints Open",
icon: "warning",
scale: "count10",
refreshMinutes: 15,
thresholds: { amberUpper: 52.5, redUpper: 75, amberLower: -52.5, redLower: -75 },
},
{
key: "invoiceActions",
label: "Invoice Actions",
icon: "invoice",
scale: "count10",
refreshMinutes: 15,
thresholds: { amberUpper: 59.5, redUpper: 85, amberLower: -59.5, redLower: -85 },
},
{
key: "deliveryPersonLeave",
label: "Delivery Person Leave",
icon: "person",
scale: "count10",
refreshMinutes: 720,
thresholds: { amberUpper: 49, redUpper: 70, amberLower: -49, redLower: -70 },
},
{
key: "refillSpreadDays",
label: "Refill Spread",
icon: "calendar",
scale: "daysCritical",
scaleBase: 10,
scaleMax: 165,
refreshMinutes: 1440,
display: { suffix: "d" },
thresholds: {
amberUpper: 50,
redUpper: 100,
doubleRedUpper: 150,
amberLower: -70,
redLower: -100,
},
areaScanView: "refillSpreadAreaScan",
areaKey: "refillSpreadAreas",
areaScanTitle: "REFILL SPREAD AREA SCAN",
areaScanLevels: [
{ level: "amber", above: 5 },
{ level: "red", above: 10 },
],
},
{
key: "pendencyDays",
label: "Pendency",
icon: "hourglass",
scale: "pendency",
scaleIdeal: 1,
scaleBase: 3,
scaleMax: 115,
refreshMinutes: 720,
display: { suffix: "d", decimals: 1 },
thresholds: { amberUpper: 33.33, redUpper: 100, amberLower: -70, redLower: -100 },
areaScanView: "pendencyAreaScan",
areaKey: "pendencyAreas",
areaScanTitle: "PENDENCY AREA SCAN",
areaScanLevels: [
{ level: "amber", above: 1 },
{ level: "red", above: 3 },
],
},
{
key: "bpclDepositLakhs",
label: "BPCL Deposit",
icon: "deposit",
scale: "raw",
refreshMinutes: 30,
display: { prefix: "₹", suffix: "L", decimals: 1 },
thresholds: { amberUpper: 4, redUpper: 6, amberLower: -1, redLower: -3 },
},
{
key: "safetyClinicDone",
label: "Safety Clinic",
icon: "calendar",
scale: "raw",
refreshMinutes: 43200,
display: { suffix: "/1" },
thresholds: { amberLower: 0.75, redLower: 0.25 },
},
{
key: "tenKgSales",
label: "10kg Sales",
icon: "deposit",
scale: "raw",
refreshMinutes: 43200,
thresholds: { amberLower: 10, redLower: 5 },
},
{
key: "fiveKgSales",
label: "5kg Sales",
icon: "deposit",
scale: "raw",
refreshMinutes: 43200,
thresholds: { amberLower: 10, redLower: 5 },
},
],
extraAxes: [
{
label: "BPCL Deposit Good",
parameterKey: "bpclDepositLakhs",
value: 6,
color: "rgba(0,255,120,.5)",
width: 1.8,
dash: [4, 4],
},
{
label: "BPCL Deposit Soft",
parameterKey: "bpclDepositLakhs",
value: 4,
color: "rgba(120,255,160,.34)",
width: 1.4,
dash: [2, 5],
},
],
};
let tvaControl = null;
let pendingTvaControlPatch = null;
let rangeFieldsInitialized = false;
let fetchIntervalId = null;
const tvaMetrics = {
complaintsOpen: 0,
invoiceActions: 2,
deliveryPersonLeave: 0,
refillSpreadDays: getDaysSinceISTMonthDay(-1, 25),
amberRefillSpreadDays: 5,
criticalRefillSpreadDays: 10,
doubleRedRefillSpreadDays: 15,
bpclDepositLakhs: 3,
safetyClinicDone: 0,
tenKgSales: 0,
fiveKgSales: 0,
pendencyDays: 2.7,
idealPendencyMaxDays: 1,
criticalPendencyDays: 3,
refillSpreadAreas: [
{ name: "KK NAGAR", days: 12 },
{ name: "WEST MAMBALAM", days: 9 },
{ name: "ASHOK NAGAR", days: 7 },
{ name: "T NAGAR", days: 11 },
{ name: "VADAPALANI", days: 6 },
{ name: "KODAMBAKKAM", days: 8 },
{ name: "SALIGRAMAM", days: 5 },
{ name: "VIRUGAMBAKKAM", days: 10 },
{ name: "NESAPAKKAM", days: 13 },
{ name: "JAFFERKHANPET", days: 6 },
{ name: "EKKATTUTHANGAL", days: 4 },
{ name: "MGR NAGAR", days: 9 },
{ name: "SAIDAPET", days: 7 },
],
pendencyAreas: [
{ name: "KK NAGAR", days: 3.4 },
{ name: "WEST MAMBALAM", days: 2.9 },
{ name: "ASHOK NAGAR", days: 2.6 },
{ name: "T NAGAR", days: 3.1 },
{ name: "VADAPALANI", days: 2.2 },
{ name: "KODAMBAKKAM", days: 2.8 },
{ name: "SALIGRAMAM", days: 1.9 },
{ name: "VIRUGAMBAKKAM", days: 2.4 },
{ name: "NESAPAKKAM", days: 3.0 },
{ name: "JAFFERKHANPET", days: 2.1 },
{ name: "EKKATTUTHANGAL", days: 1.7 },
{ name: "MGR NAGAR", days: 2.5 },
{ name: "SAIDAPET", days: 2.0 },
],
};
function getISTDateParts(date = new Date()) {
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Kolkata",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(date);
const getPart = (type) => Number(parts.find((part) => part.type === type).value);
return { year: getPart("year"), month: getPart("month"), day: getPart("day") };
}
function getISTDateEpochMs(year, month, day) {
return Date.UTC(year, month - 1, day, -5, -30, 0, 0);
}
function getDaysSinceISTMonthDay(monthOffset, day) {
const nowParts = getISTDateParts();
const targetMonthDate = new Date(Date.UTC(nowParts.year, nowParts.month - 1 + monthOffset, 1));
const targetYear = targetMonthDate.getUTCFullYear();
const targetMonth = targetMonthDate.getUTCMonth() + 1;
const targetEpoch = getISTDateEpochMs(targetYear, targetMonth, day);
const nowEpoch = Date.now();
return Math.max(0, Math.floor((nowEpoch - targetEpoch) / (24 * 60 * 60 * 1000)));
}
function finiteNumber(value) {
const number = Number(value);
return Number.isFinite(number) ? number : null;
}
function setTvaMetricFromPayload(payloadKey, metricKey, payload) {
if (!Object.prototype.hasOwnProperty.call(payload, payloadKey)) return;
const value = finiteNumber(payload[payloadKey]);
if (value !== null) tvaMetrics[metricKey] = value;
}
function normalizeNamedDayAreas(value) {
const rows = Array.isArray(value)
? value
: value && typeof value === "object"
? Object.entries(value).map(([name, days]) => ({ name, days }))
: [];
return rows
.map((row, index) => {
const name = String(row.name || row.area || row.areaName || `Area ${index + 1}`).trim();
const days = finiteNumber(row.days ?? row.pendencyDays ?? row.currentDays);
return name && days !== null ? { name, days } : null;
})
.filter(Boolean);
}
function setTvaPendencyAreasFromPayload(payload) {
if (!Object.prototype.hasOwnProperty.call(payload, "pendencyAreas")) return;
const areas = normalizeNamedDayAreas(payload.pendencyAreas);
if (areas.length) tvaMetrics.pendencyAreas = areas;
}
function setTvaRefillSpreadAreasFromPayload(payload) {
if (!Object.prototype.hasOwnProperty.call(payload, "refillSpreadAreas")) return;
const areas = normalizeNamedDayAreas(payload.refillSpreadAreas);
if (areas.length) tvaMetrics.refillSpreadAreas = areas;
}
function applyTvaMetricUpdate(payload) {
if (!payload || String(payload.type || "").toLowerCase() !== "tva-metrics") return false;
pendingTvaControlPatch = { ...(pendingTvaControlPatch || {}), ...payload };
delete pendingTvaControlPatch.type;
// Partial updates are intentional: only keys present in the payload change.
setTvaMetricFromPayload("complaintsOpen", "complaintsOpen", payload);
setTvaMetricFromPayload("invoiceActions", "invoiceActions", payload);
setTvaMetricFromPayload("deliveryPersonLeave", "deliveryPersonLeave", payload);
setTvaMetricFromPayload("refillSpreadDays", "refillSpreadDays", payload);
setTvaMetricFromPayload("bookingAgeDays", "refillSpreadDays", payload);
setTvaMetricFromPayload("bookingSpreadDays", "refillSpreadDays", payload);
setTvaMetricFromPayload("amberRefillSpreadDays", "amberRefillSpreadDays", payload);
setTvaMetricFromPayload("criticalRefillSpreadDays", "criticalRefillSpreadDays", payload);
setTvaMetricFromPayload("doubleRedRefillSpreadDays", "doubleRedRefillSpreadDays", payload);
setTvaMetricFromPayload("bpclDepositLakhs", "bpclDepositLakhs", payload);
setTvaMetricFromPayload("bpclDeposit", "bpclDepositLakhs", payload);
setTvaMetricFromPayload("safetyClinicDone", "safetyClinicDone", payload);
setTvaMetricFromPayload("tenKgSales", "tenKgSales", payload);
setTvaMetricFromPayload("fiveKgSales", "fiveKgSales", payload);
setTvaMetricFromPayload("pendencyDays", "pendencyDays", payload);
setTvaMetricFromPayload("idealPendencyMaxDays", "idealPendencyMaxDays", payload);
setTvaMetricFromPayload("criticalPendencyDays", "criticalPendencyDays", payload);
setTvaPendencyAreasFromPayload(payload);
setTvaRefillSpreadAreasFromPayload(payload);
return true;
}
function applyTvaMetricUpdatesFromRows(items) {
[...items].sort((a, b) => a.sentstamp - b.sentstamp).forEach((item) => {
const payload = serverMassage(item.msg, item.extra);
const updatedAt = getDateFromEpoch(item.sentstamp)?.getTime();
if (updatedAt) payload.updatedAt = Object.fromEntries(Object.keys(payload).map((key) => [key, updatedAt]));
applyTvaMetricUpdate(payload);
});
}
function isTvaMetricsItem(item) {
return String(serverMassage(item.msg, item.extra).type || "").toLowerCase() === "tva-metrics";
}
function formatTvaMetricValue(index, value) {
if (tvaChartCheckpoints[index] === "Pendency")
return `${tvaMetrics.pendencyDays}d · crit >${tvaMetrics.criticalPendencyDays}d`;
if (tvaChartCheckpoints[index] === "Invoice Actions")
return `${tvaMetrics.invoiceActions} invoices`;
if (tvaChartCheckpoints[index] === "Complaints Open")
return `${tvaMetrics.complaintsOpen} complaints`;
if (tvaChartCheckpoints[index] === "Delivery Person Leave")
return `${tvaMetrics.deliveryPersonLeave} leave`;
if (tvaChartCheckpoints[index] === "Refill Spread")
return `${tvaMetrics.refillSpreadDays}d · red >${tvaMetrics.criticalRefillSpreadDays}d`;
if (tvaChartCheckpoints[index] === "BPCL Deposit") return `₹${tvaMetrics.bpclDepositLakhs}L`;
return `${value}%`;
}
window.setTvaControlData = function (data) {
if (typeof data === "string") data = JSON.parse(data);
applyTvaMetricUpdate({ type: "tva-metrics", ...(data || {}) });
updateActionRequiredChart();
};
window.getTvaControlData = function () {
return tvaControl ? tvaControl.getData() : JSON.parse(JSON.stringify(tvaMetrics));
};
function applyLogsSettingsToDom() {
const prefersDark =
window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
const dark = logsSettings.theme === "dark" || (logsSettings.theme === "auto" && prefersDark);
const light = logsSettings.theme === "light" || (logsSettings.theme === "auto" && !prefersDark);
document.body.classList.toggle("logs-dark", dark);
document.body.classList.toggle("logs-light", light);
document
.querySelectorAll(".action-chart-container, .tva-control-container")
.forEach((container) => {
if (logsSettings.theme === "auto") container.removeAttribute("data-tva-theme");
else container.dataset.tvaTheme = logsSettings.theme;
});
tvaControlConfig.ambientGlow.enabled = logsSettings.ambientGlow !== false;
if (tvaControl && typeof tvaControl.refreshTheme === "function") tvaControl.refreshTheme();
}
function initLogsSettingsDialog() {
const theme = document.getElementById("settings-theme");
const glow = document.getElementById("settings-ambient-glow");
if (!theme || !glow) return;
theme.value = logsSettings.theme;
glow.checked = logsSettings.ambientGlow !== false;
}
window.openLogsSettings = function () {
initLogsSettingsDialog();
const dialog = document.getElementById("logs-settings-dialog");
if (dialog) dialog.showModal();
};
window.closeLogsSettings = function () {
const dialog = document.getElementById("logs-settings-dialog");
if (dialog) dialog.close();
};
window.saveLogsSettings = function () {
const theme = document.getElementById("settings-theme");
const glow = document.getElementById("settings-ambient-glow");
logsSettings = {
theme: theme ? theme.value : "auto",
ambientGlow: glow ? glow.checked : true,
};
persistLogsSettings();
applyLogsSettingsToDom();
closeLogsSettings();
};
function initStickyChartScroll() {
const header = document.querySelector(".app-chart-header");
if (!header || header.dataset.scrollBound) return;
header.dataset.scrollBound = "1";
const panel = document.querySelector(".segment-container");
const tabs = document.querySelector(".mobile-panel-switch");
const chart = header.querySelector(".app-header-chart");
const chatLauncher = header.querySelector(".chat-launcher");
const filters = document.querySelectorAll(".log-filter-bar");
let barHeight = 0, tabsInset = 0;
const update = () => {
const mode = tvaControl.getDisplayMode();
if (mode === "pulseGraphMax") return;
if (mode !== "pulseBar") header.style.minHeight = "";
// Only the panel edge changes on scroll; all layer sizes are cached on resize.
const coverTop = panel.getBoundingClientRect().top - tabsInset;
const docked = coverTop <= barHeight;
if (mode === "pulseGraph" && docked) {
// Keep the consumed graph space in document flow: switching the canvas
// to PulseBar must not move the messages or change the scroll position.
header.style.minHeight = `${header.getBoundingClientRect().height}px`;
tvaControl.setDisplayMode("pulseBar");
} else if (header.style.minHeight && !docked) {
header.style.minHeight = "";
tvaControl.setDisplayMode("pulseGraph");
}
};
const measure = () => {
const chartStyle = getComputedStyle(chart), headerStyle = getComputedStyle(header);
const chatStyle = chatLauncher ? getComputedStyle(chatLauncher) : null;
const chatHeight = chatLauncher
? chatLauncher.getBoundingClientRect().height
+ parseFloat(chatStyle.marginTop) + parseFloat(chatStyle.marginBottom)
: 0;
barHeight = chatHeight + parseFloat(chartStyle.getPropertyValue("--tva-pulse-bar-height"))
+ parseFloat(chartStyle.borderTopWidth) + parseFloat(chartStyle.borderBottomWidth)
+ parseFloat(headerStyle.paddingTop) + parseFloat(headerStyle.paddingBottom);
const tabsHeight = tabs.getBoundingClientRect().height;
tabsInset = tabsHeight ? tabsHeight + parseFloat(getComputedStyle(tabs).marginBottom) : 0;
const style = document.documentElement.style;
style.setProperty("--superpulse-sticky-offset", `${Math.ceil(barHeight)}px`);
style.setProperty("--panel-switch-height", `${Math.ceil(tabsHeight)}px`);
filters.forEach((filter) => filter.parentElement.style.setProperty(
"--filter-height", `${Math.ceil(filter.getBoundingClientRect().height)}px`,
));
update();
};
window.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", measure);
const observer = new ResizeObserver(measure);
[header, chart, tabs, chatLauncher, ...filters]
.filter(Boolean)
.forEach((element) => observer.observe(element));
measure();
}
function initActionRequiredChart() {
const canvas = document.getElementById("tvaReactiveChart");
if (
!canvas ||
tvaControl ||
typeof Chart === "undefined" ||
typeof createTvaControl !== "function"
)
return;
applyLogsSettingsToDom();
tvaControl = createTvaControl({ canvas, config: tvaControlConfig, data: tvaMetrics });
initStickyChartScroll();
}
function updateActionRequiredChart() {
if (!tvaControl) initActionRequiredChart();
if (!tvaControl) return;
if (pendingTvaControlPatch) {
tvaControl.update(pendingTvaControlPatch);
pendingTvaControlPatch = null;
}
}
// Reads session memory to track alerts across page refreshes
function getSeenLeaksLog() {
try {
const data = sessionStorage.getItem("seen_lpg_leaks");
return data ? JSON.parse(data) : [];
} catch (e) {
return [];
}
}
// Commits a triggered alert ID to session memory
function markLeakAsSeen(itemDomId) {
try {
const seenList = getSeenLeaksLog();
if (!seenList.includes(itemDomId)) {
seenList.push(itemDomId);
sessionStorage.setItem("seen_lpg_leaks", JSON.stringify(seenList));
}
} catch (e) {
console.error(e);
}
}
// Web Audio synthesizer tone generator
function playAlarmSound() {
try {
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (!AudioContext) return;
const ctx = new AudioContext();
[0, 0.25].forEach((delay) => {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = "sine";
osc.frequency.setValueAtTime(880, ctx.currentTime + delay);
gain.gain.setValueAtTime(0.3, ctx.currentTime + delay);
gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + delay + 0.2);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(ctx.currentTime + delay);
osc.stop(ctx.currentTime + delay + 0.2);
});
} catch (e) {
console.warn(
"Audio Context blocked. Click anywhere on the webpage once to enable sound alerts.",
);
}
}
// Bypasses sandbox blockers to show a system banner alert
function triggerDesktopNotification(sender, message, deviceId) {
if (!("Notification" in window)) return;
if (Notification.permission === "granted") {
new Notification("CRITICAL ALERT: LPG Leakage", {
body: `From: ${sender} (${deviceId})\n${message}`,
});
}
}
function escapeHTML(s, forAttribute) {
if (s === null || s === undefined) return "";
if (typeof s !== "string") return s;
if (!s) return "";
return s.replace(forAttribute ? /[&<>'"]/g : /[&<>]/g, (c) => ESC_MAP[c]);
}
function getDateFromEpoch(ts) {
if (!ts) return undefined;
let date;
if (ts < 10_000_000_000) date = new Date(ts * 1000);
else if (ts < 10_000_000_000_000) date = new Date(ts);
else if (ts < 10_000_000_000_000_000) date = new Date(Math.floor(ts / 1000));
else return undefined;
if (config.displayTimestampsAsLocalWallClock) {
return new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
}
return date;
}
// Time-only formatting for message headers now that the day/month lives in the per-date-group badge
function formatTimeOnly(date) {
if (!(date instanceof Date) || isNaN(date)) return "";
const time = new Intl.DateTimeFormat("en-IN", {
timeZone: "Asia/Kolkata",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(date);
return `<strong>${time}</strong>`;
}
function getISTDateKey(date) {
if (!(date instanceof Date) || isNaN(date)) return "";
const parts = new Intl.DateTimeFormat("en-CA", {
timeZone: "Asia/Kolkata",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(date);
const getPart = (type) => parts.find((part) => part.type === type).value;
return `${getPart("year")}-${getPart("month")}-${getPart("day")}`;
}
// Calendar-style day/month markup, matching the #custom-date template
function formatDateBadge(date) {
if (!(date instanceof Date) || isNaN(date)) return "";
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: "Asia/Kolkata",
day: "numeric",
month: "short",
}).formatToParts(date);
const day = parts.find((part) => part.type === "day").value;
const month = parts.find((part) => part.type === "month").value;
return `<div class="date-p"><p>${day}</p><small>${month}</small><hr></div>`;
}
// Rebuilds the standalone date-divider <li> elements: one per date group, inserted right before that
// group's first message. As a top-level list item (not nested inside a message row), each divider can
// stick to the top of the list on its own while its date's messages scroll underneath it. Works on any
// message <ul> — both the OTP feed and the action-required feed use it.
function syncDateDividers(list) {
if (!list) return;
list.querySelectorAll("li.date-divider").forEach((el) => el.remove());
let lastDateKey = null;
list.querySelectorAll("li.msg-list-item").forEach((item) => {
const sentDate = getDateFromEpoch(parseInt(item.dataset.timestamp, 10));
if (!sentDate) return;
const dateKey = getISTDateKey(sentDate);
if (dateKey === lastDateKey) return;
lastDateKey = dateKey;
const divider = document.createElement("li");
divider.className = "date-divider";
divider.innerHTML = formatDateBadge(sentDate);
list.insertBefore(divider, item);
});
}
// Native clipboard click handling operation
window.copyToClipboard = function (text, element) {
navigator.clipboard
.writeText(text)
.then(() => {
const originalText = element.innerText;
element.innerText = "Copied!";
element.style.background = "#d4edda";
element.style.borderColor = "#c3e6cb";
setTimeout(() => {
element.innerText = originalText;
element.style.background = "#f0f0f0";
element.style.borderColor = "#ddd";
}, 1200);
})
.catch((err) => console.error(err));
};
function copyableCodeChip(code) {
return `<span class="copyable-code" onclick="copyToClipboard('${code}', this)" style="cursor:pointer; background:#f0f0f0; padding:2px 6px; border-radius:4px; font-weight:bold; display:inline-block; margin-top:4px; border:1px solid #ddd; transition: all 0.2s;">${code}</span>`;
}
function leakageBanner(keyword) {
return `<div class="leakage-alert">${escapeHTML(keyword, true)} detected</div>`;
}
// ============================================================================
// Message templates
//
// serverMassage() is the only place that understands today's raw "gt" msg
// string. It normalizes a message into a JSON object shaped for its specific
// type — an iob-debit only carries amount/merchant, an sms only carries
// otp/leakage when those actually apply — rather than one generic shape with
// fields that don't mean anything for that type. `msg` itself is always kept
// completely raw: every other field is extracted OUT of it, never mutated
// into it, so templates render msg as-is and use the extracted fields for
// any special presentation (chips, banners, etc). Once the server starts
// sending this same JSON directly instead of a plain-text msg, serverMassage()
// is the single spot that needs to change (parse/pass-through instead of
// regex-sniffing); the header and body templates stay untouched.
// ============================================================================
function serverMassage(msg, extraRaw) {
if (msg && typeof msg === "object" && msg.type) return msg;
msg = msg || "";
// Structured payloads: once the server sends JSON straight in `msg`, each type just carries whatever
// fields it needs (e.g. "dispatch" below) — no regex-sniffing required.
if (typeof msg === "string" && msg.trim().startsWith("{")) {
try {
const parsed = JSON.parse(msg);
if (parsed && typeof parsed === "object" && parsed.type) return parsed;
} catch (e) {
/* not valid JSON, fall through to plain-text parsing */
}
}
const iobDebitMatch = msg.match(/^rs\.([0-9.]*) debited to CC-xxx2081 .* \[(.*)\]/i);
if (iobDebitMatch) {
return { type: "iob-debit", amount: iobDebitMatch[1], merchant: iobDebitMatch[2] || "", msg };
}
const iobCreditMatch = msg.match(/^rs\.([0-9.]*) credited to CC-xxx2081 .* \[(.*)\]/i);
if (iobCreditMatch) {
return {
type: "iob-credit",
amount: iobCreditMatch[1],
merchant: iobCreditMatch[2] || "",
msg,
};
}
let sim = "";
try {
const extraJson = extraRaw ? JSON.parse(extraRaw) : null;
if (extraJson && extraJson.sim) sim = extraJson.sim;
} catch (e) {
/* extra wasn't valid JSON, ignore */
}
const data = { type: "sms", msg, sim };
const otpMatch = msg.match(/\b\d{6}\b/);
if (otpMatch) data.otp = otpMatch[0];
const leakageMatch = msg.match(/(lpg leakage|gas leak|leakage detected)/i);
if (leakageMatch) data.leakage = leakageMatch[0];
return data;
}
// Body markup is fully owned by each message type — nothing outside these templates decides how a body renders.
const messageBodyTemplates = {
"iob-debit": (data) => `<div>
<details style="display: inline-block; width: 100%;"><summary style="margin-left: 6rem; display: block; color: red;">- Rs. ${escapeHTML(data.amount, true)}</summary>${escapeHTML(data.msg)}</details>
</div>`,
"iob-credit": (data) => `<div>
<details style="display: inline-block; width: 100%;"><summary style="display: block; color: green;">+ Rs. ${escapeHTML(data.amount, true)}</summary>${escapeHTML(data.msg)}</details>
</div>`,
sms: (data) =>
`${data.leakage ? leakageBanner(data.leakage) : ""}${escapeHTML(data.msg)}${data.otp ? copyableCodeChip(data.otp) : ""}`,
dispatch: (data) => `<span class="badge-status">${escapeHTML(data.status, true)}</span>
<div class="cargo-grid">
${(data.cargo || [])
.map(
(
c,
) => `<div class="cargo-item"><span class="kg-badge">${escapeHTML(c.kg, true)}</span>
<span class="qty">${escapeHTML(String(c.qty), true)}</span></div>`,
)
.join("")}
</div>
<table>
<tbody>
<tr>
<th>vehicle no</th>
<td>${escapeHTML(data.vehicleNo, true)}</td>
</tr>
<tr>
<th>time</th>
<td>${escapeHTML(data.time, true)}</td>
</tr>
<tr>
<th>invoice no.</th>
<td>${escapeHTML(data.invoiceNo, true)}</td>
</tr>
<tr>
<th>amount</th>
<td>${escapeHTML(data.amount, true)}</td>
</tr>
</tbody>
</table>
<button class="value">Acknowledge Invoice</button>`,
};
function renderMessageBody(data) {
const template = messageBodyTemplates[data.type] || messageBodyTemplates.sms;
return template(data);
}
// Only the header needs to reduce each type's custom fields down to one label string.
function getHeaderLabel(data) {
switch (data.type) {
case "iob-debit":
case "iob-credit":
return data.merchant || "";
case "sms":
return data.sim || "";
case "dispatch":
return data.vehicleNo || data.invoiceNo || "";
default:
return "";
}
}
// Header structure is the same for every message type — only the injected text (sender, label, time, device) varies.
function renderMessageHeader({ imgType, sender, headerLabel, timeStr, mid, deviceName }) {
const headerPrefixText = headerLabel ? `${headerLabel} | ` : "";
return `<div class="msg-item-header">
${imgType}
<div style="display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px;">
<span>${sender}</span>
<small style="font-weight: lighter; color: #727272;">${headerPrefixText}${timeStr}</small>
</div>
<button class="device-name-button" popovertarget="device-info-popover" data-mid="${escapeHTML(String(mid), true)}" onfocus="deviceCardUpdate(event)" onclick="deviceCardUpdate(event)" style="flex: 1; text-align: end; font-size: 11px; color:#aaa; font-weight:normal; font-family:monospace;">${deviceName}</button>
</div>`;
}
function setMessageVisibility(element, visible) {
element.style.setProperty("display", visible ? "flex" : "none", "important");
}
// Master visual filter calculation logic for the live event feed.
window.applyFilters = function () {
const selectedDevice = document.getElementById("filter-device").value;
const selectedCategory = document.getElementById("filter-category").value;
const searchQuery = document.getElementById("filter-search").value.toLowerCase();
document.querySelectorAll("#data-list .msg-list-item").forEach((element) => {
const matchesDevice = !selectedDevice || element.dataset.device === selectedDevice;
const matchesCategory = !selectedCategory || element.dataset.category === selectedCategory;
const matchesSearch = !searchQuery || element.innerText.toLowerCase().includes(searchQuery);
setMessageVisibility(element, matchesDevice && matchesCategory && matchesSearch);
});
};
// Search-only filter for the action-required panel.
window.applyActionFilters = function () {
const searchInput = document.getElementById("action-filter-search");
const searchQuery = searchInput ? searchInput.value.toLowerCase() : "";
document.querySelectorAll("#action-list .msg-list-item").forEach((element) => {
const matchesSearch = !searchQuery || element.innerText.toLowerCase().includes(searchQuery);
setMessageVisibility(element, matchesSearch);
});
};
window.showMobileSegment = function (segmentNumber) {
document.querySelectorAll(".segment").forEach((segment) => {
segment.classList.toggle("active", segment.dataset.segment === String(segmentNumber));
});
document.querySelectorAll(".mobile-panel-switch button").forEach((button) => {
const isActive = button.dataset.targetSegment === String(segmentNumber);
button.classList.toggle("active", isActive);
button.setAttribute("aria-pressed", isActive ? "true" : "false");
});
};
function epochSecondsFromLocalInput(value) {
if (!value) return null;
const match = String(value).match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/);
if (!match) return null;
const [, year, month, day, hour, minute] = match.map(Number);
// datetime-local has no timezone. Treat the control value as IST.
return Math.floor(Date.UTC(year, month - 1, day, hour - 5, minute - 30, 0, 0) / 1000);
}
function formatDateTimeLocalIST(date) {
const ist = new Date(date.getTime() + 330 * 60 * 1000);
const pad = (n) => String(n).padStart(2, "0");
return `${ist.getUTCFullYear()}-${pad(ist.getUTCMonth() + 1)}-${pad(ist.getUTCDate())}T${pad(ist.getUTCHours())}:${pad(ist.getUTCMinutes())}`;
}
function initRangeFields(force = false) {
const fromInput = document.getElementById("range-from");
const toInput = document.getElementById("range-to");
if (!fromInput || !toInput) return;
const now = new Date();
if (force || !rangeFieldsInitialized || !fromInput.value) {
const fromDate = new Date(now.getTime() - config.defaultRangeHours * 60 * 60 * 1000);
fromInput.value = formatDateTimeLocalIST(fromDate);
rangeFieldsInitialized = true;
}
toInput.value = formatDateTimeLocalIST(now);
}
function getRangeParams() {
initRangeFields();
const fromInput = document.getElementById("range-from");
const toInput = document.getElementById("range-to");
const params = {};
const fromTimestamp = epochSecondsFromLocalInput(fromInput && fromInput.value);
const toTimestamp = epochSecondsFromLocalInput(toInput && toInput.value);
if (fromTimestamp) {
// kidang currently names the lower-bound query parameter `sentstamp`.
// Use the same Unix epoch seconds that the sender/receiver exchange; any
// PostgreSQL internal epoch offset stays hidden inside the database layer.
params.sentstamp = fromTimestamp;
// Keep explicit range aliases too, so the UI remains forward-compatible if
// the backend grows true from/to query names later.
params.fromTimestamp = fromTimestamp;
}
if (toTimestamp) params.toTimestamp = toTimestamp;
return params;
}
window.refreshRangeFeeds = function () {
initRangeFields();
fetchUpdates();
fetchActionUpdates();
};
function updateDeviceDropdown(mId) {
if (!mId || trackedDevices.has(String(mId))) return;
trackedDevices.add(String(mId));
const dropdown = document.getElementById("filter-device");
if (!dropdown) return;
const option = document.createElement("option");
option.value = String(mId);
option.textContent = getDeviceNameFromId(mId) || fallbackDeviceName(mId);
dropdown.appendChild(option);
}
// Automatically populates dropdown choices based on data stream records
function updateCategoryDropdown(category) {
if (!category || trackedCategories.has(category)) return;
trackedCategories.add(category);
const dropdown = document.getElementById("filter-category");
if (!dropdown) return;
const option = document.createElement("option");
option.value = category;
if (category === "otp" || category === "sms") {
option.textContent = `${category.toUpperCase()} Only`;
} else {
option.textContent = category.charAt(0).toUpperCase() + category.slice(1);
}
dropdown.appendChild(option);
}
function fallbackDeviceName(mid) {
return mid ? `Device ${mid}` : "unknown";
}
function getDeviceNameFromId(mid) {
const cached = deviceMapCache[mid];
if (cached && typeof cached === "object" && cached.name) return cached.name;
fetchDeviceDetails(mid).then((device) => updateDeviceReferences(mid, device));
return fallbackDeviceName(mid);
}
function cssEscape(value) {
if (window.CSS && CSS.escape) return CSS.escape(value);
return value.replace(/[^a-zA-Z0-9_-]/g, "\\$&");
}
function updateDeviceReferences(mid, device) {
if (!mid || !device || !device.name) return;
document
.querySelectorAll(`.device-name-button[data-mid="${cssEscape(String(mid))}"]`)
.forEach((button) => {
button.textContent = device.name;
const item = button.closest(".msg-list-item");
if (item) item.dataset.device = String(mid);
});
const option = document.querySelector(`#filter-device option[value="${cssEscape(String(mid))}"]`);
if (option) option.textContent = device.name;
}
function getCategoryNameFromId(cid) {
// TODO Get from kidang and cache
let deviceIdMap = {
1: "sms",
2: "econnect",
3: "paytm",
4: "tampermonkey",
5: "printer",
};
return deviceIdMap[cid + ""];
}
function getDeterministicColor(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);
return `hsl(${Math.abs(hash) % 360}, 65%, 42%)`;
}
function insertInOrder(parent, newChild, newTimestamp) {
const children = parent.querySelectorAll("li.msg-list-item");
for (let i = 0; i < children.length; i++) {
const currentTimestamp = parseInt(children[i].dataset.timestamp, 10);
if (newTimestamp > currentTimestamp) {
parent.insertBefore(newChild, children[i]);
return;
}
}
parent.appendChild(newChild);
}
function isActionRequiredItem(item) {
const sender = String(item.sndr || "").toLowerCase();
const msg = String(item.msg || "").toLowerCase();
const category = getCategoryNameFromId(item.cid) || "";
return (
sender === "complaints" ||
(category === "econnect" && /\b(urgent|emergency|complain|complaint|leak)/i.test(msg))
);
}
function removeDeadItems(parent, freshData) {
const freshIds = freshData.map((item) =>
`msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, "_"),
);
parent.querySelectorAll('li[id^="msg-"]').forEach((item) => {
if (!freshIds.includes(item.id)) item.remove();
});
}
// Builds one <li class="msg-list-item"> from a raw item ({ sndr, sentstamp, mid, cid, msg, extra }),
// using serverMassage() + the header/body templates above. Shared by the live OTP feed and any other
// message list (e.g. the sample action-required item below) so both render through the same templates.
function createMessageListItem(item) {
const sentDate = getDateFromEpoch(item.sentstamp);
if (!sentDate) return null;
const dName = getDeviceNameFromId(item.mid) || fallbackDeviceName(item.mid);
const cId = getCategoryNameFromId(item.cid) || "unknown";
const messageData = serverMassage(item.msg, item.extra);
const listItem = document.createElement("li");
listItem.id = `msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, "_");
listItem.className = "msg-list-item";
listItem.dataset.device = String(item.mid || "unknown");
listItem.dataset.category = cId;
listItem.dataset.timestamp = item.sentstamp;
listItem.style.display = "flex";
listItem.style.alignItems = "flex-start";
listItem.style.padding = "10px 12px";
listItem.style.borderBottom = "1px solid #f2f2f2";
if (messageData.leakage) {
listItem.style.background = "#fff5f5";
listItem.style.borderLeft = "4px solid #dc3545";
}
const iconColor = getDeterministicColor(item.sndr || "Unknown");
let imgType = "";
if (cId === "sms") {
imgType = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${iconColor}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
</svg>`;
} else if (cId === "tampermonkey") {
imgType = '<img src="/assets/tampermonkey.svg">';
} else if (cId === "printer") {
imgType = '<img src="/assets/printer.svg">';
} else {
imgType = '<img style="height: 16px; width: 16px;" src="/assets/logs/cid-2-16x.png">';
}
listItem.innerHTML = `
<div style="flex-grow: 1; min-width: 0; display: flex; flex-direction: column;">
${renderMessageHeader({
imgType,
sender: escapeHTML(item.sndr, true),
headerLabel: escapeHTML(getHeaderLabel(messageData), true),
timeStr: formatTimeOnly(sentDate),
mid: item.mid,
deviceName: escapeHTML(dName, true),
})}
<!-- Body markup is fully owned by the message type template -->
<div class="logs-message">
${renderMessageBody(messageData)}
</div>
</div>
`;
return listItem;
}
function parseFeedResponse(textData) {
const trimmed = textData.trim();
if (!trimmed) return [];
if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) return parsed;
if (Array.isArray(parsed.rows)) return parsed.rows;
if (Array.isArray(parsed.data)) return parsed.data;
return [parsed];
} catch (e) {
// kidang's GT format can also start with "{"/"[" but is not JSON.
// Fall through to the legacy GT parser instead of breaking the live feed.
}
}
const parsed = window.parseGT(textData);
return Array.isArray(parsed) ? parsed : [parsed];
}
async function fetchTable(tableName, queryParams = {}) {
const params = new URLSearchParams({ table: tableName });
Object.entries(queryParams).forEach(([key, value]) => {
if (value !== null && value !== undefined && value !== "") params.set(key, value);
});
const response = await fetch(`${config.endpoint}?${params.toString()}`);
if (!response.ok) throw new Error(`${tableName} fetch failed: ${response.status}`);
return parseFeedResponse(await response.text());
}
async function fetchUpdates() {
try {
const rangeParams = getRangeParams();
const data = await fetchTable(config.otpTable, rangeParams);
const list = document.getElementById("data-list");
const toTimestampMs = rangeParams.toTimestamp ? rangeParams.toTimestamp * 1000 : null;
const rangedData = toTimestampMs
? data.filter((item) => item.sentstamp <= toTimestampMs)
: data;
rangedData.sort((a, b) => b.sentstamp - a.sentstamp);
applyTvaMetricUpdatesFromRows(rangedData);
const historySeenAlerts = getSeenLeaksLog();
const eventData = [];
const actionData = [];
rangedData.forEach((item) => {
if (isTvaMetricsItem(item)) return;
const cId = getCategoryNameFromId(item.cid) || "unknown";
updateDeviceDropdown(item.mid);
updateCategoryDropdown(cId);
const isActionRequired = isActionRequiredItem(item);
const targetList = isActionRequired ? document.getElementById("action-list") : list;
if (isActionRequired) actionData.push(item);
else eventData.push(item);
const itemDomId = `msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, "_");
if (targetList && targetList.querySelector(`#${cssEscape(itemDomId)}`)) return;
const messageData = serverMassage(item.msg, item.extra);
// Fires sound and alert banners only if it hasn't popped during this browser session
if (messageData.leakage && !historySeenAlerts.includes(itemDomId)) {
markLeakAsSeen(itemDomId);
historySeenAlerts.push(itemDomId);
// FIXME Enable later
playAlarmSound();
triggerDesktopNotification(item.sndr, item.msg, item.mid);
}
const listItem = createMessageListItem(item);
if (targetList && listItem) insertInOrder(targetList, listItem, item.sentstamp);
});
removeDeadItems(list, eventData);
const actionList = document.getElementById("action-list");
if (actionList) {
removeDeadItems(actionList, actionData);
updateActionRequiredChart(actionData);
applyActionFilters();
syncDateDividers(actionList);
}
applyFilters();
syncDateDividers(list);
} catch (error) {
console.error("Error fetching updates:", error);
}
}
async function fetchActionUpdates() {
const list = document.getElementById("action-list");
if (!list || !config.actionTable) return;
try {
const rangeParams = getRangeParams();
const data = await fetchTable(config.actionTable, rangeParams);
const toTimestampMs = rangeParams.toTimestamp ? rangeParams.toTimestamp * 1000 : null;
const rangedData = toTimestampMs
? data.filter((item) => item.sentstamp <= toTimestampMs)
: data;
rangedData.sort((a, b) => b.sentstamp - a.sentstamp);
applyTvaMetricUpdatesFromRows(rangedData);
rangedData.forEach((item) => {
if (isTvaMetricsItem(item)) return;
const itemDomId = `msg-${item.sndr}-${item.sentstamp}`.replace(/[^a-zA-Z0-9-]/g, "_");
if (document.getElementById(itemDomId)) return;
const listItem = createMessageListItem(item);
if (listItem) insertInOrder(list, listItem, item.sentstamp);
});
removeDeadItems(list, rangedData);
updateActionRequiredChart(rangedData);
applyActionFilters();
syncDateDividers(list);
} catch (error) {
// Some deployments do not have the action-required table yet. Stop polling
// after the first server-side failure so the normal OTP feed stays quiet.
if (String(error.message || "").match(/\b(404|500)\b/)) {
console.warn("Action-required feed unavailable; stopping action polling.", error);
config.actionTable = null;
if (actionFetchIntervalId) clearInterval(actionFetchIntervalId);
return;
}
console.error("Error fetching action-required updates:", error);
}
}
function $(id) {
return document.getElementById(id);
}
let deviceMapCache = {};
function fetchDeviceDetails(id) {
if (!id) return Promise.resolve(null);
const key = String(id);
if (!/^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/.test(key)) return Promise.resolve(null);
const cached = deviceMapCache[key];
if (cached && typeof cached.then === "function") return cached;
if (cached && typeof cached === "object") return Promise.resolve(cached);
const promise = fetch("/api/devices/" + encodeURIComponent(key))
.then(async (r) => {
let device = null;
try {
device = await r.json();
} catch (error) {
throw new Error(`Device lookup returned invalid JSON: ${r.status}`);
}
if (!r.ok)
throw new Error(
device && device.error ? device.error : `Device lookup failed: ${r.status}`,
);
const name = device && (device.name || (device.model && device.model.name));
if (!name) throw new Error("Device lookup response missing name");
return {
name,
serial: device.serial,
assigned_to: device.assigned_to && device.assigned_to.name,
image: device.image,
category_color: device.category && device.category.tag_color,
notes: device.notes,
};
})
.then((device) => {
deviceMapCache[key] = device;
updateDeviceReferences(key, device);
return device;
})
.catch((error) => {
console.warn("Device lookup failed", key, error);
delete deviceMapCache[key];
return null;
});
deviceMapCache[key] = promise;
return promise;
}
function updateDeviceCard(device) {
device = device || {};
const assigned = typeof device.assigned_to === "object" ? device.assigned_to && device.assigned_to.name : device.assigned_to;
$("p-name").textContent = device.name || "Loading device…";
$("p-assigned-to").textContent = assigned || "";
$("p-assigned-to").closest("p").hidden = !assigned;
$("p-image").src = device.image || "";
$("p-notes").textContent = device.notes || "";
$("p-serial").textContent = device.serial || "";
}
function placeDevicePopoverNear(el) {
const popover = document.getElementById("device-info-popover");
if (!popover || !el) return;
const rect = el.getBoundingClientRect();
popover.style.position = "fixed";
popover.style.left = `${Math.min(rect.left, window.innerWidth - 320)}px`;
popover.style.top = `${Math.min(rect.bottom + 6, window.innerHeight - 180)}px`;
popover.style.inset = "auto";
}
function deviceCardUpdate(ev) {
const el = ev.target;
const id = el.dataset.mid;
placeDevicePopoverNear(el);
updateDeviceCard({ name: fallbackDeviceName(id) });
if (!id) return;
fetchDeviceDetails(id).then((device) => {
if (device) updateDeviceCard(device);
placeDevicePopoverNear(el);
});
}
window.deviceCardUpdate = deviceCardUpdate;
fetchIntervalId = setInterval(fetchUpdates, 3000);
let actionFetchIntervalId = null;
fetchUpdates();
// logs.js runs before <ul id="action-list"> exists in the DOM (script tag comes before .content),
// so action-required polling starts after the parser has created that panel.
document.addEventListener("DOMContentLoaded", () => {
if (window.matchMedia)
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", applyLogsSettingsToDom);
initLogsSettingsDialog();
applyLogsSettingsToDom();
initRangeFields();
initActionRequiredChart();
fetchUpdates();
fetchActionUpdates();
actionFetchIntervalId = setInterval(fetchActionUpdates, 3000);
});