brewman/brewman/brewman/routers/batch.py

57 lines
1.5 KiB
Python

import datetime
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..core.security import get_current_active_user as get_user
from ..db.session import SessionLocal
from ..models.voucher import Batch
from ..schemas.auth import UserToken
router = APIRouter()
# Dependency
def get_db() -> Session:
try:
db = SessionLocal()
yield db
finally:
db.close()
@router.get("")
def batch_term(
q: str,
c: int = None,
d: str = None,
db: Session = Depends(get_db),
current_user: UserToken = Depends(get_user),
):
date = None if not d else datetime.datetime.strptime(d, "%d-%b-%Y")
list_ = []
for index, item in enumerate(Batch.list(q, include_nil=False, date=date, db=db)):
text = (
f"{item.product.name} ({item.product.units}) {item.quantity_remaining:.2f}@"
f"{item.rate:.2f} from {item.name.strftime('%d-%b-%Y')}"
)
list_.append(
{
"id": item.id,
"name": text,
"quantityRemaining": round(item.quantity_remaining, 2),
"rate": round(item.rate, 2),
"tax": round(item.tax, 5),
"discount": round(item.discount, 5),
"product": {
"id": item.product.id,
"name": item.product.name,
"units": item.product.units,
},
}
)
if c is not None and index == c - 1:
break
return list_