bug fixes

This commit is contained in:
2026-02-14 20:06:39 -06:00
parent 04ea648950
commit 3ccd11153c
7 changed files with 131 additions and 39 deletions

View File

@@ -155,8 +155,48 @@ def health_check():
return flask.jsonify({"status": "ok"}), 200
def _seed_templates_if_empty():
"""Auto-seed routine templates if the table is empty."""
try:
count = postgres.count("routine_templates")
if count == 0:
import logging
logging.getLogger(__name__).info("No templates found, seeding from seed_templates.sql...")
seed_path = os.path.join(os.path.dirname(__file__), "..", "config", "seed_templates.sql")
if os.path.exists(seed_path):
with open(seed_path, "r") as f:
sql = f.read()
with postgres.get_cursor() as cur:
cur.execute(sql)
logging.getLogger(__name__).info("Templates seeded successfully.")
except Exception as e:
import logging
logging.getLogger(__name__).warning(f"Failed to seed templates: {e}")
def _seed_rewards_if_empty():
"""Auto-seed reward pool if the table is empty."""
try:
count = postgres.count("reward_pool")
if count == 0:
import logging
logging.getLogger(__name__).info("No rewards found, seeding from seed_rewards.sql...")
seed_path = os.path.join(os.path.dirname(__file__), "..", "config", "seed_rewards.sql")
if os.path.exists(seed_path):
with open(seed_path, "r") as f:
sql = f.read()
with postgres.get_cursor() as cur:
cur.execute(sql)
logging.getLogger(__name__).info("Rewards seeded successfully.")
except Exception as e:
import logging
logging.getLogger(__name__).warning(f"Failed to seed rewards: {e}")
if __name__ == "__main__":
for module in ROUTE_MODULES:
if hasattr(module, "register"):
module.register(app)
_seed_templates_if_empty()
_seed_rewards_if_empty()
app.run(host="0.0.0.0", port=5000)

View File

@@ -342,18 +342,26 @@ def register(app):
all_logs = postgres.select(
"med_logs",
where={"medication_id": med["id"], "action": "taken"},
where={"medication_id": med["id"]},
)
today_taken = [
log.get("scheduled_time", "")
for log in all_logs
if str(log.get("created_at", ""))[:10] == today_str
if log.get("action") == "taken"
and str(log.get("created_at", ""))[:10] == today_str
]
today_skipped = [
log.get("scheduled_time", "")
for log in all_logs
if log.get("action") == "skipped"
and str(log.get("created_at", ""))[:10] == today_str
]
result.append({
"medication": med,
"scheduled_times": [] if is_prn else med.get("times", []),
"taken_times": today_taken,
"skipped_times": today_skipped,
"is_prn": is_prn,
})
seen_med_ids.add(med["id"])
@@ -378,18 +386,26 @@ def register(app):
all_logs = postgres.select(
"med_logs",
where={"medication_id": med["id"], "action": "taken"},
where={"medication_id": med["id"]},
)
tomorrow_taken = [
log.get("scheduled_time", "")
for log in all_logs
if str(log.get("created_at", ""))[:10] == tomorrow_str
if log.get("action") == "taken"
and str(log.get("created_at", ""))[:10] == tomorrow_str
]
tomorrow_skipped = [
log.get("scheduled_time", "")
for log in all_logs
if log.get("action") == "skipped"
and str(log.get("created_at", ""))[:10] == tomorrow_str
]
result.append({
"medication": med,
"scheduled_times": early_times,
"taken_times": tomorrow_taken,
"skipped_times": tomorrow_skipped,
"is_prn": False,
"is_next_day": True,
})
@@ -415,18 +431,26 @@ def register(app):
all_logs = postgres.select(
"med_logs",
where={"medication_id": med["id"], "action": "taken"},
where={"medication_id": med["id"]},
)
yesterday_taken = [
log.get("scheduled_time", "")
for log in all_logs
if str(log.get("created_at", ""))[:10] == yesterday_str
if log.get("action") == "taken"
and str(log.get("created_at", ""))[:10] == yesterday_str
]
yesterday_skipped = [
log.get("scheduled_time", "")
for log in all_logs
if log.get("action") == "skipped"
and str(log.get("created_at", ""))[:10] == yesterday_str
]
result.append({
"medication": med,
"scheduled_times": late_times,
"taken_times": yesterday_taken,
"skipped_times": yesterday_skipped,
"is_prn": False,
"is_previous_day": True,
})

View File

@@ -98,40 +98,56 @@ def _complete_session_with_celebration(session_id, user_uuid, session):
else:
duration_minutes = 0
# Update session as completed with duration
# Update session as completed with duration — this MUST succeed
postgres.update("routine_sessions", {
"status": "completed",
"completed_at": now.isoformat(),
"actual_duration_minutes": int(duration_minutes),
}, {"id": session_id})
# Update streak (returns streak with optional 'milestone' key)
streak_result = routines_core._update_streak(user_uuid, session["routine_id"])
# Gather celebration stats — failures here should not break completion
streak_current = 1
streak_longest = 1
streak_milestone = None
steps_completed = 0
steps_skipped = 0
total_completions = 1
# Get streak data
streak = postgres.select_one("routine_streaks", {
"user_uuid": user_uuid,
"routine_id": session["routine_id"],
})
streak_milestone = streak_result.get("milestone") if streak_result else None
try:
streak_result = routines_core._update_streak(user_uuid, session["routine_id"])
streak = postgres.select_one("routine_streaks", {
"user_uuid": user_uuid,
"routine_id": session["routine_id"],
})
if streak:
streak_current = streak["current_streak"]
streak_longest = streak["longest_streak"]
streak_milestone = streak_result.get("milestone") if streak_result else None
except Exception:
pass
# Count step results for this session
step_results = postgres.select("routine_step_results", {"session_id": session_id})
steps_completed = sum(1 for r in step_results if r.get("result") == "completed")
steps_skipped = sum(1 for r in step_results if r.get("result") == "skipped")
try:
step_results = postgres.select("routine_step_results", {"session_id": session_id})
steps_completed = sum(1 for r in step_results if r.get("result") == "completed")
steps_skipped = sum(1 for r in step_results if r.get("result") == "skipped")
except Exception:
pass
# Total completions for this routine
all_completed = postgres.select("routine_sessions", {
"routine_id": session["routine_id"],
"user_uuid": user_uuid,
"status": "completed",
})
try:
all_completed = postgres.select("routine_sessions", {
"routine_id": session["routine_id"],
"user_uuid": user_uuid,
"status": "completed",
})
total_completions = len(all_completed)
except Exception:
pass
result = {
"streak_current": streak["current_streak"] if streak else 1,
"streak_longest": streak["longest_streak"] if streak else 1,
"streak_current": streak_current,
"streak_longest": streak_longest,
"session_duration_minutes": duration_minutes,
"total_completions": len(all_completed),
"total_completions": total_completions,
"steps_completed": steps_completed,
"steps_skipped": steps_skipped,
}
@@ -339,6 +355,8 @@ def register(app):
if not routine:
return flask.jsonify({"error": "not found"}), 404
active = postgres.select_one("routine_sessions", {"user_uuid": user_uuid, "status": "active"})
if not active:
active = postgres.select_one("routine_sessions", {"user_uuid": user_uuid, "status": "paused"})
if active:
return flask.jsonify({"error": "already have active session", "session_id": active["id"]}), 409
steps = postgres.select(