55from sqlalchemy .ext .asyncio import AsyncSession
66
77from app .core .exceptions import ConflictError , NotFoundError
8+ from app .services .inventory .internal import (
9+ cancel_reservation_by_order_and_return_stock ,
10+ mark_reservation_by_order_as_completed ,
11+ )
812from app .services .inventory .models import Product , Reservation
913from app .services .orders .models import Order , OrderItem , OrderStatus
1014from app .services .orders .schemas import OrderCreate
@@ -89,11 +93,22 @@ async def confirm_order_payment(
8993 order_id : UUID ,
9094 user_id : UUID ,
9195) -> Order :
92- order , reservation = await _get_locked_order_and_reservation (
93- session , order_id , user_id
96+ order_result = await session .execute (
97+ select (Order )
98+ .with_for_update ()
99+ .where (
100+ Order .id == order_id ,
101+ Order .user_id == user_id ,
102+ )
94103 )
104+ order = order_result .scalar_one_or_none ()
105+ if not order :
106+ raise NotFoundError
107+ if order .status != OrderStatus .PENDING :
108+ raise ConflictError
109+
95110 order .status = OrderStatus .PAID
96- reservation . status = OrderStatus . COMPLETED
111+ await mark_reservation_by_order_as_completed ( session , order_id )
97112 await session .commit ()
98113 return order
99114
@@ -103,16 +118,21 @@ async def cancel_order(
103118 order_id : UUID ,
104119 user_id : UUID ,
105120) -> Order :
106- order , reservation = await _get_locked_order_and_reservation (
107- session , order_id , user_id
108- )
109- product_rollback = await session .execute (
110- select (Product ).with_for_update ().where (Product .id == reservation .product_id )
121+ order_result = await session .execute (
122+ select (Order )
123+ .with_for_update ()
124+ .where (
125+ Order .id == order_id ,
126+ Order .user_id == user_id ,
127+ )
111128 )
112- product = product_rollback .scalar_one_or_none ()
113- if product :
114- product .qty_available += reservation .qty_reserved
129+ order = order_result .scalar_one_or_none ()
130+ if not order :
131+ raise NotFoundError
132+ if order .status != OrderStatus .PENDING :
133+ raise ConflictError
134+
115135 order .status = OrderStatus .CANCELLED
116- reservation . status = OrderStatus . CANCELLED
136+ await cancel_reservation_by_order_and_return_stock ( session , order_id )
117137 await session .commit ()
118138 return order
0 commit comments