-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathOnlineShoppingService.cs
114 lines (98 loc) · 3.24 KB
/
OnlineShoppingService.cs
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace OnlineShopping
{
public class OnlineShoppingService
{
private static OnlineShoppingService _instance;
private readonly ConcurrentDictionary<string, User> _users;
private readonly ConcurrentDictionary<string, Product> _products;
private readonly ConcurrentDictionary<string, Order> _orders;
private OnlineShoppingService()
{
_users = new ConcurrentDictionary<string, User>();
_products = new ConcurrentDictionary<string, Product>();
_orders = new ConcurrentDictionary<string, Order>();
}
public static OnlineShoppingService GetInstance()
{
if (_instance == null)
{
_instance = new OnlineShoppingService();
}
return _instance;
}
public void RegisterUser(User user)
{
_users[user.Id] = user;
}
public User GetUser(string userId)
{
_users.TryGetValue(userId, out var user);
return user;
}
public void AddProduct(Product product)
{
_products[product.Id] = product;
}
public Product GetProduct(string productId)
{
_products.TryGetValue(productId, out var product);
return product;
}
public List<Product> SearchProducts(string keyword)
{
return _products.Values
.Where(p => p.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase))
.ToList();
}
public Order PlaceOrder(User user, ShoppingCart cart, Payment payment)
{
var orderItems = new List<OrderItem>();
foreach (var item in cart.GetItems())
{
var product = item.Product;
var quantity = item.Quantity;
if (product.IsAvailable(quantity))
{
product.UpdateQuantity(-quantity);
orderItems.Add(item);
}
}
if (!orderItems.Any())
{
throw new InvalidOperationException("No available products in the cart.");
}
var orderId = GenerateOrderId();
var order = new Order(orderId, user, orderItems);
_orders[orderId] = order;
user.AddOrder(order);
cart.Clear();
if (payment.ProcessPayment(order.TotalAmount))
{
order.Status = OrderStatus.Processing;
}
else
{
order.Status = OrderStatus.Cancelled;
// Revert product quantities
foreach (var item in orderItems)
{
item.Product.UpdateQuantity(item.Quantity);
}
}
return order;
}
public Order GetOrder(string orderId)
{
_orders.TryGetValue(orderId, out var order);
return order;
}
private string GenerateOrderId()
{
return $"ORDER{Guid.NewGuid().ToString().Substring(0, 8).ToUpper()}";
}
}
}