barker/barker/barker/routers/reports/product_sale_report.py

84 lines
2.6 KiB
Python
Raw Normal View History

2020-06-17 04:27:41 +00:00
from datetime import datetime, timedelta, date
from fastapi import APIRouter, Depends, Security
from sqlalchemy import func
2020-06-17 04:27:41 +00:00
from sqlalchemy.orm import Session
from barker.core.config import settings
from ...models import Voucher, VoucherType, Product, Inventory, Kot, SaleCategory, \
MenuCategory
from ...schemas import to_camel
from ...schemas.auth import UserToken
from ...core.security import get_current_active_user as get_user
from ...db.session import SessionLocal
2020-06-17 04:27:41 +00:00
router = APIRouter()
2020-06-17 04:27:41 +00:00
# Dependency
def get_db() -> Session:
try:
db = SessionLocal()
yield db
finally:
db.close()
2020-06-17 04:27:41 +00:00
@router.get("")
def product_sale_report_view(
s: str = None,
f: str = None,
db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["product-sale-report"]),
):
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
raise ValueError("Accounts Audit")
return {
2020-06-17 04:27:41 +00:00
"startDate": start_date.strftime("%d-%b-%Y"),
"finishDate": finish_date.strftime("%d-%b-%Y"),
"amounts": product_sale_report(start_date, finish_date, db),
}
2020-06-17 04:27:41 +00:00
def product_sale_report(s: date, f: date, db: Session):
start_date = s + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)
finish_date = f + timedelta(days=1, minutes=settings.NEW_DAY_OFFSET_MINUTES)
list_ = (
2020-06-17 04:27:41 +00:00
db.query(
Product.id, Product.full_name, Voucher.voucher_type, Inventory.is_happy_hour, func.sum(Inventory.quantity),
)
.join(Inventory.kot)
.join(Kot.voucher)
.join(Inventory.product)
.join(Product.sale_category)
.join(Product.menu_category)
.filter(Voucher.date >= start_date, Voucher.date <= finish_date)
.group_by(
SaleCategory.name,
MenuCategory.name,
Product.id,
Product.full_name,
Voucher.voucher_type,
Inventory.is_happy_hour,
)
.order_by(SaleCategory.name, MenuCategory.name)
.all()
)
info = []
for id_, name, type_, hh, quantity in list_:
2020-06-17 04:27:41 +00:00
type_ = to_camel(VoucherType(type_).name)
old = [i for i in info if i["id"] == id_ and i["isHappyHour"] == hh]
if len(old):
old[0][type_] = quantity
else:
info.append(
{"id": id_, "name": "H H " + name if hh else name, "isHappyHour": hh, type_: quantity,}
)
return info