1+ from decimal import Decimal
2+ from ..core .exceptions import CheckoutValidationError , CheckoutPermissionError
3+ from ..repositories .cart_repository import CartRepository
4+ from ..repositories .order_repository import OrderRepository
5+ from ..services .restaurant_service import RestaurantService
6+ from ..services .cart_service import round_money
7+ from ..schemas .cart import MAX_QUANTITY
8+ from ..schemas .customer import Customer
9+ from ..schemas .item_availability import ItemAvailability
10+ from ..schemas .order import Order , OrderItem
11+
12+ class CheckoutService :
13+ def __init__ (
14+ self ,
15+ cart_repository : CartRepository ,
16+ order_repository : OrderRepository ,
17+ restaurant_service : RestaurantService ,
18+ ) -> None :
19+ self .cart_repository = cart_repository
20+ self .order_repository = order_repository
21+ self .restaurant_service = restaurant_service
22+
23+ def checkout (self , customer : Customer ) -> Order :
24+
25+ # validate the customer
26+ if not customer .isActive :
27+ raise CheckoutPermissionError ("Deactivated customers cannot check out" )
28+
29+ if customer .role != "customer" :
30+ raise CheckoutPermissionError ("Only customer accounts can check out" )
31+
32+ if not customer .address or not customer .address .strip ():
33+ raise CheckoutValidationError ("A delivery address is required for checkout" )
34+
35+ with self .cart_repository .lock (): # lock the cart during the checkout operation.
36+ carts = self .cart_repository .get_all_carts ()
37+ cart = next ((c for c in carts if c .customerId == customer .id and c .status == "active" ), None )
38+
39+ if cart is None :
40+ raise CheckoutValidationError ("No active cart found" )
41+
42+ # lock orders while checking and saving
43+ with self .order_repository .lock ():
44+ # Recovery if an earlier attempt saved the order but failed to close the cart
45+ existing_order = (self .order_repository .get_order_by_cart_id (cart .id ))
46+
47+ if existing_order is not None :
48+ cart .status = "checkedOut"
49+ self .cart_repository .save_carts (carts )
50+ return existing_order
51+
52+ # validate the cart
53+ if not cart .items :
54+ raise CheckoutValidationError ("Cannot check out an empty cart" )
55+
56+ if not cart .restaurantId :
57+ raise CheckoutValidationError ("Cart has no restaurant" )
58+
59+ restaurant = (self .restaurant_service .get_restaurant_by_id (cart .restaurantId ))
60+
61+ if restaurant is None :
62+ raise CheckoutValidationError ("Restaurant no longer exists" )
63+
64+ menu_items = (self .restaurant_service .menu_items_by_id ())
65+
66+ order_items = []
67+ subtotal = Decimal ("0.00" )
68+ currency = None
69+
70+ # validate and reprice every item
71+ for cart_item in cart .items :
72+
73+ if not 1 <= cart_item .quantity <= MAX_QUANTITY :
74+ raise CheckoutValidationError ("Invalid item quantity" )
75+
76+ result = menu_items .get (cart_item .menuItemId )
77+
78+ if result is None :
79+ raise CheckoutValidationError (f"Menu item '{ cart_item .menuItemId } ' no longer exists" )
80+
81+ restaurant_id , menu_item = result
82+
83+ if restaurant_id != cart .restaurantId :
84+ raise CheckoutValidationError ("Cart contains an item from another restaurant" )
85+
86+ offers = (menu_item .offers if isinstance (menu_item .offers , list )else [menu_item .offers ])
87+
88+ offer = next ((o for o in offers if o .availability == ItemAvailability .IN_STOCK ), None )
89+
90+ if offer is None :
91+ raise CheckoutValidationError (f"'{ menu_item .name } ' is unavailable" )
92+
93+ # one currency per order
94+ if currency is None :
95+ currency = offer .priceCurrency
96+ elif currency != offer .priceCurrency :
97+ raise CheckoutValidationError ("Items have different currencies" )
98+
99+ unit_price = offer .price
100+ line_total = round_money (unit_price * cart_item .quantity )
101+
102+ subtotal += line_total
103+
104+ order_items .append (
105+ OrderItem (
106+ menuItemId = menu_item .id ,
107+ name = menu_item .name ,
108+ quantity = cart_item .quantity ,
109+ unitPrice = unit_price ,
110+ lineTotal = line_total ,
111+ )
112+ )
113+
114+ subtotal = round_money (subtotal )
115+ total = subtotal
116+
117+ new_order = Order (
118+ customerId = customer .id ,
119+ restaurantId = cart .restaurantId ,
120+ cartId = cart .id ,
121+ items = order_items ,
122+ currency = currency ,
123+ subtotal = subtotal ,
124+ total = total ,
125+ deliveryAddress = customer .address ,
126+ )
127+
128+ # persist the order first
129+ orders = self .order_repository .get_all_orders ()
130+ orders .append (new_order )
131+
132+ self .order_repository .save_orders (orders )
133+
134+ # only lose the cart only after successful
135+ cart .status = "checkedOut"
136+ self .cart_repository .save_carts (carts )
137+ return new_order
138+
0 commit comments