Compare commits

..

16 Commits

Author SHA1 Message Date
Peter Stockings
25d1774e53 perf: remove redundant COUNT query and use bulk insert for CSV imports 2026-03-15 00:24:26 +11:00
Peter Stockings
25aa7de043 Add minification of html, css, & js and brotli compression to reduce page size 2026-03-14 23:58:37 +11:00
Peter Stockings
f7ce1c3fd6 Shrink profile pic 2026-03-13 22:42:30 +11:00
Peter Stockings
e2d85f0a88 Make table view responsive 2026-03-13 15:28:06 +11:00
Peter Stockings
910d583966 Make date filters responsive 2026-03-13 15:20:58 +11:00
Peter Stockings
eca31040af Update DIY HTMX to trigger on input update 2026-03-13 15:18:09 +11:00
Peter Stockings
086784b2a2 Add table view 2026-03-13 15:14:00 +11:00
Peter Stockings
a9802f300b Move date filter to graph view 2026-03-13 15:11:11 +11:00
Peter Stockings
6f216944bf Improve look of graphs 2026-03-12 22:56:26 +11:00
Peter Stockings
675ca02818 Add diy replacement for turbo 2026-03-11 22:57:54 +11:00
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
Peter Stockings
dcef99c3bf perf: massive reduction in application bundle size
- Replaced Alpine.js and Turbolinks with lightweight vanilla JS event listeners
- Swapped HTMX CDN import for a custom 15-line native JS polyfill
- Removed Google Fonts ('Inter') in favor of the native system font stack
- Extracted repeated SVGs in list views into a `<defs>` block to shrink HTML
- Reduced dashboard pagination PAGE_SIZE from 50 to 25
- Minified Tailwind CSS output and enabled Gzip/Brotli via Flask-Compress
2026-03-10 19:10:47 +11:00
Peter Stockings
a0abf41ff6 Load dashboard displays using htmx 2026-03-10 16:25:52 +11:00
Peter Stockings
4f1add9154 Add ability to move forward/back on week/month view and improve UI 2026-03-09 22:13:56 +11:00
Peter Stockings
31203cd551 Improve the look of cards in list view 2026-03-09 21:59:35 +11:00
25 changed files with 1376 additions and 2360 deletions

View File

@@ -7,6 +7,7 @@ WORKDIR /app
# Copy only the necessary files for TailwindCSS build
COPY package.json package-lock.json ./
COPY ./app/templates ./app/templates
COPY ./app/static/js ./app/static/js
COPY tailwind.config.js ./
# Install Node.js dependencies
@@ -39,6 +40,7 @@ COPY . .
# Copy the built TailwindCSS assets from the first stage
COPY --from=tailwind-builder /app/app/static/css/tailwind.css ./app/static/css/tailwind.css
COPY --from=tailwind-builder /app/app/static/js/diy-turbo.min.js ./app/static/js/diy-turbo.min.js
# Run tests during the build process
RUN pytest --maxfail=5 --disable-warnings -v || (echo "Tests failed. Exiting." && exit 1)

View File

@@ -4,12 +4,16 @@ 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
from flask_minify import Minify
# Initialize Flask extensions
db = SQLAlchemy()
migrate = Migrate()
bcrypt = Bcrypt()
login_manager = LoginManager()
compress = Compress()
minify = Minify(html=True, js=True, cssless=True, fail_safe=True)
login_manager.login_view = 'auth.login'
login_manager.login_message_category = 'info'
@@ -26,6 +30,9 @@ def create_app():
migrate.init_app(app, db)
bcrypt.init_app(app)
login_manager.init_app(app)
compress.init_app(app)
minify.init_app(app)
# Import models here to avoid circular imports
from app.models import User # Import the User model

View File

@@ -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)

View File

@@ -17,16 +17,17 @@ def manage_data():
try:
csv_data = csv.reader(StringIO(file.read().decode('utf-8')))
next(csv_data) # Skip the header row
readings_to_add = []
for row in csv_data:
timestamp, systolic, diastolic, heart_rate = row
reading = Reading(
readings_to_add.append(Reading(
user_id=current_user.id,
timestamp=datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S'),
systolic=int(systolic),
diastolic=int(diastolic),
heart_rate=int(heart_rate),
)
db.session.add(reading)
))
db.session.bulk_save_objects(readings_to_add)
db.session.commit()
flash('Data imported successfully!', 'success')
except Exception as e:

View File

