84 lines
2.6 KiB
Python
84 lines
2.6 KiB
Python
from datetime import datetime, timedelta, date
|
|
|
|
from fastapi import APIRouter, Depends, Security
|
|
from sqlalchemy import func
|
|
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
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
# Dependency
|
|
def get_db() -> Session:
|
|
try:
|
|
db = SessionLocal()
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@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 {
|
|
"startDate": start_date.strftime("%d-%b-%Y"),
|
|
"finishDate": finish_date.strftime("%d-%b-%Y"),
|
|
"amounts": product_sale_report(start_date, finish_date, db),
|
|
}
|
|
|
|
|
|
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_ = (
|
|
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_:
|
|
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
|
|
|
|
|