feat: assign tags to exercises and show muscle distribution of workout

This commit is contained in:
Peter Stockings
2026-01-30 23:53:04 +11:00
parent 78f4a53c49
commit d03581bff4
10 changed files with 278 additions and 60 deletions

60
app.py
View File

@@ -1,7 +1,7 @@
from datetime import date
import os
from flask import Flask, abort, render_template, redirect, request, url_for
from flask_login import LoginManager, login_required
from flask_login import LoginManager, login_required, current_user
import jinja_partials
from jinja2_fragments import render_block
from decorators import (validate_person, validate_topset, validate_workout,
@@ -200,27 +200,57 @@ def get_person_name(person_id):
@ app.route("/exercise", methods=['POST'])
def create_exercise():
name = request.form.get("name")
new_exercise_id = db.create_exercise(name)
return render_template('partials/exercise.html', exercise_id=new_exercise_id, name=name)
attribute_ids = request.form.getlist('attribute_ids')
exercise = db.create_exercise(name, attribute_ids)
return render_template('partials/exercise.html',
exercise_id=exercise['exercise_id'],
name=exercise['name'],
attributes=exercise['attributes'])
@ app.route("/exercise/<int:exercise_id>", methods=['GET'])
def get_exercise(exercise_id):
exercise = db.get_exercise(exercise_id)
return render_template('partials/exercise.html', exercise_id=exercise_id, name=exercise.name)
return render_template('partials/exercise.html',
exercise_id=exercise_id,
name=exercise['name'],
attributes=exercise['attributes'])
@ app.route("/exercise/<int:exercise_id>/edit_form", methods=['GET'])
def get_exercise_edit_form(exercise_id):
exercise = db.get_exercise(exercise_id)
return render_template('partials/exercise.html', exercise_id=exercise_id, name=exercise['name'], is_edit=True)
all_attributes = db.exercises.get_attributes_by_category()
# Format options for custom_select
formatted_options = {}
ex_attr_ids = [a['attribute_id'] for a in exercise['attributes']]
for cat, attrs in all_attributes.items():
formatted_options[cat] = [
{
"id": a['attribute_id'],
"name": a['name'],
"selected": a['attribute_id'] in ex_attr_ids
} for a in attrs
]
return render_template('partials/exercise.html',
exercise_id=exercise_id,
name=exercise['name'],
attributes=exercise['attributes'],
all_attributes=formatted_options,
is_edit=True)
@ app.route("/exercise/<int:exercise_id>/update", methods=['PUT'])
def update_exercise(exercise_id):
new_name = request.form.get('name')
db.update_exercise(exercise_id, new_name)
return render_template('partials/exercise.html', exercise_id=exercise_id, name=new_name)
attribute_ids = request.form.getlist('attribute_ids')
exercise = db.update_exercise(exercise_id, new_name, attribute_ids)
return render_template('partials/exercise.html',
exercise_id=exercise_id,
name=exercise['name'],
attributes=exercise['attributes'])
""" @ app.route("/exercise/<int:exercise_id>/delete", methods=['DELETE'])
@@ -230,12 +260,24 @@ def delete_exercise(exercise_id):
@ app.route("/settings")
@ login_required
def settings():
# check if user is admin
if current_user.id != 1007:
return redirect(url_for('dashboard'))
people = db.get_people()
exercises = db.get_all_exercises()
all_attributes = db.exercises.get_attributes_by_category()
# Format options for custom_select
formatted_options = {}
for cat, attrs in all_attributes.items():
formatted_options[cat] = [{"id": a['attribute_id'], "name": a['name']} for a in attrs]
if htmx:
return render_block(app.jinja_env, "settings.html", "content", people=people, exercises=exercises), 200, {"HX-Trigger": "updatedPeople"}
return render_template('settings.html', people=people, exercises=exercises)
return render_block(app.jinja_env, "settings.html", "content",
people=people, exercises=exercises, all_attributes=formatted_options), 200, {"HX-Trigger": "updatedPeople"}
return render_template('settings.html', people=people, exercises=exercises, all_attributes=formatted_options)
# Routes moved to routes/tags.py blueprint

19
db.py
View File

@@ -66,22 +66,17 @@ class DataBase():
def get_exercise(self, exercise_id):
exercise = self.execute(
'SELECT exercise_id, name FROM exercise WHERE exercise_id=%s LIMIT 1', [exercise_id], one=True)
return exercise
return self.exercises.get_exercise(exercise_id)
def create_exercise(self, name):
new_exercise = self.execute('INSERT INTO exercise (name) VALUES (%s) RETURNING exercise_id AS "ExerciseId"',
[name], commit=True, one=True)
return new_exercise['ExerciseId']
def create_exercise(self, name, attribute_ids=None):
return self.exercises.add_exercise(name, attribute_ids)
def delete_exercise(self, exercise_id):
self.execute('DELETE FROM exercise WHERE exercise_id=%s', [
exercise_id], commit=True)
def update_exercise(self, exercise_id, name):
self.execute('UPDATE Exercise SET Name=%s WHERE exercise_id=%s', [
name, exercise_id], commit=True)
def update_exercise(self, exercise_id, name, attribute_ids=None):
return self.exercises.update_exercise(exercise_id, name, attribute_ids)
def get_people(self):
people = self.execute(
@@ -382,9 +377,7 @@ class DataBase():
return (topset.get('repetitions'), topset.get('weight'), topset['exercise_name'])
def get_all_exercises(self):
exercises = self.execute(
'SELECT exercise_id, name FROM exercise')
return exercises
return self.exercises.get("")
def get_exercise_progress_for_user(self, person_id, exercise_id, min_date=None, max_date=None, epoch='all', degree=1):
today = datetime.now()

View File

@@ -5,25 +5,116 @@ class Exercises:
def get(self, query):
# Add wildcards to the query
search_query = f"%{query}%"
# We need to fetch exercises with their attributes.
# Since an exercise can have many attributes, we'll fetch basic info first or use a join.
# But wait, the settings page just lists names. We can fetch attributes separately for each row or do a group_concat-like join.
# However, for the settings list, we want to show the tags.
# Let's use a simpler approach: fetch exercises and then for each one (or via a single join) get attributes.
exercises = self.execute("SELECT exercise_id, name FROM exercise WHERE LOWER(name) LIKE LOWER(%s) ORDER BY name ASC;", [search_query])
for ex in exercises:
ex['attributes'] = self.get_exercise_attributes(ex['exercise_id'])
return exercises
def get_exercise(self, exercise_id):
exercise = self.execute("SELECT exercise_id, name FROM exercise WHERE exercise_id=%s;", [exercise_id], one=True)
if exercise:
exercise['attributes'] = self.get_exercise_attributes(exercise_id)
return exercise
def update_exercise_name(self, exercise_id, updated_name):
self.execute("UPDATE exercise SET name = %s WHERE exercise_id = %s;", [updated_name, exercise_id], commit=True)
updated_exercise = self.get_exercise(exercise_id)
return updated_exercise
def get_exercise_attributes(self, exercise_id):
query = """
SELECT cat.name as category_name, attr.attribute_id, attr.name as attribute_name
FROM exercise_to_attribute eta
JOIN exercise_attribute attr ON eta.attribute_id = attr.attribute_id
JOIN exercise_attribute_category cat ON attr.category_id = cat.category_id
WHERE eta.exercise_id = %s
ORDER BY cat.name, attr.name
"""
return self.execute(query, [exercise_id])
def get_all_attribute_categories(self):
return self.execute("SELECT category_id, name FROM exercise_attribute_category ORDER BY name")
def get_attributes_by_category(self):
# Returns a dict: { category_name: [ {id, name}, ... ] }
categories = self.get_all_attribute_categories()
all_attrs = self.execute("SELECT attribute_id, name, category_id FROM exercise_attribute ORDER BY name")
result = {}
for cat in categories:
result[cat['name']] = [a for a in all_attrs if a['category_id'] == cat['category_id']]
return result
def update_exercise(self, exercise_id, name, attribute_ids=None):
self.execute("UPDATE exercise SET name = %s WHERE exercise_id = %s;", [name, exercise_id], commit=True)
# Update attributes: simple delete and re-insert for now
self.execute("DELETE FROM exercise_to_attribute WHERE exercise_id = %s", [exercise_id], commit=True)
if attribute_ids:
for attr_id in attribute_ids:
if attr_id:
self.execute("INSERT INTO exercise_to_attribute (exercise_id, attribute_id) VALUES (%s, %s)",
[exercise_id, attr_id], commit=True)
return self.get_exercise(exercise_id)
def delete_exercise(self, exercise_id):
self.execute('DELETE FROM exercise WHERE exercise_id=%s', [
exercise_id], commit=True)
def add_exercise(self, name):
def add_exercise(self, name, attribute_ids=None):
result = self.execute('INSERT INTO exercise (name) VALUES (%s) RETURNING exercise_id', [name], commit=True, one=True)
exercise_id = result['exercise_id']
new_exercise = self.get_exercise(exercise_id)
return new_exercise
if attribute_ids:
for attr_id in attribute_ids:
if attr_id:
self.execute("INSERT INTO exercise_to_attribute (exercise_id, attribute_id) VALUES (%s, %s)",
[exercise_id, attr_id], commit=True)
return self.get_exercise(exercise_id)
def get_workout_muscle_group_distribution(self, workout_id):
query = """
SELECT attr.name as muscle_group, COUNT(*) as count
FROM topset t
JOIN exercise_to_attribute eta ON t.exercise_id = eta.exercise_id
JOIN exercise_attribute attr ON eta.attribute_id = attr.attribute_id
JOIN exercise_attribute_category cat ON attr.category_id = cat.category_id
WHERE t.workout_id = %s AND cat.name = 'Muscle Group'
GROUP BY attr.name
ORDER BY count DESC
"""
distribution = self.execute(query, [workout_id])
# Calculate percentages and SVG parameters
total_counts = sum(item['count'] for item in distribution)
accumulated_percentage = 0
# Color palette for segments
colors = [
"#3b82f6", # blue-500
"#06b6d4", # cyan-500
"#8b5cf6", # violet-500
"#ec4899", # pink-500
"#f59e0b", # amber-500
"#10b981", # emerald-500
"#6366f1", # indigo-500
"#f43f5e", # rose-500
]
if total_counts > 0:
for i, item in enumerate(distribution):
percentage = (item['count'] / total_counts) * 100
item['percentage'] = round(percentage)
item['dasharray'] = f"{percentage} 100"
item['dashoffset'] = -accumulated_percentage
item['color'] = colors[i % len(colors)]
accumulated_percentage += percentage
return distribution

View File

@@ -124,6 +124,9 @@ def _get_workout_view_model(person_id, workout_id):
# Sort tags alphabetically by name for consistent display
workout_data["tags"].sort(key=lambda x: x.get('tag_name', ''))
# Add muscle group distribution
workout_data["muscle_distribution"] = db.exercises.get_workout_muscle_group_distribution(workout_id)
return workout_data
@@ -179,6 +182,14 @@ def get_workout_start_date(person_id, workout_id):
start_date = workout.get('start_date') if workout else None
return render_template('partials/start_date.html', person_id=person_id, workout_id=workout_id, start_date=start_date)
@workout_bp.route("/person/<int:person_id>/workout/<int:workout_id>/muscle_distribution", methods=['GET'])
def get_workout_muscle_distribution(person_id, workout_id):
distribution = db.exercises.get_workout_muscle_group_distribution(workout_id)
return render_template('partials/workout_breakdown.html',
person_id=person_id,
workout_id=workout_id,
muscle_distribution=distribution)
@workout_bp.route("/person/<int:person_id>/workout/<int:workout_id>/topset/<int:topset_id>/achievements", methods=['GET'])
@validate_topset
def get_topset_achievements(person_id, workout_id, topset_id):

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 199 KiB

After

Width:  |  Height:  |  Size: 227 KiB

View File

@@ -1,5 +1,5 @@
<tr>
<td class="p-4 whitespace-nowrap text-sm font-semibold text-gray-900">
<td class="p-4 whitespace-nowrap text-sm font-semibold text-gray-900 w-1/5">
{% if is_edit|default(false, true) == false %}
{{ name }}
{% else %}
@@ -8,7 +8,35 @@
type="text" name="name" value="{{ name }}">
{% endif %}
</td>
<td class="p-4 whitespace-nowrap text-sm font-semibold text-gray-900 float-right">
<td class="p-4 text-sm text-gray-900 w-3/5">
{% if is_edit|default(false, true) == false %}
<div class="flex flex-wrap gap-2">
{% for attr in attributes %}
<span
class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
title="{{ attr.category_name }}">
{{ attr.attribute_name }}
</span>
{% endfor %}
</div>
{% else %}
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
{% for cat_name, options in all_attributes.items() %}
<div>
<label class="block text-xs font-semibold text-gray-500 uppercase mb-1">{{ cat_name }}</label>
{{ render_partial('partials/custom_select.html',
name='attribute_ids',
options=options,
multiple=true,
search=true,
placeholder='Select ' ~ cat_name
)}}
</div>
{% endfor %}
</div>
{% endif %}
</td>
<td class="p-4 whitespace-nowrap text-sm font-semibold text-gray-900 w-1/5 float-right">
{% if is_edit|default(false, true) == false %}
<button
class="inline-flex justify-center p-2 text-blue-600 rounded-full cursor-pointer hover:bg-blue-100 dark:text-blue-500 dark:hover:bg-gray-600"

View File

@@ -0,0 +1,39 @@
{% if muscle_distribution %}
<div class="bg-gray-50 p-2 rounded-lg border border-gray-100 flex flex-col gap-2 max-w-sm" id="muscle-breakdown"
hx-get="{{ url_for('workout.get_workout_muscle_distribution', person_id=person_id, workout_id=workout_id) }}"
hx-trigger="topsetAdded from:body" hx-swap="outerHTML">
<div class="flex items-center gap-3">
<!-- Mini Donut SVG -->
<div class="relative w-16 h-16 flex-shrink-0">
<svg viewBox="0 0 100 100" class="w-full h-full"
style="transform: rotate(-90deg); transform-origin: center;">
<circle cx="50" cy="50" r="40" fill="transparent" stroke="#e5e7eb" stroke-width="14" />
{% for item in muscle_distribution %}
<circle cx="50" cy="50" r="40" fill="transparent" stroke="{{ item.color }}" stroke-width="14"
stroke-dasharray="{{ item.dasharray }}" stroke-dashoffset="{{ item.dashoffset }}" pathLength="100"
stroke-linecap="round" style="transform-origin: center;"
class="transition-all duration-300 segment-{{ loop.index }}" />
{% endfor %}
</svg>
<div class="absolute inset-0 flex items-center justify-center">
<span class="text-[10px] font-black text-gray-700 tracking-tighter">{{ muscle_distribution[0].percentage
}}%</span>
</div>
</div>
<!-- Mini Legend -->
<div class="flex-grow min-w-0">
<div class="flex flex-wrap gap-x-4 gap-y-2">
{% for item in muscle_distribution %}
<div class="flex items-center gap-1.5 whitespace-nowrap">
<div class="w-1.5 h-1.5 rounded-full" style="background-color: {{ item.color }}"></div>
<span class="text-[10px] font-bold text-gray-600 uppercase">{{ item.muscle_group }}</span>
<span class="text-[10px] text-gray-400 font-medium">{{ item.percentage }}%</span>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endif %}

View File

@@ -107,11 +107,15 @@
<thead class="bg-gray-50">
<tr>
<th scope="col"
class="p-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/4">
class="p-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/5">
Name
</th>
<th scope="col"
class="p-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-3/4">
class="p-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-3/5">
Attributes
</th>
<th scope="col"
class="p-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/5">
<div class="relative">
<div
class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
@@ -139,7 +143,7 @@
hx-swap="outerHTML swap:0.5s">
{% for exercise in exercises %}
{{ render_partial('partials/exercise.html', exercise_id=exercise.exercise_id,
name=exercise.name)}}
name=exercise.name, attributes=exercise.attributes)}}
{% endfor %}
</tbody>
</table>
@@ -155,12 +159,27 @@
then reset() me">
<div class="flex flex-wrap -mx-3 mb-2">
<div class="grow px-3">
<label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-city">
<label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2">
New exercise
</label>
<input
class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500"
type="text" name="name">
class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500 mb-4"
type="text" name="name" placeholder="Exercise Name">
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
{% for cat_name, options in all_attributes.items() %}
<div>
<label class="block text-xs font-bold text-gray-500 uppercase mb-1">{{ cat_name }}</label>
{{ render_partial('partials/custom_select.html',
name='attribute_ids',
options=options,
multiple=true,
search=true,
placeholder='Select ' ~ cat_name
)}}
</div>
{% endfor %}
</div>
</div>
<div class="flex flex-row pt-6 px-3 w-36">

View File

@@ -47,34 +47,29 @@
<!-- 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,
tags=tags) }}
<div class="p-2 md:p-4 border-0 md:border-b rounded-t relative">
<div class="flex flex-col lg:flex-row justify-between items-start gap-4 mr-8">
<div class="flex-grow">
<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,
tags=tags) }}
<div class="grid grid-cols-1 md:grid-cols-2 gap-2 mt-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>
<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 class="flex-shrink-0 w-full lg:w-auto">
{{ render_partial('partials/workout_breakdown.html', person_id=person_id, workout_id=workout_id,
muscle_distribution=muscle_distribution) }}
</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 mr-2"
class="absolute top-2 right-2 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"
hx-get="{{ url_for('workout.delete_workout', person_id=person_id, workout_id=workout_id) }}"
hx-confirm="Are you sure you wish to delete this workout?" hx-push-url="true"
hx-target="#container">