Skip to content

Toni grbic/backend profile leaderboard #530

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 27 commits into from
May 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
6bf122b
leaderboard wip
ToniGrbic Apr 23, 2025
ba7d26a
lint fixes
ToniGrbic Apr 23, 2025
fea0c81
build fix
ToniGrbic Apr 24, 2025
8d03fff
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic May 2, 2025
60223f3
cleanup and adjustments
ToniGrbic May 2, 2025
6479a7b
loading spinner
ToniGrbic May 2, 2025
98c9f7d
td cell padding fix
ToniGrbic May 2, 2025
3e4e667
lint fix
ToniGrbic May 2, 2025
c3857e4
added threshold
ToniGrbic May 3, 2025
270f69b
final fixes and refactor into sections
ToniGrbic May 3, 2025
b2adcc3
ErrorMessage component
ToniGrbic May 3, 2025
5597cfd
lint fix
ToniGrbic May 3, 2025
bdc5111
removed unnesseccary select field
ToniGrbic May 3, 2025
06c6f5d
added user guards
ToniGrbic May 3, 2025
b1b80ad
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic May 5, 2025
201edcf
changed images to avatars and final style adjustments
ToniGrbic May 6, 2025
11111a4
white back btn desktop
ToniGrbic May 6, 2025
d8e4864
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic May 7, 2025
d2394f5
add useEffect call for achievement
ToniGrbic May 8, 2025
1047ec7
Merge branch 'main' into ToniGrbic/backend-profile-leaderboard
ToniGrbic May 9, 2025
3ac01a2
fix confirmed user and toast
lovretomic May 9, 2025
326018a
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic May 9, 2025
4972a8d
returned mob back button and fix error message style
ToniGrbic May 9, 2025
dab0a01
increased z index for mobile navigation
ToniGrbic May 9, 2025
1a9f754
fixed error message component
ToniGrbic May 9, 2025
0330d4d
Merge branch 'main' into ToniGrbic/backend-profile-leaderboard
ToniGrbic May 11, 2025
869e23f
Merge branch 'main' into ToniGrbic/backend-profile-leaderboard
lovretomic May 11, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { EventModule } from './event/event.module';
import { FrequentlyAskedQuestionModule } from './frequently-asked-question/frequently-asked-question.module';
import { InterestModule } from './interest/interest.module';
import { JobModule } from './job/job.module';
import { LeaderboardModule } from './leaderboard/leaderboard.module';
import { NotificationModule } from './notification/notification.module';
import { PrismaService } from './prisma.service';
import { RewardModule } from './reward/reward.module';
Expand Down Expand Up @@ -65,6 +66,7 @@ import { UserModule } from './user/user.module';
BoothModule,
ShopModule,
UserModule,
LeaderboardModule,
RewardModule,
AvatarModule,
],
Expand Down
51 changes: 51 additions & 0 deletions apps/api/src/leaderboard/leaderboard.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {
LeaderboardEntryDto,
LeaderboardQueryDto,
LeaderboardResponseDto,
UserRankResponseDto,
} from '@ddays-app/types/src/dto/leaderboard';
import {
Controller,
Get,
Param,
ParseIntPipe,
Query,
Req,
UseGuards,
} from '@nestjs/common';

import { UserGuard } from '../auth/user.guard';
import { LeaderboardService } from './leaderboard.service';

@Controller('leaderboard')
export class LeaderboardController {
constructor(private readonly leaderboardService: LeaderboardService) {}

@Get()
@UseGuards(UserGuard)
async getLeaderboard(
@Query() query: LeaderboardQueryDto,
): Promise<LeaderboardResponseDto> {
return this.leaderboardService.getLeaderboard(query);
}

@Get('top')
@UseGuards(UserGuard)
async getTopUsers(): Promise<LeaderboardEntryDto[]> {
return this.leaderboardService.getTopUsers(3);
}

@Get('user/:id')
@UseGuards(UserGuard)
async getUserRank(
@Param('id', ParseIntPipe) userId: number,
): Promise<UserRankResponseDto> {
return this.leaderboardService.getUserRank(userId);
}

@Get('me')
@UseGuards(UserGuard)
async getCurrentUserRank(@Req() { user }): Promise<UserRankResponseDto> {
return this.leaderboardService.getUserRank(user.id);
}
}
33 changes: 33 additions & 0 deletions apps/api/src/leaderboard/leaderboard.helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
export const levelPoints: Record<number, number> = {
0: 1,
200: 2,
600: 3,
1200: 4,
1900: 5,
};

