Compare commits

...

4 Commits

16 changed files with 589 additions and 316 deletions

33
app.py
View File

@@ -1,5 +1,11 @@
from datetime import date
import os
from dotenv import load_dotenv
# Load environment variables from .env file in non-production environments
if os.environ.get('FLASK_ENV') != 'production':
load_dotenv()
from datetime import date
from flask import Flask, abort, render_template, redirect, request, url_for
from flask_login import LoginManager, login_required, current_user
import jinja_partials
@@ -20,18 +26,17 @@ from extensions import db
from utils import convert_str_to_date
from flask_htmx import HTMX
import minify_html
import os
from dotenv import load_dotenv
from flask_compress import Compress
# Load environment variables from .env file in non-production environments
if os.environ.get('FLASK_ENV') != 'production':
load_dotenv()
from flask_caching import Cache
app = Flask(__name__)
app.config['COMPRESS_REGISTER'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 31536000 # 1 year
app.config['CACHE_TYPE'] = 'SimpleCache'
app.config['CACHE_DEFAULT_TIMEOUT'] = 300 # 5 minutes
Compress(app)
cache = Cache(app)
app.config.from_pyfile('config.py')
app.secret_key = os.environ.get('SECRET_KEY', '2a661781919643cb8a5a8bc57642d99f')
jinja_partials.register_extensions(app)
@@ -140,7 +145,10 @@ def person_overview(person_id):
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)
limit = request.args.get('limit', type=int, default=20)
offset = request.args.get('offset', type=int, default=0)
person = db.person_overview.get(person_id, min_date, max_date, selected_exercise_ids, limit=limit, offset=offset)
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)
@@ -151,10 +159,15 @@ def person_overview(person_id):
"tags": tags,
"selected_exercise_ids": selected_exercise_ids,
"max_date": max_date,
"min_date": min_date
"min_date": min_date,
"limit": limit,
"offset": offset,
"next_offset": offset + limit
}
if htmx:
if htmx.target == 'load-more-row':
return render_template('partials/workout_rows.html', **render_args)
return render_block(app.jinja_env, 'person_overview.html', 'content', **render_args), 200, {"HX-Push-Url": url_for('person_overview', person_id=person_id, min_date=min_date, max_date=max_date, exercise_id=selected_exercise_ids), "HX-Trigger": "refreshStats"}
return render_template('person_overview.html', **render_args), 200, {"HX-Push-Url": url_for('person_overview', person_id=person_id, min_date=min_date, max_date=max_date, exercise_id=selected_exercise_ids), "HX-Trigger": "refreshStats"}
@@ -330,6 +343,7 @@ def get_exercise_progress_for_user(person_id, exercise_id):
return render_template('partials/sparkline.html', **exercise_progress)
@app.route("/stats", methods=['GET'])
@cache.cached(timeout=300, query_string=True)
def get_stats():
selected_people_ids = request.args.getlist('person_id', type=int)
min_date = request.args.get('min_date', type=convert_str_to_date)
@@ -339,6 +353,7 @@ def get_stats():
return render_template('partials/stats.html', stats=stats, refresh_url=request.full_path)
@app.route("/graphs", methods=['GET'])
@cache.cached(timeout=300, query_string=True)
def get_people_graphs():
selected_people_ids = request.args.getlist('person_id', type=int)
min_date = request.args.get('min_date', type=convert_str_to_date)

View File

