diff --git a/app/routes/main.py b/app/routes/main.py index 17be71f..6da64b8 100644 --- a/app/routes/main.py +++ b/app/routes/main.py @@ -30,7 +30,7 @@ def dashboard(): end_date = request.form.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d')) # Fetch filtered readings - readings = fetch_readings(current_user.id, start_date, end_date) + readings = fetch_readings(current_user.id, start_date, end_date, user_tz) # Annotate readings with relative and localized timestamps annotate_readings(readings, user_tz) @@ -69,16 +69,26 @@ def get_reading_date_range(user_id, user_tz): func.min(Reading.timestamp).label('first'), func.max(Reading.timestamp).label('last') ).filter(Reading.user_id == user_id).first() - return utc.localize(result.first).astimezone(user_tz), utc.localize(result.last).astimezone(user_tz) -def fetch_readings(user_id, start_date, end_date): + first = utc.localize(result.first).astimezone(user_tz) if result.first else None + last = utc.localize(result.last).astimezone(user_tz) if result.last else None + return first, last + + +def fetch_readings(user_id, start_date, end_date, user_tz): """Retrieve readings filtered by date range.""" query = Reading.query.filter_by(user_id=user_id) + if start_date and end_date: + # Convert dates to the user's timezone + start_dt = user_tz.localize(datetime.strptime(start_date, '%Y-%m-%d')).astimezone(utc) + end_dt = user_tz.localize(datetime.strptime(end_date, '%Y-%m-%d')).astimezone(utc) + timedelta(days=1) - timedelta(seconds=1) + query = query.filter( - Reading.timestamp >= datetime.strptime(start_date, '%Y-%m-%d'), - Reading.timestamp <= datetime.strptime(end_date, '%Y-%m-%d') + Reading.timestamp >= start_dt, + Reading.timestamp <= end_dt ) + return query.order_by(Reading.timestamp.desc()).all() def annotate_readings(readings, user_tz):