aboutsummaryrefslogtreecommitdiff
path: root/order-service/app/api/v1/endpoints/orders.py
blob: beff480e825d74ed55b91de29600da1a20386579 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from decimal import Decimal
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.api import deps
from app.models.order import Order, OrderItem
from app.schemas.order import OrderCreate, OrderOut
from app.kafka_producer import send_order_created_event


router = APIRouter()


@router.post("/", response_model=OrderOut, status_code=status.HTTP_202_ACCEPTED)
def create_order(order_in: OrderCreate, db: Session = Depends(deps.get_db)):
    """
    Submit a new customer order.
    Returns status code 202 (Accepted) as the order is pending verification.
    """
    try:
        total = Decimal("0.00")
        for item in order_in.items:
            total += item.price * item.quantity

        db_order = Order(
            customer_id=order_in.customer_id, status="PENDING", total_price=total
        )
        db.add(db_order)
        db.flush()

        for item in order_in.items:
            db_item = OrderItem(
                order_id=db_order.id,
                product_id=item.product_id,
                quantity=item.quantity,
                price=item.price,
            )
            db.add(db_item)

        db.commit()
        db.refresh(db_order)

        event_payload = {"order_id": db_order.id, "customer_id": order_in.customer_id}
        send_order_created_event(event_payload)

        return db_order

    except Exception as e:
        db.rollback()
        print(e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Could not initialize checkout process.",
        )


@router.get("/{order_id}", response_model=OrderOut)
def read_order(order_id: int, db: Session = Depends(deps.get_db)):
    """
    Submit a new customer order.
    Returns status code 202 (Accepted) as the order is pending verification.
    """
    try:
        order = db.query(Order).filter(Order.id == order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Order not found")
        return order

    except Exception as e:
        db.rollback()
        print(e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Could not read the order.",
        )