from flask import jsonify class Workout: def __init__(self, db_connection_method): self.execute = db_connection_method def get(self, person_id, workout_id): query = """ SELECT w.workout_id, w.person_id, w.start_date, w.note, t.topset_id, e.exercise_id, e.name AS exercise_name, t.repetitions, t.weight, tag.tag_id, tag.name AS tag_name FROM workout w JOIN topset t ON w.workout_id = t.workout_id JOIN exercise e ON t.exercise_id = e.exercise_id LEFT JOIN workout_tag wt ON w.workout_id = wt.workout_id LEFT JOIN tag ON wt.tag_id = tag.tag_id WHERE w.person_id = %s AND w.workout_id = %s; """ data = self.execute(query, [person_id, workout_id]) if not data: return {"error": "Workout not found"}, 404 exercises = self.execute("SELECT exercise_id, name FROM exercise;") # Initialize workout dictionary workout_data = { "workout_id": data[0]["workout_id"], "person_id": data[0]["person_id"], "start_date": data[0]["start_date"], "note": data[0]["note"], "tags": [], "top_sets": [], "exercises": exercises } # Initialize helpers for tracking unique tags and topsets tag_set = set() topsets_seen = set() # Process each row and add tags and topsets to workout_data for row in data: # Add unique tags tag_id = row["tag_id"] if tag_id and tag_id not in tag_set: workout_data["tags"].append({"tag_id": tag_id, "tag_name": row["tag_name"]}) tag_set.add(tag_id) # Add unique topsets based on topset_id topset_id = row["topset_id"] if topset_id not in topsets_seen: workout_data["top_sets"].append({ "topset_id": topset_id, "exercise_id": row["exercise_id"], "exercise_name": row["exercise_name"], "repetitions": row["repetitions"], "weight": row["weight"] }) topsets_seen.add(topset_id) return workout_data