Compare commits
12 Commits
dcef99c3bf
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25d1774e53 | ||
|
|
25aa7de043 | ||
|
|
f7ce1c3fd6 | ||
|
|
e2d85f0a88 | ||
|
|
910d583966 | ||
|
|
eca31040af | ||
|
|
086784b2a2 | ||
|
|
a9802f300b | ||
|
|
6f216944bf | ||
|
|
675ca02818 | ||
|
|
5b43bca7ca | ||
|
|
808143f92b |
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -27,25 +27,10 @@ def dashboard():
|
||||
"""Render the dashboard shell and default list view."""
|
||||
user_tz = timezone(current_user.profile.timezone or 'UTC')
|
||||
|
||||
# Get date range for filters
|
||||
first_reading, last_reading = get_reading_date_range(current_user.id, user_tz)
|
||||
start_date = request.form.get('start_date') or request.args.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d'))
|
||||
end_date = request.form.get('end_date') or request.args.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d'))
|
||||
|
||||
# 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)
|
||||
|
||||
# We will default to showing the list view on initial load
|
||||
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)
|
||||
badges = calculate_progress_badges(current_user.id, user_tz)
|
||||
|
||||
return render_template(
|
||||
'dashboard.html',
|
||||
@@ -54,20 +39,28 @@ def dashboard():
|
||||
systolic_avg=systolic_avg,
|
||||
diastolic_avg=diastolic_avg,
|
||||
heart_rate_avg=heart_rate_avg,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
delete_form=DeleteForm(),
|
||||
active_view='list',
|
||||
# default view context
|
||||
readings=paginated.items,
|
||||
pagination=paginated
|
||||
)
|
||||
|
||||
@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)
|
||||
@@ -75,7 +68,7 @@ def dashboard_list():
|
||||
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_list.html', readings=paginated.items, pagination=paginated)
|
||||
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
|
||||
@@ -125,14 +118,26 @@ def dashboard_monthly():
|
||||
@login_required
|
||||
def dashboard_graph():
|
||||
user_tz = timezone(current_user.profile.timezone or 'UTC')
|
||||
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)
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
@@ -240,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 = 1
|
||||
daily_streak = True
|
||||
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
|
||||
|
||||
previous_date = sorted_readings[0].timestamp.date()
|
||||
if distinct_dates:
|
||||
most_recent_date = distinct_dates[0]
|
||||
if (now_local - most_recent_date).days <= 1:
|
||||
streak_count = 1
|
||||
current_check_date = most_recent_date
|
||||
|
||||
for reading in sorted_readings[1:]:
|
||||
current_date = reading.timestamp.date()
|
||||
for d in distinct_dates[1:]:
|
||||
if (current_check_date - d).days == 1:
|
||||
streak_count += 1
|
||||
current_check_date = d
|
||||
else:
|
||||
break
|
||||
|
||||
if (current_date - previous_date).days == 1:
|
||||
streak_count += 1
|
||||
elif (current_date - previous_date).days > 1:
|
||||
daily_streak = False
|
||||
|
||||
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:]):
|
||||
badges.append("Morning Riser: Logged Readings Every Morning for a Week")
|
||||
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:]):
|
||||
badges.append("Night Owl: Logged Readings Every Night for a Week")
|
||||
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")
|
||||
|
||||
|
||||
@@ -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
68
app/static/js/diy-turbo.js
Normal file
68
app/static/js/diy-turbo.js
Normal 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
1
app/static/js/diy-turbo.min.js
vendored
Normal 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()}});
|
||||
@@ -7,6 +7,7 @@
|
||||
<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="/static/css/tailwind.css" rel="stylesheet">
|
||||
<script src="{{ url_for('static', filename='js/diy-turbo.min.js') }}"></script>
|
||||
</head>
|
||||
|
||||
<body class="bg-gray-50 text-gray-800 font-sans antialiased">
|
||||
@@ -55,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
|
||||
@@ -140,26 +129,26 @@
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Flash messages
|
||||
document.querySelectorAll('.flash-close-btn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
const el = e.target.closest('.flash-message');
|
||||
if (el) {
|
||||
el.style.opacity = '0';
|
||||
setTimeout(() => el.remove(), 300);
|
||||
}
|
||||
});
|
||||
});
|
||||
// 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
|
||||
document.body.addEventListener('click', async (e) => {
|
||||
const trigger = e.target.closest('[hx-get]');
|
||||
if (!trigger) return;
|
||||
|
||||
const htmxTrigger = e.target.closest('[hx-get]');
|
||||
if (htmxTrigger) {
|
||||
if (htmxTrigger.tagName === 'FORM') return; // Let submit handler deal with forms
|
||||
e.preventDefault();
|
||||
const url = trigger.getAttribute('hx-get');
|
||||
const targetSelector = trigger.getAttribute('hx-target');
|
||||
const url = htmxTrigger.getAttribute('hx-get');
|
||||
const targetSelector = htmxTrigger.getAttribute('hx-target');
|
||||
if (!url || !targetSelector) return;
|
||||
|
||||
const targetEl = document.querySelector(targetSelector);
|
||||
@@ -172,19 +161,20 @@
|
||||
} catch (err) {
|
||||
console.error('Micro-HTMX error:', err);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Mobile Menu
|
||||
const menuBtn = document.getElementById('mobile-menu-btn');
|
||||
const menu = document.getElementById('mobile-menu');
|
||||
const nav = document.getElementById('mobile-nav');
|
||||
const iconMenu = document.getElementById('icon-menu');
|
||||
const iconClose = document.getElementById('icon-close');
|
||||
// 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 (menuBtn && menu) {
|
||||
const toggleMenu = (forceClose = false) => {
|
||||
if (menu) {
|
||||
const isHidden = menu.classList.contains('hidden');
|
||||
if (!isHidden || forceClose) {
|
||||
if (!isHidden) {
|
||||
menu.classList.add('hidden');
|
||||
nav.classList.replace('bg-primary-900', 'bg-primary-800');
|
||||
iconMenu.classList.remove('hidden');
|
||||
@@ -197,17 +187,108 @@
|
||||
iconClose.classList.remove('hidden');
|
||||
menuBtn.classList.add('rotate-180', 'transform');
|
||||
}
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
menuBtn.addEventListener('click', () => toggleMenu());
|
||||
document.addEventListener('click', (e) => {
|
||||
if (!nav.contains(e.target) && !menu.classList.contains('hidden')) toggleMenu(true);
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && !menu.classList.contains('hidden')) toggleMenu(true);
|
||||
});
|
||||
// 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>
|
||||
|
||||
|
||||
@@ -40,112 +40,75 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="relative">
|
||||
<!-- Compact Icon -->
|
||||
<button id="filter-btn"
|
||||
class="bg-primary-600 text-white p-3 rounded-full shadow-lg focus:outline-none hover:bg-primary-700 transition">
|
||||
<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">
|
||||
<!-- Chevron down icon (default) -->
|
||||
<path id="filter-icon-closed" class="{{ 'hidden' if request.method == 'POST' else '' }}"
|
||||
stroke-linecap="round" stroke-linejoin="round" d="M6 9l6 6 6-6" />
|
||||
<!-- X icon -->
|
||||
<path id="filter-icon-open" class="{{ '' if request.method == 'POST' else 'hidden' }}"
|
||||
stroke-linecap="round" stroke-linejoin="round" d="M18 15l-6-6-6 6" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Collapsible Filter Form -->
|
||||
<div id="filter-form"
|
||||
class="{{ '' if request.method == 'POST' else 'hidden' }} transition-all duration-300 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">
|
||||
<!-- Tabs -->
|
||||
<div class="flex border-b mb-4" id="dashboard-tabs">
|
||||
<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 {{ 'border-primary-600 text-primary-600' if active_view == 'list' else '' }}">List
|
||||
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 {{ 'border-primary-600 text-primary-600' if active_view == 'weekly' else '' }}">Weekly
|
||||
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 {{ 'border-primary-600 text-primary-600' if active_view == 'monthly' else '' }}">Monthly
|
||||
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 {{ 'border-primary-600 text-primary-600' if active_view == 'graph' else '' }}">Graph
|
||||
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>
|
||||
|
||||
<!-- Dashboard Content Target Area for HTMX -->
|
||||
<div id="dashboard-content">
|
||||
{% include 'partials/dashboard_list.html' %}
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Use event delegation for dashboard interactions to survive DIY Turbo page replacements
|
||||
document.addEventListener('click', (e) => {
|
||||
// Filter Form Toggle
|
||||
const filterBtn = document.getElementById('filter-btn');
|
||||
const filterForm = document.getElementById('filter-form');
|
||||
const iconClosed = document.getElementById('filter-icon-closed');
|
||||
const iconOpen = document.getElementById('filter-icon-open');
|
||||
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');
|
||||
|
||||
if (filterBtn && filterForm) {
|
||||
filterBtn.addEventListener('click', () => {
|
||||
if (filterForm) {
|
||||
const isHidden = filterForm.classList.contains('hidden');
|
||||
if (isHidden) {
|
||||
filterForm.classList.remove('hidden');
|
||||
iconClosed.classList.add('hidden');
|
||||
iconOpen.classList.remove('hidden');
|
||||
if (iconClosed) iconClosed.classList.add('hidden');
|
||||
if (iconOpen) iconOpen.classList.remove('hidden');
|
||||
} else {
|
||||
filterForm.classList.add('hidden');
|
||||
iconClosed.classList.remove('hidden');
|
||||
iconOpen.classList.add('hidden');
|
||||
if (iconClosed) iconClosed.classList.remove('hidden');
|
||||
if (iconOpen) iconOpen.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Tabs
|
||||
const tabBtns = document.querySelectorAll('.tab-btn');
|
||||
tabBtns.forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
tabBtns.forEach(b => {
|
||||
b.classList.remove('border-primary-600', 'text-primary-600');
|
||||
});
|
||||
btn.classList.add('border-primary-600', 'text-primary-600');
|
||||
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 %}
|
||||
@@ -1,64 +1,346 @@
|
||||
<div 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 -->
|
||||
<style>
|
||||
.svg-tooltip-group .svg-tooltip-content {
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.2s ease-in-out;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
<!-- 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 %}
|
||||
.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>
|
||||
|
||||
<!-- 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 %}
|
||||
<!-- 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>
|
||||
|
||||
<!-- 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 %}" />
|
||||
<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>
|
||||
|
||||
<!-- 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 %}" />
|
||||
{% if timestamps %}
|
||||
{% set n = timestamps|length %}
|
||||
{% set spacing = 700 / (n - 1) if n > 1 else 0 %}
|
||||
|
||||
<!-- 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>
|
||||
<!-- 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 -->
|
||||
<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 -->
|
||||
<!-- 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>
|
||||
|
||||
<!-- 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 %}
|
||||
<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>
|
||||
|
||||
<!-- 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 %}
|
||||
{% if timestamps %}
|
||||
{% set n = timestamps|length %}
|
||||
{% set spacing = 700 / (n - 1) if n > 1 else 0 %}
|
||||
|
||||
<!-- 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 %}" />
|
||||
<!-- 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 %}
|
||||
|
||||
<!-- 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>
|
||||
<!-- 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>
|
||||
172
app/templates/partials/dashboard_table.html
Normal file
172
app/templates/partials/dashboard_table.html
Normal 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">«
|
||||
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
|
||||
»</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -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>
|
||||
|
||||
|
||||
|
||||
@@ -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
77
package-lock.json
generated
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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