Skip to content

Commit 5e4ec5f

Browse files
authored
Merge pull request #86 from OpenDash-Team/feature/checkout-followups
Checkout follow-ups and customer-to-order workflow test
2 parents 37833f3 + 903c636 commit 5e4ec5f

8 files changed

Lines changed: 109 additions & 9 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ Customer login returns a bearer token. Include it in the `Authorization` header
216216
| PATCH | `/api/v1/cart/items/{menu_item_id}` | `Sets an item's quantity (1-99). Returns 200, 401, 404 if the item isn't in the cart or was removed from the menu, 409 if raising the quantity of an out of stock item, 422 for an invalid quantity.` |
217217
| DELETE | `/api/v1/cart/items/{menu_item_id}` | `Removes an item from the cart. Returns 200 with the updated cart, 401, 404 if the item isn't in the cart.` |
218218
| DELETE | `/api/v1/cart` | `Clears the cart. Returns 200 with the empty cart, 401 if not signed in.` |
219+
| POST | `/api/v1/checkout` | `Checks out the signed-in customer's cart: checks availability and prices again, saves the order, then closes the cart. Returns 201 with the order, 401, 403 for owner or deactivated accounts, 409 if the cart is empty, has an unavailable item or there's no delivery address.` |
219220

220221

221222
## API Documentation

