barker/barker/barker/routers/customer_discount.py

74 lines
2.3 KiB
Python

import uuid
from decimal import Decimal
import barker.schemas.discount_item as schemas
from fastapi import APIRouter, Security
from sqlalchemy import select
from sqlalchemy.orm import Session
from ..core.security import get_current_active_user as get_user
from ..db.session import SessionFuture
from ..models.customer import Customer
from ..models.db_setting import DbSetting
from ..models.sale_category import SaleCategory
from ..schemas.user_token import UserToken
router = APIRouter()
@router.get("", response_model=list[schemas.DiscountItem])
def show_blank(
user: UserToken = Security(get_user, scopes=["customers"]),
) -> list[schemas.DiscountItem]:
with SessionFuture() as db:
return customer_discounts_blank(db)
@router.get("/{id_}", response_model=list[schemas.DiscountItem])
def show_id(
id_: uuid.UUID,
user: UserToken = Security(get_user, scopes=["customers"]),
) -> list[schemas.DiscountItem]:
with SessionFuture() as db:
item: Customer = db.execute(select(Customer).where(Customer.id == id_)).scalar_one()
return customer_discounts(item, db)
def customer_discounts(item: Customer, db: Session) -> list[schemas.DiscountItem]:
default_discount = (
db.execute(select(DbSetting).where(DbSetting.name == "Prefill Customer Discount")).scalar_one().data["Value"]
)
return [
schemas.DiscountItem(
id=sc.id,
name=sc.name,
discount=Decimal(0)
if not default_discount
else next((d.discount for d in item.discounts if d.sale_category_id == sc.id), Decimal(0)),
limit=sc.discount_limit,
customer=next((d.discount for d in item.discounts if d.sale_category_id == sc.id), Decimal(0)),
)
for sc in db.execute(select(SaleCategory).where(SaleCategory.discount_limit != 0).order_by(SaleCategory.name))
.scalars()
.all()
]
def customer_discounts_blank(db: Session) -> list[schemas.DiscountItem]:
return [
schemas.DiscountItem(
id=sc.id,
name=sc.name,
discount=0,
limit=sc.discount_limit,
customer=0,
)
for sc in db.execute(select(SaleCategory).where(SaleCategory.discount_limit != 0).order_by(SaleCategory.name))
.scalars()
.all()
]