Start refactoring person overview (list) page, currently is accessible through tags and workout exercise select. Doesnt have any stats or graphs

This commit is contained in:
Peter Stockings
2025-01-26 18:21:44 +11:00
parent 76b610c949
commit b0fb8895df
8 changed files with 371 additions and 136 deletions

47
app.py
View File

@@ -119,6 +119,40 @@ def get_person(person_id):
return render_template('person.html', person=person, selected_exercise_ids=selected_exercise_ids, max_date=max_date, min_date=min_date, tags=tags), 200, {"HX-Trigger": "updatedPeople"}
@ app.route("/person/<int:person_id>/workout/overview", methods=['GET'])
def person_overview(person_id):
min_date = request.args.get('min_date', type=convert_str_to_date)
max_date = request.args.get('max_date', type=convert_str_to_date)
selected_exercise_ids = request.args.getlist('exercise_id', type=int)
if not min_date or not max_date:
db_min_date, db_max_date = db.person_overview.get_earliest_and_latest_workout_dates(person_id)
min_date = min_date or db_min_date
max_date = max_date or db_max_date
if not selected_exercise_ids and htmx.trigger_name != 'exercise_id':
selected_exercise_ids = db.person_overview.list_of_performed_exercise_ids(person_id, min_date, max_date)
person = db.person_overview.get(person_id, min_date, max_date, selected_exercise_ids)
exercises = db.person_overview.get_exercises_with_selection(person_id, min_date, max_date, selected_exercise_ids)
tags = db.get_tags_for_person(person_id)
# Render the appropriate response for HTMX or full page
render_args = {
**person,
"exercises": exercises,
"tags": tags,
"selected_exercise_ids": selected_exercise_ids,
"max_date": max_date,
"min_date": min_date
}
if htmx:
return render_block(app.jinja_env, 'person_overview.html', 'content', **render_args), 200, {"HX-Trigger": "updatedPeople"}
return render_template('person_overview.html', **render_args), 200, {"HX-Trigger": "updatedPeople"}
@ app.route("/person/<int:person_id>/calendar")
@ validate_person
@@ -146,17 +180,6 @@ def get_person_notes(person_id):
return render_block(app.jinja_env, 'notes.html', 'content', person_id=person_id, person_name=person_name, workout_notes=workout_notes)
return render_template('notes.html', person_id=person_id, person_name=person_name, workout_notes=workout_notes)
@ app.route("/person/<int:person_id>/workout/<int:workout_id>/modal", methods=['GET'])
@ validate_workout
def get_workout_modal(person_id, workout_id):
workout = db.get_workout(person_id, workout_id)
(person_tags, workout_tags, selected_workout_tag_ids) = db.get_workout_tags(
person_id, workout_id)
exercises = db.get_all_exercises()
return render_template('partials/workout_modal.html', **workout, person_tags=person_tags, workout_tags=workout_tags, selected_workout_tag_ids=selected_workout_tag_ids, exercises=exercises)
@ app.route("/person/<int:person_id>/workout", methods=['POST'])
def create_workout(person_id):
new_workout_id = db.create_workout(person_id)
@@ -324,7 +347,7 @@ def goto_tag():
person_id = request.args.get("person_id")
tag_filter = request.args.get('filter')
if person_id:
return redirect(url_for('get_person', person_id=int(person_id)) + tag_filter)
return redirect(url_for('person_overview', person_id=int(person_id)) + tag_filter)
return redirect(url_for('dashboard') + tag_filter)

3
db.py
View File