@@ -11,7 +11,7 @@ from datetime import date, datetime, timedelta
main = Blueprint('main', __name__)
# Number of readings to show per page in list view
PAGE_SIZE = 50
PAGE_SIZE = 25
@main.route('/', methods=['GET'])
def landing():
@@ -24,64 +24,123 @@ def health():
@main.route('/dashboard', methods=['GET', 'POST'])
@login_required
def dashboard():
"""Render the dashboard with readings, stats, and calendar views."""
"""Render the dashboard shell and default list view."""
user_tz = timezone(current_user.profile.timezone or 'UTC')
# Get date range for readings
first_reading, last_reading = get_reading_date_range(current_user.id, user_tz)
start_date = request.form.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d'))
end_date = request.form.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d'))
# Pagination for list view
page = request.args.get('page', 1, type=int)
# Fetch paginated readings for the list view
paginated = fetch_readings_paginated(current_user.id, start_date, end_date, user_tz, page, PAGE_SIZE)
# For calendar/graph/badges, fetch only current month + week readings (much smaller set)
now = datetime.now(user_tz)
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month_start_utc = month_start.astimezone(utc)
calendar_readings = fetch_readings_for_range(current_user.id, month_start_utc)
# Annotate all readings with relative and localized timestamps
annotate_readings(paginated.items, user_tz)
annotate_readings(calendar_readings, user_tz)
# Build shared lookup for calendar views (single pass)
readings_by_day = build_readings_by_day(calendar_readings, user_tz)
# Generate calendar views from the shared lookup
week_view = generate_weekly_calendar(readings_by_day, now, user_tz)
month_view = generate_monthly_calendar(readings_by_day, now, user_tz)
# Calculate weekly averages via SQL (much faster than Python)
# Calculate weekly averages via SQL
systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary_sql(current_user.id)
# Badges from the paginated readings (or full set if needed)
badges = calculate_progress_badges(paginated.items)
# Prepare graph data from calendar readings (current month)
graph_data = prepare_graph_data(calendar_readings)
badges = calculate_progress_badges(current_user.id, user_tz)
return render_template(
'dashboard.html',
readings=paginated.items,
pagination=paginated,
profile=current_user.profile,
badges=badges,
systolic_avg=systolic_avg,
diastolic_avg=diastolic_avg,
heart_rate_avg=heart_rate_avg,
delete_form=DeleteForm(),
start_date=start_date,
end_date=end_date,
month=month_view,
week=week_view,
date=date,
**graph_data
active_view='list',
)
@main.route('/dashboard/list', methods=['GET'])
@login_required
def dashboard_list():
user_tz = timezone(current_user.profile.timezone or 'UTC')
page = request.args.get('page', 1, type=int)
# List view is no longer constrained by date filter
paginated = fetch_readings_paginated(current_user.id, None, None, user_tz, page, PAGE_SIZE)
annotate_readings(paginated.items, user_tz)
return render_template('partials/dashboard_list.html', readings=paginated.items, pagination=paginated)
@main.route('/dashboard/table', methods=['GET'])
@login_required
def dashboard_table():
user_tz = timezone(current_user.profile.timezone or 'UTC')
first_reading, last_reading = get_reading_date_range(current_user.id, user_tz)
start_date = request.args.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d'))
end_date = request.args.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d'))
page = request.args.get('page', 1, type=int)
paginated = fetch_readings_paginated(current_user.id, start_date, end_date, user_tz, page, PAGE_SIZE)
annotate_readings(paginated.items, user_tz)
return render_template('partials/dashboard_table.html', readings=paginated.items, pagination=paginated, start_date=start_date, end_date=end_date)
@main.route('/dashboard/weekly', methods=['GET'])
@login_required
def dashboard_weekly():
user_tz = timezone(current_user.profile.timezone or 'UTC')
week_offset = request.args.get('week_offset', 0, type=int)
now = datetime.now(user_tz)
target_week_date = now + timedelta(weeks=week_offset)
target_week_start = target_week_date - timedelta(days=target_week_date.weekday())
target_week_start_utc = target_week_start.replace(hour=0, minute=0, second=0, microsecond=0).astimezone(utc)
target_week_end_utc = (target_week_start + timedelta(days=7)).replace(hour=0, minute=0, second=0, microsecond=0).astimezone(utc)
calendar_readings = fetch_readings_for_range(current_user.id, target_week_start_utc, target_week_end_utc)
annotate_readings(calendar_readings, user_tz)
readings_by_day = build_readings_by_day(calendar_readings, user_tz)
week_view = generate_weekly_calendar(readings_by_day, target_week_date, user_tz)
return render_template('partials/dashboard_weekly.html', week=week_view, week_offset=week_offset)
@main.route('/dashboard/monthly', methods=['GET'])
@login_required
def dashboard_monthly():
user_tz = timezone(current_user.profile.timezone or 'UTC')
month_offset = request.args.get('month_offset', 0, type=int)
now = datetime.now(user_tz)
target_month_year = now.year + (now.month + month_offset - 1) // 12
target_month_month = (now.month + month_offset - 1) % 12 + 1
target_month_date = now.replace(year=target_month_year, month=target_month_month, day=1, hour=0, minute=0, second=0, microsecond=0)
first_day = target_month_date
start_date = first_day - timedelta(days=(first_day.weekday() + 1) % 7)
end_date = start_date + timedelta(days=42)
start_utc = start_date.replace(hour=0, minute=0, second=0, microsecond=0).astimezone(utc)
end_utc = end_date.replace(hour=0, minute=0, second=0, microsecond=0).astimezone(utc)
calendar_readings = fetch_readings_for_range(current_user.id, start_utc, end_utc)
annotate_readings(calendar_readings, user_tz)
readings_by_day = build_readings_by_day(calendar_readings, user_tz)
month_view = generate_monthly_calendar(readings_by_day, target_month_date, user_tz)
return render_template('partials/dashboard_monthly.html', month=month_view, target_month_date=target_month_date, month_offset=month_offset)
@main.route('/dashboard/graph', methods=['GET'])
@login_required
def dashboard_graph():
user_tz = timezone(current_user.profile.timezone or 'UTC')
first_reading, last_reading = get_reading_date_range(current_user.id, user_tz)
start_date = request.args.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d'))
end_date = request.args.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d'))
if start_date and end_date:
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)
calendar_readings = fetch_readings_for_range(current_user.id, start_dt, end_dt)
else:
now = datetime.now(user_tz)
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month_start_utc = month_start.astimezone(utc)
calendar_readings = fetch_readings_for_range(current_user.id, month_start_utc)
annotate_readings(calendar_readings, user_tz)
graph_data = prepare_graph_data(calendar_readings)
graph_data['start_date'] = start_date
graph_data['end_date'] = end_date
return render_template('partials/dashboard_graph.html', **graph_data)
def get_reading_date_range(user_id, user_tz):
"""Fetch the earliest and latest reading timestamps for a user."""
result = db.session.query(
@@ -186,55 +245,102 @@ def generate_weekly_calendar(readings_by_day, selected_date, local_tz):
]
def prepare_graph_data(readings):
"""Prepare data for graph rendering."""
"""Prepare data for graph rendering, reversing so chronological order is left-to-right."""
chronological_readings = list(reversed(readings))
n = len(chronological_readings)
time_percentages = []
systolic_vals = [r.systolic for r in chronological_readings]
diastolic_vals = [r.diastolic for r in chronological_readings]
hr_vals = [r.heart_rate for r in chronological_readings]
sys_avg = round(sum(systolic_vals) / n, 1) if n > 0 else 0
dia_avg = round(sum(diastolic_vals) / n, 1) if n > 0 else 0
hr_avg = round(sum(hr_vals) / n, 1) if n > 0 else 0
if n == 0:
pass
elif n == 1:
time_percentages = [0.5]
else:
first_time = chronological_readings[0].timestamp.timestamp()
last_time = chronological_readings[-1].timestamp.timestamp()
time_span = last_time - first_time
for r in chronological_readings:
if time_span == 0:
time_percentages.append(0.5)
else:
p = (r.timestamp.timestamp() - first_time) / time_span
time_percentages.append(p)
return {
'timestamps': [r.timestamp.strftime('%b %d') for r in readings],
'systolic': [r.systolic for r in readings],
'diastolic': [r.diastolic for r in readings],
'heart_rate': [r.heart_rate for r in readings],
'timestamps': [r.timestamp.strftime('%b %d\n%H:%M') for r in chronological_readings],
'systolic': systolic_vals,
'diastolic': diastolic_vals,
'heart_rate': hr_vals,
'time_percentages': time_percentages,
'sys_avg': sys_avg,
'dia_avg': dia_avg,
'hr_avg': hr_avg,
}
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."""
# Fetch only timestamps (index-only scan on the composite index)
timestamps = db.session.query(Reading.timestamp).filter(Reading.user_id == user_id).order_by(Reading.timestamp.desc()).all()
total_readings = len(timestamps)
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")

View File

@@ -33,7 +33,7 @@ def profile():
try:
image = Image.open(io.BytesIO(file_data))
image = image.convert("RGB") # Ensure it's in RGB format
image.thumbnail((300, 300)) # Resize to a maximum of 300x300 pixels
image.thumbnail((200, 200)) # Resize to a maximum of 200x200 pixels
# Save the resized image to a buffer
buffer = io.BytesIO()

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,68 @@
document.addEventListener('click', async (e) => {
const link = e.target.closest('a');
if (!link) return;
const url = link.getAttribute('href');
if (!url || url.startsWith('#') || url.startsWith('javascript:')) return;
// Only intercept same-origin links
if (link.origin !== window.location.origin) return;
// Ignore links that open in a new tab, download, or modifier keys
if (link.target === '_blank' || link.hasAttribute('download')) return;
if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey) return;
// Optional: add a "data-turbo='false'" attribute check to disable it on specific links
if (link.getAttribute('data-turbo') === 'false') return;
e.preventDefault();
document.body.style.cursor = 'wait';
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
document.title = doc.title;
document.body.innerHTML = doc.body.innerHTML;
// Carry over classes on the body if they changed
document.body.className = doc.body.className;
document.body.style.cursor = 'default';
window.history.pushState({}, '', url);
window.scrollTo(0, 0);
// Dispatch a custom event so other scripts can re-initialize if necessary
document.dispatchEvent(new Event('diy-turbo:load'));
} catch (error) {
console.error('DIY Turbo navigation error:', error);
window.location.href = url; // fallback
}
});
window.addEventListener('popstate', async () => {
document.body.style.cursor = 'wait';
try {
const response = await fetch(window.location.href);
if (!response.ok) throw new Error('Fetch failed');
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
document.title = doc.title;
document.body.innerHTML = doc.body.innerHTML;
document.body.className = doc.body.className;
document.body.style.cursor = 'default';
document.dispatchEvent(new Event('diy-turbo:load'));
} catch (error) {
console.error('DIY Turbo popstate error:', error);
window.location.reload(); // fallback
}
});

1
app/static/js/diy-turbo.min.js vendored Normal file
View File

@@ -0,0 +1 @@
document.addEventListener("click",async t=>{const e=t.target.closest("a");if(!e)return;const o=e.getAttribute("href");if(o&&!o.startsWith("#")&&!o.startsWith("javascript:")&&e.origin===window.location.origin&&!("_blank"===e.target||e.hasAttribute("download")||t.ctrlKey||t.shiftKey||t.metaKey||t.altKey||"false"===e.getAttribute("data-turbo"))){t.preventDefault(),document.body.style.cursor="wait";try{const t=await fetch(o);if(!t.ok)throw new Error("Fetch failed");const e=await t.text(),r=(new DOMParser).parseFromString(e,"text/html");document.title=r.title,document.body.innerHTML=r.body.innerHTML,document.body.className=r.body.className,document.body.style.cursor="default",window.history.pushState({},"",o),window.scrollTo(0,0),document.dispatchEvent(new Event("diy-turbo:load"))}catch(t){console.error("DIY Turbo navigation error:",t),window.location.href=o}}}),window.addEventListener("popstate",async()=>{document.body.style.cursor="wait";try{const t=await fetch(window.location.href);if(!t.ok)throw new Error("Fetch failed");const e=await t.text(),o=(new DOMParser).parseFromString(e,"text/html");document.title=o.title,document.body.innerHTML=o.body.innerHTML,document.body.className=o.body.className,document.body.style.cursor="default",document.dispatchEvent(new Event("diy-turbo:load"))}catch(t){console.error("DIY Turbo popstate error:",t),window.location.reload()}});

File diff suppressed because one or more lines are too long

View File

@@ -6,16 +6,13 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}BP Tracker{% endblock %}</title>
<link rel="icon" type="image/svg+xml" sizes="any" href="{{ url_for('static', filename='images/favicon.svg') }}">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link href="/static/css/tailwind.css" rel="stylesheet">
<script src="/static/js/alpine.min.js" defer></script>
<script src="/static/js/turbolinks.min.js"></script>
<script src="{{ url_for('static', filename='js/diy-turbo.min.js') }}"></script>
</head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased">
<nav class="flex items-center justify-between flex-wrap p-6 fixed w-full z-10 top-0 transition-colors duration-300 shadow-md"
x-data="{ isOpen: false }" @keydown.escape="isOpen = false" @click.away="isOpen = false"
:class="{ 'bg-primary-900' : isOpen , 'bg-primary-800' : !isOpen}">
<nav id="mobile-nav"
class="flex items-center justify-between flex-wrap p-6 fixed w-full z-10 top-0 transition-colors duration-300 shadow-md bg-primary-800">
<!--Logo etc-->
<div class="flex items-center flex-shrink-0 text-white mr-6">
<a class="text-white no-underline hover:text-white hover:no-underline" href="/">
@@ -24,20 +21,18 @@
</div>
<!--Toggle button (hidden on large screens)-->
<button @click="isOpen = !isOpen" type="button"
class="block lg:hidden px-2 text-gray-500 hover:text-white focus:outline-none focus:text-white"
:class="{ 'transition transform-180': isOpen }">
<button id="mobile-menu-btn" type="button"
class="block lg:hidden px-2 text-gray-500 hover:text-white focus:outline-none focus:text-white transition">
<svg class="h-6 w-6 fill-current" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path x-show="isOpen" fill-rule="evenodd" clip-rule="evenodd"
<path id="icon-close" class="hidden" fill-rule="evenodd" clip-rule="evenodd"
d="M18.278 16.864a1 1 0 0 1-1.414 1.414l-4.829-4.828-4.828 4.828a1 1 0 0 1-1.414-1.414l4.828-4.829-4.828-4.828a1 1 0 0 1 1.414-1.414l4.829 4.828 4.828-4.828a1 1 0 1 1 1.414 1.414l-4.828 4.829 4.828 4.828z" />
<path x-show="!isOpen" fill-rule="evenodd"
<path id="icon-menu" fill-rule="evenodd"
d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z" />
</svg>
</button>
<!--Menu-->
<div class="w-full flex-grow lg:flex lg:items-center lg:w-auto"
:class="{ 'block shadow-3xl': isOpen, 'hidden': !isOpen }" x-show.transition="true">
<div id="mobile-menu" class="w-full flex-grow lg:flex lg:items-center lg:w-auto hidden shadow-3xl">
<ul class="pt-6 lg:pt-0 list-reset lg:flex justify-end flex-1 items-center">
{% if current_user.is_authenticated %}
<li class="mr-3">
@@ -61,20 +56,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
@@ -120,11 +103,11 @@
{% if messages %}
<div class="fixed top-24 right-4 z-50 space-y-4">
{% for category, message in messages %}
<div class="flex items-center justify-between p-4 rounded-xl shadow-xl text-white bg-{{ 'red' if category == 'danger' else 'primary' }}-500 min-w-[300px]"
x-data="{ visible: true }" x-show="visible" x-transition.duration.300ms>
<div
class="flash-message flex items-center justify-between p-4 rounded-xl shadow-xl text-white bg-{{ 'red' if category == 'danger' else 'primary' }}-500 min-w-[300px] transition-all duration-300">
<span class="font-medium">{{ message }}</span>
<button @click="visible = false"
class="text-2xl font-bold ml-4 hover:text-gray-200 transition-colors">&times;</button>
<button
class="flash-close-btn text-2xl font-bold ml-4 hover:text-gray-200 transition-colors">&times;</button>
</div>
{% endfor %}
</div>
@@ -145,6 +128,168 @@
</div>
</footer>
<script>
// Use document for event delegation since body is replaced by diy-turbo
document.addEventListener('click', async (e) => {
// Flash messages close button
const flashCloseBtn = e.target.closest('.flash-close-btn');
if (flashCloseBtn) {
const el = flashCloseBtn.closest('.flash-message');
if (el) {
el.style.opacity = '0';
setTimeout(() => el.remove(), 300);
}
return;
}
// Micro-HTMX implementation
const htmxTrigger = e.target.closest('[hx-get]');
if (htmxTrigger) {
if (htmxTrigger.tagName === 'FORM') return; // Let submit handler deal with forms
e.preventDefault();
const url = htmxTrigger.getAttribute('hx-get');
const targetSelector = htmxTrigger.getAttribute('hx-target');
if (!url || !targetSelector) return;
const targetEl = document.querySelector(targetSelector);
if (!targetEl) return;
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
targetEl.innerHTML = await response.text();
} catch (err) {
console.error('Micro-HTMX error:', err);
}
return;
}
// Mobile Menu Toggle Button
const menuBtn = e.target.closest('#mobile-menu-btn');
if (menuBtn) {
const menu = document.getElementById('mobile-menu');
const nav = document.getElementById('mobile-nav');
const iconMenu = document.getElementById('icon-menu');
const iconClose = document.getElementById('icon-close');
if (menu) {
const isHidden = menu.classList.contains('hidden');
if (!isHidden) {
menu.classList.add('hidden');
nav.classList.replace('bg-primary-900', 'bg-primary-800');
iconMenu.classList.remove('hidden');
iconClose.classList.add('hidden');
menuBtn.classList.remove('rotate-180', 'transform');
} else {
menu.classList.remove('hidden');
nav.classList.replace('bg-primary-800', 'bg-primary-900');
iconMenu.classList.add('hidden');
iconClose.classList.remove('hidden');
menuBtn.classList.add('rotate-180', 'transform');
}
}
return;
}
// Handle clicks outside of nav/menu to close mobile menu
const nav = document.getElementById('mobile-nav');
const menu = document.getElementById('mobile-menu');
if (nav && menu && !nav.contains(e.target) && !menu.classList.contains('hidden')) {
menu.classList.add('hidden');
nav.classList.replace('bg-primary-900', 'bg-primary-800');
const iconMenu = document.getElementById('icon-menu');
const iconClose = document.getElementById('icon-close');
const mobileMenuBtn = document.getElementById('mobile-menu-btn');
if (iconMenu) iconMenu.classList.remove('hidden');
if (iconClose) iconClose.classList.add('hidden');
if (mobileMenuBtn) mobileMenuBtn.classList.remove('rotate-180', 'transform');
}
});
// Handle Escape key to close mobile menu
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
const menu = document.getElementById('mobile-menu');
if (menu && !menu.classList.contains('hidden')) {
const nav = document.getElementById('mobile-nav');
menu.classList.add('hidden');
if (nav) nav.classList.replace('bg-primary-900', 'bg-primary-800');
const iconMenu = document.getElementById('icon-menu');
const iconClose = document.getElementById('icon-close');
const mobileMenuBtn = document.getElementById('mobile-menu-btn');
if (iconMenu) iconMenu.classList.remove('hidden');
if (iconClose) iconClose.classList.add('hidden');
if (mobileMenuBtn) mobileMenuBtn.classList.remove('rotate-180', 'transform');
}
}
});
// Auto-submit forms when inputs change
document.addEventListener('change', (e) => {
const htmxForm = e.target.closest('form[hx-get], form[hx-post]');
if (htmxForm) {
htmxForm.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
}
});
// Handle form submissions for Micro-HTMX
document.addEventListener('submit', async (e) => {
const htmxForm = e.target.closest('form[hx-get], form[hx-post]');
if (htmxForm) {
e.preventDefault();
const method = htmxForm.hasAttribute('hx-post') ? 'POST' : 'GET';
let url = htmxForm.getAttribute('hx-get') || htmxForm.getAttribute('hx-post');
const targetSelector = htmxForm.getAttribute('hx-target');
if (!url || !targetSelector) return;
const targetEl = document.querySelector(targetSelector);
if (!targetEl) return;
try {
let fetchOpts = { method };
if (method === 'GET') {
const formData = new FormData(htmxForm);
const params = new URLSearchParams(formData).toString();
if (params) {
url += (url.includes('?') ? '&' : '?') + params;
}
} else {
fetchOpts.body = new FormData(htmxForm);
}
const response = await fetch(url, fetchOpts);
if (!response.ok) throw new Error('Fetch failed');
targetEl.innerHTML = await response.text();
} catch (err) {
console.error('Micro-HTMX submit error:', err);
}
}
});
// Handle auto-loading elements
const handleAutoLoads = async () => {
const elements = document.querySelectorAll('[hx-trigger="load"][hx-get]');
for (const el of elements) {
const url = el.getAttribute('hx-get');
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Auto-fetch failed');
el.innerHTML = await response.text();
el.removeAttribute('hx-trigger'); // ensure it only loads once per page view
} catch (err) {
console.error('Micro-HTMX autoload error:', err);
}
}
};
document.addEventListener('DOMContentLoaded', handleAutoLoads);
document.addEventListener('diy-turbo:load', handleAutoLoads);
</script>
</body>
</html>

View File

@@ -40,304 +40,75 @@
</div>
</div>
<div x-data="{ open: {{ 'true' if request.method == 'POST' else 'false' }} }" class="relative">
<!-- Compact Icon -->
<button @click="open = !open"
class="bg-primary-600 text-white p-3 rounded-full shadow-lg focus:outline-none hover:bg-primary-700">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
stroke="currentColor" class="w-6 h-6">
<path x-show="!open" stroke-linecap="round" stroke-linejoin="round" d="M6 9l6 6 6-6" />
<path x-show="open" x-cloak stroke-linecap="round" stroke-linejoin="round" d="M18 15l-6-6-6 6" />
</svg>
</button>
<!-- Collapsible Filter Form -->
<div x-show="open" x-transition.duration.300ms
class="w-full md:w-1/3 bg-white p-6 rounded-xl shadow-lg border border-gray-200">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-bold text-gray-800">Filter Readings</h3>
</div>
<form method="POST" action="{{ url_for('main.dashboard') }}" class="space-y-4">
<!-- Start Date -->
<div>
<label for="start_date" class="block text-sm font-medium text-gray-700">Start Date</label>
<input type="date" name="start_date" id="start_date"
class="w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500">
</div>
<!-- End Date -->
<div>
<label for="end_date" class="block text-sm font-medium text-gray-700">End Date</label>
<input type="date" name="end_date" id="end_date"
class="w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500">
</div>
<!-- Apply Button -->
<div>
<button type="submit"
class="w-full bg-primary-600 text-white py-2 rounded-xl font-semibold shadow-md hover:bg-primary-700 focus:outline-none">
Apply Filters
</button>
</div>
</form>
</div>
</div>
<div class="max-w-5xl mx-auto" x-data="{ activeView: 'list' }">
<div class="max-w-5xl mx-auto">
<!-- Tabs -->
<div class="flex border-b mb-4">
<button @click="activeView = 'list'" :class="{'border-primary-600 text-primary-600': activeView === 'list'}"
class="px-4 py-2 text-sm font-medium border-b-2">List View</button>
<button @click="activeView = 'weekly'"
:class="{'border-primary-600 text-primary-600': activeView === 'weekly'}"
class="px-4 py-2 text-sm font-medium border-b-2">Weekly View</button>
<button @click="activeView = 'monthly'"
:class="{'border-primary-600 text-primary-600': activeView === 'monthly'}"
class="px-4 py-2 text-sm font-medium border-b-2">Monthly View</button>
<button @click="activeView = 'graph'"
:class="{'border-primary-600 text-primary-600': activeView === 'graph'}"
class="px-4 py-2 text-sm font-medium border-b-2">Graph View</button>
<div class="flex border-b mb-4 overflow-x-auto" id="dashboard-tabs">
<button hx-get="{{ url_for('main.dashboard_list') }}" hx-target="#dashboard-content"
class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'list' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">List
View</button>
<button hx-get="{{ url_for('main.dashboard_table') }}" hx-target="#dashboard-content"
class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'table' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Table
View</button>
<button hx-get="{{ url_for('main.dashboard_weekly') }}" hx-target="#dashboard-content"
class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'weekly' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Weekly
View</button>
<button hx-get="{{ url_for('main.dashboard_monthly') }}" hx-target="#dashboard-content"
class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'monthly' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Monthly
View</button>
<button hx-get="{{ url_for('main.dashboard_graph') }}" hx-target="#dashboard-content"
class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'graph' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Graph
View</button>
</div>
<!-- List -->
<div x-show="activeView === 'list'" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{% for reading in readings %}
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="bg-white shadow-md rounded-xl p-4 flex flex-col justify-between relative hover:shadow-lg transition-shadow">
<!-- Timestamp -->
<div class="absolute top-2 right-2 flex items-center text-gray-400 text-xs">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round"
d="M12 8v4l3 3m9-3a9 9 0 1 1-18 0 9 9 0 0 1 18 0z" />
</svg>
<span title="{{ reading.local_timestamp.strftime('%d %b %Y, %I:%M %p') }}">
{{ reading.relative_timestamp }}
</span>
<!-- Dashboard Content Target Area for HTMX -->
<div id="dashboard-content" hx-get="{{ url_for('main.dashboard_list') }}" hx-trigger="load">
<div class="flex justify-center items-center p-12">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
</div>
<!-- Blood Pressure -->
<div class="text-sm text-gray-600 mb-2">
<span class="block text-lg font-semibold text-gray-800">Blood Pressure</span>
<span class="text-2xl font-bold text-primary-600">{{ reading.systolic }}</span>
<span class="text-lg text-gray-500">/</span>
<span class="text-xl font-bold text-red-600">{{ reading.diastolic }}</span>
<span class="text-sm text-gray-500">mmHg</span>
</div>
<!-- Heart Rate and Arrow -->
<div class="flex justify-between items-center mt-4 relative">
<div class="text-sm text-gray-600">
<span class="block text-lg font-semibold text-gray-800">Heart Rate</span>
<span class="text-2xl font-bold text-green-600">{{ reading.heart_rate }}</span>
<span class="text-sm text-gray-500">bpm</span>
</div>
<!-- Arrow Icon -->
<div class="absolute bottom-0 right-0 text-gray-400 hover:text-gray-600">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="h-5 w-5">
<path stroke-linecap="round" stroke-linejoin="round"
d="M6.75 12a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0ZM12.75 12a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0ZM18.75 12a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z" />
</svg>
</div>
</div>
</a>
{% else %}
<div class="col-span-full text-center text-sm text-gray-500">
No readings found.
</div>
{% endfor %}
</div>
<!-- Pagination Controls -->
{% if pagination.pages > 1 %}
<div x-show="activeView === 'list'" class="flex justify-center items-center gap-2 mt-6">
{% if pagination.has_prev %}
<a href="{{ url_for('main.dashboard', page=pagination.prev_num) }}"
class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">&laquo; Prev</a>
{% endif %}
{% for page_num in pagination.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
{% if page_num %}
<a href="{{ url_for('main.dashboard', page=page_num) }}"
class="px-3 py-1 rounded text-sm {% if page_num == pagination.page %}bg-primary-600 text-white{% else %}bg-gray-200 hover:bg-gray-300{% endif %}">
{{ page_num }}
</a>
{% else %}
<span class="text-gray-400"></span>
{% endif %}
{% endfor %}
{% if pagination.has_next %}
<a href="{{ url_for('main.dashboard', page=pagination.next_num) }}"
class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">Next &raquo;</a>
{% endif %}
</div>
{% endif %}
<!-- Weekly View -->
<div x-show="activeView === 'weekly'" class="grid grid-cols-7 text-center">
{% for day in week %}
<div class="border p-1 md:p-4 bg-gray-50">
<div class="text-sm font-bold text-gray-500">{{ day.date }}</div>
{% if day.readings %}
{% for reading in day.readings %}
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="block mt-2 p-0 md:p-2 bg-green-100 rounded-xl shadow hover:bg-green-200 transition">
<p class="text-xs font-medium text-green-800">
{{ reading.systolic }}/{{ reading.diastolic }} mmHg
</p>
<p class="text-xs text-gray-600 mt-1">{{ reading.heart_rate }} bpm</p>
<!-- Timestamp -->
<div class="text-xs text-gray-500 mt-1">
{{ reading.local_timestamp.strftime('%I:%M %p') }}
</div>
</a>
{% endfor %}
{% else %}
<div class="h-8"></div> <!-- Placeholder for spacing -->
{% endif %}
</div>
{% endfor %}
</div>
<!-- Monthly View -->
<div class="flex flex-col px-2 py-2 -mb-px" x-show="activeView === 'monthly'">
{% set current_date = date.today().replace(day=1) %}
<!-- Month Name -->
<div class="text-center">
<h2 class="text-xl font-bold text-gray-800">{{ current_date.strftime('%B %Y') }}</h2>
</div>
<div class="grid grid-cols-7 pl-2 pr-2">
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Sunday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Sun</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Monday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Mon</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Tuesday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Tue</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Wednesday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Wed</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Thursday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Thu</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Friday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Fri</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Saturday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Sat</span>
</div>
</div>
<div class="grid grid-cols-7 overflow-hidden flex-1 pl-2 pr-2 w-full">
{% for day in month %}
<div
class="{% if day.is_today %}rounded-md border-4 border-green-50{% endif %} border flex flex-col h-36 sm:h-40 md:h-30 lg:h-30 mx-auto mx-auto overflow-hidden w-full pt-2 pl-1 cursor-pointer {% if day.is_in_current_month %}bg-gray-100{% endif %}">
<div class="top h-5 w-full">
<span class="text-gray-500 font-semibold">{{ day.day }}</span>
</div>
{% for reading in day.readings %}
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="block mt-2 p-0 md:p-2 bg-green-100 rounded-xl shadow hover:bg-green-200 transition">
<p class="text-xs font-medium text-green-800">
{{ reading.systolic }}/{{ reading.diastolic }} mmHg
</p>
<p class="text-xs text-gray-600 mt-1">{{ reading.heart_rate }} bpm</p>
<!-- Timestamp -->
<div class="text-xs text-gray-500 mt-1">
{{ reading.local_timestamp.strftime('%I:%M %p') }}
</div>
</a>
{% endfor %}
</div>
{% endfor %}
</div>
</div>
<!-- Graph Section -->
<div x-show="activeView === 'graph'" class="space-y-6">
<!-- Blood Pressure Graph -->
<div>
<h3 class="text-sm font-semibold text-gray-600 mb-2">Blood Pressure (mmHg)</h3>
<svg viewBox="0 0 600 250" xmlns="http://www.w3.org/2000/svg" class="w-full">
<!-- Axes -->
<line x1="50" y1="200" x2="550" y2="200" stroke="black" stroke-width="1" /> <!-- X-axis -->
<line x1="50" y1="20" x2="50" y2="200" stroke="black" stroke-width="1" /> <!-- Y-axis -->
<script>
// Use event delegation for dashboard interactions to survive DIY Turbo page replacements
document.addEventListener('click', (e) => {
// Filter Form Toggle
const filterBtn = e.target.closest('#filter-btn');
if (filterBtn) {
const filterForm = document.getElementById('filter-form');
const iconClosed = document.getElementById('filter-icon-closed');
const iconOpen = document.getElementById('filter-icon-open');
<!-- Y-axis Labels (Blood Pressure Values) -->
{% for value in range(50, 201, 50) %}
<text x="40" y="{{ 200 - (value / 200 * 180) }}" font-size="10" text-anchor="end">{{ value }}</text>
{% endfor %}
if (filterForm) {
const isHidden = filterForm.classList.contains('hidden');
if (isHidden) {
filterForm.classList.remove('hidden');
if (iconClosed) iconClosed.classList.add('hidden');
if (iconOpen) iconOpen.classList.remove('hidden');
} else {
filterForm.classList.add('hidden');
if (iconClosed) iconClosed.classList.remove('hidden');
if (iconOpen) iconOpen.classList.add('hidden');
}
}
return;
}
<!-- X-axis Labels (Timestamps) -->
{% for i in range(timestamps|length) %}
<text x="{{ 50 + i * 50 }}" y="215" font-size="10" text-anchor="middle">{{ timestamps[i] }}</text>
{% endfor %}
<!-- Graph Lines -->
<!-- Systolic Line -->
<polyline fill="none" stroke="blue" stroke-width="2"
points="{% for i in range(timestamps|length) %}{{ 50 + i * 50 }},{{ 200 - (systolic[i] / 200 * 180) }} {% endfor %}" />
<!-- Diastolic Line -->
<polyline fill="none" stroke="red" stroke-width="2"
points="{% for i in range(timestamps|length) %}{{ 50 + i * 50 }},{{ 200 - (diastolic[i] / 200 * 180) }} {% endfor %}" />
<!-- Axis Labels -->
<text x="25" y="110" font-size="12" transform="rotate(-90, 25, 110)" text-anchor="middle">Blood
Pressure (mmHg)</text>
<text x="300" y="240" font-size="12" text-anchor="middle">Date</text>
</svg>
</div>
<!-- Heart Rate Graph -->
<div>
<h3 class="text-sm font-semibold text-gray-600 mb-2">Heart Rate (bpm)</h3>
<svg viewBox="0 0 600 250" xmlns="http://www.w3.org/2000/svg" class="w-full">
<!-- Axes -->
<line x1="50" y1="200" x2="550" y2="200" stroke="black" stroke-width="1" /> <!-- X-axis -->
<line x1="50" y1="20" x2="50" y2="200" stroke="black" stroke-width="1" /> <!-- Y-axis -->
<!-- Y-axis Labels (Heart Rate Values) -->
{% for value in range(50, 201, 50) %}
<text x="40" y="{{ 200 - (value / 200 * 180) }}" font-size="10" text-anchor="end">{{ value }}</text>
{% endfor %}
<!-- X-axis Labels (Timestamps) -->
{% for i in range(timestamps|length) %}
<text x="{{ 50 + i * 50 }}" y="215" font-size="10" text-anchor="middle">{{ timestamps[i] }}</text>
{% endfor %}
<!-- Heart Rate Line -->
<polyline fill="none" stroke="green" stroke-width="2"
points="{% for i in range(timestamps|length) %}{{ 50 + i * 50 }},{{ 200 - (heart_rate[i] / 200 * 180) }} {% endfor %}" />
<!-- Axis Labels -->
<text x="25" y="110" font-size="12" transform="rotate(-90, 25, 110)" text-anchor="middle">Heart Rate
(bpm)</text>
<text x="300" y="240" font-size="12" text-anchor="middle">Date</text>
</svg>
</div>
</div>
</div>
</div>
// Tabs
const tabBtn = e.target.closest('.tab-btn');
if (tabBtn) {
const tabBtns = document.querySelectorAll('.tab-btn');
tabBtns.forEach(b => {
b.classList.remove('border-primary-600', 'text-primary-600');
});
tabBtn.classList.add('border-primary-600', 'text-primary-600');
// The click will still bubble up and be caught by the Micro-HTMX logic in _layout.html
return;
}
});
</script>
{% endblock %}

View File

@@ -0,0 +1,346 @@
<style>
.svg-tooltip-group .svg-tooltip-content {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s ease-in-out;
pointer-events: none;
}
.svg-tooltip-group:hover .svg-tooltip-content {
opacity: 1;
visibility: visible;
}
</style>
<div class="space-y-8">
<!-- Graph Date Filter -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-2">
<form hx-get="{{ url_for('main.dashboard_graph') }}" hx-target="#dashboard-content"
class="flex flex-col sm:flex-row gap-4">
<!-- Start Date -->
<div class="flex-1">
<label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
<input type="date" name="start_date" id="start_date" value="{{ start_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
<!-- End Date -->
<div class="flex-1">
<label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">End Date</label>
<input type="date" name="end_date" id="end_date" value="{{ end_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
</form>
</div>
<!-- Blood Pressure Graph Card -->
<div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 transition-all hover:shadow-xl">
<div class="flex flex-col md:flex-row md:items-center justify-between mb-6">
<div>
<h3 class="text-xl font-bold text-gray-800">Blood Pressure Trends</h3>
<p class="text-sm text-gray-500 mt-1">Systolic vs Diastolic over time (mmHg)</p>
</div>
<div class="flex space-x-6 text-sm mt-4 md:mt-0 bg-gray-50 px-4 py-2 rounded-full">
<div class="flex items-center"><span
class="w-3 h-3 rounded-full bg-blue-500 mr-2 shadow-sm"></span><span
class="font-medium text-gray-700">Systolic</span></div>
<div class="flex items-center"><span
class="w-3 h-3 rounded-full bg-pink-500 mr-2 shadow-sm"></span><span
class="font-medium text-gray-700">Diastolic</span></div>
</div>
</div>
<div class="w-full overflow-x-auto pb-4">
<svg viewBox="0 0 800 350" class="w-full min-w-[600px] h-auto drop-shadow-sm font-sans"
style="max-height: 350px;">
<defs>
<linearGradient id="sysGrad" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="#3b82f6" stop-opacity="0.3" />
<stop offset="100%" stop-color="#3b82f6" stop-opacity="0.0" />
</linearGradient>
<linearGradient id="diaGrad" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="#ec4899" stop-opacity="0.3" />
<stop offset="100%" stop-color="#ec4899" stop-opacity="0.0" />
</linearGradient>
</defs>
{% if timestamps %}
{% set n = timestamps|length %}
{% set spacing = 700 / (n - 1) if n > 1 else 0 %}
<!-- Horizontal Grid Lines & Y-Axis Labels -->
{% for value in range(50, 201, 50) %}
{% set y = 280 - (value / 200 * 250) %}
<line x1="50" y1="{{ y }}" x2="750" y2="{{ y }}" stroke="#e5e7eb" stroke-width="1"
stroke-dasharray="4 4" />
<text x="40" y="{{ y + 4 }}" font-size="12" fill="#9ca3af" text-anchor="end" font-weight="500">{{ value
}}</text>
{% endfor %}
<!-- X-Axis Base Line -->
<line x1="50" y1="280" x2="750" y2="280" stroke="#d1d5db" stroke-width="1" />
<!-- X-Axis Labels -->
{% set ns = namespace(last_x=-100) %}
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
<!-- Optimization: only draw label if it has enough horizontal space from the last drawn label -->
{% set is_last = (i == n - 1) %}
{% if x - ns.last_x > 45 or is_last %}
<!-- If it's the last label but too close to the previous, maybe we draw it anyway but it will overlap. We prevent overlap by aggressively spacing. -->
{% if not is_last or x - ns.last_x > 40 or ns.last_x == -100 %}
<text x="{{ x }}" y="310" font-size="11" fill="#6b7280" text-anchor="middle" font-weight="500"
transform="rotate(-25 {{ x }} 310)">{{
timestamps[i] }}</text>
{% set ns.last_x = x %}
{% endif %}
{% endif %}
{% endfor %}
<!-- Systolic Filled Area -->
<polygon fill="url(#sysGrad)" points="{% if n>1 %}50{% else %}400{% endif %},280
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (systolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}
{% if n>1 %}{{ 50 + (n - 1) * spacing }}{% else %}400{% endif %},280" />
<!-- Systolic Line -->
<polyline fill="none" stroke="#3b82f6" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"
points="{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (systolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}" />
<!-- Systolic Points -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (systolic[i] / 200 * 250) %}
<circle cx="{{ x }}" cy="{{ y }}" r="5" fill="#ffffff" stroke="#3b82f6" stroke-width="2.5"></circle>
{% endfor %}
<!-- Diastolic Filled Area -->
<polygon fill="url(#diaGrad)" points="{% if n>1 %}50{% else %}400{% endif %},280
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (diastolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}
{% if n>1 %}{{ 50 + (n - 1) * spacing }}{% else %}400{% endif %},280" />
<!-- Diastolic Line -->
<polyline fill="none" stroke="#ec4899" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"
points="{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (diastolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}" />
<!-- Diastolic Points -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (diastolic[i] / 200 * 250) %}
<circle cx="{{ x }}" cy="{{ y }}" r="5" fill="#ffffff" stroke="#ec4899" stroke-width="2.5"></circle>
{% endfor %}
<!-- Tooltips (Rendered last to stay on top) -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set ySys = 280 - (systolic[i] / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: pointer;">
<circle cx="{{ x }}" cy="{{ ySys }}" r="15" fill="transparent" />
<circle cx="{{ x }}" cy="{{ ySys }}" r="7" fill="#ffffff" stroke="#3b82f6" stroke-width="2.5"
class="svg-tooltip-content" />
<g class="svg-tooltip-content">
<rect x="{{ x - 64 }}" y="{{ ySys - 54 }}" width="128" height="40" fill="#1f2937" rx="6" />
<polygon points="{{ x - 6 }},{{ ySys - 14 }} {{ x + 6 }},{{ ySys - 14 }} {{ x }},{{ ySys - 6 }}"
fill="#1f2937" />
<text x="{{ x }}" y="{{ ySys - 36 }}" font-size="11" fill="#f3f4f6" text-anchor="middle"
font-weight="600" class="font-sans">{{ timestamps[i] }}</text>
<text x="{{ x }}" y="{{ ySys - 22 }}" font-size="11" fill="#93c5fd" text-anchor="middle"
font-weight="500" class="font-sans">Systolic: {{ systolic[i] }}</text>
</g>
</g>
{% set yDia = 280 - (diastolic[i] / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: pointer;">
<circle cx="{{ x }}" cy="{{ yDia }}" r="15" fill="transparent" />
<circle cx="{{ x }}" cy="{{ yDia }}" r="7" fill="#ffffff" stroke="#ec4899" stroke-width="2.5"
class="svg-tooltip-content" />
<g class="svg-tooltip-content">
<rect x="{{ x - 64 }}" y="{{ yDia - 54 }}" width="128" height="40" fill="#1f2937" rx="6" />
<polygon points="{{ x - 6 }},{{ yDia - 14 }} {{ x + 6 }},{{ yDia - 14 }} {{ x }},{{ yDia - 6 }}"
fill="#1f2937" />
<text x="{{ x }}" y="{{ yDia - 36 }}" font-size="11" fill="#f3f4f6" text-anchor="middle"
font-weight="600" class="font-sans">{{ timestamps[i] }}</text>
<text x="{{ x }}" y="{{ yDia - 22 }}" font-size="11" fill="#f472b6" text-anchor="middle"
font-weight="500" class="font-sans">Diastolic: {{ diastolic[i] }}</text>
</g>
</g>
{% endfor %}
<!-- Average Lines -->
{% set ySysAvg = 280 - (sys_avg / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: default;">
<line x1="50" y1="{{ ySysAvg }}" x2="750" y2="{{ ySysAvg }}" stroke="#3b82f6" stroke-width="2"
stroke-dasharray="8 6" opacity="0.8" />
<line x1="50" y1="{{ ySysAvg }}" x2="750" y2="{{ ySysAvg }}" stroke="transparent"
stroke-width="15" /> <!-- Invisible hover anchor -->
<g class="svg-tooltip-content">
<rect x="336" y="{{ ySysAvg - 34 }}" width="128" height="26" fill="#1f2937" rx="6" />
<polygon points="394,{{ ySysAvg - 8 }} 406,{{ ySysAvg - 8 }} 400,{{ ySysAvg - 2 }}"
fill="#1f2937" />
<text x="400" y="{{ ySysAvg - 17 }}" font-size="11" fill="#93c5fd" text-anchor="middle"
font-weight="600" class="font-sans">Avg Systolic: {{ sys_avg }}</text>
</g>
</g>
{% set yDiaAvg = 280 - (dia_avg / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: default;">
<line x1="50" y1="{{ yDiaAvg }}" x2="750" y2="{{ yDiaAvg }}" stroke="#ec4899" stroke-width="2"
stroke-dasharray="8 6" opacity="0.8" />
<line x1="50" y1="{{ yDiaAvg }}" x2="750" y2="{{ yDiaAvg }}" stroke="transparent"
stroke-width="15" /> <!-- Invisible hover anchor -->
<g class="svg-tooltip-content">
<rect x="336" y="{{ yDiaAvg - 34 }}" width="128" height="26" fill="#1f2937" rx="6" />
<polygon points="394,{{ yDiaAvg - 8 }} 406,{{ yDiaAvg - 8 }} 400,{{ yDiaAvg - 2 }}"
fill="#1f2937" />
<text x="400" y="{{ yDiaAvg - 17 }}" font-size="11" fill="#f472b6" text-anchor="middle"
font-weight="600" class="font-sans">Avg Diastolic: {{ dia_avg }}</text>
</g>
</g>
{% else %}
<rect x="50" y="30" width="700" height="250" fill="#f9fafb" rx="10" />
<text x="400" y="155" font-size="16" fill="#9ca3af" text-anchor="middle" font-weight="500">No data
available for the selected period.</text>
{% endif %}
</svg>
</div>
</div>
<!-- Heart Rate Graph Card -->
<div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 transition-all hover:shadow-xl">
<div class="flex flex-col md:flex-row md:items-center justify-between mb-6">
<div>
<h3 class="text-xl font-bold text-gray-800">Heart Rate</h3>
<p class="text-sm text-gray-500 mt-1">Beats per minute over time (bpm)</p>
</div>
<div class="flex space-x-6 text-sm mt-4 md:mt-0 bg-gray-50 px-4 py-2 rounded-full">
<div class="flex items-center"><span
class="w-3 h-3 rounded-full bg-emerald-500 mr-2 shadow-sm"></span><span
class="font-medium text-gray-700">Heart Rate</span></div>
</div>
</div>
<div class="w-full overflow-x-auto pb-4">
<svg viewBox="0 0 800 350" class="w-full min-w-[600px] h-auto drop-shadow-sm font-sans"
style="max-height: 350px;">
<defs>
<linearGradient id="hrGrad" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="#10b981" stop-opacity="0.3" />
<stop offset="100%" stop-color="#10b981" stop-opacity="0.0" />
</linearGradient>
</defs>
{% if timestamps %}
{% set n = timestamps|length %}
{% set spacing = 700 / (n - 1) if n > 1 else 0 %}
<!-- Horizontal Grid Lines & Y-Axis Labels -->
{% for value in range(50, 201, 50) %}
{% set y = 280 - (value / 200 * 250) %}
<line x1="50" y1="{{ y }}" x2="750" y2="{{ y }}" stroke="#e5e7eb" stroke-width="1"
stroke-dasharray="4 4" />
<text x="40" y="{{ y + 4 }}" font-size="12" fill="#9ca3af" text-anchor="end" font-weight="500">{{ value
}}</text>
{% endfor %}
<!-- X-Axis Base Line -->
<line x1="50" y1="280" x2="750" y2="280" stroke="#d1d5db" stroke-width="1" />
<!-- X-Axis Labels -->
{% set ns = namespace(last_x=-100) %}
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set is_last = (i == n - 1) %}
{% if x - ns.last_x > 45 or is_last %}
{% if not is_last or x - ns.last_x > 40 or ns.last_x == -100 %}
<text x="{{ x }}" y="310" font-size="11" fill="#6b7280" text-anchor="middle" font-weight="500"
transform="rotate(-25 {{ x }} 310)">{{
timestamps[i] }}</text>
{% set ns.last_x = x %}
{% endif %}
{% endif %}
{% endfor %}
<!-- Heart Rate Filled Area -->
<polygon fill="url(#hrGrad)" points="{% if n>1 %}50{% else %}400{% endif %},280
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (heart_rate[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}
{% if n>1 %}{{ 50 + (n - 1) * spacing }}{% else %}400{% endif %},280" />
<!-- Heart Rate Line -->
<polyline fill="none" stroke="#10b981" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"
points="{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (heart_rate[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}" />
<!-- Heart Rate Points -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (heart_rate[i] / 200 * 250) %}
<circle cx="{{ x }}" cy="{{ y }}" r="5" fill="#ffffff" stroke="#10b981" stroke-width="2.5"></circle>
{% endfor %}
<!-- Tooltips (Rendered last to stay on top) -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set yHR = 280 - (heart_rate[i] / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: pointer;">
<circle cx="{{ x }}" cy="{{ yHR }}" r="15" fill="transparent" />
<circle cx="{{ x }}" cy="{{ yHR }}" r="7" fill="#ffffff" stroke="#10b981" stroke-width="2.5"
class="svg-tooltip-content" />
<g class="svg-tooltip-content">
<rect x="{{ x - 64 }}" y="{{ yHR - 54 }}" width="128" height="40" fill="#1f2937" rx="6" />
<polygon points="{{ x - 6 }},{{ yHR - 14 }} {{ x + 6 }},{{ yHR - 14 }} {{ x }},{{ yHR - 6 }}"
fill="#1f2937" />
<text x="{{ x }}" y="{{ yHR - 36 }}" font-size="11" fill="#f3f4f6" text-anchor="middle"
font-weight="600" class="font-sans">{{ timestamps[i] }}</text>
<text x="{{ x }}" y="{{ yHR - 22 }}" font-size="11" fill="#34d399" text-anchor="middle"
font-weight="500" class="font-sans">Heart Rate: {{ heart_rate[i] }}</text>
</g>
</g>
{% endfor %}
<!-- Average Line -->
{% set yHrAvg = 280 - (hr_avg / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: default;">
<line x1="50" y1="{{ yHrAvg }}" x2="750" y2="{{ yHrAvg }}" stroke="#10b981" stroke-width="2"
stroke-dasharray="8 6" opacity="0.8" />
<line x1="50" y1="{{ yHrAvg }}" x2="750" y2="{{ yHrAvg }}" stroke="transparent" stroke-width="15" />
<!-- Invisible hover anchor -->
<g class="svg-tooltip-content">
<rect x="336" y="{{ yHrAvg - 34 }}" width="128" height="26" fill="#1f2937" rx="6" />
<polygon points="394,{{ yHrAvg - 8 }} 406,{{ yHrAvg - 8 }} 400,{{ yHrAvg - 2 }}"
fill="#1f2937" />
<text x="400" y="{{ yHrAvg - 17 }}" font-size="11" fill="#34d399" text-anchor="middle"
font-weight="600" class="font-sans">Avg Heart Rate: {{ hr_avg }}</text>
</g>
</g>
{% else %}
<rect x="50" y="30" width="700" height="250" fill="#f9fafb" rx="10" />
<text x="400" y="155" font-size="16" fill="#9ca3af" text-anchor="middle" font-weight="500">No data
available for the selected period.</text>
{% endif %}
</svg>
</div>
</div>
</div>

View File

@@ -0,0 +1,79 @@
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<defs>
<path id="icon-clock" stroke-linecap="round" stroke-linejoin="round"
d="M12 8v4l3 3m9-3a9 9 0 1 1-18 0 9 9 0 0 1 18 0z" />
<path id="icon-chevron" stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</defs>
</svg>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
{% for reading in readings %}
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="bg-white shadow-sm hover:shadow-md rounded-xl p-3 flex justify-between items-center border border-gray-100 transition-all">
<!-- Left side: Timestamp & BP -->
<div>
<div class="flex items-center text-gray-400 text-xs mb-1">
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor" stroke-width="2">
<use href="#icon-clock"></use>
</svg>
<span title="{{ reading.local_timestamp.strftime('%d %b %Y, %I:%M %p') }}">
{{ reading.relative_timestamp }}
</span>
</div>
<div class="flex items-baseline">
<span class="text-xl font-bold text-gray-800">{{ reading.systolic }}<span
class="text-gray-400 font-normal mx-0.5">/</span>{{ reading.diastolic }}</span>
<span class="text-xs text-gray-500 ml-1">mmHg</span>
</div>
</div>
<!-- Right side: Heart Rate & Icon -->
<div class="flex items-center space-x-4">
<div class="text-right">
<span class="text-xs text-gray-500 block mb-0.5">HR</span>
<div class="flex items-baseline justify-end">
<span class="text-lg font-bold text-gray-700">{{ reading.heart_rate }}</span>
<span class="text-xs text-gray-400 ml-1">bpm</span>
</div>
</div>
<div class="text-gray-300">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
stroke="currentColor" class="h-4 w-4">
<use href="#icon-chevron"></use>
</svg>
</div>
</div>
</a>
{% else %}
<div class="col-span-full text-center text-sm text-gray-500">
No readings found.
</div>
{% endfor %}
</div>
<!-- Pagination Controls -->
{% if pagination.pages > 1 %}
<div class="flex justify-center items-center gap-2 mt-6">
{% if pagination.has_prev %}
<button hx-get="{{ url_for('main.dashboard_list', page=pagination.prev_num) }}" hx-target="#dashboard-content"
class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">&laquo; Prev</button>
{% endif %}
{% for page_num in pagination.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
{% if page_num %}
<button hx-get="{{ url_for('main.dashboard_list', page=page_num) }}" hx-target="#dashboard-content"
class="px-3 py-1 rounded text-sm {% if page_num == pagination.page %}bg-primary-600 text-white{% else %}bg-gray-200 hover:bg-gray-300{% endif %}">
{{ page_num }}
</button>
{% else %}
<span class="text-gray-400"></span>
{% endif %}
{% endfor %}
{% if pagination.has_next %}
<button hx-get="{{ url_for('main.dashboard_list', page=pagination.next_num) }}" hx-target="#dashboard-content"
class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">Next &raquo;</button>
{% endif %}
</div>
{% endif %}

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

@@ -0,0 +1,88 @@
<div class="flex flex-col px-2 py-2 -mb-px">
<!-- Monthly Navigation -->
<div class="flex justify-between items-center mb-4 px-2 mt-2">
<button hx-get="{{ url_for('main.dashboard_monthly', month_offset=month_offset - 1) }}"
hx-target="#dashboard-content"
class="flex items-center text-primary-600 hover:text-primary-800 font-medium transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
Previous Month
</button>
<h2 class="text-xl font-bold text-gray-800">{{ target_month_date.strftime('%B %Y') }}</h2>
<button hx-get="{{ url_for('main.dashboard_monthly', month_offset=month_offset + 1) }}"
hx-target="#dashboard-content"
class="flex items-center text-primary-600 hover:text-primary-800 font-medium transition-colors {% if month_offset >= 0 %}opacity-50 pointer-events-none{% endif %}">
Next Month
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 ml-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
<div class="grid grid-cols-7 pl-2 pr-2">
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Sunday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Sun</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Monday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Mon</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Tuesday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Tue</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Wednesday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Wed</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Thursday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Thu</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Friday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Fri</span>
</div>
<div class="p-2 h-10 text-center font-bold">
<span class="xl:block lg:block md:block sm:block hidden">Saturday</span>
<span class="xl:hidden lg:hidden md:hidden sm:hidden block">Sat</span>
</div>
</div>
<div class="grid grid-cols-7 overflow-hidden flex-1 pl-2 pr-2 w-full">
{% for day in month %}
<div
class="{% if day.is_today %}border-2 border-primary-400 bg-primary-50{% else %}border bg-white{% endif %} flex flex-col min-h-[120px] p-1.5 transition-colors {% if not day.is_in_current_month %}bg-gray-50 opacity-50{% endif %}">
<div class="text-right w-full mb-1">
<span
class="text-xs font-semibold {% if day.is_today %}text-primary-600{% else %}text-gray-500{% endif %}">{{
day.day }}</span>
</div>
<div class="space-y-1 flex-grow">
{% for reading in day.readings %}
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="flex flex-col xl:flex-row justify-between items-center px-1 py-1 bg-white border border-gray-100 rounded shadow-sm hover:border-primary-300 hover:bg-primary-50 transition-colors">
<span class="text-[10px] sm:text-xs font-bold text-gray-800 leading-none mb-0.5 xl:mb-0">{{
reading.systolic }}/{{ reading.diastolic }}</span>
<div class="flex items-center gap-0.5">
<span
class="text-[9px] sm:text-[10px] font-medium bg-red-50 text-red-600 px-1 rounded leading-none py-0.5"
title="Heart Rate">{{ reading.heart_rate }}</span>
</div>
</a>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>

View File

@@ -0,0 +1,172 @@
<div class="space-y-6">
<!-- Table Date Filter -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-2">
<form hx-get="{{ url_for('main.dashboard_table') }}" hx-target="#dashboard-content"
class="flex flex-col sm:flex-row gap-4">
<!-- Start Date -->
<div class="flex-1">
<label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
<input type="date" name="start_date" id="start_date" value="{{ start_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
<!-- End Date -->
<div class="flex-1">
<label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">End Date</label>
<input type="date" name="end_date" id="end_date" value="{{ end_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
</form>
</div>
<!-- Data Container -->
<div class="bg-transparent md:bg-white md:rounded-2xl md:shadow-sm md:border md:border-gray-100 overflow-hidden">
<!-- Mobile Card View (Hidden on medium screens and up) -->
<div class="md:hidden space-y-4">
{% for reading in readings %}
<div class="bg-white p-4 rounded-xl shadow-sm border border-gray-100 flex flex-col gap-3">
<div class="flex justify-between items-center border-b border-gray-50 pb-2">
<div class="flex items-center gap-2">
<svg class="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span class="text-sm font-bold text-gray-800">{{ reading.local_timestamp.strftime('%Y-%m-%d')
}}</span>
</div>
<span class="text-sm font-medium text-gray-500">{{ reading.local_timestamp.strftime('%I:%M %p')
}}</span>
</div>
<div class="flex justify-between items-center">
<span class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Blood Pressure</span>
<div class="flex items-baseline gap-1">
<span
class="font-bold text-lg {{ 'text-red-500' if reading.systolic >= 130 else 'text-gray-900' }}">{{
reading.systolic }}</span>
<span class="font-medium text-gray-400">/</span>
<span
class="font-bold text-lg {{ 'text-red-500' if reading.diastolic >= 80 else 'text-gray-900' }}">{{
reading.diastolic }}</span>
<span class="text-xs text-gray-500 font-medium ml-1">mmHg</span>
</div>
</div>
<div class="flex justify-between items-center">
<span class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Heart Rate</span>
<div class="flex items-baseline">
<span class="font-bold text-lg text-gray-900">{{ reading.heart_rate }}</span>
<span class="text-xs text-gray-500 font-medium ml-1">bpm</span>
</div>
</div>
<div class="flex justify-end pt-3 mt-1 border-t border-gray-50">
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="inline-flex items-center gap-1 text-primary-600 hover:text-primary-800 text-sm font-bold transition-colors">
Edit
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</a>
</div>
</div>
{% else %}
<div
class="bg-white p-8 text-center rounded-xl shadow-sm border border-gray-100 flex flex-col items-center gap-3">
<svg class="w-12 h-12 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
</svg>
<span class="text-sm font-medium text-gray-500">No readings found for this date range.</span>
</div>
{% endfor %}
</div>
<!-- Desktop Table View (Hidden on small screens) -->
<div class="hidden md:block overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Date</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Time</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Systolic</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Diastolic</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Heart Rate</th>
<th scope="col"
class="px-6 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">
Actions</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
{% for reading in readings %}
<tr class="hover:bg-gray-50 transition-colors">
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{
reading.local_timestamp.strftime('%Y-%m-%d') }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{
reading.local_timestamp.strftime('%I:%M %p') }}</td>
<td
class="px-6 py-4 whitespace-nowrap text-sm font-semibold {{ 'text-red-500' if reading.systolic >= 130 else 'text-gray-900' }}">
{{ reading.systolic }}</td>
<td
class="px-6 py-4 whitespace-nowrap text-sm font-semibold {{ 'text-red-500' if reading.diastolic >= 80 else 'text-gray-900' }}">
{{ reading.diastolic }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reading.heart_rate }} bpm</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="text-primary-600 hover:text-primary-900">Edit</a>
</td>
</tr>
{% else %}
<tr>
<td colspan="6" class="px-6 py-12 text-center text-sm text-gray-500">
No readings found for this date range.
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!-- Pagination Controls -->
{% if pagination.pages > 1 %}
<div class="flex justify-center items-center gap-2 mt-6">
{% if pagination.has_prev %}
<button
hx-get="{{ url_for('main.dashboard_table', page=pagination.prev_num, start_date=start_date, end_date=end_date) }}"
hx-target="#dashboard-content" class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">&laquo;
Prev</button>
{% endif %}
{% for page_num in pagination.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
{% if page_num %}
<button hx-get="{{ url_for('main.dashboard_table', page=page_num, start_date=start_date, end_date=end_date) }}"
hx-target="#dashboard-content"
class="px-3 py-1 rounded text-sm {% if page_num == pagination.page %}bg-primary-600 text-white{% else %}bg-gray-200 hover:bg-gray-300{% endif %}">
{{ page_num }}
</button>
{% else %}
<span class="text-gray-400"></span>
{% endif %}
{% endfor %}
{% if pagination.has_next %}
<button
hx-get="{{ url_for('main.dashboard_table', page=pagination.next_num, start_date=start_date, end_date=end_date) }}"
hx-target="#dashboard-content" class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">Next
&raquo;</button>
{% endif %}
</div>
{% endif %}
</div>

View File

@@ -0,0 +1,56 @@
<div>
<!-- Weekly Navigation -->
<div class="flex justify-between items-center mb-4 px-2">
<button hx-get="{{ url_for('main.dashboard_weekly', week_offset=week_offset - 1) }}"
hx-target="#dashboard-content"
class="flex items-center text-primary-600 hover:text-primary-800 font-medium transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
Previous Week
</button>
<span class="text-gray-600 font-semibold {% if week_offset == 0 %}text-primary-600{% endif %}">
{% if week_offset == 0 %}This Week{% elif week_offset == -1 %}Last Week{% elif week_offset == 1 %}Next
Week{% else %}{{ week_offset|abs }} weeks {% if week_offset < 0 %}ago{% else %}from now{% endif %}{% endif
%} </span>
<button hx-get="{{ url_for('main.dashboard_weekly', week_offset=week_offset + 1) }}"
hx-target="#dashboard-content"
class="flex items-center text-primary-600 hover:text-primary-800 font-medium transition-colors {% if week_offset >= 0 %}opacity-50 pointer-events-none{% endif %}">
Next Week
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 ml-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
<div class="grid grid-cols-7 text-center">
{% for day in week %}
<div class="border p-2 bg-gray-50 flex flex-col min-h-[140px]">
<div class="text-sm font-bold text-gray-500 mb-2">{{ day.date }}</div>
{% if day.readings %}
<div class="space-y-1.5 flex-grow">
{% for reading in day.readings %}
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="flex flex-col 2xl:flex-row justify-between items-center px-1.5 py-1 bg-white border border-gray-200 rounded shadow-sm hover:border-primary-400 hover:bg-primary-50 transition-colors">
<span class="text-xs font-bold text-gray-800">{{ reading.systolic }}/{{ reading.diastolic
}}</span>
<div class="flex items-center gap-1 2xl:mt-0 mt-0.5">
<span class="text-[10px] font-medium bg-red-50 text-red-600 px-1 rounded" title="Heart Rate">{{
reading.heart_rate }}</span>
<span class="text-[10px] text-gray-400 font-medium whitespace-nowrap">{{
reading.local_timestamp.strftime('%H:%M') }}</span>
</div>
</a>
{% endfor %}
</div>
{% else %}
<div class="flex-grow"></div> <!-- Spacer -->
{% endif %}
</div>
{% endfor %}
</div>
</div>

View File

@@ -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-32 h-32 rounded-full border object-cover shadow">
</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 ###

77
package-lock.json generated
View File

@@ -8,10 +8,14 @@
"name": "bloodpressure",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"tailwindcss": "^3.0.0"
},
"devDependencies": {
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17"
"tailwindcss": "^3.4.17",
"terser": "^5.46.0"
}
},
"node_modules/@alloc/quick-lru": {
@@ -75,6 +79,16 @@
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/source-map": {
"version": "0.3.11",
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",
"integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",
"dev": true,
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.25"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz",
@@ -136,6 +150,18 @@
"node": ">=14"
}
},
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"dev": true,
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/ansi-regex": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz",
@@ -293,6 +319,12 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"dev": true
},
"node_modules/camelcase-css": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -1175,6 +1207,15 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -1184,6 +1225,16 @@
"node": ">=0.10.0"
}
},
"node_modules/source-map-support": {
"version": "0.5.21",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
"dev": true,
"dependencies": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
}
},
"node_modules/string-width": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
@@ -1351,6 +1402,30 @@
"node": ">=14.0.0"
}
},
"node_modules/terser": {
"version": "5.46.0",
"resolved": "https://registry.npmjs.org/terser/-/terser-5.46.0.tgz",
"integrity": "sha512-jTwoImyr/QbOWFFso3YoU3ik0jBBDJ6JTOQiy/J2YxVJdZCc+5u7skhNwiOR3FQIygFqVUPHl7qbbxtjW2K3Qg==",
"dev": true,
"dependencies": {
"@jridgewell/source-map": "^0.3.3",
"acorn": "^8.15.0",
"commander": "^2.20.0",
"source-map-support": "~0.5.20"
},
"bin": {
"terser": "bin/terser"
},
"engines": {
"node": ">=10"
}
},
"node_modules/terser/node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
"dev": true
},
"node_modules/thenify": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",

View File

@@ -4,8 +4,8 @@
"description": "",
"main": "index.js",
"scripts": {
"build": "npx tailwindcss -o ./app/static/css/tailwind.css --minify",
"serve": "npx tailwindcss -o ./app/static/css/tailwind.css --watch"
"build": "npx tailwindcss -o ./app/static/css/tailwind.css --minify && npx terser ./app/static/js/diy-turbo.js -o ./app/static/js/diy-turbo.min.js -c -m",
"serve": "npx tailwindcss -o ./app/static/css/tailwind.css --minify --watch"
},
"author": "",
"license": "ISC",
@@ -15,6 +15,7 @@
"devDependencies": {
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17"
"tailwindcss": "^3.4.17",
"terser": "^5.46.0"
}
}

View File

@@ -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
@@ -36,3 +37,5 @@ typing-extensions==4.12.2
werkzeug==3.1.3
wtforms==3.2.1
zipp==3.21.0
Flask-Minify==0.43
Brotli==1.2.0

View File

@@ -3,9 +3,6 @@ module.exports = {
content: ["./app/templates/**/*.html"],
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
colors: {
primary: {
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)
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