‎backend/app/api/routes.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -425,9 +425,6 @@ def checkout(
425425
persists an order, and then closes the cart.
426426
"""
427427

428-
if current_customer is None:
429-
raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"},)
430-
431428
try:
432429
return checkout_service.checkout(current_customer)
433430

‎backend/sample-data/orders.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[]

‎backend/tests/conftest.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434

3535
@pytest.fixture(autouse=True)
3636
def isolated_data():
37-
files_to_track = ["restaurants.json", "customers.json", "carts.json"]
37+
files_to_track = ["restaurants.json", "customers.json", "carts.json", "orders.json"]
3838

3939
for name in files_to_track:
4040
test_file = TEST_DATA / name
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[]

‎backend/tests/test_checkout_routes.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,10 @@ def checkout(self, current_customer):
6666

6767

6868
def test_checkout_requires_authentication(test_app):
69-
test_app.dependency_overrides[get_current_customer] = (lambda: None)
70-
client = TestClient(test_app)
71-
response = client.post("/api/v1/checkout")
69+
# no token is sent, so the real get_current_customer rejects it
70+
response = TestClient(test_app).post("/api/v1/checkout")
71+
7272
assert response.status_code == 401
73-
assert response.json()["detail"] == "Not authenticated"
7473

7574

7675
def test_checkout_invalid_cart(test_app, customer):

‎backend/tests/test_checkout_service.py‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,41 @@ def test_checkout_rejects_deactivated_customer(checkout_setup):
102102
customer.isActive = False
103103
with pytest.raises(CheckoutPermissionError):
104104
service.checkout(customer)
105-
assert order_repo.get_all_orders() == []
105+
assert order_repo.get_all_orders() == []
106+
107+
108+
def test_checking_out_twice_only_creates_one_order(checkout_setup):
109+
(service, customer, _, order_repo, _, _) = checkout_setup
110+
service.checkout(customer)
111+
112+
with pytest.raises(CheckoutValidationError, match="No active cart"):
113+
service.checkout(customer)
114+
115+
assert len(order_repo.get_all_orders()) == 1
116+
117+
118+
def test_retry_after_cart_failed_to_close_returns_the_same_order(checkout_setup):
119+
(service, customer, cart_repo, order_repo, _, _) = checkout_setup
120+
order = service.checkout(customer)
121+
122+
# pretend closing the cart failed last time: the order is saved but the cart is still active
123+
carts = cart_repo.get_all_carts()
124+
carts[0].status = "active"
125+
cart_repo.save_carts(carts)
126+
127+
assert service.checkout(customer).id == order.id
128+
assert len(order_repo.get_all_orders()) == 1
129+
assert cart_repo.get_all_carts()[0].status == "checkedOut"
130+
131+
132+
def test_item_removed_from_menu_blocks_checkout(checkout_setup):
133+
(service, customer, cart_repo, order_repo, restaurant_repo, _) = checkout_setup
134+
restaurants = restaurant_repo.get_all_restaurants()
135+
restaurants[0].hasMenu.hasMenuSection[0].hasMenuItem = []
136+
restaurant_repo.save_restaurants(restaurants)
137+
138+
with pytest.raises(CheckoutValidationError, match="no longer exists"):
139+
service.checkout(customer)
140+
141+
assert order_repo.get_all_orders() == []
142+
assert cart_repo.get_all_carts()[0].status == "active"
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from decimal import Decimal
2+
3+
from fastapi.testclient import TestClient
4+
5+
from backend.app.main import main
6+
from backend.app.repositories.order_repository import OrderRepository
7+
from backend.tests.conftest import REAL_DATA
8+
9+
FRAPPUCCINO = "F5hn9s3VD9qzKsLV4z8CW" # Starbucks item in test-data/restaurants.json, 5.95
10+
11+
12+
def login(client, email):
13+
token = client.post("/api/v1/login", json={"email": email, "password": "password123"}).json()["access_token"]
14+
return {"Authorization": f"Bearer {token}"}
15+
16+
17+
def set_frappuccino_price(client, owner, restaurant_id, price):
18+
offers = {"price": price, "priceCurrency": "USD", "availability": "https://schema.org/InStock"}
19+
response = client.patch(f"/api/v1/restaurants/{restaurant_id}/menu-items/{FRAPPUCCINO}", json={"offers": offers}, headers=owner)
20+
assert response.status_code == 200
21+
22+
23+
def test_customer_to_order_workflow(client):
24+
# Customer: register and sign in
25+
registered = client.post("/api/v1/customers", json={
26+
"name": "Jordan Smith", "email": "jordan@example.com", "password": "password123", "address": "1 Main St, Kelowna",
27+
})
28+
assert registered.status_code == 201
29+
customer = login(client, "jordan@example.com")
30+
31+
# Restaurant and menu: find the restaurant that sells the item
32+
restaurants = client.get("/api/v1/restaurants?name=Starbucks").json()
33+
restaurant_id = restaurants[0]["id"]
34+
assert client.get(f"/api/v1/restaurants/{restaurant_id}").status_code == 200
35+
36+
# Cart: add the item, backend works out the total
37+
cart = client.post("/api/v1/cart/items", json={"menuItemId": FRAPPUCCINO, "quantity": 2}, headers=customer).json()
38+
assert cart["total"] == "11.90"
39+
40+
# The owner changes the price before checkout, checkout has to use the new one
41+
owner = login(client, "owner@example.com")
42+
set_frappuccino_price(client, owner, restaurant_id, 6.50)
43+
44+
# Checkout: creates the order and closes the cart
45+
response = client.post("/api/v1/checkout", headers=customer)
46+
assert response.status_code == 201
47+
order = response.json()
48+
assert order["customerId"] == registered.json()["id"]
49+
assert order["restaurantId"] == restaurant_id
50+
assert order["deliveryAddress"] == "1 Main St, Kelowna"
51+
assert order["items"][0]["unitPrice"] == "6.5"
52+
assert order["total"] == "13.00"
53+
assert client.get("/api/v1/cart", headers=customer).json()["items"] == []
54+
55+
# Order: still there after a restart, and a later price change doesn't touch it
56+
set_frappuccino_price(client, owner, restaurant_id, 9.99)
57+
restarted = TestClient(main())
58+
login(restarted, "jordan@example.com")
59+
60+
saved = OrderRepository(REAL_DATA / "orders.json").get_all_orders()
61+
assert [o.id for o in saved] == [order["id"]]
62+
assert saved[0].items[0].name.startswith("Caramel Ribbon Crunch")
63+
assert saved[0].items[0].unitPrice == Decimal("6.5")
64+
assert saved[0].total == Decimal("13.00")

0 commit comments

Comments
 (0)