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

60 lines
1.7 KiB
Python

import uuid
from fastapi import APIRouter, HTTPException, status, Depends, Security
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from . import do_update_settlements
from ...schemas.auth import UserToken
import barker.schemas.receive_payment as schemas
from ...core.security import get_current_active_user as get_user
from ...db.session import SessionLocal
from ...models import Voucher, VoucherType, SettleOption, Settlement, Overview
router = APIRouter()
# Dependency
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
@router.post("/receive-payment/{id_}")
def update(
id_: uuid.UUID,
data: schemas.ReceivePayment,
u: bool, # Update table?
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["settle-bill"]),
):
try:
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.query(Voucher).filter(Voucher.id == id_).first()
if item.voucher_type in [VoucherType.NO_CHARGE, VoucherType.STAFF]:
item.reason = data.name.title()
do_update_settlements(item, amounts, db)
if update_table:
db.query(Overview).filter(Overview.voucher_id == item.id).delete()
db.commit()
return True
except SQLAlchemyError as e:
db.rollback()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
)
except Exception:
db.rollback()
raise