Compare commits
2 Commits
dcef99c3bf
...
5b43bca7ca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b43bca7ca | ||
|
|
808143f92b |
@@ -4,12 +4,14 @@ from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_bcrypt import Bcrypt
|
||||
from flask_login import LoginManager
|
||||
from flask_compress import Compress
|
||||
|
||||
# Initialize Flask extensions
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
bcrypt = Bcrypt()
|
||||
login_manager = LoginManager()
|
||||
compress = Compress()
|
||||
|
||||
login_manager.login_view = 'auth.login'
|
||||
login_manager.login_message_category = 'info'
|
||||
@@ -26,6 +28,7 @@ def create_app():
|
||||
migrate.init_app(app, db)
|
||||
bcrypt.init_app(app)
|
||||
login_manager.init_app(app)
|
||||
compress.init_app(app)
|
||||
|
||||
# Import models here to avoid circular imports
|
||||
from app.models import User # Import the User model
|
||||
|
||||
@@ -11,10 +11,10 @@ class User(UserMixin, db.Model):
|
||||
|
||||
class Profile(db.Model):
|
||||
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))
|
||||
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)
|
||||
diastolic_threshold = db.Column(db.Integer, default=90)
|
||||
dark_mode = db.Column(db.Boolean, default=False)
|
||||
|
||||
@@ -35,12 +35,7 @@ def dashboard():
|
||||
# Calculate weekly averages via SQL
|
||||
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
|
||||
# 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)
|
||||
badges = calculate_progress_badges(current_user.id, user_tz)
|
||||
|
||||
# We will default to showing the list view on initial load
|
||||
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],
|
||||
}
|
||||
|
||||
def calculate_progress_badges(readings):
|
||||
"""Generate badges based on user activity and milestones."""
|
||||
now = datetime.utcnow().date()
|
||||
def calculate_progress_badges(user_id, user_tz):
|
||||
"""Generate badges based on user activity and milestones using optimized queries."""
|
||||
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 = []
|
||||
|
||||
if not readings:
|
||||
if total_readings == 0:
|
||||
return badges
|
||||
|
||||
# Use reversed() instead of re-sorting — readings come in desc order from DB
|
||||
sorted_readings = list(reversed(readings))
|
||||
streak_count = 0
|
||||
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
|
||||
daily_streak = True
|
||||
current_check_date = most_recent_date
|
||||
|
||||
previous_date = sorted_readings[0].timestamp.date()
|
||||
|
||||
for reading in sorted_readings[1:]:
|
||||
current_date = reading.timestamp.date()
|
||||
|
||||
if (current_date - previous_date).days == 1:
|
||||
for d in distinct_dates[1:]:
|
||||
if (current_check_date - d).days == 1:
|
||||
streak_count += 1
|
||||
elif (current_date - previous_date).days > 1:
|
||||
daily_streak = False
|
||||
current_check_date = d
|
||||
else:
|
||||
break
|
||||
|
||||
previous_date = current_date
|
||||
|
||||
if daily_streak and streak_count >= 1:
|
||||
if streak_count >= 1:
|
||||
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")
|
||||
|
||||
if daily_streak and streak_count >= 30 and previous_date == now:
|
||||
if streak_count >= 30:
|
||||
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")
|
||||
|
||||
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")
|
||||
|
||||
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:
|
||||
badges.append(f"{highest_milestone} Readings Logged")
|
||||
|
||||
|
||||
@@ -55,20 +55,8 @@
|
||||
<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"
|
||||
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"
|
||||
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
|
||||
{% if request.path == url_for('user.profile') %}
|
||||
text-white
|
||||
|
||||
@@ -15,13 +15,8 @@
|
||||
<div class="bg-white p-6 rounded-lg shadow-md mb-6">
|
||||
|
||||
<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"
|
||||
class="w-44 h-44 rounded-full border">
|
||||
{% else %}
|
||||
<img src="{{ url_for('static', filename='default.png') }}" alt="Default Profile Picture"
|
||||
class="w-44 h-44 rounded-full border">
|
||||
{% endif %}
|
||||
class="w-44 h-44 rounded-full border object-cover shadow">
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
@@ -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 ###
|
||||
@@ -5,7 +5,7 @@
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"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": "",
|
||||
"license": "ISC",
|
||||
|
||||
@@ -8,6 +8,7 @@ email-validator==2.2.0
|
||||
exceptiongroup==1.2.2
|
||||
flask==3.1.0
|
||||
Flask-Bcrypt==1.0.1
|
||||
Flask-Compress==1.14
|
||||
Flask-Login==0.6.3
|
||||
Flask-Migrate==4.0.7
|
||||
flask-sqlalchemy==3.1.1
|
||||
|
||||
@@ -3,9 +3,6 @@ module.exports = {
|
||||
content: ["./app/templates/**/*.html"],
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter', 'sans-serif'],
|
||||
},
|
||||
colors: {
|
||||
primary: {
|
||||
50: '#f0fdfa',
|
||||
|
||||
@@ -7,13 +7,19 @@ project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
sys.path.insert(0, project_root)
|
||||
|
||||
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():
|
||||
readings = []
|
||||
badges = calculate_progress_badges(readings)
|
||||
badges = calculate_progress_badges_test_helper(readings)
|
||||
assert badges == []
|
||||
|
||||
|
||||
@@ -22,7 +28,7 @@ def test_daily_streak():
|
||||
readings = [
|
||||
Reading(timestamp=now - timedelta(days=i)) for i in range(3)
|
||||
] # 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
|
||||
|
||||
|
||||
@@ -31,7 +37,7 @@ def test_weekly_streak():
|
||||
readings = [
|
||||
Reading(timestamp=now - timedelta(days=i)) for i in range(7)
|
||||
] # 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
|
||||
|
||||
|
||||
@@ -40,7 +46,7 @@ def test_morning_riser():
|
||||
readings = [
|
||||
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
|
||||
|
||||
|
||||
@@ -49,7 +55,7 @@ def test_night_owl():
|
||||
readings = [
|
||||
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
|
||||
|
||||
|
||||
@@ -57,7 +63,7 @@ def test_milestones():
|
||||
readings = [
|
||||
Reading(timestamp=datetime.utcnow()) for _ in range(50)
|
||||
] # 50 readings
|
||||
badges = calculate_progress_badges(readings)
|
||||
badges = calculate_progress_badges_test_helper(readings)
|
||||
assert "50 Readings Logged" in badges
|
||||
assert "100 Readings Logged" not in badges # Ensure only the highest milestone
|
||||
|
||||
@@ -67,5 +73,5 @@ def test_no_streak_with_gaps():
|
||||
readings = [
|
||||
Reading(timestamp=now - timedelta(days=i * 2)) for i in range(3)
|
||||
] # Gaps in dates
|
||||
badges = calculate_progress_badges(readings)
|
||||
badges = calculate_progress_badges_test_helper(readings, test_now=now)
|
||||
assert "Current Streak" not in badges
|
||||
|
||||
Reference in New Issue
Block a user