Compare commits

..

2 Commits

Author SHA1 Message Date
Peter Stockings
5b43bca7ca Defer loading of profile pic 2026-03-10 19:40:19 +11:00
Peter Stockings
808143f92b Improve badge performance 2026-03-10 19:23:56 +11:00
10 changed files with 101 additions and 67 deletions

View File

@@ -4,12 +4,14 @@ from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate from flask_migrate import Migrate
from flask_bcrypt import Bcrypt from flask_bcrypt import Bcrypt
from flask_login import LoginManager from flask_login import LoginManager
from flask_compress import Compress
# Initialize Flask extensions # Initialize Flask extensions
db = SQLAlchemy() db = SQLAlchemy()
migrate = Migrate() migrate = Migrate()
bcrypt = Bcrypt() bcrypt = Bcrypt()
login_manager = LoginManager() login_manager = LoginManager()
compress = Compress()
login_manager.login_view = 'auth.login' login_manager.login_view = 'auth.login'
login_manager.login_message_category = 'info' login_manager.login_message_category = 'info'
@@ -26,6 +28,7 @@ def create_app():
migrate.init_app(app, db) migrate.init_app(app, db)
bcrypt.init_app(app) bcrypt.init_app(app)
login_manager.init_app(app) login_manager.init_app(app)
compress.init_app(app)
# Import models here to avoid circular imports # Import models here to avoid circular imports
from app.models import User # Import the User model from app.models import User # Import the User model

View File

@@ -11,10 +11,10 @@ class User(UserMixin, db.Model):
class Profile(db.Model): class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
name = db.Column(db.String(100)) name = db.Column(db.String(100))
email = db.Column(db.String(150), unique=True) email = db.Column(db.String(150), unique=True)
profile_pic = db.Column(db.Text) # Store image as a base64 string profile_pic = db.deferred(db.Column(db.Text)) # Store image as a base64 string, deferred so it doesn't load on every query
systolic_threshold = db.Column(db.Integer, default=140) systolic_threshold = db.Column(db.Integer, default=140)
diastolic_threshold = db.Column(db.Integer, default=90) diastolic_threshold = db.Column(db.Integer, default=90)
dark_mode = db.Column(db.Boolean, default=False) dark_mode = db.Column(db.Boolean, default=False)

View File

