-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderProcessingFunction.cs
More file actions
305 lines (266 loc) · 10.7 KB
/
OrderProcessingFunction.cs
File metadata and controls
305 lines (266 loc) · 10.7 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
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using Jbh.SampleOrderingApi.Models;
using Jbh.SampleOrderingApi.Services;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace Jbh.SampleOrderingApi;
public class OrderProcessingFunction
{
private readonly ILogger<OrderProcessingFunction> _logger;
private readonly HttpClient _httpClient;
private readonly Dictionary<string, DateTime> _orderCache;
private readonly object _cacheLock = new object();
private readonly MockExternalServices _mockServices;
public OrderProcessingFunction(
ILogger<OrderProcessingFunction> logger,
HttpClient httpClient,
MockExternalServices mockServices)
{
_logger = logger;
_httpClient = httpClient;
_httpClient.Timeout = TimeSpan.FromSeconds(30);
_orderCache = new Dictionary<string, DateTime>();
_mockServices = mockServices;
}
[Function("ProcessOrder")]
public async Task<HttpResponseData> RunAsync(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
{
try
{
_logger.LogInformation("Processing order request started");
// Read request body
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var orderRequest = JsonSerializer.Deserialize<OrderRequest>(requestBody);
if (orderRequest == null || string.IsNullOrEmpty(orderRequest.OrderId))
{
return await CreateErrorResponse(req, "Invalid request format", HttpStatusCode.BadRequest);
}
// Check for duplicate orders
bool isDuplicate = false;
lock (_cacheLock)
{
if (_orderCache.ContainsKey(orderRequest.OrderId))
{
var lastProcessed = _orderCache[orderRequest.OrderId];
if (DateTime.UtcNow - lastProcessed < TimeSpan.FromMinutes(5))
{
isDuplicate = true;
}
}
}
if (isDuplicate)
{
_logger.LogWarning($"Duplicate order detected: {orderRequest.OrderId}");
return await CreateErrorResponse(req, "Duplicate order", HttpStatusCode.Conflict);
}
// Validate inventory
var inventoryValid = await ValidateInventory(orderRequest.Items);
if (!inventoryValid)
{
return await CreateErrorResponse(req, "Insufficient inventory", HttpStatusCode.BadRequest);
}
// Process payment
var paymentResult = await ProcessPayment(orderRequest.PaymentInfo);
if (!paymentResult.Success)
{
return await CreateErrorResponse(req, paymentResult.ErrorMessage, HttpStatusCode.PaymentRequired);
}
// Update inventory
await UpdateInventory(orderRequest.Items);
// Send confirmation email
var emailSent = await SendConfirmationEmail(orderRequest.CustomerEmail, orderRequest.OrderId);
// Cache the order
lock (_cacheLock)
{
_orderCache[orderRequest.OrderId] = DateTime.UtcNow;
}
// Create success response
var response = req.CreateResponse(HttpStatusCode.OK);
var successResult = new OrderResult
{
OrderId = orderRequest.OrderId,
Status = "Processed",
ProcessedAt = DateTime.UtcNow,
PaymentId = paymentResult.PaymentId,
EmailSent = emailSent
};
await response.WriteStringAsync(JsonSerializer.Serialize(successResult));
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing order");
return await CreateErrorResponse(req, "Internal server error", HttpStatusCode.InternalServerError);
}
}
private async Task<bool> ValidateInventory(List<OrderItem> items)
{
var tasks = items.Select(async item =>
{
try
{
// Use mock service for local testing
if (_mockServices.IsLocalTesting())
{
return await _mockServices.CheckInventory(item.ProductId, item.Quantity);
}
var response = await _httpClient.GetAsync($"https://inventory-service.com/api/check/{item.ProductId}");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var inventoryData = JsonSerializer.Deserialize<InventoryResponse>(content);
return inventoryData?.Available >= item.Quantity;
}
return false;
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, $"Failed to validate inventory for product {item.ProductId}");
return false;
}
catch (TaskCanceledException ex)
{
_logger.LogError(ex, $"Timeout validating inventory for product {item.ProductId}");
return false;
}
});
var results = await Task.WhenAll(tasks);
return results.All(r => r);
}
private async Task<PaymentResult> ProcessPayment(PaymentInfo paymentInfo)
{
try
{
// Use mock service for local testing
if (_mockServices.IsLocalTesting())
{
return await _mockServices.ProcessPayment(paymentInfo);
}
var paymentData = new
{
Amount = paymentInfo.Amount,
Currency = paymentInfo.Currency,
CardNumber = paymentInfo.CardNumber,
ExpiryDate = paymentInfo.ExpiryDate,
CVV = paymentInfo.CVV
};
var json = JsonSerializer.Serialize(paymentData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("https://payment-gateway.com/api/process", content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<PaymentApiResponse>(responseContent);
return new PaymentResult
{
Success = result.Status == "approved",
PaymentId = result.TransactionId,
ErrorMessage = result.Status != "approved" ? result.Message : null
};
}
return new PaymentResult
{
Success = false,
ErrorMessage = $"Payment service returned {response.StatusCode}"
};
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Payment processing failed");
return new PaymentResult
{
Success = false,
ErrorMessage = "Payment service unavailable"
};
}
catch (JsonException ex)
{
_logger.LogError(ex, "Failed to parse payment response");
return new PaymentResult
{
Success = false,
ErrorMessage = "Invalid payment response"
};
}
}
private async Task UpdateInventory(List<OrderItem> items)
{
var tasks = items.Select(async item =>
{
try
{
// Use mock service for local testing
if (_mockServices.IsLocalTesting())
{
return await _mockServices.UpdateInventory(item.ProductId, item.Quantity);
}
var updateData = new { ProductId = item.ProductId, Quantity = -item.Quantity };
var json = JsonSerializer.Serialize(updateData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("https://inventory-service.com/api/update", content);
if (!response.IsSuccessStatusCode)
{
_logger.LogError($"Failed to update inventory for product {item.ProductId}. Status: {response.StatusCode}");
}
return response.IsSuccessStatusCode;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error updating inventory for product {item.ProductId}");
return false;
}
});
var results = await Task.WhenAll(tasks);
if (results.Any(r => !r))
{
_logger.LogWarning("Some inventory updates failed");
}
}
private async Task<bool> SendConfirmationEmail(string customerEmail, string orderId)
{
try
{
// Use mock service for local testing
if (_mockServices.IsLocalTesting())
{
return await _mockServices.SendEmail(customerEmail, orderId);
}
if (string.IsNullOrEmpty(customerEmail))
{
_logger.LogWarning($"No email provided for order {orderId}");
return false;
}
var emailData = new
{
To = customerEmail,
Subject = $"Order Confirmation - {orderId}",
Body = $"Your order {orderId} has been processed successfully."
};
var json = JsonSerializer.Serialize(emailData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("https://email-service.com/api/send", content);
if (!response.IsSuccessStatusCode)
{
_logger.LogError($"Failed to send confirmation email for order {orderId}. Status: {response.StatusCode}");
}
return response.IsSuccessStatusCode;
}
catch (Exception ex)
{
_logger.LogError(ex, $"Exception sending confirmation email for order {orderId}");
return false;
}
}
private async Task<HttpResponseData> CreateErrorResponse(HttpRequestData req, string message, HttpStatusCode statusCode)
{
var response = req.CreateResponse(statusCode);
var errorResult = new { Error = message, Timestamp = DateTime.UtcNow };
await response.WriteStringAsync(JsonSerializer.Serialize(errorResult));
return response;
}
}