@@ -77,11 +77,33 @@ class PersonOverview:
return exercises
def get(self, person_id, start_date, end_date, selected_exercise_ids):
def get(self, person_id, start_date, end_date, selected_exercise_ids, limit=20, offset=0):
# Build placeholders for exercise IDs
placeholders = ", ".join(["%s"] * len(selected_exercise_ids))
exercise_placeholders = ", ".join(["%s"] * len(selected_exercise_ids))
# Dynamically inject placeholders into the query
# 1. Fetch workout IDs first for pagination
# We need to filter by person, date, and selected exercises
workout_ids_query = f"""
SELECT DISTINCT w.workout_id, w.start_date
FROM workout w
JOIN topset t ON w.workout_id = t.workout_id
WHERE w.person_id = %s
AND w.start_date BETWEEN %s AND %s
AND t.exercise_id IN ({exercise_placeholders})
ORDER BY w.start_date DESC
LIMIT %s OFFSET %s
"""
params = [person_id, start_date, end_date] + selected_exercise_ids + [limit + 1, offset]
workout_id_results = self.execute(workout_ids_query, params)
if not workout_id_results:
return {"person_id": person_id, "person_name": None, "workouts": [], "selected_exercises": [], "exercise_progress_graphs": [], "has_more": False}
has_more = len(workout_id_results) > limit
target_workout_ids = [r["workout_id"] for r in workout_id_results[:limit]]
workout_id_placeholders = ", ".join(["%s"] * len(target_workout_ids))
# 2. Fetch all details for these specific workouts
sql_query = f"""
SELECT
p.person_id,
@@ -103,19 +125,18 @@ class PersonOverview:
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})
w.workout_id IN ({workout_id_placeholders})
AND e.exercise_id IN ({exercise_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
# Parameters for the detailed query
params = target_workout_ids + selected_exercise_ids
result = self.execute(sql_query, params)
if not result:
return {"person_id": person_id, "person_name": None, "workouts": [], "selected_exercises": [], "exercise_progress_graphs": []}
return {"person_id": person_id, "person_name": None, "workouts": [], "selected_exercises": [], "exercise_progress_graphs": [], "has_more": False}
# Extract person info from the first row
person_info = {"person_id": result[0]["person_id"], "person_name": result[0]["person_name"]}
@@ -132,7 +153,6 @@ class PersonOverview:
exercises = sorted(exercises, key=lambda ex: ex["name"])
# Initialize the table structure
workouts = []
workout_map = {} # Map to track workouts
# Initialize the exercise sets dictionary
@@ -153,10 +173,11 @@ class PersonOverview:
# Add topset to the corresponding exercise
if row["exercise_id"] and row["topset_id"]:
# Add to workout exercises
workout_map[workout_id]["exercises"][row["exercise_id"]].append({
"repetitions": row["repetitions"],
"weight": row["weight"]
})
if row["exercise_id"] in workout_map[workout_id]["exercises"]:
workout_map[workout_id]["exercises"][row["exercise_id"]].append({
"repetitions": row["repetitions"],
"weight": row["weight"]
})
# Add to the exercise sets dictionary with workout start date
exercise_sets[row["exercise_id"]]["sets"].append({
@@ -167,9 +188,8 @@ class PersonOverview:
"exercise_name": row["exercise_name"]
})
# Transform into a list of rows
for workout_id, workout in workout_map.items():
workouts.append(workout)
# Transform into a list of rows, maintaining DESC order
workouts = [workout_map[wid] for wid in target_workout_ids if wid in workout_map]
exercise_progress_graphs = self.generate_exercise_progress_graphs(person_info["person_id"], exercise_sets)
@@ -177,7 +197,8 @@ class PersonOverview:
**person_info,
"workouts": workouts,
"selected_exercises": exercises,
"exercise_progress_graphs": exercise_progress_graphs
"exercise_progress_graphs": exercise_progress_graphs,
"has_more": has_more
}
def generate_exercise_progress_graphs(self, person_id, exercise_sets):

View File

@@ -18,4 +18,6 @@ email-validator==2.2.0
requests==2.26.0
polars>=0.20.0
pyarrow>=14.0.0
Flask-Compress==1.13
Flask-Compress==1.13
Brotli==1.0.9
Flask-Caching==2.0.2

View File

@@ -226,6 +226,16 @@ def create_topset(person_id, workout_id):
exercise_id = request.form.get("exercise_id")
repetitions = request.form.get("repetitions")
weight = request.form.get("weight")
# Validation: Ensure exercise_id is present and is a valid integer
if not exercise_id or not exercise_id.strip():
return "Please select an exercise.", 400
try:
exercise_id = int(exercise_id)
except ValueError:
return "Invalid exercise selection.", 400
new_topset_id = db.create_topset(workout_id, exercise_id, repetitions, weight)
exercise = db.get_exercise(exercise_id)
db.activityRequest.log(current_user.id, 'ADD_SET', 'topset', new_topset_id, f"Added set: {repetitions} x {weight}kg {exercise['name']} in workout {workout_id}")

View File

@@ -10,7 +10,7 @@ tr.htmx-swapping td {
bottom: 0px;
left: 0px;
right: 0px;
background-color: rgba(0,0,0,0.9);
background-color: rgba(0, 0, 0, 0.9);
z-index: 1000;
/* Flexbox centers the .modal-content vertically and horizontally */
display: flex;
@@ -22,42 +22,42 @@ tr.htmx-swapping td {
animation-timing-function: ease;
}
#modal > .modal-underlay {
/* underlay takes up the entire viewport. This is only
#modal>.modal-underlay {
/* underlay takes up the entire viewport. This is only
required if you want to click to dismiss the popup */
position: absolute;
z-index: -1;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
position: absolute;
z-index: -1;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
#modal > .modal-content {
/* Display properties for visible dialog*/
border: solid 1px #999;
border-radius: 8px;
box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.3);
background-color: white;
/* Animate when opening */
animation-name: zoomIn;
animation-duration: 150ms;
animation-timing-function: ease;
}
#modal>.modal-content {
/* Display properties for visible dialog*/
border: solid 1px #999;
border-radius: 8px;
box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.3);
background-color: white;
/* Animate when opening */
animation-name: zoomIn;
animation-duration: 150ms;
animation-timing-function: ease;
}
#modal.closing {
/* Animate when closing */
animation-name: fadeOut;
animation-duration: 150ms;
animation-timing-function: ease;
}
#modal.closing {
/* Animate when closing */
animation-name: fadeOut;
animation-duration: 150ms;
animation-timing-function: ease;
}
#modal.closing > .modal-content {
/* Aniate when closing */
animation-name: zoomOut;
animation-duration: 150ms;
animation-timing-function: ease;
}
#modal.closing>.modal-content {
/* Aniate when closing */
animation-name: zoomOut;
animation-duration: 150ms;
animation-timing-function: ease;
}
@keyframes fadeIn {
0% {
@@ -99,20 +99,29 @@ tr.htmx-swapping td {
}
}
.loading-indicator{
display:none;
.loading-indicator {
display: none;
}
.htmx-request .loading-indicator{
display:flex;
.htmx-request .loading-indicator {
display: flex;
}
.htmx-request.loading-indicator{
display:flex;
.htmx-request.loading-indicator {
display: flex;
}
@keyframes slideInLeft {
from { transform: translateX(-100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.animate-slideInLeft {
@@ -122,12 +131,76 @@ tr.htmx-swapping td {
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.animate-fadeIn {
animation-name: fadeIn;
animation-duration: 0.5s;
animation-fill-mode: both;
}
/* SQL Explorer Custom Styles */
.sql-editor-container {
background: #1e1e1e;
border-radius: 0.5rem;
padding: 0.5rem;
box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06);
}
.sql-editor-textarea {
background: transparent !important;
color: #dcdcdc !important;
font-family: 'Fira Code', 'Courier New', Courier, monospace;
line-height: 1.5;
tab-size: 4;
border: none !important;
outline: none !important;
width: 100%;
}
.glass-card {
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.3);
}
.btn-premium {
position: relative;
overflow: hidden;
transition: all 0.3s ease;
}
.btn-premium::after {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg,
transparent,
rgba(255, 255, 255, 0.2),
transparent);
transition: 0.5s;
}
.btn-premium:hover::after {
left: 100%;
}
.table-zebra tbody tr:nth-child(even) {
background-color: rgba(243, 244, 246, 0.5);
}
.table-zebra tbody tr:hover {
background-color: rgba(229, 231, 235, 0.8);
}

View File

@@ -8,6 +8,10 @@
<title>Workout Tracker</title>
<link rel="icon" type="image/png" href="{{ url_for('static', filename='img/logo.png') }}">
<!-- Resource Preloads -->
<link rel="preload" href="/static/css/tailwind.css" as="style">
<link rel="preload" href="/static/js/htmx.min.js" as="script">
<link href="/static/css/tailwind.css" rel="stylesheet">
<link href="/static/css/style.css" rel="stylesheet">

View File

@@ -133,9 +133,7 @@
<div class="w-full mt-2 pb-2 aspect-video"
hx-get="{{ url_for('get_exercise_progress_for_user', person_id=person.id, exercise_id=exercise.id, min_date=min_date, max_date=max_date) }}"
hx-trigger="intersect once" hx-swap="outerHTML">
<div class="flex items-center justify-center h-full bg-gray-50 rounded-lg">
<div class="text-sm text-gray-400 animate-pulse font-medium">Loading graph...</div>
</div>
{{ render_partial('partials/skeleton_graph.html') }}
</div>
<table class="min-w-full divide-y divide-gray-200">

View File

@@ -1,13 +1,24 @@
<div id="new-set-form-container-{{ workout_id }}" class="w-full">
<form class="w-full" id="new-set-workout-{{ workout_id }}"
hx-post="{{ url_for('workout.create_topset', person_id=person_id, workout_id=workout_id) }}" hx-swap="beforeend"
hx-target="#new-workout" _="on htmx:afterOnLoad if #no-workouts add .hidden to #no-workouts end
on topsetAdded
hx-target="#new-workout" _="on htmx:afterOnLoad
if #no-workouts add .hidden to #no-workouts end
if detail.xhr.status == 200
set #validation-error-{{ workout_id }}.innerText to ''
add .hidden to #validation-error-{{ workout_id }}
else
set #validation-error-{{ workout_id }}.innerText to detail.xhr.responseText
remove .hidden from #validation-error-{{ workout_id }}
end
on topsetAdded
render #notification-template with (message: 'Topset added') then append it to #notifications-container
then call _hyperscript.processNode(#notifications-container)
then reset() me
then trigger clearNewSetInputs">
<div id="validation-error-{{ workout_id }}"
class="hidden text-red-500 text-xs italic mb-4 p-2 bg-red-50 border border-red-200 rounded"></div>
<div class="flex flex-wrap -mx-3 mb-2">
<div class="w-full md:w-[30%] 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-state">

View File

@@ -0,0 +1,17 @@
<div class="w-full h-full bg-gray-100 rounded-lg animate-pulse relative overflow-hidden">
<!-- Subtle shimmer effect -->
<div
class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full animate-[shimmer_2s_infinite]">
</div>
<div class="flex items-center justify-center h-full">
<div class="text-xs text-gray-400 font-medium">Loading...</div>
</div>
</div>
<style>
@keyframes shimmer {
100% {
transform: translateX(100%);
}
}
</style>

View File

@@ -1,43 +1,56 @@
{% if error or results %}
<div class="relative">
<div class="mt-12 bg-white border border-gray-200 rounded-2xl overflow-hidden shadow-lg animate-fadeIn relative">
<!-- Floating Clear Button -->
<button _="on click set the innerHTML of my.parentElement to ''"
class="absolute top-0 right-0 m-2 px-3 py-2 flex items-center gap-2 rounded-full bg-gray-800 text-white shadow-md opacity-50 hover:opacity-100 hover:bg-gray-700 transition-all">
<!-- Trash Icon -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
stroke-linecap="round" stroke-linejoin="round" class="h-5 w-5">
<path
d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6m5 4v6m4-6v6" />
<button _="on click transition opacity to 0 then set my.parentElement.innerHTML to ''"
class="absolute top-4 right-4 p-2 bg-gray-900/10 hover:bg-red-50 text-gray-500 hover:text-red-600 rounded-full transition-all duration-200 group z-10"
title="Clear results">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5-4h4a2 2 0 012 2v1H7V5a2 2 0 012-2z" />
</svg>
<span>Clear</span>
</button>
<div class="px-6 py-4 border-b border-gray-100 bg-gray-50/50">
<h3 class="text-sm font-bold text-gray-700 uppercase tracking-wider">Query Results</h3>
{% if results %}
<p class="text-xs text-gray-500 mt-0.5">{{ results|length }} rows returned</p>
{% endif %}
</div>
{% if error %}
<div class="bg-red-200 text-red-800 p-4 rounded mb-4">
<strong>Error:</strong> {{ error }}
<div class="p-6">
<div class="bg-red-50 border-l-4 border-red-400 p-4 rounded text-red-700 text-sm">
<strong class="font-bold">Execution Error:</strong> {{ error }}
</div>
</div>
{% endif %}
{% if results %}
<table class="min-w-full bg-white">
<thead>
<tr>
{% for col in columns %}
<th class="py-2 px-4 border-b">{{ col }}</th>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200 table-zebra">
<thead class="bg-gray-50/30">
<tr>
{% for col in columns %}
<th scope="col"
class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-widest border-b border-gray-100">
{{ col }}
</th>
{% endfor %}
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-100">
{% for row in results %}
<tr class="hover:bg-blue-50/30 transition-colors">
{% for col in columns %}
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-medium">
{{ row[col] if row[col] is not none else 'NULL' }}
</td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in results %}
<tr class="text-center">
{% for col in columns %}
<td class="py-2 px-4 border-b">{{ row[col] }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</tbody>
</table>
</div>
{% endif %}
</div>
{% endif %}

View File

@@ -1,23 +1,51 @@
<div class="relative">
<div class="relative space-y-4">
<!-- Hidden textarea containing the actual SQL (so we preserve line breaks) -->
<textarea id="create_sql_text" style="display: none;">{{ create_sql }}</textarea>
<textarea id="create_sql_text" class="hidden">{{ create_sql }}</textarea>
<!-- Floating Clear Button -->
<button onclick="copySqlToClipboard()"
class="absolute top-0 right-0 m-2 px-3 py-2 flex items-center gap-2 rounded-full bg-gray-800 text-white shadow-md opacity-50 hover:opacity-100 hover:bg-gray-700 transition-all">
<!-- Floating Actions Container -->
<div class="absolute top-4 right-4 flex items-center gap-2 z-10">
<button id="copy-ddl-btn" onclick="copySqlToClipboard()"
_="on click set my.innerText to 'Copied!' then wait 2s then set my.innerText to 'Copy DDL SQL'"
class="px-4 py-2 flex items-center gap-2 rounded-xl bg-gray-900 text-white shadow-lg hover:bg-gray-800 transition-all text-sm font-medium border border-gray-700">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012-2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
</svg>
<span>Copy DDL SQL</span>
</button>
</div>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
class="h-5 w-5">
<path stroke-linecap="round" stroke-linejoin="round"
d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 0 0 2.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 0 0-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75 2.25 2.25 0 0 0-.1-.664m-5.8 0A2.251 2.251 0 0 1 13.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25ZM6.75 12h.008v.008H6.75V12Zm0 3h.008v.008H6.75V15Zm0 3h.008v.008H6.75V18Z" />
</svg>
<!-- Schema Diagram Frame -->
<div class="overflow-auto border-2 border-dashed border-gray-200 rounded-2xl bg-slate-50 p-8 shadow-inner"
style="max-height: 80vh;">
<div class="flex justify-center min-w-max">
<div class="bg-white p-4 rounded-2xl shadow-xl border border-gray-100">
<object data="/static/img/schema.svg" type="image/svg+xml" id="schema-svg-object"
class="block transition-all duration-300"
style="min-width: 1000px; height: auto; min-height: 600px;">
<p class="text-gray-500">Your browser does not support SVG objects.
<a href="/static/img/schema.svg" target="_blank" class="text-blue-500 hover:underline">Click
here to view the schema directly.</a>
</p>
</object>
</div>
</div>
</div>
<span>Copy SQL</span>
</button>
<div class="overflow-auto border rounded-xl bg-slate-50 p-4" style="max-height: 80vh;">
<div class="flex justify-center">
<img src="/static/img/schema.svg" alt="Database Schema Diagram" class="max-w-full h-auto">
<!-- Schema Footer Info -->
<div class="flex items-center justify-center gap-4 text-xs font-medium text-gray-400">
<div class="flex items-center gap-1.5">
<span class="w-2 h-2 rounded-full bg-green-500"></span>
Primary Keys
</div>
<div class="flex items-center gap-1.5">
<span class="w-2 h-2 rounded-full bg-blue-500"></span>
Foreign Keys
</div>
<div class="flex items-center gap-1.5">
<span class="w-2 h-2 rounded-full bg-gray-300"></span>
Columns
</div>
</div>
@@ -27,27 +55,23 @@
const text = textArea.value;
if (navigator.clipboard && navigator.clipboard.writeText) {
// Modern approach: Use Clipboard API
navigator.clipboard.writeText(text)
.then(() => {
alert("SQL copied to clipboard!");
// We could use a toast here if available
console.log("SQL copied to clipboard!");
})
.catch(err => {
alert("Failed to copy: " + err);
console.error("Failed to copy: " + err);
});
} else {
// Fallback (older browsers):
// - Temporarily show the textarea, select, and use document.execCommand('copy')
// - This approach is less reliable but widely supported before navigator.clipboard.
textArea.style.display = "block"; // show temporarily
textArea.classList.remove('hidden');
textArea.select();
try {
document.execCommand("copy");
alert("SQL copied to clipboard!");
} catch (err) {
alert("Failed to copy: " + err);
console.error("Failed to copy: " + err);
}
textArea.style.display = "none"; // hide again
textArea.classList.add('hidden');
}
}
</script>

View File

@@ -1,199 +1,208 @@
<div id="sql-query">
<div id="sql-query" class="space-y-8">
{% if error %}
<div class="bg-red-200 text-red-800 p-3 rounded mb-4">
<strong>Error:</strong> {{ error }}
<div class="bg-red-50 border-l-4 border-red-400 p-4 rounded shadow-sm animate-fadeIn">
<div class="flex">
<div class="flex-shrink-0">
<svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
clip-rule="evenodd" />
</svg>
</div>
<div class="ml-3">
<p class="text-sm text-red-700">
<strong class="font-bold">Error:</strong> {{ error }}
</p>
</div>
</div>
</div>
{% endif %}
<form method="POST" hx-post="{{ url_for('sql_explorer.sql_query') }}" hx-target="#sql-query">
<!-- Title Input -->
<div>
<label for="query-title" class="block text-sm font-medium text-gray-700">Title</label>
<input type="text" id="query-title" name="title"
class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Enter a title for your query" {% if title %} value="{{ title }}" {% endif %}>
</div>
<div class=" pt-2">
<label for="query" class="block text-sm font-medium text-gray-700 pb-1">Query</label>
<textarea name="query" spellcheck="false" id="query"
class="w-full h-48 p-4 font-mono text-sm text-gray-800 bg-gray-100 border border-gray-300 rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
placeholder="Enter your SQL query here..." required
_="on load set my.style.height to my.scrollHeight + 'px'
on input set my.style.height to 0 then set my.style.height to my.scrollHeight + 'px'">{{ query }}</textarea>
</div>
<!-- Natural Language Query Input -->
<div class="pt-2">
<label for="natural-query" class="block text-sm font-medium text-gray-700 pb-1">Generate SQL from Natural
Language</label>
<div class="flex items-center">
<input type="text" id="natural-query" name="natural_query"
class="flex-grow p-2 border border-gray-300 rounded-l-md shadow-sm focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
placeholder="e.g., 'Show me the number of workouts per person'">
<button type="button" hx-post="{{ url_for('sql_explorer.generate_sql') }}"
hx-include="[name='natural_query']" hx-indicator="#sql-spinner" hx-swap="none"
_="on htmx:afterRequest set #query.value to detail.xhr.responseText then send input to #query"
class="bg-purple-600 text-white p-2.5 rounded-r-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 inline-flex items-center">
Generate SQL
<span id="sql-spinner" class="htmx-indicator ml-2">
<svg class="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
</circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
<form method="POST" hx-post="{{ url_for('sql_explorer.sql_query') }}" hx-target="#sql-query" class="space-y-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Title Input -->
<div class="space-y-1">
<label for="query-title" class="block text-sm font-semibold text-gray-700">Query Title</label>
<div class="relative">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</span>
</button>
</div>
<input type="text" id="query-title" name="title"
class="block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm"
placeholder="Untitled Query" {% if title %} value="{{ title }}" {% endif %}>
</div>
</div>
<!-- Magic SQL Generator -->
<div class="space-y-1">
<label for="natural-query" class="block text-sm font-semibold text-gray-700">AI SQL Generator</label>
<div class="flex items-center gap-2">
<div class="relative flex-grow">
<div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<svg class="h-4 w-4 text-purple-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd"
d="M5 2a1 1 0 011 1v1h1a1 1 0 010 2H6v1a1 1 0 01-2 0V6H3a1 1 0 010-2h1V3a1 1 0 011-1zm0 10a1 1 0 011 1v1h1a1 1 0 110 2H6v1a1 1 0 11-2 0v-1H3a1 1 0 110-2h1v-1a1 1 0 011-1zM12 2a1 1 0 01.967.744L14.146 7.2 17.5 9.134a1 1 0 010 1.732l-3.354 1.935-1.18 4.455a1 1 0 01-1.933 0L9.854 12.8 6.5 10.866a1 1 0 010-1.732l3.354-1.935 1.18-4.455A1 1 0 0112 2z"
clip-rule="evenodd" />
</svg>
</div>
<input type="text" id="natural-query" name="natural_query"
class="block w-full pl-9 pr-3 py-2.5 border border-purple-200 rounded-xl shadow-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm bg-purple-50/30 placeholder-purple-300"
placeholder="e.g. 'Workouts per person last month'">
</div>
<button type="button" hx-post="{{ url_for('sql_explorer.generate_sql') }}"
hx-include="[name='natural_query']" hx-indicator="#sql-spinner" hx-swap="none"
_="on htmx:afterRequest set #query.value to detail.xhr.responseText then send input to #query"
class="btn-premium whitespace-nowrap inline-flex items-center justify-center px-4 py-2.5 border border-transparent text-sm font-medium rounded-xl text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 shadow-sm transition-all">
Generate
<span id="sql-spinner" class="htmx-indicator ml-2">
<svg class="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
</span>
</button>
</div>
</div>
</div>
<!-- SQL Editor -->
<div class="space-y-1">
<div class="flex items-center justify-between">
<label for="query" class="block text-sm font-semibold text-gray-700">SQL Statement</label>
<span class="text-xs text-gray-400 font-mono">PostgreSQL Dialect</span>
</div>
<div class="sql-editor-container border border-gray-800 shadow-lg">
<textarea name="query" spellcheck="false" id="query"
class="sql-editor-textarea h-64 p-4 text-sm resize-none"
placeholder="SELECT * FROM workouts LIMIT 10;" required
_="on load set my.style.height to Math.max(256, my.scrollHeight) + 'px'
on input set my.style.height to 0 then set my.style.height to Math.max(256, my.scrollHeight) + 'px'">{{ query }}</textarea>
</div>
</div>
<!-- Action Buttons -->
<div class="flex space-x-2 pt-1">
<div class="flex flex-wrap items-center gap-3 pt-2">
<!-- Execute Button -->
<button hx-post="{{ url_for('sql_explorer.execute_sql_query') }}" hx-target="#execute-query-results"
hx-include="[name='query']" hx-trigger="click" hx-swap="innerHTML"
class="flex items-center bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
<!-- Execute Icon (Heroicon: Play) -->
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M14.752 11.168l-5.197-2.132A1 1 0 008 9.868v4.264a1 1 0 001.555.832l5.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
class="btn-premium inline-flex items-center px-6 py-2.5 border border-transparent text-sm font-semibold rounded-xl text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 shadow-md">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z"
clip-rule="evenodd" />
</svg>
Execute
Execute Query
</button>
<!-- Plot Button -->
<button hx-post="{{ url_for('sql_explorer.plot_unsaved_query') }}" hx-target="#sql-plot-results"
hx-trigger="click" hx-include="[name='query'],[name='title']" hx-indicator="#sql-plot-results-loader"
class="flex items-center bg-blue-100 text-white px-4 py-2 rounded hover:bg-blue-300 focus:outline-none focus:ring-2 focus:ring-blue-300">
<!-- Plot Icon (Heroicon: Chart Bar) -->
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="h-5 w-5 mr-1">
<path stroke-linecap=" round" stroke-linejoin="round"
d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 0 1 3 19.875v-6.75ZM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V8.625ZM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V4.125Z" />
class="btn-premium inline-flex items-center px-6 py-2.5 border border-gray-300 text-sm font-semibold rounded-xl text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 shadow-sm">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2 text-blue-500" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
Plot
<!-- Overlay with Animated Spinner -->
<div id="sql-plot-results-loader" class="loading-indicator inset-0 opacity-35 pl-2">
<svg class="animate-spin h-5 w-5 text-white opacity-100" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100" fill="none">
<circle cx="50" cy="50" r="45" stroke="currentColor" stroke-width="10" stroke-linecap="round"
class="opacity-20"></circle>
<path d="M50,5 A45,45 0 0,1 95,50" stroke="currentColor" stroke-width="10"
stroke-linecap="round" class="opacity-75"></path>
Visualize Plot
<span id="sql-plot-results-loader" class="htmx-indicator ml-2">
<svg class="animate-spin h-3 w-3 text-blue-500" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
</circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
</div>
</span>
</button>
<!-- Save Button -->
<button type="submit" name="action" value="save"
class="flex items-center bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500">
<!-- Save Icon (Heroicon: Save) -->
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24"
class="btn-premium inline-flex items-center px-6 py-2.5 border border-transparent text-sm font-semibold rounded-xl text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 shadow-md">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h7a2 2 0 012 2v1" />
d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
</svg>
Save
Save Query
</button>
</div>
</form>
<!-- Sql query Results Section -->
<div id="execute-query-results" class="mt-6">
</div>
<!-- Plot Results Section -->
<div id="sql-plot-results" class="mt-8">
</div>
<!-- Query Results -->
<div id="execute-query-results" class="transition-all duration-300"></div>
<!-- Plot Results -->
<div id="sql-plot-results" class="transition-all duration-300"></div>
<!-- Saved Queries Section -->
<div class="mt-8">
<h2 class="text-xl font-semibold mb-4">Saved Queries</h2>
<div class="pt-10 border-t border-gray-100">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-bold text-gray-800">Saved Queries Library</h2>
<span class="text-xs font-medium text-gray-400 uppercase tracking-widest">{{ saved_queries|length }} Queries
Total</span>
</div>
{% if saved_queries %}
<div class="overflow-x-auto">
<table class="min-w-full bg-white shadow-md rounded-lg overflow-hidden">
<thead>
<div class="bg-white border border-gray-200 rounded-2xl overflow-hidden shadow-sm">
<table class="min-w-full table-zebra">
<thead class="bg-gray-50/50">
<tr>
<th
class="py-3 px-6 bg-gray-200 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">
Title</th>
class="px-6 py-4 text-left text-xs font-bold text-gray-500 uppercase tracking-wider border-b">
Query Title</th>
<th
class="py-3 px-6 bg-gray-200 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">
Actions</th>
class="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase tracking-wider border-b">
Quick Actions</th>
</tr>
</thead>
<tbody>
<tbody class="divide-y divide-gray-100">
{% for saved in saved_queries %}
<tr class="hover:bg-gray-100 transition-colors duration-200">
<!-- Query Title as Load Action -->
<td class="py-4 px-6 border-b">
<a href="#" hx-get="{{ url_for('sql_explorer.load_sql_query', query_id=saved.id) }}"
<tr class="group transition-colors">
<td class="px-6 py-4 whitespace-nowrap">
<button hx-get="{{ url_for('sql_explorer.load_sql_query', query_id=saved.id) }}"
hx-target="#sql-query"
class="flex items-center text-blue-500 hover:text-blue-700 cursor-pointer">
<!-- Load Icon (Heroicon: Eye) -->
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none"
class="flex items-center text-sm font-medium text-gray-900 hover:text-blue-600 group-hover:translate-x-1 transition-all">
<svg xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4 mr-2.5 text-gray-400 group-hover:text-blue-500" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
{{ saved.title }}
</a>
{{ saved.title or 'Untitled Query' }}
</button>
</td>
<td class="py-4 px-6 border-b">
<div class="flex space-x-4">
<td class="px-6 py-4 whitespace-nowrap text-right">
<div class="flex items-center justify-end gap-4">
<!-- Plot Action -->
<a href="#" hx-get="{{ url_for('sql_explorer.plot_query', query_id=saved.id) }}"
hx-target="#sql-plot-results"
class="flex items-center text-green-500 hover:text-green-700 cursor-pointer"
hx-trigger="click" hx-indicator="#sql-plot-results-loader-{{ saved.id }}">
<!-- Plot Icon (Heroicon: Chart Bar) -->
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" class="h-5 w-5 mr-1">
<path stroke-linecap=" round" stroke-linejoin="round"
d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 0 1 3 19.875v-6.75ZM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V8.625ZM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V4.125Z" />
<button hx-get="{{ url_for('sql_explorer.plot_query', query_id=saved.id) }}"
hx-target="#sql-plot-results" hx-indicator="#sql-plot-results-loader-{{ saved.id }}"
class="text-green-600 hover:text-green-800 p-1 rounded-lg hover:bg-green-50 transition-colors tooltip"
title="Visualize Plot">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
Plot
<!-- Overlay with Animated Spinner -->
<div id="sql-plot-results-loader-{{ saved.id }}"
class="loading-indicator inset-0 opacity-35 pl-2">
<svg class="animate-spin h-5 w-5 text-white opacity-100"
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="none">
<circle cx="50" cy="50" r="45" stroke="currentColor" stroke-width="10"
stroke-linecap="round" class="opacity-20"></circle>
<path d="M50,5 A45,45 0 0,1 95,50" stroke="currentColor" stroke-width="10"
stroke-linecap="round" class="opacity-75"></path>
</svg>
</div>
</a>
</button>
<!-- Delete Action -->
<a href="#"
hx-delete="{{ url_for('sql_explorer.delete_sql_query', query_id=saved.id) }}"
hx-target="#sql-query"
class="flex items-center text-red-500 hover:text-red-700 cursor-pointer"
hx-confirm="Are you sure you want to delete the query titled '{{ saved.title }}'?">
<!-- Delete Icon (Heroicon: Trash) -->
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none"
<button hx-delete="{{ url_for('sql_explorer.delete_sql_query', query_id=saved.id) }}"
hx-target="#sql-query" hx-confirm="Delete query '{{ saved.title }}'?"
class="text-red-400 hover:text-red-600 p-1 rounded-lg hover:bg-red-50 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5-4h4a2 2 0 012 2v1H7V5a2 2 0 012-2z" />
</svg>
Delete
</a>
</button>
</div>
</td>
</tr>
@@ -202,8 +211,14 @@
</table>
</div>
{% else %}
<p class="text-gray-600">No saved queries found.</p>
<div class="text-center py-12 bg-gray-50 rounded-2xl border-2 border-dashed border-gray-200">
<svg class="mx-auto h-12 w-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>
<h3 class="mt-2 text-sm font-medium text-gray-900">No saved queries</h3>
<p class="mt-1 text-sm text-gray-500">Get started by creating and saving your first SQL query.</p>
</div>
{% endif %}
</div>
</div>

View File

@@ -0,0 +1,29 @@
{% for workout in workouts %}
<tr hx-get="{{ url_for('workout.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>
{% if loop.last and has_more %}
<tr id="load-more-row">
<td colspan="{{ selected_exercises|length + 1 }}" class="p-4 text-center">
<button class="text-blue-600 font-medium hover:underline px-4 py-2"
hx-get="{{ url_for('person_overview', person_id=person_id, offset=next_offset, limit=limit) }}"
hx-include="[name='exercise_id'],[name='min_date'],[name='max_date']" hx-target="#load-more-row"
hx-swap="outerHTML">
Load More Workouts
</button>
</td>
</tr>
{% endif %}
{% endfor %}

View File

@@ -107,9 +107,8 @@
{% for graph in exercise_progress_graphs %}
<div hx-get="{{ url_for('get_exercise_progress_for_user', person_id=person_id, exercise_id=graph.exercise_id, min_date=min_date, max_date=max_date) }}"
hx-trigger="intersect once" hx-swap="outerHTML">
<div class="flex items-center justify-center h-48 bg-gray-50 rounded-lg">
<div class="text-sm text-gray-400 animate-pulse font-medium">Loading {{ graph.exercise_name }}...
</div>
<div class="h-48">
{{ render_partial('partials/skeleton_graph.html') }}
</div>
</div>
{% endfor %}
@@ -138,22 +137,7 @@
</thead>
<tbody class="bg-white">
{% for workout in workouts %}
<tr hx-get="{{ url_for('workout.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 %}
{% include 'partials/workout_rows.html' %}
</tbody>
</table>

View File

@@ -2,17 +2,74 @@
{% block content %}
<div class="bg-white shadow rounded-lg p-4 sm:p-6 xl:p-8 mb-8">
<div class="mb-4 flex items-center justify-between">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="mb-8 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h3 class="text-xl font-bold text-gray-900 mb-2">SQL Explorer</h3>
<h1 class="text-3xl font-extrabold text-gray-900 tracking-tight sm:text-4xl">
SQL <span class="text-blue-600">Explorer</span>
</h1>
<p class="mt-2 text-sm text-gray-500 max-w-2xl">
Query your workout data directly using SQL or natural language. Explore the database schema below to
understand the available tables and relationships.
</p>
</div>
<div class="flex items-center gap-2">
<span
class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
<span class="flex h-2 w-2 mr-1.5 space-x-1">
<span class="animate-ping absolute inline-flex h-2 w-2 rounded-full bg-blue-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-blue-500"></span>
</span>
PostgreSQL Connected
</span>
</div>
</div>
<div hx-get="{{ url_for('sql_explorer.sql_schema') }}" hx-trigger="load"></div>
{{ render_partial('partials/sql_explorer/sql_query.html', saved_queries=saved_queries) }}
<div class="grid grid-cols-1 gap-8">
<!-- Schema Section -->
<section
class="bg-white shadow-sm border border-gray-200 rounded-2xl overflow-hidden transition-all hover:shadow-md">
<div class="px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-gray-50/50">
<div class="flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
<h3 class="text-lg font-semibold text-gray-800">Database Schema</h3>
</div>
<button class="text-sm text-blue-600 hover:text-blue-700 font-medium transition-colors" _="on click toggle .hidden on #schema-content then
if #schema-content.classList.contains('hidden') set my.innerText to 'Show Schema'
else set my.innerText to 'Hide Schema'">
Hide Schema
</button>
</div>
<div id="schema-content" class="p-6 transition-all duration-300">
<div hx-get="{{ url_for('sql_explorer.sql_schema') }}" hx-trigger="load">
<!-- Loader placeholder -->
<div class="flex justify-center items-center py-12">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
</div>
</div>
</div>
</section>
<!-- Query Section -->
<section
class="bg-white shadow-sm border border-gray-200 rounded-2xl overflow-hidden transition-all hover:shadow-md">
<div class="px-6 py-4 border-b border-gray-100 flex items-center gap-2 bg-gray-50/50">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
</svg>
<h3 class="text-lg font-semibold text-gray-800">SQL Query Editor</h3>
</div>
<div class="p-6">
{{ render_partial('partials/sql_explorer/sql_query.html', saved_queries=saved_queries) }}
</div>
</section>
</div>
</div>
{% endblock %}

View File

@@ -34,10 +34,10 @@ def get_exercise_graph_model(title, estimated_1rm, repetitions, weight, start_da
vb_height *= 75 / vb_height # Scale to 75px height
# Use NumPy arrays for efficient scaling
relative_positions = np.array([(date - min_date).days / total_span for date in start_dates])
estimated_1rm_scaled = ((np.array(estimated_1rm) - min_e1rm) / e1rm_range) * vb_height
repetitions_scaled = ((np.array(repetitions) - min_reps) / reps_range) * vb_height
weight_scaled = ((np.array(weight) - min_weight) / weight_range) * vb_height
relative_positions = np.round(np.array([(date - min_date).days / total_span for date in start_dates]), 1)
estimated_1rm_scaled = np.round(((np.array(estimated_1rm) - min_e1rm) / e1rm_range) * vb_height, 1)
repetitions_scaled = np.round(((np.array(repetitions) - min_reps) / reps_range) * vb_height, 1)
weight_scaled = np.round(((np.array(weight) - min_weight) / weight_range) * vb_height, 1)
# Calculate slope and line of best fit
slope_kg_per_day = e1rm_range / total_span
@@ -57,7 +57,7 @@ def get_exercise_graph_model(title, estimated_1rm, repetitions, weight, start_da
if len(np.unique(x_fit)) > degree:
coeffs = np.polyfit(x_fit, y_fit, degree)
poly_fit = np.poly1d(coeffs)
y_best_fit = poly_fit(relative_positions)
y_best_fit = np.round(poly_fit(relative_positions), 1)
best_fit_points = list(zip(y_best_fit.tolist(), relative_positions.tolist()))
else:
best_fit_points = []
@@ -258,20 +258,6 @@ def prepare_svg_plot_data(results, columns, title):
plot_data['plot_type'] = 'table' # Fallback if essential data is missing
return plot_data
def get_client_ip():
"""Get real client IP address, checking proxy headers first"""
# Check common proxy headers in order of preference
if request.headers.get('X-Forwarded-For'):
# X-Forwarded-For can contain multiple IPs, get the first (original client)
return request.headers.get('X-Forwarded-For').split(',')[0].strip()
elif request.headers.get('X-Real-IP'):
return request.headers.get('X-Real-IP')
elif request.headers.get('CF-Connecting-IP'): # Cloudflare
return request.headers.get('CF-Connecting-IP')
else:
# Fallback to direct connection IP
return request.remote_addr
# Calculate ranges (handle datetime separately)
if x_type == 'datetime':
valid_dates = [d for d in x_values_raw if d is not None]
@@ -360,4 +346,18 @@ def get_client_ip():
plot_data['bar_width'] = draw_width / len(points) * 0.8 if points else 10
return plot_data
return plot_data
def get_client_ip():
"""Get real client IP address, checking proxy headers first"""
# Check common proxy headers in order of preference
if request.headers.get('X-Forwarded-For'):
# X-Forwarded-For can contain multiple IPs, get the first (original client)
return request.headers.get('X-Forwarded-For').split(',')[0].strip()
elif request.headers.get('X-Real-IP'):
return request.headers.get('X-Real-IP')
elif request.headers.get('CF-Connecting-IP'): # Cloudflare
return request.headers.get('CF-Connecting-IP')
else:
# Fallback to direct connection IP
return request.remote_addr