Refactor codebase

This commit is contained in:
Peter Stockings
2026-02-24 21:23:14 +11:00
parent f3abb4781b
commit 56168a182b
11 changed files with 191 additions and 127 deletions

View File

@@ -1,9 +1,12 @@
from flask import Blueprint, jsonify, request, session
from app import SYDNEY_TZ
from app.auth import login_required
from app.db import query, query_one
from collections import OrderedDict
from datetime import datetime, timezone
from flask import Blueprint, jsonify, request, session
from app.config import SYDNEY_TZ
from app.auth import login_required, privacy_guard
from app.db import query
from app.utils import calculate_weight_change
bp = Blueprint("api", __name__, url_prefix="/api")
# Distinct hues for up to 12 users; cycles if more
@@ -58,7 +61,6 @@ def progress_over_time():
""", params)
# Group rows by user
from collections import OrderedDict
users_map = OrderedDict()
for r in rows:
uid = r["user_id"]
@@ -90,7 +92,6 @@ def progress_over_time():
points = entry["data"]
best_fit = {"slope": 0, "intercept": 0}
if len(points) >= 2:
# Convert dates to day offsets from first point
base = datetime.strptime(points[0]["date"], "%Y-%m-%d")
xs = [(datetime.strptime(p["date"], "%Y-%m-%d") - base).days for p in points]
ys = [p["weight"] for p in points]
@@ -118,14 +119,9 @@ def progress_over_time():
@bp.route("/chart-data/<int:user_id>")
@login_required
@privacy_guard
def chart_data(user_id):
"""Return weight & BMI over time for Chart.js."""
# Privacy guard: don't expose private user data to others
if user_id != session.get("user_id"):
target = query_one("SELECT is_private FROM users WHERE id = %s", (user_id,))
if target and target["is_private"]:
return jsonify({"labels": [], "weights": [], "bmis": []})
checkins = query(
"""SELECT weight_kg, bmi, checked_in_at
FROM checkins WHERE user_id = %s
@@ -169,15 +165,10 @@ def comparison():
for u in users:
start_w = float(u["starting_weight_kg"] or u["first_weight"] or 0)
current_w = float(u["current_weight"] or start_w)
if start_w > 0:
lost = start_w - current_w
pct = round((lost / start_w) * 100, 1)
else:
lost = 0
pct = 0
lost, pct = calculate_weight_change(start_w, current_w)
names.append(u["display_name"] or u["username"])
pct_lost.append(pct)
kg_lost.append(round(lost, 1))
kg_lost.append(lost)
return jsonify({
"names": names,
@@ -188,14 +179,9 @@ def comparison():
@bp.route("/weekly-change/<int:user_id>")
@login_required
@privacy_guard
def weekly_change(user_id):
"""Return weekly weight changes for bar chart."""
# Privacy guard: don't expose private user data to others
if user_id != session.get("user_id"):
target = query_one("SELECT is_private FROM users WHERE id = %s", (user_id,))
if target and target["is_private"]:
return jsonify({"labels": [], "changes": []})
checkins = query(
"""SELECT weight_kg, checked_in_at
FROM checkins WHERE user_id = %s