major claude changes
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
import logging
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Import your existing database models
|
||||
from app.models.auto import Auto_Delivery, Auto_Temp, Auto_Update, Tickets_Auto_Delivery
|
||||
|
||||
@@ -58,7 +61,7 @@ class FuelEstimator:
|
||||
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)")
|
||||
logger.info(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)
|
||||
@@ -74,13 +77,13 @@ class FuelEstimator:
|
||||
|
||||
# 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.")
|
||||
logger.info(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.")
|
||||
logger.info(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.
|
||||
@@ -92,10 +95,10 @@ class FuelEstimator:
|
||||
).all()
|
||||
|
||||
if not auto_customers:
|
||||
print("No active automatic delivery customers found.")
|
||||
logger.info("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...")
|
||||
logger.info(f"Staging daily fuel update for {len(auto_customers)} customers...")
|
||||
|
||||
corrections_made = 0
|
||||
|
||||
@@ -124,7 +127,7 @@ class FuelEstimator:
|
||||
new_update_log = Auto_Update(last_updated=today)
|
||||
self.session.add(new_update_log)
|
||||
|
||||
print("Daily update staged. Awaiting commit.")
|
||||
logger.info("Daily update staged. Awaiting commit.")
|
||||
message = f"Successfully staged updates for {len(auto_customers)} customers."
|
||||
if corrections_made > 0:
|
||||
message += f" Corrected house factors for {corrections_made} customers."
|
||||
@@ -141,11 +144,11 @@ class FuelEstimator:
|
||||
).first()
|
||||
|
||||
if not customer:
|
||||
print(f"Customer {ticket.customer_id} not found.")
|
||||
logger.info(f"Customer {ticket.customer_id} not found.")
|
||||
return
|
||||
|
||||
if not customer.last_fill:
|
||||
print(f"Setting initial K-Factor for new customer {ticket.customer_id} with only one delivery.")
|
||||
logger.info(f"Setting initial K-Factor for new customer {ticket.customer_id} with only one delivery.")
|
||||
customer.house_factor = self._estimate_initial_house_factor(customer)
|
||||
self._update_tank_after_fill(customer, ticket)
|
||||
return
|
||||
@@ -154,7 +157,7 @@ class FuelEstimator:
|
||||
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.")
|
||||
logger.info(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
|
||||
|
||||
@@ -172,7 +175,7 @@ class FuelEstimator:
|
||||
|
||||
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.")
|
||||
logger.info(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
|
||||
|
||||
@@ -181,13 +184,13 @@ class FuelEstimator:
|
||||
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}")
|
||||
logger.info(f"Refining K-Factor for Customer ID {customer.customer_id}:")
|
||||
logger.info(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.")
|
||||
logger.info(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 update customer tank status after a fill-up or partial delivery."""
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import logging
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Import your existing database models
|
||||
from app.models.customer import Customer_estimate_gallons, Customer_Update
|
||||
from app.models.delivery import Delivery
|
||||
@@ -60,7 +63,7 @@ class FuelEstimatorCustomer:
|
||||
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)")
|
||||
logger.info(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)
|
||||
@@ -76,13 +79,13 @@ class FuelEstimatorCustomer:
|
||||
|
||||
# 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.")
|
||||
logger.info(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.")
|
||||
logger.info(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.
|
||||
@@ -94,10 +97,10 @@ class FuelEstimatorCustomer:
|
||||
).all()
|
||||
|
||||
if not customer_estimates:
|
||||
print("No active regular delivery customers found.")
|
||||
logger.info("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...")
|
||||
logger.info(f"Staging daily fuel update for {len(customer_estimates)} customers...")
|
||||
|
||||
corrections_made = 0
|
||||
|
||||
@@ -126,7 +129,7 @@ class FuelEstimatorCustomer:
|
||||
new_update_log = Customer_Update(last_updated=today)
|
||||
self.session.add(new_update_log)
|
||||
|
||||
print("Daily update staged. Awaiting commit.")
|
||||
logger.info("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."
|
||||
@@ -143,11 +146,11 @@ class FuelEstimatorCustomer:
|
||||
).first()
|
||||
|
||||
if not customer:
|
||||
print(f"Customer {delivery.customer_id} not found.")
|
||||
logger.info(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.")
|
||||
logger.info(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
|
||||
@@ -156,7 +159,7 @@ class FuelEstimatorCustomer:
|
||||
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.")
|
||||
logger.info(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
|
||||
|
||||
@@ -174,7 +177,7 @@ class FuelEstimatorCustomer:
|
||||
|
||||
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.")
|
||||
logger.info(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
|
||||
|
||||
@@ -183,13 +186,13 @@ class FuelEstimatorCustomer:
|
||||
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}")
|
||||
logger.info(f"Refining K-Factor for Customer ID {customer.customer_id}:")
|
||||
logger.info(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.")
|
||||
logger.info(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."""
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import logging
|
||||
from datetime import date
|
||||
import requests
|
||||
from decimal import Decimal
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Import your database model and the session from your database configuration
|
||||
from app.models.auto import Auto_Temp
|
||||
from database import session
|
||||
@@ -22,11 +25,11 @@ def fetch_and_store_daily_temp() -> bool:
|
||||
# 1. Check if the temperature for today already exists in the database
|
||||
today = date.today()
|
||||
if session.query(Auto_Temp).filter(Auto_Temp.todays_date == today).first():
|
||||
print(f"Temperature for {today} already exists in the database. Skipping fetch.")
|
||||
logger.info(f"Temperature for {today} already exists in the database. Skipping fetch.")
|
||||
return True
|
||||
|
||||
# 2. If it doesn't exist, fetch it from the API
|
||||
print(f"Fetching temperature for {today} from OpenWeatherMap...")
|
||||
logger.info(f"Fetching temperature for {today} from OpenWeatherMap...")
|
||||
try:
|
||||
# API key and location
|
||||
api_key = '21648d8c8d1a4ae495ace0b7810b4d36'
|
||||
@@ -63,11 +66,11 @@ def fetch_and_store_daily_temp() -> bool:
|
||||
|
||||
# 4. Add the new record to the session (it will be committed by the calling function)
|
||||
session.add(add_new_temp)
|
||||
print(f"Successfully fetched and staged temperature for {today}.")
|
||||
logger.info(f"Successfully fetched and staged temperature for {today}.")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"An error occurred while fetching weather data: {e}")
|
||||
logger.info(f"An error occurred while fetching weather data: {e}")
|
||||
# Make sure to rollback the session in case of a partial failure
|
||||
session.rollback()
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user