Move date filter to graph view

This commit is contained in:
Peter Stockings
2026-03-13 15:11:11 +11:00
parent 6f216944bf
commit a9802f300b
5 changed files with 106 additions and 71 deletions

View File

@@ -27,21 +27,11 @@ 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 = calculate_progress_badges(current_user.id, user_tz)
# We will default to showing the list view on initial load
page = request.args.get('page', 1, type=int)
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(
'dashboard.html',
profile=current_user.profile,
@@ -49,25 +39,18 @@ 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')
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)
# 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)
@@ -120,14 +103,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)

File diff suppressed because one or more lines are too long

View File

@@ -145,6 +145,7 @@
// 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');
@@ -225,6 +226,61 @@
}
}
});
// 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>

View File

@@ -40,52 +40,7 @@
</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" value="{{ start_date or '' }}"
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" value="{{ end_date or '' }}"
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">
@@ -106,8 +61,10 @@
</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>

View File

@@ -12,6 +12,33 @@
}
</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 md:flex-row gap-4 items-end">
<!-- 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>
<!-- Apply Button -->
<div>
<button type="submit"
class="w-full md:w-auto bg-primary-600 text-white px-6 py-2.5 rounded-xl font-semibold shadow-md hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 transition-colors">
Apply Filter
</button>
</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">