11using System . Net . Http . Json ;
2+ using System . Text . Json ;
23
34namespace ECommerce . AdminUI . Services ;
45
5- public class DashboardService
6+ public class DashboardService (
7+ IHttpClientFactory httpClientFactory ,
8+ ILogger < DashboardService > logger ,
9+ IHttpContextAccessor httpContextAccessor ,
10+ OrderService orderService )
611{
7- private readonly HttpClient _httpClient ;
8- private readonly ILogger < DashboardService > _logger ;
9- private readonly IHttpContextAccessor _httpContextAccessor ;
10- private readonly OrderService _orderService ;
11-
12- public DashboardService (
13- IHttpClientFactory httpClientFactory ,
14- ILogger < DashboardService > logger ,
15- IHttpContextAccessor httpContextAccessor ,
16- OrderService orderService )
17- {
18- _httpClient = httpClientFactory . CreateClient ( "ModularMonolith" ) ;
19- _logger = logger ;
20- _httpContextAccessor = httpContextAccessor ;
21- _orderService = orderService ;
22- }
12+ private readonly HttpClient _httpClient = httpClientFactory . CreateClient ( "ModularMonolith" ) ;
2313
2414 private void AddAuthorizationHeader ( )
2515 {
26- var token = _httpContextAccessor . HttpContext ? . Session . GetString ( "AuthToken" ) ;
16+ var token = httpContextAccessor . HttpContext ? . Session . GetString ( "AuthToken" ) ;
2717 if ( ! string . IsNullOrEmpty ( token ) )
2818 {
2919 _httpClient . DefaultRequestHeaders . Remove ( "Authorization" ) ;
@@ -56,10 +46,20 @@ public async Task<DashboardStats> GetDashboardStatsAsync()
5646 }
5747
5848 // Get orders
59- var orders = await _orderService . GetAllOrdersAsync ( ) ;
49+ var orders = await orderService . GetAllOrdersAsync ( ) ;
6050 stats . OrderCount = orders . Count ;
6151 stats . TotalSales = orders . Sum ( o => o . TotalPrice ) ;
6252
53+ logger . LogInformation ( "Retrieved {OrderCount} orders with total sales: ${TotalSales}" ,
54+ orders . Count , stats . TotalSales ) ;
55+
56+ // Log order dates to diagnose the issue
57+ foreach ( var order in orders )
58+ {
59+ logger . LogInformation ( "Order ID: {OrderId}, CreatedAt: {CreatedAt}, Price: ${Price}" ,
60+ order . Id , order . CreatedAt , order . TotalPrice ) ;
61+ }
62+
6363 // Get business events
6464 var eventsResponse = await _httpClient . GetAsync ( "events" ) ;
6565 if ( eventsResponse . IsSuccessStatusCode )
@@ -70,10 +70,22 @@ public async Task<DashboardStats> GetDashboardStatsAsync()
7070
7171 // Generate order statistics for chart
7272 stats . OrderStatistics = GenerateOrderStatistics ( orders ) ;
73+
74+ // Log the generated statistics
75+ logger . LogInformation ( "Generated {StatCount} order statistics entries:" , stats . OrderStatistics . Count ) ;
76+ foreach ( var stat in stats . OrderStatistics )
77+ {
78+ logger . LogInformation ( "Date: {Date}, OrderCount: {Count}, TotalSales: ${Sales}" ,
79+ stat . Date . ToString ( "yyyy-MM-dd" ) , stat . OrderCount , stat . TotalSales ) ;
80+ }
81+
82+ // Log the JSON that will be sent to the chart
83+ logger . LogInformation ( "Order statistics JSON: {OrderStatsJson}" ,
84+ JsonSerializer . Serialize ( stats . OrderStatistics ) ) ;
7385 }
7486 catch ( Exception ex )
7587 {
76- _logger . LogError ( ex , "Error retrieving dashboard statistics" ) ;
88+ logger . LogError ( ex , "Error retrieving dashboard statistics" ) ;
7789 }
7890
7991 return stats ;
@@ -84,34 +96,50 @@ private List<OrderStatistic> GenerateOrderStatistics(List<OrderDto> orders)
8496 // For demo/initial implementation purpose, if no orders exist, create some sample data
8597 if ( orders == null || ! orders . Any ( ) )
8698 {
99+ logger . LogInformation ( "No orders found, generating sample statistics" ) ;
87100 return GenerateSampleOrderStatistics ( ) ;
88101 }
89102
90- // Group orders by day for the last 7 days (week) instead of 30 days
91- var startDate = DateTime . UtcNow . AddDays ( - 7 ) ;
103+ // Calculate a date range for the past 7 days
104+ var endDate = DateTime . UtcNow . Date ;
105+ var startDate = endDate . AddDays ( - 6 ) ; // This gives us 7 days total (today + 6 previous days)
106+
107+ logger . LogInformation ( "Generating statistics from {StartDate} to {EndDate}" ,
108+ startDate . ToString ( "yyyy-MM-dd" ) , endDate . ToString ( "yyyy-MM-dd" ) ) ;
109+
110+ // Log the orders being considered for the chart
111+ logger . LogInformation ( "Orders in date range: {Count}" ,
112+ orders . Count ( o => o . CreatedAt . Date >= startDate && o . CreatedAt . Date <= endDate ) ) ;
113+
114+ // Group orders by day for the last 7 days
92115 var ordersByDay = orders
93- . Where ( o => o . CreatedAt >= startDate )
116+ . Where ( o => o . CreatedAt . Date >= startDate && o . CreatedAt . Date <= endDate )
94117 . GroupBy ( o => o . CreatedAt . Date )
95118 . Select ( g => new OrderStatistic
96119 {
97120 Date = g . Key ,
98121 OrderCount = g . Count ( ) ,
99122 TotalSales = g . Sum ( o => o . TotalPrice )
100123 } )
101- . OrderBy ( x => x . Date )
102- . ToList ( ) ;
124+ . ToDictionary ( x => x . Date , x => x ) ; // Convert to dictionary for easier lookup
125+
126+ // Log the unique dates found in orders
127+ logger . LogInformation ( "Found orders on these dates: {Dates}" ,
128+ string . Join ( ", " , ordersByDay . Keys . Select ( d => d . ToString ( "yyyy-MM-dd" ) ) ) ) ;
103129
104- // Fill in missing dates
130+ // Fill in missing dates with zero values
105131 var result = new List < OrderStatistic > ( ) ;
106- for ( var day = startDate . Date ; day <= DateTime . UtcNow . Date ; day = day . AddDays ( 1 ) )
132+ for ( var day = startDate ; day <= endDate ; day = day . AddDays ( 1 ) )
107133 {
108- var existingStat = ordersByDay . FirstOrDefault ( s => s . Date == day ) ;
109- if ( existingStat != null )
134+ if ( ordersByDay . TryGetValue ( day , out var existingStat ) )
110135 {
136+ logger . LogInformation ( "Adding existing stat for {Date}: {Count} orders, ${Sales}" ,
137+ day . ToString ( "yyyy-MM-dd" ) , existingStat . OrderCount , existingStat . TotalSales ) ;
111138 result . Add ( existingStat ) ;
112139 }
113140 else
114141 {
142+ logger . LogInformation ( "Adding zero stat for {Date} (no orders)" , day . ToString ( "yyyy-MM-dd" ) ) ;
115143 result . Add ( new OrderStatistic { Date = day , OrderCount = 0 , TotalSales = 0 } ) ;
116144 }
117145 }
0 commit comments