@@ -35,12 +35,7 @@ def dashboard():
# Calculate weekly averages via SQL # Calculate weekly averages via SQL
systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary_sql(current_user.id) systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary_sql(current_user.id)
# Badges need paginated or all readings. We'll fetch all readings for badges badges = calculate_progress_badges(current_user.id, user_tz)
# Note: To avoid huge queries, we might want a specific badge query in the future.
# For now, let's fetch current month readings + previous as a rough approximation or keep behavior.
# A generic query for badges:
all_readings = Reading.query.filter_by(user_id=current_user.id).order_by(Reading.timestamp.desc()).all()
badges = calculate_progress_badges(all_readings)
# We will default to showing the list view on initial load # We will default to showing the list view on initial load
page = request.args.get('page', 1, type=int) page = request.args.get('page', 1, type=int)
@@ -248,47 +243,64 @@ def prepare_graph_data(readings):
'heart_rate': [r.heart_rate for r in readings], 'heart_rate': [r.heart_rate for r in readings],
} }
def calculate_progress_badges(readings): def calculate_progress_badges(user_id, user_tz):
"""Generate badges based on user activity and milestones.""" """Generate badges based on user activity and milestones using optimized queries."""
now = datetime.utcnow().date() total_readings = Reading.query.filter_by(user_id=user_id).count()
if total_readings == 0:
return []
# Fetch only timestamps (highly optimized compared to fetching full objects)
timestamps = db.session.query(Reading.timestamp).filter(Reading.user_id == user_id).order_by(Reading.timestamp.desc()).all()
return _compute_badges(total_readings, timestamps, user_tz)
def _compute_badges(total_readings, timestamps, user_tz, now_local=None):
if now_local is None:
now_local = datetime.now(user_tz).date()
badges = [] badges = []
if not readings: if total_readings == 0:
return badges return badges
# Use reversed() instead of re-sorting — readings come in desc order from DB streak_count = 0
sorted_readings = list(reversed(readings)) if timestamps:
distinct_dates = []
last_date = None
for (ts,) in timestamps:
local_date = utc.localize(ts).astimezone(user_tz).date()
if local_date != last_date:
distinct_dates.append(local_date)
last_date = local_date
if distinct_dates:
most_recent_date = distinct_dates[0]
if (now_local - most_recent_date).days <= 1:
streak_count = 1 streak_count = 1
daily_streak = True current_check_date = most_recent_date
previous_date = sorted_readings[0].timestamp.date() for d in distinct_dates[1:]:
if (current_check_date - d).days == 1:
for reading in sorted_readings[1:]:
current_date = reading.timestamp.date()
if (current_date - previous_date).days == 1:
streak_count += 1 streak_count += 1
elif (current_date - previous_date).days > 1: current_check_date = d
daily_streak = False else:
break
previous_date = current_date if streak_count >= 1:
if daily_streak and streak_count >= 1:
badges.append(f"Current Streak: {streak_count} Days") badges.append(f"Current Streak: {streak_count} Days")
if daily_streak and streak_count >= 7: if streak_count >= 7:
badges.append("Logged Every Day for a Week") badges.append("Logged Every Day for a Week")
if streak_count >= 30:
if daily_streak and streak_count >= 30 and previous_date == now:
badges.append("Monthly Streak") badges.append("Monthly Streak")
if all(5 <= r.timestamp.hour < 12 for r in sorted_readings[-7:]): last_7_readings = timestamps[:7]
if len(last_7_readings) == 7:
if all(5 <= utc.localize(ts).astimezone(user_tz).hour < 12 for (ts,) in last_7_readings):
badges.append("Morning Riser: Logged Readings Every Morning for a Week") badges.append("Morning Riser: Logged Readings Every Morning for a Week")
if all(18 <= r.timestamp.hour <= 23 for r in sorted_readings[-7:]): if all(18 <= utc.localize(ts).astimezone(user_tz).hour <= 23 for (ts,) in last_7_readings):
badges.append("Night Owl: Logged Readings Every Night for a Week") badges.append("Night Owl: Logged Readings Every Night for a Week")
milestones = [10, 50, 100, 500, 1000, 5000, 10000] milestones = [10, 50, 100, 500, 1000, 5000, 10000]
highest_milestone = max((m for m in milestones if len(readings) >= m), default=None) highest_milestone = max((m for m in milestones if total_readings >= m), default=None)
if highest_milestone: if highest_milestone:
badges.append(f"{highest_milestone} Readings Logged") badges.append(f"{highest_milestone} Readings Logged")

View File

@@ -55,20 +55,8 @@
<li class="mr-3"> <li class="mr-3">
<a class="flex items-center gap-2 text-primary-200 no-underline hover:text-white font-medium transition-colors py-2 px-4" <a class="flex items-center gap-2 text-primary-200 no-underline hover:text-white font-medium transition-colors py-2 px-4"
href="{{ url_for('user.profile') }}"> href="{{ url_for('user.profile') }}">
{% if current_user.profile and current_user.profile.profile_pic %}
<img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture" <img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture"
class="w-8 h-8 rounded-full border-2 border-white object-cover group-hover:scale-105 transition"> class="w-8 h-8 rounded-full border-2 border-white object-cover group-hover:scale-105 transition">
{% else %}
<!-- Default SVG Icon -->
<div
class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center border-2 border-white">
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="w-5 h-5 text-gray-600"
viewBox="0 0 24 24">
<path
d="M12 12c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
</svg>
</div>
{% endif %}
<span class=" text-sm font-medium group-hover:underline <span class=" text-sm font-medium group-hover:underline
{% if request.path == url_for('user.profile') %} {% if request.path == url_for('user.profile') %}
text-white text-white

View File

@@ -15,13 +15,8 @@
<div class="bg-white p-6 rounded-lg shadow-md mb-6"> <div class="bg-white p-6 rounded-lg shadow-md mb-6">
<div class="flex items-center justify-center mb-4"> <div class="flex items-center justify-center mb-4">
{% if profile.profile_pic %}
<img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture" <img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture"
class="w-44 h-44 rounded-full border"> class="w-44 h-44 rounded-full border object-cover shadow">
{% else %}
<img src="{{ url_for('static', filename='default.png') }}" alt="Default Profile Picture"
class="w-44 h-44 rounded-full border">
{% endif %}
</div> </div>

View File

