Skip to content

Commit 8df6360

Browse files
authored
Merge pull request #85 from OpenDash-Team/feature/Checkout-and-Initial-Order-Creation
Feature/checkout and initial order creation
2 parents f922bed + 1e6ee9c commit 8df6360

11 files changed

Lines changed: 636 additions & 1 deletion

File tree

‎backend/app/api/routes.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
from ..schemas.login_request import LoginRequest
1919
from ..schemas.token import Token
2020
from ..core import security
21+
from ..core.dependencies import get_checkout_service
22+
from ..services.checkout_service import CheckoutService
23+
from ..schemas.order import Order
24+
from ..core.exceptions import CheckoutValidationError, CheckoutPermissionError
2125

2226
def create_routes(api: FastAPI | APIRouter):
2327
@api.get("/health")
@@ -401,6 +405,38 @@ def clear_cart(
401405
except CustomerDeactivatedError as e:
402406
raise HTTPException(status_code=401, detail=str(e))
403407

408+
@api.post(
409+
"/checkout",
410+
response_model=Order,
411+
status_code=201,
412+
summary="Checkout the current customer's active cart",
413+
responses={
414+
401: { "model": ErrorResponse, "description": "Not authenticated",},
415+
403: {"model": ErrorResponse, "description": "Customer cannot check out",},
416+
409: {"model": ErrorResponse, "description": "Cart or menu validation failed",},
417+
},
418+
)
419+
def checkout(
420+
current_customer: Customer = Depends(get_current_customer),
421+
checkout_service: CheckoutService = Depends(get_checkout_service),
422+
):
423+
"""
424+
Validates the current cart, recalculates prices,
425+
persists an order, and then closes the cart.
426+
"""
427+
428+
if current_customer is None:
429+
raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"},)
430+
431+
try:
432+
return checkout_service.checkout(current_customer)
433+
434+
except CheckoutPermissionError as e:
435+
raise HTTPException(status_code=403, detail=str(e),) from e
436+
437+
except CheckoutValidationError as e:
438+
raise HTTPException(status_code=409, detail=str(e),) from e
439+
404440

405441
@api.get("/", include_in_schema=False)
406442
@api.get("/{path:path}", include_in_schema=False)

‎backend/app/core/dependencies.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from ..repositories.customer_repository import CustomerRepository
1111
from ..repositories.restaurant_repository import RestaurantRepository
1212
from ..schemas.customer import Customer
13+
from ..services.checkout_service import CheckoutService
14+
from ..repositories.order_repository import OrderRepository
1315
from ..services.customer_service import CustomerService
1416
from ..services.restaurant_service import RestaurantService
1517

@@ -40,7 +42,6 @@ def get_cart_service() -> CartService:
4042
cart_repository = CartRepository(get_data_dir() / "carts.json")
4143
return CartService(cart_repository, get_restaurant_service())
4244

43-
4445
def get_current_customer(
4546
token: str = Depends(oauth2_scheme),
4647
customer_service: CustomerService = Depends(get_customer_service),
@@ -70,3 +71,8 @@ def require_owner(
7071

7172
return current_customer
7273

74+
def get_checkout_service() -> CheckoutService:
75+
cart_repository = CartRepository(get_data_dir() / "carts.json")
76+
order_repository = OrderRepository(get_data_dir() / "orders.json")
77+
restaurant_service = get_restaurant_service()
78+
return CheckoutService(cart_repository=cart_repository, order_repository=order_repository,restaurant_service=restaurant_service,)

‎backend/app/core/exceptions.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,12 @@ class CartItemNotFoundError(Exception):
3030

3131
class CartQuantityError(Exception):
3232
"""The change would put a cart item's quantity outside the allowed range."""
33+
34+
class CheckoutError(Exception):
35+
"""Base exception for expected checkout failures."""
36+
37+
class CheckoutValidationError(CheckoutError):
38+
"""The cart or customer does not satisfy checkout requirements."""
39+
40+
class CheckoutPermissionError(CheckoutError):
41+
"""The authenticated account is not allowed to check out."""
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from pathlib import Path
2+
from .json_repository import JsonRepository
3+
from ..schemas.order import Order
4+
5+
6+
class OrderRepository(JsonRepository[Order]):
7+
8+
def __init__(self, orders_file_path: Path) -> None:
9+
super().__init__(orders_file_path, Order)
10+
11+
def get_all_orders(self) -> list[Order]:
12+
return self._load_all()
13+
14+
def save_orders(self, orders: list[Order]) -> None:
15+
self._save_all(orders)
16+
17+
def get_order_by_id(self, order_id: str) -> Order | None:
18+
orders = self.get_all_orders()
19+
20+
for order in orders:
21+
if order.id == order_id:
22+
return order
23+
return None
24+
25+
def get_orders_by_customer(self, customer_id: str) -> list[Order]:
26+
orders = self.get_all_orders()
27+
return [order for order in orders if order.customerId == customer_id]
28+
29+
def get_order_by_cart_id(self, cart_id: str) -> Order | None:
30+
orders = self.get_all_orders()
31+
for order in orders:
32+
if order.cartId == cart_id:
33+
return order
34+
return None

‎backend/app/schemas/order.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from datetime import datetime, timezone
2+
from decimal import Decimal
3+
from typing import Literal
4+
from pydantic import BaseModel, Field
5+
from ..core.identifiers import generate_id
6+
7+
8+
class OrderItem(BaseModel):
9+
menuItemId: str
10+
name: str = Field(min_length=1)
11+
quantity: int = Field(strict=True, ge=1, le=99)
12+
unitPrice: Decimal = Field(ge=0) # to calculate money value precisely
13+
lineTotal: Decimal = Field(ge=0)
14+
15+
16+
class Order(BaseModel):
17+
id: str = Field(default_factory=generate_id, frozen=True)
18+
customerId: str
19+
restaurantId: str
20+
cartId: str
21+
items: list[OrderItem] = Field(min_length=1)
22+
currency: str = Field(min_length=3, max_length=3)
23+
subtotal: Decimal = Field(ge=0)
24+
total: Decimal = Field(ge=0)
25+
deliveryAddress: str = Field(min_length=1)
26+
createdAt: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
27+
status: Literal["created"] = "created"
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
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+

‎backend/tests/conftest.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,22 @@
99
from backend.app.core.dependencies import get_current_customer, get_customer_service
1010
from backend.app.core.exceptions import CustomerDeactivatedError, CustomerNotFoundError
1111

12+
from decimal import Decimal
13+
from backend.app.repositories.cart_repository import CartRepository
14+
from backend.app.repositories.order_repository import OrderRepository
15+
from backend.app.repositories.restaurant_repository import RestaurantRepository
16+
from backend.app.services.checkout_service import CheckoutService
17+
from backend.app.services.restaurant_service import RestaurantService
18+
from backend.app.schemas.customer import Customer
19+
from backend.app.schemas.cart import Cart, CartItem
20+
from backend.app.schemas.restaurant import Restaurant
21+
from backend.app.schemas.menu import Menu
22+
from backend.app.schemas.menu_section import MenuSection
23+
from backend.app.schemas.menu_item import MenuItem
24+
from backend.app.schemas.offer import Offer
25+
from backend.app.schemas.item_availability import ItemAvailability
26+
from backend.app.schemas.restricted_diet import RestrictedDiet
27+
1228
CURRENT_DIR = Path(__file__).resolve().parent
1329
REAL_DATA = CURRENT_DIR.parent / "data"
1430
TEST_DATA = CURRENT_DIR.parent / "tests/test-data"
@@ -76,3 +92,68 @@ def fake_current_customer():
7692
@pytest.fixture
7793
def owner_client(sign_in_as):
7894
return sign_in_as(OWNER_ID)
95+
96+
97+
@pytest.fixture
98+
def checkout_setup(tmp_path):
99+
restaurant_repo = RestaurantRepository(tmp_path / "restaurants.json")
100+
cart_repo = CartRepository(tmp_path / "carts.json")
101+
order_repo = OrderRepository(tmp_path / "orders.json")
102+
103+
menu_item = MenuItem(
104+
name="Test Latte",
105+
description="A latte",
106+
suitableForDiet=RestrictedDiet.VEGETARIAN,
107+
offers=Offer(
108+
price=Decimal("5.49"),
109+
priceCurrency="CAD",
110+
availability=ItemAvailability.IN_STOCK,
111+
),
112+
)
113+
114+
restaurant = Restaurant(
115+
name="Test Cafe",
116+
address="123 Test Road",
117+
telephone="1234567890",
118+
openingHours="Mo-Fr 09:00-17:00",
119+
hasMenu=Menu(
120+
hasMenuSection=[
121+
MenuSection(
122+
name="Drinks",
123+
hasMenuItem=[menu_item],
124+
)
125+
]
126+
),
127+
)
128+
129+
restaurant_repo.save_restaurants([restaurant])
130+
131+
customer = Customer(
132+
name="Test Customer",
133+
email="test@example.com",
134+
hashedPassword="test-only-hash",
135+
address="456 Customer Street",
136+
)
137+
138+
cart = Cart(
139+
customerId=customer.id,
140+
restaurantId=restaurant.id,
141+
items=[
142+
CartItem(
143+
menuItemId=menu_item.id,
144+
quantity=2,
145+
)
146+
],
147+
)
148+
149+
cart_repo.save_carts([cart])
150+
151+
service = CheckoutService(
152+
cart_repository=cart_repo,
153+
order_repository=order_repo,
154+
restaurant_service=RestaurantService(
155+
restaurant_repo
156+
),
157+
)
158+
159+
return (service,customer, cart_repo, order_repo, restaurant_repo, menu_item)

0 commit comments

Comments
 (0)