from fastapi import APIRouter from fastapi.responses import JSONResponse from fastapi.encoders import jsonable_encoder from database import session from sqlalchemy import func from datetime import date from decimal import Decimal from app.models.customer import Customer_Customer, Customer_estimate_gallons from app.models.delivery import Delivery from app.models.auto import Auto_Temp # Constants from fuel_estimator HOT_WATER_DAILY_USAGE = Decimal('1.0') K_FACTOR_SMOOTHING_WEIGHT = Decimal('0.7') TUNING_FACTOR = Decimal('1.1') # Maximum fill amounts for different tank sizes (gallons we can actually fill) TANK_MAX_FILLS = { 275: 240, 330: 280, 500: 475, 550: 500 } router = APIRouter( prefix="/fixstuff_customer", tags=["fixstuff_customer"], responses={404: {"description": "Not found"}}, ) @router.get("/lastdelivered", status_code=200) def fix_customer_last_delivered(): """ Updates the last_fill date in the customer_estimate table for each customer by finding the most recent completed delivery (delivery with non-NULL when_delivered) from the delivery table, matched by customer_id and automatic == 0. Returns statistics and a list of changes made. """ session.rollback() # Reset any aborted transaction state customer_estimates = session.query(Customer_estimate_gallons).all() changes = [] total_customers = len(customer_estimates) deliveries_found = 0 updates_made = 0 for ce in customer_estimates: latest_delivery = session.query(Delivery).filter( Delivery.customer_id == ce.customer_id, Delivery.automatic == 0, Delivery.when_delivered.isnot(None) ).order_by(Delivery.when_delivered.desc()).first() if latest_delivery: deliveries_found += 1 if ce.last_fill != latest_delivery.when_delivered: updates_made += 1 old_date = ce.last_fill ce.last_fill = latest_delivery.when_delivered changes.append({ "id": ce.id, "customer_full_name": ce.customer_full_name, "before_date": str(old_date) if old_date else None, "new_date": str(latest_delivery.when_delivered) }) session.add(ce) session.commit() result = { "total_customers": total_customers, "deliveries_found": deliveries_found, "updates_made": updates_made, "changes": changes } return JSONResponse(content=jsonable_encoder(result)) @router.get("/estimate_gallons/{update_db}", status_code=200) def estimate_customer_gallons(update_db: int): """ Estimates current gallons for each regular customer based on delivery history and weather. update_db: 0 for estimation only (no DB changes), 1 for estimation with DB updates. No deliveries: assume 100 gallons. Single delivery: use weather for 2000 sq ft home. Multiple deliveries: use historical average. Includes address and scaling factor. When update_db=1, updates estimated_gallons_left and house_factor in database. """ session.rollback() # Reset any aborted transaction state # Check if weather data is available auto_temp_count = session.query(Auto_Temp).count() if auto_temp_count == 0: return JSONResponse(content={ "error": "Auto_Temp table is empty. Cannot perform fuel estimations without weather data.", "solution": "Populate the Auto_Temp table with weather data first." }) customer_estimates = session.query(Customer_estimate_gallons).all() estimates = [] for ce in customer_estimates: deliveries = session.query(Delivery).filter( Delivery.customer_id == ce.customer_id, Delivery.automatic == 0, Delivery.when_delivered.isnot(None) ).order_by(Delivery.when_delivered).all() # Get tank size and hot water setting tank_size = Decimal(ce.tank_size) if ce.tank_size else Decimal('275') # Use maximum fill amount (how much we can actually fill the tank) tank_size_float = float(tank_size) max_fill = TANK_MAX_FILLS.get(tank_size_float, tank_size_float) effective_tank = Decimal(str(max_fill)) hot_water = ce.hot_water_summer == 1 calculated_scaling = None # For DB update if not deliveries: estimated_gallons = Decimal('100') calculated_scaling = Decimal('0.12') # No deliveries = use average baseline else: last_fill = deliveries[-1].when_delivered estimated_gallons_left = effective_tank today = date.today() if len(deliveries) == 1: # Single delivery: use weather data for 2000 sq ft home, only heat when temp <=65 calculated_scaling = Decimal('0.12') if last_fill < today: # Get daily weather data temp_days = session.query(Auto_Temp).filter( Auto_Temp.todays_date > last_fill, Auto_Temp.todays_date <= today ).all() heating_usage = Decimal('0') hot_water_usage = Decimal('0') house_factor_2000_sqft = Decimal('0.12') # gallons per degree day (average) for temp in temp_days: degree_day = max(0, 65 - float(temp.temp_avg)) heating_usage += house_factor_2000_sqft * Decimal(degree_day) if hot_water: hot_water_usage += HOT_WATER_DAILY_USAGE total_usage = heating_usage + hot_water_usage estimated_gallons_left = max(Decimal('0'), estimated_gallons_left - total_usage) else: # Multiple deliveries: calculate house_factor (gallons per degree day) calculated_scaling = Decimal('0.12') # Default average daily_heating_usages = [] avg_degree_per_days = [] for i in range(len(deliveries) - 1): prev_delivery = deliveries[i] next_delivery = deliveries[i + 1] days = (next_delivery.when_delivered - prev_delivery.when_delivered).days if days > 0: # Calculate degree days for this interval from temp_avg interval_temps = session.query(Auto_Temp).filter( Auto_Temp.todays_date > prev_delivery.when_delivered, Auto_Temp.todays_date <= next_delivery.when_delivered ).all() total_degree_days = sum(max(0, 65 - float(temp.temp_avg)) for temp in interval_temps) total_degree_days = Decimal(total_degree_days) avg_degree_per_day = total_degree_days / days total_hot_water = HOT_WATER_DAILY_USAGE * days gallons_heating = prev_delivery.gallons_delivered - total_hot_water if gallons_heating > 0 and total_degree_days > 0: daily_heating = gallons_heating / days daily_heating_usages.append(daily_heating) avg_degree_per_days.append(avg_degree_per_day) if daily_heating_usages and avg_degree_per_days: average_daily_heating = sum(daily_heating_usages) / len(daily_heating_usages) average_degree_days_per_day = sum(avg_degree_per_days) / len(avg_degree_per_days) if average_degree_days_per_day > 0: house_factor = average_daily_heating / average_degree_days_per_day calculated_scaling = house_factor * TUNING_FACTOR # Override default with calculated value house_factor = calculated_scaling # Use the scaling factor for usage calculation # Calculate usage from last_fill to today using temperature-dependent heating if last_fill < today: temp_days = session.query(Auto_Temp).filter( Auto_Temp.todays_date > last_fill, Auto_Temp.todays_date <= today ).all() heating_usage = Decimal('0') hot_water_usage = Decimal('0') for temp in temp_days: degree_day = max(0, 65 - float(temp.temp_avg)) heating_usage += house_factor * Decimal(degree_day) if hot_water: hot_water_usage += HOT_WATER_DAILY_USAGE total_usage = heating_usage + hot_water_usage estimated_gallons_left = max(Decimal('0'), estimated_gallons_left - total_usage) estimated_gallons = estimated_gallons_left # Update database if requested if update_db == 1: ce.estimated_gallons_left = estimated_gallons if calculated_scaling is not None: ce.house_factor = calculated_scaling session.add(ce) last_5 = deliveries[-5:] if deliveries else [] scaling_factor = float(calculated_scaling) if calculated_scaling is not None else (float(ce.house_factor) if ce.house_factor else None) estimates.append({ "id": ce.id, "total_deliveries": len(deliveries), "customer_full_name": ce.customer_full_name, "account_number": ce.account_number, "address": ce.customer_address, "estimated_gallons": float(estimated_gallons), "scaling_factor": scaling_factor, "last_5_deliveries": [ { "fill_date": str(d.when_delivered), "gallons_delivered": float(d.gallons_delivered), "price_per_gallon": float(d.customer_price / d.gallons_delivered) if d.gallons_delivered and d.gallons_delivered > 0 else None, "total_amount_customer": float(d.customer_price) } for d in last_5 ] }) if update_db == 1: session.commit() return JSONResponse(content=jsonable_encoder(estimates)) @router.get("/estimate_gallons/customer/{customer_id}", status_code=200) def estimate_customer_gallons_specific(customer_id: int): """ Estimates current gallons for a specific regular customer based on delivery history and weather. Returns estimation data for the specified customer only. """ session.rollback() # Reset any aborted transaction state # Check if weather data is available auto_temp_count = session.query(Auto_Temp).count() if auto_temp_count == 0: return JSONResponse(content={ "error": "Auto_Temp table is empty. Cannot perform fuel estimations without weather data.", "solution": "Populate the Auto_Temp table with weather data first." }) customer_estimate = session.query(Customer_estimate_gallons).filter( Customer_estimate_gallons.customer_id == customer_id ).first() if not customer_estimate: return JSONResponse(content={ "error": f"No fuel estimation data found for customer {customer_id}", "solution": "Run the populate_estimates endpoint first to initialize customer data." }) deliveries = session.query(Delivery).filter( Delivery.customer_id == customer_estimate.customer_id, Delivery.automatic == 0, Delivery.when_delivered.isnot(None) ).order_by(Delivery.when_delivered).all() # Get tank size and hot water setting tank_size = Decimal(customer_estimate.tank_size) if customer_estimate.tank_size else Decimal('275') # Use maximum fill amount (how much we can actually fill the tank) tank_size_float = float(tank_size) max_fill = TANK_MAX_FILLS.get(tank_size_float, tank_size_float) effective_tank = Decimal(str(max_fill)) hot_water = customer_estimate.hot_water_summer == 1 calculated_scaling = None # For DB update if not deliveries: estimated_gallons = Decimal('100') calculated_scaling = Decimal('0.12') # No deliveries = use average baseline else: last_fill = deliveries[-1].when_delivered estimated_gallons_left = effective_tank today = date.today() if len(deliveries) == 1: # Single delivery: use weather data for 2000 sq ft home, only heat when temp <=65 calculated_scaling = Decimal('0.12') if last_fill < today: # Get daily weather data temp_days = session.query(Auto_Temp).filter( Auto_Temp.todays_date > last_fill, Auto_Temp.todays_date <= today ).all() heating_usage = Decimal('0') hot_water_usage = Decimal('0') house_factor_2000_sqft = Decimal('0.12') # gallons per degree day (average) for temp in temp_days: degree_day = max(0, 65 - float(temp.temp_avg)) heating_usage += house_factor_2000_sqft * Decimal(degree_day) if hot_water: hot_water_usage += HOT_WATER_DAILY_USAGE total_usage = heating_usage + hot_water_usage estimated_gallons_left = max(Decimal('0'), estimated_gallons_left - total_usage) else: # Multiple deliveries: calculate house_factor (gallons per degree day) calculated_scaling = Decimal('0.12') # Default average daily_heating_usages = [] avg_degree_per_days = [] for i in range(len(deliveries) - 1): prev_delivery = deliveries[i] next_delivery = deliveries[i + 1] days = (next_delivery.when_delivered - prev_delivery.when_delivered).days if days > 0: # Calculate degree days for this interval from temp_avg interval_temps = session.query(Auto_Temp).filter( Auto_Temp.todays_date > prev_delivery.when_delivered, Auto_Temp.todays_date <= next_delivery.when_delivered ).all() total_degree_days = sum(max(0, 65 - float(temp.temp_avg)) for temp in interval_temps) total_degree_days = Decimal(total_degree_days) avg_degree_per_day = total_degree_days / days total_hot_water = HOT_WATER_DAILY_USAGE * days gallons_heating = prev_delivery.gallons_delivered - total_hot_water if gallons_heating > 0 and total_degree_days > 0: daily_heating = gallons_heating / days daily_heating_usages.append(daily_heating) avg_degree_per_days.append(avg_degree_per_day) if daily_heating_usages and avg_degree_per_days: average_daily_heating = sum(daily_heating_usages) / len(daily_heating_usages) average_degree_days_per_day = sum(avg_degree_per_days) / len(avg_degree_per_days) if average_degree_days_per_day > 0: house_factor = average_daily_heating / average_degree_days_per_day calculated_scaling = house_factor * TUNING_FACTOR # Override default with calculated value house_factor = calculated_scaling # Use the scaling factor for usage calculation # Calculate usage from last_fill to today using temperature-dependent heating if last_fill < today: temp_days = session.query(Auto_Temp).filter( Auto_Temp.todays_date > last_fill, Auto_Temp.todays_date <= today ).all() heating_usage = Decimal('0') hot_water_usage = Decimal('0') for temp in temp_days: degree_day = max(0, 65 - float(temp.temp_avg)) heating_usage += house_factor * Decimal(degree_day) if hot_water: hot_water_usage += HOT_WATER_DAILY_USAGE total_usage = heating_usage + hot_water_usage estimated_gallons_left = max(Decimal('0'), estimated_gallons_left - total_usage) estimated_gallons = estimated_gallons_left last_5 = deliveries[-5:] if deliveries else [] scaling_factor = float(calculated_scaling) if calculated_scaling is not None else (float(customer_estimate.house_factor) if customer_estimate.house_factor else None) result = { "id": customer_estimate.id, "customer_id": customer_estimate.customer_id, "total_deliveries": len(deliveries), "customer_full_name": customer_estimate.customer_full_name, "account_number": customer_estimate.account_number, "address": customer_estimate.customer_address, "estimated_gallons": float(estimated_gallons), "tank_size": float(tank_size), "scaling_factor": scaling_factor, "last_5_deliveries": [ { "fill_date": str(d.when_delivered), "gallons_delivered": float(d.gallons_delivered), "price_per_gallon": float(d.customer_price / d.gallons_delivered) if d.gallons_delivered and d.gallons_delivered > 0 else None, "total_amount_customer": float(d.customer_price) } for d in last_5 ] } return JSONResponse(content=jsonable_encoder(result)) @router.get("/populate_estimates", status_code=200) def populate_customer_estimates(): """ Populates the customer_estimate table with data from customer_customer for regular (non-automatic) customers. Only creates records for customers that don't already exist in customer_estimate. Sets default values for fuel estimation fields. Returns statistics on records created. """ session.rollback() # Reset any aborted transaction state # Get all regular customers (customer_automatic == 0) regular_customers = session.query(Customer_Customer).filter( Customer_Customer.customer_automatic == 0 ).all() records_created = 0 skipped_existing = 0 for customer in regular_customers: # Check if estimate record already exists existing_estimate = session.query(Customer_estimate_gallons).filter( Customer_estimate_gallons.customer_id == customer.id ).first() if existing_estimate: skipped_existing += 1 continue # Create new estimate record with defaults new_estimate = Customer_estimate_gallons( customer_id=customer.id, account_number=customer.account_number, customer_town=customer.customer_town, customer_state=customer.customer_state, customer_address=customer.customer_address, customer_zip=customer.customer_zip, customer_full_name=f"{customer.customer_first_name} {customer.customer_last_name}".strip(), last_fill=None, days_since_last_fill=None, last_updated=None, estimated_gallons_left=Decimal('100'), # Default starting value estimated_gallons_left_prev_day=Decimal('100'), tank_height=None, tank_size='275', # Default tank size house_factor=None, auto_status=1, # Active open_ticket_id=None, hot_water_summer=0 # Default to no hot water heating ) session.add(new_estimate) records_created += 1 session.commit() result = { "total_regular_customers": len(regular_customers), "records_created": records_created, "skipped_existing": skipped_existing, "message": f"Created {records_created} new customer estimate records" } return JSONResponse(content=jsonable_encoder(result))