barker/barker/barker/routers/voucher/receive_payment.py

59 lines
1.9 KiB
Python

import uuid
import barker.schemas.receive_payment as schemas
from fastapi import APIRouter, HTTPException, Security, status
from sqlalchemy import delete, select
from sqlalchemy.exc import SQLAlchemyError
from ...core.security import get_current_active_user as get_user
from ...db.session import SessionFuture
from ...models.overview import Overview
from ...models.settle_option import SettleOption
from ...models.voucher import Voucher
from ...models.voucher_type import VoucherType
from ...schemas.user_token import UserToken
from . import do_update_settlements
router = APIRouter()
@router.post("/receive-payment/{id_}")
def update_route(
id_: uuid.UUID,
data: schemas.ReceivePayment,
u: bool, # Update table?
user: UserToken = Security(get_user, scopes=["settle-bill"]),
):
try:
with SessionFuture() as db:
update_table = u
amounts = [
j
for j in data.amounts
if j.amount != 0 and j.id_ not in [SettleOption.AMOUNT(), SettleOption.ROUND_OFF()]
]
for i in amounts:
i.amount = round(i.amount, 0)
item: Voucher = db.execute(select(Voucher).where(Voucher.id == id_)).scalar_one()
if item.voucher_type in [VoucherType.NO_CHARGE, VoucherType.STAFF]:
item.reason = data.reason.title()
if not do_update_settlements(item, amounts, db):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Bill amount not fully settled",
)
if update_table:
db.execute(delete(Overview).where(Overview.voucher_id == item.id))
db.commit()
return True
except SQLAlchemyError as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str(e),
)