From c7f59723c8484079de346098dbf242f3511602a1 Mon Sep 17 00:00:00 2001 From: Winston Hsiao Date: Mon, 18 Nov 2024 11:49:30 -0800 Subject: [PATCH] Remove unused order CRUD functions and rearrange router order to fix endpoint 404 --- store/app/crud/orders.py | 23 +++-------- store/app/routers/orders.py | 82 ++++++++++++++++++------------------- 2 files changed, 45 insertions(+), 60 deletions(-) diff --git a/store/app/crud/orders.py b/store/app/crud/orders.py index 416b9eeb..d5226e0d 100644 --- a/store/app/crud/orders.py +++ b/store/app/crud/orders.py @@ -1,5 +1,6 @@ """This module provides CRUD operations for orders.""" +import logging from typing import NotRequired, TypedDict from pydantic import ValidationError @@ -7,6 +8,8 @@ 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 @@ -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: diff --git a/store/app/routers/orders.py b/store/app/routers/orders.py index 09949c19..c5860173 100644 --- a/store/app/routers/orders.py +++ b/store/app/routers/orders.py @@ -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 @@ -17,7 +17,7 @@ router = APIRouter() -logger = getLogger(__name__) +logger = logging.getLogger(__name__) class ProductInfo(BaseModel): @@ -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), @@ -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