-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHome.razor
More file actions
1002 lines (902 loc) · 36.9 KB
/
Home.razor
File metadata and controls
1002 lines (902 loc) · 36.9 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
@page "/"
@using DevMetricsPro.Application.DTOs
@using DevMetricsPro.Application.DTOs.Charts
@using DevMetricsPro.Application.DTOs.Metrics
@using DevMetricsPro.Application.Enums
@using DevMetricsPro.Application.Interfaces
@using DevMetricsPro.Web.Components.Shared
@using DevMetricsPro.Web.Components.Shared.Charts
@using DevMetricsPro.Web.Services
@using Microsoft.AspNetCore.SignalR.Client
@implements IAsyncDisposable
@implements IDisposable
@inject AuthStateService AuthState
@inject IChartDataService ChartDataService
@inject ILeaderboardService LeaderboardService
@inject IMetricsCalculationService MetricsService
@inject SignalRService SignalR
@inject DashboardStateService DashboardState
@inject HttpClient Http
@inject NavigationManager Navigation
@inject ILogger<Home> Logger
@inject ISnackbar Snackbar
<PageTitle>Dashboard - DevMetrics Pro</PageTitle>
<!-- Sync Status Indicator -->
@if (_isSyncing)
{
<MudAlert Severity="Severity.Info" Class="mb-4" Icon="@Icons.Material.Filled.Sync">
<div style="display: flex; align-items: center; gap: 12px;">
<MudProgressCircular Size="Size.Small" Indeterminate="true" />
<span>Syncing data from GitHub... Dashboard will update automatically.</span>
</div>
</MudAlert>
}
<!-- Connection Status (only show when disconnected) -->
@if (_isAuthenticated && !_isSignalRConnected && _signalRConnectionAttempted)
{
<MudAlert Severity="Severity.Warning" Class="mb-4" Icon="@Icons.Material.Filled.CloudOff">
<span>Real-time updates unavailable. Data will still refresh on page reload.</span>
</MudAlert>
}
@if (!_isAuthenticated)
{
<div style="text-align: center; padding: 60px 20px;">
<h1 style="font-size: 32px; margin-bottom: 16px; color: var(--text-primary);">Welcome to DevMetrics Pro</h1>
<p style="font-size: 16px; margin-bottom: 24px; color: var(--text-secondary);">
A real-time developer analytics platform for tracking team productivity and code quality.
</p>
<a href="/login" class="panel-action" style="padding: 12px 24px; font-size: 16px; text-decoration: none; display: inline-block;">
Get Started
</a>
</div>
}
else
{
<!-- Global Time Range Selector - Phase 3.9 -->
<MudPaper Class="pa-3 mb-4" Elevation="1">
<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">
<MudText Typo="Typo.subtitle1" Style="font-weight: 600;">
<MudIcon Icon="@Icons.Material.Filled.FilterAlt" Size="Size.Small" Class="mr-2" />
Dashboard Filter
</MudText>
<TimeRangeSelector />
</div>
</MudPaper>
<!-- Metrics Grid -->
<div class="metrics-grid">
<MetricCard
Label="Total Commits"
Value="@_totalCommits.ToString("N0")"
Change="+12.5% from last week"
Trend="MetricCard.TrendDirection.Up" />
<MetricCard
Label="Pull Requests"
Value="89"
Change="+8.3% from last week"
Trend="MetricCard.TrendDirection.Up" />
<MetricCard
Label="Active Developers"
Value="24"
Change="+2 this month"
Trend="MetricCard.TrendDirection.Up" />
<MetricCard
Label="Code Reviews"
Value="156"
Change="+15.2% from last week"
Trend="MetricCard.TrendDirection.Up" />
</div>
<!-- Commit Activity Chart - Phase 3.2 -->
<MudPaper Class="pa-4 mt-4">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
<MudText Typo="Typo.h5">📈 Commit Activity</MudText>
</div>
@if (_isLoadingChart)
{
<div style="text-align: center; padding: 60px;">
<MudProgressCircular Indeterminate="true" />
<MudText Class="mt-2">Loading chart data...</MudText>
</div>
}
else if (_chartData != null && _chartData.TotalCommits > 0)
{
<!-- Stats Row -->
<div style="display: flex; gap: 24px; margin-bottom: 16px; padding: 12px; background: rgba(0,0,0,0.02); border-radius: 4px;">
<div>
<MudText Typo="Typo.body2" Style="color: var(--mud-palette-text-secondary);">Total Commits</MudText>
<MudText Typo="Typo.h6" Style="color: var(--mud-palette-primary);">@_chartData.TotalCommits</MudText>
</div>
<div>
<MudText Typo="Typo.body2" Style="color: var(--mud-palette-text-secondary);">Daily Average</MudText>
<MudText Typo="Typo.h6" Style="color: var(--mud-palette-primary);">@_chartData.AveragePerDay.ToString("F1")</MudText>
</div>
<div>
<MudText Typo="Typo.body2" Style="color: var(--mud-palette-text-secondary);">Date Range</MudText>
<MudText Typo="Typo.body2">@_chartData.StartDate.ToString("MMM dd") - @_chartData.EndDate.ToString("MMM dd")</MudText>
</div>
</div>
<!-- Chart -->
<LineChart
Labels="@_chartData.Labels"
Data="@_chartData.Values"
ChartTitle="Daily Commits"
ShowLegend="true" />
}
else
{
<div style="text-align: center; padding: 60px; color: var(--mud-palette-text-secondary);">
<div style="font-size: 48px; margin-bottom: 16px;">📊</div>
<MudText Typo="Typo.h6">No commit data available</MudText>
<MudText Typo="Typo.body2">Connect GitHub and sync your repositories to see commit activity</MudText>
</div>
}
</MudPaper>
<!-- PR Statistics Chart - Phase 3.3 -->
<MudPaper Class="pa-4 mt-4">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
<MudText Typo="Typo.h5">🔀 Pull Request Statistics</MudText>
</div>
@if (_isLoadingPRChart)
{
<div style="text-align: center; padding: 60px;">
<MudProgressCircular Indeterminate="true" />
<MudText Class="mt-2">Loading PR statistics...</MudText>
</div>
}
else if (_prChartData != null && _prChartData.TotalPRs > 0)
{
<!-- Stats Row -->
<div style="display: flex; gap: 24px; margin-bottom: 16px; padding: 12px; background: rgba(0,0,0,0.02); border-radius: 4px;">
<div>
<MudText Typo="Typo.body2" Style="color: var(--mud-palette-text-secondary);">Total PRs</MudText>
<MudText Typo="Typo.h6" Style="color: var(--mud-palette-primary);">@_prChartData.TotalPRs</MudText>
</div>
@if (_prChartData.AverageReviewTimeHours.HasValue)
{
<div>
<MudText Typo="Typo.body2" Style="color: var(--mud-palette-text-secondary);">Avg Review Time</MudText>
<MudText Typo="Typo.h6" Style="color: var(--mud-palette-primary);">
@if (_prChartData.AverageReviewTimeHours.Value < 24)
{
@($"{_prChartData.AverageReviewTimeHours.Value:F1}h")
}
else
{
@($"{(_prChartData.AverageReviewTimeHours.Value / 24):F1}d")
}
</MudText>
</div>
}
<div>
<MudText Typo="Typo.body2" Style="color: var(--mud-palette-text-secondary);">Date Range</MudText>
<MudText Typo="Typo.body2">@_prChartData.StartDate.ToString("MMM dd") - @_prChartData.EndDate.ToString("MMM dd")</MudText>
</div>
</div>
<!-- Chart -->
<BarChart
Labels="@_prChartData.Labels"
Data="@_prChartData.Values"
Title="Pull Requests by Status"
Color="rgba(75, 192, 192, 0.8)"
BorderColor="rgba(75, 192, 192, 1)" />
}
else
{
<div style="text-align: center; padding: 60px; color: var(--mud-palette-text-secondary);">
<div style="font-size: 48px; margin-bottom: 16px;">🔀</div>
<MudText Typo="Typo.h6">No pull request data available</MudText>
<MudText Typo="Typo.body2">Connect GitHub and sync your repositories to see PR statistics</MudText>
</div>
}
</MudPaper>
<!-- Contribution Heatmap - Phase 3.4 -->
<MudPaper Class="pa-4 mt-4">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
<MudText Typo="Typo.h5">🗓️ Contribution Activity</MudText>
</div>
<ContributionHeatmap
Data="@_heatmapData"
Title="Commit Contributions"
IsLoading="@_isLoadingHeatmap" />
</MudPaper>
<!-- Team Leaderboard - Phase 3.5 -->
<MudPaper Class="pa-4 mt-4">
<MudText Typo="Typo.h5" Class="mb-4">🏆 Top Contributors (@DashboardState.GetRangeLabel())</MudText>
<Leaderboard
Entries="@_leaderboardEntries"
Title="Team Leaderboard"
IsLoading="@_isLoadingLeaderboard"
ShowMetricSelector="true"
SelectedMetric="@_selectedMetric"
OnMetricChanged="OnLeaderboardMetricChanged" />
</MudPaper>
<!-- Advanced Metrics - Phase 3.8 -->
<div class="metrics-grid" style="margin-top: 24px;">
<!-- PR Review Time Metrics -->
<MudPaper Class="pa-4">
<MudText Typo="Typo.h6" Class="mb-3">⏱️ PR Review Time</MudText>
@if (_isLoadingReviewMetrics)
{
<div style="text-align: center; padding: 20px;">
<MudProgressCircular Size="Size.Small" Indeterminate="true" />
</div>
}
else if (_reviewMetrics != null && _reviewMetrics.TotalPRsAnalyzed > 0)
{
<div style="display: flex; flex-direction: column; gap: 12px;">
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--mud-palette-text-secondary);">Avg Time to Merge</span>
<strong style="color: var(--mud-palette-primary);">@_reviewMetrics.AverageTimeToMergeFormatted</strong>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--mud-palette-text-secondary);">Median</span>
<strong>@FormatDuration(_reviewMetrics.MedianTimeToMergeHours)</strong>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--mud-palette-text-secondary);">Merge Rate</span>
<strong style="color: @(_reviewMetrics.MergeRatePercent >= 70 ? "var(--mud-palette-success)" : "var(--mud-palette-warning)")">
@_reviewMetrics.MergeRatePercent.ToString("F0")%
</strong>
</div>
<MudDivider Class="my-2" />
<div style="display: flex; justify-content: space-between; font-size: 12px;">
<span>@_reviewMetrics.MergedPRs merged / @_reviewMetrics.TotalPRsAnalyzed total PRs</span>
</div>
</div>
}
else
{
<div style="text-align: center; color: var(--mud-palette-text-secondary); padding: 20px;">
<MudText Typo="Typo.body2">No PR data available</MudText>
</div>
}
</MudPaper>
<!-- Code Velocity Metrics -->
<MudPaper Class="pa-4">
<MudText Typo="Typo.h6" Class="mb-3">🚀 Code Velocity</MudText>
@if (_isLoadingVelocity)
{
<div style="text-align: center; padding: 20px;">
<MudProgressCircular Size="Size.Small" Indeterminate="true" />
</div>
}
else if (_velocityMetrics != null && _velocityMetrics.TotalCommits > 0)
{
<div style="display: flex; flex-direction: column; gap: 12px;">
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--mud-palette-text-secondary);">Avg Commits/Week</span>
<strong style="color: var(--mud-palette-primary);">@_velocityMetrics.AverageCommitsPerWeek.ToString("F1")</strong>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--mud-palette-text-secondary);">Avg Lines/Week</span>
<strong>@_velocityMetrics.AverageLinesPerWeek.ToString("N0")</strong>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="color: var(--mud-palette-text-secondary);">Trend</span>
<strong style="color: @GetTrendColor(_velocityMetrics.CommitTrend)">
@GetTrendIcon(_velocityMetrics.CommitTrend) @Math.Abs(_velocityMetrics.CommitTrendPercent).ToString("F0")%
</strong>
</div>
<MudDivider Class="my-2" />
<div style="display: flex; justify-content: space-between; font-size: 12px;">
<span>@_velocityMetrics.WeeksAnalyzed weeks analyzed</span>
</div>
</div>
}
else
{
<div style="text-align: center; color: var(--mud-palette-text-secondary); padding: 20px;">
<MudText Typo="Typo.body2">No velocity data available</MudText>
</div>
}
</MudPaper>
</div>
<!-- Panels Grid -->
<div class="panel-grid" style="margin-top: 24px;">
<DataPanel Title="Activity Overview">
<div style="text-align: center; padding: 60px 20px; color: var(--text-tertiary);">
<div style="font-size: 48px; margin-bottom: 16px;">📊</div>
<div style="font-size: 14px;">Chart visualization will be implemented in Sprint 3</div>
</div>
</DataPanel>
<DataPanel Title="Recent Activity">
@if (_recentCommits.Any())
{
<DataTable TItem="RecentCommitDto" Items="@_recentCommits">
<TableHeader>
<th>Commit</th>
<th class="text-right">Time</th>
</TableHeader>
<RowTemplate>
<td>
<div style="font-size: 13px; color: var(--text-primary); margin-bottom: 2px;">
@(context.Message.Length > 40 ? context.Message.Substring(0, 40) + "..." : context.Message)
</div>
<div class="text-small text-muted">
@context.AuthorName in @context.RepositoryName
</div>
</td>
<td class="text-right text-small text-muted">
@GetRelativeTime(context.CommittedAt)
</td>
</RowTemplate>
</DataTable>
}
else
{
<div style="text-align: center; padding: 40px 20px; color: var(--text-tertiary);">
<div style="font-size: 14px; margin-bottom: 4px;">No commits yet</div>
<div style="font-size: 12px;">Sync your repositories to see commits</div>
</div>
}
</DataPanel>
</div>
}
@if (_isAuthenticated)
{
<div style="margin-top: 24px; max-width: 600px;">
<DataPanel Title="GitHub Integration">
@if (!isGitHubConnected)
{
<p style="font-size: 14px; color: var(--text-secondary); margin-bottom: 16px;">
Connect your GitHub account to sync repositories and track metrics.
</p>
<button class="panel-action" @onclick="ConnectGitHub" disabled="@isConnectingGitHub"
style="padding: 8px 16px; background: var(--text-primary); color: white; cursor: @(isConnectingGitHub ? "not-allowed" : "pointer");">
@if (isConnectingGitHub)
{
<span>Connecting...</span>
}
else
{
<span>Connect GitHub</span>
}
</button>
}
else
{
<div style="padding: 12px; background: rgba(40, 167, 69, 0.1); border-radius: 4px; margin-bottom: 16px;">
<div style="color: var(--success); font-size: 14px;">
✓ Connected as <strong>@@@githubUsername</strong>
</div>
</div>
<p style="font-size: 14px; color: var(--text-secondary);">
Your GitHub account is linked and ready to sync.
</p>
}
@if (!string.IsNullOrEmpty(githubConnectedMessage))
{
<div style="padding: 12px; background: rgba(3, 102, 214, 0.1); border-radius: 4px; margin-top: 16px;">
<div style="color: var(--info); font-size: 14px;">@githubConnectedMessage</div>
</div>
}
</DataPanel>
</div>
}
@code {
private bool _isAuthenticated = false;
private int _totalCommits = 0;
private List<RecentCommitDto> _recentCommits = new();
private bool isConnectingGitHub = false;
private bool isGitHubConnected = false;
private string? githubUsername;
private string? githubConnectedMessage;
// Chart data - Phase 3.2
private CommitActivityChartDto? _chartData;
private bool _isLoadingChart = false;
// PR Chart data - Phase 3.3
private PullRequestChartDto? _prChartData;
private bool _isLoadingPRChart = false;
// Heatmap data - Phase 3.4
private ContributionHeatmapDto? _heatmapData;
private bool _isLoadingHeatmap = false;
// Leaderboard data - Phase 3.5
private List<LeaderboardEntryDto>? _leaderboardEntries;
private bool _isLoadingLeaderboard = false;
private LeaderboardMetric _selectedMetric = LeaderboardMetric.Commits;
// SignalR state - Phase 3.7
private bool _isSyncing = false;
private bool _isSignalRConnected = false;
private bool _signalRConnectionAttempted = false;
private string? _currentUserId;
// Advanced metrics - Phase 3.8
private ReviewTimeMetricsDto? _reviewMetrics;
private CodeVelocityDto? _velocityMetrics;
private bool _isLoadingReviewMetrics = false;
private bool _isLoadingVelocity = false;
protected override async Task OnInitializedAsync()
{
_isAuthenticated = await AuthState.IsAuthenticatedAsync();
if (_isAuthenticated)
{
// Get user ID for SignalR
_currentUserId = await AuthState.GetUserIdAsync();
// Subscribe to global time range changes - Phase 3.9
DashboardState.OnStateChanged += HandleTimeRangeChanged;
await CheckGitHubConnectionStatus();
await LoadRecentCommitsAsync();
// Load all charts using global time range
await LoadAllChartsAsync();
// Initialize SignalR connection
await InitializeSignalRAsync();
}
// Check if we were redirected back from GitHub OAuth
var uri = new Uri(Navigation.Uri);
var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
if (query["github"] == "connected")
{
githubConnectedMessage = "GitHub account connected successfully!";
await CheckGitHubConnectionStatus(); // Refresh status
}
}
/// <summary>
/// Handler for global time range changes - Phase 3.9
/// </summary>
private async void HandleTimeRangeChanged()
{
await InvokeAsync(async () =>
{
Logger.LogInformation("Time range changed to: {Start} - {End}",
DashboardState.StartDate, DashboardState.EndDate);
// Reload all charts with new time range
await LoadAllChartsAsync();
StateHasChanged();
});
}
/// <summary>
/// Loads all chart data using the global time range
/// </summary>
private async Task LoadAllChartsAsync()
{
var tasks = new List<Task>
{
LoadCommitActivityAsync(),
LoadPRStatsAsync(),
LoadHeatmapAsync(),
LoadLeaderboardAsync(_selectedMetric),
LoadAdvancedMetricsAsync()
};
await Task.WhenAll(tasks);
}
private async Task InitializeSignalRAsync()
{
if (string.IsNullOrEmpty(_currentUserId))
return;
try
{
// Register event handlers
SignalR.OnSyncStarted += HandleSyncStarted;
SignalR.OnSyncCompleted += HandleSyncCompleted;
SignalR.OnMetricsUpdated += HandleMetricsUpdated;
SignalR.OnConnectionStateChanged += HandleConnectionStateChanged;
// Start connection
await SignalR.StartAsync(_currentUserId);
_isSignalRConnected = true;
_signalRConnectionAttempted = true;
Logger.LogInformation("SignalR connected for dashboard updates");
}
catch (Exception ex)
{
Logger.LogError(ex, "Failed to initialize SignalR connection");
_isSignalRConnected = false;
_signalRConnectionAttempted = true;
// Don't show error - dashboard still works without real-time updates
}
}
private async Task HandleSyncStarted()
{
await InvokeAsync(() =>
{
_isSyncing = true;
StateHasChanged();
});
}
private async Task HandleSyncCompleted(SyncResultDto result)
{
await InvokeAsync(async () =>
{
_isSyncing = false;
if (result.Success)
{
// Show success notification
Snackbar.Add(
$"Sync complete! {result.RepositoriesSynced} repos, {result.CommitsSynced} commits, {result.PullRequestsSynced} PRs",
Severity.Success,
config => config.Icon = Icons.Material.Filled.CheckCircle);
// Refresh all dashboard data
await RefreshAllDataAsync();
}
else
{
Snackbar.Add(
$"Sync failed: {result.ErrorMessage ?? "Unknown error"}",
Severity.Error,
config => config.Icon = Icons.Material.Filled.Error);
}
StateHasChanged();
});
}
private async Task HandleMetricsUpdated()
{
await InvokeAsync(async () =>
{
Snackbar.Add("Metrics updated!", Severity.Info, config => config.Icon = Icons.Material.Filled.Refresh);
await RefreshAllDataAsync();
StateHasChanged();
});
}
private void HandleConnectionStateChanged(HubConnectionState state)
{
InvokeAsync(() =>
{
_isSignalRConnected = state == HubConnectionState.Connected;
if (state == HubConnectionState.Reconnecting)
{
Snackbar.Add("Connection lost. Reconnecting...", Severity.Warning);
}
else if (state == HubConnectionState.Connected && _signalRConnectionAttempted)
{
Snackbar.Add("Reconnected!", Severity.Success);
}
StateHasChanged();
});
}
private async Task RefreshAllDataAsync()
{
// Reload all data in parallel for efficiency
var tasks = new List<Task>
{
LoadRecentCommitsAsync(),
LoadAllChartsAsync()
};
await Task.WhenAll(tasks);
}
private async Task LoadAdvancedMetricsAsync()
{
// Load both metrics in parallel
var reviewTask = LoadReviewTimeMetricsAsync();
var velocityTask = LoadCodeVelocityAsync();
await Task.WhenAll(reviewTask, velocityTask);
}
private async Task LoadReviewTimeMetricsAsync()
{
_isLoadingReviewMetrics = true;
StateHasChanged();
try
{
// Use global time range from DashboardState - Phase 3.9
_reviewMetrics = await MetricsService.GetReviewTimeMetricsAsync(
developerId: null, // All developers
startDate: DashboardState.StartDate,
endDate: DashboardState.EndDate,
cancellationToken: default);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading review time metrics");
}
finally
{
_isLoadingReviewMetrics = false;
StateHasChanged();
}
}
private async Task LoadCodeVelocityAsync()
{
_isLoadingVelocity = true;
StateHasChanged();
try
{
// Calculate weeks from global time range - Phase 3.9
var days = DashboardState.GetDaysInRange();
var weeks = days == int.MaxValue ? 12 : Math.Max(1, days / 7);
_velocityMetrics = await MetricsService.GetCodeVelocityAsync(
developerId: null, // All developers
numberOfWeeks: weeks,
cancellationToken: default);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading code velocity metrics");
}
finally
{
_isLoadingVelocity = false;
StateHasChanged();
}
}
private static string FormatDuration(double hours)
{
if (hours < 1)
return $"{(int)(hours * 60)}m";
if (hours < 24)
return $"{hours:F1}h";
return $"{(hours / 24):F1}d";
}
private static string GetTrendColor(int trend) => trend switch
{
1 => "var(--mud-palette-success)",
-1 => "var(--mud-palette-error)",
_ => "var(--mud-palette-text-secondary)"
};
private static string GetTrendIcon(int trend) => trend switch
{
1 => "↑",
-1 => "↓",
_ => "→"
};
private async Task CheckGitHubConnectionStatus()
{
try
{
var token = await AuthState.GetTokenAsync();
if (string.IsNullOrEmpty(token))
return;
var request = new HttpRequestMessage(HttpMethod.Get, "/api/github/status");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var response = await Http.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var status = await response.Content.ReadFromJsonAsync<GitHubStatusResponse>();
if (status?.Connected == true)
{
isGitHubConnected = true;
githubUsername = status.Username;
}
}
else
{
await NotifyApiProblemAsync(response, "Unable to check GitHub connection status.", Severity.Warning);
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error checking GitHub connection status");
Snackbar.Add("Unable to check GitHub connection status.", Severity.Error);
}
}
private async Task ConnectGitHub()
{
isConnectingGitHub = true;
try
{
var token = await AuthState.GetTokenAsync();
if (string.IsNullOrEmpty(token))
{
Snackbar.Add("Please login first", Severity.Warning);
return;
}
// Create request with Authorization header
var request = new HttpRequestMessage(HttpMethod.Get, "/api/github/authorize");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var response = await Http.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<GitHubAuthResponse>();
if (result?.AuthorizationUrl != null)
{
// Redirect to GitHub authorization page
Navigation.NavigateTo(result.AuthorizationUrl, forceLoad: true);
}
}
else
{
await NotifyApiProblemAsync(response, "Failed to initiate GitHub connection.");
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error connecting to GitHub");
Snackbar.Add("Failed to connect to GitHub. Please try again.", Severity.Error);
}
finally
{
isConnectingGitHub = false;
}
}
private async Task LoadRecentCommitsAsync()
{
try
{
var token = await AuthState.GetTokenAsync();
if (string.IsNullOrEmpty(token))
return;
var request = new HttpRequestMessage(HttpMethod.Get, "/api/github/commits/recent?limit=10");
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var response = await Http.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<RecentCommitsResponse>();
if (result?.Success == true)
{
_totalCommits = result.TotalCommits;
_recentCommits = result.Commits ?? new List<RecentCommitDto>();
}
}
else
{
await NotifyApiProblemAsync(response, "Failed to load recent commits.");
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading recent commits");
Snackbar.Add("Failed to load recent commits.", Severity.Error);
}
}
private string GetRelativeTime(DateTime dateTime)
{
var timeSpan = DateTime.UtcNow - dateTime;
if (timeSpan.TotalMinutes < 1)
return "just now";
if (timeSpan.TotalMinutes < 60)
return $"{(int)timeSpan.TotalMinutes} minutes ago";
if (timeSpan.TotalHours < 24)
return $"{(int)timeSpan.TotalHours} hours ago";
if (timeSpan.TotalDays < 30)
return $"{(int)timeSpan.TotalDays} days ago";
return dateTime.ToString("MMM dd, yyyy");
}
private async Task NotifyApiProblemAsync(HttpResponseMessage response, string fallbackMessage, Severity severity = Severity.Error)
{
var message = await response.ReadProblemDetailsMessageAsync();
Snackbar.Add(message ?? fallbackMessage, severity);
}
private async Task LoadCommitActivityAsync()
{
_isLoadingChart = true;
StateHasChanged();
try
{
// Use global time range from DashboardState - Phase 3.9
_chartData = await ChartDataService.GetCommitActivityAsync(
developerId: null, // null = all developers
startDate: DashboardState.StartDate,
endDate: DashboardState.EndDate,
cancellationToken: default);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading commit activity chart");
Snackbar.Add("Failed to load chart data", Severity.Error);
}
finally
{
_isLoadingChart = false;
StateHasChanged();
}
}
private async Task LoadPRStatsAsync()
{
_isLoadingPRChart = true;
StateHasChanged();
try
{
// Use global time range from DashboardState - Phase 3.9
var days = DashboardState.GetDaysInRange();
if (days == int.MaxValue) days = 365; // Cap at 1 year for "All Time"
_prChartData = await ChartDataService.GetPullRequestStatsAsync(
days: days,
cancellationToken: default);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading PR statistics");
Snackbar.Add("Failed to load PR statistics", Severity.Error);
}
finally
{
_isLoadingPRChart = false;
StateHasChanged();
}
}
private async Task LoadHeatmapAsync()
{
_isLoadingHeatmap = true;
StateHasChanged();
try
{
// Calculate weeks from global time range - Phase 3.9
var days = DashboardState.GetDaysInRange();
var weeks = days == int.MaxValue ? 52 : Math.Max(1, days / 7);
_heatmapData = await ChartDataService.GetContributionHeatmapAsync(
numberOfWeeks: weeks,
cancellationToken: default);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading contribution heatmap");
Snackbar.Add("Failed to load contribution heatmap", Severity.Error);
}
finally
{
_isLoadingHeatmap = false;
StateHasChanged();
}
}
private async Task LoadLeaderboardAsync(LeaderboardMetric metric)
{
_selectedMetric = metric;
_isLoadingLeaderboard = true;
StateHasChanged();
try
{
// Use global time range from DashboardState - Phase 3.9
_leaderboardEntries = await LeaderboardService.GetLeaderboardAsync(
metric: metric,
topN: 10,
startDate: DashboardState.StartDate,
endDate: DashboardState.EndDate,
cancellationToken: default);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading leaderboard");
Snackbar.Add("Failed to load leaderboard", Severity.Error);
}
finally
{
_isLoadingLeaderboard = false;
StateHasChanged();
}
}
private async Task OnLeaderboardMetricChanged(LeaderboardMetric metric)
{
await LoadLeaderboardAsync(metric);
}
// Helper classes for deserializing API responses
private class GitHubAuthResponse
{
public string? AuthorizationUrl { get; set; }
}
private class GitHubStatusResponse
{
public bool Connected { get; set; }
public string? Username { get; set; }
public DateTime? ConnectedAt { get; set; }
}
private class RecentCommitsResponse
{
public bool Success { get; set; }
public int TotalCommits { get; set; }
[System.Text.Json.Serialization.JsonPropertyName("recentCommits")]
public List<RecentCommitDto>? Commits { get; set; }
}
private class RecentCommitDto
{
public string Sha { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public string AuthorName { get; set; } = string.Empty;
public DateTime CommittedAt { get; set; }
public string RepositoryName { get; set; } = string.Empty;
public int LinesAdded { get; set; }
public int LinesRemoved { get; set; }
}
public void Dispose()
{
// Unsubscribe from dashboard state changes - Phase 3.9
DashboardState.OnStateChanged -= HandleTimeRangeChanged;
}
public async ValueTask DisposeAsync()
{
// Unregister event handlers
SignalR.OnSyncStarted -= HandleSyncStarted;
SignalR.OnSyncCompleted -= HandleSyncCompleted;
SignalR.OnMetricsUpdated -= HandleMetricsUpdated;
SignalR.OnConnectionStateChanged -= HandleConnectionStateChanged;
// Unsubscribe from dashboard state - Phase 3.9
DashboardState.OnStateChanged -= HandleTimeRangeChanged;
// Note: Don't dispose SignalR service here as it's managed by DI
// Just leave the dashboard group
if (!string.IsNullOrEmpty(_currentUserId))
{
try
{
await SignalR.LeaveDashboardAsync();
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Error leaving dashboard group during dispose");
}
}