Skip to content

Commit 8409179

Browse files
authored
Merge pull request #76 from OpenDash-Team/feature/56-shopping-cart
Shopping cart (#55)
2 parents fcf2d22 + 8e7cdf7 commit 8409179

19 files changed

Lines changed: 1090 additions & 40 deletions

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,11 @@ The API provides the following endpoints:
189189
| GET | `/api/v1/customers/me` | `Returns the signed-in customer's info. Returns 401 if not signed in.` |
190190
| PATCH | `/api/v1/customers/me` | `Updates the signed-in customer's name, email, telephone or delivery address. Returns 200, 401, 409 if the email is taken, 422 for invalid input.` |
191191
| DELETE | `/api/v1/customers/me` | `Deactivates the signed-in customer's account (kept but marked inactive). Returns 204, 401 if not signed in.` |
192+
| GET | `/api/v1/cart` | `Returns the signed-in customer's active cart (creates an empty one the first time) with current prices, subtotal and total. Returns 200, 401 if not signed in.` |
193+
| POST | `/api/v1/cart/items` | `Adds a menu item (or increases its quantity). Returns 200, 401, 404 for an unknown item, 409 if it's out of stock, from another restaurant or would go over 99, 422 for an invalid quantity.` |
194+
| 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.` |
195+
| 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.` |
196+
| DELETE | `/api/v1/cart` | `Clears the cart. Returns 200 with the empty cart, 401 if not signed in.` |
192197

193198

194199
## API Documentation

‎backend/app/api/routes.py‎

Lines changed: 131 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
1-
from fastapi import FastAPI, HTTPException, Depends, APIRouter
1+
from fastapi import FastAPI, HTTPException, Depends, APIRouter, Path
22
from json import JSONDecodeError
33

4-
from ..core.dependencies import get_restaurant_service, get_customer_service, get_current_customer
4+
from ..core.dependencies import get_restaurant_service, get_customer_service, get_current_customer, get_cart_service
55
from ..schemas.restaurant import Restaurant
66
from ..schemas.restaurant_query import RestaurantQuery
77
from ..services.restaurant_service import RestaurantService
88
from ..schemas.menu_item import MenuItem
99
from ..schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
1010
from ..schemas.restaurant_request import RestaurantCreate, RestaurantUpdate
11-
from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError, DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError
11+
from ..core.exceptions import (
12+
DuplicateRestaurantError, RestaurantNotFoundError,
13+
DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError,
14+
MenuItemNotFoundError, MenuItemUnavailableError, DifferentRestaurantError, CartItemNotFoundError, CartQuantityError,
15+
)
1216
from ..schemas.customer import Customer, CustomerResponse
1317
from ..schemas.error import ErrorResponse
1418
from ..schemas.customer_request import CustomerCreate, CustomerUpdate
1519
from ..services.customer_service import CustomerService
20+
from ..schemas.cart import CartResponse
21+
from ..schemas.cart_request import CartItemAdd, CartItemUpdate
22+
from ..services.cart_service import CartService
1623

1724
def create_routes(api: FastAPI | APIRouter):
1825
@api.get("/health")
@@ -195,6 +202,127 @@ def deactivate_my_account(
195202
raise HTTPException(status_code=401, detail=str(e))
196203

197204

205+
@api.get(
206+
"/cart",
207+
response_model=CartResponse,
208+
summary="Get my cart",
209+
responses={401: {"model": ErrorResponse, "description": "Not signed in"}},
210+
)
211+
def get_cart(
212+
current_customer: Customer = Depends(get_current_customer),
213+
cart_service: CartService = Depends(get_cart_service),
214+
):
215+
"""Returns the signed-in customer's active cart (an empty one is created the first time),
216+
with current prices and the subtotal and total calculated by the backend."""
217+
try:
218+
return cart_service.get_cart(current_customer)
219+
220+
except CustomerDeactivatedError as e:
221+
raise HTTPException(status_code=401, detail=str(e))
222+
223+
224+
@api.post(
225+
"/cart/items",
226+
response_model=CartResponse,
227+
summary="Add a menu item to my cart",
228+
responses={
229+
401: {"model": ErrorResponse, "description": "Not signed in"},
230+
404: {"model": ErrorResponse, "description": "No menu item has this id"},
231+
409: {"model": ErrorResponse, "description": "The item is out of stock, the cart has items from another restaurant, or it would go over 99"},
232+
},
233+
)
234+
def add_cart_item(
235+
request: CartItemAdd,
236+
current_customer: Customer = Depends(get_current_customer),
237+
cart_service: CartService = Depends(get_cart_service),
238+
):
239+
"""Adds the item to the cart. If it's already there, its quantity goes up instead."""
240+
try:
241+
return cart_service.add_item(current_customer, request)
242+
243+
except CustomerDeactivatedError as e:
244+
raise HTTPException(status_code=401, detail=str(e))
245+
246+
except MenuItemNotFoundError as e:
247+
raise HTTPException(status_code=404, detail=str(e))
248+
249+
except (MenuItemUnavailableError, DifferentRestaurantError, CartQuantityError) as e:
250+
raise HTTPException(status_code=409, detail=str(e))
251+
252+
253+
@api.patch(
254+
"/cart/items/{menu_item_id}",
255+
response_model=CartResponse,
256+
summary="Change the quantity of an item in my cart",
257+
responses={
258+
401: {"model": ErrorResponse, "description": "Not signed in"},
259+
404: {"model": ErrorResponse, "description": "The item is not in the cart, or is no longer on the menu"},
260+
409: {"model": ErrorResponse, "description": "The item is out of stock, so its quantity can only go down"},
261+
},
262+
)
263+
def update_cart_item(
264+
request: CartItemUpdate,
265+
menu_item_id: str = Path(description="Id of the menu item in the cart"),
266+
current_customer: Customer = Depends(get_current_customer),
267+
cart_service: CartService = Depends(get_cart_service),
268+
):
269+
"""Sets the item's quantity (1-99). To take it out of the cart, use DELETE instead."""
270+
try:
271+
return cart_service.update_item_quantity(current_customer, menu_item_id, request)
272+
273+
except CustomerDeactivatedError as e:
274+
raise HTTPException(status_code=401, detail=str(e))
275+
276+
except (CartItemNotFoundError, MenuItemNotFoundError) as e:
277+
raise HTTPException(status_code=404, detail=str(e))
278+
279+
except MenuItemUnavailableError as e:
280+
raise HTTPException(status_code=409, detail=str(e))
281+
282+
283+
@api.delete(
284+
"/cart/items/{menu_item_id}",
285+
response_model=CartResponse,
286+
summary="Remove an item from my cart",
287+
responses={
288+
401: {"model": ErrorResponse, "description": "Not signed in"},
289+
404: {"model": ErrorResponse, "description": "The item is not in the cart"},
290+
},
291+
)
292+
def remove_cart_item(
293+
menu_item_id: str = Path(description="Id of the menu item in the cart"),
294+
current_customer: Customer = Depends(get_current_customer),
295+
cart_service: CartService = Depends(get_cart_service),
296+
):
297+
"""Removes the item and returns the updated cart. Works for items that are out of stock or no longer on the menu."""
298+
try:
299+
return cart_service.remove_item(current_customer, menu_item_id)
300+
301+
except CustomerDeactivatedError as e:
302+
raise HTTPException(status_code=401, detail=str(e))
303+
304+
except CartItemNotFoundError as e:
305+
raise HTTPException(status_code=404, detail=str(e))
306+
307+
308+
@api.delete(
309+
"/cart",
310+
response_model=CartResponse,
311+
summary="Clear my cart",
312+
responses={401: {"model": ErrorResponse, "description": "Not signed in"}},
313+
)
314+
def clear_cart(
315+
current_customer: Customer = Depends(get_current_customer),
316+
cart_service: CartService = Depends(get_cart_service),
317+
):
318+
"""Removes every item. The cart stays, empty, and can be used for any restaurant again."""
319+
try:
320+
return cart_service.clear_cart(current_customer)
321+
322+
except CustomerDeactivatedError as e:
323+
raise HTTPException(status_code=401, detail=str(e))
324+
325+
198326
@api.get("/", include_in_schema=False)
199327
@api.get("/{path:path}", include_in_schema=False)
200328
def api_not_found(path: str):

‎backend/app/core/dependencies.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44

55
from ..services.restaurant_service import RestaurantService
66
from ..services.customer_service import CustomerService
7+
from ..services.cart_service import CartService
78
from ..repositories.restaurant_repository import RestaurantRepository
89
from ..repositories.customer_repository import CustomerRepository
10+
from ..repositories.cart_repository import CartRepository
911
from ..schemas.customer import Customer
1012

1113

@@ -25,6 +27,10 @@ def get_customer_service() -> CustomerService:
2527
customer_repository = CustomerRepository(get_data_dir() / "customers.json")
2628
return CustomerService(customer_repository)
2729

30+
def get_cart_service() -> CartService:
31+
cart_repository = CartRepository(get_data_dir() / "carts.json")
32+
return CartService(cart_repository, get_restaurant_service())
33+
2834
def get_current_customer() -> Customer:
2935
"""Placeholder until login (#52) is merged: rejects every request."""
3036
raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"})

‎backend/app/core/exceptions.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,18 @@ class DuplicateEmailError(Exception):
1212

1313
class CustomerDeactivatedError(Exception):
1414
"""The customer's account has been deactivated."""
15+
16+
class MenuItemNotFoundError(Exception):
17+
"""No restaurant has a menu item with the given ID."""
18+
19+
class MenuItemUnavailableError(Exception):
20+
"""The menu item exists but can't be ordered right now (out of stock)."""
21+
22+
class DifferentRestaurantError(Exception):
23+
"""The cart already has items from another restaurant."""
24+
25+
class CartItemNotFoundError(Exception):
26+
"""The menu item is not in the customer's cart."""
27+
28+
class CartQuantityError(Exception):
29+
"""The change would put a cart item's quantity outside the allowed range."""
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from pathlib import Path
2+
3+
from .json_repository import JsonRepository
4+
from ..schemas.cart import Cart
5+
6+
7+
class CartRepository(JsonRepository[Cart]):
8+
def __init__(self, carts_file_path: Path) -> None:
9+
super().__init__(carts_file_path, Cart)
10+
11+
def get_all_carts(self) -> list[Cart]:
12+
return self._load_all()
13+
14+
def save_carts(self, carts: list[Cart]) -> None:
15+
self._save_all(carts)
16+
17+
def get_active_cart(self, customer_id: str) -> Cart | None:
18+
for cart in self.get_all_carts():
19+
if cart.customerId == customer_id and cart.status == "active":
20+
return cart
21+
return None

‎backend/app/schemas/cart.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from decimal import Decimal
2+
from typing import Annotated, Literal
3+
4+
from pydantic import BaseModel, Field
5+
6+
from ..core.identifiers import generate_id
7+
8+
MAX_QUANTITY = 99
9+
10+
CartStatus = Literal["active", "checkedOut"]
11+
Quantity = Annotated[int, Field(strict=True, ge=1, le=MAX_QUANTITY)] # strict: "2" or true are rejected
12+
13+
14+
class CartItem(BaseModel):
15+
"""Only the item id is stored, so prices always come from the current menu."""
16+
17+
menuItemId: str
18+
quantity: Quantity
19+
20+
21+
class Cart(BaseModel):
22+
"""A cart as it is stored in carts.json."""
23+
24+
id: str = Field(default_factory=generate_id, frozen=True)
25+
customerId: str
26+
restaurantId: str | None = None # a cart only holds items from one restaurant
27+
items: list[CartItem] = []
28+
status: CartStatus = "active"
29+
30+
31+
class CartItemResponse(BaseModel):
32+
menuItemId: str
33+
name: str | None = Field(description="None if the item is no longer on the menu")
34+
quantity: int
35+
unitPrice: Decimal | None = Field(description="Current price, None if the item can't be ordered right now")
36+
lineTotal: Decimal
37+
available: bool = Field(description="False if the item is out of stock or no longer on the menu. It is left out of the totals")
38+
39+
40+
class CartResponse(BaseModel):
41+
id: str
42+
customerId: str
43+
restaurantId: str | None
44+
items: list[CartItemResponse]
45+
currency: str | None
46+
subtotal: Decimal
47+
total: Decimal
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from pydantic import BaseModel, ConfigDict, Field
2+
3+
from .cart import Quantity
4+
5+
6+
class CartItemAdd(BaseModel):
7+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
8+
9+
menuItemId: str = Field(min_length=1, description="Id of the menu item to add")
10+
quantity: Quantity = Field(1, description="How many to add, 1-99. Adding an item already in the cart increases its quantity")
11+
12+
13+
class CartItemUpdate(BaseModel):
14+
model_config = ConfigDict(extra="forbid")
15+
16+
quantity: Quantity = Field(description="New quantity, 1-99. To remove an item use DELETE instead")

0 commit comments

Comments
 (0)