|
from fastapi import APIRouter, status, HTTPException |
|
from models.query import Query |
|
from services.elasticsearch import add_to_cart, view_cart, remove_from_cart, checkout |
|
|
|
router = APIRouter() |
|
|
|
|
|
@router.post("/add-to-cart") |
|
def handle_add_to_cart(query: Query): |
|
customer_id = next( |
|
(entity['value'] for entity in query.entities if entity['entity'] == 'customer_id'), None) |
|
product_id = next( |
|
(entity['value'] for entity in query.entities if entity['entity'] == 'product_id'), None) |
|
quantity = next( |
|
(entity['value'] for entity in query.entities if entity['entity'] == 'quantity'), 1) |
|
if customer_id and product_id: |
|
cart = add_to_cart(customer_id, product_id, int(quantity)) |
|
return cart |
|
else: |
|
raise HTTPException( |
|
status_code=status.HTTP_404_NOT_FOUND, detail="Customer ID or Product ID not provided.") |
|
|
|
|
|
@router.get("/view-cart/{customer_id}") |
|
def handle_view_cart(customer_id: str): |
|
cart = view_cart(customer_id) |
|
if not cart: |
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Cart not found") |
|
return cart |
|
|
|
|
|
@router.post("/remove-from-cart") |
|
def handle_remove_from_cart(query: Query): |
|
customer_id = next( |
|
(entity['value'] for entity in query.entities if entity['entity'] == 'customer_id'), None) |
|
product_id = next( |
|
(entity['value'] for entity in query.entities if entity['entity'] == 'product_id'), None) |
|
if customer_id and product_id: |
|
cart = remove_from_cart(customer_id, product_id) |
|
return cart |
|
else: |
|
raise HTTPException( |
|
status_code=status.HTTP_404_NOT_FOUND, detail="Customer ID or Product ID not provided.") |
|
|
|
|
|
@router.post("/checkout") |
|
def handle_checkout(query: Query): |
|
customer_id = next( |
|
(entity['value'] for entity in query.entities if entity['entity'] == 'customer_id'), None) |
|
if customer_id: |
|
order = checkout(customer_id) |
|
return order |
|
else: |
|
raise HTTPException( |
|
status_code=status.HTTP_404_NOT_FOUND, detail="Customer ID not provided.") |
|
|