Files
eamco_auto_api/app/script/fuel_estimator_customer.py
2026-01-05 08:43:40 -05:00

220 lines
9.7 KiB
Python

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.customer import Customer_estimate_gallons, Customer_Update
from app.models.delivery import Delivery
from app.models.auto import Auto_Temp
# --- 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('1.0')
# 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')
TANK_MAX_FILLS = {
275: 240,
330: 280,
500: 475,
550: 500
}
PARTIAL_DELIVERIES = [100, 125, 150, 200]
class FuelEstimatorCustomer:
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 _estimate_initial_house_factor(self, customer: Customer_estimate_gallons) -> Decimal:
"""
Generic function to estimate initial house factor for customers with only one delivery.
This can be improved with more sophisticated logic (e.g., averaging similar customers).
"""
# Default generic house factor: 0.12 gallons per degree day (average based on existing customer data)
# This represents typical heating usage and can be adjusted based on future data analysis
return Decimal('0.12')
def _verify_house_factor_correctness(self, customer: Customer_estimate_gallons) -> bool:
"""
Verify and correct house_factor based on delivery history.
Returns True if correction was made.
"""
# Count deliveries for this customer
delivery_count = self.session.query(func.count(Delivery.id)).filter(
Delivery.customer_id == customer.customer_id
).scalar()
corrected = False
if delivery_count <= 1:
# Customers with 0 or 1 delivery should have house_factor = 0.12 (initial average)
if customer.house_factor != Decimal('0.12'):
print(f"Correcting house_factor for customer {customer.customer_id} from {customer.house_factor} to 0.12 (1 or fewer deliveries)")
customer.house_factor = Decimal('0.12')
corrected = True
# For customers with 2+ deliveries, keep their calculated factor (no correction needed)
return corrected
def run_daily_update(self):
"""
Main function to run once per day. It updates the estimated fuel level
for all active regular customers. The calling function must commit the session.
"""
today = date.today()
# 1. Check if the update has already run today
if self.session.query(Customer_Update).filter(Customer_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 = 0.
degree_day = Decimal(max(0, 65 - float(todays_weather.temp_avg)))
# 3. Get all active regular customers
customer_estimates = self.session.query(Customer_estimate_gallons).filter(
Customer_estimate_gallons.auto_status == 1 # Assuming 1 means active
).all()
if not customer_estimates:
print("No active regular delivery customers found.")
return {"ok": True, "message": "No active customers to update."}
print(f"Staging daily fuel update for {len(customer_estimates)} customers...")
corrections_made = 0
# 4. Loop through each customer and update their fuel level
for customer in customer_estimates:
# Verify and correct house_factor if needed
if self._verify_house_factor_correctness(customer):
corrections_made += 1
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 = Customer_Update(last_updated=today)
self.session.add(new_update_log)
print("Daily update staged. Awaiting commit.")
message = f"Successfully staged updates for {len(customer_estimates)} customers."
if corrections_made > 0:
message += f" Corrected house factors for {corrections_made} customers."
return {"ok": True, "message": message}
def refine_factor_after_delivery(self, delivery: 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(Customer_estimate_gallons).filter(
Customer_estimate_gallons.customer_id == delivery.customer_id
).first()
if not customer:
print(f"Customer {delivery.customer_id} not found.")
return
if not customer.last_fill:
print(f"Setting initial K-Factor for new customer {delivery.customer_id} with only one delivery.")
customer.house_factor = self._estimate_initial_house_factor(customer)
self._update_tank_after_fill(customer, delivery)
return
start_date = customer.last_fill
end_date = delivery.when_delivered
if start_date >= end_date:
print(f"Cannot refine K-Factor for customer {delivery.customer_id}: New fill date is not after the last one. Resetting tank only.")
self._update_tank_after_fill(customer, delivery)
return
interval_temps = self.session.query(Auto_Temp).filter(
Auto_Temp.todays_date > start_date,
Auto_Temp.todays_date <= end_date
).all()
total_degree_days = sum(max(0, 65 - float(temp.temp_avg)) for temp in interval_temps)
total_hdd = Decimal(total_degree_days)
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 = delivery.gallons_delivered - total_hot_water_usage
if gallons_for_heating <= 0 or total_hdd == 0:
print(f"Cannot calculate new K-Factor for customer {delivery.customer_id}. (HDD: {total_hdd}, Heating Gallons: {gallons_for_heating}). Resetting tank only.")
self._update_tank_after_fill(customer, delivery)
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, delivery)
print(f"K-Factor and tank status for Customer {customer.customer_id} staged for update.")
def _update_tank_after_fill(self, customer: Customer_estimate_gallons, delivery: Delivery):
"""Helper to update customer tank status after a fill-up or partial delivery."""
customer.last_fill = delivery.when_delivered
customer.days_since_last_fill = 0
# Determine max fill capacity
if customer.tank_size and Decimal(customer.tank_size) > 0:
tank_size = float(Decimal(customer.tank_size))
max_fill = TANK_MAX_FILLS.get(tank_size, tank_size)
else:
# Default to legal max for common tank size (275 gallons = 240)
max_fill = 240.0
# Check if this is a partial delivery
if float(delivery.gallons_delivered) in PARTIAL_DELIVERIES:
# Partial delivery: add to current level, cap at max_fill
customer.estimated_gallons_left += delivery.gallons_delivered
customer.estimated_gallons_left = min(customer.estimated_gallons_left, Decimal(str(max_fill)))
else:
# Full delivery: set to max_fill
customer.estimated_gallons_left = Decimal(str(max_fill))
# The previous day's value should match the new 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