Skip to content

Commit dd5f6a2

Browse files
codergautamclaude
andcommitted
Fix daily leaderboard delta calculation for single stats
- Use most recent stat before 24h window instead of oldest ever - Consistent logic for both ELO and XP calculations - Shows actual gain since last activity 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 62ab9ba commit dd5f6a2

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

api/leaderboard.js

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,26 +65,31 @@ async function getDailyLeaderboard(isXp = true) {
6565
statCount: { $sum: 1 }
6666
}
6767
},
68-
// STEP 3.5: For users with only one stat in 24h, get their oldest ever stat
68+
// STEP 3.5: For users with only one stat in 24h, get their most recent stat before 24h window
6969
{
7070
$lookup: {
7171
from: 'userstats',
72-
let: { userId: '$_id', statCount: '$statCount' },
72+
let: {
73+
userId: '$_id',
74+
statCount: '$statCount',
75+
dayAgo: new Date(Date.now() - (24 * 60 * 60 * 1000))
76+
},
7377
pipeline: [
7478
{
7579
$match: {
7680
$expr: {
7781
$and: [
7882
{ $eq: ['$userId', '$$userId'] },
79-
{ $eq: ['$$statCount', 1] }
83+
{ $eq: ['$$statCount', 1] },
84+
{ $lt: ['$timestamp', '$$dayAgo'] }
8085
]
8186
}
8287
}
8388
},
84-
{ $sort: { timestamp: 1 } },
89+
{ $sort: { timestamp: -1 } },
8590
{ $limit: 1 }
8691
],
87-
as: 'oldestStat'
92+
as: 'previousStat'
8893
}
8994
},
9095
// STEP 4: Calculate deltas and add user lookup in single stage
@@ -116,8 +121,8 @@ async function getDailyLeaderboard(isXp = true) {
116121
then: { $subtract: [`$latestStat.${scoreField}`, `$earliestStat.${scoreField}`] },
117122
else: {
118123
$cond: {
119-
if: { $gt: [{ $size: '$oldestStat' }, 0] },
120-
then: { $subtract: [`$latestStat.${scoreField}`, { $arrayElemAt: [`$oldestStat.${scoreField}`, 0] }] },
124+
if: { $gt: [{ $size: '$previousStat' }, 0] },
125+
then: { $subtract: [`$latestStat.${scoreField}`, { $arrayElemAt: [`$previousStat.${scoreField}`, 0] }] },
121126
else: 0
122127
}
123128
}

0 commit comments

Comments
 (0)