-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservicehealth.html
More file actions
1226 lines (1150 loc) · 56.5 KB
/
Copy pathservicehealth.html
File metadata and controls
1226 lines (1150 loc) · 56.5 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microsoft 365 Service Health – Microsoft Communications Portal</title>
<script>
(() => {
const param = new URLSearchParams(window.location.search).get("clawpilotTheme");
const theme = param || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
document.documentElement.setAttribute("data-theme", theme);
})();
</script>
<script src="/static/util.js" defer></script>
<link rel="stylesheet" href="/static/common.css">
<link rel="stylesheet" href="/static/servicehealth.css">
</head>
<body>
<script src="/static/nav.js" defer></script>
<div class="page-content">
<!-- Heading bar -->
<div class="sh-hero">
<div class="sh-hero-left">
<div class="sh-hero-title">Microsoft 365 Service Health</div>
<span class="sh-live">Live</span>
</div>
</div>
<!-- Dashboard layout -->
<div class="sh-page-stack">
<!-- Top row: left column (overview + breakdown), right column (activity + heatmap) -->
<div class="sh-top-row">
<div class="sh-top-left">
<section class="sh-panel">
<div class="sh-panel-head">
<div class="sh-panel-title">Overview</div>
<div class="sh-panel-meta">
<span id="sh-updated">—</span>
<button class="export-btn" id="sh-refresh-btn" type="button" aria-label="Refresh service health"><span aria-hidden="true">↻</span></button>
</div>
</div>
<div class="sh-overview">
<div class="sh-donut-wrap">
<svg class="sh-donut-svg" id="sh-donut-svg" viewBox="0 0 42 42" role="img" aria-label="Service health overview"></svg>
<div class="sh-donut-center">
<div class="sh-donut-num" id="sh-donut-total">—</div>
<div class="sh-donut-label">Services</div>
</div>
</div>
<div class="sh-legend">
<div class="sh-legend-row">
<span class="sh-legend-dot operational"></span>
<span class="sh-legend-name">Operational</span>
<span class="sh-legend-num" id="sh-stat-operational">—</span>
</div>
<div class="sh-legend-row">
<span class="sh-legend-dot degraded"></span>
<span class="sh-legend-name">Degraded</span>
<span class="sh-legend-num" id="sh-stat-degraded">—</span>
</div>
<div class="sh-legend-row">
<span class="sh-legend-dot extended"></span>
<span class="sh-legend-name">Extended Recovery</span>
<span class="sh-legend-num" id="sh-stat-extended">—</span>
</div>
<div class="sh-legend-row">
<span class="sh-legend-dot degraded"></span>
<span class="sh-legend-name">Active issues</span>
<span class="sh-legend-num" id="sh-stat-issues">—</span>
</div>
</div>
</div>
</section>
<section class="sh-panel sh-panel-flex">
<div class="sh-panel-head">
<div class="sh-panel-title">
<span>By Service</span>
<span class="sh-panel-title-count" id="sh-breakdown-total">—</span>
</div>
</div>
<div class="sh-breakdown" id="sh-breakdown">
<div class="sh-loading" role="status" aria-live="polite"><div class="spinner" aria-hidden="true"></div></div>
</div>
</section>
</div>
<div class="sh-top-right">
<section class="sh-panel sh-panel-flex">
<div class="sh-panel-head">
<div class="sh-panel-title">
<span>Recent Activity</span>
<span class="sh-panel-title-count" id="sh-activity-total">—</span>
</div>
</div>
<div class="sh-severity-legend">
<span class="sh-severity-legend-item"><span class="sh-severity-legend-dot" style="background:var(--cp-danger)"></span>Incident</span>
<span class="sh-severity-legend-item"><span class="sh-severity-legend-dot" style="background:var(--cp-warning)"></span>Advisory</span>
<span class="sh-severity-legend-item"><span class="sh-severity-legend-dot" style="background:var(--cp-purple)"></span>Extended</span>
<span class="sh-severity-legend-item"><span class="sh-severity-legend-dot" style="background:var(--cp-link)"></span>Investigating</span>
</div>
<div class="sh-activity" id="sh-activity">
<div class="sh-loading" role="status" aria-live="polite"><div class="spinner" aria-hidden="true"></div></div>
</div>
</section>
<section class="sh-panel">
<div class="sh-panel-head">
<div class="sh-panel-title">
<span>Uptime Heatmap</span>
</div>
</div>
<div class="sh-heatmap-wrap" id="sh-heatmap">
<div class="sh-loading" role="status" aria-live="polite"><div class="spinner" aria-hidden="true"></div></div>
</div>
<div class="sh-heatmap-legend">
<span class="sh-heatmap-legend-item"><span class="sh-heatmap-legend-dot" style="background:var(--cp-success)"></span>Operational</span>
<span class="sh-heatmap-legend-item"><span class="sh-heatmap-legend-dot" style="background:var(--cp-warning)"></span>Degraded</span>
<span class="sh-heatmap-legend-item"><span class="sh-heatmap-legend-dot" style="background:var(--cp-danger)"></span>Incident</span>
</div>
</section>
</div>
</div>
<!-- Trend chart — full width for better readability -->
<section class="sh-panel">
<div class="sh-panel-head">
<div class="sh-panel-title">
<span class="sh-panel-title-icon" aria-hidden="true" style="color:var(--cp-success)">📈</span>
<span>30-Day Health Trend</span>
</div>
<div class="sh-trend-toggle" id="sh-trend-toggle" role="group" aria-label="Trend range">
<button type="button" data-range="7" aria-pressed="false" aria-label="7 days">7d</button>
<button type="button" data-range="14" aria-pressed="false" aria-label="14 days">14d</button>
<button type="button" data-range="30" class="active" aria-pressed="true" aria-label="30 days">30d</button>
</div>
</div>
<svg class="sh-trend-svg" id="sh-trend-svg" viewBox="0 0 800 90" preserveAspectRatio="none" role="img" aria-label="30-day health trend chart"></svg>
<div class="sh-trend-legend">
<span class="sh-trend-legend-item"><span class="sh-trend-legend-dot" style="background:var(--cp-danger)"></span>Active issues</span>
<span class="sh-trend-legend-item"><span class="sh-trend-legend-dot" style="background:var(--cp-warning)"></span>Affected services</span>
<span class="sh-trend-legend-item"><span class="sh-trend-legend-dot" style="background:var(--cp-success)"></span>Operational services</span>
</div>
</section>
<!-- Current Issues — fills remaining height, scrolls internally -->
<section class="sh-panel sh-issues-panel">
<div class="sh-panel-head">
<div class="sh-panel-title">
<span>Current Issues</span>
<span class="sh-panel-title-count" id="sh-issues-total">—</span>
</div>
<div style="display:flex;gap:0.4rem;align-items:center">
<button class="export-btn" id="sh-export-btn" type="button">⬇ Export</button>
<button class="ghost-btn" id="sh-expand-btn" type="button" aria-expanded="false">Show all</button>
<button class="ghost-btn" id="sh-pause-btn" type="button" aria-pressed="false">Pause</button>
</div>
</div>
<div class="sh-severity-legend">
<span class="sh-severity-legend-item"><span class="sh-severity-legend-bar" style="background:var(--cp-danger)"></span>Incident</span>
<span class="sh-severity-legend-item"><span class="sh-severity-legend-bar" style="background:var(--cp-warning)"></span>Advisory</span>
<span class="sh-severity-legend-item"><span class="sh-severity-legend-bar" style="background:var(--cp-purple)"></span>Extended</span>
<span class="sh-severity-legend-item"><span class="sh-severity-legend-bar" style="background:var(--cp-link)"></span>Investigating</span>
</div>
<div class="sh-issues-list" id="sh-sidebar-list">
<div class="sh-loading" role="status" aria-live="polite"><div class="spinner" aria-hidden="true"></div></div>
</div>
</section>
</div>
</div>
<!-- Issue detail modal -->
<div class="sh-modal-backdrop" id="sh-modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="sh-modal-title" aria-hidden="true">
<div class="sh-modal" role="document">
<div class="sh-modal-head">
<div style="min-width:0">
<div class="sh-modal-title" id="sh-modal-title">Issue</div>
<div class="sh-modal-sub" id="sh-modal-sub"></div>
</div>
<button class="sh-modal-close" id="sh-modal-close" aria-label="Close">✕</button>
</div>
<div class="sh-modal-body">
<div class="sh-modal-meta" id="sh-modal-meta"></div>
<div class="sh-modal-section-title">Impact</div>
<div class="sh-modal-impact" id="sh-modal-impact"></div>
<div class="sh-modal-section-title">Updates</div>
<div class="sh-modal-posts" id="sh-modal-posts"></div>
</div>
</div>
</div>
<script>
let allServices = [];
let trendRange = 30;
let isPaused = false;
let expandedIssues = false;
let refreshTimer = null;
let issuesById = new Map();
// The shared toggleTheme() in /static/util.js handles the theme flip and
// button label. Wrap it so the trend SVG re-renders with new theme colors.
(function () {
const sharedToggle = window.toggleTheme;
window.toggleTheme = function () {
if (sharedToggle) sharedToggle();
if (typeof renderTrend === 'function') renderTrend();
};
})();
function statusClass(status) {
if (!status) return 'unknown';
const s = status.toLowerCase();
// Graph healthOverviews returns "serviceOperational" / "serviceRestored"
// for healthy services. Treat both as operational.
if (s === 'operational' || s === 'serviceoperational' || s === 'servicerestored') return 'operational';
if (s.includes('degradation')) return 'degraded';
if (s.includes('interruption')) return 'incident';
if (s.includes('restoring')) return 'restoring';
if (s.includes('investigating')) return 'investigating';
if (s.includes('extended')) return 'extended';
return 'unknown';
}
// escapeHtml() is provided by /static/util.js.
function severityFromIssue(it) {
const s = String(it.status || '').toLowerCase();
if (s.includes('extended')) return 'extended';
if (s.includes('interruption')) return 'incident';
if (s.includes('degradation')) return 'degraded';
if (s.includes('restoring')) return 'restoring';
if (s.includes('investigating')) return 'investigating';
// Fallback by classification.
const cls = String(it.classification || '').toLowerCase();
if (cls === 'incident') return 'incident';
if (cls === 'advisory') return 'degraded';
return 'unknown';
}
function humanizeStatus(status, sevFallback) {
if (!status) return sevFallback || 'active';
// Convert camelCase Graph status (e.g. "serviceDegradation") into spaced words.
return String(status)
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/^service\s+/i, '')
.toLowerCase();
}
function humanizeClassification(c) {
if (!c) return '';
const v = String(c).toLowerCase();
if (v === 'incident') return 'Incident';
if (v === 'advisory') return 'Advisory';
return c.charAt(0).toUpperCase() + c.slice(1);
}
function formatShortDate(d) {
return d.toLocaleDateString(undefined, { month: 'numeric', day: 'numeric', year: 'numeric' });
}
function formatShortTime(d) {
return d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit', hour12: true });
}
function formatTickDate(d) {
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
async function loadServiceHealth() {
if (isPaused) return;
try {
const res = await fetch('/api/servicehealth');
const data = await res.json();
if (data.error) {
document.getElementById('sh-breakdown').innerHTML = `<div class="sh-empty">⚠️ ${escapeHtml(data.error)}</div>`;
document.getElementById('sh-sidebar-list').innerHTML = `<div class="sh-empty">⚠️ ${escapeHtml(data.error)}</div>`;
return;
}
allServices = data.services || [];
document.getElementById('sh-updated').textContent =
`Last updated: ${formatShortTime(new Date())}`;
recordSnapshot();
renderStats();
renderBreakdown();
renderSidebar();
renderRecentActivity();
renderHeatmap();
renderTrend();
} catch (err) {
document.getElementById('sh-breakdown').innerHTML =
`<div class="sh-empty">❌ ${escapeHtml(err.message)}</div>`;
}
}
function isActiveIssue(i) {
if (!i) return false;
if (i.isResolved === true) return false;
if (i.endDateTime) return false;
const s = String(i.status || '').toLowerCase();
// Treat any "resolved"-family status as inactive.
if (s.includes('restored') || s.includes('resolved') || s.includes('mitigated') ||
s.includes('postincident') || s.includes('falsepositive') || s.includes('suspended')) {
return false;
}
return true;
}
function getCounts() {
let degraded = 0, incident = 0, extended = 0, operational = 0, totalIssues = 0;
const affected = new Set();
const breakdown = new Map();
for (const svc of allServices) {
const sc = statusClass(svc.status);
if (sc === 'operational') operational++;
else if (sc === 'degraded') degraded++;
else if (sc === 'incident') incident++;
else if (sc === 'extended') extended++;
const activeIssues = (svc.issues || []).filter(isActiveIssue);
if (activeIssues.length > 0) {
const name = svc.service || svc.displayName || 'Unknown';
affected.add(name);
breakdown.set(name, activeIssues.length);
}
totalIssues += activeIssues.length;
}
return { degraded, incident, extended, operational, totalIssues, affected: affected.size, breakdown };
}
function renderStats() {
const c = getCounts();
document.getElementById('sh-stat-degraded').textContent = c.degraded;
document.getElementById('sh-stat-extended').textContent = c.extended;
document.getElementById('sh-stat-issues').textContent = c.totalIssues;
const operationalEl = document.getElementById('sh-stat-operational');
if (operationalEl) operationalEl.textContent = c.operational;
const issuesTotal = document.getElementById('sh-issues-total');
if (issuesTotal) issuesTotal.textContent = c.totalIssues;
renderDonut(c);
}
function renderDonut(c) {
const svg = document.getElementById('sh-donut-svg');
const totalEl = document.getElementById('sh-donut-total');
if (!svg) return;
const styles = getComputedStyle(document.documentElement);
const cDanger = styles.getPropertyValue('--cp-danger').trim() || '#dc2626';
const cWarning = styles.getPropertyValue('--cp-warning').trim() || '#f59e0b';
const cSuccess = styles.getPropertyValue('--cp-success').trim() || '#16a34a';
const cTrack = styles.getPropertyValue('--cp-border').trim() || '#dedede';
// Donut ring on a 42x42 viewBox; circumference of r=15.915 ≈ 100 (percent-friendly).
const segments = [
{ value: c.operational, color: cSuccess },
{ value: c.degraded + c.incident, color: cDanger },
{ value: c.extended, color: cWarning },
];
const total = segments.reduce((s, x) => s + x.value, 0);
if (totalEl) totalEl.textContent = total || '—';
const C = 100;
const stroke = 6;
let cum = 0;
const ringParts = [];
ringParts.push(`<circle cx="21" cy="21" r="15.915" fill="none" stroke="${cTrack}" stroke-width="${stroke}" stroke-opacity="0.35"/>`);
if (total > 0) {
for (const seg of segments) {
if (seg.value <= 0) continue;
const len = (seg.value / total) * C;
ringParts.push(
`<circle cx="21" cy="21" r="15.915" fill="none" stroke="${seg.color}" stroke-width="${stroke}" ` +
`stroke-dasharray="${len.toFixed(3)} ${(C - len).toFixed(3)}" ` +
`stroke-dashoffset="${(-cum).toFixed(3)}" stroke-linecap="butt"/>`
);
cum += len;
}
}
svg.innerHTML = ringParts.join('');
}
function renderBreakdown() {
const c = getCounts();
const rows = [...c.breakdown.entries()]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
document.getElementById('sh-breakdown-total').textContent = c.totalIssues;
const container = document.getElementById('sh-breakdown');
if (!rows.length) {
container.innerHTML = '<div class="sh-empty">✓ No active issues</div>';
return;
}
container.innerHTML = rows.map(([name, n]) => `
<div class="sh-breakdown-row">
<span class="sh-breakdown-name" title="${escapeHtml(name)}">${escapeHtml(name)}</span>
<span class="sh-breakdown-count">${n}</span>
</div>`).join('');
}
function flatIssues() {
const out = [];
for (const svc of allServices) {
const name = svc.service || svc.displayName || 'Unknown Service';
for (const i of (svc.issues || [])) {
if (!isActiveIssue(i)) continue;
out.push({
service: name,
id: i.id || '',
title: i.title || 'Active issue',
impact: i.impactDescription || '',
classification: i.classification || '',
status: i.status || '',
feature: i.feature || '',
featureGroup: i.featureGroup || '',
highImpact: !!i.highImpact,
startDateTime: i.startDateTime || null,
endDateTime: i.endDateTime || null,
lastModifiedDateTime: i.lastModifiedDateTime || i.startDateTime || null,
posts: Array.isArray(i.posts) ? i.posts : [],
});
}
}
out.sort((a, b) => {
const ta = new Date(a.lastModifiedDateTime || 0).getTime();
const tb = new Date(b.lastModifiedDateTime || 0).getTime();
return tb - ta;
});
return out;
}
function renderSidebar() {
const list = flatIssues();
const container = document.getElementById('sh-sidebar-list');
if (!list.length) {
container.innerHTML = '<div class="sh-empty">✓ All services operational</div>';
return;
}
// Stash the latest list so the modal can look an issue up by id.
issuesById = new Map(list.map(it => [it.id, it]));
const expandBtn = document.getElementById('sh-expand-btn');
if (expandBtn) expandBtn.style.display = list.length > 25 ? '' : 'none';
const items = expandedIssues ? list : list.slice(0, 25);
container.innerHTML = items.map(it => {
const sev = severityFromIssue(it);
const dt = it.lastModifiedDateTime ? new Date(it.lastModifiedDateTime) : null;
const timeStr = dt ? `${formatShortDate(dt)} · ${formatShortTime(dt)}` : '';
const cls = humanizeClassification(it.classification);
return `
<div class="sh-issue-card sev-${sev}"
role="button" tabindex="0"
data-issue-id="${escapeHtml(it.id)}"
aria-label="${escapeHtml(it.title)} — ${escapeHtml(it.service)}"
title="${escapeHtml(it.title)}">
<div class="sh-issue-head">
${cls ? `<span class="sh-issue-class">${escapeHtml(cls)}</span>` : ''}
<span class="sh-issue-service">${(window.ProductIcons ? window.ProductIcons.productIconImg(it.service) : '')}<span>${escapeHtml(it.service)}</span></span>
</div>
<div class="sh-issue-title">${escapeHtml(it.title)}</div>
<div class="sh-issue-foot">
<span class="sh-issue-id">${escapeHtml(it.id)}</span>
<span class="sh-issue-time">${escapeHtml(timeStr)}</span>
</div>
</div>`;
}).join('');
}
function renderRecentActivity() {
const list = flatIssues().slice(0, 6);
const container = document.getElementById('sh-activity');
const countEl = document.getElementById('sh-activity-total');
const total = flatIssues().length;
if (countEl) countEl.textContent = total;
if (!list.length) {
container.innerHTML = '<div class="sh-empty">✓ No recent activity</div>';
return;
}
container.innerHTML = list.map(it => {
const sev = severityFromIssue(it);
const dt = it.lastModifiedDateTime ? new Date(it.lastModifiedDateTime) : null;
const ago = dt ? timeAgo(dt) : '';
return `
<div class="sh-activity-row">
<span class="sh-activity-dot sev-${sev}"></span>
<div class="sh-activity-body">
<div class="sh-activity-title" title="${escapeHtml(it.title)}">${escapeHtml(it.title)}</div>
<div class="sh-activity-meta">
<span>${escapeHtml(it.service)}</span>
<span>${escapeHtml(ago)}</span>
</div>
</div>
</div>`;
}).join('');
}
function timeAgo(dt) {
const diff = Date.now() - dt.getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return 'just now';
if (mins < 60) return mins + 'm ago';
const hrs = Math.floor(mins / 60);
if (hrs < 24) return hrs + 'h ago';
const days = Math.floor(hrs / 24);
return days + 'd ago';
}
function renderHeatmap() {
const container = document.getElementById('sh-heatmap');
const DAYS = 14;
const today = new Date(); today.setHours(0,0,0,0);
// Build per-service per-day status from allServices issue data.
const svcMap = new Map();
for (const svc of allServices) {
const name = svc.service || svc.displayName || 'Unknown';
if (!svcMap.has(name)) svcMap.set(name, new Map());
const dayMap = svcMap.get(name);
for (const issue of (svc.issues || [])) {
const start = issue.startDateTime ? new Date(issue.startDateTime) : null;
const end = issue.endDateTime ? new Date(issue.endDateTime) : (issue.isResolved ? null : new Date());
if (!start) continue;
const cls = String(issue.classification || '').toLowerCase();
const weight = cls === 'incident' ? 2 : 1;
for (let di = 0; di < DAYS; di++) {
const d = new Date(today); d.setDate(today.getDate() - (DAYS - 1 - di));
const dk = dayKey(d);
const dEnd = new Date(d); dEnd.setHours(23,59,59,999);
if (start <= dEnd && (!end || end >= d)) {
dayMap.set(dk, Math.max(dayMap.get(dk) || 0, weight));
}
}
}
}
// Pick top services (those with any issues, plus top operational ones, up to 6).
let svcNames = [...svcMap.entries()]
.filter(([, dm]) => [...dm.values()].some(v => v > 0))
.sort((a, b) => {
const sa = [...a[1].values()].reduce((s,v) => s+v, 0);
const sb = [...b[1].values()].reduce((s,v) => s+v, 0);
return sb - sa;
})
.map(([n]) => n)
.slice(0, 6);
// If fewer than 3, pad with operational services for context.
if (svcNames.length < 3) {
for (const svc of allServices) {
const n = svc.service || svc.displayName || 'Unknown';
if (!svcNames.includes(n)) { svcNames.push(n); }
if (svcNames.length >= 5) break;
}
}
if (!svcNames.length) {
container.innerHTML = '<div class="sh-empty">No service data</div>';
return;
}
const cols = DAYS + 1; // +1 for label column
let html = `<div class="sh-heatmap" style="grid-template-columns: 100px repeat(${DAYS}, 1fr);">`;
// Day header row.
html += '<div class="sh-heatmap-label"></div>';
for (let di = 0; di < DAYS; di++) {
const d = new Date(today); d.setDate(today.getDate() - (DAYS - 1 - di));
const label = di === DAYS - 1 ? 'Today' : `${d.getMonth()+1}/${d.getDate()}`;
html += `<div class="sh-heatmap-daylabel">${label}</div>`;
}
// Service rows.
for (const name of svcNames) {
html += `<div class="sh-heatmap-label" title="${escapeHtml(name)}">${escapeHtml(name)}</div>`;
const dayMap = svcMap.get(name) || new Map();
for (let di = 0; di < DAYS; di++) {
const d = new Date(today); d.setDate(today.getDate() - (DAYS - 1 - di));
const dk = dayKey(d);
const v = dayMap.get(dk) || 0;
const cls = v >= 2 ? 'hm-incident' : v === 1 ? 'hm-degraded' : 'hm-ok';
const tip = `${name} — ${d.getMonth()+1}/${d.getDate()}: ${v >= 2 ? 'Incident' : v === 1 ? 'Degraded' : 'Operational'}`;
html += `<div class="sh-heatmap-cell ${cls}" title="${escapeHtml(tip)}" data-svc="${escapeHtml(name)}" data-day="${dk}"></div>`;
}
}
html += '</div>';
container.innerHTML = html;
}
// Heatmap click handler — event delegation on the static container (registered once)
document.getElementById('sh-heatmap').addEventListener('click', (ev) => {
const cell = ev.target.closest('.sh-heatmap-cell');
if (!cell) return;
const svcName = cell.getAttribute('data-svc');
const day = cell.getAttribute('data-day');
if (!svcName || !day) return;
const v = cell.classList.contains('hm-incident') ? 2 : cell.classList.contains('hm-degraded') ? 1 : 0;
if (v === 0) return;
openHeatmapDayIssues(svcName, day);
});
/**
* Find issues for a service on a specific day and open the detail modal.
*/
function openHeatmapDayIssues(svcName, dayStr) {
const dayStart = new Date(dayStr + 'T00:00:00');
const dayEnd = new Date(dayStr + 'T23:59:59.999');
const matches = [];
for (const svc of allServices) {
const name = svc.service || svc.displayName || 'Unknown';
if (name !== svcName) continue;
for (const issue of (svc.issues || [])) {
const start = issue.startDateTime ? new Date(issue.startDateTime) : null;
const end = issue.endDateTime ? new Date(issue.endDateTime) : (issue.isResolved ? null : new Date());
if (!start) continue;
if (start <= dayEnd && (!end || end >= dayStart)) {
matches.push({
service: name,
id: issue.id || '',
title: issue.title || 'Active issue',
impact: issue.impactDescription || '',
classification: issue.classification || '',
status: issue.status || '',
feature: issue.feature || '',
featureGroup: issue.featureGroup || '',
highImpact: !!issue.highImpact,
startDateTime: issue.startDateTime || null,
endDateTime: issue.endDateTime || null,
lastModifiedDateTime: issue.lastModifiedDateTime || issue.startDateTime || null,
posts: Array.isArray(issue.posts) ? issue.posts : [],
});
}
}
}
if (!matches.length) return;
// Ensure issuesById has these entries so openIssueModal can find them
for (const m of matches) issuesById.set(m.id, m);
if (matches.length === 1) {
openIssueModal(matches[0].id);
} else {
openHeatmapIssuePicker(svcName, dayStr, matches);
}
}
/**
* Show a picker modal when multiple issues match a heatmap cell.
*/
function openHeatmapIssuePicker(svcName, dayStr, issues) {
const d = new Date(dayStr + 'T00:00:00');
const dateLabel = `${d.getMonth()+1}/${d.getDate()}`;
document.getElementById('sh-modal-title').textContent = `${svcName} — ${dateLabel}`;
document.getElementById('sh-modal-sub').innerHTML =
`<span class="sh-issue-class">${issues.length} issue${issues.length > 1 ? 's' : ''} on this day</span>`;
document.getElementById('sh-modal-meta').innerHTML = '';
document.getElementById('sh-modal-impact').textContent = '';
document.getElementById('sh-modal-posts').innerHTML = issues.map(it => {
const sev = severityFromIssue(it);
const status = humanizeStatus(it.status, sev);
const cls = humanizeClassification(it.classification);
const last = it.lastModifiedDateTime ? new Date(it.lastModifiedDateTime) : null;
const timeStr = last ? `${formatShortDate(last)} · ${formatShortTime(last)}` : '';
return `
<div class="sh-modal-post" style="cursor:pointer" role="button" tabindex="0"
onclick="closeIssueModal(); setTimeout(function(){ openIssueModal('${escapeHtml(it.id)}'); }, 160)">
<div class="sh-modal-post-head">
<span class="sh-issue-pill sev-${sev}" style="font-size:10px"><span class="sh-issue-pill-dot"></span>${escapeHtml(status)}</span>
<span>${escapeHtml(timeStr)}</span>
</div>
<div class="sh-modal-post-body" style="font-weight:600">${escapeHtml(it.title)}</div>
<div style="font-size:11px;color:var(--cp-text-muted);margin-top:0.3rem">
${cls ? `<span>${escapeHtml(cls)}</span> · ` : ''}${escapeHtml(it.feature || '')}
</div>
</div>`;
}).join('');
const backdrop = document.getElementById('sh-modal-backdrop');
backdrop.classList.add('open');
backdrop.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
}
function toggleExpandIssues() {
expandedIssues = !expandedIssues;
const btn = document.getElementById('sh-expand-btn');
btn.textContent = expandedIssues ? 'Show less' : 'Show all';
btn.setAttribute('aria-expanded', String(expandedIssues));
renderSidebar();
}
function togglePause() {
isPaused = !isPaused;
const btn = document.getElementById('sh-pause-btn');
btn.textContent = isPaused ? 'Resume' : 'Pause';
btn.setAttribute('aria-pressed', String(isPaused));
if (isPaused) {
if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; }
} else {
scheduleRefresh();
loadServiceHealth();
}
}
function scheduleRefresh() {
if (refreshTimer) clearInterval(refreshTimer);
refreshTimer = setInterval(() => loadServiceHealth(), 60_000);
}
// ── 30-day trend ────────────────────────────────────────────────────────
// Persist a daily snapshot in localStorage so over time real history
// accumulates. Until enough days are recorded, pad with deterministic
// synthetic points so the chart visualizes meaningfully on first load.
const TREND_KEY = 'sh-trend-history-v1';
function loadHistory() {
try {
const raw = localStorage.getItem(TREND_KEY);
return raw ? JSON.parse(raw) : {};
} catch { return {}; }
}
function saveHistory(h) {
try { localStorage.setItem(TREND_KEY, JSON.stringify(h)); } catch {}
}
function dayKey(d) {
return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}
function recordSnapshot() {
const h = loadHistory();
const c = getCounts();
h[dayKey(new Date())] = {
active: c.totalIssues,
affected: c.affected,
operational: c.operational,
};
// Trim anything older than 60 days.
const cutoff = Date.now() - 60 * 24 * 60 * 60 * 1000;
for (const k of Object.keys(h)) {
if (new Date(k).getTime() < cutoff) delete h[k];
}
saveHistory(h);
}
// Deterministic seeded RNG (mulberry32) for stable synthetic points.
function rng(seed) {
return () => {
seed |= 0; seed = seed + 0x6D2B79F5 | 0;
let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
function buildSeries(days) {
const h = loadHistory();
const c = getCounts();
const today = new Date();
today.setHours(0, 0, 0, 0);
const seedBase = today.getFullYear() * 1000 + (today.getMonth() + 1) * 31 + today.getDate();
const rand = rng(seedBase);
const out = [];
for (let i = days - 1; i >= 0; i--) {
const d = new Date(today);
d.setDate(today.getDate() - i);
const key = dayKey(d);
const real = h[key];
if (real) {
out.push({ date: d, ...real });
} else if (i === 0) {
// Today's point — always use live counts.
out.push({ date: d, active: c.totalIssues, affected: c.affected, operational: c.operational });
} else {
// Synthesize a believable variation around current values.
const wobble = (mid, span) => Math.max(0, Math.round(mid + (rand() - 0.5) * span));
out.push({
date: d,
active: wobble(Math.max(c.totalIssues, 6), 8),
affected: wobble(Math.max(c.affected, 4), 4),
operational: wobble(Math.max(c.operational, 26), 4),
});
}
}
return out;
}
function renderTrend() {
const svg = document.getElementById('sh-trend-svg');
if (!svg) return;
const W = 800, H = 90;
const pad = { top: 8, right: 12, bottom: 20, left: 28 };
const innerW = W - pad.left - pad.right;
const innerH = H - pad.top - pad.bottom;
const series = buildSeries(trendRange);
if (!series.length) { svg.innerHTML = ''; return; }
const maxY = Math.max(
4,
...series.map(s => Math.max(s.active || 0, s.affected || 0, s.operational || 0))
);
// Add a touch of headroom so the top line isn't right at the edge.
const niceMax = Math.ceil((maxY + 2) / 8) * 8 || 32;
const x = (i) => pad.left + (series.length === 1 ? innerW/2 : (i * innerW) / (series.length - 1));
const y = (v) => pad.top + innerH - (v / niceMax) * innerH;
const grid = [];
const ticks = 4;
for (let i = 0; i <= ticks; i++) {
const v = Math.round((niceMax / ticks) * i);
const yy = y(v);
grid.push(`<line x1="${pad.left}" x2="${W - pad.right}" y1="${yy}" y2="${yy}" stroke="currentColor" stroke-opacity="0.12" stroke-dasharray="2,3"/>`);
grid.push(`<text x="${pad.left - 6}" y="${yy + 3}" text-anchor="end" font-size="10" fill="currentColor" fill-opacity="0.55">${v}</text>`);
}
const xLabels = [];
const labelCount = Math.min(6, series.length);
for (let k = 0; k < labelCount; k++) {
const i = Math.round(((series.length - 1) * k) / (labelCount - 1));
const d = series[i].date;
const text = (k === labelCount - 1) ? 'Today' : formatTickDate(d);
xLabels.push(`<text x="${x(i)}" y="${H - 6}" text-anchor="middle" font-size="10" fill="currentColor" fill-opacity="0.55">${text}</text>`);
}
const linePath = (key, color) => {
const d = series.map((s, i) => `${i === 0 ? 'M' : 'L'} ${x(i).toFixed(1)} ${y(s[key] || 0).toFixed(1)}`).join(' ');
const dots = series.map((s, i) =>
`<circle cx="${x(i).toFixed(1)}" cy="${y(s[key] || 0).toFixed(1)}" r="2.5" fill="${color}"/>`
).join('');
return `<path d="${d}" stroke="${color}" stroke-width="2" fill="none" stroke-linejoin="round" stroke-linecap="round"/>${dots}`;
};
const styles = getComputedStyle(document.documentElement);
const cDanger = styles.getPropertyValue('--cp-danger').trim() || '#dc2626';
const cWarning = styles.getPropertyValue('--cp-warning').trim() || '#f59e0b';
const cSuccess = styles.getPropertyValue('--cp-success').trim() || '#16a34a';
svg.innerHTML = `
${grid.join('')}
${linePath('operational', cSuccess)}
${linePath('active', cDanger)}
${linePath('affected', cWarning)}
${xLabels.join('')}
`;
}
document.getElementById('sh-trend-toggle').addEventListener('click', (ev) => {
const btn = ev.target.closest('button[data-range]');
if (!btn) return;
trendRange = parseInt(btn.dataset.range, 10) || 30;
[...ev.currentTarget.querySelectorAll('button')].forEach(b => {
const active = b === btn;
b.classList.toggle('active', active);
b.setAttribute('aria-pressed', String(active));
});
renderTrend();
});
// ----- Issue detail modal -----
function openIssueModal(id) {
const it = issuesById.get(id);
if (!it) return;
const sev = severityFromIssue(it);
const cls = humanizeClassification(it.classification);
const status = humanizeStatus(it.status, sev);
const start = it.startDateTime ? new Date(it.startDateTime) : null;
const last = it.lastModifiedDateTime ? new Date(it.lastModifiedDateTime) : null;
const fmt = (d) => d ? `${formatShortDate(d)} · ${formatShortTime(d)}` : '—';
document.getElementById('sh-modal-title').textContent = it.title || 'Active issue';
const subParts = [
`<span class="sh-issue-pill sev-${sev}"><span class="sh-issue-pill-dot"></span>${escapeHtml(status)}</span>`,
cls ? `<span class="sh-issue-class">${escapeHtml(cls)}</span>` : '',
`<span class="sh-issue-service" style="margin-left:0;max-width:none">${escapeHtml(it.service)}</span>`,
].filter(Boolean).join('');
document.getElementById('sh-modal-sub').innerHTML = subParts;
const meta = [
{ label: 'Issue ID', value: it.id || '—', mono: true },
{ label: 'Started', value: fmt(start) },
{ label: 'Last updated', value: fmt(last) },
{ label: 'Feature', value: it.feature || '—' },
{ label: 'Feature group', value: it.featureGroup || '—' },
{ label: 'High impact', value: it.highImpact ? 'Yes' : 'No' },
];
document.getElementById('sh-modal-meta').innerHTML = meta.map(m => `
<div class="sh-modal-meta-item">
<div class="sh-modal-meta-label">${escapeHtml(m.label)}</div>
<div class="sh-modal-meta-val"${m.mono ? ' style="font-family:ui-monospace,Consolas,monospace"' : ''}>${escapeHtml(m.value)}</div>
</div>`).join('');
const impactEl = document.getElementById('sh-modal-impact');
const impactText = it.impact || '';
impactEl.textContent = impactText || 'No impact description provided.';
const postsEl = document.getElementById('sh-modal-posts');
const posts = (it.posts || []).slice().sort((a, b) =>
new Date(b.createdDateTime || 0) - new Date(a.createdDateTime || 0)
);
if (!posts.length) {
postsEl.innerHTML = '<div class="sh-empty" style="padding:0.75rem 0">No status updates posted.</div>';
} else {
postsEl.innerHTML = posts.map(p => {
const t = p.createdDateTime ? new Date(p.createdDateTime) : null;
const body = (p.description && p.description.content) || '';
// Posts come back as plain text (contentType usually 'html' in MC, but text in service health).
// Render as text to be safe.
return `
<div class="sh-modal-post">
<div class="sh-modal-post-head">
<span class="sh-modal-post-type">${escapeHtml(p.postType || 'update')}</span>
<span>${escapeHtml(t ? `${formatShortDate(t)} · ${formatShortTime(t)}` : '')}</span>
</div>
<div class="sh-modal-post-body">${escapeHtml(body)}</div>
</div>`;
}).join('');
}
const backdrop = document.getElementById('sh-modal-backdrop');
backdrop.classList.add('open');
backdrop.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
if (window.CportalAi && window.CportalAi.isEnabled()) {
// Service health issues lack a description field — synthesize one for the AI from impact + latest post.
const latestPost = (it.posts || []).slice().sort((a, b) =>
new Date(b.createdDateTime || 0) - new Date(a.createdDateTime || 0))[0];
const aiItem = {
id: it.id,
title: it.title,
description: [it.impact, latestPost && latestPost.description && latestPost.description.content]
.filter(Boolean).join('\n\n'),
link: '',
pubDate: it.lastModifiedDateTime || it.startDateTime,
categories: [it.classification, it.service, it.feature].filter(Boolean),
};
window.CportalAi.attachToModal(
document.querySelector('#sh-modal-backdrop .sh-modal-body'),
'servicehealth', aiItem);
}
}
function closeIssueModal() {
const backdrop = document.getElementById('sh-modal-backdrop');
backdrop.classList.remove('open');
backdrop.setAttribute('aria-hidden', 'true');
document.body.style.overflow = '';
}
document.getElementById('sh-sidebar-list').addEventListener('click', (ev) => {
const card = ev.target.closest('.sh-issue-card');
if (!card) return;
const id = card.getAttribute('data-issue-id');
if (id) openIssueModal(id);
});
document.getElementById('sh-sidebar-list').addEventListener('keydown', (ev) => {
if (ev.key !== 'Enter' && ev.key !== ' ') return;
const card = ev.target.closest('.sh-issue-card');
if (!card) return;
ev.preventDefault();
const id = card.getAttribute('data-issue-id');
if (id) openIssueModal(id);
});
document.getElementById('sh-modal-backdrop').addEventListener('click', (ev) => {
if (ev.target === ev.currentTarget) closeIssueModal();
});
document.getElementById('sh-modal-close').addEventListener('click', closeIssueModal);
document.addEventListener('keydown', (ev) => {
if (ev.key === 'Escape' && document.getElementById('sh-modal-backdrop').classList.contains('open')) {
closeIssueModal();
}
});
// Initial load + auto-refresh every minute
loadServiceHealth();
scheduleRefresh();
// ════════════════════════════════════════════════
// GENERATE EXPORT MODAL
// ════════════════════════════════════════════════
const EXPORT_MODAL_CONFIG = {
getAllRows: () => (typeof flatIssues === 'function' ? flatIssues() : []),
getProducts: (it) => [it && it.service].filter(Boolean),
getDate: (it) => { const d = Date.parse((it && (it.startDateTime || it.lastModifiedDateTime)) || ''); return isNaN(d) ? null : d; },
runExport: (rows, format) => exportServiceHealthToHtml(rows, format),
};
const EXPORT_UNCLASSIFIED = '(Unclassified)';
function getExportProducts(row) {
const arr = (EXPORT_MODAL_CONFIG.getProducts(row) || []).map(p => String(p || '').trim()).filter(Boolean);
return arr.length ? arr : [EXPORT_UNCLASSIFIED];
}
function openExportModal() {
const rows = EXPORT_MODAL_CONFIG.getAllRows() || [];
if (!rows.length) { alert('No active issues to export.'); return; }
const set = new Set();
rows.forEach(r => getExportProducts(r).forEach(p => set.add(p)));
const products = Array.from(set).sort((a, b) => {
if (a === EXPORT_UNCLASSIFIED) return 1;
if (b === EXPORT_UNCLASSIFIED) return -1;
return a.localeCompare(b);
});
const list = document.getElementById('gen-product-list');
if (!products.length) {
list.innerHTML = '<div class="gen-empty">No services found.</div>';
} else {
list.innerHTML = products.map(p => {
const safe = p.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
return `<label data-product="${safe.toLowerCase()}"><input type="checkbox" value="${safe}" checked> ${safe}</label>`;
}).join('');
}
document.getElementById('gen-from-date').value = '';