Skip to content

Commit

Permalink
Remove unused order CRUD functions and rearrange router order to fix …
Browse files Browse the repository at this point in the history
…endpoint 404
  • Loading branch information
Winston-Hsiao committed Nov 18, 2024
1 parent a93b46c commit c7f5972
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 60 deletions.
23 changes: 6 additions & 17 deletions store/app/crud/orders.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
"""This module provides CRUD operations for orders."""

import logging
from typing import NotRequired, TypedDict

from pydantic import ValidationError

from store.app.crud.base import BaseCrud, ItemNotFoundError
from store.app.model import InventoryType, Order, OrderStatus

logger = logging.getLogger(__name__)


class OrderDataCreate(TypedDict):
user_id: str
Expand Down Expand Up @@ -66,29 +69,15 @@ async def create_order(self, order_data: OrderDataCreate) -> Order:
await self._add_item(order)
return order

async def get_order(self, order_id: str) -> Order | None:
return await self._get_item(order_id, Order, throw_if_missing=False)

async def get_orders_by_user_id(self, user_id: str) -> list[Order]:
orders = await self._get_items_from_secondary_index("user_id", user_id, Order)
if not orders:
raise OrdersNotFoundError(f"No orders found for user {user_id}")
return orders

async def get_orders_by_stripe_connect_account_id(self, stripe_connect_account_id: str) -> list[Order]:
orders = await self._get_items_from_secondary_index(
"stripe_connect_account_id",
stripe_connect_account_id,
Order,
)
if not orders:
raise ItemNotFoundError("No orders found for this Stripe Connect account")
return orders

async def get_order(self, order_id: str) -> Order | None:
return await self._get_item(order_id, Order, throw_if_missing=False)

async def get_order_by_session_id(self, session_id: str) -> Order | None:
orders = await self._get_items_from_secondary_index("stripe_checkout_session_id", session_id, Order)
return orders[0] if orders else None

async def update_order(self, order_id: str, update_data: OrderDataUpdate) -> Order:
order = await self.get_order(order_id)
if not order:
Expand Down
82 changes: 39 additions & 43 deletions store/app/routers/orders.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Defines the router endpoints for handling Orders."""

import asyncio
from logging import getLogger
import logging

from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
Expand All @@ -17,7 +17,7 @@

router = APIRouter()

logger = getLogger(__name__)
logger = logging.getLogger(__name__)


class ProductInfo(BaseModel):
Expand All @@ -34,33 +34,6 @@ class OrderWithProduct(BaseModel):
product: ProductInfo | None


@router.get("/{order_id}", response_model=OrderWithProduct)
async def get_order(
order_id: str,
user: User = Depends(get_session_user_with_read_permission),
crud: Crud = Depends(),
) -> OrderWithProduct:
async with crud:
order = await crud.get_order(order_id)
if not order or order.user_id != user.id:
raise HTTPException(status_code=404, detail="Order not found")

# Get product info from Stripe
product = await stripe.get_product(order.stripe_product_id, crud)

# Convert ProductResponse to ProductInfo
product_info = ProductInfo(
id=product.id,
name=product.name,
description=product.description,
images=product.images,
metadata=product.metadata,
active=product.active,
)

return OrderWithProduct(order=order, product=product_info)


@router.get("/me", response_model=list[OrderWithProduct])
async def get_user_orders(
user: User = Depends(get_session_user_with_read_permission),
Expand Down Expand Up @@ -89,26 +62,49 @@ async def get_product_info(order: Order) -> OrderWithProduct:
return OrderWithProduct(order=order, product=None)

try:
orders = await crud.get_orders_by_user_id(user.id)
return await asyncio.gather(*[get_product_info(order) for order in orders])
except OrdersNotFoundError:
async with crud:
orders = await crud.get_orders_by_user_id(user.id)
results = await asyncio.gather(*[get_product_info(order) for order in orders])
return results

except OrdersNotFoundError as e:
logger.info(f"No orders found for user: {user.id}")
return []
except asyncio.TimeoutError:
logger.error("Timeout while fetching orders", extra={"user_id": user.id})
raise HTTPException(
status_code=status.HTTP_504_GATEWAY_TIMEOUT, detail="Request timed out while fetching orders"
)
except Exception as e:
logger.error(
"Unexpected error fetching user orders",
extra={"user_id": user.id, "error": str(e), "error_type": type(e).__name__},
)
logger.error(f"Error fetching orders: {str(e)}", exc_info=True)
print(f"Error fetching orders: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="An unexpected error occurred while fetching orders",
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error fetching orders: {str(e)}"
)


@router.get("/{order_id}", response_model=OrderWithProduct)
async def get_order(
order_id: str,
user: User = Depends(get_session_user_with_read_permission),
crud: Crud = Depends(),
) -> OrderWithProduct:
async with crud:
order = await crud.get_order(order_id)
if not order or order.user_id != user.id:
raise HTTPException(status_code=404, detail="Order not found")

# Get product info from Stripe
product = await stripe.get_product(order.stripe_product_id, crud)

# Convert ProductResponse to ProductInfo
product_info = ProductInfo(
id=product.id,
name=product.name,
description=product.description,
images=product.images,
metadata=product.metadata,
active=product.active,
)

return OrderWithProduct(order=order, product=product_info)


class UpdateOrderAddressRequest(BaseModel):
shipping_name: str
shipping_address_line1: str
Expand Down

0 comments on commit c7f5972

Please sign in to comment.