diff --git a/.gitignore b/.gitignore index d84ea4e..ec50e19 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,12 @@ Coverage/ #Env file .env -.env.development \ No newline at end of file +.env.development + +# Playwright +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +/playwright/.auth/ +playwright-report-api/ diff --git a/Backend/Schema.ts b/Backend/Schema.ts index 90306a3..398d8ac 100644 --- a/Backend/Schema.ts +++ b/Backend/Schema.ts @@ -75,6 +75,8 @@ export const typeDefs = `#graphql discountedGames(genre: String!): [Game!]! reviews(gameId: Int!, userId: Int): [Review!]! recentReviews(limit: Int = 10): [Review!]! + userReviews(userId: Int!, limit: Int = 6, offset: Int = 0): [Review!]! + userReviewCount(userId: Int!): Int! friends(userId: Int!): [Friend!]! friendWishlist(userId: Int!, friendId: Int!): [Game!]! myFriendId(userId: Int!): String diff --git a/Backend/Server.ts b/Backend/Server.ts index c83244a..04ffd60 100644 --- a/Backend/Server.ts +++ b/Backend/Server.ts @@ -4,12 +4,19 @@ import { typeDefs } from './Schema.ts' import { resolvers } from './resolvers/index.ts' const server = new ApolloServer({ typeDefs, resolvers }) + +const port = Number(process.env.PORT ?? 3001) + const { url } = await startStandaloneServer(server, { - listen: { host: process.env.HOST ?? '127.0.0.1', port: 3001 }, + listen: { + host: process.env.HOST ?? '127.0.0.1', + port + }, context: async ({ req }) => ({ token: req.headers.authorization?.replace(/^Bearer /, '') ?? null }) }) + console.log( `Database: ${process.env.DB_USER}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}` ) diff --git a/Backend/logic/ReviewsLogicBackend.ts b/Backend/logic/ReviewsLogicBackend.ts index a8c298f..d2c0f40 100644 --- a/Backend/logic/ReviewsLogicBackend.ts +++ b/Backend/logic/ReviewsLogicBackend.ts @@ -29,6 +29,17 @@ function ValidateId(id: number, name: string) { if (!Number.isSafeInteger(id) || id <= 0) throw new Error(`The ${name} is invalid.`) } +function ClampLimit(limit: number): number { + return Math.min(Math.max(Math.trunc(limit) || 1, 1), 50) +} + +const REVIEWS_WITH_GAME_NAME = ` + SELECT ${REVIEW_COLUMNS}, + g.game_name AS "gameName" + FROM reviews r + JOIN users u ON u.user_id = r.user_id + JOIN games g ON g.game_id = r.game_id` + export async function GetReviewsForGame( gameId: number, currentUserId: number | null = null @@ -47,21 +58,38 @@ export async function GetReviewsForGame( } export async function GetRecentReviews(limit = 10): Promise { - const safeLimit = Math.min(Math.max(Math.trunc(limit) || 1, 1), 50) - const { rows } = await pool.query( - `SELECT ${REVIEW_COLUMNS}, - g.game_name AS "gameName" - FROM reviews r - JOIN users u ON u.user_id = r.user_id - JOIN games g ON g.game_id = r.game_id + `${REVIEWS_WITH_GAME_NAME} ORDER BY r.review_id DESC LIMIT $1`, - [safeLimit] + [ClampLimit(limit)] + ) + return rows +} + +export async function GetReviewsByUser(userId: number, limit = 6, offset = 0): Promise { + ValidateId(userId, 'user ID') + const safeOffset = Math.max(Math.trunc(offset) || 0, 0) + + const { rows } = await pool.query( + `${REVIEWS_WITH_GAME_NAME} + WHERE r.user_id = $1 + ORDER BY r.review_id DESC + LIMIT $2 OFFSET $3`, + [userId, ClampLimit(limit), safeOffset] ) return rows } +export async function CountReviewsByUser(userId: number): Promise { + ValidateId(userId, 'user ID') + + const { rows } = await pool.query('SELECT COUNT(*) AS count FROM reviews WHERE user_id = $1', [ + userId + ]) + return Number(rows[0].count) +} + export async function CreateReview( userId: number, gameId: number, diff --git a/Backend/logic/UserLogicBackend.ts b/Backend/logic/UserLogicBackend.ts index 6536e44..6042858 100644 --- a/Backend/logic/UserLogicBackend.ts +++ b/Backend/logic/UserLogicBackend.ts @@ -112,8 +112,11 @@ export async function RequireUser(token: string | null, userId: number | null): }) } const { rows } = await pool.query('SELECT user_id FROM users WHERE token = $1', [token]) - if (rows.length === 0 || rows[0].user_id !== userId) { - throw new GraphQLError('Not allowed.', { extensions: { code: 'FORBIDDEN' } }) + + if (rows.length === 0 || Number(rows[0].user_id) !== Number(userId)) { + throw new GraphQLError('Not allowed.', { + extensions: { code: 'FORBIDDEN' } + }) } } diff --git a/Backend/resolvers/ReviewResolvers.ts b/Backend/resolvers/ReviewResolvers.ts index 33ec562..ab4e925 100644 --- a/Backend/resolvers/ReviewResolvers.ts +++ b/Backend/resolvers/ReviewResolvers.ts @@ -1,7 +1,9 @@ import { + CountReviewsByUser, CreateReview, DeleteReview, GetRecentReviews, + GetReviewsByUser, GetReviewsForGame, UpdateReview } from '../logic/ReviewsLogicBackend.ts' @@ -12,7 +14,15 @@ export const reviewQueryResolvers = { reviews: (_parent: unknown, { gameId, userId }: { gameId: number; userId?: number | null }) => GetReviewsForGame(gameId, userId ?? null), - recentReviews: (_parent: unknown, { limit }: { limit: number }) => GetRecentReviews(limit) + recentReviews: (_parent: unknown, { limit }: { limit: number }) => GetRecentReviews(limit), + + userReviews: ( + _parent: unknown, + { userId, limit, offset }: { userId: number; limit: number; offset: number } + ) => GetReviewsByUser(userId, limit, offset), + + userReviewCount: (_parent: unknown, { userId }: { userId: number }) => + CountReviewsByUser(userId) } export const reviewMutationResolvers = { diff --git a/Backend/tests/GameResolvers.test.ts b/Backend/tests/GameResolvers.test.ts new file mode 100644 index 0000000..b06ea06 --- /dev/null +++ b/Backend/tests/GameResolvers.test.ts @@ -0,0 +1,46 @@ +// @vitest-environment node +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { Query } = vi.hoisted(() => ({ Query: vi.fn() })) + +vi.mock('../DatabaseConnection.ts', () => ({ pool: { query: Query } })) + +import { gameQueryResolvers } from '../resolvers/GameResolvers.ts' + +beforeEach(() => { + Query.mockReset() +}) + +describe('games resolver search', () => { + it('filters by name and returns the requested page', async () => { + const games = [{ appid: 570, name: 'Dota 2' }] + Query.mockResolvedValue({ rows: games }) + + const result = await gameQueryResolvers.games(null, { + search: 'dota', + limit: 20, + offset: 20 + }) + + expect(result).toEqual(games) + expect(Query.mock.calls[0][0]).toContain('g.game_name ILIKE $1') + expect(Query.mock.calls[0][0]).toContain('LIMIT $4 OFFSET $5') + expect(Query.mock.calls[0][1].slice(-2)).toEqual([20, 20]) + }) + + it('caps page size at the existing API maximum', async () => { + Query.mockResolvedValue({ rows: [] }) + + await gameQueryResolvers.games(null, { search: 'game', limit: 1000, offset: 0 }) + + expect(Query.mock.calls[0][1].slice(-2)).toEqual([500, 0]) + }) + + it('passes database errors through', async () => { + Query.mockRejectedValue(new Error('connection refused')) + + await expect( + gameQueryResolvers.games(null, { search: 'game', limit: 20, offset: 0 }) + ).rejects.toThrow('connection refused') + }) +}) diff --git a/Backend/tests/ReviewsBackend.test.ts b/Backend/tests/ReviewsBackend.test.ts index f67d188..016941b 100644 --- a/Backend/tests/ReviewsBackend.test.ts +++ b/Backend/tests/ReviewsBackend.test.ts @@ -7,9 +7,11 @@ const { Query } = vi.hoisted(() => ({ Query: vi.fn() })) vi.mock('../DatabaseConnection.ts', () => ({ pool: { query: Query } })) import { + CountReviewsByUser, CreateReview, DeleteReview, GetRecentReviews, + GetReviewsByUser, GetReviewsForGame, UpdateReview } from '../logic/ReviewsLogicBackend.ts' @@ -86,6 +88,59 @@ describe('reviews (backend)', () => { }) }) + describe('GetReviewsByUser', () => { + it("returns the first page of one user's reviews with the game names, newest first", async () => { + Query.mockResolvedValue({ rows: [testReview] }) + + await expect(GetReviewsByUser(7)).resolves.toEqual([testReview]) + + const [sql, params] = Query.mock.calls[0] + expect(String(sql)).toContain('g.game_name AS "gameName"') + expect(String(sql)).toContain('WHERE r.user_id = $1') + expect(String(sql)).toContain('ORDER BY r.review_id DESC') + expect(String(sql)).toContain('LIMIT $2 OFFSET $3') + expect(params).toEqual([7, 6, 0]) + }) + + it('skips the reviews of earlier pages', async () => { + Query.mockResolvedValue({ rows: [] }) + + await GetReviewsByUser(7, 6, 12) + + expect(Query.mock.calls[0][1]).toEqual([7, 6, 12]) + }) + + it('keeps the page size between 1 and 50 and the offset at 0 or more', async () => { + Query.mockResolvedValue({ rows: [] }) + + await GetReviewsByUser(7, 1000, -5) + + expect(Query.mock.calls[0][1]).toEqual([7, 50, 0]) + }) + + it('rejects an invalid user id without touching the database', async () => { + await expect(GetReviewsByUser(0)).rejects.toThrow('The user ID is invalid.') + expect(Query).not.toHaveBeenCalled() + }) + }) + + describe('CountReviewsByUser', () => { + it('counts all reviews written by the user', async () => { + Query.mockResolvedValue({ rows: [{ count: '13' }] }) + + await expect(CountReviewsByUser(7)).resolves.toBe(13) + + const [sql, params] = Query.mock.calls[0] + expect(String(sql)).toContain('WHERE user_id = $1') + expect(params).toEqual([7]) + }) + + it('rejects an invalid user id without touching the database', async () => { + await expect(CountReviewsByUser(-1)).rejects.toThrow('The user ID is invalid.') + expect(Query).not.toHaveBeenCalled() + }) + }) + describe('CreateReview', () => { it('saves the review and returns it with the username', async () => { Query.mockResolvedValue({ rows: [testReview] }) diff --git a/E2E/Auth.spec.ts b/E2E/Auth.spec.ts new file mode 100644 index 0000000..a7ecc43 --- /dev/null +++ b/E2E/Auth.spec.ts @@ -0,0 +1,143 @@ + +import { test, expect } from './fixtures' +import type { Page } from '@playwright/test' + +async function clickHeaderLink(page: Page, name: string) { + const openMenuButton = page.getByRole('button', { + name: 'Open menu' + }) + + if (await openMenuButton.isVisible()) { + await openMenuButton.click() + } + + await page.getByRole('link', { + name, + exact: true + }).click() +} + +async function signUpAndTestWrongPassword(page: Page) { + const stamp = `${Date.now()}${Math.random().toString(36).slice(2, 6)}` + const email = `ui+${stamp}@example.com` + const username = `ui${stamp}` + const password = 'secret123' + + // Main page -> Sign in page + await page.goto('/') + await clickHeaderLink(page, 'Sign In') + + await expect(page).toHaveURL(/#\/SignIn/i) + await expect( + page.getByRole('heading', { name: 'Sign in' }) + ).toBeVisible() + + // Sign in page -> Sign up page + await page.getByRole('link', { name: 'Sign up' }).click() + + await expect(page).toHaveURL(/#\/signup/i) + await expect( + page.getByRole('heading', { name: 'Sign up' }) + ).toBeVisible() + + // Make an account + await page.getByLabel('Email').fill(email) + await page.getByLabel('Username').fill(username) + await page.getByLabel('Password', { exact: true }).fill(password) + await page.getByLabel('Re-enter Password').fill(password) + + await page.getByRole('button', { + name: 'Sign up' + }).click() + + // Signed up users land on the main page and are signed in + await expect(page).toHaveURL(/#\/$/) + await expect( + page.getByRole('heading', { name: /Welcome to GameStart/ }) + ).toBeVisible() + + // Open the mobile menu before checking Sign Out + const openMenuButton = page.getByRole('button', { + name: 'Open menu' + }) + + if (await openMenuButton.isVisible()) { + await openMenuButton.click() + } + + await expect( + page.getByRole('link', { name: 'Sign Out', exact: true }) + ).toBeVisible() + + // Sign out + await clickHeaderLink(page, 'Sign Out') + + await expect(page).toHaveURL(/#\/$/) + + // Open mobile menu before checking Sign In + const openMenuAfterSignOut = page.getByRole('button', { + name: 'Open menu' + }) + + if (await openMenuAfterSignOut.isVisible()) { + await openMenuAfterSignOut.click() + } + + await expect( + page.getByRole('link', { name: 'Sign In', exact: true }) + ).toBeVisible() + + await expect( + page.getByRole('link', { name: 'Sign Out', exact: true }) + ).toHaveCount(0) + + // Sign in again, with the wrong password + await clickHeaderLink(page, 'Sign In') + + await page.getByLabel('Email').fill(email) + await page.getByLabel('Password').fill('wrongpass1') + + await page.getByRole('button', { + name: 'Sign in' + }).click() + + // Stays on the sign in page and shows an error, still signed out + await expect(page.getByRole('alert')).toBeVisible() + await expect(page).toHaveURL(/#\/SignIn/i) + + await expect( + page.getByRole('link', { name: 'Sign Out' }) + ).toHaveCount(0) +} + +// Desktop authentication +test.describe('Desktop authentication', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test('sign up, sign out, and fail to sign in with a wrong password', async ({ page }) => { + await signUpAndTestWrongPassword(page) + }) +}) + +// Mobile authentication +test.describe('Mobile authentication', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test('sign up, sign out, and fail to sign in with a wrong password on mobile', async ({ page }) => { + await signUpAndTestWrongPassword(page) + }) +}) diff --git a/E2E/E2EConfig.ts b/E2E/E2EConfig.ts new file mode 100644 index 0000000..4c0710f --- /dev/null +++ b/E2E/E2EConfig.ts @@ -0,0 +1,11 @@ +export const FRONTEND_URL = 'http://localhost:5173' +export const BACKEND_URL = 'http://localhost:3001' + +// Same local Postgres as development, but a separate database +export const TestDB = { + DB_HOST: '127.0.0.1', + DB_PORT: '5432', + DB_NAME: 'gamestart_e2e', + DB_USER: 'e2etestuser', + DB_PASSWORD: 'e2etestpassword' +} diff --git a/E2E/Fixtures.ts b/E2E/Fixtures.ts new file mode 100644 index 0000000..876d106 --- /dev/null +++ b/E2E/Fixtures.ts @@ -0,0 +1,283 @@ + +import { test as base, expect } from '@playwright/test' +import { BACKEND_URL } from './E2EConfig' +import { addCoverageReport } from 'monocart-reporter' + +export type TestUser = { + id: number + token: string + username: string + email: string +} + +export type SecondUser = TestUser & { + friendId: string +} + +type Fixtures = { + user: TestUser + secondUser: SecondUser + seedWishlist: (userId: number, count: number) => Promise + seedReview: (userId: number) => Promise +} + +// GraphQL helper +async function graphql( + request: any, + query: string, + variables = {}, + token?: string +) { + const res = await request.post(BACKEND_URL, { + headers: token + ? { Authorization: `Bearer ${token}` } + : {}, + data: { query, variables } + }) + + if (!res.ok) { + const body = await res.text() + throw new Error( + `Backend request failed: ${res.status}\nResponse: ${body}` + ) + } + + const json = await res.json() + + if (json.errors) { + throw new Error(json.errors[0].message) + } + + return json.data +} + +// Create a test user +async function createUser(request: any): Promise { + const stamp = + `${Date.now()}${Math.random().toString(36).slice(2, 6)}` + + const username = `e2e${stamp}` + const email = `e2e+${stamp}@example.com` + + const data = await graphql( + request, + ` + mutation($u: String!, $e: String!, $p: String!) { + signup(username: $u, email: $e, password: $p) { + id + email + username + token + } + } + `, + { + u: username, + e: email, + p: 'secret123' + } + ) + + return data.signup +} + +export const test = base.extend({ + + // Main test user + user: async ({ request, context }, use) => { + const user = await createUser(request) + + await context.addInitScript((u) => { + localStorage.setItem('GameStart:user', JSON.stringify(u)) + }, user) + + await use(user) + }, + + // Second test user, including their actual FriendID + secondUser: async ({ request }, use) => { + const createdUser = await createUser(request) + + const data = await graphql( + request, + ` + query($userId: Int!) { + myFriendId(userId: $userId) + } + `, + { + userId: createdUser.id + }, + createdUser.token + ) + + const secondUser: SecondUser = { + ...createdUser, + friendId: String(data.myFriendId) + } + + await use(secondUser) + }, + + // Seed a wishlist through the API + seedWishlist: async ({ request, user, secondUser }, use) => { + const seedWishlist = async ( + userId: number, + count: number + ) => { + const targetUser = + user.id === userId + ? user + : secondUser.id === userId + ? secondUser + : null + + if (!targetUser) { + throw new Error(`Unknown test user ID: ${userId}`) + } + + const gamesData = await graphql( + request, + ` + query { + games(limit: 500, offset: 0) { + appid + } + } + `, + {}, + targetUser.token + ) + + const games = gamesData.games.slice(0, count) + + if (games.length < count) { + throw new Error( + `Requested ${count} games, but only found ${games.length}.` + ) + } + + for (const game of games) { + await graphql( + request, + ` + mutation($userId: Int!, $gameId: Int!) { + addToWishlist(userId: $userId, gameId: $gameId) + } + `, + { + userId, + gameId: game.appid + }, + targetUser.token + ) + } + } + + await use(seedWishlist) + }, + + // Seed a review through the API + seedReview: async ({ request, user }, use) => { + const seedReview = async (userId: number) => { + if (userId !== user.id) { + throw new Error( + `No test user with ID ${userId} is available` + ) + } + + const gamesData = await graphql( + request, + ` + query { + games(limit: 1, offset: 0) { + appid + } + } + `, + {}, + user.token + ) + + const game = gamesData.games[0] + + if (!game) { + throw new Error('No games available to create a test review') + } + + await graphql( + request, + ` + mutation( + $userId: Int! + $gameId: Int! + $rating: Int! + $text: String! + ) { + createReview( + userId: $userId + gameId: $gameId + rating: $rating + text: $text + ) { + id + } + } + `, + { + userId, + gameId: game.appid, + rating: 5, + text: 'Playwright E2E test review' + }, + user.token + ) + } + + await use(seedReview) + }, + + // Automatically collect frontend JavaScript and CSS coverage. + coverage: [ + async ({ page }, use) => { + const isChromium = test.info().project.name === 'chromium' + + if (isChromium) { + await Promise.all([ + page.coverage.startJSCoverage({ + resetOnNavigation: false + }), + page.coverage.startCSSCoverage({ + resetOnNavigation: false + }) + ]) + } + + try { + await use() + } finally { + if (isChromium) { + const [jsCoverage, cssCoverage] = await Promise.all([ + page.coverage.stopJSCoverage(), + page.coverage.stopCSSCoverage() + ]) + + const coverageList = [ + ...jsCoverage, + ...cssCoverage + ] + + if (coverageList.length > 0) { + await addCoverageReport( + coverageList, + test.info() + ) + } + } + } + }, + { auto: true } + ] +}) + +export { expect } diff --git a/E2E/Friendpage.spec.ts b/E2E/Friendpage.spec.ts new file mode 100644 index 0000000..7d191e7 --- /dev/null +++ b/E2E/Friendpage.spec.ts @@ -0,0 +1,138 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' +import type { Page } from '@playwright/test' + +const FRIEND_PAGE = /#\/FriendsPage$/ + +async function addFriend(page: Page, friendId: string) { + const friendInput = page.getByRole('textbox', { + name: /friend id/i + }) + + await friendInput.fill(friendId) + + await page.getByRole('button', { + name: 'Add', + exact: true + }).click() + + // The Friend ID field is cleared after a successful add. + await expect(friendInput).toHaveValue('') + + // The selected friend's wishlist has finished loading. + await expect(page.locator('.games-grid-wishlist')).toBeVisible() + } + + async function checkFriendWishlistPagination(page: Page) { + const wishlistGames = page.locator('.games-grid-wishlist > *') + + await expect(wishlistGames).toHaveCount(5) + + const firstPageGame = (await wishlistGames.first().innerText()).trim() + + const nextPage = page.getByRole('button', { + name: 'Go to page 2' + }) + + await expect(nextPage).toBeVisible() + await nextPage.click() + + await expect(wishlistGames).toHaveCount(1) + + const secondPageGame = (await wishlistGames.first().innerText()).trim() + + expect(secondPageGame).not.toBe(firstPageGame) + } + + async function openDesktopFriendPage(page: Page) { + await openMainPage(page) + + await page.getByRole('link', { + name: 'Friends', + exact: true + }).click() + + await expect(page).toHaveURL(FRIEND_PAGE) + } + + async function openMobileFriendPage(page: Page) { + await openMainPage(page) + + await page.getByRole('button', { + name: 'Open menu' + }).click() + + await page.getByRole('link', { + name: 'Friends', + exact: true + }).click() + + await expect(page).toHaveURL(FRIEND_PAGE) + + // Confirm navigation closed the mobile menu. + await expect( + page.getByRole('button', { name: 'Open menu' }) + ).toBeVisible() +} + +// Desktop tests +test.describe('FriendPage', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test.beforeEach(async ({ page, secondUser, seedWishlist }) => { + await seedWishlist(secondUser.id, 6) + await openDesktopFriendPage(page) + }) + + test('Add a friend', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId) + }) + + test('Friend wishlist pagination', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId) + await checkFriendWishlistPagination(page) + }) +}) + +// Mobile tests +test.describe('Mobile FriendPage', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test.beforeEach(async ({ page, secondUser, seedWishlist }) => { + await seedWishlist(secondUser.id, 6) + await openMobileFriendPage(page) + }) + + test('Add a friend on mobile', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId) + }) + + test('Friend wishlist pagination on mobile', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId) + await checkFriendWishlistPagination(page) + }) + + test('FriendPage has no horizontal overflow', async ({ page }) => { + const hasOverflow = await page.evaluate(() => { + return document.documentElement.scrollWidth > + document.documentElement.clientWidth + }) + + expect(hasOverflow).toBe(false) + }) +}) diff --git a/E2E/Global-Setup.ts b/E2E/Global-Setup.ts new file mode 100644 index 0000000..9b8b62b --- /dev/null +++ b/E2E/Global-Setup.ts @@ -0,0 +1,117 @@ + +import 'dotenv/config' +import { execFileSync } from 'node:child_process' +import pg from 'pg' +import { TestDB } from './E2EConfig' + +export default async function globalSetup() { + const adminPassword = process.env.PG_ADMIN_PASSWORD + + if (TestDB.DB_NAME === process.env.DB_NAME) { + throw new Error( + 'E2E database cannot be the same as development database!' + ) + } + + if (!adminPassword) { + throw new Error( + 'PG_ADMIN_PASSWORD is missing. Check your root .env file.' + ) + } + + const admin = new pg.Client({ + host: TestDB.DB_HOST, + port: Number(TestDB.DB_PORT), + user: process.env.PG_ADMIN_USER ?? 'postgres', + password: adminPassword, + database: 'postgres', + }) + + // Safely quote PostgreSQL identifiers and string literals. + const quoteIdentifier = (value: string) => + `"${value.replace(/"/g, '""')}"` + + const quoteLiteral = (value: string) => + `'${value.replace(/'/g, "''")}'` + + try { + await admin.connect() + + // Create or update the dedicated E2E database user. + const roleResult = await admin.query( + 'SELECT 1 FROM pg_roles WHERE rolname = $1', + [TestDB.DB_USER] + ) + + if (roleResult.rowCount === 0) { + await admin.query( + `CREATE ROLE ${quoteIdentifier(TestDB.DB_USER)} + LOGIN PASSWORD ${quoteLiteral(TestDB.DB_PASSWORD)}` + ) + } else { + await admin.query( + `ALTER ROLE ${quoteIdentifier(TestDB.DB_USER)} + WITH LOGIN PASSWORD ${quoteLiteral(TestDB.DB_PASSWORD)}` + ) + } + + // Check whether the E2E database exists. + const dbResult = await admin.query( + 'SELECT 1 FROM pg_database WHERE datname = $1', + [TestDB.DB_NAME] + ) + + // Create the E2E database with the test user as owner. + if (dbResult.rowCount === 0) { + await admin.query( + `CREATE DATABASE ${quoteIdentifier(TestDB.DB_NAME)} + OWNER ${quoteIdentifier(TestDB.DB_USER)}` + ) + } else { + await admin.query( + `ALTER DATABASE ${quoteIdentifier(TestDB.DB_NAME)} + OWNER TO ${quoteIdentifier(TestDB.DB_USER)}` + ) + } + + } finally { + await admin.end() + } + + // Verify that the E2E credentials work. + const testConnection = new pg.Client({ + host: TestDB.DB_HOST, + port: Number(TestDB.DB_PORT), + user: TestDB.DB_USER, + password: TestDB.DB_PASSWORD, + database: TestDB.DB_NAME, + }) + + try { + await testConnection.connect() + console.log('E2E database connection successful.') + } finally { + await testConnection.end() + } + + // Run database setup scripts using ONLY E2E credentials. + const env = { + ...process.env, + ...TestDB, + } + + for (const script of [ + 'Database/CreateTables.ts', + 'Database/FillDb.ts', + 'Database/FillGenres.ts', + ]) { + console.log(`Running ${script}...`) + + execFileSync(process.execPath, [script], { + env, + stdio: 'inherit', + }) + } + + console.log('E2E database setup completed.') +} diff --git a/E2E/Mainpage.spec.ts b/E2E/Mainpage.spec.ts new file mode 100644 index 0000000..777c422 --- /dev/null +++ b/E2E/Mainpage.spec.ts @@ -0,0 +1,125 @@ + +import { test, expect } from './fixtures' +import { openMainPage, testCarousel } from './helpers' + +const GAME_PAGE = /#\/gamepage\/\d+$/ + +async function checkFeaturedGames(page: import('@playwright/test').Page) { + const section = page + .getByRole('heading', { name: 'Top 3 Games' }) + .locator('xpath=ancestor::section[1]') + + await expect(section).toBeVisible() + + await expect( + section.locator('.featured-game-card') + ).toHaveCount(3) +} + +async function navigateFromRecentReviewToGame( + page: import('@playwright/test').Page, + userId: number, + seedReview: (userId: number) => Promise + ) { + await seedReview(userId) + await openMainPage(page) + + const reviewCard = page.locator('.reviewCard').first() + + await expect(reviewCard).toBeVisible() + + await reviewCard.getByRole('link', { + name: 'See this game', + exact: true + }).click() + + await expect(page).toHaveURL(GAME_PAGE) +} + +// Desktop tests +test.describe('Desktop MainPage - Carousels', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test.beforeEach(async ({ page }) => { + await openMainPage(page) + }) + + test('Top 3 featured games are displayed', async ({ page }) => { + await checkFeaturedGames(page) + }) + + test('Discounted games - next and previous buttons', async ({ page }) => { + await testCarousel(page, 'Discounts by Genre') + }) +}) + +// Mobile tests +test.describe('Mobile MainPage - Carousels', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test.beforeEach(async ({ page }) => { + await openMainPage(page) + }) + + test('Top 3 featured games are displayed on mobile', async ({ page }) => { + await checkFeaturedGames(page) + }) + + test('Discounted games - next and previous buttons on mobile', async ({ page }) => { + await testCarousel(page, 'Discounts by Genre') + }) +}) + +// Recent review navigation - Desktop +test.describe('Desktop MainPage components', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test('Navigate from a recent review to its game', async ({ + page, + user, + seedReview + }) => { + await navigateFromRecentReviewToGame(page, user.id, seedReview) + }) +}) + +// Recent review navigation - Mobile +test.describe('Mobile MainPage components', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test('Navigate from a recent review to its game on mobile', async ({ + page, + user, + seedReview + }) => { + await navigateFromRecentReviewToGame(page, user.id, seedReview) + }) +}) diff --git a/E2E/MainpageToGamepage.spec.ts b/E2E/MainpageToGamepage.spec.ts new file mode 100644 index 0000000..e0e3cea --- /dev/null +++ b/E2E/MainpageToGamepage.spec.ts @@ -0,0 +1,117 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' +import type { Page } from '@playwright/test' + +const GAME_PAGE = /#\/gamepage\/\d+$/ +const WISHLIST_PAGE = /#\/WishlistPage$/ + +async function openTopGameAndToggleWishlist(page: Page) { + const topSection = page.locator('section').filter({ + has: page.getByRole('heading', { name: /top 3 games/i }) + }).first() + + await expect(topSection.getByText(/loading/i)).toHaveCount(0) + + const firstGameLink = topSection.getByRole('link').first() + + await expect(firstGameLink).toBeVisible() + + const gameName = (await firstGameLink.innerText()) + .split('\n')[0] + .trim() + + await firstGameLink.click() + + await expect(page).toHaveURL(GAME_PAGE) + + await expect( + page.getByRole('heading', { name: gameName }).first() + ).toBeVisible() + + const addButton = page.getByRole('button', { + name: 'Add to wishlist', + exact: true + }) + + const removeButton = page.getByRole('button', { + name: 'Remove from wishlist', + exact: true + }) + + await expect(addButton).toBeVisible() + await addButton.click() + + await expect(removeButton).toBeVisible() + await removeButton.click() + + await expect(addButton).toBeVisible() +} + +async function navigateToWishlist(page: Page, isMobile = false) { + if (isMobile) { + await page.getByRole('button', { + name: 'Open menu' + }).click() + } + + await page.getByRole('link', { + name: 'Wishlist', + exact: true + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) + + if (isMobile) { + // Confirm the mobile menu closed after navigation. + await expect( + page.getByRole('button', { name: 'Open menu' }) + ).toBeVisible() + } +} + +// Desktop test +test.describe('Desktop top game and wishlist', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test('open the top game, go back, and toggle the wishlist button', async ({ + page, + user + }) => { + expect(user.id).toBeGreaterThan(0) + + await openMainPage(page) + await openTopGameAndToggleWishlist(page) + await navigateToWishlist(page) + }) +}) + +// Mobile test +test.describe('Mobile top game and wishlist', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test('open the top game, toggle wishlist, and navigate to WishlistPage', async ({ + page, + user + }) => { + expect(user.id).toBeGreaterThan(0) + + await openMainPage(page) + await openTopGameAndToggleWishlist(page) + await navigateToWishlist(page, true) + }) +}) diff --git a/E2E/Navigation.spec.ts b/E2E/Navigation.spec.ts new file mode 100644 index 0000000..44d73f2 --- /dev/null +++ b/E2E/Navigation.spec.ts @@ -0,0 +1,198 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' +import type { Page } from '@playwright/test' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const SEARCH_PAGE = /#\/SearchPage$/ +const WISHLIST_PAGE = /#\/WishlistPage$/ +const FRIEND_PAGE = /#\/FriendsPage$/ +const PROFILE_PAGE = /#\/ProfilePage$/ + +async function navigateMobile( + page: Page, + linkName: string, + expectedUrl: RegExp +) { + const openMenuButton = page.getByRole('button', { + name: 'Open menu' + }) + + // Open menu if it is closed + if (await openMenuButton.isVisible()) { + await openMenuButton.click() + } + + const link = page.getByRole('link', { + name: linkName, + exact: true + }) + + await expect(link).toBeVisible() + await link.click() + + // Wait for navigation + await expect(page).toHaveURL(expectedUrl) + + // Wait for menu to close + await expect( + page.getByRole('button', { name: 'Open menu' }) + ).toHaveAttribute('aria-expanded', 'false') +} + +// Desktop header navigation +test.describe('Desktop header navigation', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test('Navigate through all header pages and sign out', async ({ page, user }) => { + await openMainPage(page) + + // MainPage -> SearchPage + await page.getByRole('link', { + name: 'Search', + exact: true + }).click() + + await expect(page).toHaveURL(SEARCH_PAGE) + + // SearchPage -> WishlistPage + await page.getByRole('link', { + name: 'Wishlist', + exact: true + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) + + // WishlistPage -> FriendsPage + await page.getByRole('link', { + name: 'Friends', + exact: true + }).click() + + await expect(page).toHaveURL(FRIEND_PAGE) + + // FriendsPage -> ProfilePage + await page.getByRole('link', { + name: 'Profile', + exact: true + }).click() + + await expect(page).toHaveURL(PROFILE_PAGE) + + // ProfilePage -> Sign Out + await page.getByRole('link', { + name: 'Sign Out', + exact: true + }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + + // Verify logged-out header + await expect( + page.getByRole('link', { + name: 'Sign In', + exact: true + }) + ).toBeVisible() + + // MainPage -> Home using logo + await page.getByRole('link', { + name: 'GameStart home' + }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + }) +}) + +// Mobile header navigation +test.describe('Mobile header navigation', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test('Navigate through all header pages and sign out', async ({ page, user }) => { + await openMainPage(page) + + // MainPage -> SearchPage + await navigateMobile(page, 'Search', SEARCH_PAGE) + + // SearchPage -> WishlistPage + await navigateMobile(page, 'Wishlist', WISHLIST_PAGE) + + // WishlistPage -> FriendsPage + await navigateMobile(page, 'Friends', FRIEND_PAGE) + + // FriendsPage -> ProfilePage + await navigateMobile(page, 'Profile', PROFILE_PAGE) + + // ProfilePage -> Sign Out + await navigateMobile(page, 'Sign Out', MAIN_PAGE) + + // Open menu to verify logged-out header + await page.getByRole('button', { + name: 'Open menu' + }).click() + + await expect( + page.getByRole('link', { + name: 'Sign In', + exact: true + }) + ).toBeVisible() + + await expect( + page.getByRole('link', { + name: 'Sign Out', + exact: true + }) + ).toHaveCount(0) + }) + + test('Mobile menu closes when pressing Escape', async ({ page }) => { + await openMainPage(page) + + await page.getByRole('button', { + name: 'Open menu' + }).click() + + await expect( + page.getByRole('button', { name: 'Close menu' }) + ).toHaveAttribute('aria-expanded', 'true') + + await page.keyboard.press('Escape') + + await expect( + page.getByRole('button', { name: 'Open menu' }) + ).toHaveAttribute('aria-expanded', 'false') + }) + + test('Mobile menu closes when clicking backdrop', async ({ page }) => { + await openMainPage(page) + + await page.getByRole('button', { + name: 'Open menu' + }).click() + + await expect( + page.getByRole('button', { name: 'Close menu' }) + ).toBeVisible() + + await page.locator('.headerBackdrop').click() + + await expect( + page.getByRole('button', { name: 'Open menu' }) + ).toHaveAttribute('aria-expanded', 'false') + }) +}) diff --git a/E2E/Profilepage.spec.ts b/E2E/Profilepage.spec.ts new file mode 100644 index 0000000..8a8de48 --- /dev/null +++ b/E2E/Profilepage.spec.ts @@ -0,0 +1,69 @@ + +import { test, expect } from './fixtures' +import type { Page } from '@playwright/test' + +async function editUserProfile(page: Page) { + await page.goto('/#/ProfilePage') + + // Confirm the profile page has loaded + await expect( + page.getByRole('heading', { name: 'Profile', exact: true }) + ).toBeVisible() + + // Open profile editor + const editButton = page.getByRole('button', { + name: 'Edit profile', + exact: true + }) + + await expect(editButton).toBeVisible() + await editButton.click() + + const newDescription = 'This is my updated profile description.' + + await page.getByRole('textbox', { + name: 'Description' + }).fill(newDescription) + + await page.getByRole('button', { + name: 'Save profile', + exact: true + }).click() + + // Confirm the updated description is displayed + await expect( + page.getByText(newDescription, { exact: true }) + ).toBeVisible() +} + +// Desktop profile tests +test.describe('Desktop ProfilePage', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test('User can edit their profile', async ({ page, user }) => { + await editUserProfile(page) + }) +}) + +// Mobile profile tests +test.describe('Mobile ProfilePage', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test('User can edit their profile on mobile', async ({ page, user }) => { + await editUserProfile(page) + }) +}) diff --git a/E2E/Reviews.spec.ts b/E2E/Reviews.spec.ts new file mode 100644 index 0000000..9e04dcd --- /dev/null +++ b/E2E/Reviews.spec.ts @@ -0,0 +1,71 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' +import type { Page } from '@playwright/test' + +const GAME_PAGE = /#\/gamepage\/\d+$/ + +async function navigateFromRecentReviewToGame( + page: Page, + userId: number, + seedReview: (userId: number) => Promise + ) { + await seedReview(userId) + await openMainPage(page) + + const reviewsSection = page.locator('section.main-page-reviews') + + await expect( + reviewsSection.getByRole('heading', { name: /recent reviews/i }) + ).toBeVisible() + + const seeGameLink = reviewsSection.getByRole('link', { + name: 'See this game', + exact: true + }).first() + + await expect(seeGameLink).toBeVisible() + await seeGameLink.click() + + await expect(page).toHaveURL(GAME_PAGE) +} + +// Desktop tests + test.describe('Desktop Recent Reviews', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test('Recent Reviews - navigate to a game', async ({ + page, + user, + seedReview + }) => { + await navigateFromRecentReviewToGame(page, user.id, seedReview) + }) +}) + +// Mobile tests +test.describe('Mobile Recent Reviews', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.use({ + viewport: { width: 390, height: 844 } + }) + + test('Recent Reviews - navigate to a game on mobile', async ({ + page, + user, + seedReview + }) => { + await navigateFromRecentReviewToGame(page, user.id, seedReview) + }) +}) diff --git a/E2E/Searchpage.spec.ts b/E2E/Searchpage.spec.ts new file mode 100644 index 0000000..9f40717 --- /dev/null +++ b/E2E/Searchpage.spec.ts @@ -0,0 +1,233 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' +import type { Page } from '@playwright/test' + +const SEARCH_PAGE = /#\/SearchPage$/ + +async function waitForSearchPage(page: Page) { + await expect(page).toHaveURL(SEARCH_PAGE) + + await expect( + page.locator('.games-grid-searchpage') + ).toBeVisible() + + await expect( + page.getByText('Loading games...') + ).toHaveCount(0) +} + +async function openDesktopSearchPage(page: Page) { + await openMainPage(page) + + await page.getByRole('link', { + name: /browse games/i + }).click() + + await waitForSearchPage(page) +} + +async function openMobileSearchPage(page: Page) { + await openMainPage(page) + + await page.getByRole('button', { + name: 'Open menu' + }).click() + + await page.getByRole('link', { + name: 'Search', + exact: true + }).click() + + await waitForSearchPage(page) +} + +async function openFiltersIfNeeded(page: Page) { + const toggle = page.getByRole('button', { + name: 'Toggle filters' + }) + + await expect(toggle).toBeVisible() + + if (await toggle.getAttribute('aria-pressed') !== 'true') { + await toggle.click() + } +} + +async function searchForGames(page: Page) { + const searchInput = page.getByPlaceholder( + 'Search here or use filter' + ) + + await searchInput.fill('The Witcher') + + await expect( + page.locator('.games-grid-searchpage') + ).toContainText(/witcher/i) +} + +async function filterGamesByGenre(page: Page) { + await openFiltersIfNeeded(page) + + const filter = page.getByRole('combobox', { + name: 'Filter by genre' + }) + + await expect(filter).toBeVisible() + await filter.click() + + const firstOption = page.getByRole('option').first() + await expect(firstOption).toBeVisible() + + const genreName = (await firstOption.innerText()).trim() + await firstOption.click() + + await expect( + page.locator('.MuiSelect-select').filter({ + hasText: genreName + }) + ).toBeVisible() + + await expect(page.locator('.filtersection')).toBeVisible() + await expect(page.locator('.games-grid-searchpage')).toBeVisible() +} + +async function sortGames(page: Page) { + await openFiltersIfNeeded(page) + + const sortDropdown = page.getByRole('combobox', { + name: 'Sort by' + }) + + await expect(sortDropdown).toBeVisible() + await sortDropdown.click() + + await page.getByRole('option', { + name: 'Title: Z to A' + }).click() + + await expect(sortDropdown).toContainText('Title: Z to A') +} + +async function checkSearchPagination(page: Page, checkReturnToFirstPage = true) { + const gameCards = page.locator( + '.games-grid-searchpage > *' + ) + + const pagination = page.locator('.pageinationSearch') + + await expect(gameCards).toHaveCount(12) + + const firstPageFirstGame = ( + await gameCards.first().innerText() + ).replace(/\s+/g, ' ').trim() + + await pagination.getByRole('button', { + name: 'Go to page 2' + }).click() + + await expect.poll(async () => { + return (await gameCards.first().innerText()) + .replace(/\s+/g, ' ') + .trim() + }).not.toBe(firstPageFirstGame) + + await expect(gameCards).toHaveCount(12) + + if (checkReturnToFirstPage) { + await pagination.getByRole('button', { + name: 'Go to page 1' + }).click() + + await expect.poll(async () => { + return (await gameCards.first().innerText()) + .replace(/\s+/g, ' ') + .trim() + }).toBe(firstPageFirstGame) + } +} + +// Desktop SearchPage tests +test.describe('Desktop SearchPage', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test.beforeEach(async ({ page }) => { + await openDesktopSearchPage(page) + }) + + test('Search for games', async ({ page }) => { + await searchForGames(page) + }) + + test('Search with no matching results', async ({ page }) => { + const searchInput = page.getByPlaceholder( + 'Search here or use filter' + ) + + await searchInput.fill('rtrdfghriufhwe') + + await expect( + page.getByText('No games found.') + ).toBeVisible() + }) + + test('Filter games by genre', async ({ page }) => { + await filterGamesByGenre(page) + }) + + test('Sort games', async ({ page }) => { + await sortGames(page) + }) + + test('User can navigate between pages of search results', async ({ page }) => { + await checkSearchPagination(page) + }) +}) + +// Mobile SearchPage tests +test.describe('Mobile SearchPage', () => { + test.use({ + viewport: { width: 390, height: 844 } + }) + + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.beforeEach(async ({ page }) => { + await openMobileSearchPage(page) + }) + + test('Search input works on mobile', async ({ page }) => { + await searchForGames(page) + }) + + test('Mobile users can filter games by genre', async ({ page }) => { + await filterGamesByGenre(page) + }) + + test('Mobile users can sort games', async ({ page }) => { + await sortGames(page) + }) + + test('Mobile search results have no horizontal overflow', async ({ page }) => { + const hasOverflow = await page.evaluate(() => { + return document.documentElement.scrollWidth > + document.documentElement.clientWidth + }) + + expect(hasOverflow).toBe(false) + }) + + test('Mobile users can navigate between search result pages', async ({ page }) => { + await checkSearchPagination(page, false) + }) +}) diff --git a/E2E/Wishlist.spec.ts b/E2E/Wishlist.spec.ts new file mode 100644 index 0000000..841ef76 --- /dev/null +++ b/E2E/Wishlist.spec.ts @@ -0,0 +1,166 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' +import type { Page } from '@playwright/test' + +const WISHLIST_PAGE = /#\/WishlistPage$/ +const GAME_PAGE = /#\/gamepage\/\d+$/ + +async function openDesktopWishlistPage( + page: Page, + userId: number, + seedWishlist: (userId: number, count: number) => Promise + ) { + await seedWishlist(userId, 3) + await openMainPage(page) + + await page.getByRole('link', { + name: 'Wishlist', + exact: true + }).click() + + await waitForWishlistPage(page) +} + +async function openMobileWishlistPage( + page: Page, + userId: number, + seedWishlist: (userId: number, count: number) => Promise + ) { + await seedWishlist(userId, 3) + await openMainPage(page) + + await page.getByRole('button', { + name: 'Open menu' + }).click() + + await page.getByRole('link', { + name: 'Wishlist', + exact: true + }).click() + + await waitForWishlistPage(page) +} + +async function waitForWishlistPage(page: Page) { + await expect(page).toHaveURL(WISHLIST_PAGE) + await expect(page.getByText('Loading games...')).toHaveCount(0) +} + +async function openWishlistedGameAndGoBack(page: Page) { + const firstGame = page.locator('a[href*="gamepage"]').first() + + await expect(firstGame).toBeVisible() + await firstGame.click() + + await expect(page).toHaveURL(GAME_PAGE) + + await page.getByRole('button', { + name: /back/i + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) +} + +async function sortWishlistGames(page: Page) { + const sortDropdown = page.getByRole('combobox', { + name: /sort by/i + }) + + await expect(sortDropdown).toBeVisible() + await sortDropdown.click() + + await page.getByRole('option', { + name: 'Price: low to high' + }).click() + + await expect(sortDropdown).toContainText('Price: low to high') +} + +async function removeGameFromWishlist(page: Page) { + const firstGame = page.locator('a[href*="gamepage"]').first() + + await expect(firstGame).toBeVisible() + + const gameName = (await firstGame.innerText()).trim() + + const removeButton = page.getByRole('button', { + name: /remove/i + }).first() + + await expect(removeButton).toBeVisible() + await removeButton.click() + + await expect( + page.getByText(gameName, { exact: false }) + ).toHaveCount(0) +} + +async function checkWishlistHorizontalOverflow(page: Page) { + const hasOverflow = await page.evaluate(() => { + return document.documentElement.scrollWidth > + document.documentElement.clientWidth + }) + + expect(hasOverflow).toBe(false) +} + +// Desktop WishlistPage tests +test.describe('Desktop WishlistPage', () => { + test.beforeEach(async ({}, testInfo) => { + test.skip( + ['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Desktop tests are not run on mobile projects' + ) + }) + + test.beforeEach(async ({ page, user, seedWishlist }) => { + await openDesktopWishlistPage(page, user.id, seedWishlist) + }) + + test('Open a wishlisted game and navigate back', async ({ page }) => { + await openWishlistedGameAndGoBack(page) + }) + + test('Sort wishlist games', async ({ page }) => { + await sortWishlistGames(page) + }) + + test('Remove a game from wishlist', async ({ page }) => { + await removeGameFromWishlist(page) + }) +}) + +// Mobile WishlistPage tests +test.describe('Mobile WishlistPage', () => { + test.use({ + viewport: { width: 390, height: 844 } + }) + + test.beforeEach(async ({}, testInfo) => { + test.skip( + !['mobile-chrome', 'Mobile Safari'].includes(testInfo.project.name), + 'Mobile tests are only run on mobile projects' + ) + }) + + test.beforeEach(async ({ page, user, seedWishlist }) => { + await openMobileWishlistPage(page, user.id, seedWishlist) + }) + + test('Mobile user can open a wishlisted game and navigate back', async ({ page }) => { + await openWishlistedGameAndGoBack(page) + }) + + test('Mobile user can sort wishlist games', async ({ page }) => { + await sortWishlistGames(page) + }) + + test('Mobile user can remove a game from wishlist', async ({ page }) => { + await removeGameFromWishlist(page) + }) + + test('Mobile wishlist has no horizontal overflow', async ({ page }) => { + await checkWishlistHorizontalOverflow(page) + }) +}) diff --git a/E2E/api/HelpersAPI.ts b/E2E/api/HelpersAPI.ts new file mode 100644 index 0000000..2766b8f --- /dev/null +++ b/E2E/api/HelpersAPI.ts @@ -0,0 +1,46 @@ +import type { APIRequestContext } from '@playwright/test' +import { BACKEND_URL } from '../E2EConfig' + +export type GqlResult = { data: T | null; errors?: { message: string }[] } +export type ApiUser = { id: number; email: string; username: string; token: string } + +export async function Gql>( + request: APIRequestContext, + query: string, + variables: Record = {}, + token?: string, +): Promise> { + const res = await request.post(BACKEND_URL, { + data: { query, variables }, + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }) + return (await res.json()) as GqlResult +} + +export function Unique(label: string) { + return `${label}${Date.now()}${Math.random().toString(36).slice(2, 6)}` +} + +export async function NewUser(request: APIRequestContext, label = 'api'): Promise { + const id = Unique(label) + const { data, errors } = await Gql<{ signup: ApiUser }>( + request, + `mutation($u: String!, $e: String!, $p: String!) { + signup(username: $u, email: $e, password: $p) { id email username token } + }`, + { u: id, e: `${id}@example.com`, p: 'secret123' }, + ) + if (errors) throw new Error(errors[0].message) + return data!.signup +} + +export async function SomeGames(request: APIRequestContext, count: number, offset = 0) { + const { data } = await Gql<{ games: { appid: number; name: string }[] }>( + request, + `query($l: Int, $o: Int) { games(limit: $l, offset: $o, sort: "title-asc") { appid name } }`, + { l: count, o: offset }, + ) + return data!.games +} + +export const GAME_FIELDS = 'appid name price initialprice discount img genre description' \ No newline at end of file diff --git a/E2E/api/auth.api.spec.ts b/E2E/api/auth.api.spec.ts new file mode 100644 index 0000000..e202f79 --- /dev/null +++ b/E2E/api/auth.api.spec.ts @@ -0,0 +1,73 @@ +import { test, expect } from '@playwright/test' +import { Gql, NewUser, Unique, type ApiUser } from './HelpersAPI' + +const SIGNUP = `mutation($u: String!, $e: String!, $p: String!) { + signup(username: $u, email: $e, password: $p) { id email username token } +}` +const SIGNIN = `mutation($e: String!, $p: String!) { + signin(email: $e, password: $p) { id email username token } +}` + +test.describe('auth', () => { + test('signup returns a user with id and token', async ({ request }) => { + const name = Unique('signup') + const { data, errors } = await Gql<{ signup: ApiUser }>(request, SIGNUP, { + u: name, + e: `${name}@example.com`, + p: 'secret123', + }) + expect(errors).toBeUndefined() + expect(data!.signup.id).toBeGreaterThan(0) + expect(data!.signup.username).toBe(name) + expect(data!.signup.email).toBe(`${name}@example.com`) + expect(data!.signup.token.length).toBeGreaterThan(0) + }) + + test('signup with an email that already exists fails', async ({ request }) => { + const user = await NewUser(request) + const { data, errors } = await Gql(request, SIGNUP, { + u: Unique('dup'), + e: user.email, + p: 'secret123', + }) + expect(data).toBeNull() + expect(errors?.length).toBeGreaterThan(0) + }) + + test('signin with the right password returns the same user', async ({ request }) => { + const user = await NewUser(request) + const { data, errors } = await Gql<{ signin: ApiUser }>(request, SIGNIN, { + e: user.email, + p: 'secret123', + }) + expect(errors).toBeUndefined() + expect(data!.signin.id).toBe(user.id) + expect(data!.signin.token.length).toBeGreaterThan(0) + }) + + test('signin with a wrong password fails', async ({ request }) => { + const user = await NewUser(request) + const { data, errors } = await Gql(request, SIGNIN, { e: user.email, p: 'wrongpass1' }) + expect(data).toBeNull() + expect(errors?.length).toBeGreaterThan(0) + }) + + test('signin with an unknown email fails', async ({ request }) => { + const { data, errors } = await Gql(request, SIGNIN, { + e: `${Unique('nobody')}@example.com`, + p: 'secret123', + }) + expect(data).toBeNull() + expect(errors?.length).toBeGreaterThan(0) + }) + + test('the password hash is never part of the schema', async ({ request }) => { + const user = await NewUser(request) + const { errors } = await Gql( + request, + `mutation($e: String!, $p: String!) { signin(email: $e, password: $p) { password_hash } }`, + { e: user.email, p: 'secret123' }, + ) + expect(errors?.length).toBeGreaterThan(0) + }) +}) \ No newline at end of file diff --git a/E2E/api/friends.api.spec.ts b/E2E/api/friends.api.spec.ts new file mode 100644 index 0000000..6f5bc5f --- /dev/null +++ b/E2E/api/friends.api.spec.ts @@ -0,0 +1,118 @@ +import { test, expect } from '@playwright/test' +import { GAME_FIELDS, Gql, NewUser, SomeGames } from './HelpersAPI' + +type Friend = { id: number; username: string; description: string | null; setup: string | null } + +const MY_CODE = `query($u: Int!) { myFriendId(userId: $u) }` +const ADD_FRIEND = `mutation($u: Int!, $c: String!) { addFriend(userId: $u, friendCode: $c) { id username } }` +const FRIENDS = `query($u: Int!) { friends(userId: $u) { id username description setup } }` +const FRIEND_WISHLIST = `query($u: Int!, $f: Int!) { friendWishlist(userId: $u, friendId: $f) { ${GAME_FIELDS} } }` +const ADD_WISH = `mutation($u: Int!, $g: Int!) { addToWishlist(userId: $u, gameId: $g) }` + +async function Code(request: import('@playwright/test').APIRequestContext, user: { id: number; token: string }) { + const { data } = await Gql<{ myFriendId: string }>(request, MY_CODE, { u: user.id }, user.token) + return data!.myFriendId +} + +test.describe('friends', () => { + test('every user gets an 8 character friend code', async ({ request }) => { + const user = await NewUser(request) + expect(await Code(request, user)).toMatch(/^[a-z0-9]{8}$/i) + }) + + test('add a friend by code and see them in the friends list', async ({ request }) => { + const me = await NewUser(request, 'me') + const friend = await NewUser(request, 'friend') + const code = await Code(request, friend) + + const added = await Gql<{ addFriend: Friend }>(request, ADD_FRIEND, { u: me.id, c: code }, me.token) + expect(added.errors).toBeUndefined() + expect(added.data!.addFriend.id).toBe(friend.id) + + const list = await Gql<{ friends: Friend[] }>(request, FRIENDS, { u: me.id }, me.token) + expect(list.data!.friends.map((f) => f.id)).toContain(friend.id) + }) + + test('adding an unknown code fails', async ({ request }) => { + const me = await NewUser(request) + const { errors } = await Gql(request, ADD_FRIEND, { u: me.id, c: 'zzzzzzzz' }, me.token) + expect(errors?.length).toBeGreaterThan(0) + }) + + test('adding yourself fails', async ({ request }) => { + const me = await NewUser(request) + const { errors } = await Gql(request, ADD_FRIEND, { u: me.id, c: await Code(request, me) }, me.token) + expect(errors?.length).toBeGreaterThan(0) + }) + + test('adding a friend without a token fails', async ({ request }) => { + const me = await NewUser(request) + const friend = await NewUser(request) + const { errors } = await Gql(request, ADD_FRIEND, { u: me.id, c: await Code(request, friend) }) + expect(errors?.length).toBeGreaterThan(0) + }) + + test('a friends wishlist can be read, a strangers cannot', async ({ request }) => { + const me = await NewUser(request, 'me') + const friend = await NewUser(request, 'friend') + const stranger = await NewUser(request, 'stranger') + const games = await SomeGames(request, 3) + for (const g of games) await Gql(request, ADD_WISH, { u: friend.id, g: g.appid }, friend.token) + await Gql(request, ADD_FRIEND, { u: me.id, c: await Code(request, friend) }, me.token) + + const ok = await Gql<{ friendWishlist: { appid: number }[] }>(request, FRIEND_WISHLIST, { u: me.id, f: friend.id }, me.token) + expect(ok.data!.friendWishlist).toHaveLength(3) + + const denied = await Gql(request, FRIEND_WISHLIST, { u: stranger.id, f: friend.id }, stranger.token) + expect(denied.errors?.length).toBeGreaterThan(0) + }) +}) + +test.describe('profile', () => { + const PROFILE = `query($u: Int!) { profile(userId: $u) { username description setup favouriteGame } }` + const UPDATE = `mutation($u: Int!, $i: ProfileInput!) { + updateProfile(userId: $u, input: $i) { username description setup favouriteGame } + }` + + test('a new profile has no description, setup or favourite game', async ({ request }) => { + const user = await NewUser(request) + + const { data, errors } = await Gql<{ profile: Record }>( + request, + PROFILE, + { u: user.id }, + user.token + ) + + expect(errors).toBeUndefined() + expect(data!.profile).toMatchObject({ + username: user.username, + description: null, + setup: null, + favouriteGame: null + }) + }) + + test('updateProfile saves description, setup and favourite game', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1) + const input = { description: 'Hello', setup: 'PC', favouriteGame: game.appid } + + const { data, errors } = await Gql<{ updateProfile: Record }>(request, UPDATE, { u: user.id, i: input }, user.token) + expect(errors).toBeUndefined() + expect(data!.updateProfile).toMatchObject(input) + + const read = await Gql<{ profile: Record }>( + request, PROFILE, { u: user.id }, user.token + ) + expect(read.data!.profile).toMatchObject(input) + }) + + + test('another user cannot update the profile', async ({ request }) => { + const owner = await NewUser(request, 'owner') + const intruder = await NewUser(request, 'intruder') + const { errors } = await Gql(request, UPDATE, { u: owner.id, i: { description: 'x', setup: null, favouriteGame: null } }, intruder.token) + expect(errors?.length).toBeGreaterThan(0) + }) +}) \ No newline at end of file diff --git a/E2E/api/games.api.spec.ts b/E2E/api/games.api.spec.ts new file mode 100644 index 0000000..94e0240 --- /dev/null +++ b/E2E/api/games.api.spec.ts @@ -0,0 +1,143 @@ +import { test, expect } from '@playwright/test' +import { GAME_FIELDS, Gql } from './HelpersAPI' + +type Game = { + appid: number + name: string + price: string + initialprice: string + discount: string + img: string + genre: string + description: string +} + +const GAMES = `query($l: Int, $o: Int, $s: String, $g: [String!], $sort: String) { + games(limit: $l, offset: $o, search: $s, genres: $g, sort: $sort) { ${GAME_FIELDS} } +}` +const COUNT = `query($s: String, $g: [String!]) { totalGameCount(search: $s, genres: $g) }` + +test.describe('games', () => { + test('returns games with all fields, and genre as a string', async ({ request }) => { + const { data } = await Gql<{ games: Game[] }>(request, GAMES, { l: 5 }) + expect(data!.games).toHaveLength(5) + for (const g of data!.games) { + expect(g.appid).toBeGreaterThan(0) + expect(g.name.length).toBeGreaterThan(0) + expect(typeof g.price).toBe('string') + expect(typeof g.genre).toBe('string') + } + }) + + test('limit and offset page through the games without overlap', async ({ request }) => { + const first = await Gql<{ games: Game[] }>(request, GAMES, { l: 5, o: 0 }) + const second = await Gql<{ games: Game[] }>(request, GAMES, { l: 5, o: 5 }) + const ids1 = first.data!.games.map((g) => g.appid) + const ids2 = second.data!.games.map((g) => g.appid) + expect(ids2).toHaveLength(5) + expect(ids1.filter((id) => ids2.includes(id))).toHaveLength(0) + }) + + test('search matches names case-insensitively', async ({ request }) => { + const [{ name }] = (await Gql<{ games: Game[] }>(request, GAMES, { l: 1 })).data!.games + const term = name.slice(0, 3).toUpperCase() + const { data } = await Gql<{ games: Game[] }>(request, GAMES, { l: 50, s: term }) + expect(data!.games.length).toBeGreaterThan(0) + for (const g of data!.games) expect(g.name.toLowerCase()).toContain(term.toLowerCase()) + }) + + test('search that matches nothing returns an empty list and count 0', async ({ request }) => { + const list = await Gql<{ games: Game[] }>(request, GAMES, { s: 'rtrdfghriufhwe' }) + expect(list.data!.games).toEqual([]) + const count = await Gql<{ totalGameCount: number }>(request, COUNT, { s: 'rtrdfghriufhwe' }) + expect(count.data!.totalGameCount).toBe(0) + }) + + test('search ranks names starting with the word before names that only contain it', async ({ + request, + }) => { + const [{ name }] = (await Gql<{ games: Game[] }>(request, GAMES, { l: 1 })).data!.games + const word = name.split(/\s+/)[0].replace(/[^\p{L}\p{N}]/gu, '') + test.skip(word.length < 3, 'First game name has no usable first word') + const { data } = await Gql<{ games: Game[] }>(request, GAMES, { l: 500, s: word }) + const starts = (n: string) => new RegExp(`^${word}\\b`, 'i').test(n) + const flags = data!.games.map((g) => starts(g.name)) + // Once a game that does not start with the word appears, no start-with game may follow + const firstNonStart = flags.indexOf(false) + if (firstNonStart !== -1) expect(flags.slice(firstNonStart)).not.toContain(true) + }) + + for (const [sort, cmp] of [ + ['price-asc', (a: number, b: number) => a <= b], + ['price-desc', (a: number, b: number) => a >= b], + ['discount-desc', (a: number, b: number) => a >= b], + ] as const) { + test(`sort ${sort} orders the result`, async ({ request }) => { + const { data } = await Gql<{ games: Game[] }>(request, GAMES, { l: 50, sort }) + const key = sort.startsWith('price') ? 'price' : 'discount' + const values = data!.games.map((g) => Number(g[key])) + for (let i = 1; i < values.length; i++) expect(cmp(values[i - 1], values[i])).toBe(true) + }) + } + + test('sort title-asc orders by name', async ({ request }) => { + const { data } = await Gql<{ games: Game[] }>(request, GAMES, { l: 50, sort: 'title-asc' }) + const names = data!.games.map((g) => g.name) + expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b, 'en'))) + }) + + test('an unknown sort value is ignored, not an error', async ({ request }) => { + const { data, errors } = await Gql<{ games: Game[] }>(request, GAMES, { l: 3, sort: 'nonsense' }) + expect(errors).toBeUndefined() + expect(data!.games).toHaveLength(3) + }) + + test('genre filter only returns games that have the genre', async ({ request }) => { + const genres = (await Gql<{ genres: string[] }>(request, `query { genres }`)).data!.genres + const genre = genres[0] + const { data } = await Gql<{ games: Game[] }>(request, GAMES, { l: 20, g: [genre] }) + expect(data!.games.length).toBeGreaterThan(0) + for (const g of data!.games) expect(g.genre).toContain(genre) + }) + + test('several genres require all of them', async ({ request }) => { + const [first] = (await Gql<{ games: Game[] }>(request, GAMES, { l: 200 })).data!.games.filter( + (g) => g.genre.includes(','), + ) + test.skip(!first, 'No game with two genres in the database') + const wanted = first.genre.split(',').map((s) => s.trim()).slice(0, 2) + const { data } = await Gql<{ games: Game[] }>(request, GAMES, { l: 200, g: wanted }) + expect(data!.games.map((g) => g.appid)).toContain(first.appid) + for (const g of data!.games) for (const w of wanted) expect(g.genre).toContain(w) + }) + + test('game(appid) returns one game, and null for an unknown id', async ({ request }) => { + const [{ appid }] = (await Gql<{ games: Game[] }>(request, GAMES, { l: 1 })).data!.games + const found = await Gql<{ game: Game }>( + request, + `query($id: Int!) { game(appid: $id) { ${GAME_FIELDS} } }`, + { id: appid }, + ) + expect(found.data!.game.appid).toBe(appid) + const missing = await Gql<{ game: Game | null }>( + request, + `query($id: Int!) { game(appid: $id) { appid } }`, + { id: 2147483000 }, + ) + expect(missing.data!.game).toBeNull() + }) + + test('genres returns a list of unique names', async ({ request }) => { + const { data } = await Gql<{ genres: string[] }>(request, `query { genres }`) + const genres = data!.genres + expect(genres.length).toBeGreaterThan(0) + expect(new Set(genres).size).toBe(genres.length) + expect(genres.every((g) => !g.includes(','))).toBe(true) + }) + + test('a query for a field that does not exist is rejected', async ({ request }) => { + const { data, errors } = await Gql(request, `query { games { doesNotExist } }`) + expect(data).toBeUndefined() + expect(errors?.length).toBeGreaterThan(0) + }) +}) \ No newline at end of file diff --git a/E2E/api/mainpage.api.spec.ts b/E2E/api/mainpage.api.spec.ts new file mode 100644 index 0000000..6103344 --- /dev/null +++ b/E2E/api/mainpage.api.spec.ts @@ -0,0 +1,75 @@ +import { test, expect } from '@playwright/test' +import { GAME_FIELDS, Gql } from './HelpersAPI' + +type Game = { appid: number; name: string; discount: string; genre: string } + +test.describe('main page queries', () => { + test('top3Games returns exactly three distinct games', async ({ request }) => { + const { data } = await Gql<{ top3Games: Game[] }>(request, `query { top3Games { ${GAME_FIELDS} } }`) + expect(data!.top3Games).toHaveLength(3) + expect(new Set(data!.top3Games.map((g) => g.appid)).size).toBe(3) + }) + + test('topGamesByGenre returns at most 10 games, all in the genre', async ({ request }) => { + const genres = (await Gql<{ genres: string[] }>(request, `query { genres }`)).data!.genres + for (const genre of genres.slice(0, 5)) { + const { data } = await Gql<{ topGamesByGenre: Game[] }>( + request, + `query($g: String!) { topGamesByGenre(genre: $g) { ${GAME_FIELDS} } }`, + { g: genre }, + ) + expect(data!.topGamesByGenre.length).toBeLessThanOrEqual(10) + for (const g of data!.topGamesByGenre) expect(g.genre).toContain(genre) + } + }) + + test('discountedGames only returns discounted games, biggest discount first, max 10', async ({ request }) => { + const genres = (await Gql<{ genres: string[] }>(request, `query { genres }`)).data!.genres + for (const genre of genres.slice(0, 8)) { + const { data } = await Gql<{ discountedGames: Game[] }>( + request, + `query($g: String!) { discountedGames(genre: $g) { ${GAME_FIELDS} } }`, + { g: genre }, + ) + const list = data!.discountedGames + expect(list.length).toBeLessThanOrEqual(10) + const discounts = list.map((g) => Number(g.discount)) + expect(discounts.every((d) => d > 0)).toBe(true) + expect(discounts).toEqual([...discounts].sort((a, b) => b - a)) + } + }) + + test('the genre lookup ignores case', async ({ request }) => { + const genre = (await Gql<{ genres: string[] }>(request, `query { genres }`)).data!.genres[0] + const q = `query($g: String!) { topGamesByGenre(genre: $g) { appid } }` + const a = await Gql<{ topGamesByGenre: Game[] }>(request, q, { g: genre }) + const b = await Gql<{ topGamesByGenre: Game[] }>(request, q, { g: genre.toUpperCase() }) + expect(b.data!.topGamesByGenre).toEqual(a.data!.topGamesByGenre) + }) + + test('an unknown genre returns an empty list', async ({ request }) => { + const { data } = await Gql<{ topGamesByGenre: Game[] }>( + request, + `query($g: String!) { topGamesByGenre(genre: $g) { appid } }`, + { g: 'NoSuchGenre123' }, + ) + expect(data!.topGamesByGenre).toEqual([]) + }) + + test('top games are ranked by review score', async ({ request }) => { + // Seed a game with the best possible reviews and check it ranks above unreviewed ones + const { NewUser, SomeGames } = await import('./HelpersAPI') + const [game] = await SomeGames(request, 1, 20) + const reviewers = await Promise.all([NewUser(request), NewUser(request), NewUser(request)]) + for (const u of reviewers) { + await Gql( + request, + `mutation($u: Int!, $g: Int!) { createReview(userId: $u, gameId: $g, rating: 5, text: "top") { id } }`, + { u: u.id, g: game.appid }, + u.token, + ) + } + const { data } = await Gql<{ top3Games: Game[] }>(request, `query { top3Games { appid } }`) + expect(data!.top3Games.map((g) => g.appid)).toContain(game.appid) + }) +}) \ No newline at end of file diff --git a/E2E/api/reviews.api.spec.ts b/E2E/api/reviews.api.spec.ts new file mode 100644 index 0000000..edf7a67 --- /dev/null +++ b/E2E/api/reviews.api.spec.ts @@ -0,0 +1,126 @@ +import { test, expect } from '@playwright/test' +import { Gql, NewUser, SomeGames } from './HelpersAPI' + +type Review = { id: number; gameId: number; userId: number | null; reviewer: string; rating: number; text: string; gameName?: string } + +const FIELDS = 'id gameId userId reviewer rating text' +const CREATE = `mutation($u: Int!, $g: Int!, $r: Int!, $t: String!) { + createReview(userId: $u, gameId: $g, rating: $r, text: $t) { ${FIELDS} } +}` +const UPDATE = `mutation($id: Int!, $u: Int!, $r: Int!, $t: String!) { + updateReview(reviewId: $id, userId: $u, rating: $r, text: $t) { ${FIELDS} } +}` +const DELETE = `mutation($id: Int!, $u: Int!) { deleteReview(reviewId: $id, userId: $u) }` +const FOR_GAME = `query($g: Int!, $u: Int) { reviews(gameId: $g, userId: $u) { ${FIELDS} } }` +const RECENT = `query($l: Int) { recentReviews(limit: $l) { ${FIELDS} gameName } }` + +test.describe('reviews', () => { + test('create a review and read it back', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1) + + const created = await Gql<{ createReview: Review }>(request, CREATE, { u: user.id, g: game.appid, r: 4, t: 'Fun game' }, user.token) + expect(created.errors).toBeUndefined() + expect(created.data!.createReview).toMatchObject({ gameId: game.appid, userId: user.id, rating: 4, text: 'Fun game', reviewer: user.username }) + + const list = await Gql<{ reviews: Review[] }>(request, FOR_GAME, { g: game.appid }) + expect(list.data!.reviews.map((r) => r.id)).toContain(created.data!.createReview.id) + }) + + test('the current users own review comes first', async ({ request }) => { + const author = await NewUser(request, 'first') + const other = await NewUser(request, 'second') + const [game] = await SomeGames(request, 1, 3) + await Gql(request, CREATE, { u: author.id, g: game.appid, r: 3, t: 'a' }, author.token) + await Gql(request, CREATE, { u: other.id, g: game.appid, r: 5, t: 'b' }, other.token) + + const { data } = await Gql<{ reviews: Review[] }>(request, FOR_GAME, { g: game.appid, u: author.id }) + expect(data!.reviews[0].userId).toBe(author.id) + }) + + test('a user can only have one review per game', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1, 1) + await Gql(request, CREATE, { u: user.id, g: game.appid, r: 4, t: 'one' }, user.token) + const second = await Gql(request, CREATE, { u: user.id, g: game.appid, r: 2, t: 'two' }, user.token) + expect(second.errors?.length).toBeGreaterThan(0) + }) + + for (const rating of [0, 6, -1]) { + test(`rating ${rating} is rejected`, async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1, 2) + const { errors } = await Gql(request, CREATE, { u: user.id, g: game.appid, r: rating, t: 'x' }, user.token) + expect(errors?.length).toBeGreaterThan(0) + }) + } + + test('a text over 500 characters is rejected', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1, 2) + const { errors } = await Gql(request, CREATE, { u: user.id, g: game.appid, r: 3, t: 'x'.repeat(501) }, user.token) + expect(errors?.length).toBeGreaterThan(0) + }) + + test('creating a review without a token fails', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1) + const { errors } = await Gql(request, CREATE, { u: user.id, g: game.appid, r: 3, t: 'x' }) + expect(errors?.length).toBeGreaterThan(0) + }) + + test('update changes rating and text', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1, 4) + const created = await Gql<{ createReview: Review }>(request, CREATE, { u: user.id, g: game.appid, r: 2, t: 'old' }, user.token) + const id = created.data!.createReview.id + + const updated = await Gql<{ updateReview: Review }>(request, UPDATE, { id, u: user.id, r: 5, t: 'new' }, user.token) + expect(updated.errors).toBeUndefined() + expect(updated.data!.updateReview).toMatchObject({ id, rating: 5, text: 'new' }) + }) + + test('another user cannot update or delete a review', async ({ request }) => { + const owner = await NewUser(request, 'owner') + const intruder = await NewUser(request, 'intruder') + const [game] = await SomeGames(request, 1, 5) + const created = await Gql<{ createReview: Review }>(request, CREATE, { u: owner.id, g: game.appid, r: 3, t: 'mine' }, owner.token) + const id = created.data!.createReview.id + + const upd = await Gql(request, UPDATE, { id, u: intruder.id, r: 1, t: 'hacked' }, intruder.token) + expect(upd.errors?.length).toBeGreaterThan(0) + const del = await Gql(request, DELETE, { id, u: intruder.id }, intruder.token) + expect(del.errors?.length).toBeGreaterThan(0) + + const { data } = await Gql<{ reviews: Review[] }>(request, FOR_GAME, { g: game.appid }) + expect(data!.reviews.find((r) => r.id === id)?.text).toBe('mine') + }) + + test('delete removes the review', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1, 6) + const created = await Gql<{ createReview: Review }>(request, CREATE, { u: user.id, g: game.appid, r: 3, t: 'bye' }, user.token) + const id = created.data!.createReview.id + + const del = await Gql<{ deleteReview: boolean }>(request, DELETE, { id, u: user.id }, user.token) + expect(del.data!.deleteReview).toBe(true) + const { data } = await Gql<{ reviews: Review[] }>(request, FOR_GAME, { g: game.appid }) + expect(data!.reviews.map((r) => r.id)).not.toContain(id) + }) + + test('recentReviews includes the new review with the game name, and respects the limit', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1, 7) + const created = await Gql<{ createReview: Review }>(request, CREATE, { u: user.id, g: game.appid, r: 5, t: 'recent' }, user.token) + + const { data } = await Gql<{ recentReviews: Review[] }>(request, RECENT, { l: 3 }) + expect(data!.recentReviews.length).toBeLessThanOrEqual(3) + const mine = data!.recentReviews.find((r) => r.id === created.data!.createReview.id) + expect(mine?.gameName).toBe(game.name) + }) + + test('reviews on a game with none returns an empty list', async ({ request }) => { + const { data } = await Gql<{ reviews: Review[] }>(request, FOR_GAME, { g: 2147483000 }) + expect(data!.reviews).toEqual([]) + }) +}) \ No newline at end of file diff --git a/E2E/api/wishlist.api.spec.ts b/E2E/api/wishlist.api.spec.ts new file mode 100644 index 0000000..5982c50 --- /dev/null +++ b/E2E/api/wishlist.api.spec.ts @@ -0,0 +1,83 @@ +import { test, expect } from '@playwright/test' +import { GAME_FIELDS, Gql, NewUser, SomeGames } from './HelpersAPI' + +const ADD = `mutation($u: Int!, $g: Int!) { addToWishlist(userId: $u, gameId: $g) }` +const REMOVE = `mutation($u: Int!, $g: Int!) { removeFromWishlist(userId: $u, gameId: $g) }` +const LIST = `query($u: Int!) { wishlist(userId: $u) { ${GAME_FIELDS} } }` + +test.describe('wishlist', () => { + test('a new user has an empty wishlist', async ({ request }) => { + const user = await NewUser(request) + const { data } = await Gql<{ wishlist: unknown[] }>(request, LIST, { u: user.id }, user.token) + expect(data!.wishlist).toEqual([]) + }) + + test('add, list and remove a game', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1) + + const add = await Gql<{ addToWishlist: boolean }>(request, ADD, { u: user.id, g: game.appid }, user.token) + expect(add.data!.addToWishlist).toBe(true) + + const list = await Gql<{ wishlist: { appid: number }[] }>(request, LIST, { u: user.id }, user.token) + expect(list.data!.wishlist.map((g) => g.appid)).toEqual([game.appid]) + + const remove = await Gql<{ removeFromWishlist: boolean }>(request, REMOVE, { u: user.id, g: game.appid }, user.token) + expect(remove.data!.removeFromWishlist).toBe(true) + + const after = await Gql<{ wishlist: unknown[] }>(request, LIST, { u: user.id }, user.token) + expect(after.data!.wishlist).toEqual([]) + }) + + test('adding the same game twice does not create a duplicate', async ({ request }) => { + const user = await NewUser(request) + const [game] = await SomeGames(request, 1) + await Gql(request, ADD, { u: user.id, g: game.appid }, user.token) + await Gql(request, ADD, { u: user.id, g: game.appid }, user.token) + const { data } = await Gql<{ wishlist: unknown[] }>(request, LIST, { u: user.id }, user.token) + expect(data!.wishlist).toHaveLength(1) + }) + + test('the wishlist is sorted by game name', async ({ request }) => { + const user = await NewUser(request) + const games = await SomeGames(request, 4) + for (const g of [...games].reverse()) await Gql(request, ADD, { u: user.id, g: g.appid }, user.token) + const { data } = await Gql<{ wishlist: { name: string }[] }>(request, LIST, { u: user.id }, user.token) + const names = data!.wishlist.map((g) => g.name) + expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b, 'en'))) + }) + + test('reading a wishlist without a token fails', async ({ request }) => { + const user = await NewUser(request) + const { data, errors } = await Gql(request, LIST, { u: user.id }) + expect(data).toBeNull() + expect(errors?.length).toBeGreaterThan(0) + }) + + test('a user cannot read or change another users wishlist', async ({ request }) => { + const owner = await NewUser(request, 'owner') + const intruder = await NewUser(request, 'intruder') + const [game] = await SomeGames(request, 1) + + const read = await Gql(request, LIST, { u: owner.id }, intruder.token) + expect(read.errors?.length).toBeGreaterThan(0) + + const add = await Gql(request, ADD, { u: owner.id, g: game.appid }, intruder.token) + expect(add.errors?.length).toBeGreaterThan(0) + + const remove = await Gql(request, REMOVE, { u: owner.id, g: game.appid }, intruder.token) + expect(remove.errors?.length).toBeGreaterThan(0) + }) + + test('an invalid token is rejected', async ({ request }) => { + const user = await NewUser(request) + const { errors } = await Gql(request, LIST, { u: user.id }, 'not-a-real-token') + expect(errors?.length).toBeGreaterThan(0) + }) + + test('adding a game that does not exist fails', async ({ request }) => { + const user = await NewUser(request) + const { errors } = await Gql(request, ADD, { u: user.id, g: 2147483000 }, user.token) + expect(errors?.length).toBeGreaterThan(0) + }) +}) \ No newline at end of file diff --git a/E2E/helpers.ts b/E2E/helpers.ts new file mode 100644 index 0000000..1de3ce2 --- /dev/null +++ b/E2E/helpers.ts @@ -0,0 +1,83 @@ + +import { expect } from './fixtures' +import type { Page } from '@playwright/test' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ + +// Reusable helpers + +export async function openMainPage(page: Page) { + await page.goto('/') + await expect(page).toHaveURL(MAIN_PAGE) +} + +export async function getSection(page: Page, heading: string) { + const headingLocator = page.getByRole('heading', { + name: heading, + exact: true + }) + + await expect(headingLocator).toBeVisible() + + return headingLocator.locator('xpath=ancestor::section[1]') +} + +export async function testCarousel(page: Page, heading: string) { + const section = await getSection(page, heading) + + const nextButton = section.getByRole('button', { + name: 'Next', + exact: true + }) + + const previousButton = section.getByRole('button', { + name: 'Previous', + exact: true + }) + + const gameCards = section.locator( + '.genre-games-row a[href*="gamepage/"]' + ) + + await expect(nextButton).toBeVisible() + await expect(previousButton).toBeVisible() + + // Wait until the games have finished loading. + await expect(section.getByText(/loading/i)).toHaveCount(0) + + const initialCount = await gameCards.count() + + if (initialCount === 0) { + await expect(nextButton).toBeDisabled() + await expect(previousButton).toBeDisabled() + return + } + + const initialGames = await gameCards.allInnerTexts() + + // If there are not enough games for another page, + // the carousel should not allow moving forward. + if (await nextButton.isDisabled()) { + await expect(previousButton).toBeDisabled() + return + } + + await nextButton.click() + + await expect.poll(async () => { + return gameCards.allInnerTexts() + }).not.toEqual(initialGames) + + await expect(previousButton).toBeEnabled() + + await previousButton.click() + + await expect.poll(async () => { + return gameCards.allInnerTexts() + }).toEqual(initialGames) +} + +export async function goBackToMain(page: Page) { + await page.goBack() + await expect(page).toHaveURL(MAIN_PAGE) +} diff --git a/Frontend/.env.example b/Frontend/.env.example index e661313..22df02b 100644 --- a/Frontend/.env.example +++ b/Frontend/.env.example @@ -4,4 +4,7 @@ DB_PORT= DB_NAME= DB_USER= DB_PASSWORD= -HOST= \ No newline at end of file +HOST= + +PG_ADMIN_USER= +PG_ADMIN_PASSWORD= \ No newline at end of file diff --git a/Frontend/index.html b/Frontend/index.html index 10595f1..dc25ea3 100644 --- a/Frontend/index.html +++ b/Frontend/index.html @@ -2,7 +2,7 @@ - + t10-project-2 diff --git a/Frontend/src/FrontendLogic/GameLogicFrontend.ts b/Frontend/src/FrontendLogic/GameLogicFrontend.ts index 0fd559c..a230ffc 100644 --- a/Frontend/src/FrontendLogic/GameLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/GameLogicFrontend.ts @@ -1,5 +1,5 @@ import type { Game } from '../../../Backend/Steam' -import { BACKEND_URL } from './LogicConnection' +import { BACKEND_URL, NETWORK_ERROR_MESSAGE } from './LogicConnection' import { OrNull, ReadStored, RemoveStored, WriteStored } from './Storage' interface GraphQLResponse { @@ -7,6 +7,14 @@ interface GraphQLResponse { errors?: { message: string }[] } +async function FetchBackend(init: RequestInit): Promise { + try { + return await fetch(BACKEND_URL, init) + } catch { + throw new Error(NETWORK_ERROR_MESSAGE) + } +} + const CACHE_TTL_MS = 12 * 60 * 60 * 1000 const GAMES_CACHE_PREFIX = `games:v2:${encodeURIComponent(BACKEND_URL)}:` @@ -105,7 +113,7 @@ export async function GetGameById(appid: number): Promise { const cachedGame = FindCachedGameById(appid) if (cachedGame) return cachedGame - const response = await fetch(BACKEND_URL, { + const response = await FetchBackend({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ @@ -128,8 +136,7 @@ export async function GetGameById(appid: number): Promise { }) if (!response.ok) { - const body = await response.text() - throw new Error(`Failed to fetch game: ${response.status} ${body}`) + throw new Error(`Failed to fetch game: ${response.status}`) } const { data, errors } = (await response.json()) as GraphQLResponse<{ @@ -151,7 +158,7 @@ async function FetchGamesFromDB( const cachedGames = ReadCachedGames(cacheKey) if (cachedGames) return cachedGames - const response = await fetch(BACKEND_URL, { + const response = await FetchBackend({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ @@ -180,8 +187,7 @@ async function FetchGamesFromDB( }) if (!response.ok) { - const body = await response.text() - throw new Error(`Failed to fetch resources: ${response.status} ${body}`) + throw new Error(`Failed to fetch resources: ${response.status}`) } const { data, errors } = (await response.json()) as GraphQLResponse<{ @@ -197,7 +203,7 @@ async function FetchGamesFromDB( export async function GetTotalGameCount( options: Pick = {} ): Promise { - const response = await fetch(BACKEND_URL, { + const response = await FetchBackend({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ @@ -214,8 +220,7 @@ export async function GetTotalGameCount( }) if (!response.ok) { - const body = await response.text() - throw new Error(`Failed to fetch game count: ${response.status} ${body}`) + throw new Error(`Failed to fetch game count: ${response.status}`) } const { data, errors } = (await response.json()) as GraphQLResponse<{ diff --git a/Frontend/src/FrontendLogic/LogicConnection.ts b/Frontend/src/FrontendLogic/LogicConnection.ts index 0b50100..c7e6654 100644 --- a/Frontend/src/FrontendLogic/LogicConnection.ts +++ b/Frontend/src/FrontendLogic/LogicConnection.ts @@ -1,15 +1,23 @@ export const BACKEND_URL = import.meta.env.VITE_BACKEND_URL ?? 'http://it2810-10.idi.ntnu.no:3001/' +export const NETWORK_ERROR_MESSAGE = + 'Could not reach the server.' + export async function Gql(query: string, variables: Record): Promise { const token = GetStoredToken() - const res = await fetch(BACKEND_URL, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - ...(token ? { Authorization: `Bearer ${token}` } : {}) - }, - body: JSON.stringify({ query, variables }) - }) + let res: Response + try { + res = await fetch(BACKEND_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Bearer ${token}` } : {}) + }, + body: JSON.stringify({ query, variables }) + }) + } catch { + throw new Error(NETWORK_ERROR_MESSAGE) + } if (!res.ok) throw new Error(`Request failed: ${res.status}`) const json = await res.json() if (json.errors) throw new Error(json.errors[0].message) diff --git a/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts b/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts index ea12e03..1f4867f 100644 --- a/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/ProfileLogicFrontend.ts @@ -16,12 +16,35 @@ export async function FetchProfileFrontend(userId: number): Promise { - const data = await Gql<{ gameOptions: GameOption[] }>( - `query { gameOptions { appid name } }`, - {} +export async function FetchGameOptions( + options: { + search?: string + appid?: number + limit?: number + offset?: number + } = {} +): Promise { + if (options.appid !== undefined) { + const data = await Gql<{ game: GameOption | null }>( + `query($appid: Int!) { + game(appid: $appid) { appid name } + }`, + { appid: options.appid } + ) + return data.game ? [data.game] : [] + } + + const data = await Gql<{ games: GameOption[] }>( + `query($search: String, $limit: Int, $offset: Int) { + games(search: $search, limit: $limit, offset: $offset) { appid name } + }`, + { + search: options.search ?? null, + limit: options.limit ?? 20, + offset: options.offset ?? 0 + } ) - return data.gameOptions + return data.games } export async function UpdateProfileFrontend( diff --git a/Frontend/src/FrontendLogic/ReviewLogicFrontend.ts b/Frontend/src/FrontendLogic/ReviewLogicFrontend.ts index cc31b09..c5eae41 100644 --- a/Frontend/src/FrontendLogic/ReviewLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/ReviewLogicFrontend.ts @@ -31,6 +31,24 @@ export async function GetRecentReviews(limit = 10): Promise { return data.recentReviews } +export const USER_REVIEWS_PER_PAGE = 6 + +export type UserReviewPage = { + reviews: Review[] + totalCount: number +} + +export async function GetReviewsByUser(userId: number, page = 1): Promise { + const data = await Gql<{ userReviews: Review[]; userReviewCount: number }>( + `query($userId: Int!, $limit: Int, $offset: Int) { + userReviews(userId: $userId, limit: $limit, offset: $offset) { ${REVIEW_FIELDS} gameName } + userReviewCount(userId: $userId) + }`, + { userId, limit: USER_REVIEWS_PER_PAGE, offset: (page - 1) * USER_REVIEWS_PER_PAGE } + ) + return { reviews: data.userReviews, totalCount: data.userReviewCount } +} + export async function CreateReview( gameId: number, userId: number, diff --git a/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts b/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts index 91c3d11..4159648 100644 --- a/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts +++ b/Frontend/src/FrontendLogic/SearchPageLogicFrontend.ts @@ -1,5 +1,5 @@ import { Gql } from './LogicConnection' -import { IsBoolean, IsInteger, IsString, IsStringArray, ReadStored, RemoveStored, WriteStored } from './Storage' +import { IsBoolean, IsInteger, IsString, IsStringArray, ReadStored, WriteStored } from './Storage' const filterStorageKey = 'GameStart:filtersSearchpage' const sortStorageKey = 'GameStart:sortOptionSearchpage' diff --git a/Frontend/src/assets/LogoGameStartTransparent.png b/Frontend/src/assets/LogoGameStartTransparent.png deleted file mode 100644 index 3725d9f..0000000 Binary files a/Frontend/src/assets/LogoGameStartTransparent.png and /dev/null differ diff --git a/Frontend/src/assets/LogoGameStartTransparent.webp b/Frontend/src/assets/LogoGameStartTransparent.webp new file mode 100644 index 0000000..8fb2766 Binary files /dev/null and b/Frontend/src/assets/LogoGameStartTransparent.webp differ diff --git a/Frontend/src/assets/maskot_gamestart.png b/Frontend/src/assets/maskot_gamestart.png deleted file mode 100644 index dbc8a9a..0000000 Binary files a/Frontend/src/assets/maskot_gamestart.png and /dev/null differ diff --git a/Frontend/src/assets/maskot_gamestart.webp b/Frontend/src/assets/maskot_gamestart.webp new file mode 100644 index 0000000..2ede345 Binary files /dev/null and b/Frontend/src/assets/maskot_gamestart.webp differ diff --git a/Frontend/src/assets/maskot_head_gamestart.png b/Frontend/src/assets/maskot_head_gamestart.png deleted file mode 100644 index 35ad389..0000000 Binary files a/Frontend/src/assets/maskot_head_gamestart.png and /dev/null differ diff --git a/Frontend/src/assets/maskot_head_gamestart.webp b/Frontend/src/assets/maskot_head_gamestart.webp new file mode 100644 index 0000000..c5b3c35 Binary files /dev/null and b/Frontend/src/assets/maskot_head_gamestart.webp differ diff --git a/Frontend/src/components/ActiveGameCard.tsx b/Frontend/src/components/ActiveGameCard.tsx index a07fc96..ce9d8b2 100644 --- a/Frontend/src/components/ActiveGameCard.tsx +++ b/Frontend/src/components/ActiveGameCard.tsx @@ -42,6 +42,8 @@ export default function ActiveGameCard({ const isOnSale = game.salePercent !== undefined && game.salePercent > 0 && game.salePercent <= 100 + const showOriginalPrice = + isOnSale && game.originalPrice !== undefined && game.originalPrice > game.price //Loads the game's reviews, again when the user signs in or out so their own review comes first useEffect(() => { @@ -140,6 +142,7 @@ export default function ActiveGameCard({ component="img" image={game.image} alt={`${game.name} game poster`} + loading="lazy" /> {isLoggedIn && ( - - - )} - + )}
+ + Review by {review.reviewer} + {isOwner && ' (you)'} + + {isOwner && onEdit && onDelete && ( +
+ + +
+ )} - {review.text &&

“{review.text}”

} + {collapsible ? ( +
+ {reviewText || ( +

No written review

+ )} + {canExpand && !isExpanded &&
} +
+ ) : ( + reviewText + )} {game && ( See this game diff --git a/Frontend/src/components/ReviewComposer.tsx b/Frontend/src/components/ReviewComposer.tsx new file mode 100644 index 0000000..77a097f --- /dev/null +++ b/Frontend/src/components/ReviewComposer.tsx @@ -0,0 +1,70 @@ +import { useState } from 'react' +import Button from '@mui/material/Button' +import Rating from '@mui/material/Rating' +import TextField from '@mui/material/TextField' +import Typography from '@mui/material/Typography' +import '../css/ReviewComposer.css' + +type ReviewComposerProps = { + isEditing: boolean + gameName?: string + initialRating?: number | null + initialText?: string + onSave: (rating: number, text: string) => Promise + onCancel: () => void +} + +export default function ReviewComposer({ + isEditing, + gameName, + initialRating = null, + initialText = '', + onSave, + onCancel +}: ReviewComposerProps) { + const [rating, setRating] = useState(initialRating) + const [text, setText] = useState(initialText) + + async function HandleSubmit(event: React.FormEvent) { + event.preventDefault() + if (rating === null) return + await onSave(rating, text) + } + + return ( +
+ + {isEditing ? 'Edit your review' : 'Write your review'} + {gameName && ` of ${gameName}`} + +
+ Your rating (required) + setRating(value)} + getLabelText={(value) => `Rating ${value} out of 5`} + /> +
+ setText(event.target.value)} + multiline + minRows={3} + maxRows={6} + slotProps={{ htmlInput: { maxLength: 500 } }} + helperText={`${text.length} / 500 characters`} + fullWidth + /> +
+ + +
+ + ) +} diff --git a/Frontend/src/components/Reviews.tsx b/Frontend/src/components/Reviews.tsx index 9358914..4ee8089 100644 --- a/Frontend/src/components/Reviews.tsx +++ b/Frontend/src/components/Reviews.tsx @@ -2,10 +2,9 @@ import { useState } from 'react' import Button from '@mui/material/Button' import CardContent from '@mui/material/CardContent' import Divider from '@mui/material/Divider' -import Rating from '@mui/material/Rating' -import TextField from '@mui/material/TextField' import Typography from '@mui/material/Typography' import ReviewCard from './ReviewCard' +import ReviewComposer from './ReviewComposer' import type { Review } from '../types/Review' function GetAverageRating(reviews: Review[]): number | null { @@ -40,9 +39,7 @@ export default function Reviews({ onDeleteReview }: ReviewsProps) { const [isComposerOpen, setIsComposerOpen] = useState(false) - const [rating, setRating] = useState(null) - const [text, setText] = useState('') - const [editingReviewId, setEditingReviewId] = useState(null) + const [editingReview, setEditingReview] = useState(null) const [error, setError] = useState(null) function IsOwnReview(review: Review) { @@ -53,35 +50,28 @@ export default function Reviews({ const averageRating = GetAverageRating(reviews) function OpenNewReviewForm() { - setEditingReviewId(null) - setRating(null) - setText('') + setEditingReview(null) setError(null) setIsComposerOpen(true) } function OpenEditReviewForm(review: Review) { - setEditingReviewId(review.id) - setRating(review.rating) - setText(review.text) + setEditingReview(review) setError(null) setIsComposerOpen(true) } function CloseComposer() { setIsComposerOpen(false) - setEditingReviewId(null) + setEditingReview(null) } - async function HandleSave(event: React.FormEvent) { - event.preventDefault() - if (rating === null) return - + async function HandleSave(rating: number, text: string) { try { - if (editingReviewId === null) { + if (editingReview === null) { await onSubmitReview(rating, text) } else { - await onEditReview(editingReviewId, rating, text) + await onEditReview(editingReview.id, rating, text) } CloseComposer() setError(null) @@ -93,7 +83,7 @@ export default function Reviews({ async function HandleDelete(review: Review) { try { await onDeleteReview(review.id) - if (editingReviewId === review.id) CloseComposer() + if (editingReview?.id === review.id) CloseComposer() setError(null) } catch (deleteError: unknown) { setError( @@ -126,43 +116,18 @@ export default function Reviews({

Sign in to submit a review.

)} {isComposerOpen && ( -
- - {editingReviewId === null ? 'Write your review' : 'Edit your review'} - -
- Your rating (required) - setRating(value)} - getLabelText={(value) => `Rating ${value} out of 5`} - /> -
- setText(event.target.value)} - multiline - minRows={3} - maxRows={6} - slotProps={{ htmlInput: { maxLength: 500 } }} - helperText={`${text.length} / 500 characters`} - fullWidth - /> -
- - -
- + )} - {(error ?? loadError) && ( + {error && (

- {error ?? loadError} + {error}

)} @@ -177,6 +142,10 @@ export default function Reviews({ onDelete={HandleDelete} /> )) + ) : loadError ? ( +

+ Could not load reviews: {loadError} +

) : (

No reviews yet.

)} diff --git a/Frontend/src/components/SearchPageControls.tsx b/Frontend/src/components/SearchPageControls.tsx new file mode 100644 index 0000000..df487ab --- /dev/null +++ b/Frontend/src/components/SearchPageControls.tsx @@ -0,0 +1,163 @@ +import { + Button, + FormControl, + IconButton, + InputBase, + InputLabel, + MenuItem, + Paper, + Select +} from '@mui/material' +import type { SelectChangeEvent } from '@mui/material' +import { Funnel, X } from 'lucide-react' + +export type SortOption = + '' | 'discount-desc' | 'price-asc' | 'price-desc' | 'title-asc' | 'title-desc' + +interface SearchPageControlsProps { + searchValue: string + searchQuery: string + onSearchChange: (value: string) => void + onSearchSubmit: (event: React.FormEvent) => void + onClearSearch: () => void + isFilterActive: boolean + onToggleFilters: () => void + genres: string[] + genresError?: string | null + activeFilters: string[] + onFilterChange: (event: SelectChangeEvent) => void + activeSorting: SortOption + onSortChange: (event: SelectChangeEvent) => void + onRemoveFilters: () => void + onReset: () => void +} + +const DEFAULT_SORT: SortOption = 'title-asc' + +export default function SearchPageControls({ + searchValue, + searchQuery, + onSearchChange, + onSearchSubmit, + onClearSearch, + isFilterActive, + onToggleFilters, + genres, + genresError = null, + activeFilters, + onFilterChange, + activeSorting, + onSortChange, + onRemoveFilters, + onReset +}: SearchPageControlsProps) { + return ( + <> + + onSearchChange(event.target.value)} + /> + + + + + + + {isFilterActive && ( +
+ + Sort by + + + + Filter by genre + + {genresError && ( + + )} + + + +
+ )} + + ) +} diff --git a/Frontend/src/components/SearchPageResults.tsx b/Frontend/src/components/SearchPageResults.tsx new file mode 100644 index 0000000..19759b9 --- /dev/null +++ b/Frontend/src/components/SearchPageResults.tsx @@ -0,0 +1,89 @@ +import { memo } from 'react' +import { Pagination } from '@mui/material' +import type { Game } from '../../../Backend/Steam' +import PassiveGameCard from './PassiveGameCard' + +const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: Game[] }) { + return ( +
+ {games.map((game) => { + const price = Number(game.price) + const salePercent = Number(game.discount) + + return ( + + ) + })} +
+ ) +}) + +interface SearchPageResultsProps { + games: Game[] + error: string | null + isLoading: boolean + totalCount: number + page: number + onPageChange: (page: number) => void +} + +const GAMES_PER_PAGE = 12 + +export default function SearchPageResults({ + games, + error, + isLoading, + totalCount, + page, + onPageChange +}: SearchPageResultsProps) { + const pageCount = Math.max(1, Math.ceil(totalCount / GAMES_PER_PAGE)) + + function HandleBottomPageChange(_: unknown, value: number) { + onPageChange(value) + window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + return ( + <> +
+ {!error && totalCount > 0 && ( +

+ {totalCount} {totalCount === 1 ? 'game' : 'games'} found +

+ )} + onPageChange(value)} + /> +
+ {error && ( +

+ Could not load games: {error} +

+ )} + {isLoading && games.length === 0 &&

Loading games...

} + {!error && !isLoading && games.length === 0 && ( +

No games found.

+ )} + {games.length > 0 && } + + + ) +} diff --git a/Frontend/src/components/TopGames.tsx b/Frontend/src/components/TopGames.tsx index e9903e7..379efec 100644 --- a/Frontend/src/components/TopGames.tsx +++ b/Frontend/src/components/TopGames.tsx @@ -5,9 +5,10 @@ import PassiveGameCard from './PassiveGameCard' interface TopGamesProps { loading: boolean featuredGames: PageGame[] + error?: string | null } -export default function TopGames({ loading, featuredGames }: TopGamesProps) { +export default function TopGames({ loading, featuredGames, error = null }: TopGamesProps) { return (
@@ -15,7 +16,11 @@ export default function TopGames({ loading, featuredGames }: TopGamesProps) {
{loading ? ( -

Loading games...

+

Loading games...

+ ) : error ? ( +

+ Could not load the top games: {error} +

) : featuredGames.length === 0 ? (

No games found.

) : ( diff --git a/Frontend/src/components/UserReviews.tsx b/Frontend/src/components/UserReviews.tsx new file mode 100644 index 0000000..895eb6b --- /dev/null +++ b/Frontend/src/components/UserReviews.tsx @@ -0,0 +1,180 @@ +import { useEffect, useRef, useState } from 'react' +import Card from '@mui/material/Card' +import CardContent from '@mui/material/CardContent' +import Divider from '@mui/material/Divider' +import Pagination from '@mui/material/Pagination' +import useMediaQuery from '@mui/material/useMediaQuery' +import ReviewCard from './ReviewCard' +import ReviewComposer from './ReviewComposer' +import '../css/UserReviews.css' +import { + DeleteReview, + GetReviewsByUser, + UpdateReview, + USER_REVIEWS_PER_PAGE, + type UserReviewPage +} from '../FrontendLogic/ReviewLogicFrontend' +import type { Review } from '../types/Review' + +type UserReviewsProps = { + userId: number +} + +export default function UserReviews({ userId }: UserReviewsProps) { + const [page, setPage] = useState(1) + const [reviewPage, setReviewPage] = useState(null) + const [reloadCount, setReloadCount] = useState(0) + const [editingReviewId, setEditingReviewId] = useState(null) + const [error, setError] = useState(null) + const cardRef = useRef(null) + const isSingleColumn = useMediaQuery('(max-width: 43.75rem)') + + useEffect(() => { + let cancelled = false + + GetReviewsByUser(userId, page) + .then((loaded) => { + if (cancelled) return + if (loaded.reviews.length === 0 && page > 1) { + setPage(page - 1) + return + } + setReviewPage(loaded) + setError(null) + }) + .catch((loadError: unknown) => { + if (!cancelled) + setError( + loadError instanceof Error ? loadError.message : 'Could not load reviews.' + ) + }) + + return () => { + cancelled = true + } + }, [userId, page, reloadCount]) + + const reviews = reviewPage?.reviews ?? [] + const pageCount = Math.max(1, Math.ceil((reviewPage?.totalCount ?? 0) / USER_REVIEWS_PER_PAGE)) + + const columns = isSingleColumn + ? [reviews] + : [ + reviews.filter((_, index) => index % 2 === 0), + reviews.filter((_, index) => index % 2 === 1) + ] + + function ChangePage(value: number, scrollToTop: boolean) { + setPage(value) + setEditingReviewId(null) + if (scrollToTop) cardRef.current?.scrollIntoView?.({ behavior: 'smooth', block: 'start' }) + } + + function OpenEditReviewForm(review: Review) { + setEditingReviewId(review.id) + setError(null) + } + + async function HandleSave(review: Review, rating: number, text: string) { + try { + await UpdateReview(review.gameId, review.id, userId, rating, text) + setReviewPage( + (current) => + current && { + ...current, + reviews: current.reviews.map((other) => + other.id === review.id ? { ...other, rating, text } : other + ) + } + ) + setEditingReviewId(null) + setError(null) + } catch (saveError: unknown) { + setError(saveError instanceof Error ? saveError.message : 'Could not save review.') + } + } + + async function HandleDelete(review: Review) { + try { + await DeleteReview(review.gameId, review.id, userId) + if (editingReviewId === review.id) setEditingReviewId(null) + setReloadCount((count) => count + 1) + setError(null) + } catch (deleteError: unknown) { + setError( + deleteError instanceof Error ? deleteError.message : 'Could not delete review.' + ) + } + } + + function RenderReview(review: Review) { + return review.id === editingReviewId ? ( + HandleSave(review, rating, text)} + onCancel={() => setEditingReviewId(null)} + /> + ) : ( + + ) + } + + function RenderPagination(scrollToTop: boolean) { + if (pageCount <= 1) return null + return ( + ChangePage(value, scrollToTop)} + /> + ) + } + + return ( + + +

Your reviews

+
+ + + + + {error && ( +

+ {error} +

+ )} + {reviewPage === null ? ( + !error &&

Loading reviews…

+ ) : reviews.length === 0 ? ( +

You have not reviewed any games yet.

+ ) : ( + <> + {RenderPagination(false)} +
+ {columns.map((column, columnIndex) => ( +
+ {column.map(RenderReview)} +
+ ))} +
+ {RenderPagination(true)} + + )} +
+
+ ) +} diff --git a/Frontend/src/components/WishlistGameCard.tsx b/Frontend/src/components/WishlistGameCard.tsx index 757e8b3..5c54408 100644 --- a/Frontend/src/components/WishlistGameCard.tsx +++ b/Frontend/src/components/WishlistGameCard.tsx @@ -49,6 +49,7 @@ export default function WishlistGameCard({ component="img" image={game.image} alt="" + loading="lazy" />

@@ -66,9 +67,14 @@ export default function WishlistGameCard({ /> )}

{game.price.toFixed(2)} $

- {error &&

{error}

}

+ {error && ( +

+ {error} +

+ )} + {!readOnly && ( - + { + setFriendCode(event.target.value) + setAddError(null) + }} + inputProps={{ + 'aria-label': 'Friend ID', + 'aria-invalid': addError ? true : undefined, + 'aria-describedby': addError ? 'addFriendError' : undefined + }} + /> + + + {addError && ( + + )} + } /> {user && ownCode && ( @@ -278,7 +296,6 @@ export default function FriendPage() {

)} - {addError &&

{addError}

} {showOnlyStatus ? ( -
{statusPanel}
+
+ {statusPanel} +
) : (
diff --git a/Frontend/src/pages/GamePage.tsx b/Frontend/src/pages/GamePage.tsx index d1f426a..d9204d5 100644 --- a/Frontend/src/pages/GamePage.tsx +++ b/Frontend/src/pages/GamePage.tsx @@ -17,10 +17,12 @@ export default function GamePage() { error: string | null } | null>(null) + const isValidAppId = Number.isSafeInteger(appid) && appid > 0 + useEffect(() => { - let cancelled = false + if (!isValidAppId) return - if (!Number.isSafeInteger(appid)) return + let cancelled = false GetGameById(appid) .then((loadedGame) => { @@ -41,13 +43,13 @@ export default function GamePage() { } }, [appid]) - const isValidAppId = Number.isSafeInteger(appid) const isLoading = isValidAppId && loadedGame?.appid !== appid const game = loadedGame?.appid === appid ? loadedGame.game : null const error = loadedGame?.appid === appid ? loadedGame.error : null const price = game ? Number(game.price) : 0 const salePercent = game ? Number(game.discount) : 0 + const originalPrice = game ? Number(game.initialprice) : 0 const genres = game ? game.genre .split(',') @@ -68,9 +70,11 @@ export default function GamePage() { />
{isLoading ? ( -

Loading game...

+

Loading game...

) : error ? ( -

Error loading game: {error}

+

+ Something went wrong while loading this game: {error} +

) : game ? ( ) : ( -

Game not found.

+

+ We couldn't find that game. It may have been removed, or the link is wrong. +

)}
diff --git a/Frontend/src/pages/MainPage.tsx b/Frontend/src/pages/MainPage.tsx index a2f67fe..92a80e6 100644 --- a/Frontend/src/pages/MainPage.tsx +++ b/Frontend/src/pages/MainPage.tsx @@ -10,7 +10,7 @@ import { FetchGenres } from '../FrontendLogic/SearchPageLogicFrontend' import { Link } from 'react-router-dom' import { useEffect, useState } from 'react' import { Button } from '@mui/material' -import maskot_gamestart from '../assets/maskot_gamestart.png' +import maskot_gamestart from '../assets/maskot_gamestart.webp' import RecentReviews from '../components/RecentReviews' import { GetRecentReviews } from '../FrontendLogic/ReviewLogicFrontend' import type { Review } from '../types/Review' @@ -23,21 +23,25 @@ export default function MainPage() { const [genres, setGenres] = useState([]) const [isLoadingFeatured, setIsLoadingFeatured] = useState(true) const [isLoadingGenres, setIsLoadingGenres] = useState(true) - const [error, setError] = useState(null) + // One error per section, so each failure is shown inside the box it belongs to + const [featuredError, setFeaturedError] = useState(null) + const [genresError, setGenresError] = useState(null) + const [reviewsError, setReviewsError] = useState(null) const [recentReviews, setRecentReviews] = useState([]) const [isLoadingReviews, setIsLoadingReviews] = useState(true) useEffect(() => { let cancelled = false - const ReportError = (e: unknown, fallback: string) => { - if (!cancelled) setError(e instanceof Error ? e.message : fallback) - } + const ReportError = + (setError: (message: string) => void, fallback: string) => (e: unknown) => { + if (!cancelled) setError(e instanceof Error ? e.message : fallback) + } LoadTop3Games() .then((games) => { if (!cancelled) setFeaturedGames(games.map(ToPageGame)) }) - .catch((e: unknown) => ReportError(e, 'Could not load top games')) + .catch(ReportError(setFeaturedError, 'Could not load top games')) .finally(() => { if (!cancelled) setIsLoadingFeatured(false) }) @@ -46,7 +50,7 @@ export default function MainPage() { .then((loaded) => { if (!cancelled) setGenres([...loaded].sort()) }) - .catch((e: unknown) => ReportError(e, 'Could not load genres')) + .catch(ReportError(setGenresError, 'Could not load genres')) .finally(() => { if (!cancelled) setIsLoadingGenres(false) }) @@ -55,7 +59,7 @@ export default function MainPage() { .then((reviews) => { if (!cancelled) setRecentReviews(reviews) }) - .catch((e: unknown) => ReportError(e, 'Could not load reviews')) + .catch(ReportError(setReviewsError, 'Could not load reviews')) .finally(() => { if (!cancelled) setIsLoadingReviews(false) }) @@ -98,15 +102,19 @@ export default function MainPage() {
- HaroldTheHare + HaroldTheHare
- {error && ( -

- {error} -

- )} - +
@@ -114,6 +122,7 @@ export default function MainPage() { title="Top 10 Games by Genre" genres={genres} genresLoading={isLoadingGenres} + genresError={genresError} loadGames={LoadTopGamesByGenre} loadingText="Loading games..." emptyText="No games found for this genre." @@ -123,6 +132,7 @@ export default function MainPage() { title="Discounts by Genre" genres={genres} genresLoading={isLoadingGenres} + genresError={genresError} loadGames={LoadDiscountedGames} loadingText="Loading discount games..." emptyText="No discount games found for this genre." @@ -131,7 +141,11 @@ export default function MainPage() { />
- +