celo-poll/lib/achievements.ts
2025-12-08 16:31:30 +03:00

62 lines
1.8 KiB
TypeScript

import { redis } from './redis'
import { ACHIEVEMENTS, UserAchievement } from '@/types/achievement'
export async function checkAndUnlockAchievements(fid: string, event: {
type: 'vote' | 'win' | 'comment' | 'follow' | 'referral'
value?: number
}) {
const unlocked: string[] = []
for (const achievement of ACHIEVEMENTS) {
const key = `achievement:${fid}:${achievement.id}`
const isUnlocked = await redis.get(key)
if (isUnlocked) continue
const progress = await getProgress(fid, achievement.id, event)
if (progress >= achievement.requirement) {
await redis.set(key, new Date().toISOString())
unlocked.push(achievement.id)
}
}
return unlocked
}
async function getProgress(fid: string, achievementId: string, event: any): Promise<number> {
if (achievementId.startsWith('voter_')) {
return parseInt(await redis.get(`user:${fid}:votes:count`) as string || '0')
}
if (achievementId.startsWith('winner_')) {
return parseInt(await redis.get(`user:${fid}:wins:count`) as string || '0')
}
if (achievementId.startsWith('streak_')) {
return parseInt(await redis.get(`user:${fid}:streak`) as string || '0')
}
if (achievementId.startsWith('social_')) {
return parseInt(await redis.get(`user:${fid}:comments:count`) as string || '0')
}
if (achievementId === 'referral_5') {
return parseInt(await redis.get(`referral:user:${fid}:completed`) as string || '0')
}
return 0
}
export async function getUserAchievements(fid: string) {
const unlocked = []
for (const achievement of ACHIEVEMENTS) {
const key = `achievement:${fid}:${achievement.id}`
const unlockedAt = await redis.get(key)
if (unlockedAt) {
unlocked.push({
...achievement,
unlockedAt: unlockedAt as string,
})
}
}
return unlocked
}