-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnalyticsController.cs
More file actions
231 lines (195 loc) · 7.64 KB
/
Copy pathAnalyticsController.cs
File metadata and controls
231 lines (195 loc) · 7.64 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
// Service Interface
public interface IAnalyticsService
{
Task<List<UserAnalytics>> GetUserAnalyticsAsync(string userId);
Task<List<OrderSummary>> GetOrderSummaryAsync(DateTime startDate, DateTime endDate);
}
// Scoped Service Implementation
public class AnalyticsService : IAnalyticsService
{
private readonly IMongoCollection<User> _users;
private readonly IMongoCollection<Order> _orders;
private readonly IMongoCollection<Product> _products;
private readonly ILogger<AnalyticsService> _logger;
// Cache aggregation results within the scope
private Dictionary<string, object> _aggregationCache = new();
public AnalyticsService(
IMongoDatabase database,
ILogger<AnalyticsService> logger)
{
_users = database.GetCollection<User>("users");
_orders = database.GetCollection<Order>("orders");
_products = database.GetCollection<Product>("products");
_logger = logger;
}
public async Task<List<UserAnalytics>> GetUserAnalyticsAsync(string userId)
{
var cacheKey = $"user_analytics_{userId}";
if (_aggregationCache.ContainsKey(cacheKey))
{
return (List<UserAnalytics>)_aggregationCache[cacheKey];
}
var pipeline = new[]
{
// Match specific user
new BsonDocument("$match", new BsonDocument("_id", ObjectId.Parse(userId))),
// Lookup orders
new BsonDocument("$lookup", new BsonDocument
{
{"from", "orders"},
{"localField", "_id"},
{"foreignField", "userId"},
{"as", "orders"}
}),
// Lookup products for each order
new BsonDocument("$unwind", new BsonDocument
{
{"path", "$orders"},
{"preserveNullAndEmptyArrays", true}
}),
new BsonDocument("$lookup", new BsonDocument
{
{"from", "products"},
{"localField", "orders.productId"},
{"foreignField", "_id"},
{"as", "orderProducts"}
}),
// Group and calculate analytics
new BsonDocument("$group", new BsonDocument
{
{"_id", "$_id"},
{"userName", new BsonDocument("$first", "$name")},
{"totalOrders", new BsonDocument("$sum", 1)},
{"totalSpent", new BsonDocument("$sum", "$orders.totalAmount")},
{"avgOrderValue", new BsonDocument("$avg", "$orders.totalAmount")},
{"favoriteCategories", new BsonDocument("$push", "$orderProducts.category")},
{"lastOrderDate", new BsonDocument("$max", "$orders.orderDate")}
}),
// Project final structure
new BsonDocument("$project", new BsonDocument
{
{"userId", "$_id"},
{"userName", 1},
{"totalOrders", 1},
{"totalSpent", 1},
{"avgOrderValue", 1},
{"lastOrderDate", 1},
{"favoriteCategories", new BsonDocument("$setUnion", "$favoriteCategories")}
})
};
var result = await _users.Aggregate<UserAnalytics>(pipeline).ToListAsync();
// Cache within scope
_aggregationCache[cacheKey] = result;
_logger.LogInformation($"User analytics calculated for user {userId}");
return result;
}
public async Task<List<OrderSummary>> GetOrderSummaryAsync(DateTime startDate, DateTime endDate)
{
var cacheKey = $"order_summary_{startDate:yyyyMMdd}_{endDate:yyyyMMdd}";
if (_aggregationCache.ContainsKey(cacheKey))
{
return (List<OrderSummary>)_aggregationCache[cacheKey];
}
var pipeline = new[]
{
// Match date range
new BsonDocument("$match", new BsonDocument
{
{"orderDate", new BsonDocument
{
{"$gte", startDate},
{"$lte", endDate}
}}
}),
// Lookup user info
new BsonDocument("$lookup", new BsonDocument
{
{"from", "users"},
{"localField", "userId"},
{"foreignField", "_id"},
{"as", "user"}
}),
// Unwind user array
new BsonDocument("$unwind", "$user"),
// Group by date and calculate metrics
new BsonDocument("$group", new BsonDocument
{
{"_id", new BsonDocument("$dateToString", new BsonDocument
{
{"format", "%Y-%m-%d"},
{"date", "$orderDate"}
})},
{"totalOrders", new BsonDocument("$sum", 1)},
{"totalRevenue", new BsonDocument("$sum", "$totalAmount")},
{"uniqueCustomers", new BsonDocument("$addToSet", "$userId")},
{"avgOrderValue", new BsonDocument("$avg", "$totalAmount")}
}),
// Add calculated fields
new BsonDocument("$addFields", new BsonDocument
{
{"uniqueCustomerCount", new BsonDocument("$size", "$uniqueCustomers")}
}),
// Sort by date
new BsonDocument("$sort", new BsonDocument("_id", 1))
};
var result = await _orders.Aggregate<OrderSummary>(pipeline).ToListAsync();
// Cache within scope
_aggregationCache[cacheKey] = result;
_logger.LogInformation($"Order summary calculated for {startDate:yyyy-MM-dd} to {endDate:yyyy-MM-dd}");
return result;
}
}
// Data Models
public class UserAnalytics
{
public string UserId { get; set; }
public string UserName { get; set; }
public int TotalOrders { get; set; }
public decimal TotalSpent { get; set; }
public decimal AvgOrderValue { get; set; }
public DateTime LastOrderDate { get; set; }
public List<string> FavoriteCategories { get; set; }
}
public class OrderSummary
{
public string Date { get; set; }
public int TotalOrders { get; set; }
public decimal TotalRevenue { get; set; }
public int UniqueCustomerCount { get; set; }
public decimal AvgOrderValue { get; set; }
}
// Startup Registration
public void ConfigureServices(IServiceCollection services)
{
// Register MongoDB
services.AddSingleton<IMongoClient>(sp =>
new MongoClient("mongodb://localhost:27017"));
services.AddScoped<IMongoDatabase>(sp =>
sp.GetService<IMongoClient>().GetDatabase("ecommerce"));
// Register scoped service
services.AddScoped<IAnalyticsService, AnalyticsService>();
}
// Controller Usage
[ApiController]
[Route("api/[controller]")]
public class AnalyticsController : ControllerBase
{
private readonly IAnalyticsService _analyticsService;
public AnalyticsController(IAnalyticsService analyticsService)
{
_analyticsService = analyticsService;
}
[HttpGet("user/{userId}")]
public async Task<ActionResult<List<UserAnalytics>>> GetUserAnalytics(string userId)
{
var analytics = await _analyticsService.GetUserAnalyticsAsync(userId);
return Ok(analytics);
}
[HttpGet("orders")]
public async Task<ActionResult<List<OrderSummary>>> GetOrderSummary(
DateTime startDate, DateTime endDate)
{
var summary = await _analyticsService.GetOrderSummaryAsync(startDate, endDate);
return Ok(summary);
}
}