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

68 lines
1.9 KiB
Python

import uuid
import barker.schemas.receive_payment as schemas
from fastapi import APIRouter, Depends, HTTPException, Security, status
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from ...core.security import get_current_active_user as get_user
from ...db.session import SessionLocal
from ...models.master import SettleOption, VoucherType
from ...models.voucher import Overview, Voucher
from ...schemas.auth import UserToken
from . import do_update_settlements
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.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.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