-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
6bf122b
leaderboard wip
ToniGrbic ba7d26a
lint fixes
ToniGrbic fea0c81
build fix
ToniGrbic 8d03fff
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic 60223f3
cleanup and adjustments
ToniGrbic 6479a7b
loading spinner
ToniGrbic 98c9f7d
td cell padding fix
ToniGrbic 3e4e667
lint fix
ToniGrbic c3857e4
added threshold
ToniGrbic 270f69b
final fixes and refactor into sections
ToniGrbic b2adcc3
ErrorMessage component
ToniGrbic 5597cfd
lint fix
ToniGrbic bdc5111
removed unnesseccary select field
ToniGrbic 06c6f5d
added user guards
ToniGrbic b1b80ad
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic 201edcf
changed images to avatars and final style adjustments
ToniGrbic 11111a4
white back btn desktop
ToniGrbic d8e4864
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic d2394f5
add useEffect call for achievement
ToniGrbic 1047ec7
Merge branch 'main' into ToniGrbic/backend-profile-leaderboard
ToniGrbic 3ac01a2
fix confirmed user and toast
lovretomic 326018a
Merge branch 'main' of github.com:dump-hr/ddays-app into ToniGrbic/ba…
ToniGrbic 4972a8d
returned mob back button and fix error message style
ToniGrbic dab0a01
increased z index for mobile navigation
ToniGrbic 1a9f754
fixed error message component
ToniGrbic 0330d4d
Merge branch 'main' into ToniGrbic/backend-profile-leaderboard
ToniGrbic 869e23f
Merge branch 'main' into ToniGrbic/backend-profile-leaderboard
lovretomic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
})); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}, | ||
); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}, | ||
); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
15
apps/app/src/components/ErrorMessage/ErrorMessage.module.scss
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import ErrorMessage from './ErrorMessage'; | ||
|
||
export default ErrorMessage; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.