From 8b08623c1c601f57598ed912184d7ef14ca04de9 Mon Sep 17 00:00:00 2001 From: Jonatas Oliveira Date: Wed, 16 Oct 2024 15:05:33 +0200 Subject: [PATCH] feat: add cancel order endpoint --- app/entities/order.py | 4 ++++ app/infra/endpoints/order.py | 12 ++++++++++++ app/order/services.py | 24 ++++++++++++++++++++++-- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/app/entities/order.py b/app/entities/order.py index 301a242c..f90c35a1 100644 --- a/app/entities/order.py +++ b/app/entities/order.py @@ -49,6 +49,10 @@ class OrderInDB(BaseModel): model_config = ConfigDict(from_attributes=True) +class CancelOrder(BaseModel): + cancel_reason: str + + class OrderItemResponse(BaseModel): order_items: list[OrderItemInDB] page: int diff --git a/app/infra/endpoints/order.py b/app/infra/endpoints/order.py index 7193116e..05f83f46 100644 --- a/app/infra/endpoints/order.py +++ b/app/infra/endpoints/order.py @@ -14,6 +14,7 @@ from app.infra.deps import get_db from app.infra.models import PaymentDB, OrderDB from app.entities.order import ( + CancelOrder, OrderSchema, TrackingFullResponse, OrderUserListResponse, @@ -115,6 +116,17 @@ async def complete_order( raise +@order.delete('/{order_id}', status_code=status.HTTP_204_NO_CONTENT) +async def delete_order( + *, + db: Session = Depends(get_db), + cancel_reason: CancelOrder, + order_id: int, +) -> None: + """Delete order.""" + services.delete_order(order_id, cancel=cancel_reason, db=db) + + @order.patch( '/{order_id}/tracking_number', status_code=status.HTTP_204_NO_CONTENT, diff --git a/app/order/services.py b/app/order/services.py index af0ea91f..dd56b6ed 100644 --- a/app/order/services.py +++ b/app/order/services.py @@ -1,8 +1,9 @@ +from datetime import UTC, datetime import json import math from typing import Any -from app.infra.constants import OrderStatus +from app.infra.constants import OrderStatus, PaymentStatus from fastapi import HTTPException, status from loguru import logger from pydantic import TypeAdapter @@ -11,7 +12,7 @@ from app.product import repository from faststream.rabbit import RabbitQueue -from app.entities.order import OrderInDB, OrderResponse +from app.entities.order import CancelOrder, OrderInDB, OrderNotFoundError, OrderResponse from app.entities.product import ( ProductCategoryInDB, ProductCreate, @@ -318,6 +319,25 @@ def get_order(db: Session, order_id: int) -> OrderInDB: return OrderInDB.model_validate(order) +def delete_order(order_id: int, *, cancel: CancelOrder, db) -> None: + """Soft delete order.""" + with db: + order_query = ( + select(OrderDB) + .options(selectinload(OrderDB.items)) + .where(OrderDB.order_id == order_id) + ) + order = db.scalar(order_query) + if not order: + raise OrderNotFoundError + order.order_status = PaymentStatus.CANCELLED + order.checked = False + order.cancelled_at = datetime.now(tz=UTC) + order.cancelled_reason=cancel.cancel_reason + db.add(order) + db.commit() + + def get_order_users(db: Session, id): ...