diff --git a/apps/backend/src/geocoding.ts b/apps/backend/src/geocoding.ts index f63b3fe..aca97ef 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,24 @@ export async function geocodeAddress( }) } - const results = (await response.json()) as GeocodingResult[] + return (await response.json()) as NominatimPlace[] +} + +/** + * Looks up the coordinates for an 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', + }) + + const results = await searchNominatim(params) if (results.length === 0) return null @@ -49,3 +77,50 @@ export async function geocodeAddress( lon: Number(results[0].lon), } } + +/** + * 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: '8', + featureType: 'settlement', + 'accept-language': 'no,en', + }) + + 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 + + // 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, { + 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..75b68b4 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' @@ -45,11 +46,49 @@ 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'), }), }) +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' }, + }) + } +} + +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'), @@ -521,8 +560,22 @@ builder.queryType({ mode: 'insensitive', }, }, + orderBy: { name: 'asc' }, }), }), + cityPlaceSearch: t.field({ + type: [cityPlaceRef], + args: { + name: t.arg.string({ required: true }), + }, + description: + 'Search cities through Nominatim. Used by the admin form to find places outside the local database.', + resolve: (_parent, args) => { + const term = args.name.trim() + + return term.length < 2 ? [] : searchCities(term) + }, + }), search: t.field({ type: [searchResultRef], args: { @@ -779,15 +832,11 @@ 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 }, - select: { id: true, name: true }, + select: { id: true, name: true, displayName: true }, }) if (city === null) { @@ -796,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( @@ -834,5 +886,80 @@ builder.mutationType({ }) }, }), + findOrCreateCity: t.prismaFieldWithInput({ + 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.', + }), + 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 displayName = args.input.displayName?.trim() || null + 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 candidates = await prisma.city.findMany({ + where: { + name: { + equals: name, + mode: 'insensitive', + }, + }, + }) + + 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 b03d9ea..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' @@ -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, }) => { @@ -73,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 ({ @@ -626,6 +725,116 @@ test('createPriceSighting rejects an unknown venue', async ({ request }) => { expect(body.errors?.[0]?.message).toBe(`Unknown venue: ${unknownVenueId}`) }) +test('findOrCreateCity reuses matching places and separates same-named cities', async ({ + request, +}) => { + const name = `Playwright ${randomUUID()}` + const displayName = `${name}, Testland` + const variables = { + input: { name, displayName, lat: 59.1234, lon: 10.5678 }, + } + + try { + const { findOrCreateCity } = await adminQuery<{ + findOrCreateCity: { + id: string + name: string + displayName: string | null + lat: number + lon: number + } + }>( + request, + ` + mutation FindOrCreateCity($input: MutationFindOrCreateCityInput!) { + findOrCreateCity(input: $input) { + id + name + displayName + lat + lon + } + } + `, + variables, + ) + + expect(findOrCreateCity).toMatchObject({ + id: expect.any(String), + name, + displayName, + 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 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(2) + } 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..d3b2a75 100644 --- a/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx +++ b/apps/frontend/src/components/__tests__/AddVenueDialog.test.tsx @@ -1,10 +1,15 @@ 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' +import type { City, CityPlace } from '#/types/city' import { AddVenueDialog } from '../admin/AddVenueDialog' vi.mock('#/graphql/client', () => ({ @@ -13,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() @@ -87,8 +129,22 @@ 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 () => { - mockGraphqlFetch.mockResolvedValueOnce({ city: [CITY] }) + mockApi({ cities: [CITY] }) const { user, dialog } = await openDialog() @@ -109,11 +165,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') @@ -159,4 +211,103 @@ describe('AddVenueDialog', () => { expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['venues'] }) }) + + 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', + lat: 60.3943055, + lon: 5.3259192, + } + const createdCity = { + id: 'city-bergen', + name: 'Bergen', + displayName: place.displayName, + lat: place.lat, + lon: place.lon, + } + + mockApi({ cities: [CITY], places: [place], createdCity }) + + 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') + + 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, { + name: 'Bergen', + }) + expect(mockGraphqlFetch).toHaveBeenCalledWith( + FIND_OR_CREATE_CITY, + { + input: { + name: place.name, + displayName: place.displayName, + 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..cf36075 100644 --- a/apps/frontend/src/components/forms/CitySearchInput.tsx +++ b/apps/frontend/src/components/forms/CitySearchInput.tsx @@ -1,24 +1,72 @@ -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 DEBOUNCE_MS = 1000 +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; 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, label = 'City', + createCityToken, }: CitySearchInputProps) { const inputId = useId() const listId = useId() @@ -27,6 +75,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 +92,15 @@ export function CitySearchInput({ } else { setTerm('') } + setCityError(null) }, [value]) - const { data, isFetching, isError } = useQuery({ + const { + data: dbData, + isFetching: isDbFetching, + isError: isDbError, + isPlaceholderData: isDbPlaceholderData, + } = useQuery({ queryKey: ['citySearch', debouncedTerm], queryFn: () => graphqlFetch<{ city: City[] }>(CITY_SEARCH, { name: debouncedTerm }), @@ -52,11 +109,78 @@ export function CitySearchInput({ retry: 1, }) - const cities = data?.city ?? [] + const dbCities = isDbPlaceholderData ? [] : (dbData?.city ?? []) const waitingForDebounce = term.trim() !== debouncedTerm - const activeCity = - activeIndex >= 0 && activeIndex < cities.length - ? cities[activeIndex] + + // 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 + + 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, + displayName: place.displayName, + lat: place.lat, + lon: place.lon, + }, + }, + createCityToken, + ), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: ['search'] }) + }, + }) + + const places = shouldSearchPlaces ? (placesData?.cityPlaceSearch ?? []) : [] + const newPlaces = places.filter((place) => !isKnownCity(place, dbCities)) + const searchingPlaces = + shouldSearchPlaces && (isPlacesFetching || isPlacesPending) + const isSearching = waitingForDebounce || isDbFetching || searchingPlaces + + const suggestions: CitySuggestion[] = [ + ...dbCities.map((city) => ({ + key: city.id, + name: city.name, + displayName: city.displayName, + city, + })), + ...newPlaces.map((place, index) => ({ + key: `place-${index}-${place.lat}-${place.lon}`, + name: place.name, + displayName: place.displayName, + place, + })), + ] + + const hasSuggestions = suggestions.length > 0 + const searchFailed = + !hasSuggestions && (isDbError || (shouldSearchPlaces && isPlacesError)) + + const activeSuggestion = + activeIndex >= 0 && activeIndex < suggestions.length + ? suggestions[activeIndex] : undefined function select(city: City) { @@ -64,19 +188,52 @@ 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) { - event.preventDefault() - select(activeCity) + } 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) @@ -88,13 +245,21 @@ export function CitySearchInput({
{label}
- {value.name} + + {value.name} + {value.displayName && value.displayName !== value.name && ( + + {value.displayName} + + )} + ))} )}
+ + {cityError && ( +

+ {cityError} +

+ )} ) } diff --git a/apps/frontend/src/graphql/cities.ts b/apps/frontend/src/graphql/cities.ts index 1c8194e..08418ec 100644 --- a/apps/frontend/src/graphql/cities.ts +++ b/apps/frontend/src/graphql/cities.ts @@ -3,6 +3,31 @@ export const CITY_SEARCH = ` city(name: $name) { id name + displayName + lat + lon + } + } +` + +/** Nominatim-backed search used alongside the database results. */ +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 + displayName lat lon } 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/apps/frontend/src/types/city.ts b/apps/frontend/src/types/city.ts index 61ed1d6..e6cb42c 100644 --- a/apps/frontend/src/types/city.ts +++ b/apps/frontend/src/types/city.ts @@ -1,6 +1,14 @@ export interface City { id: string name: string + displayName?: string | null + lat: number + lon: number +} + +export interface CityPlace { + name: string + displayName: string lat: number lon: number } diff --git a/docs/work-summary.md b/docs/work-summary.md new file mode 100644 index 0000000..7e6a789 --- /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. 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[] 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,