aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--thallium-backend/src/routes/orders.py24
1 files changed, 15 insertions, 9 deletions
diff --git a/thallium-backend/src/routes/orders.py b/thallium-backend/src/routes/orders.py
index 20682c0..af659bd 100644
--- a/thallium-backend/src/routes/orders.py
+++ b/thallium-backend/src/routes/orders.py
@@ -4,7 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy import select
from src.auth import TokenAuth
-from src.dto import Order, OrderCreate, Voucher
+from src.dto import Order, OrderCosts, OrderCreate, Voucher
from src.orm import Voucher as DBVoucher
from src.settings import DBSession, PrintfulClient
@@ -21,19 +21,25 @@ async def create_order(request: Request, db: DBSession, client: PrintfulClient,
If the voucher does not have enough funds, the order is cancelled.
"""
voucher: Voucher = request.state.voucher
-
- resp = await client.post("/orders", json=order.as_printful_payload(voucher), params={"confirm": False})
- resp.raise_for_status()
- submitted_order = Order.model_validate(resp.json()["result"])
-
stmt = select(DBVoucher).where(DBVoucher.id == voucher.id).with_for_update()
db_voucher = await db.scalar(stmt)
- if submitted_order.costs.total > db_voucher.balance:
- await client.delete(f"/orders/{submitted_order.id}")
+
+ resp = await client.post(
+ "/orders/estimate-costs",
+ json=order.as_printful_payload(voucher),
+ params={"confirm": False},
+ )
+ resp.raise_for_status()
+ cost = OrderCosts.model_validate(resp.json()["result"]["costs"])
+ if cost.total > db_voucher.balance:
raise HTTPException(
status_code=400,
- detail=f"Order totals {submitted_order.costs.total}, only {db_voucher.balance} remaining on voucher.",
+ detail=f"Order totals {cost.total}, only {db_voucher.balance} remaining on voucher.",
)
+ resp = await client.post("/orders", json=order.as_printful_payload(voucher), params={"confirm": False})
+ resp.raise_for_status()
+ submitted_order = Order.model_validate(resp.json()["result"])
+
db_voucher.balance = db_voucher.balance - submitted_order.costs.total
return submitted_order