from sqlalchemy.orm import Session from sqlalchemy import func from datetime import date, timedelta from decimal import Decimal # Import your existing database models from app.models.auto import Auto_Delivery, Auto_Temp, Auto_Update, Tickets_Auto_Delivery # --- Constants for the Model --- # This is a baseline daily usage for homes that use oil for hot water. # A typical value is 0.5 to 1.0 gallons per day. Adjust as needed. HOT_WATER_DAILY_USAGE = Decimal('0.7') # This determines how quickly the K-Factor adjusts. # 0.7 means 70% weight is given to the historical factor and 30% to the new one. # This prevents wild swings from a single unusual delivery period. K_FACTOR_SMOOTHING_WEIGHT = Decimal('0.7') class FuelEstimator: def __init__(self, session: Session): self.session = session def _get_weather_for_date(self, target_date: date) -> Auto_Temp | None: """Helper to fetch weather data for a specific date.""" return self.session.query(Auto_Temp).filter(Auto_Temp.todays_date == target_date).first() def run_daily_update(self): """ Main function to run once per day. It updates the estimated fuel level for all active automatic delivery customers. The calling function must commit the session. """ today = date.today() # 1. Check if the update has already run today if self.session.query(Auto_Update).filter(Auto_Update.last_updated == today).first(): print(f"Daily update for {today} has already been completed.") return {"ok": True, "message": "Update already run today."} # 2. Get today's weather data (specifically the Heating Degree Days) todays_weather = self._get_weather_for_date(today) if not todays_weather: print(f"Error: Weather data for {today} not found. Cannot run update.") return {"ok": False, "message": f"Weather data for {today} not found."} # Degree days can't be negative for this calculation. If it's warm, HDD is 0. degree_day = Decimal(max(0, todays_weather.degree_day)) # 3. Get all active automatic customers auto_customers = self.session.query(Auto_Delivery).filter( Auto_Delivery.auto_status == 1 # Assuming 1 means active ).all() if not auto_customers: print("No active automatic delivery customers found.") return {"ok": True, "message": "No active customers to update."} print(f"Staging daily fuel update for {len(auto_customers)} customers...") # 4. Loop through each customer and update their fuel level for customer in auto_customers: heating_usage = customer.house_factor * degree_day hot_water_usage = Decimal('0.0') if customer.hot_water_summer == 1: hot_water_usage = HOT_WATER_DAILY_USAGE gallons_used_today = heating_usage + hot_water_usage customer.estimated_gallons_left_prev_day = customer.estimated_gallons_left new_estimated_gallons = customer.estimated_gallons_left - gallons_used_today customer.estimated_gallons_left = max(Decimal('0.0'), new_estimated_gallons) customer.last_updated = today if customer.days_since_last_fill is not None: customer.days_since_last_fill += 1 # 5. Log that today's update is complete new_update_log = Auto_Update(last_updated=today) self.session.add(new_update_log) print("Daily update staged. Awaiting commit.") return {"ok": True, "message": f"Successfully staged updates for {len(auto_customers)} customers."} def refine_factor_after_delivery(self, ticket: Tickets_Auto_Delivery): """ This is the self-correction logic. It recalculates and refines the customer's K-Factor (house_factor) after a delivery. The calling function must commit the session. """ customer = self.session.query(Auto_Delivery).filter( Auto_Delivery.customer_id == ticket.customer_id ).first() if not customer or not customer.last_fill: print(f"Cannot refine K-Factor: Customer {ticket.customer_id} not found or has no previous fill date. Resetting tank only.") self._update_tank_after_fill(customer, ticket) return start_date = customer.last_fill end_date = ticket.fill_date if start_date >= end_date: print(f"Cannot refine K-Factor for customer {ticket.customer_id}: New fill date is not after the last one. Resetting tank only.") self._update_tank_after_fill(customer, ticket) return total_hdd_result = self.session.query(func.sum(Auto_Temp.degree_day)).filter( Auto_Temp.todays_date > start_date, Auto_Temp.todays_date <= end_date, Auto_Temp.degree_day > 0 ).scalar() total_hdd = Decimal(total_hdd_result or 0) total_hot_water_usage = Decimal('0.0') if customer.hot_water_summer == 1: num_days = (end_date - start_date).days total_hot_water_usage = Decimal(num_days) * HOT_WATER_DAILY_USAGE gallons_for_heating = ticket.gallons_delivered - total_hot_water_usage if gallons_for_heating <= 0 or total_hdd == 0: print(f"Cannot calculate new K-Factor for customer {ticket.customer_id}. (HDD: {total_hdd}, Heating Gallons: {gallons_for_heating}). Resetting tank only.") self._update_tank_after_fill(customer, ticket) return new_k_factor = gallons_for_heating / total_hdd current_k_factor = customer.house_factor smoothed_k_factor = (current_k_factor * K_FACTOR_SMOOTHING_WEIGHT) + (new_k_factor * (Decimal('1.0') - K_FACTOR_SMOOTHING_WEIGHT)) print(f"Refining K-Factor for Customer ID {customer.customer_id}:") print(f" - Old K-Factor: {current_k_factor:.4f}, New Smoothed K-Factor: {smoothed_k_factor:.4f}") customer.house_factor = smoothed_k_factor self._update_tank_after_fill(customer, ticket) print(f"K-Factor and tank status for Customer {customer.customer_id} staged for update.") def _update_tank_after_fill(self, customer: Auto_Delivery, ticket: Tickets_Auto_Delivery): """Helper to reset customer tank status after a fill-up.""" customer.last_fill = ticket.fill_date customer.days_since_last_fill = 0 # A "fill-up" means the tank is full. This is critical for accuracy. if customer.tank_size and Decimal(customer.tank_size) > 0: customer.estimated_gallons_left = Decimal(customer.tank_size) else: # Default to a common tank size if not specified, e.g., 275 customer.estimated_gallons_left = Decimal('275.0') # The previous day's value should match the new full value on a fill day. customer.estimated_gallons_left_prev_day = customer.estimated_gallons_left customer.last_updated = date.today() customer.auto_status = 1 # Reactivate the customer