"""Points, streaks and badges for medication adherence.""" from datetime import datetime, timedelta, date from sqlalchemy.orm import Session from database import User, DoseEvent, Badge POINTS_ON_TIME = 10 POINTS_LATE = 5 ON_TIME_GRACE_MIN = 30 # taken within 30 min of schedule == on time # Badge catalogue. metric is one of: doses (lifetime taken), streak (consecutive # days), points (lifetime points). Each has a threshold the user must reach. BADGE_DEFS = [ {"code": "first_dose", "emoji": "🎉", "label": "First Step", "description": "Take your very first dose", "metric": "doses", "threshold": 1}, {"code": "10_doses", "emoji": "💪", "label": "On a Roll", "description": "Take 10 doses", "metric": "doses", "threshold": 10}, {"code": "50_doses", "emoji": "🏅", "label": "Half Century", "description": "Take 50 doses", "metric": "doses", "threshold": 50}, {"code": "100_doses", "emoji": "🏆", "label": "Centurion", "description": "Take 100 doses", "metric": "doses", "threshold": 100}, {"code": "3_day_streak", "emoji": "✨", "label": "Getting Steady", "description": "Keep a 3-day streak", "metric": "streak", "threshold": 3}, {"code": "7_day_streak", "emoji": "🔥", "label": "Week Warrior", "description": "Keep a 7-day streak", "metric": "streak", "threshold": 7}, {"code": "30_day_streak", "emoji": "⭐", "label": "Monthly Master", "description": "Keep a 30-day streak", "metric": "streak", "threshold": 30}, {"code": "points_100", "emoji": "💯", "label": "Century Club", "description": "Earn 100 points", "metric": "points", "threshold": 100}, {"code": "points_500", "emoji": "👑", "label": "Adherence Royalty", "description": "Earn 500 points", "metric": "points", "threshold": 500}, ] _DEF_BY_CODE = {d["code"]: d for d in BADGE_DEFS} def _award_badge(db: Session, user_id: int, code: str) -> bool: """Insert a badge if not present. Returns True if newly awarded.""" exists = db.query(Badge).filter(Badge.user_id == user_id, Badge.code == code).first() if exists: return False db.add(Badge(user_id=user_id, code=code)) return True def compute_streak(db: Session, user_id: int) -> int: """Consecutive days (ending today/yesterday) with at least one taken dose.""" taken = db.query(DoseEvent).filter( DoseEvent.user_id == user_id, DoseEvent.status == "taken", ).all() taken_days = {e.scheduled_for.date() for e in taken if e.scheduled_for} if not taken_days: return 0 streak = 0 day = date.today() if day not in taken_days: day = day - timedelta(days=1) while day in taken_days: streak += 1 day -= timedelta(days=1) return streak def _doses_taken(db: Session, user_id: int) -> int: return db.query(DoseEvent).filter( DoseEvent.user_id == user_id, DoseEvent.status == "taken" ).count() def _metric_value(db: Session, user: User, metric: str) -> int: if metric == "doses": return _doses_taken(db, user.id) if metric == "streak": return compute_streak(db, user.id) if metric == "points": return user.points or 0 return 0 def award_for_dose(db: Session, user: User, dose: DoseEvent) -> dict: """Award points + any newly-unlocked badges when a dose is marked taken.""" if dose.points_awarded and dose.points_awarded > 0: return {"points_added": 0, "total_points": user.points or 0, "streak": compute_streak(db, user.id), "new_badges": []} delta = abs((datetime.now() - dose.scheduled_for).total_seconds()) / 60.0 points = POINTS_ON_TIME if delta <= ON_TIME_GRACE_MIN else POINTS_LATE dose.points_awarded = points user.points = (user.points or 0) + points db.flush() # so metric values reflect this dose # cache metric values values = { "doses": _doses_taken(db, user.id), "streak": compute_streak(db, user.id), "points": user.points or 0, } new_badges = [] for d in BADGE_DEFS: if values[d["metric"]] >= d["threshold"]: if _award_badge(db, user.id, d["code"]): new_badges.append({"code": d["code"], "label": d["label"], "emoji": d["emoji"]}) db.commit() return { "points_added": points, "total_points": user.points, "streak": values["streak"], "new_badges": new_badges, } def badge_progress(db: Session, user: User) -> list: """All badges with earned status and progress toward the threshold.""" earned = {b.code for b in db.query(Badge).filter(Badge.user_id == user.id).all()} vals = { "doses": _doses_taken(db, user.id), "streak": compute_streak(db, user.id), "points": user.points or 0, } out = [] for d in BADGE_DEFS: cur = vals[d["metric"]] is_earned = d["code"] in earned out.append({ "code": d["code"], "label": d["label"], "emoji": d["emoji"], "description": d["description"], "metric": d["metric"], "threshold": d["threshold"], "current": min(cur, d["threshold"]) if not is_earned else d["threshold"], "earned": is_earned, "remaining": 0 if is_earned else max(0, d["threshold"] - cur), "pct": 100 if is_earned else min(100, round(cur * 100 / d["threshold"])), }) return out def user_stats(db: Session, user: User) -> dict: progress = badge_progress(db, user) return { "points": user.points or 0, "streak": compute_streak(db, user.id), "doses_taken": _doses_taken(db, user.id), "badges": [b for b in progress if b["earned"]], "all_badges": progress, }