Skip to content

Commit 5e8dc62

Browse files
committed
Score calc fix and filters disable
1 parent 8d393c3 commit 5e8dc62

File tree

6 files changed

+95
-40
lines changed

6 files changed

+95
-40
lines changed

app/api/banner/[username]/route.tsx

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import { type NextRequest, NextResponse } from "next/server"
2-
import { fetchGitHubUser, fetchUserRepos } from "@/lib/github-api"
3-
import { calculateGitScore, generateBadges } from "@/lib/score-calculator"
2+
import { fetchGitHubUser, fetchUserRepos, getCachedScore } from "@/lib/github-api"
43

54
export async function GET(request: NextRequest, { params }: { params: { username: string } }) {
65
try {
76
const userData = await fetchGitHubUser(params.username)
87
const reposData = await fetchUserRepos(params.username)
9-
const score = calculateGitScore(userData, reposData)
10-
const badges = generateBadges(userData, reposData).slice(0, 3) // Mostrar apenas 3 badges no banner
8+
const { score, badges } = await getCachedScore(params.username)
119

1210
const svg = generateScoreCard({
1311
username: userData.login,
@@ -16,8 +14,8 @@ export async function GET(request: NextRequest, { params }: { params: { username
1614
avatar: userData.avatar_url,
1715
followers: userData.followers,
1816
repos: userData.public_repos,
19-
stars: reposData.reduce((acc, repo) => acc + repo.stargazers_count, 0),
20-
badges,
17+
stars: reposData.reduce((acc: number, repo: any) => acc + repo.stargazers_count, 0),
18+
badges: badges.slice(0, 3),
2119
})
2220

2321
return new NextResponse(svg, {

app/leaderboard/page.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@ export default function LeaderboardPage({ searchParams }: PageProps) {
2727
</div>
2828

2929
{/* Filters */}
30-
<div className="mb-8">
30+
{/* Desativado temporariamente */}
31+
{/* <div className="mb-8 mx-auto max-w-6xl">
3132
<LeaderboardFilters />
32-
</div>
33+
</div> */}
3334

3435
{/* Content */}
3536
<Suspense fallback={<LeaderboardSkeleton />}>

app/user/[username]/page.tsx

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import { UserBadges } from "@/components/user-badges"
44
import { UserStats } from "@/components/user-stats"
55
import { UserRepos } from "@/components/user-repos"
66
import { ReadmeMD } from "@/components/readme-md"
7-
import { calculateGitScore, generateBadges } from "@/lib/score-calculator"
8-
import { fetchGitHubUser, fetchUserRepos } from "@/lib/github-api"
7+
import { fetchGitHubUser, fetchUserRepos, getCachedScore } from "@/lib/github-api"
98

109
interface PageProps {
1110
params: {
@@ -18,8 +17,7 @@ export default async function UserPage({ params }: PageProps) {
1817
const userData = await fetchGitHubUser(params.username)
1918
const reposData = await fetchUserRepos(params.username)
2019

21-
const score = calculateGitScore(userData, reposData)
22-
const badges = generateBadges(userData, reposData)
20+
const { score, badges } = await getCachedScore(params.username)
2321

2422
return (
2523
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">

components/leaderboard-filters.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export function LeaderboardFilters() {
8383
<div className="space-y-4">
8484
{/* Filter Toggle */}
8585
<div className="flex items-center justify-between">
86-
<Button variant="outline" onClick={() => setShowFilters(!showFilters)} className="flex items-center space-x-2">
86+
<Button variant="outline" onClick={() => setShowFilters(!showFilters)} className="flex items-center space-x-4">
8787
<Filter className="h-4 w-4" />
8888
<span>Filtros Avançados</span>
8989
</Button>

lib/github-api.ts

Lines changed: 60 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { calculateGitScore, generateBadges } from "@/lib/score-calculator"
2+
13
const GITHUB_TOKEN = process.env.GITHUB_TOKEN || "";
24

35
interface NextFetchRequestConfig {
@@ -9,6 +11,63 @@ interface ExtendedRequestInit extends RequestInit {
911
next?: NextFetchRequestConfig;
1012
}
1113

14+
// Cache para scores calculados
15+
const scoreCache = new Map<string, {
16+
score: number;
17+
badges: any[];
18+
timestamp: number;
19+
userDataHash: string;
20+
}>()
21+
22+
const CACHE_DURATION = 1000 * 60 * 60 * 24 // 24 horas
23+
24+
// Função para gerar hash dos dados do usuário (para detectar mudanças)
25+
function generateUserDataHash(userData: any, reposData: any[]): string {
26+
const hashData = {
27+
followers: userData.followers,
28+
public_repos: userData.public_repos,
29+
public_gists: userData.public_gists,
30+
stars: reposData.reduce((acc: number, repo: any) => acc + repo.stargazers_count, 0),
31+
forks: reposData.reduce((acc: number, repo: any) => acc + repo.forks_count, 0),
32+
lastPush: reposData.length > 0 ? reposData[0].pushed_at : null,
33+
}
34+
return JSON.stringify(hashData)
35+
}
36+
37+
// Função para obter score com cache
38+
export async function getCachedScore(username: string): Promise<{ score: number; badges: any[] }> {
39+
const now = Date.now()
40+
const userKey = username.toLowerCase()
41+
42+
const userData = await fetchGitHubUser(username)
43+
const reposData = await fetchUserRepos(username)
44+
const currentHash = generateUserDataHash(userData, reposData)
45+
46+
// Verificar se existe cache válido
47+
const cached = scoreCache.get(userKey)
48+
if (cached &&
49+
(now - cached.timestamp) < CACHE_DURATION &&
50+
cached.userDataHash === currentHash) {
51+
console.log(`Using cached score for ${username}`)
52+
return { score: cached.score, badges: cached.badges }
53+
}
54+
55+
// Calcular novo score
56+
// console.log(`Calculating new score for ${username}`)
57+
const score = calculateGitScore(userData, reposData)
58+
const badges = generateBadges(userData, reposData)
59+
60+
// Armazenar no cache
61+
scoreCache.set(userKey, {
62+
score,
63+
badges,
64+
timestamp: now,
65+
userDataHash: currentHash
66+
})
67+
68+
return { score, badges }
69+
}
70+
1271
export async function fetchGitHubUser(username: string) {
1372
const response = await fetch(`https://api.github.com/users/${username}`, {
1473
headers: {
@@ -103,27 +162,6 @@ export async function fetchPopularDevelopers(location?: string, language?: strin
103162
return response.json()
104163
}
105164

106-
// Função para calcular GitScore baseado nos dados do usuário e repositórios
107-
export function calculateGitScore(user: any, repos: any[]) {
108-
const totalStars = repos.reduce((acc, repo) => acc + repo.stargazers_count, 0)
109-
const totalForks = repos.reduce((acc, repo) => acc + repo.forks_count, 0)
110-
const publicRepos = user.public_repos || repos.length
111-
const followers = user.followers || 0
112-
const accountAge = Math.max(1, Math.floor((Date.now() - new Date(user.created_at).getTime()) / (1000 * 60 * 60 * 24 * 365)))
113-
114-
// Cálculo do score baseado em múltiplos fatores
115-
const starScore = Math.sqrt(totalStars) * 10
116-
const forkScore = Math.sqrt(totalForks) * 8
117-
const repoScore = Math.sqrt(publicRepos) * 15
118-
const followerScore = Math.sqrt(followers) * 12
119-
const consistencyBonus = Math.min(100, (publicRepos / accountAge) * 20)
120-
121-
const rawScore = starScore + forkScore + repoScore + followerScore + consistencyBonus
122-
123-
// Normalizar para uma escala mais intuitiva
124-
return Math.round(rawScore)
125-
}
126-
127165
// Função para obter rank baseado no score
128166
export function getRankFromScore(score: number): string {
129167
if (score >= 4000) return "SS+"
@@ -160,7 +198,7 @@ export async function fetchLeaderboardData(filters: {
160198
fetchUserRepos(dev.login)
161199
])
162200

163-
const score = calculateGitScore(userDetails, repos)
201+
const { score, badges } = await getCachedScore(dev.login)
164202
const rank = getRankFromScore(score)
165203

166204
// Filtrar por score se especificado

lib/score-calculator.ts

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,24 @@ export function calculateGitScore(userData: any, reposData: any[]) {
55
const publicRepos = userData.public_repos
66
const publicGists = userData.public_gists
77

8-
// Simular contribuições (em uma implementação real, usaria GraphQL)
9-
const contributions = Math.floor(Math.random() * 1000) + 200
8+
// Calcular contribuições baseado em dados existentes ao invés de aleatório
9+
const contributions = Math.min(
10+
reposData.reduce((acc, repo) => acc + repo.open_issues_count, 0) * 10 +
11+
publicRepos * 15 +
12+
publicGists * 5,
13+
2000
14+
)
1015

11-
// Calcular dias desde último commit (simulado)
12-
const daysSinceLastCommit = Math.floor(Math.random() * 30)
16+
// Calcular "frescor" baseado na data do último push (ao invés de aleatório)
17+
const now = new Date()
18+
const lastPushDates = reposData
19+
.filter(repo => repo.pushed_at)
20+
.map(repo => new Date(repo.pushed_at))
21+
.sort((a, b) => b.getTime() - a.getTime())
22+
23+
const daysSinceLastCommit = lastPushDates.length > 0
24+
? Math.min(Math.floor((now.getTime() - lastPushDates[0].getTime()) / (1000 * 60 * 60 * 24)), 365)
25+
: 365
1326

1427
const score = Math.max(
1528
0,
@@ -28,7 +41,14 @@ export function calculateGitScore(userData: any, reposData: any[]) {
2841
export function generateBadges(userData: any, reposData: any[]) {
2942
const stars = reposData.reduce((acc, repo) => acc + repo.stargazers_count, 0)
3043
const forks = reposData.reduce((acc, repo) => acc + repo.forks_count, 0)
31-
const contributions = Math.floor(Math.random() * 1000) + 200
44+
45+
// Calcular contribuições baseado em dados existentes ao invés de aleatório
46+
const contributions = Math.min(
47+
reposData.reduce((acc, repo) => acc + repo.open_issues_count, 0) * 10 +
48+
userData.public_repos * 15 +
49+
userData.public_gists * 5,
50+
2000
51+
)
3252

3353
// Calcular linguagens únicas
3454
const languages = new Set(reposData.filter((repo) => repo.language).map((repo) => repo.language))

0 commit comments

Comments
 (0)