from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from datetime import datetime from app.models.customer import Customer_Customer from app.models.delivery import Delivery from database import get_db from sqlalchemy import func router = APIRouter( prefix="/info", tags=["info"], ) def get_customers_without_delivery_since(db: Session, date_threshold: datetime): """ Queries all customers who haven't received a delivery since the specified date. Args: db: The database session. date_threshold: The date threshold. Customers whose last delivery is before this date (or have no deliveries) will be returned. Returns: A tuple containing the count and a list of Customer_Customer objects. """ # Subquery to find the last delivery date for each customer last_delivery_subquery = ( db.query( Delivery.customer_id, func.max(Delivery.when_delivered).label("last_delivery_date") ) .group_by(Delivery.customer_id) .subquery() ) # Main query to join customers with their last delivery date # and filter based on the date threshold customers = ( db.query(Customer_Customer) .outerjoin( last_delivery_subquery, Customer_Customer.id == last_delivery_subquery.c.customer_id ) .filter( (last_delivery_subquery.c.last_delivery_date < date_threshold) | (last_delivery_subquery.c.last_delivery_date == None) ) .all() ) return len(customers), customers @router.get("/customers/no_delivery_since/{year}/{month}/{day}") async def customers_no_delivery_since( year: int, month: int, day: int, db: Session = Depends(get_db) ): """ Get customers who have not had a delivery since the specified date. """ try: threshold_date = datetime(year, month, day).date() count, customers = get_customers_without_delivery_since(db, threshold_date) return {"customer_count": count, "customers": customers} except ValueError as e: return {"error": str(e)}