Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions Backend/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export const typeDefs = `#graphql
isGameWishlisted(userId: Int!, gameId: Int!): Boolean!
game(appid: Int!): Game
genres: [String!]!
discountedGenres: [String!]!
profile(userId: Int!): Profile
gameOptions: [GameOption!]!
totalGameCount(
Expand Down
16 changes: 16 additions & 0 deletions Backend/logic/GenresLogicBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,19 @@ export async function FetchGenres(): Promise<string[]> {
const { rows } = await pool.query(`SELECT genre_name FROM genres ORDER BY genre_name`)
return rows.map((r) => r.genre_name as string)
}

export async function FetchGenresWithDiscounts(): Promise<string[]> {
const { rows } = await pool.query(
`SELECT ge.genre_name
FROM genres ge
WHERE EXISTS (
SELECT 1
FROM genretogame gg
JOIN games g ON g.game_id = gg.game_id
WHERE gg.genre_id = ge.genre_id
AND g.discount_percent > 0
)
ORDER BY ge.genre_name`
)
return rows.map((r) => r.genre_name as string)
}
3 changes: 2 additions & 1 deletion Backend/resolvers/GameResolvers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { pool } from '../DatabaseConnection.ts'
import { FetchGenres } from '../logic/GenresLogicBackend.ts'
import { FetchGenres, FetchGenresWithDiscounts } from '../logic/GenresLogicBackend.ts'
import { GAME_COLUMNS } from '../types/GameColumns.ts'
import {
FetchDiscountedGames,
Expand Down Expand Up @@ -123,6 +123,7 @@ export const gameQueryResolvers = {
},

genres: () => FetchGenres(),
discountedGenres: () => FetchGenresWithDiscounts(),

gameOptions: async () => {
const { rows } = await pool.query(
Expand Down
4 changes: 2 additions & 2 deletions Backend/resolvers/WishlistResolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const wishlistQueryResolvers = {
{ token }: GraphQLContext
): Promise<Game[]> => {
await RequireUser(token, userId)

const { rows } = await pool.query(
`SELECT ${GAME_COLUMNS}
FROM wishlist w
Expand All @@ -29,7 +29,7 @@ export const wishlistQueryResolvers = {
{ token }: GraphQLContext
): Promise<boolean> => {
await RequireUser(token, userId)

const { rows } = await pool.query(
`SELECT EXISTS (
SELECT 1
Expand Down
18 changes: 17 additions & 1 deletion Backend/tests/GenresBackend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { Query } = vi.hoisted(() => ({ Query: vi.fn() }))

vi.mock('../DatabaseConnection.ts', () => ({ pool: { query: Query } }))

import { FetchGenres } from '../logic/GenresLogicBackend.ts'
import { FetchGenres, FetchGenresWithDiscounts } from '../logic/GenresLogicBackend.ts'

describe('fetchGenres (backend)', () => {
beforeEach(() => {
Expand Down Expand Up @@ -57,4 +57,20 @@ describe('fetchGenres (backend)', () => {

await expect(FetchGenres()).rejects.toThrow('connection refused')
})

it('returns only genres that have at least one discounted game', async () => {
Query.mockResolvedValue({
rows: [{ genre_name: 'Action' }, { genre_name: 'Indie' }]
})

expect(await FetchGenresWithDiscounts()).toEqual(['Action', 'Indie'])

const sql = String(Query.mock.calls[0][0])
expect(sql).toContain('FROM genres ge')
expect(sql).toContain('WHERE EXISTS')
expect(sql).toContain('FROM genretogame gg')
expect(sql).toContain('JOIN games g ON g.game_id = gg.game_id')
expect(sql).toContain('g.discount_percent > 0')
expect(sql).toContain('ORDER BY ge.genre_name')
})
})
5 changes: 5 additions & 0 deletions Frontend/src/FrontendLogic/MainPageLogicFrontend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,8 @@ export async function LoadDiscountedGames(genre: string): Promise<Game[]> {
)
return data.discountedGames
}

export async function LoadDiscountedGenres(): Promise<string[]> {
const data = await Gql<{ discountedGenres: string[] }>(`query { discountedGenres }`, {})
return data.discountedGenres
}
1 change: 0 additions & 1 deletion Frontend/src/FrontendLogic/WishlistLogicFrontend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,3 @@ export async function FetchIsGameWishlistedFrontend(

return data.isGameWishlisted
}

85 changes: 62 additions & 23 deletions Frontend/src/components/ActiveGameCard/ActiveGameCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,43 +17,64 @@ type ActiveGameCardProps = {
onAddToWishlist?: (gameId: number) => void
}

type WishlistCheckResult =
| { userId: number; gameId: number; status: 'loaded'; isWishlisted: boolean }
| { userId: number; gameId: number; status: 'error'; message: string }

export default function ActiveGameCard({
game,
onAddToWishlist,
onRemoveFromWishlist
}: ActiveGameCardProps) {
const [isWishlisted, setIsWishlisted] = useState(false)
const [isChecking, setIsChecking] = useState(() => GetSavedUser() !== null)
const [wishlistCheck, setWishlistCheck] = useState<WishlistCheckResult | null>(null)
const [isBusy, setIsBusy] = useState(false)
const [error, setError] = useState<string | null>(null)

const [actionError, setActionError] = useState<{
userId: number | null
gameId: number
message: string
} | null>(null)

const user = GetSavedUser()
const userId = user?.id ?? null
const isLoggedIn = userId !== null
const currentCheck =
userId !== null && wishlistCheck?.userId === userId && wishlistCheck.gameId === game.id
? wishlistCheck
: null
const isWishlisted = currentCheck?.status === 'loaded' && currentCheck.isWishlisted
const isChecking = isLoggedIn && currentCheck === null
const error =
(currentCheck?.status === 'error' ? currentCheck.message : null) ??
(actionError?.userId === userId && actionError.gameId === game.id
? actionError.message
: null)

// Finds out if the signed in user already has this game on their wishlist
useEffect(() => {
let cancelled = false

if (userId == null) {
setIsChecking(false)
setIsWishlisted(false)
return
}

setIsChecking(true)
setError(null)
if (userId == null) return

FetchIsGameWishlistedFrontend(userId, game.id)
.then((wishlisted) => {
if (!cancelled)
setIsWishlisted(wishlisted)
if (!cancelled) {
setWishlistCheck({
userId,
gameId: game.id,
status: 'loaded',
isWishlisted: wishlisted
})
}
})
.catch(() => {
if (!cancelled) setError('Could not check your wishlist')
})
.finally(() => {
if (!cancelled) setIsChecking(false)
if (!cancelled) {
setWishlistCheck({
userId,
gameId: game.id,
status: 'error',
message: 'Could not check your wishlist'
})
}
})

return () => {
Expand All @@ -65,24 +86,42 @@ export default function ActiveGameCard({
async function HandleToggleWishlist() {
const user = GetSavedUser()
if (!user) {
setError('You need to sign in to change your wishlist')
setActionError({
userId: null,
gameId: game.id,
message: 'You need to sign in to change your wishlist'
})
return
}

setIsBusy(true)
setError(null)
setActionError(null)
try {
if (isWishlisted) {
await RemoveFromWishlistFrontend(user.id, game.id)
setIsWishlisted(false)
setWishlistCheck({
userId: user.id,
gameId: game.id,
status: 'loaded',
isWishlisted: false
})
onRemoveFromWishlist?.(game.id)
} else {
await AddToWishlistFrontend(user.id, game.id)
setIsWishlisted(true)
setWishlistCheck({
userId: user.id,
gameId: game.id,
status: 'loaded',
isWishlisted: true
})
onAddToWishlist?.(game.id)
}
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Could not update wishlist')
setActionError({
userId: user.id,
gameId: game.id,
message: err instanceof Error ? err.message : 'Could not update wishlist'
})
} finally {
setIsBusy(false)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@
align-items: flex-start;
flex-direction: column;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,4 @@ export default function ActiveGameCardInfo({ game }: ActiveGameInfoProps) {
</CardContent>
</Card>
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
.activeGameReviewsCard {
display: flex;
min-height: 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,4 @@ export default function ActiveGameCardReviews({ gameId }: ActiveGameReviewsProps
/>
</Card>
)
}
}
21 changes: 17 additions & 4 deletions Frontend/src/pages/MainPage/MainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { useDocumentTitle } from '../../hooks/useDocumentTitle'
import {
LoadTop3Games,
LoadTopGamesByGenre,
LoadDiscountedGames
LoadDiscountedGames,
LoadDiscountedGenres
} from '../../FrontendLogic/MainPageLogicFrontend'
import { FetchGenres } from '../../FrontendLogic/SearchPageLogicFrontend'
import { Link } from 'react-router-dom'
Expand All @@ -22,11 +23,14 @@ import TopGames from '../../components/TopGames'
export default function MainPage() {
const [featuredGames, setFeaturedGames] = useState<PageGame[]>([])
const [genres, setGenres] = useState<string[]>([])
const [discountedGenres, setDiscountedGenres] = useState<string[]>([])
const [isLoadingFeatured, setIsLoadingFeatured] = useState(true)
const [isLoadingGenres, setIsLoadingGenres] = useState(true)
const [isLoadingDiscountedGenres, setIsLoadingDiscountedGenres] = useState(true)
// One error per section, so each failure is shown inside the box it belongs to
const [featuredError, setFeaturedError] = useState<string | null>(null)
const [genresError, setGenresError] = useState<string | null>(null)
const [discountedGenresError, setDiscountedGenresError] = useState<string | null>(null)
const [reviewsError, setReviewsError] = useState<string | null>(null)
const [recentReviews, setRecentReviews] = useState<Review[]>([])
const [isLoadingReviews, setIsLoadingReviews] = useState(true)
Expand Down Expand Up @@ -58,6 +62,15 @@ export default function MainPage() {
if (!cancelled) setIsLoadingGenres(false)
})

LoadDiscountedGenres()
.then((loaded) => {
if (!cancelled) setDiscountedGenres([...loaded].sort())
})
.catch(ReportError(setDiscountedGenresError, 'Could not load discounted genres'))
.finally(() => {
if (!cancelled) setIsLoadingDiscountedGenres(false)
})

GetRecentReviews()
.then((reviews) => {
if (!cancelled) setRecentReviews(reviews)
Expand Down Expand Up @@ -133,9 +146,9 @@ export default function MainPage() {
/>
<GenreGamesSection
title="Discounts by Genre"
genres={genres}
genresLoading={isLoadingGenres}
genresError={genresError}
genres={discountedGenres}
genresLoading={isLoadingDiscountedGenres}
genresError={discountedGenresError}
loadGames={LoadDiscountedGames}
loadingText="Loading discount games..."
emptyText="No discounted games found for this genre."
Expand Down
32 changes: 10 additions & 22 deletions Frontend/src/tests/ActiveGameCard.test.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@

// @vitest-environment jsdom
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MemoryRouter } from 'react-router-dom'
import type { GameData } from '../types/Game'

const {
getSavedUserMock,
addToWishlistMock,
removeFromWishlistMock,
fetchIsGameWishlistedMock
} = vi.hoisted(() => ({
getSavedUserMock: vi.fn(),
addToWishlistMock: vi.fn(),
removeFromWishlistMock: vi.fn(),
fetchIsGameWishlistedMock: vi.fn()
}))
const { getSavedUserMock, addToWishlistMock, removeFromWishlistMock, fetchIsGameWishlistedMock } =
vi.hoisted(() => ({
getSavedUserMock: vi.fn(),
addToWishlistMock: vi.fn(),
removeFromWishlistMock: vi.fn(),
fetchIsGameWishlistedMock: vi.fn()
}))

vi.mock('../context/AuthContext', () => ({
UseAuth: () => ({ user: null })
Expand Down Expand Up @@ -112,17 +107,14 @@ describe('ActiveGameCard', () => {
})
})


describe('wishlist', () => {
it('shows the Add to wishlist button when the game is not wishlisted', async () => {
getSavedUserMock.mockReturnValue({ id: 1 })
fetchIsGameWishlistedMock.mockResolvedValue(false)

RenderActiveGameCard(testGame)

expect(
await screen.findByRole('button', { name: 'Add to wishlist' })
).not.toBeNull()
expect(await screen.findByRole('button', { name: 'Add to wishlist' })).not.toBeNull()

expect(fetchIsGameWishlistedMock).toHaveBeenCalledWith(1, testGame.id)
})
Expand Down Expand Up @@ -175,19 +167,15 @@ describe('ActiveGameCard', () => {
expect(removeFromWishlistMock).toHaveBeenCalledWith(1, testGame.id)
})

expect(
await screen.findByRole('button', { name: 'Add to wishlist' })
).not.toBeNull()
expect(await screen.findByRole('button', { name: 'Add to wishlist' })).not.toBeNull()
})

it('does not show the wishlist button when the user is not logged in', () => {
getSavedUserMock.mockReturnValue(null)

RenderActiveGameCard(testGame)

expect(
screen.queryByRole('button', { name: 'Add to wishlist' })
).toBeNull()
expect(screen.queryByRole('button', { name: 'Add to wishlist' })).toBeNull()

expect(fetchIsGameWishlistedMock).not.toHaveBeenCalled()
})
Expand Down
Loading