export function getLevelFromPoints(points: number): {
level: number;
exceeded: number;
} {
const thresholds = Object.keys(levelPoints)
.map(Number)
.sort((a, b) => a - b);

let level = 1;
let currentThreshold = 0;

for (const threshold of thresholds) {
if (points >= threshold) {
level = levelPoints[threshold];
currentThreshold = threshold;
} else {
break;
}
}

return {
level,
exceeded: points - currentThreshold,
};
}
11 changes: 11 additions & 0 deletions apps/api/src/leaderboard/leaderboard.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { PrismaService } from 'src/prisma.service';

import { LeaderboardController } from './leaderboard.controller';
import { LeaderboardService } from './leaderboard.service';

@Module({
controllers: [LeaderboardController],
providers: [LeaderboardService, PrismaService],
})
export class LeaderboardModule {}
145 changes: 145 additions & 0 deletions apps/api/src/leaderboard/leaderboard.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import {
LeaderboardEntryDto,
LeaderboardQueryDto,
LeaderboardResponseDto,
UserRankResponseDto,
} from '@ddays-app/types/src/dto/leaderboard';
import { Injectable } from '@nestjs/common';

import { PrismaService } from '../prisma.service';
import { getLevelFromPoints } from './leaderboard.helper';

@Injectable()
export class LeaderboardService {
constructor(private prisma: PrismaService) {}

async getLeaderboard(
query: LeaderboardQueryDto,
): Promise<LeaderboardResponseDto> {
const { page, pageSize = 5, includeDeleted = false } = query;

const pageNum = Number(page) || 1;
const skip = (pageNum - 1) * pageSize;

const where = {
...(includeDeleted ? {} : { isDeleted: false }),
points: { not: null },
isConfirmed: true,
};

const totalEntries = await this.prisma.user.count({ where });

const users = await this.prisma.user.findMany({
where,
select: {
id: true,
firstName: true,
lastName: true,
points: true,
profilePhotoUrl: true,
},
orderBy: [
{ points: 'desc' },
{ id: 'asc' }, // Add secondary sort by ID to match tie-breaking rule
],
skip,
take: Number(pageSize),
});

const entries = users.map((user, index) => {
const rank = skip + index + 1;

return {
id: user.id,
name: `${user.firstName} ${user.lastName}`,
level: getLevelFromPoints(user.points || 0).level,
points: user.points || 0,
rank,
profilePhotoUrl: user.profilePhotoUrl,
};
});

return {
entries,
totalEntries,
page,
pageSize,
};
}

async getUserRank(userId: number): Promise<UserRankResponseDto> {
const user = await this.prisma.user.findUnique({
where: { id: userId, isDeleted: false },
select: {
id: true,
firstName: true,
lastName: true,
points: true,
profilePhotoUrl: true,
},
});

if (!user) {
throw new Error('User not found');
}

const usersAbove = await this.prisma.user.count({
where: {
isDeleted: false,
isConfirmed: true,
OR: [
{ points: { gt: user.points || 0 } },
{
AND: [
{ points: user.points || 0 }, // Same points
{ id: { lt: user.id } }, // But created earlier (lower ID)
],
},
],
},
});

const rank = usersAbove + 1;

const formatUser = (u, r): LeaderboardEntryDto => ({
id: u.id,
name: `${u.firstName} ${u.lastName}`,
points: u.points || 0,
rank: r,
level: getLevelFromPoints(u.points || 0).level,
profilePhotoUrl: u.profilePhotoUrl,
});

return {
user: formatUser(user, rank),
};
}

async getTopUsers(count = 3): Promise<LeaderboardEntryDto[]> {
const topUsers = await this.prisma.user.findMany({
where: {
isDeleted: false,
isConfirmed: true,
points: { not: null },
},
orderBy: [{ points: 'desc' }, { id: 'asc' }],
take: count,
select: {
id: true,
firstName: true,
lastName: true,
points: true,
profilePhotoUrl: true,
},
});

return topUsers.map((user, index) => ({
id: user.id,
name: `${user.firstName} ${user.lastName}`,
level: getLevelFromPoints(user.points || 0).level,
points: user.points || 0,
rank: index + 1,
profilePhotoUrl: user.profilePhotoUrl,
}));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,9 @@ export const useAchievementCompleteByName = () => {
whiteSpace: 'nowrap',
},
duration: 3000,
position: 'top-center',
});
},
onError: (error) => {
console.error('Achievement error:', error);
},
},
);
};
19 changes: 19 additions & 0 deletions apps/app/src/api/leaderboard/useGetTopUsers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useQuery } from 'react-query';
import axios from '../base';
import { LeaderboardEntryDto } from '@ddays-app/types/src/dto/leaderboard';
import { QUERY_KEYS } from '@/constants/queryKeys';

