From 37032cfd71b3e981cbb49098503ec3b94aca67c3 Mon Sep 17 00:00:00 2001 From: sivertlv Date: Sun, 22 Nov 2026 19:39:46 +0100 Subject: [PATCH 1/7] add work-summary.md --- docs/work-summary.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 docs/work-summary.md diff --git a/docs/work-summary.md b/docs/work-summary.md new file mode 100644 index 0000000..58d137c --- /dev/null +++ b/docs/work-summary.md @@ -0,0 +1,44 @@ +# Work Summary from Git History + +Generated 2026-11-22 from `main` at `origin/main`. + +Local `main` was 4 commits behind `origin/main` at the time of writing, so the four newest PR commits (#52–#55) are included. Only commits reachable from `main` are counted; work on unmerged branches is excluded. + +## Method + +There is no timesheet data in the repository, so hours are estimated from commit timestamps: + +- Per member per day: first commit to last commit. +- A day with a single commit counts as 0.5 hours. +- "Total" is estimated person-hours, so it can exceed the team's wall-clock window when members worked in parallel. +- PRs are squash-merged, meaning each commit represents an entire PR. The estimates are therefore rough and likely a lower bound. + +The two initial course-staff commits by Trond Aalberg (29.08) are excluded. The `sivertlv` identity is merged with Sivert Lindblad Vårum, and the two Kristian email identities are merged with Kristian Numme. + +## Summary by date + +| Date | Team window | Total person-hours | Members (estimated hours) | +|---|---:|---:|---| +| Tue 29.09 | 15:42–17:23 | 2.2 h | Henry 1.7, Sivert 0.5 | +| Wed 14.10 | 13:48–15:43 | 1.9 h | Henry 1.9 | +| Thu 15.10 | 20:27–22:55 | 3.6 h | Henry 2.5, Sivert 0.6, Kristian 0.5 | +| Fri 16.10 | 23:12 | 0.5 h | Henry 0.5 | +| Tue 27.10 | 18:44–21:41 | 3.9 h | Henry 2.9, Nicolay 0.5, Sivert 0.5 | +| Thu 29.10 | 13:29–20:07 | 18.8 h | Henry 5.0, Nicolay 5.3, Sivert 4.1, Kristian 4.4 | +| Fri 30.10 | 17:11 | 0.5 h | Nicolay 0.5 | +| Mon 09.11 | 14:19–19:48 | 9.7 h | Henry 5.5, Nicolay 4.2 | +| Sun 22.11 | 14:21–15:39 | 1.8 h | Henry 1.3, Nicolay 0.5 | +| **Total** | **9 dates** | **42.9 h** | **4 members** | + +## Summary by member + +| Member | Active dates | Commits | Estimated hours | +|---|---:|---:|---:| +| Henry Græsberg | 8 | 25 | 21.3 h | +| Nicolay Bennett Rennemo | 5 | 9 | 11.0 h | +| Sivert Lindblad Vårum | 4 | 6 | 5.7 h | +| Kristian Numme | 2 | 4 | 4.9 h | + +Summed daily team windows are approximately 22.4 hours. The 42.9-hour total is person-hours where members worked in parallel. + +Strictly local `main`, without the four 22.11 commits, would be 8 dates and 41.1 person-hours. From ffb6ab250c5a48d617b5759c5bad65e215619be5 Mon Sep 17 00:00:00 2001 From: sivertlv Date: Sun, 22 Nov 2026 20:47:19 +0100 Subject: [PATCH 2/7] feat: allow adding venues in cities outside the database Search Norwegian cities through Nominatim when the local city table has no match. Selecting an external result persists it through a new admin-only findOrCreateCity mutation, so the created city gets a normal id and can be used exactly like seeded cities. --- apps/backend/src/geocoding.ts | 110 ++++++++-- apps/backend/src/schema/schema.ts | 104 +++++++++- apps/backend/tests/e2e/api.spec.ts | 102 +++++++++ .../__tests__/AddVenueDialog.test.tsx | 78 ++++++- .../src/components/admin/AddVenueDialog.tsx | 15 +- .../src/components/forms/CitySearchInput.tsx | 196 ++++++++++++++---- apps/frontend/src/graphql/cities.ts | 23 ++ apps/frontend/src/types/city.ts | 7 + 8 files changed, 571 insertions(+), 64 deletions(-) diff --git a/apps/backend/src/geocoding.ts b/apps/backend/src/geocoding.ts index f63b3fe..d3ae5da 100644 --- a/apps/backend/src/geocoding.ts +++ b/apps/backend/src/geocoding.ts @@ -5,33 +5,44 @@ export interface GeocodingResult { lon: number } +export interface CitySearchResult { + name: string + displayName: string + 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' +const REQUEST_TIMEOUT_MS = 5000 + +interface NominatimPlace { + lat: string + lon: string + name?: string + display_name: string + address?: { + city?: string + town?: string + village?: string + municipality?: string + } +} /** - * 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 + * Looks up addresses through Nominatim. 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', - }) - +async function searchNominatim( + params: URLSearchParams, +): Promise { const response = await fetch(`${NOMINATIM_URL}?${params}`, { headers: { 'User-Agent': USER_AGENT, }, - signal: AbortSignal.timeout(5000), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }) if (!response.ok) { @@ -40,7 +51,25 @@ export async function geocodeAddress( }) } - const results = (await response.json()) as GeocodingResult[] + return (await response.json()) as NominatimPlace[] +} + +/** + * Looks up the coordinates for a Norwegian address using Nominatim. + * Returns null when the address could not be found. + */ +export async function geocodeAddress( + address: string, + city: string, +): Promise { + const params = new URLSearchParams({ + q: `${address}, ${city}`, + format: 'jsonv2', + limit: '1', + countrycodes: 'no', + }) + + const results = await searchNominatim(params) if (results.length === 0) return null @@ -49,3 +78,50 @@ export async function geocodeAddress( lon: Number(results[0].lon), } } + +/** + * Searches Norwegian settlements through Nominatim. This is the fallback used + * by the admin venue form when the local city table has no match, so cities + * outside the seed data can still be used. + */ +export async function searchCities(term: string): Promise { + const params = new URLSearchParams({ + q: term, + format: 'jsonv2', + addressdetails: '1', + limit: '6', + featureType: 'settlement', + countrycodes: 'no', + 'accept-language': 'no', + }) + + const results = await searchNominatim(params) + const cities = new Map() + + for (const result of results) { + const lat = Number(result.lat) + const lon = Number(result.lon) + const name = + result.name ?? + result.address?.city ?? + result.address?.town ?? + result.address?.village ?? + result.address?.municipality ?? + result.display_name.split(',')[0]?.trim() + + if (!name || !Number.isFinite(lat) || !Number.isFinite(lon)) continue + + const key = name.toLocaleLowerCase('nb-NO') + + if (!cities.has(key)) { + cities.set(key, { + name, + displayName: result.display_name, + lat, + lon, + }) + } + } + + return [...cities.values()] +} diff --git a/apps/backend/src/schema/schema.ts b/apps/backend/src/schema/schema.ts index 980ae84..3a7b525 100644 --- a/apps/backend/src/schema/schema.ts +++ b/apps/backend/src/schema/schema.ts @@ -7,7 +7,8 @@ import type { import { GraphQLError } from 'graphql' import { builder } from '../builder.js' -import { geocodeAddress } from '../geocoding.js' +import type { Context } from '../context.js' +import { geocodeAddress, searchCities } from '../geocoding.js' import { latestPriceSightings } from './price-sightings.js' import type { VenueWithPriceSightings } from './price-sightings.js' @@ -50,6 +51,30 @@ builder.prismaObject('City', { }), }) +interface CityPlace { + name: string + displayName: string + lat: number + lon: number +} + +const cityPlaceRef = builder.objectRef('CityPlace').implement({ + fields: (t) => ({ + name: t.exposeString('name'), + displayName: t.exposeString('displayName'), + lat: t.exposeFloat('lat'), + lon: t.exposeFloat('lon'), + }), +}) + +function requireAdmin(context: Context) { + if (context.user?.role !== 'admin') { + throw new GraphQLError('Unauthorized', { + extensions: { code: 'UNAUTHORIZED' }, + }) + } +} + builder.prismaObject('Review', { fields: (t) => ({ id: t.exposeString('id'), @@ -523,6 +548,19 @@ builder.queryType({ }, }), }), + cityPlaceSearch: t.field({ + type: [cityPlaceRef], + args: { + name: t.arg.string({ required: true }), + }, + description: + 'Search Norwegian cities through Nominatim. Used by the admin form when the city is not in the database.', + resolve: (_parent, args) => { + const term = args.name.trim() + + return term.length < 2 ? [] : searchCities(term) + }, + }), search: t.field({ type: [searchResultRef], args: { @@ -779,11 +817,7 @@ builder.mutationType({ }), }, resolve: async (query, _parent, args, context) => { - if (context.user?.role !== 'admin') { - throw new GraphQLError('Unauthorized', { - extensions: { code: 'UNAUTHORIZED' }, - }) - } + requireAdmin(context) const city = await prisma.city.findUnique({ where: { id: args.input.cityId }, @@ -834,5 +868,63 @@ builder.mutationType({ }) }, }), + findOrCreateCity: t.prismaFieldWithInput({ + type: 'City', + input: { + name: t.input.string({ required: true }), + lat: t.input.float({ + required: true, + description: 'Latitude of the city centre.', + }), + lon: t.input.float({ + required: true, + description: 'Longitude of the city centre.', + }), + }, + resolve: async (query, _parent, args, context) => { + requireAdmin(context) + + const name = args.input.name.trim() + const { lat, lon } = args.input + + if (!name) { + throw new GraphQLError('City name is required', { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + if (!Number.isFinite(lat) || lat < -90 || lat > 90) { + throw new GraphQLError('lat must be between -90 and 90', { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + if (!Number.isFinite(lon) || lon < -180 || lon > 180) { + throw new GraphQLError('lon must be between -180 and 180', { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + const existing = await prisma.city.findFirst({ + where: { + name: { + equals: name, + mode: 'insensitive', + }, + }, + }) + + if (existing !== null) return existing + + return prisma.city.create({ + ...query, + data: { + name, + centreLat: lat, + centreLon: lon, + }, + }) + }, + }), }), }) diff --git a/apps/backend/tests/e2e/api.spec.ts b/apps/backend/tests/e2e/api.spec.ts index b03d9ea..df0875e 100644 --- a/apps/backend/tests/e2e/api.spec.ts +++ b/apps/backend/tests/e2e/api.spec.ts @@ -39,6 +39,27 @@ async function query( return body.data } +async function adminQuery( + request: APIRequestContext, + document: string, + variables?: Record, +): Promise { + const response = await request.post('/', { + headers: { authorization: `Bearer ${adminToken()}` }, + data: { query: document, variables }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors).toBeUndefined() + + if (body.data == null) { + throw new Error('GraphQL response did not contain data') + } + + return body.data +} + test('city query returns Trondheim and its map coordinates', async ({ request, }) => { @@ -626,6 +647,87 @@ test('createPriceSighting rejects an unknown venue', async ({ request }) => { expect(body.errors?.[0]?.message).toBe(`Unknown venue: ${unknownVenueId}`) }) +test('findOrCreateCity creates a city with coordinates and reuses it', async ({ + request, +}) => { + const name = `Playwright ${randomUUID()}` + const variables = { + input: { name, lat: 59.1234, lon: 10.5678 }, + } + + try { + const { findOrCreateCity } = await adminQuery<{ + findOrCreateCity: { + id: string + name: string + lat: number + lon: number + } + }>( + request, + ` + mutation FindOrCreateCity($input: MutationFindOrCreateCityInput!) { + findOrCreateCity(input: $input) { + id + name + lat + lon + } + } + `, + variables, + ) + + expect(findOrCreateCity).toMatchObject({ + id: expect.any(String), + name, + lat: 59.1234, + lon: 10.5678, + }) + + const second = await adminQuery<{ + findOrCreateCity: { id: string } + }>( + request, + ` + mutation FindOrCreateCity($input: MutationFindOrCreateCityInput!) { + findOrCreateCity(input: $input) { + id + } + } + `, + variables, + ) + + expect(second.findOrCreateCity.id).toBe(findOrCreateCity.id) + + const cities = await prisma.city.findMany({ where: { name } }) + expect(cities).toHaveLength(1) + } finally { + await prisma.city.deleteMany({ where: { name } }) + } +}) + +test('findOrCreateCity requires an admin user', async ({ request }) => { + const response = await request.post('/', { + data: { + query: ` + mutation { + findOrCreateCity( + input: { name: "Playwright city", lat: 59.1234, lon: 10.5678 } + ) { + id + } + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors?.[0]?.message).toBe('Unauthorized') +}) + test('createVenue rejects an unknown city before geocoding', async ({ request, }) => { diff --git a/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx b/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx index fa24309..ad0089a 100644 --- a/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx +++ b/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx @@ -1,7 +1,11 @@ import { fireEvent, screen, waitFor, within } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { CITY_SEARCH } from '#/graphql/cities' +import { + CITY_PLACE_SEARCH, + CITY_SEARCH, + FIND_OR_CREATE_CITY, +} from '#/graphql/cities' import { graphqlFetch } from '#/graphql/client' import { CREATE_VENUE } from '#/graphql/venues' import { renderWithProviders } from '#/test/render' @@ -159,4 +163,76 @@ describe('AddVenueDialog', () => { expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['venues'] }) }) + + it('creates a city found through the Nominatim fallback and uses its id', async () => { + const place = { + name: 'Bergen', + displayName: 'Bergen, Vestland, Norge', + lat: 60.3943055, + lon: 5.3259192, + } + const createdCity = { + id: 'city-bergen', + name: 'Bergen', + lat: place.lat, + lon: place.lon, + } + + mockGraphqlFetch.mockResolvedValueOnce({ city: [] }) + mockGraphqlFetch.mockResolvedValueOnce({ cityPlaceSearch: [place] }) + mockGraphqlFetch.mockResolvedValueOnce({ findOrCreateCity: createdCity }) + mockGraphqlFetch.mockResolvedValueOnce({ + createVenue: { id: 'venue-new' }, + }) + + const { user, dialog } = await openDialog() + + await user.type(screen.getByLabelText('Venue name'), 'Bryggen Pub') + await user.type(screen.getByLabelText('Address'), 'Bryggen 1') + await user.type(screen.getByLabelText('City'), 'Bergen') + + await user.click( + await screen.findByRole('button', { + name: /Bergen, Vestland, Norge/, + }), + ) + + await waitFor(() => { + expect(mockGraphqlFetch).toHaveBeenCalledWith(CITY_PLACE_SEARCH, { + name: 'Bergen', + }) + expect(mockGraphqlFetch).toHaveBeenCalledWith( + FIND_OR_CREATE_CITY, + { + input: { + name: place.name, + lat: place.lat, + lon: place.lon, + }, + }, + expect.any(String), + ) + }) + + expect( + await screen.findByRole('button', { name: 'Change' }), + ).toBeInTheDocument() + + submitForm(dialog) + + await waitFor(() => { + expect(mockGraphqlFetch).toHaveBeenCalledWith( + CREATE_VENUE, + { + input: { + name: 'Bryggen Pub', + address: 'Bryggen 1', + cityId: createdCity.id, + openingHours: [], + }, + }, + expect.any(String), + ) + }) + }) }) diff --git a/apps/frontend/src/components/admin/AddVenueDialog.tsx b/apps/frontend/src/components/admin/AddVenueDialog.tsx index ef18561..8eb484a 100644 --- a/apps/frontend/src/components/admin/AddVenueDialog.tsx +++ b/apps/frontend/src/components/admin/AddVenueDialog.tsx @@ -33,6 +33,11 @@ interface AddVenueDialogProps { onCreated?: () => void } +// Token lasts till 2033 for development. In production this would come from an +// auth provider. +const ADMIN_TOKEN = + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIwMWExZmZlZC1hNDY3LTc3MDQtOTM0MS1jM2ZjZjNiMTk5YWMiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE1MTYyMzkwMjIsImV4cCI6MjAwMDAwMDAwMH0.EohmXYCm3GANzUwpGetPEbEP8CRt5oF6Roc-4Y4ZLQk' + export function AddVenueDialog({ onCreated }: AddVenueDialogProps) { return ( - + diff --git a/apps/frontend/src/components/forms/CitySearchInput.tsx b/apps/frontend/src/components/forms/CitySearchInput.tsx index 474c11d..ae00b80 100644 --- a/apps/frontend/src/components/forms/CitySearchInput.tsx +++ b/apps/frontend/src/components/forms/CitySearchInput.tsx @@ -1,24 +1,41 @@ -import { keepPreviousData, useQuery } from '@tanstack/react-query' +import { + keepPreviousData, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/react-query' import { useEffect, useId, useState } from 'react' import type { KeyboardEvent } from 'react' import { FormField, inputClassName } from '#/components/ui/FormField' -import { CITY_SEARCH } from '#/graphql/cities' +import { + CITY_PLACE_SEARCH, + CITY_SEARCH, + FIND_OR_CREATE_CITY, +} from '#/graphql/cities' import { graphqlFetch } from '#/graphql/client' -import type { City } from '#/types/city' +import type { City, CityPlace } from '#/types/city' const DEBOUNCE_MS = 300 +const MIN_EXTERNAL_SEARCH_LENGTH = 2 interface CitySearchInputProps { value: City | null onChange: (city: City | null) => void label?: string + /** Admin token used to save cities found outside the local database. */ + createCityToken?: string } +type CitySuggestion = + | { key: string; name: string; city: City } + | { key: string; name: string; displayName: string; place: CityPlace } + export function CitySearchInput({ value, onChange, label = 'City', + createCityToken, }: CitySearchInputProps) { const inputId = useId() const listId = useId() @@ -27,6 +44,9 @@ export function CitySearchInput({ const [debouncedTerm, setDebouncedTerm] = useState('') const [open, setOpen] = useState(false) const [activeIndex, setActiveIndex] = useState(-1) + const [cityError, setCityError] = useState(null) + + const queryClient = useQueryClient() useEffect(() => { const timeout = setTimeout(() => setDebouncedTerm(term.trim()), DEBOUNCE_MS) @@ -41,9 +61,14 @@ export function CitySearchInput({ } else { setTerm('') } + setCityError(null) }, [value]) - const { data, isFetching, isError } = useQuery({ + const { + data: dbData, + isFetching: isDbFetching, + isError: isDbError, + } = useQuery({ queryKey: ['citySearch', debouncedTerm], queryFn: () => graphqlFetch<{ city: City[] }>(CITY_SEARCH, { name: debouncedTerm }), @@ -52,11 +77,69 @@ export function CitySearchInput({ retry: 1, }) - const cities = data?.city ?? [] + const dbCities = dbData?.city ?? [] const waitingForDebounce = term.trim() !== debouncedTerm - const activeCity = - activeIndex >= 0 && activeIndex < cities.length - ? cities[activeIndex] + + // Nominatim is only asked when the local city table has no match. This keeps + // seeded cities instant and avoids unnecessary external requests. + const shouldSearchPlaces = + value === null && + debouncedTerm.length >= MIN_EXTERNAL_SEARCH_LENGTH && + !waitingForDebounce && + !isDbFetching && + !isDbError && + dbCities.length === 0 + + const { + data: placesData, + isFetching: isPlacesFetching, + isPending: isPlacesPending, + isError: isPlacesError, + } = useQuery({ + queryKey: ['cityPlaces', debouncedTerm], + queryFn: () => + graphqlFetch<{ cityPlaceSearch: CityPlace[] }>(CITY_PLACE_SEARCH, { + name: debouncedTerm, + }), + enabled: shouldSearchPlaces, + retry: 1, + }) + + const { mutateAsync: createCity, isPending: isCreatingCity } = useMutation({ + mutationFn: (place: CityPlace) => + graphqlFetch<{ findOrCreateCity: City }>( + FIND_OR_CREATE_CITY, + { input: { name: place.name, lat: place.lat, lon: place.lon } }, + createCityToken, + ), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: ['search'] }) + }, + }) + + const places = shouldSearchPlaces ? (placesData?.cityPlaceSearch ?? []) : [] + const searchingPlaces = + shouldSearchPlaces && (isPlacesFetching || isPlacesPending) + const isSearching = waitingForDebounce || isDbFetching || searchingPlaces + const searchFailed = isDbError || (shouldSearchPlaces && isPlacesError) + + const suggestions: CitySuggestion[] = [ + ...dbCities.map((city) => ({ + key: city.id, + name: city.name, + city, + })), + ...places.map((place, index) => ({ + key: `place-${index}-${place.lat}-${place.lon}`, + name: place.name, + displayName: place.displayName, + place, + })), + ] + + const activeSuggestion = + activeIndex >= 0 && activeIndex < suggestions.length + ? suggestions[activeIndex] : undefined function select(city: City) { @@ -64,19 +147,48 @@ export function CitySearchInput({ setTerm(city.name) setOpen(false) setActiveIndex(-1) + setCityError(null) + } + + async function selectPlace(place: CityPlace) { + if (isCreatingCity) return + + setCityError(null) + + try { + const { findOrCreateCity } = await createCity(place) + select(findOrCreateCity) + } catch (error) { + setCityError( + error instanceof Error + ? error.message + : 'Could not add the city. Please try again.', + ) + } + } + + function choose(suggestion: CitySuggestion) { + if (isCreatingCity) return + + if ('city' in suggestion) { + select(suggestion.city) + return + } + + void selectPlace(suggestion.place) } function handleKeyDown(event: KeyboardEvent) { if (event.key === 'ArrowDown') { event.preventDefault() setOpen(true) - setActiveIndex((index) => Math.min(index + 1, cities.length - 1)) + setActiveIndex((index) => Math.min(index + 1, suggestions.length - 1)) } else if (event.key === 'ArrowUp') { event.preventDefault() setActiveIndex((index) => Math.max(index - 1, -1)) - } else if (event.key === 'Enter' && activeCity) { + } else if (event.key === 'Enter' && activeSuggestion) { event.preventDefault() - select(activeCity) + choose(activeSuggestion) } else if (event.key === 'Escape') { setOpen(false) setActiveIndex(-1) @@ -95,6 +207,7 @@ export function CitySearchInput({ onChange(null) setTerm('') setDebouncedTerm('') + setCityError(null) }} className="rounded-lg px-2 py-0.5 text-xs font-bold text-(--sea-ink-soft) hover:bg-(--link-bg-hover) hover:text-(--sea-ink) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--lagoon-deep)" > @@ -109,7 +222,7 @@ export function CitySearchInput({
setOpen(true)} onBlur={() => setOpen(false)} @@ -130,8 +244,9 @@ export function CitySearchInput({ aria-controls={listId} aria-expanded={open && term.trim().length > 0} aria-autocomplete="list" + aria-busy={isCreatingCity} aria-activedescendant={ - activeCity ? `${listId}-${activeCity.id}` : undefined + activeSuggestion ? `${listId}-option-${activeIndex}` : undefined } className={inputClassName} /> @@ -142,57 +257,66 @@ export function CitySearchInput({ role="listbox" className="absolute top-full right-0 left-0 z-10 mt-1 max-h-56 overflow-y-auto rounded-xl bg-(--surface-strong) p-1 shadow-lg" > - {isError && ( + {searchFailed && (
  • City search is unavailable right now.
  • )} - {!isError && (waitingForDebounce || isFetching) && ( + {!searchFailed && (isSearching || isCreatingCity) && (
  • - Searching… + {isCreatingCity ? 'Adding city…' : 'Searching…'}
  • )} - {!isError && - !waitingForDebounce && - !isFetching && - cities.length === 0 && ( + {!searchFailed && + !isSearching && + !isCreatingCity && + suggestions.length === 0 && (
  • No cities match “{debouncedTerm}”.
  • )} - {!isError && - cities.map((city) => ( + {!searchFailed && + suggestions.map((suggestion, index) => (
  • ))} )}
    + + {cityError && ( +

    + {cityError} +

    + )}
    ) } diff --git a/apps/frontend/src/graphql/cities.ts b/apps/frontend/src/graphql/cities.ts index 1c8194e..cd7342f 100644 --- a/apps/frontend/src/graphql/cities.ts +++ b/apps/frontend/src/graphql/cities.ts @@ -8,3 +8,26 @@ export const CITY_SEARCH = ` } } ` + +/** Nominatim-backed fallback used when the city is not in the database. */ +export const CITY_PLACE_SEARCH = ` + query CityPlaceSearch($name: String!) { + cityPlaceSearch(name: $name) { + name + displayName + lat + lon + } + } +` + +export const FIND_OR_CREATE_CITY = ` + mutation FindOrCreateCity($input: MutationFindOrCreateCityInput!) { + findOrCreateCity(input: $input) { + id + name + lat + lon + } + } +` diff --git a/apps/frontend/src/types/city.ts b/apps/frontend/src/types/city.ts index 61ed1d6..22d7726 100644 --- a/apps/frontend/src/types/city.ts +++ b/apps/frontend/src/types/city.ts @@ -4,3 +4,10 @@ export interface City { lat: number lon: number } + +export interface CityPlace { + name: string + displayName: string + lat: number + lon: number +} From 6975bb77b4f02063582c8a10d2d777b29da1d10c Mon Sep 17 00:00:00 2001 From: sivertlv Date: Sun, 22 Nov 2026 20:52:48 +0100 Subject: [PATCH 3/7] prettier --- docs/work-summary.md | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/work-summary.md b/docs/work-summary.md index 58d137c..7e6a789 100644 --- a/docs/work-summary.md +++ b/docs/work-summary.md @@ -17,27 +17,27 @@ The two initial course-staff commits by Trond Aalberg (29.08) are excluded. The ## Summary by date -| Date | Team window | Total person-hours | Members (estimated hours) | -|---|---:|---:|---| -| Tue 29.09 | 15:42–17:23 | 2.2 h | Henry 1.7, Sivert 0.5 | -| Wed 14.10 | 13:48–15:43 | 1.9 h | Henry 1.9 | -| Thu 15.10 | 20:27–22:55 | 3.6 h | Henry 2.5, Sivert 0.6, Kristian 0.5 | -| Fri 16.10 | 23:12 | 0.5 h | Henry 0.5 | -| Tue 27.10 | 18:44–21:41 | 3.9 h | Henry 2.9, Nicolay 0.5, Sivert 0.5 | -| Thu 29.10 | 13:29–20:07 | 18.8 h | Henry 5.0, Nicolay 5.3, Sivert 4.1, Kristian 4.4 | -| Fri 30.10 | 17:11 | 0.5 h | Nicolay 0.5 | -| Mon 09.11 | 14:19–19:48 | 9.7 h | Henry 5.5, Nicolay 4.2 | -| Sun 22.11 | 14:21–15:39 | 1.8 h | Henry 1.3, Nicolay 0.5 | -| **Total** | **9 dates** | **42.9 h** | **4 members** | +| Date | Team window | Total person-hours | Members (estimated hours) | +| --------- | ----------: | -----------------: | ------------------------------------------------ | +| Tue 29.09 | 15:42–17:23 | 2.2 h | Henry 1.7, Sivert 0.5 | +| Wed 14.10 | 13:48–15:43 | 1.9 h | Henry 1.9 | +| Thu 15.10 | 20:27–22:55 | 3.6 h | Henry 2.5, Sivert 0.6, Kristian 0.5 | +| Fri 16.10 | 23:12 | 0.5 h | Henry 0.5 | +| Tue 27.10 | 18:44–21:41 | 3.9 h | Henry 2.9, Nicolay 0.5, Sivert 0.5 | +| Thu 29.10 | 13:29–20:07 | 18.8 h | Henry 5.0, Nicolay 5.3, Sivert 4.1, Kristian 4.4 | +| Fri 30.10 | 17:11 | 0.5 h | Nicolay 0.5 | +| Mon 09.11 | 14:19–19:48 | 9.7 h | Henry 5.5, Nicolay 4.2 | +| Sun 22.11 | 14:21–15:39 | 1.8 h | Henry 1.3, Nicolay 0.5 | +| **Total** | **9 dates** | **42.9 h** | **4 members** | ## Summary by member -| Member | Active dates | Commits | Estimated hours | -|---|---:|---:|---:| -| Henry Græsberg | 8 | 25 | 21.3 h | -| Nicolay Bennett Rennemo | 5 | 9 | 11.0 h | -| Sivert Lindblad Vårum | 4 | 6 | 5.7 h | -| Kristian Numme | 2 | 4 | 4.9 h | +| Member | Active dates | Commits | Estimated hours | +| ----------------------- | -----------: | ------: | --------------: | +| Henry Græsberg | 8 | 25 | 21.3 h | +| Nicolay Bennett Rennemo | 5 | 9 | 11.0 h | +| Sivert Lindblad Vårum | 4 | 6 | 5.7 h | +| Kristian Numme | 2 | 4 | 4.9 h | Summed daily team windows are approximately 22.4 hours. The 42.9-hour total is person-hours where members worked in parallel. From 39bbd9520dc309c7cae465278cfbe33db56d1ede Mon Sep 17 00:00:00 2001 From: sivertlv Date: Sun, 22 Nov 2026 21:05:05 +0100 Subject: [PATCH 4/7] feat: search worldwide cities alongside database results Remove the Norway restriction from city and address lookups, merge Nominatim candidates with known cities with database results first, and store each external place's full display name so same-named cities in different regions remain distinct. --- apps/backend/src/geocoding.ts | 19 ++-- apps/backend/src/schema/schema.ts | 43 +++++++- apps/backend/tests/e2e/api.spec.ts | 35 +++++- .../__tests__/AddVenueDialog.test.tsx | 99 +++++++++++++---- .../src/components/forms/CitySearchInput.tsx | 101 +++++++++++++----- apps/frontend/src/graphql/cities.ts | 4 +- apps/frontend/src/types/city.ts | 1 + .../migration.sql | 1 + packages/db/prisma/schema.prisma | 9 +- 9 files changed, 246 insertions(+), 66 deletions(-) create mode 100644 packages/db/prisma/migrations/20261122120000_add_city_display_name/migration.sql diff --git a/apps/backend/src/geocoding.ts b/apps/backend/src/geocoding.ts index d3ae5da..aca97ef 100644 --- a/apps/backend/src/geocoding.ts +++ b/apps/backend/src/geocoding.ts @@ -55,8 +55,8 @@ async function searchNominatim( } /** - * Looks up the coordinates for a Norwegian address using Nominatim. - * Returns null when the address could not be found. + * Looks up the coordinates for an address using Nominatim. Returns null when + * the address could not be found. */ export async function geocodeAddress( address: string, @@ -66,7 +66,6 @@ export async function geocodeAddress( q: `${address}, ${city}`, format: 'jsonv2', limit: '1', - countrycodes: 'no', }) const results = await searchNominatim(params) @@ -80,19 +79,17 @@ export async function geocodeAddress( } /** - * Searches Norwegian settlements through Nominatim. This is the fallback used - * by the admin venue form when the local city table has no match, so cities - * outside the seed data can still be used. + * Searches settlements through Nominatim. This is the fallback used by the + * admin venue form for cities outside the local city table. */ export async function searchCities(term: string): Promise { const params = new URLSearchParams({ q: term, format: 'jsonv2', addressdetails: '1', - limit: '6', + limit: '8', featureType: 'settlement', - countrycodes: 'no', - 'accept-language': 'no', + 'accept-language': 'no,en', }) const results = await searchNominatim(params) @@ -111,7 +108,9 @@ export async function searchCities(term: string): Promise { if (!name || !Number.isFinite(lat) || !Number.isFinite(lon)) continue - const key = name.toLocaleLowerCase('nb-NO') + // Keep same-named places in different regions/countries: the display name + // includes the administrative context that the short name omits. + const key = result.display_name.toLocaleLowerCase('nb-NO') if (!cities.has(key)) { cities.set(key, { diff --git a/apps/backend/src/schema/schema.ts b/apps/backend/src/schema/schema.ts index 3a7b525..75b68b4 100644 --- a/apps/backend/src/schema/schema.ts +++ b/apps/backend/src/schema/schema.ts @@ -46,6 +46,7 @@ builder.prismaObject('City', { fields: (t) => ({ id: t.exposeString('id'), name: t.exposeString('name'), + displayName: t.exposeString('displayName', { nullable: true }), lat: t.exposeFloat('centreLat'), lon: t.exposeFloat('centreLon'), }), @@ -75,6 +76,19 @@ function requireAdmin(context: Context) { } } +function distanceKm(aLat: number, aLon: number, bLat: number, bLon: number) { + const toRadians = (degrees: number) => (degrees * Math.PI) / 180 + const latDelta = toRadians(bLat - aLat) + const lonDelta = toRadians(bLon - aLon) + const a = + Math.sin(latDelta / 2) ** 2 + + Math.cos(toRadians(aLat)) * + Math.cos(toRadians(bLat)) * + Math.sin(lonDelta / 2) ** 2 + + return 6371 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) +} + builder.prismaObject('Review', { fields: (t) => ({ id: t.exposeString('id'), @@ -546,6 +560,7 @@ builder.queryType({ mode: 'insensitive', }, }, + orderBy: { name: 'asc' }, }), }), cityPlaceSearch: t.field({ @@ -554,7 +569,7 @@ builder.queryType({ name: t.arg.string({ required: true }), }, description: - 'Search Norwegian cities through Nominatim. Used by the admin form when the city is not in the database.', + 'Search cities through Nominatim. Used by the admin form to find places outside the local database.', resolve: (_parent, args) => { const term = args.name.trim() @@ -821,7 +836,7 @@ builder.mutationType({ const city = await prisma.city.findUnique({ where: { id: args.input.cityId }, - select: { id: true, name: true }, + select: { id: true, name: true, displayName: true }, }) if (city === null) { @@ -830,7 +845,10 @@ builder.mutationType({ }) } - const coordinates = await geocodeAddress(args.input.address, city.name) + const coordinates = await geocodeAddress( + args.input.address, + city.displayName ?? city.name, + ) if (coordinates === null) { throw new GraphQLError( @@ -872,6 +890,11 @@ builder.mutationType({ type: 'City', input: { name: t.input.string({ required: true }), + displayName: t.input.string({ + required: false, + description: + 'Full place name from Nominatim, including region and country.', + }), lat: t.input.float({ required: true, description: 'Latitude of the city centre.', @@ -885,6 +908,7 @@ builder.mutationType({ requireAdmin(context) const name = args.input.name.trim() + const displayName = args.input.displayName?.trim() || null const { lat, lon } = args.input if (!name) { @@ -905,7 +929,7 @@ builder.mutationType({ }) } - const existing = await prisma.city.findFirst({ + const candidates = await prisma.city.findMany({ where: { name: { equals: name, @@ -914,12 +938,23 @@ builder.mutationType({ }, }) + const normalizedDisplayName = displayName?.toLocaleLowerCase('nb-NO') + const existing = + candidates.find( + (city) => + (normalizedDisplayName !== undefined && + city.displayName?.toLocaleLowerCase('nb-NO') === + normalizedDisplayName) || + distanceKm(lat, lon, city.centreLat, city.centreLon) <= 25, + ) ?? null + if (existing !== null) return existing return prisma.city.create({ ...query, data: { name, + displayName, centreLat: lat, centreLon: lon, }, diff --git a/apps/backend/tests/e2e/api.spec.ts b/apps/backend/tests/e2e/api.spec.ts index df0875e..fbfa62f 100644 --- a/apps/backend/tests/e2e/api.spec.ts +++ b/apps/backend/tests/e2e/api.spec.ts @@ -647,12 +647,13 @@ test('createPriceSighting rejects an unknown venue', async ({ request }) => { expect(body.errors?.[0]?.message).toBe(`Unknown venue: ${unknownVenueId}`) }) -test('findOrCreateCity creates a city with coordinates and reuses it', async ({ +test('findOrCreateCity reuses matching places and separates same-named cities', async ({ request, }) => { const name = `Playwright ${randomUUID()}` + const displayName = `${name}, Testland` const variables = { - input: { name, lat: 59.1234, lon: 10.5678 }, + input: { name, displayName, lat: 59.1234, lon: 10.5678 }, } try { @@ -660,6 +661,7 @@ test('findOrCreateCity creates a city with coordinates and reuses it', async ({ findOrCreateCity: { id: string name: string + displayName: string | null lat: number lon: number } @@ -670,6 +672,7 @@ test('findOrCreateCity creates a city with coordinates and reuses it', async ({ findOrCreateCity(input: $input) { id name + displayName lat lon } @@ -681,6 +684,7 @@ test('findOrCreateCity creates a city with coordinates and reuses it', async ({ expect(findOrCreateCity).toMatchObject({ id: expect.any(String), name, + displayName, lat: 59.1234, lon: 10.5678, }) @@ -701,8 +705,33 @@ test('findOrCreateCity creates a city with coordinates and reuses it', async ({ expect(second.findOrCreateCity.id).toBe(findOrCreateCity.id) + const otherPlace = await adminQuery<{ + findOrCreateCity: { id: string; displayName: string | null } + }>( + request, + ` + mutation FindOrCreateCity($input: MutationFindOrCreateCityInput!) { + findOrCreateCity(input: $input) { + id + displayName + } + } + `, + { + input: { + name, + displayName: `${name}, Anotherland`, + lat: 40.7128, + lon: -74.006, + }, + }, + ) + + expect(otherPlace.findOrCreateCity.id).not.toBe(findOrCreateCity.id) + expect(otherPlace.findOrCreateCity.displayName).toBe(`${name}, Anotherland`) + const cities = await prisma.city.findMany({ where: { name } }) - expect(cities).toHaveLength(1) + expect(cities).toHaveLength(2) } finally { await prisma.city.deleteMany({ where: { name } }) } diff --git a/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx b/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx index ad0089a..f818985 100644 --- a/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx +++ b/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx @@ -9,6 +9,7 @@ import { import { graphqlFetch } from '#/graphql/client' import { CREATE_VENUE } from '#/graphql/venues' import { renderWithProviders } from '#/test/render' +import type { City, CityPlace } from '#/types/city' import { AddVenueDialog } from '../admin/AddVenueDialog' vi.mock('#/graphql/client', () => ({ @@ -17,13 +18,50 @@ vi.mock('#/graphql/client', () => ({ const mockGraphqlFetch = vi.mocked(graphqlFetch) -const CITY = { +const CITY: City = { id: 'city-1', name: 'Trondheim', + displayName: null, lat: 63.4305, lon: 10.3951, } +interface MockApiOptions { + cities?: City[] + places?: CityPlace[] + createdCity?: City +} + +function mockApi({ + cities = [], + places = [], + createdCity, +}: MockApiOptions = {}) { + mockGraphqlFetch.mockImplementation(async (query) => { + if (query === CITY_SEARCH) { + return { city: cities } + } + + if (query === CITY_PLACE_SEARCH) { + return { cityPlaceSearch: places } + } + + if (query === FIND_OR_CREATE_CITY) { + if (!createdCity) { + throw new Error('findOrCreateCity was not expected') + } + + return { findOrCreateCity: createdCity } + } + + if (query === CREATE_VENUE) { + return { createVenue: { id: 'venue-new' } } + } + + throw new Error(`Unexpected GraphQL query: ${query}`) + }) +} + async function openDialog() { const utils = renderWithProviders() @@ -92,7 +130,7 @@ describe('AddVenueDialog', () => { }) it('requires every opening-hours entry to have days and times', async () => { - mockGraphqlFetch.mockResolvedValueOnce({ city: [CITY] }) + mockApi({ cities: [CITY] }) const { user, dialog } = await openDialog() @@ -113,11 +151,7 @@ describe('AddVenueDialog', () => { }) it('searches for a city and submits the venue with opening hours', async () => { - mockGraphqlFetch.mockResolvedValueOnce({ city: [CITY] }) - mockGraphqlFetch.mockResolvedValueOnce({ - createVenue: { id: 'venue-new' }, - }) - mockGraphqlFetch.mockResolvedValue({ city: [CITY] }) + mockApi({ cities: [CITY] }) const { user, dialog, queryClient } = await openDialog() const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') @@ -164,7 +198,34 @@ describe('AddVenueDialog', () => { expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['venues'] }) }) - it('creates a city found through the Nominatim fallback and uses its id', async () => { + it('does not duplicate database cities in the Nominatim results', async () => { + mockApi({ + cities: [CITY], + places: [ + { + name: 'Trondheim', + displayName: 'Trondheim, Trøndelag, Norge', + lat: 63.4305, + lon: 10.3951, + }, + ], + }) + + const { user } = await openDialog() + + await user.type(screen.getByLabelText('City'), 'Tro') + + await screen.findByRole('button', { name: 'Trondheim' }) + await waitFor(() => { + expect(mockGraphqlFetch).toHaveBeenCalledWith(CITY_PLACE_SEARCH, { + name: 'Tro', + }) + }) + + expect(screen.getAllByRole('option')).toHaveLength(1) + }) + + it('merges database and Nominatim results, keeping database cities first', async () => { const place = { name: 'Bergen', displayName: 'Bergen, Vestland, Norge', @@ -174,16 +235,12 @@ describe('AddVenueDialog', () => { const createdCity = { id: 'city-bergen', name: 'Bergen', + displayName: place.displayName, lat: place.lat, lon: place.lon, } - mockGraphqlFetch.mockResolvedValueOnce({ city: [] }) - mockGraphqlFetch.mockResolvedValueOnce({ cityPlaceSearch: [place] }) - mockGraphqlFetch.mockResolvedValueOnce({ findOrCreateCity: createdCity }) - mockGraphqlFetch.mockResolvedValueOnce({ - createVenue: { id: 'venue-new' }, - }) + mockApi({ cities: [CITY], places: [place], createdCity }) const { user, dialog } = await openDialog() @@ -191,11 +248,14 @@ describe('AddVenueDialog', () => { await user.type(screen.getByLabelText('Address'), 'Bryggen 1') await user.type(screen.getByLabelText('City'), 'Bergen') - await user.click( - await screen.findByRole('button', { - name: /Bergen, Vestland, Norge/, - }), - ) + const externalOption = await screen.findByRole('button', { + name: /Bergen, Vestland, Norge/, + }) + const options = screen.getAllByRole('option') + expect(options[0]).toHaveTextContent('Trondheim') + expect(options[1]).toHaveTextContent('Bergen') + + await user.click(externalOption) await waitFor(() => { expect(mockGraphqlFetch).toHaveBeenCalledWith(CITY_PLACE_SEARCH, { @@ -206,6 +266,7 @@ describe('AddVenueDialog', () => { { input: { name: place.name, + displayName: place.displayName, lat: place.lat, lon: place.lon, }, diff --git a/apps/frontend/src/components/forms/CitySearchInput.tsx b/apps/frontend/src/components/forms/CitySearchInput.tsx index ae00b80..a341406 100644 --- a/apps/frontend/src/components/forms/CitySearchInput.tsx +++ b/apps/frontend/src/components/forms/CitySearchInput.tsx @@ -28,9 +28,40 @@ interface CitySearchInputProps { } type CitySuggestion = - | { key: string; name: string; city: City } + | { key: string; name: string; displayName?: string | null; city: City } | { key: string; name: string; displayName: string; place: CityPlace } +function distanceKm(aLat: number, aLon: number, bLat: number, bLon: number) { + const toRadians = (degrees: number) => (degrees * Math.PI) / 180 + const latDelta = toRadians(bLat - aLat) + const lonDelta = toRadians(bLon - aLon) + const a = + Math.sin(latDelta / 2) ** 2 + + Math.cos(toRadians(aLat)) * + Math.cos(toRadians(bLat)) * + Math.sin(lonDelta / 2) ** 2 + + return 6371 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) +} + +function isKnownCity(place: CityPlace, cities: City[]) { + const placeName = place.name.toLocaleLowerCase('nb-NO') + const placeDisplayName = place.displayName.toLocaleLowerCase('nb-NO') + + return cities.some((city) => { + if (city.name.toLocaleLowerCase('nb-NO') !== placeName) return false + + if ( + city.displayName && + city.displayName.toLocaleLowerCase('nb-NO') === placeDisplayName + ) { + return true + } + + return distanceKm(place.lat, place.lon, city.lat, city.lon) <= 25 + }) +} + export function CitySearchInput({ value, onChange, @@ -68,6 +99,7 @@ export function CitySearchInput({ data: dbData, isFetching: isDbFetching, isError: isDbError, + isPlaceholderData: isDbPlaceholderData, } = useQuery({ queryKey: ['citySearch', debouncedTerm], queryFn: () => @@ -77,18 +109,15 @@ export function CitySearchInput({ retry: 1, }) - const dbCities = dbData?.city ?? [] + const dbCities = isDbPlaceholderData ? [] : (dbData?.city ?? []) const waitingForDebounce = term.trim() !== debouncedTerm - // Nominatim is only asked when the local city table has no match. This keeps - // seeded cities instant and avoids unnecessary external requests. + // The local results and the Nominatim results are combined, so both known + // cities and new places are visible in the same list. const shouldSearchPlaces = value === null && debouncedTerm.length >= MIN_EXTERNAL_SEARCH_LENGTH && - !waitingForDebounce && - !isDbFetching && - !isDbError && - dbCities.length === 0 + !waitingForDebounce const { data: placesData, @@ -109,7 +138,14 @@ export function CitySearchInput({ mutationFn: (place: CityPlace) => graphqlFetch<{ findOrCreateCity: City }>( FIND_OR_CREATE_CITY, - { input: { name: place.name, lat: place.lat, lon: place.lon } }, + { + input: { + name: place.name, + displayName: place.displayName, + lat: place.lat, + lon: place.lon, + }, + }, createCityToken, ), onSuccess: () => { @@ -118,18 +154,19 @@ export function CitySearchInput({ }) const places = shouldSearchPlaces ? (placesData?.cityPlaceSearch ?? []) : [] + const newPlaces = places.filter((place) => !isKnownCity(place, dbCities)) const searchingPlaces = shouldSearchPlaces && (isPlacesFetching || isPlacesPending) const isSearching = waitingForDebounce || isDbFetching || searchingPlaces - const searchFailed = isDbError || (shouldSearchPlaces && isPlacesError) const suggestions: CitySuggestion[] = [ ...dbCities.map((city) => ({ key: city.id, name: city.name, + displayName: city.displayName, city, })), - ...places.map((place, index) => ({ + ...newPlaces.map((place, index) => ({ key: `place-${index}-${place.lat}-${place.lon}`, name: place.name, displayName: place.displayName, @@ -137,6 +174,10 @@ export function CitySearchInput({ })), ] + const hasSuggestions = suggestions.length > 0 + const searchFailed = + !hasSuggestions && (isDbError || (shouldSearchPlaces && isPlacesError)) + const activeSuggestion = activeIndex >= 0 && activeIndex < suggestions.length ? suggestions[activeIndex] @@ -200,7 +241,14 @@ export function CitySearchInput({
    {label}
    - {value.name} + + {value.name} + {value.displayName && value.displayName !== value.name && ( + + {value.displayName} + + )} + ))} diff --git a/apps/frontend/src/graphql/cities.ts b/apps/frontend/src/graphql/cities.ts index cd7342f..08418ec 100644 --- a/apps/frontend/src/graphql/cities.ts +++ b/apps/frontend/src/graphql/cities.ts @@ -3,13 +3,14 @@ export const CITY_SEARCH = ` city(name: $name) { id name + displayName lat lon } } ` -/** Nominatim-backed fallback used when the city is not in the database. */ +/** Nominatim-backed search used alongside the database results. */ export const CITY_PLACE_SEARCH = ` query CityPlaceSearch($name: String!) { cityPlaceSearch(name: $name) { @@ -26,6 +27,7 @@ export const FIND_OR_CREATE_CITY = ` findOrCreateCity(input: $input) { id name + displayName lat lon } diff --git a/apps/frontend/src/types/city.ts b/apps/frontend/src/types/city.ts index 22d7726..e6cb42c 100644 --- a/apps/frontend/src/types/city.ts +++ b/apps/frontend/src/types/city.ts @@ -1,6 +1,7 @@ export interface City { id: string name: string + displayName?: string | null lat: number lon: number } diff --git a/packages/db/prisma/migrations/20261122120000_add_city_display_name/migration.sql b/packages/db/prisma/migrations/20261122120000_add_city_display_name/migration.sql new file mode 100644 index 0000000..f62323d --- /dev/null +++ b/packages/db/prisma/migrations/20261122120000_add_city_display_name/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "city" ADD COLUMN "display_name" TEXT; diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index 690c5e0..d393725 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -85,10 +85,11 @@ model OpeningHoursNote { } model City { - id String @id @default(dbgenerated("uuidv7()")) @db.Uuid - name String - centreLon Float @map("centre_lon") - centreLat Float @map("centre_lat") + id String @id @default(dbgenerated("uuidv7()")) @db.Uuid + name String + displayName String? @map("display_name") + centreLon Float @map("centre_lon") + centreLat Float @map("centre_lat") venues Venue[] From 2a8cd20877ecd1fea54275e6d36196ded4d87a54 Mon Sep 17 00:00:00 2001 From: sivertlv Date: Sun, 22 Nov 2026 21:12:36 +0100 Subject: [PATCH 5/7] fix: let Enter accept the first city search result Pressing Enter after searching previously submitted the venue form instead of selecting a city, so external places such as Stockholm appeared impossible to accept. --- .../components/__tests__/AddVenueDialog.test.tsx | 14 ++++++++++++++ .../src/components/forms/CitySearchInput.tsx | 12 ++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx b/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx index f818985..d3b2a75 100644 --- a/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx +++ b/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx @@ -129,6 +129,20 @@ describe('AddVenueDialog', () => { ) }) + it('selects the first city result when Enter is pressed', async () => { + mockApi({ cities: [CITY] }) + + const { user } = await openDialog() + + await user.type(screen.getByLabelText('City'), 'Tro') + await screen.findByRole('button', { name: 'Trondheim' }) + await user.keyboard('{Enter}') + + expect( + await screen.findByRole('button', { name: 'Change' }), + ).toBeInTheDocument() + }) + it('requires every opening-hours entry to have days and times', async () => { mockApi({ cities: [CITY] }) diff --git a/apps/frontend/src/components/forms/CitySearchInput.tsx b/apps/frontend/src/components/forms/CitySearchInput.tsx index a341406..67e4dc6 100644 --- a/apps/frontend/src/components/forms/CitySearchInput.tsx +++ b/apps/frontend/src/components/forms/CitySearchInput.tsx @@ -227,9 +227,13 @@ export function CitySearchInput({ } else if (event.key === 'ArrowUp') { event.preventDefault() setActiveIndex((index) => Math.max(index - 1, -1)) - } else if (event.key === 'Enter' && activeSuggestion) { - event.preventDefault() - choose(activeSuggestion) + } else if (event.key === 'Enter') { + const suggestion = activeSuggestion ?? suggestions.at(0) + + if (suggestion) { + event.preventDefault() + choose(suggestion) + } } else if (event.key === 'Escape') { setOpen(false) setActiveIndex(-1) @@ -270,7 +274,7 @@ export function CitySearchInput({
    Date: Sun, 22 Nov 2026 22:10:25 +0100 Subject: [PATCH 6/7] fix citySearchInput debounce to 1000ms --- apps/frontend/src/components/forms/CitySearchInput.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/frontend/src/components/forms/CitySearchInput.tsx b/apps/frontend/src/components/forms/CitySearchInput.tsx index 67e4dc6..cf36075 100644 --- a/apps/frontend/src/components/forms/CitySearchInput.tsx +++ b/apps/frontend/src/components/forms/CitySearchInput.tsx @@ -16,7 +16,7 @@ import { import { graphqlFetch } from '#/graphql/client' import type { City, CityPlace } from '#/types/city' -const DEBOUNCE_MS = 300 +const DEBOUNCE_MS = 1000 const MIN_EXTERNAL_SEARCH_LENGTH = 2 interface CitySearchInputProps { From 7ab4482938fade9195b6e07d9a236227850c256a Mon Sep 17 00:00:00 2001 From: sivertlv Date: Sun, 22 Nov 2026 22:34:20 +0100 Subject: [PATCH 7/7] fix test not passing --- apps/backend/tests/e2e/api.spec.ts | 166 +++++++++++++++++++++-------- apps/frontend/src/test/setup.ts | 6 +- packages/db/src/index.ts | 7 +- 3 files changed, 133 insertions(+), 46 deletions(-) diff --git a/apps/backend/tests/e2e/api.spec.ts b/apps/backend/tests/e2e/api.spec.ts index fbfa62f..ff37182 100644 --- a/apps/backend/tests/e2e/api.spec.ts +++ b/apps/backend/tests/e2e/api.spec.ts @@ -3,7 +3,7 @@ import type { APIRequestContext } from '@playwright/test' import { randomUUID } from 'node:crypto' import jwt from 'jsonwebtoken' -import { prisma } from '@t09-project-2/db' +import { Day, GlassSize, prisma } from '@t09-project-2/db' const ADMIN_SECRET = 'secret-string' @@ -94,55 +94,133 @@ test('city query returns Trondheim and its map coordinates', async ({ test('venue query returns its related city, hours, prices, and reviews', async ({ request, }) => { - const { venue } = await query<{ - venue: { - name: string - city: { name: string } - openingHours: { days: string[] }[] - pricesSighted: { price: number }[] - reviews: { username: string; rating: number }[] - }[] - }>( - request, - ` - query { - venue { - name - city { + const suffix = randomUUID() + const cityName = `zz test city ${suffix}` + const venueName = `zz test venue ${suffix}` + // Deliberately far from Trondheim and last alphabetically so this fixture + // cannot affect the ordering assertions in the pagination tests running in + // parallel. + const latitude = -33.8688 + const longitude = 151.2093 + let cityId: string | undefined + let venueId: string | undefined + + try { + const city = await prisma.city.create({ + data: { + name: cityName, + centreLat: latitude, + centreLon: longitude, + }, + }) + cityId = city.id + + const venue = await prisma.venue.create({ + data: { + name: venueName, + address: 'Testveien 1', + lat: latitude, + lon: longitude, + cityId: city.id, + openingHours: { + create: [ + { + days: [Day.MON], + opening: new Date('2000-01-01T12:00:00Z'), + closing: new Date('2000-01-01T20:00:00Z'), + }, + ], + }, + pricesSighted: { + create: [ + { + price: 99, + size: GlassSize.PINT, + limitation: [], + }, + ], + }, + reviews: { + create: [ + { + username: 'fixture-user', + body: 'Fixture review', + rating: 4, + }, + ], + }, + }, + }) + venueId = venue.id + + const { venue: venues } = await query<{ + venue: { + name: string + city: { name: string } + openingHours: { days: string[] }[] + pricesSighted: { price: number }[] + reviews: { username: string; rating: number }[] + }[] + }>( + request, + ` + query { + venue { name - } - openingHours { - days - } - pricesSighted { - price - } - reviews { - username - rating + city { + name + } + openingHours { + days + } + pricesSighted { + price + } + reviews { + username + rating + } } } - } - `, - ) + `, + ) - const seededVenue = venue.find(({ name }) => name === 'Den Gode Nabo') - expect(seededVenue).toBeDefined() + const createdVenue = venues.find(({ name }) => name === venueName) + expect(createdVenue).toBeDefined() - if (!seededVenue) { - throw new Error('Seeded venue "Den Gode Nabo" was not returned') - } + if (!createdVenue) { + throw new Error(`Created venue "${venueName}" was not returned`) + } - expect(seededVenue.city.name).toBe('Trondheim') - expect(seededVenue.openingHours).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - days: expect.arrayContaining(['MON']), - }), - ]), - ) - expect(seededVenue.pricesSighted.length).toBeGreaterThan(0) - expect(seededVenue.reviews.length).toBeGreaterThan(0) + expect(createdVenue.city.name).toBe(cityName) + expect(createdVenue.openingHours).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + days: expect.arrayContaining(['MON']), + }), + ]), + ) + expect(createdVenue.pricesSighted).toEqual( + expect.arrayContaining([expect.objectContaining({ price: 99 })]), + ) + expect(createdVenue.reviews).toEqual( + expect.arrayContaining([ + expect.objectContaining({ username: 'fixture-user', rating: 4 }), + ]), + ) + } finally { + if (venueId) { + await prisma.review.deleteMany({ where: { venueId } }) + await prisma.priceSighting.deleteMany({ where: { venueId } }) + await prisma.openingHours.deleteMany({ where: { venueId } }) + await prisma.openingHoursNote.deleteMany({ where: { venueId } }) + await prisma.venue.deleteMany({ where: { id: venueId } }) + } + + if (cityId) { + await prisma.city.deleteMany({ where: { id: cityId } }) + } + } }) test('venue query paginates with a cursor without changing its sort order', async ({ diff --git a/apps/frontend/src/test/setup.ts b/apps/frontend/src/test/setup.ts index 05ece6a..f97f9a4 100644 --- a/apps/frontend/src/test/setup.ts +++ b/apps/frontend/src/test/setup.ts @@ -1,8 +1,12 @@ import '@testing-library/jest-dom/vitest' -import { cleanup } from '@testing-library/react' +import { cleanup, configure } from '@testing-library/react' import { afterEach, vi } from 'vitest' +// City search debounces by 1 second, so async queries need more than the +// Testing Library default timeout of 1 second. +configure({ asyncUtilTimeout: 3000 }) + // The in-memory router tries to restore scroll position after navigation. window.scrollTo = vi.fn() diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 0c68b18..43eedc5 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -1,6 +1,11 @@ export { getDatabaseUrl } from './database-url.js' export { prisma } from './client.js' -export { GlassSize, Prisma, PrismaClient } from './generated/prisma/client.js' +export { + Day, + GlassSize, + Prisma, + PrismaClient, +} from './generated/prisma/client.js' export type { OpeningHours, OpeningHoursNote,