feat(leaderboard): cleaned date related and unused code

This commit is contained in:
lucasnevespereira
2025-08-10 19:41:06 +02:00
parent be91c444cd
commit a678a3a748
11 changed files with 49 additions and 62 deletions
+1
View File
@@ -1681,6 +1681,7 @@ export default {
},
},
commons: {
just_now: "just now",
signup_with: "Sign up with {provider}",
signin_with: "Sign in with {provider}",
signup: "Sign up",
+1
View File
@@ -818,6 +818,7 @@ export default {
},
},
commons: {
just_now: "ahora mismo",
signup_with: "Registrarse con {provider}",
signin_with: "Iniciar sesión con {provider}",
signup: "Registrarse",
+1
View File
@@ -1707,6 +1707,7 @@ export default {
},
},
commons: {
just_now: "à l'instant",
signup_with: "S'inscrire avec {provider}",
signin_with: "Se connecter avec {provider}",
signup: "S'inscrire",
+1
View File
@@ -1691,6 +1691,7 @@ export default {
},
commons: {
just_now: "agora mesmo",
signup_with: "Inscrever com {provider}",
signin_with: "Entrar com {provider}",
signup: "Inscrever-se",
+1
View File
@@ -1682,6 +1682,7 @@ export default {
},
},
commons: {
just_now: "только что",
signup_with: "Регистрация через {provider}",
signin_with: "Вход через {provider}",
signup: "Регистрация",
+1
View File
@@ -813,6 +813,7 @@ export default {
},
},
commons: {
just_now: "刚刚",
signup_with: "使用 {provider} 注册",
signin_with: "使用 {provider} 登录",
signup: "注册",
@@ -1,5 +1,6 @@
"use server";
import dayjs from "dayjs";
import { prisma } from "@/shared/lib/prisma";
import { actionClient } from "@/shared/api/safe-actions";
@@ -47,22 +48,17 @@ export const getTopWorkoutUsersAction = actionClient.action(async () => {
const users: TopWorkoutUser[] = topUsers.map((user) => {
const totalWorkouts = user._count.WorkoutSession;
const firstWorkout = user.WorkoutSession[0];
const lastWorkout = user.WorkoutSession[0];
const lastWorkoutAt = lastWorkout?.endedAt || lastWorkout?.startedAt || null;
// Calculate weeks since first workout or account creation
const startDate = firstWorkout?.startedAt || user.createdAt;
const now = new Date();
const weeksSinceStart = Math.max(1, Math.ceil((now.getTime() - startDate.getTime()) / (7 * 24 * 60 * 60 * 1000)));
const startDate = user.createdAt;
const weeksSinceStart = Math.max(1, Math.ceil(dayjs().diff(dayjs(startDate), "week", true)));
// Calculate average workouts per week
const averageWorkoutsPerWeek = Math.round((totalWorkouts / weeksSinceStart) * 10) / 10; // Round to 1 decimal
const averageWorkoutsPerWeek = Math.round((totalWorkouts / weeksSinceStart) * 10) / 10;
return {
userId: user.id,
userName: user.name,
userEmail: user.email,
userImage: user.image,
totalWorkouts,
lastWorkoutAt: lastWorkoutAt,
@@ -5,15 +5,14 @@ import { useQuery } from "@tanstack/react-query";
import { getTopWorkoutUsersAction } from "../actions/get-top-workout-users.action";
export interface UseTopWorkoutUsersOptions {
limit?: number;
refetchInterval?: number;
}
export function useTopWorkoutUsers(options: UseTopWorkoutUsersOptions = {}) {
const { limit = 20, refetchInterval } = options;
const { refetchInterval } = options;
return useQuery({
queryKey: ["top-workout-users", limit],
queryKey: ["top-workout-users"],
queryFn: async () => {
const result = await getTopWorkoutUsersAction();
return result?.data || [];
-1
View File
@@ -1,7 +1,6 @@
export interface TopWorkoutUser {
userId: string;
userName: string;
userEmail: string;
userImage: string | null;
totalWorkouts: number;
lastWorkoutAt: Date | null;
@@ -2,8 +2,7 @@
import React from "react";
import Image from "next/image";
import { Trophy, Medal, Award } from "lucide-react";
import {Trophy, Medal, Award} from "lucide-react"
import { useCurrentLocale, useI18n } from "locales/client";
import { formatDateShort, formatRelativeTime } from "@/shared/lib/date";
@@ -12,55 +11,38 @@ import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
const getRankIcon = (rank: number) => {
switch (rank) {
case 1:
return <Trophy className="w-6 h-6 text-yellow-500" />;
case 2:
return <Medal className="w-6 h-6 text-gray-400" />;
case 3:
return <Award className="w-6 h-6 text-amber-600" />;
default:
return <span className="w-6 h-6 flex items-center justify-center text-sm font-bold text-gray-500">#{rank}</span>;
}
};
const getRankBadge = (rank: number, t: any) => {
switch (rank) {
case 1:
return <Badge className="bg-yellow-500 text-white border-yellow-600">{t("leaderboard.champion_badge")}</Badge>;
case 2:
return <Badge className="bg-slate-500 text-white border-slate-600">{t("leaderboard.runner_up_badge")}</Badge>;
case 3:
return <Badge className="bg-amber-600 text-white border-amber-700">{t("leaderboard.third_place_badge")}</Badge>;
default:
return null;
}
};
const LeaderboardItem: React.FC<{ user: TopWorkoutUser; rank: number }> = ({ user, rank }) => {
const t = useI18n();
const locale = useCurrentLocale();
const dicebearUrl = `https://api.dicebear.com/7.x/micah/svg?seed=${encodeURIComponent(user.userId)}&backgroundColor=b6e3f4,c0aede,d1d4f9,ffd5dc,ffdfbf`;
const generateAvatarUrl = (seed: string) => {
return `https://api.dicebear.com/7.x/micah/svg?seed=${encodeURIComponent(seed)}&backgroundColor=b6e3f4,c0aede,d1d4f9,ffd5dc,ffdfbf`;
};
const getRankIcon = (rank: number) => {
switch (rank) {
case 1:
return <Trophy className="w-6 h-6 text-yellow-500" />;
case 2:
return <Medal className="w-6 h-6 text-gray-400" />;
case 3:
return <Award className="w-6 h-6 text-amber-600" />;
default:
return <span className="w-6 h-6 flex items-center justify-center text-sm font-bold text-gray-500">#{rank}</span>;
}
};
// Use userId as seed for consistency, fallback to userName or email
const avatarSeed = user.userId || user.userName || user.userEmail;
const dicebearUrl = generateAvatarUrl(avatarSeed);
const getRankBadge = (rank: number) => {
switch (rank) {
case 1:
return <Badge className="bg-yellow-500 text-white border-yellow-600">{t("leaderboard.champion_badge")}</Badge>;
case 2:
return <Badge className="bg-slate-500 text-white border-slate-600">{t("leaderboard.runner_up_badge")}</Badge>;
case 3:
return <Badge className="bg-amber-600 text-white border-amber-700">{t("leaderboard.third_place_badge")}</Badge>;
default:
return null;
}
};
const formatMemberSince = (date: Date) => {
return formatDateShort(date, locale);
};
const formatLastWorkout = (date: Date | null) => {
if (!date) return null
return formatRelativeTime(date, locale);
};
return (
<div className="flex items-center gap-4 p-6 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
{/* Rank */}
@@ -94,15 +76,15 @@ const LeaderboardItem: React.FC<{ user: TopWorkoutUser; rank: number }> = ({ use
<h3 className="font-semibold text-gray-900 dark:text-gray-100 truncate">
{user.userName}
</h3>
{rank <= 3 && getRankBadge(rank, t)}
{rank <= 3 && getRankBadge(rank)}
</div>
<div className="space-y-0.5">
<p className="text-xs text-slate-400 dark:text-gray-300 truncate">
{t("leaderboard.member_since")} {formatMemberSince(user.memberSince)}
{t("leaderboard.member_since")} {formatDateShort(user.memberSince, locale)}
</p>
{user.lastWorkoutAt && (
<p className="text-xs text-slate-300 dark:text-gray-400 truncate">
{t("leaderboard.last_workout")} {formatLastWorkout(user.lastWorkoutAt)}
{t("leaderboard.last_workout")} {formatRelativeTime(user.lastWorkoutAt, locale, t("commons.just_now"))}
</p>
)}
</div>
+8 -3
View File
@@ -64,21 +64,26 @@ export const formatDateShort = (date: string | Date, locale: string = "en"): str
/**
* Format relative time (e.g., "2 hours ago", "3 days ago")
*/
export const formatRelativeTime = (date: string | Date | null, locale: string = "en"): string | null => {
export const formatRelativeTime = (
date: string | Date | null,
locale: string = "en",
justNowText: string = "just now"
): string | null => {
if (!date) return null;
const target = dayjs(date).locale(locale);
const now = dayjs().locale(locale);
// Safety check: if date is in the future, treat as "just now"
if (target.isAfter(now)) {
console.warn("date is in the future:", target.format(), "treating as \"just now\"");
return "just now";
return justNowText;
}
// If less than 1 minute ago, show "just now" instead of "in a few seconds"
if (now.diff(target, "minute") < 1) {
return "just now";
return justNowText;
}
return target.fromNow();