Move nested functions

This commit is contained in:
Peter Stockings
2024-12-29 22:59:08 +11:00
parent 91b3ef0e7e
commit 6291c37820
3 changed files with 131 additions and 134 deletions

View File

@@ -36,4 +36,3 @@ def logout():
logout_user() # Logs out the current user logout_user() # Logs out the current user
flash('You have been logged out.', 'success') flash('You have been logged out.', 'success')
return redirect(url_for('auth.login')) # Redirect to login page or home page return redirect(url_for('auth.login')) # Redirect to login page or home page

View File

@@ -23,6 +23,79 @@ def health():
@main.route('/dashboard', methods=['GET', 'POST']) @main.route('/dashboard', methods=['GET', 'POST'])
@login_required @login_required
def dashboard(): def dashboard():
# Get the first and last reading timestamps
first_reading_timestamp, last_reading_timestamp = get_reading_date_range(current_user.id)
# Set default start and end dates
start_date = first_reading_timestamp.strftime('%Y-%m-%d') if first_reading_timestamp else None
end_date = last_reading_timestamp.strftime('%Y-%m-%d') if last_reading_timestamp else None
# Handle filtering for POST request
readings_query = Reading.query.filter_by(user_id=current_user.id)
if request.method == 'POST':
start_date = request.form.get('start_date') or start_date
end_date = request.form.get('end_date') or end_date
if start_date and end_date:
readings_query = readings_query.filter(
Reading.timestamp >= datetime.strptime(start_date, '%Y-%m-%d'),
Reading.timestamp <= datetime.strptime(end_date, '%Y-%m-%d')
)
# Fetch readings
readings = readings_query.order_by(Reading.timestamp.desc()).all()
# Fetch the user's timezone (default to 'UTC' if none is set)
user_timezone = current_user.profile.timezone if current_user.profile and current_user.profile.timezone else 'UTC'
local_tz = timezone(user_timezone)
# Add relative & local timestamps to readings
now = datetime.utcnow()
for reading in readings:
reading.relative_timestamp = humanize.naturaltime(now - reading.timestamp)
reading.local_timestamp = utc.localize(reading.timestamp).astimezone(local_tz)
month_view = generate_monthly_calendar(readings, now, local_tz)
# Calculate weekly summary and progress badges
systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary(readings)
badges = calculate_progress_badges(readings)
# Prepare graph data
timestamps = [reading.timestamp.strftime('%b %d') for reading in readings]
systolic = [reading.systolic for reading in readings]
diastolic = [reading.diastolic for reading in readings]
heart_rate = [reading.heart_rate for reading in readings]
# Group readings by date
readings_by_date = {}
for reading in readings:
date_key = reading.timestamp.date()
if date_key not in readings_by_date:
readings_by_date[date_key] = []
readings_by_date[date_key].append(reading)
# Render template
return render_template(
'dashboard.html',
readings=readings,
profile=current_user.profile,
badges=badges,
systolic_avg=systolic_avg,
diastolic_avg=diastolic_avg,
heart_rate_avg=heart_rate_avg,
delete_form=DeleteForm(),
timestamps=timestamps,
systolic=systolic,
diastolic=diastolic,
heart_rate=heart_rate,
start_date=start_date,
end_date=end_date,
readings_by_date=readings_by_date,
month = month_view,
date=date,
timedelta=timedelta
)
# Helper function to get first and last reading timestamps # Helper function to get first and last reading timestamps
def get_reading_date_range(user_id): def get_reading_date_range(user_id):
result = ( result = (
@@ -47,6 +120,35 @@ def dashboard():
systolic_avg = diastolic_avg = heart_rate_avg = 0 systolic_avg = diastolic_avg = heart_rate_avg = 0
return systolic_avg, diastolic_avg, heart_rate_avg return systolic_avg, diastolic_avg, heart_rate_avg
def generate_monthly_calendar(readings, selected_date, local_timezone):
# Convert selected date to user's timezone and extract the start/end dates
today = datetime.now(local_timezone).date()
date = selected_date.astimezone(local_timezone).date()
first_day_of_month = date.replace(day=1)
days_to_subtract = (first_day_of_month.weekday() + 1) % 7
start_date = first_day_of_month - timedelta(days=days_to_subtract)
end_date = start_date + timedelta(days=6 * 7 - 1)
# Group readings by day
readings_by_day = {}
for reading in readings:
local_date = reading.timestamp.astimezone(local_timezone).date()
readings_by_day.setdefault(local_date, []).append(reading)
# Build calendar days
calendar = []
current_date = start_date
while current_date <= end_date:
calendar.append({
'day': current_date.day,
'is_today': current_date == today,
'is_in_current_month': current_date.month == date.month,
'readings': readings_by_day.get(current_date, []),
})
current_date += timedelta(days=1)
return calendar
# Helper function to calculate progress badges # Helper function to calculate progress badges
def calculate_progress_badges(readings): def calculate_progress_badges(readings):
"""Calculate badges based on user reading activity.""" """Calculate badges based on user reading activity."""
@@ -119,105 +221,3 @@ def dashboard():
badges.append("Night Owl: Logged Readings Every Night for a Week") badges.append("Night Owl: Logged Readings Every Night for a Week")
return badges return badges
def generate_monthly_calendar(readings, selected_date, local_timezone):
# Convert selected date to user's timezone and extract the start/end dates
today = datetime.now(local_timezone).date()
date = selected_date.astimezone(local_timezone).date()
first_day_of_month = date.replace(day=1)
days_to_subtract = (first_day_of_month.weekday() + 1) % 7
start_date = first_day_of_month - timedelta(days=days_to_subtract)
end_date = start_date + timedelta(days=6 * 7 - 1)
# Group readings by day
readings_by_day = {}
for reading in readings:
local_date = reading.timestamp.astimezone(local_timezone).date()
readings_by_day.setdefault(local_date, []).append(reading)
# Build calendar days
calendar = []
current_date = start_date
while current_date <= end_date:
calendar.append({
'day': current_date.day,
'is_today': current_date == today,
'is_in_current_month': current_date.month == date.month,
'readings': readings_by_day.get(current_date, []),
})
current_date += timedelta(days=1)
return calendar
# Get the first and last reading timestamps
first_reading_timestamp, last_reading_timestamp = get_reading_date_range(current_user.id)
# Set default start and end dates
start_date = first_reading_timestamp.strftime('%Y-%m-%d') if first_reading_timestamp else None
end_date = last_reading_timestamp.strftime('%Y-%m-%d') if last_reading_timestamp else None
# Handle filtering for POST request
readings_query = Reading.query.filter_by(user_id=current_user.id)
if request.method == 'POST':
start_date = request.form.get('start_date') or start_date
end_date = request.form.get('end_date') or end_date
if start_date and end_date:
readings_query = readings_query.filter(
Reading.timestamp >= datetime.strptime(start_date, '%Y-%m-%d'),
Reading.timestamp <= datetime.strptime(end_date, '%Y-%m-%d')
)
# Fetch readings
readings = readings_query.order_by(Reading.timestamp.desc()).all()
# Fetch the user's timezone (default to 'UTC' if none is set)
user_timezone = current_user.profile.timezone if current_user.profile and current_user.profile.timezone else 'UTC'
local_tz = timezone(user_timezone)
# Add relative & local timestamps to readings
now = datetime.utcnow()
for reading in readings:
reading.relative_timestamp = humanize.naturaltime(now - reading.timestamp)
reading.local_timestamp = utc.localize(reading.timestamp).astimezone(local_tz)
month_view = generate_monthly_calendar(readings, now, local_tz)
# Calculate weekly summary and progress badges
systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary(readings)
badges = calculate_progress_badges(readings)
# Prepare graph data
timestamps = [reading.timestamp.strftime('%b %d') for reading in readings]
systolic = [reading.systolic for reading in readings]
diastolic = [reading.diastolic for reading in readings]
heart_rate = [reading.heart_rate for reading in readings]
# Group readings by date
readings_by_date = {}
for reading in readings:
date_key = reading.timestamp.date()
if date_key not in readings_by_date:
readings_by_date[date_key] = []
readings_by_date[date_key].append(reading)
# Render template
return render_template(
'dashboard.html',
readings=readings,
profile=current_user.profile,
badges=badges,
systolic_avg=systolic_avg,
diastolic_avg=diastolic_avg,
heart_rate_avg=heart_rate_avg,
delete_form=DeleteForm(),
timestamps=timestamps,
systolic=systolic,
diastolic=diastolic,
heart_rate=heart_rate,
start_date=start_date,
end_date=end_date,
readings_by_date=readings_by_date,
month = month_view,
date=date,
timedelta=timedelta
)

View File

@@ -1,12 +1,10 @@
from collections import defaultdict
from flask import Blueprint, render_template, redirect, request, url_for, flash from flask import Blueprint, render_template, redirect, request, url_for, flash
import humanize
from pytz import timezone, utc from pytz import timezone, utc
from sqlalchemy import func
from app.models import Reading, db from app.models import Reading, db
from app.forms import DeleteForm, ReadingForm from app.forms import ReadingForm
from flask_login import login_required, current_user from flask_login import login_required, current_user
from datetime import date, datetime, timedelta from datetime import datetime
reading = Blueprint('reading', __name__) reading = Blueprint('reading', __name__)
@reading.route('/add', methods=['GET', 'POST']) @reading.route('/add', methods=['GET', 'POST'])