const getTopUsers = async (): Promise<LeaderboardEntryDto[]> => {
return axios.get<never, LeaderboardEntryDto[]>('/leaderboard/top');
};

export const useGetTopUsers = () => {
return useQuery<LeaderboardEntryDto[]>(
QUERY_KEYS.leaderboardTop,
getTopUsers,
{
refetchOnWindowFocus: false,
staleTime: 60000, // 1 minute
},
);
};
19 changes: 19 additions & 0 deletions apps/app/src/api/leaderboard/useGetUserRank.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useQuery } from 'react-query';
import axios from '../base';
import { UserRankResponseDto } from '@ddays-app/types/src/dto/leaderboard';
import { QUERY_KEYS } from '@/constants/queryKeys';

const getUserRank = async (): Promise<UserRankResponseDto> => {
return axios.get<never, UserRankResponseDto>('leaderboard/me');
};

export const useGetUserRank = () => {
return useQuery<UserRankResponseDto>(
QUERY_KEYS.leaderboardUserRank,
getUserRank,
{
refetchOnWindowFocus: true,
staleTime: 60000, // 1 minute
},
);
};
45 changes: 45 additions & 0 deletions apps/app/src/api/leaderboard/useInfiniteLeaderboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useInfiniteQuery } from 'react-query';
import axios from '../base';
import { LeaderboardResponseDto } from '@ddays-app/types/src/dto/leaderboard';
import { QUERY_KEYS } from '@/constants/queryKeys';

interface LeaderboardParams {
pageSize?: number;
includeDeleted?: boolean;
}

export const useInfiniteLeaderboard = ({
pageSize,
includeDeleted = false,
}: LeaderboardParams = {}) => {
const getLeaderboard = async ({
pageParam = 1,
}): Promise<LeaderboardResponseDto> => {
return axios.get<never, LeaderboardResponseDto>('leaderboard', {
params: {
page: pageParam,
pageSize,
includeDeleted,
},
});
};

return useInfiniteQuery<
LeaderboardResponseDto,
Error,
LeaderboardResponseDto
>([QUERY_KEYS.leaderboard, pageSize, includeDeleted], getLeaderboard, {
getNextPageParam: (lastPage) => {
const currentPage = Number(lastPage.page);
const totalPages = Math.ceil(lastPage.totalEntries / lastPage.pageSize);

if (currentPage < totalPages) {
return currentPage + 1;
}

return undefined;
},
keepPreviousData: true,
refetchOnWindowFocus: true,
});
};
15 changes: 15 additions & 0 deletions apps/app/src/components/ErrorMessage/ErrorMessage.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.errorMessageContainer {
display: flex;
justify-content: center;
align-items: center;
z-index: 5;

}

.errorMessage {
@include heading-2;
color: $primary-black;
margin: 0 2rem;
text-align: center;
}

15 changes: 15 additions & 0 deletions apps/app/src/components/ErrorMessage/ErrorMessage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import styles from './ErrorMessage.module.scss';

interface ErrorMessageProps {
message: string;
}

const ErrorMessage = ({ message }: ErrorMessageProps) => {
return (
<div className={styles.errorMessageContainer}>
<p className={styles.errorMessage}>{message}</p>
</div>
);
};

export default ErrorMessage;
3 changes: 3 additions & 0 deletions apps/app/src/components/ErrorMessage/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import ErrorMessage from './ErrorMessage';

export default ErrorMessage;
Loading
Loading