File size: 6,065 Bytes
3eab45c
 
 
 
 
 
 
e0ce113
3eab45c
 
 
 
 
 
229d06d
 
3eab45c
 
 
 
 
 
 
 
 
 
 
 
 
e0ce113
 
 
 
 
 
 
 
229d06d
e0ce113
 
 
 
 
3eab45c
9831def
3eab45c
 
 
 
9831def
3eab45c
 
9831def
e0ce113
 
 
9831def
 
 
 
 
 
 
 
 
 
e0ce113
 
 
9831def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0ce113
9831def
 
 
 
 
e0ce113
 
9831def
 
 
 
 
 
 
 
 
 
 
 
 
 
3eab45c
9831def
3eab45c
e0ce113
9831def
 
 
 
3eab45c
e0ce113
 
 
 
3eab45c
 
9831def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3eab45c
 
 
 
9831def
229d06d
 
3eab45c
 
9831def
 
 
 
 
3eab45c
 
9831def
 
3eab45c
 
9831def
3eab45c
260832f
3eab45c
9831def
 
 
 
 
3eab45c
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
178
179
180
181
182
/**
 * Gamification Queries - Drizzle ORM
 */

import { db } from "@/db";
import { trophies, users, issues } from "@/db/schema";
import { eq, desc, and, count, not, sql } from "drizzle-orm";
import { streakCache, calendarCache } from "@/lib/cache";

// =============================================================================
// Badges / Trophies
// =============================================================================

export async function getUserBadges(username: string) {
    // Case-insensitive lookup - GitHub usernames are case-insensitive
    const user = await db.select().from(users).where(sql`LOWER(${users.username}) = LOWER(${username})`).limit(1);
    if (!user[0]) return [];

    return db.select()
        .from(trophies)
        .where(eq(trophies.userId, user[0].id))
        .orderBy(desc(trophies.awardedAt));
}

// =============================================================================
// Streak
// =============================================================================

export async function getUserStreak(username: string) {
    const cacheKey = `streak:${username}`;

    // Check cache first
    const cached = streakCache.get(cacheKey);
    if (cached) {
        return cached;
    }

    const user = await db.select().from(users).where(sql`LOWER(${users.username}) = LOWER(${username})`).limit(1);
    if (!user[0]) {
        const emptyResult = { current_streak: 0, longest_streak: 0, is_active: false, total_contribution_days: 0 };
        streakCache.set(cacheKey, emptyResult);
        return emptyResult;
    }

    // Get all activity dates (from issues created by this user)
    const activity = await db.select({
        createdAt: issues.createdAt
    })
        .from(issues)
        .where(eq(issues.authorName, username))
        .orderBy(desc(issues.createdAt));

    if (activity.length === 0) {
        const emptyResult = { current_streak: 0, longest_streak: 0, is_active: false, total_contribution_days: 0 };
        streakCache.set(cacheKey, emptyResult);
        return emptyResult;
    }

    // Get unique dates (YYYY-MM-DD format)
    const activityDates = [...new Set(
        activity
            .map(a => a.createdAt?.substring(0, 10))
            .filter(Boolean)
    )].sort().reverse(); // Most recent first

    if (activityDates.length === 0) {
        const emptyResult = { current_streak: 0, longest_streak: 0, is_active: false, total_contribution_days: 0 };
        streakCache.set(cacheKey, emptyResult);
        return emptyResult;
    }

    const today = new Date().toISOString().substring(0, 10);
    const yesterday = new Date(Date.now() - 86400000).toISOString().substring(0, 10);

    // Calculate current streak
    let currentStreak = 0;
    let isActive = false;

    // Check if contributed today or yesterday
    if (activityDates[0] === today) {
        isActive = true;
        currentStreak = 1;
    } else if (activityDates[0] === yesterday) {
        isActive = false; // Need to contribute today to keep streak
        currentStreak = 1;
    } else {
        // Streak is broken
        const brokenResult = {
            current_streak: 0,
            longest_streak: calculateLongestStreak(activityDates),
            is_active: false,
            total_contribution_days: activityDates.length
        };
        streakCache.set(cacheKey, brokenResult);
        return brokenResult;
    }

    // Count consecutive days
    for (let i = 1; i < activityDates.length; i++) {
        const current = new Date(activityDates[i - 1]);
        const prev = new Date(activityDates[i]);
        const diffDays = Math.floor((current.getTime() - prev.getTime()) / 86400000);

        if (diffDays === 1) {
            currentStreak++;
        } else {
            break;
        }
    }

    const longestStreak = calculateLongestStreak(activityDates);

    const result = {
        current_streak: currentStreak,
        longest_streak: Math.max(currentStreak, longestStreak),
        is_active: isActive,
        total_contribution_days: activityDates.length
    };

    // Cache the result
    streakCache.set(cacheKey, result);
    return result;
}

// Helper function to calculate longest streak
function calculateLongestStreak(sortedDates: string[]): number {
    if (sortedDates.length === 0) return 0;

    // Sort dates ascending for this calculation
    const dates = [...sortedDates].sort();

    let longest = 1;
    let current = 1;

    for (let i = 1; i < dates.length; i++) {
        const today = new Date(dates[i]);
        const yesterday = new Date(dates[i - 1]);
        const diffDays = Math.floor((today.getTime() - yesterday.getTime()) / 86400000);

        if (diffDays === 1) {
            current++;
            longest = Math.max(longest, current);
        } else if (diffDays > 1) {
            current = 1;
        }
        // If diffDays === 0, same day, skip
    }

    return longest;
}

// =============================================================================
// Clean Calendar Data
// =============================================================================

export async function getUserCalendar(username: string, days: number = 365) {
    // Case-insensitive lookup
    const user = await db.select().from(users).where(sql`LOWER(${users.username}) = LOWER(${username})`).limit(1);
    if (!user[0]) return [];

    // Calculate date range
    const endDate = new Date();
    const startDate = new Date(Date.now() - days * 86400000);
    const startDateStr = startDate.toISOString().substring(0, 10);

    // Aggregate issues created by day
    const activity = await db.select({
        date: sql<string>`substr(${issues.createdAt}, 1, 10)`,
        contributions: count()
    })
        .from(issues)
        .where(eq(issues.authorName, username))
        .groupBy(sql`substr(${issues.createdAt}, 1, 10)`)
        .orderBy(sql`substr(${issues.createdAt}, 1, 10)`);

    // Convert to heatmap format
    return activity.map(a => ({
        date: a.date,
        contributions: Number(a.contributions)
    }));
}