@@ -9,6 +9,7 @@ from flask import g
import pandas as pd
from features.calendar import Calendar
from features.exercises import Exercises
from features.person_overview import PersonOverview
from features.stats import Stats
from features.workout import Workout
from features.sql_explorer import SQLExplorer
@@ -22,6 +23,7 @@ class DataBase():
self.workout = Workout(self.execute)
self.exercises = Exercises(self.execute)
self.sql_explorer = SQLExplorer(self.execute)
self.person_overview = PersonOverview(self.execute)
db_url = urlparse(os.environ['DATABASE_URL'])
# if db_url is null then throw error
if not db_url:
@@ -578,7 +580,6 @@ class DataBase():
workout_notes_list = list(workout_notes.values())
return person_name, workout_notes_list
def get_exercise_earliest_and_latest_dates(self, person_id, exercise_id):
sql_query = """
SELECT

164
features/person_overview.py Normal file
View File

@@ -0,0 +1,164 @@
class PersonOverview:
def __init__(self, db_connection_method):
self.execute = db_connection_method
def get_earliest_and_latest_workout_dates(self, person_id):
sql_query = """
SELECT
MIN(w.start_date) AS earliest_date,
MAX(w.start_date) AS latest_date
FROM workout w
INNER JOIN topset t ON w.workout_id = t.workout_id
WHERE w.person_id = %s;
"""
result = self.execute(sql_query, [person_id])
if not result or not result[0]:
return None, None
return result[0]['earliest_date'], result[0]['latest_date']
def list_of_performed_exercise_ids(self, person_id, min_date, max_date):
sql_query = """
SELECT
ARRAY_AGG(DISTINCT e.exercise_id) AS exercise_ids
FROM workout w
LEFT JOIN topset t ON w.workout_id = t.workout_id
LEFT JOIN exercise e ON t.exercise_id = e.exercise_id
WHERE w.start_date BETWEEN %s AND %s
AND w.person_id = %s
"""
result = self.execute(sql_query, [min_date, max_date, person_id])
if not result or not result[0]:
return []
return result[0]['exercise_ids']
def get_exercises_with_selection(self, person_id, start_date, end_date, selected_exercise_ids):
# SQL query to fetch all exercises performed by the person in the given time range
sql_query = """
SELECT DISTINCT
e.exercise_id,
e.name AS exercise_name
FROM
workout w
JOIN
topset t ON w.workout_id = t.workout_id
JOIN
exercise e ON t.exercise_id = e.exercise_id
WHERE
w.person_id = %s
AND w.start_date BETWEEN %s AND %s
ORDER BY
e.name ASC;
"""
# Execute the query with parameters
result = self.execute(sql_query, [person_id, start_date, end_date])
if not result:
return [] # No exercises found in the given time range
# Add the "selected" property to each exercise
exercises = []
for row in result:
exercises.append({
"id": row["exercise_id"],
"name": row["exercise_name"],
"selected": row["exercise_id"] in selected_exercise_ids
})
return exercises
def get(self, person_id, start_date, end_date, selected_exercise_ids):
# Build placeholders for exercise IDs
placeholders = ", ".join(["%s"] * len(selected_exercise_ids))
# Dynamically inject placeholders into the query
sql_query = f"""
SELECT
p.person_id,
p.name AS person_name,
w.workout_id,
w.start_date,
w.note AS workout_note,
e.exercise_id,
e.name AS exercise_name,
t.topset_id,
t.repetitions,
t.weight
FROM
person p
JOIN
workout w ON p.person_id = w.person_id
JOIN
topset t ON w.workout_id = t.workout_id
JOIN
exercise e ON t.exercise_id = e.exercise_id
WHERE
p.person_id = %s
AND w.start_date BETWEEN %s AND %s
AND e.exercise_id IN ({placeholders})
ORDER BY
w.start_date DESC, e.exercise_id ASC, t.topset_id ASC;
"""
# Add parameters for the query
params = [person_id, start_date, end_date] + selected_exercise_ids
result = self.execute(sql_query, params)
if not result:
return {"person_id": person_id, "person_name": None, "workouts": [], "selected_exercises": []}
# Extract person info from the first row
person_info = {"person_id": result[0]["person_id"], "person_name": result[0]["person_name"]}
# Extract and sort all unique exercises by name
exercises = []
unique_exercise_ids = set()
for row in result:
if row["exercise_id"] not in unique_exercise_ids:
unique_exercise_ids.add(row["exercise_id"])
exercises.append({"id": row["exercise_id"], "name": row["exercise_name"]})
# Sort the exercises by name
exercises = sorted(exercises, key=lambda ex: ex["name"])
# Initialize the table structure
workouts = []
workout_map = {} # Map to track workouts
for row in result:
workout_id = row["workout_id"]
# Initialize the workout if not already present
if workout_id not in workout_map:
workout_map[workout_id] = {
"id": workout_id,
"start_date": row["start_date"],
"note": row["workout_note"],
"exercises": {exercise["id"]: [] for exercise in exercises} # Keyed by exercise_id
}
# Add topset to the corresponding exercise
if row["exercise_id"] and row["topset_id"]:
workout_map[workout_id]["exercises"][row["exercise_id"]].append({
"repetitions": row["repetitions"],
"weight": row["weight"]
})
# Transform into a list of rows
for workout_id, workout in workout_map.items():
workouts.append(workout)
return {**person_info, "workouts": workouts, "selected_exercises": exercises}

View File

@@ -2,10 +2,6 @@
{% block content %}
<a hx-get="{{ url_for('get_calendar', person_id=person_id) }}" hx-target="#container"
hx-vals='{"date": "{{ date }}", "view": "{{ view }}"}' hx-trigger="refreshView" id="refreshViewElement"
hx-swap="innerHTML swap:0.5s"></a>
<div class="flex flex-grow flex-col bg-white sm:rounded shadow overflow-hidden animate-fadeIn">
<div class="flex items-center justify-between pt-2 pb-2">
<div class="flex">

View File

@@ -2,9 +2,6 @@
{% block content %}
<a hx-get="{{ url_for('get_calendar', person_id=person_id) }}" hx-target="#container" hx-vals='{"view": "notes"}'
hx-trigger="refreshView" id="refreshViewElement"></a>
<div class="flex flex-grow flex-col bg-white sm:rounded shadow overflow-hidden">
<div class="flex items-center justify-between pt-2 pb-2">
<div class="flex">
@@ -47,8 +44,8 @@
{% for workout_note in workout_notes %}
<tr class="border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
<td class="p-4 align-middle [&amp;:has([role=checkbox])]:pr-0 cursor-pointer"
hx-get="{{ url_for('get_workout_modal', person_id=person_id, workout_id=workout_note.workout_id) }}"
hx-target='body' hx-swap='beforeend'>
hx-get="{{ url_for('show_workout', person_id=person_id, workout_id=workout_note.workout_id) }}"
hx-push-url="true" hx-target="#container">
<div class="flex flex-row items-center justify-center">
<button
class="inline-flex items-center justify-center whitespace-nowrap text-sm font-medium h-10 px-2 py-1 bg-transparent text-black rounded hidden md:block"

View File

@@ -1,110 +0,0 @@
<div id='modal' _='on closeModal
add .closing
then wait for animationend
then remove me
then toggle .hide-scrollbar on document.body
then send refreshView to #refreshViewElement
on closeModalWithoutRefresh
add .closing
then wait for animationend
then remove me
then toggle .hide-scrollbar on document.body'>
<div class='modal-underlay' _='on click trigger closeModal'></div>
<div class='modal-content p-2 md:p-4 m-2 sm:mt-24 max-h-[98%]' _='init toggle .hide-scrollbar on document.body'>
<div class="relative w-full h-full max-w-2xl md:h-auto overflow-auto">
<!-- Modal content -->
<div class="relative bg-white rounded-lg shadow">
<!-- Modal header -->
<div class="flex items-start justify-between p-2 md:p-4 border-0 md:border-b rounded-t">
<div class="flex flex-col w-full">
<div class="flex items-center justify-between">
<div class="w-full">
<h3 class="text-xl font-bold text-gray-900">{{ person_name }}</h3>
{{ render_partial('partials/workout_tags.html', person_id=person_id,
workout_id=workout_id,
person_tags=person_tags, workout_tags=workout_tags,
selected_workout_tag_ids=selected_workout_tag_ids) }}
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2">
{{ render_partial('partials/start_date.html', person_id=person_id,
workout_id=workout_id,
start_date=start_date) }}
{{ render_partial('partials/workout_note.html', person_id=person_id,
workout_id=workout_id,
note=note) }}
</div>
</div>
<button type="button"
class="absolute right-0 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-600 dark:hover:text-white"
data-modal-toggle="defaultModal" _="on click trigger closeModal">
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg" data-darkreader-inline-fill=""
style="--darkreader-inline-fill:currentColor;">
<path fill-rule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clip-rule="evenodd"></path>
</svg>
<span class="sr-only">Close modal</span>
</button>
</div>
</div>
<!-- Modal body -->
<div class="p-3 md:p-6 space-y-6">
<table class="items-center w-full bg-transparent border-collapse table-fixed">
<thead>
<tr>
<th
class="px-4 bg-gray-50 text-gray-700 align-middle py-3 text-xs font-semibold text-left uppercase border-l-0 border-r-0 whitespace-nowrap">
Exercise</th>
<th
class="px-4 bg-gray-50 text-gray-700 align-middle py-3 text-xs font-semibold text-left uppercase border-l-0 border-r-0 whitespace-nowrap">
Top Set</th>
<th
class="bg-gray-50 text-gray-700 align-middle py-3 text-xs font-semibold text-left uppercase border-l-0 border-r-0 whitespace-nowrap w-9 sm:w-20">
</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100" id="new-workout" hx-target="closest tr"
hx-swap="outerHTML swap:0.5s">
{% for topset in top_sets %}
{{ render_partial('partials/topset.html', person_id=person_id,
workout_id=workout_id,
topset_id=topset.topset_id, exercise_id=topset.exercise_id, exercise_name=topset.exercise_name,
repetitions=topset.repetitions,
weight=topset.weight) }}
{% endfor %}
</tbody>
</table>
{% if top_sets|length == 0 %}
<div class="bg-purple-100 rounded-lg py-5 px-6 mb-4 text-base text-purple-700 mb-3" role="alert"
id="no-workouts">
No topsets found.
</div>
{% endif %}
</div>
<!-- Modal footer -->
<div class="flex items-center p-3 md:p-6 space-x-2 border-t border-gray-200 rounded-b dark:border-gray-600">
{{ render_partial('partials/new_set_form.html', person_id=person_id,
workout_id=workout_id,
exercises=exercises,
has_value=False) }}
</div>
<div id="exercise-progress-{{ person_id }}" class="mx-0 md:mx-5">
</div>
</div>
</div>
</div>
</div>

View File

@@ -10,10 +10,6 @@
{% endfor %}
</div>
<a hx-get="{{ url_for('get_person', person_id=person['PersonId']) }}"
hx-include="[name='exercise_id'],[name='min_date'],[name='max_date']" hx-target="#container"
hx-trigger="refreshView" id="refreshViewElement"></a>
<div class="flex max-w-full overflow-x-hidden">
<div class="bg-white shadow rounded-lg pt-2 pb-2 sm:w-full xl:p-8 md:w-full">

View File

@@ -0,0 +1,168 @@
{% extends 'base.html' %}
{% block content %}
<div class="flex max-w-full overflow-x-hidden">
<div class="bg-white shadow rounded-lg pt-2 pb-2 sm:w-full xl:p-8 md:w-full">
<div class="mb-4 flex items-center justify-between px-2 md:px-3">
<div>
<h3 class="text-xl font-bold text-gray-900 mb-2">{{ person_name }}</h3>
<span class="text-base font-normal text-gray-500">List of workouts</span>
</div>
<div>
<div>
<select name="view" hx-get="{{ url_for('get_calendar', person_id=person_id) }}"
hx-target="#container" hx-push-url="true" _="init js(me) tail.select(me, {}) end"
class="h-10 invisible">
<option value="month">Month</option>
<option value="year">Year</option>
<option value="notes">Notes</option>
<option value="all" selected>All</option>
</select>
</div>
</div>
</div>
<div class="flex flex-wrap mb-1">
<div class="w-full md:w-1/3 px-2 md:px-3 mb-6 md:mb-0">
<div class="mb-1 w-full">
<label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-city">
Exercises
</label>
<select data-te-select-filter="true" data-te-select-size="lg" name="exercise_id"
class="bg-gray-50 border border-gray-300 " multiple
hx-get="{{ url_for('person_overview', person_id=person_id) }}"
hx-include="[name='exercise_id'],[name='min_date'],[name='max_date'],[name='graph_axis']"
hx-target="#container" hx-push-url="true" _="init js(me)
tail.select(me, {
multiple: true,
search: true,
placeholder: 'Filter exercises',
})
end">
{% for exercise in exercises %}
<option value="{{ exercise.id }}" {% if exercise.selected %}selected{% endif %}>
{{ exercise.name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="w-full md:w-1/3 px-2 md:px-3 mb-6 md:mb-0">
<label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-city">
Min date
</label>
<div class="relative pr-2">
<div class="flex absolute inset-y-0 left-0 items-center pl-3 pointer-events-none">
<svg aria-hidden="true" class="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor"
viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd"
d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z"
clip-rule="evenodd"></path>
</svg>
</div>
<input type="date"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full pl-10 p-2.5 w-full"
name="min_date" value="{{ min_date }}"
hx-get="{{ url_for('person_overview', person_id=person_id) }}"
hx-include="[name='exercise_id'],[name='min_date'],[name='max_date'],[name='graph_axis']"
hx-target="#container" hx-push-url="true" hx-trigger="change">
</div>
</div>
<div class="w-full md:w-1/3 px-2 md:px-3 mb-6 md:mb-0">
<label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-zip">
Max date
</label>
<div class="relative pr-2">
<div class="flex absolute inset-y-0 left-0 items-center pl-3 pointer-events-none">
<svg aria-hidden="true" class="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor"
viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd"
d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z"
clip-rule="evenodd"></path>
</svg>
</div>
<input type="date"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full pl-10 p-2.5 w-full"
name="max_date" value="{{ max_date }}"
hx-get="{{ url_for('person_overview', person_id=person_id) }}"
hx-include="[name='exercise_id'],[name='min_date'],[name='max_date'],[name='graph_axis']"
hx-target="#container" hx-push-url="true" hx-trigger="change">
</div>
</div>
</div>
{{ render_partial('partials/tags.html',person_id=person_id, tags=tags) }}
<div class="flex flex-col mt-3 w-screen sm:w-full overflow-auto">
<div class="overflow-x-auto rounded-lg">
<div class="flex justify-center">
<div class="flex justify-center shadow sm:rounded-lg w-screen sm:w-screen">
{% if workouts|length > 0 %}
<table class="min-w-content divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col"
class="p-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Date
</th>
{% for exercise in selected_exercises %}
<th scope="col"
class="p-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{{ exercise.name }}
</th>
{% endfor %}
</tr>
</thead>
<tbody class="bg-white">
{% for workout in workouts %}
<tr hx-get="{{ url_for('show_workout', person_id=person_id, workout_id=workout.id) }}"
hx-push-url="true" hx-target="#container" class="cursor-pointer">
<td class="p-4 whitespace-nowrap text-sm font-normal text-gray-500">
{{ workout.start_date | strftime("%b %d %Y") }}
</td>
{% for exercise in selected_exercises %}
<td class="p-4 whitespace-nowrap text-sm font-semibold text-gray-900">
{% for set in workout.exercises[exercise.id] %}
{{ set.repetitions }} x {{ set.weight }}kg
{% endfor %}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% if workouts|length == 0 %}
<div class="bg-purple-100 rounded-lg py-5 px-6 mb-4 text-base text-purple-700 mb-3"
role="alert">
No workouts found.
</div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{{ render_partial('partials/stats.html', stats=stats) }}
<button
class="fixed z-90 bottom-10 right-8 bg-blue-600 w-20 h-20 rounded-full drop-shadow-lg flex justify-center items-center text-white text-4xl hover:bg-blue-700 hover:drop-shadow-2xl hover:animate-bounce duration-300"
hx-post="{{ url_for('create_workout', person_id=person_id) }}" hx-target='body' hx-swap='beforeend'>
<svg viewBox="0 0 20 20" enable-background="new 0 0 20 20" class="w-6 h-6 inline-block">
<path fill="#FFFFFF" d="M16,10c0,0.553-0.048,1-0.601,1H11v4.399C11,15.951,10.553,16,10,16c-0.553,0-1-0.049-1-0.601V11H4.601
C4.049,11,4,10.553,4,10c0-0.553,0.049-1,0.601-1H9V4.601C9,4.048,9.447,4,10,4c0.553,0,1,0.048,1,0.601V9h4.399
C15.952,9,16,9.447,16,10z" />
</svg>
</button>
{% endblock %}