diff --git a/apps/backend/package.json b/apps/backend/package.json index 5268fae..ad1c26f 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -15,10 +15,12 @@ "@pothos/plugin-with-input": "^4.1.5", "@t09-project-2/db": "workspace:*", "graphql": "^16.9.0", - "tsx": "^4.23.15" + "tsx": "^4.23.15", + "jsonwebtoken": "^9.0.3" }, "devDependencies": { "@playwright/test": "^1.64.1", + "@types/jsonwebtoken": "^9.0.10", "@types/node": "^22.20.4", "dotenv-cli": "^11.0.0", "typescript": "^6.0.3" diff --git a/apps/backend/src/builder.ts b/apps/backend/src/builder.ts index 95b79fd..da4f6e4 100644 --- a/apps/backend/src/builder.ts +++ b/apps/backend/src/builder.ts @@ -27,4 +27,5 @@ export const builder = new SchemaBuilder<{ builder.scalarType('DateTime', { serialize: (date: Date) => date.toISOString(), + parseValue: (value) => new Date(value as string | number | Date), }) diff --git a/apps/backend/src/context.ts b/apps/backend/src/context.ts index af1f0e5..4228112 100644 --- a/apps/backend/src/context.ts +++ b/apps/backend/src/context.ts @@ -1,10 +1,40 @@ import { prisma } from '@t09-project-2/db' +import jwt from 'jsonwebtoken' import type { PrismaClient } from '@t09-project-2/db' +import type { IncomingMessage } from 'node:http' + +// In a real application, this would be a type an auth provider like Auth0 +export interface User { + sub: string + iat: number + exp: number + role: 'admin' | 'user' +} export interface Context { prisma: PrismaClient + user: User | null } -export function createContext(): Context { - return { prisma } +export function createContext({ req }: { req: IncomingMessage }): Context { + const authHeader = req.headers.authorization + let user: User | null = null + + if (authHeader === undefined || !authHeader.startsWith('Bearer ')) { + return { + prisma, + user, + } + } + + try { + const token = authHeader.split(' ')[1] + // Would not have the secret in plain text in a real prod application obviously + user = jwt.verify(token, 'secret-string', { algorithms: ['HS256'] }) as User + } catch {} // Empty catch to keep user null if the token in invalid or header is malformed + + return { + prisma, + user, + } } diff --git a/apps/backend/src/geocoding.ts b/apps/backend/src/geocoding.ts new file mode 100644 index 0000000..f63b3fe --- /dev/null +++ b/apps/backend/src/geocoding.ts @@ -0,0 +1,51 @@ +import { GraphQLError } from 'graphql' + +export interface GeocodingResult { + lat: number + lon: number +} + +const NOMINATIM_URL = 'https://nominatim.openstreetmap.org/search' +const USER_AGENT = process.env.NOMINATIM_USER_AGENT ?? 'T09-Project-2/1.0' + +/** + * Looks up the coordinates for a Norwegian address using Nominatim. + * Returns null when the address could not be found. + * + * See https://operations.osmfoundation.org/policies/nominatim/ for the usage + * policy. In particular, requests should identify the application through the + * User-Agent header and must not be sent at a high rate. + */ +export async function geocodeAddress( + address: string, + city: string, +): Promise { + const params = new URLSearchParams({ + q: `${address}, ${city}`, + format: 'jsonv2', + limit: '1', + countrycodes: 'no', + }) + + const response = await fetch(`${NOMINATIM_URL}?${params}`, { + headers: { + 'User-Agent': USER_AGENT, + }, + signal: AbortSignal.timeout(5000), + }) + + if (!response.ok) { + throw new GraphQLError(`Geocoding failed: ${response.status}`, { + extensions: { code: 'BAD_GATEWAY' }, + }) + } + + const results = (await response.json()) as GeocodingResult[] + + if (results.length === 0) return null + + return { + lat: Number(results[0].lat), + lon: Number(results[0].lon), + } +} diff --git a/apps/backend/src/index.ts b/apps/backend/src/index.ts index 4b013ce..5201119 100644 --- a/apps/backend/src/index.ts +++ b/apps/backend/src/index.ts @@ -13,7 +13,7 @@ const port = Number(process.env.PORT ?? 3001) const { url } = await startStandaloneServer(server, { listen: { port }, - context: async () => createContext(), + context: async ({ req }) => createContext({ req }), }) console.log(`GraphQL server ready at ${url}`) diff --git a/apps/backend/src/schema/schema.ts b/apps/backend/src/schema/schema.ts index 9043923..980ae84 100644 --- a/apps/backend/src/schema/schema.ts +++ b/apps/backend/src/schema/schema.ts @@ -7,6 +7,7 @@ import type { import { GraphQLError } from 'graphql' import { builder } from '../builder.js' +import { geocodeAddress } from '../geocoding.js' import { latestPriceSightings } from './price-sightings.js' import type { VenueWithPriceSightings } from './price-sightings.js' @@ -62,6 +63,7 @@ builder.prismaObject('Review', { const priceSightingRef = builder.prismaObject('PriceSighting', { select: { + id: true, size: true, sizeMl: true, limitation: true, @@ -70,6 +72,7 @@ const priceSightingRef = builder.prismaObject('PriceSighting', { timeSighted: true, }, fields: (t) => ({ + id: t.exposeString('id'), timeSighted: t.expose('timeSighted', { type: 'DateTime' }), venue: t.relation('venue'), price: t.exposeFloat('price'), @@ -86,11 +89,34 @@ const glassSizeRef = builder.enumType('GlassSize', { PINT: { value: GlassSize.PINT }, HALF_LITER: { value: GlassSize.HALF_LITER }, QUARTER_LITER: { value: GlassSize.QUARTER_LITER }, - BOX: { value: GlassSize.BOX }, + CAN: { value: GlassSize.CAN }, OTHER: { value: GlassSize.OTHER }, }, }) +const dayRef = builder.enumType('Day', { + values: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'] as const, +}) + +const limitationsRef = builder.enumType('Limitations', { + values: ['TIME', 'MEMBERSHIP'] as const, +}) + +const openingHoursInputRef = builder.inputType('OpeningHoursInput', { + fields: (t) => ({ + days: t.field({ type: [dayRef], required: true }), + opening: t.field({ type: 'DateTime', required: true }), + closing: t.field({ type: 'DateTime', required: true }), + }), +}) + +const openingHoursNoteInputRef = builder.inputType('OpeningHoursNoteInput', { + fields: (t) => ({ + days: t.field({ type: [dayRef], required: true }), + note: t.string({ required: true }), + }), +}) + type SearchResultItem = { id: string cityId: string | null @@ -652,5 +678,161 @@ builder.mutationType({ }, }), }), + createPriceSighting: t.prismaFieldWithInput({ + type: 'PriceSighting', + input: { + venueId: t.input.string({ required: true }), + price: t.input.float({ + required: true, + description: 'Price in NOK.', + }), + size: t.input.field({ type: glassSizeRef, required: true }), + sizeMl: t.input.float({ + description: 'Serving size in millilitres, when known.', + }), + limitation: t.input.field({ + type: [limitationsRef], + required: false, + description: 'Defaults to no limitations.', + }), + timeStart: t.input.field({ + type: 'DateTime', + description: 'Start of the time-limited offer. Requires TIME.', + }), + timeEnd: t.input.field({ + type: 'DateTime', + description: 'End of the time-limited offer. Requires TIME.', + }), + }, + resolve: async (query, _parent, args) => { + const { venueId, price, size, sizeMl, timeStart, timeEnd } = args.input + const limitation = args.input.limitation ?? [] + + if (!Number.isFinite(price) || price <= 0) { + throw new GraphQLError('Price must be greater than 0', { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + if (sizeMl != null && (!Number.isFinite(sizeMl) || sizeMl <= 0)) { + throw new GraphQLError('sizeMl must be greater than 0', { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + const hasTimeLimit = limitation.includes('TIME') + + if (hasTimeLimit !== (timeStart != null && timeEnd != null)) { + throw new GraphQLError( + 'timeStart and timeEnd are required when limitation includes TIME, and must otherwise be omitted', + { extensions: { code: 'BAD_USER_INPUT' } }, + ) + } + + const venue = await prisma.venue.findUnique({ + where: { id: venueId }, + select: { id: true }, + }) + + if (venue === null) { + throw new GraphQLError(`Unknown venue: ${venueId}`, { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + return prisma.priceSighting.create({ + ...query, + data: { + venue: { connect: { id: venueId } }, + price, + size, + sizeMl: sizeMl ?? null, + limitation: [...limitation], + timeStart: timeStart ?? null, + timeEnd: timeEnd ?? null, + timeSighted: new Date(), + }, + }) + }, + }), + createVenue: t.prismaFieldWithInput({ + type: 'Venue', + input: { + name: t.input.string({ required: true }), + address: t.input.string({ + required: true, + description: + 'Street address used to look up the venue coordinates with Nominatim.', + }), + cityId: t.input.string({ + required: true, + description: + 'ID of an existing city, for example from the city search.', + }), + openingHours: t.input.field({ + type: [openingHoursInputRef], + required: false, + }), + openingHoursNotes: t.input.field({ + type: [openingHoursNoteInputRef], + required: false, + }), + }, + resolve: async (query, _parent, args, context) => { + if (context.user?.role !== 'admin') { + throw new GraphQLError('Unauthorized', { + extensions: { code: 'UNAUTHORIZED' }, + }) + } + + const city = await prisma.city.findUnique({ + where: { id: args.input.cityId }, + select: { id: true, name: true }, + }) + + if (city === null) { + throw new GraphQLError(`Unknown city: ${args.input.cityId}`, { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + const coordinates = await geocodeAddress(args.input.address, city.name) + + if (coordinates === null) { + throw new GraphQLError( + `Could not geocode address: ${args.input.address}`, + { extensions: { code: 'BAD_USER_INPUT' } }, + ) + } + + return prisma.venue.create({ + ...query, + data: { + name: args.input.name, + address: args.input.address, + lat: coordinates.lat, + lon: coordinates.lon, + city: { connect: { id: city.id } }, + openingHours: args.input.openingHours + ? { + create: args.input.openingHours.map((hours) => ({ + days: [...hours.days], + opening: hours.opening, + closing: hours.closing, + })), + } + : undefined, + openingHoursNotes: args.input.openingHoursNotes + ? { + create: args.input.openingHoursNotes.map((note) => ({ + days: [...note.days], + note: note.note, + })), + } + : undefined, + }, + }) + }, + }), }), }) diff --git a/apps/backend/tests/e2e/api.spec.ts b/apps/backend/tests/e2e/api.spec.ts index 2455eb9..b03d9ea 100644 --- a/apps/backend/tests/e2e/api.spec.ts +++ b/apps/backend/tests/e2e/api.spec.ts @@ -1,9 +1,19 @@ import { expect, test } from '@playwright/test' import type { APIRequestContext } from '@playwright/test' import { randomUUID } from 'node:crypto' +import jwt from 'jsonwebtoken' import { prisma } from '@t09-project-2/db' +const ADMIN_SECRET = 'secret-string' + +function adminToken() { + return jwt.sign({ sub: 'playwright-admin', role: 'admin' }, ADMIN_SECRET, { + algorithm: 'HS256', + expiresIn: '1h', + }) +} + type GraphQLResponse = { data?: T | null errors?: { message: string }[] @@ -421,3 +431,249 @@ test('createReview rejects input missing a required field', async ({ 'Field "MutationCreateReviewInput.body" of required type "String!" was not provided.', ) }) + +test('createPriceSighting persists a sighting for its venue', async ({ + request, +}) => { + const { venue } = await query<{ venue: { id: string; name: string }[] }>( + request, + ` + query { + venue { + id + name + } + } + `, + ) + const seededVenue = venue.find(({ name }) => name === 'Den Gode Nabo') + expect(seededVenue).toBeDefined() + + if (!seededVenue) { + throw new Error('Seeded venue "Den Gode Nabo" was not returned') + } + + let createdSightingId: string | undefined + + try { + const { createPriceSighting } = await query<{ + createPriceSighting: { + id: string + price: number + size: string + sizeMl: number | null + Limitations: string[] + timeStart: string | null + timeEnd: string | null + timeSighted: string + } + }>( + request, + ` + mutation CreatePriceSighting( + $input: MutationCreatePriceSightingInput! + ) { + createPriceSighting(input: $input) { + id + price + size + sizeMl + Limitations + timeStart + timeEnd + timeSighted + } + } + `, + { + input: { + venueId: seededVenue.id, + price: 123.5, + size: 'PINT', + sizeMl: 568, + limitation: ['MEMBERSHIP'], + }, + }, + ) + createdSightingId = createPriceSighting.id + + expect(createPriceSighting).toMatchObject({ + id: expect.any(String), + price: 123.5, + size: 'PINT', + sizeMl: 568, + Limitations: ['MEMBERSHIP'], + timeStart: null, + timeEnd: null, + }) + expect(Number.isNaN(Date.parse(createPriceSighting.timeSighted))).toBe( + false, + ) + + const { venue: venuesWithPrices } = await query<{ + venue: { + id: string + pricesSighted: { + id: string + price: number + size: string + Limitations: string[] + }[] + }[] + }>( + request, + ` + query { + venue { + id + pricesSighted { + id + price + size + Limitations + } + } + } + `, + ) + const persistedSighting = venuesWithPrices + .find(({ id }) => id === seededVenue.id) + ?.pricesSighted.find(({ id }) => id === createPriceSighting.id) + + expect(persistedSighting).toEqual({ + id: createPriceSighting.id, + price: 123.5, + size: 'PINT', + Limitations: ['MEMBERSHIP'], + }) + } finally { + if (createdSightingId) { + await prisma.priceSighting.deleteMany({ + where: { id: createdSightingId }, + }) + } + } +}) + +test('createPriceSighting requires both times for a TIME limitation', async ({ + request, +}) => { + const { venue } = await query<{ venue: { id: string; name: string }[] }>( + request, + ` + query { + venue { + id + name + } + } + `, + ) + const seededVenue = venue.find(({ name }) => name === 'Den Gode Nabo') + + if (!seededVenue) { + throw new Error('Seeded venue "Den Gode Nabo" was not returned') + } + + const response = await request.post('/', { + data: { + query: ` + mutation { + createPriceSighting( + input: { + venueId: "${seededVenue.id}" + price: 89 + size: PINT + limitation: [TIME] + } + ) { + id + } + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors?.[0]?.message).toBe( + 'timeStart and timeEnd are required when limitation includes TIME, and must otherwise be omitted', + ) +}) + +test('createPriceSighting rejects an unknown venue', async ({ request }) => { + const unknownVenueId = '00000000-0000-0000-0000-000000000000' + const response = await request.post('/', { + data: { + query: ` + mutation { + createPriceSighting( + input: { + venueId: "${unknownVenueId}" + price: 89 + size: PINT + } + ) { + id + } + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors?.[0]?.message).toBe(`Unknown venue: ${unknownVenueId}`) +}) + +test('createVenue rejects an unknown city before geocoding', async ({ + request, +}) => { + const unknownCityId = '00000000-0000-0000-0000-000000000000' + const response = await request.post('/', { + headers: { authorization: `Bearer ${adminToken()}` }, + data: { + query: ` + mutation { + createVenue( + input: { + name: "Playwright venue" + address: "Øvre Bakklandet 66, Trondheim" + cityId: "${unknownCityId}" + } + ) { + id + } + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors?.[0]?.message).toBe(`Unknown city: ${unknownCityId}`) +}) + +test('createVenue requires an admin user', async ({ request }) => { + const response = await request.post('/', { + data: { + query: ` + mutation { + createVenue( + input: { + name: "Playwright venue" + address: "Øvre Bakklandet 66, Trondheim" + cityId: "00000000-0000-0000-0000-000000000000" + } + ) { + id + } + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors?.[0]?.message).toBe('Unauthorized') +}) diff --git a/apps/frontend/src/components/AddReviewDialog.tsx b/apps/frontend/src/components/AddReviewDialog.tsx deleted file mode 100644 index 5c6c7b7..0000000 --- a/apps/frontend/src/components/AddReviewDialog.tsx +++ /dev/null @@ -1,261 +0,0 @@ -import type { FormEvent } from 'react' -import { useId, useRef, useState } from 'react' -import { useMutation, useQueryClient } from '@tanstack/react-query' - -import { graphqlFetch } from '#/graphql/client' -import { CREATE_REVIEW } from '#/graphql/venues' -import HARP_SRC from '#/assets/harp.svg?url' -import type { VenueReview } from '#/types/venue' - -const USERNAME_STORAGE_KEY = 'g-spotter:review-username' -const BODY_MAX_LENGTH = 1000 -const RATING_VALUES = [1, 2, 3, 4, 5] - -interface ReviewInput { - venueId: string - username: string - body: string - rating: number -} - -export default function AddReviewDialog({ - venueId, - venueName, -}: { - venueId: string - venueName: string -}) { - const dialogRef = useRef(null) - const nameInputRef = useRef(null) - const titleId = useId() - const descriptionId = useId() - const nameId = useId() - const bodyId = useId() - const errorId = useId() - - const [username, setUsername] = useState('') - const [rating, setRating] = useState(0) - const [hoveredRating, setHoveredRating] = useState(0) - const [body, setBody] = useState('') - const [error, setError] = useState(null) - - const queryClient = useQueryClient() - - const { mutate, isPending } = useMutation({ - mutationFn: (input: ReviewInput) => - graphqlFetch<{ createReview: VenueReview }>(CREATE_REVIEW, { input }), - onSuccess: () => { - setRating(0) - setHoveredRating(0) - setBody('') - setError(null) - dialogRef.current?.close() - void queryClient.invalidateQueries({ queryKey: ['venues'] }) - }, - onError: () => { - setError('Could not post your review. Please try again.') - }, - }) - - const visibleRating = hoveredRating || rating - - function openDialog() { - const savedName = window.localStorage.getItem(USERNAME_STORAGE_KEY) - if (savedName) { - setUsername(savedName) - } - setError(null) - dialogRef.current?.showModal() - } - - function closeDialog() { - dialogRef.current?.close() - } - - function handleSubmit(event: FormEvent) { - event.preventDefault() - - if (isPending) return - - const trimmedName = username.trim() - const trimmedBody = body.trim() - - if (!trimmedName) { - setError('Please enter your name.') - nameInputRef.current?.focus() - return - } - - if (rating < 1) { - setError('Please choose a rating.') - return - } - - if (!trimmedBody) { - setError('Please write a short review.') - return - } - - setError(null) - window.localStorage.setItem(USERNAME_STORAGE_KEY, trimmedName) - mutate({ - venueId, - username: trimmedName, - body: trimmedBody, - rating, - }) - } - - return ( - <> - - - { - if (event.target === dialogRef.current) { - closeDialog() - } - }} - className="m-auto max-h-[calc(100dvh-2rem)] w-[min(30rem,calc(100vw-2rem))] overflow-y-auto rounded-2xl bg-(--surface-strong) p-0 text-(--sea-ink) shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-sm" - > -
-

- Add a review -

-

- Share your thoughts about {venueName}. -

- -
-
- - setUsername(event.target.value)} - maxLength={50} - required - autoComplete="nickname" - placeholder="e.g. Kari" - className="w-full rounded-xl bg-(--chip-bg) px-3 py-2 text-sm text-(--sea-ink) outline-none placeholder:text-(--sea-ink-soft) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--lagoon-deep)" - /> -
- -
- Rating -
setHoveredRating(0)} - > - - Select a rating: - -
- {RATING_VALUES.map((value) => ( - - ))} -
-
-
- -
-
- - - {body.length}/{BODY_MAX_LENGTH} - -
-