File size: 6,053 Bytes
507973e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""Phase V: Stats service — streak calculation, achievement checks, heatmap data."""
import logging
from datetime import date, datetime, timezone

from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select

from ..models.stats import Achievement, DailyCompletion, UserStats

logger = logging.getLogger(__name__)

ACHIEVEMENT_LABELS = {
    "on_fire": "🔥 On Fire",
    "centurion": "💪 Centurion",
    "speed_runner": "⚡ Speed Runner",
    "night_owl": "🌙 Night Owl",
    "planner": "📅 Planner",
    "consistent": "🎯 Consistent",
}

ACHIEVEMENT_DESCRIPTIONS = {
    "on_fire": "7-day consecutive completion streak",
    "centurion": "Completed 100 tasks",
    "speed_runner": "5+ tasks completed in a single day",
    "night_owl": "Completed a task after 10 PM",
    "planner": "Completed a task before its due date",
    "consistent": "30-day consecutive completion streak",
}


async def _get_or_create_stats(session: AsyncSession, user_id: str) -> UserStats:
    result = await session.execute(select(UserStats).where(UserStats.user_id == user_id))
    stats = result.scalar_one_or_none()
    if not stats:
        stats = UserStats(user_id=user_id)
        session.add(stats)
        await session.flush()
    return stats


async def _upsert_daily_completion(session: AsyncSession, user_id: str, today: date) -> int:
    result = await session.execute(
        select(DailyCompletion).where(
            DailyCompletion.user_id == user_id,
            DailyCompletion.date == today,
        )
    )
    dc = result.scalar_one_or_none()
    if dc:
        dc.count += 1
    else:
        dc = DailyCompletion(user_id=user_id, date=today, count=1)
        session.add(dc)
    await session.flush()
    return dc.count


async def _unlock_achievement(session: AsyncSession, user_id: str, achievement_type: str) -> bool:
    result = await session.execute(
        select(Achievement).where(
            Achievement.user_id == user_id,
            Achievement.achievement_type == achievement_type,
        )
    )
    if result.scalar_one_or_none():
        return False  # already unlocked
    session.add(Achievement(user_id=user_id, achievement_type=achievement_type))
    await session.flush()
    logger.info("Achievement unlocked: user=%s type=%s", user_id, achievement_type)
    return True


async def record_completion(
    session: AsyncSession, user_id: str, task_id: int, task_data: dict
) -> None:
    """Record a task completion: update streak, daily count, check achievements."""
    today = date.today()
    now = datetime.now()

    # Update daily completion count
    daily_count = await _upsert_daily_completion(session, user_id, today)

    # Update user stats
    stats = await _get_or_create_stats(session, user_id)
    stats.total_completed += 1

    if stats.last_active_date is None:
        stats.current_streak = 1
    elif stats.last_active_date == today:
        pass  # already counted today
    elif (today - stats.last_active_date).days == 1:
        stats.current_streak += 1
    else:
        stats.current_streak = 1  # streak broken

    stats.longest_streak = max(stats.current_streak, stats.longest_streak)
    stats.last_active_date = today
    stats.updated_at = datetime.utcnow()
    session.add(stats)

    # Check achievements
    if stats.current_streak >= 7:
        await _unlock_achievement(session, user_id, "on_fire")
    if stats.current_streak >= 30:
        await _unlock_achievement(session, user_id, "consistent")
    if stats.total_completed >= 100:
        await _unlock_achievement(session, user_id, "centurion")
    if daily_count >= 5:
        await _unlock_achievement(session, user_id, "speed_runner")
    if now.hour >= 22:
        await _unlock_achievement(session, user_id, "night_owl")
    if task_data.get("due_date"):
        try:
            due = datetime.fromisoformat(task_data["due_date"])
            if now < due:
                await _unlock_achievement(session, user_id, "planner")
        except (ValueError, TypeError):
            pass

    await session.commit()


async def get_stats(session: AsyncSession, user_id: str) -> dict:
    """Return full stats including heatmap data for the last 12 months."""
    from datetime import timedelta

    stats = await _get_or_create_stats(session, user_id)

    # Heatmap: last 365 days
    one_year_ago = date.today().replace(year=date.today().year - 1)
    result = await session.execute(
        select(DailyCompletion).where(
            DailyCompletion.user_id == user_id,
            DailyCompletion.date >= one_year_ago,
        )
    )
    completions = result.scalars().all()
    heatmap = [{"date": str(dc.date), "count": dc.count} for dc in completions]

    # Achievements
    ach_result = await session.execute(
        select(Achievement).where(Achievement.user_id == user_id)
    )
    achievements = [
        {
            "type": a.achievement_type,
            "label": ACHIEVEMENT_LABELS.get(a.achievement_type, a.achievement_type),
            "description": ACHIEVEMENT_DESCRIPTIONS.get(a.achievement_type, ""),
            "unlocked_at": a.unlocked_at.isoformat(),
        }
        for a in ach_result.scalars().all()
    ]

    return {
        "total_completed": stats.total_completed,
        "current_streak": stats.current_streak,
        "longest_streak": stats.longest_streak,
        "last_active_date": str(stats.last_active_date) if stats.last_active_date else None,
        "heatmap": heatmap,
        "achievements": achievements,
    }


async def get_achievements(session: AsyncSession, user_id: str) -> list:
    result = await session.execute(
        select(Achievement).where(Achievement.user_id == user_id)
    )
    return [
        {
            "type": a.achievement_type,
            "label": ACHIEVEMENT_LABELS.get(a.achievement_type, a.achievement_type),
            "description": ACHIEVEMENT_DESCRIPTIONS.get(a.achievement_type, ""),
            "unlocked_at": a.unlocked_at.isoformat(),
        }
        for a in result.scalars().all()
    ]