@@ -0,0 +1,32 @@
"""Add user id index on profile
Revision ID: bd83e779fcc1
Revises: 8cfe56a1e597
Create Date: 2026-03-10 19:33:12.629077
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bd83e779fcc1'
down_revision = '8cfe56a1e597'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('profile', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_profile_user_id'), ['user_id'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('profile', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_profile_user_id'))
# ### end Alembic commands ###

View File

@@ -5,7 +5,7 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"build": "npx tailwindcss -o ./app/static/css/tailwind.css --minify", "build": "npx tailwindcss -o ./app/static/css/tailwind.css --minify",
"serve": "npx tailwindcss -o ./app/static/css/tailwind.css --watch" "serve": "npx tailwindcss -o ./app/static/css/tailwind.css --minify --watch"
}, },
"author": "", "author": "",
"license": "ISC", "license": "ISC",

View File

@@ -8,6 +8,7 @@ email-validator==2.2.0
exceptiongroup==1.2.2 exceptiongroup==1.2.2
flask==3.1.0 flask==3.1.0
Flask-Bcrypt==1.0.1 Flask-Bcrypt==1.0.1
Flask-Compress==1.14
Flask-Login==0.6.3 Flask-Login==0.6.3
Flask-Migrate==4.0.7 Flask-Migrate==4.0.7
flask-sqlalchemy==3.1.1 flask-sqlalchemy==3.1.1

View File

@@ -3,9 +3,6 @@ module.exports = {
content: ["./app/templates/**/*.html"], content: ["./app/templates/**/*.html"],
theme: { theme: {
extend: { extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
colors: { colors: {
primary: { primary: {
50: '#f0fdfa', 50: '#f0fdfa',

View File

@@ -7,13 +7,19 @@ project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, project_root) sys.path.insert(0, project_root)
from app.models import Reading from app.models import Reading
from app.routes.main import calculate_progress_badges from app.routes.main import _compute_badges
from pytz import utc
def calculate_progress_badges_test_helper(readings, test_now=None):
total = len(readings)
timestamps = [(r.timestamp,) for r in sorted(readings, key=lambda x: x.timestamp, reverse=True)]
now_date = test_now.date() if test_now else datetime.utcnow().date()
return _compute_badges(total, timestamps, utc, now_local=now_date)
def test_no_readings(): def test_no_readings():
readings = [] readings = []
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings)
assert badges == [] assert badges == []
@@ -22,7 +28,7 @@ def test_daily_streak():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(3) Reading(timestamp=now - timedelta(days=i)) for i in range(3)
] # 3-day streak ] # 3-day streak
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Current Streak: 3 Days" in badges assert "Current Streak: 3 Days" in badges
@@ -31,7 +37,7 @@ def test_weekly_streak():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(7) Reading(timestamp=now - timedelta(days=i)) for i in range(7)
] # 7-day streak ] # 7-day streak
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Logged Every Day for a Week" in badges assert "Logged Every Day for a Week" in badges
@@ -40,7 +46,7 @@ def test_morning_riser():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(7) Reading(timestamp=now - timedelta(days=i)) for i in range(7)
] ]
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Morning Riser: Logged Readings Every Morning for a Week" in badges assert "Morning Riser: Logged Readings Every Morning for a Week" in badges
@@ -49,7 +55,7 @@ def test_night_owl():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(7) Reading(timestamp=now - timedelta(days=i)) for i in range(7)
] ]
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Night Owl: Logged Readings Every Night for a Week" in badges assert "Night Owl: Logged Readings Every Night for a Week" in badges
@@ -57,7 +63,7 @@ def test_milestones():
readings = [ readings = [
Reading(timestamp=datetime.utcnow()) for _ in range(50) Reading(timestamp=datetime.utcnow()) for _ in range(50)
] # 50 readings ] # 50 readings
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings)
assert "50 Readings Logged" in badges assert "50 Readings Logged" in badges
assert "100 Readings Logged" not in badges # Ensure only the highest milestone assert "100 Readings Logged" not in badges # Ensure only the highest milestone
@@ -67,5 +73,5 @@ def test_no_streak_with_gaps():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i * 2)) for i in range(3) Reading(timestamp=now - timedelta(days=i * 2)) for i in range(3)
] # Gaps in dates ] # Gaps in dates
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Current Streak" not in badges assert "Current Streak" not in badges