From 42c8d4b19c6d8fbd4e7289b56956c0f331a3fdc9 Mon Sep 17 00:00:00 2001 From: Kristian Date: Fri, 27 Nov 2026 14:25:59 +0100 Subject: [PATCH 1/5] fix mock location notice --- apps/frontend/src/components/MockLocationNotice.tsx | 2 +- apps/frontend/src/styles.css | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/frontend/src/components/MockLocationNotice.tsx b/apps/frontend/src/components/MockLocationNotice.tsx index 7075873..771ee87 100644 --- a/apps/frontend/src/components/MockLocationNotice.tsx +++ b/apps/frontend/src/components/MockLocationNotice.tsx @@ -31,7 +31,7 @@ export default function MockLocationNotice() { href={'https://gspotter.graesberg.com'} target="_blank" rel="norefferer" - > + >{' '} public Azure deployment {' '} and run the website on localhost. diff --git a/apps/frontend/src/styles.css b/apps/frontend/src/styles.css index 8cf19f1..d8786d4 100644 --- a/apps/frontend/src/styles.css +++ b/apps/frontend/src/styles.css @@ -340,7 +340,8 @@ pre code { .demo-alert { border: 1px solid rgba(193, 126, 42, 0.3); border-radius: 1rem; - background: rgba(193, 126, 42, 0.1); + /* background: rgba(193, 126, 42, 0.8); */ + background: rgba(193, 126, 42, 0.9); color: var(--sea-ink); padding: 1rem; } @@ -349,7 +350,7 @@ pre code { mock position. The flag is set by an inline script before the first paint, so the notice never appears late and shifts the page. */ .mock-location-notice { - display: none; + display: block; } html[data-mock-location] .mock-location-notice { From 19499aa5be9c6405864b7aee6f02e3e39c581ea1 Mon Sep 17 00:00:00 2001 From: Kristian Date: Fri, 27 Nov 2026 14:27:38 +0100 Subject: [PATCH 2/5] minor fix --- apps/frontend/src/styles.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/frontend/src/styles.css b/apps/frontend/src/styles.css index d8786d4..1854b15 100644 --- a/apps/frontend/src/styles.css +++ b/apps/frontend/src/styles.css @@ -350,7 +350,7 @@ pre code { mock position. The flag is set by an inline script before the first paint, so the notice never appears late and shifts the page. */ .mock-location-notice { - display: block; + display: none; } html[data-mock-location] .mock-location-notice { From c58838e989f5ea0e5ecc3c53f976507a164e3842 Mon Sep 17 00:00:00 2001 From: Kristian Date: Fri, 27 Nov 2026 14:30:06 +0100 Subject: [PATCH 3/5] format --- apps/frontend/src/components/MockLocationNotice.tsx | 3 ++- apps/frontend/src/styles.css | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/frontend/src/components/MockLocationNotice.tsx b/apps/frontend/src/components/MockLocationNotice.tsx index 771ee87..2a7253e 100644 --- a/apps/frontend/src/components/MockLocationNotice.tsx +++ b/apps/frontend/src/components/MockLocationNotice.tsx @@ -31,7 +31,8 @@ export default function MockLocationNotice() { href={'https://gspotter.graesberg.com'} target="_blank" rel="norefferer" - >{' '} + > + {' '} public Azure deployment {' '} and run the website on localhost. diff --git a/apps/frontend/src/styles.css b/apps/frontend/src/styles.css index 1854b15..e34097d 100644 --- a/apps/frontend/src/styles.css +++ b/apps/frontend/src/styles.css @@ -340,7 +340,6 @@ pre code { .demo-alert { border: 1px solid rgba(193, 126, 42, 0.3); border-radius: 1rem; - /* background: rgba(193, 126, 42, 0.8); */ background: rgba(193, 126, 42, 0.9); color: var(--sea-ink); padding: 1rem; From d31a15e252a31dc65d3612b82ca200ebf5f774b2 Mon Sep 17 00:00:00 2001 From: Kristian Date: Fri, 27 Nov 2026 15:13:18 +0100 Subject: [PATCH 4/5] techincal choices doc --- README.md | 2 + docs/initial-plan.md | 4 +- docs/updated-spec.md | 294 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 297 insertions(+), 3 deletions(-) create mode 100644 docs/updated-spec.md diff --git a/README.md b/README.md index d5831b6..2a84df6 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ Our inital spec, written for the first deliverable, and what we are basing the development on, is outlined in [./docs/inital-plan.md](./docs/initial-plan.md) +The updated specification, including what was actually implemented and the reasoning behind our technical choices, is in [./docs/updated-spec.md](./docs/updated-spec.md) + Password for admin page access is "guinness" ## Index diff --git a/docs/initial-plan.md b/docs/initial-plan.md index 372c232..202fbea 100644 --- a/docs/initial-plan.md +++ b/docs/initial-plan.md @@ -76,7 +76,7 @@ Users should be able to filter by: Results can be sorted by: - distance -- price per selected volume +- price - rating - number of ratings - name @@ -84,8 +84,6 @@ Results can be sorted by: Filtering and sorting will be performed by the backend/database rather than only on the results already loaded by the client. -For prices, we will distinguish between the **actual price** and a **normalized price**. This allows, for example, NOK 89 for 0.4 L to be compared with NOK 109 for 0.5 L by calculating the price per litre, without hiding the original price. - ## Presentation Results will primarily be presented as a list of cards for each venue. A card will display information such as: diff --git a/docs/updated-spec.md b/docs/updated-spec.md new file mode 100644 index 0000000..49dbad9 --- /dev/null +++ b/docs/updated-spec.md @@ -0,0 +1,294 @@ +# G-Spotter — Updated Specification and Technical Rationale + +**Status:** This document describes the system as implemented and supersedes [`initial-plan.md`](./initial-plan.md) as the current specification. The initial plan remains the requirements baseline we started from; Section 5 tracks explicitly what changed. + +**Last updated:** 2026-11-27 + +**Sources:** [`initial-plan.md`](./initial-plan.md), [`README.md`](../README.md), and the code referenced throughout this document. + +--- + +## 1. Purpose and reading guide + +G-Spotter is a search and comparison service for Guinness. Users find pubs by city, name or address, inspect them on a map, compare recent prices and ratings, and contribute their own price observations and reviews. Administrators maintain the venue catalogue through a dedicated UI. + +This document has three parts: + +- **Sections 2–3** specify the delivered functionality, data, API, and architecture. +- **Section 4** explains and defends the technical choices, including trade-offs and alternatives considered. +- **Sections 5–6** record deviations from the initial plan, known limitations, and prioritised follow-up work. + +--- + +## 2. Updated product specification + +### 2.1 Users and roles + +| Role | Capabilities | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| Visitor | Search venues and cities, filter results, browse the map, open venue detail pages, submit price sightings and reviews, share searches via URL. | +| Administrator | All visitor capabilities plus creating/editing/deleting venues and cities, editing opening hours and notes, deleting price sightings and reviews. | + +There are no public user accounts. Reviews carry a free-text `username`; price sightings are anonymous. Administrator access is a demo-grade shared password/JWT (see §2.5). + +### 2.2 Functional requirements (as delivered) + +| ID | Requirement | Implementation | +| ----- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| FR-01 | Find venues in a city | City autocomplete and `/$cityId/venues` with a map-first city view; cities are stored locally with country, display name and centre coordinates. | +| FR-02 | Case-insensitive combined search | `search(term, …)` matches venue name/address with `ILIKE` and city names with Prisma `mode: 'insensitive'`. Results mix cities and venues in one response. | +| FR-03 | Responsive search UX | 300 ms debounce, URL as source of truth (`q`), at most 3 visible results until Enter/search button, `keepPreviousData` while typing, cities sorted before venues in the dropdown. ([`SearchBox.tsx`](../apps/frontend/src/components/SearchBox.tsx)) | +| FR-04 | Distance | Distances are computed in PostgreSQL with an `IMMUTABLE`, `PARALLEL SAFE` SQL `haversine_distance()` function. Map viewport changes drive the requested radius; the browser geolocation position is used when available. | +| FR-05 | Filtering | Maximum distance (1/2/5/10/25 km), min/max price in NOK, serving-size checkboxes (pint, half litre, quarter litre, can, other), and minimum rating (3/3.5/4/4.5). Filters are sent to the backend and applied in the database. | +| FR-06 | Results list and map | Cards show name, address, distance, latest regular price, size, rating, review count, and opening hours. An interactive Leaflet/MapLibre map with marker clustering complements the list; the list is fully usable without the map. | +| FR-07 | Venue detail | `/$cityId/venues/$venueId` shows venue information, opening hours and notes, a single-venue map, directions link, price history and reviews. | +| FR-08 | Price observations | `PriceSighting` records price, size, optional millilitres, limitations (`TIME`, `MEMBERSHIP`), observation timestamp, and optional offer window. The current regular price is the latest sighting with no limitations; restricted prices remain visible and labelled. | +| FR-09 | Reviews | Visitors submit a username, comment and 1–5 harp rating; reviews are timestamped and shown newest first. | +| FR-10 | Pagination | Cursor-based keyset pagination; 5 venues per public page, 10 in the admin table. `IntersectionObserver` prefetches the next page as the user nears the end of the sidebar/table. `venueCount` is requested alongside pages. | +| FR-11 | Shareable state | Search term and all filters live in the URL query string and are validated on parse, so hand-edited or stale URLs cannot break the UI. Navigation uses `replace: true` to avoid history noise. ([`search-filters.ts`](../apps/frontend/src/lib/search-filters.ts)) | +| FR-12 | Administration | Admin UI supports adding/editing/deleting venues, creating cities, editing opening hours and notes, managing prices, removing reviews, and filtering the admin venue table by city. | +| FR-13 | Geocoding | Addresses are geocoded through OpenStreetMap Nominatim on venue create/update. Admin city lookup first searches the local database, then falls back to Nominatim settlements; cities within 25 km with the same name/country are reused. | +| FR-14 | Location fallback | Geolocation is requested only in secure contexts. When unavailable (notably the VM's plain-HTTP deployment), a labelled mock position at NTNU Realfagsbygget is used. Positions are cached in `localStorage` for one hour. ([`location.ts`](../apps/frontend/src/lib/location.ts)) | + +### 2.3 API specification + +GraphQL is the only application API. Queries and mutations are defined with Pothos in [`apps/backend/src/schema`](../apps/backend/src/schema). + +| Operation | Arguments | Behaviour | +| ------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `venue` | `cityId`, `lat`, `lon`, `limit`, `cursor`, `maxDistanceKm`, `minPrice`, `maxPrice`, `sizes`, `minRating` | Filtered, ordered, paginated venues. Distance ordering is used when coordinates are present, otherwise name ordering. | +| `venueCount` | Same filters, no pagination | Count of the matching set, via `COUNT(*) OVER ()` in the same SQL query shape. | +| `search` | `term!` plus all filters except pagination | Mixed venue/city results with distance, latest price, rating and opening hours. City results are suppressed when a venue filter is active. | +| `city`, `cityById` | `name` / `id` | Case-insensitive city lookup / lookup by UUID. | +| `citySearch` | `name!` | Admin-only; local cities first, Nominatim fallback for terms of at least two characters. | + +| Mutation | Access | Notes | +| ------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------ | +| `createVenue`, `updateVenue`, `deleteVenue` | Admin | Geocode on address/city changes; deletion removes related hours, notes, prices and reviews in a transaction. | +| `createCity` | Admin | Validates ISO-2 country and coordinate ranges; deduplicates nearby cities. | +| `createPriceSighting` | Public | Validates positive price/volume and consistent `TIME` limitations; `timeSighted` is server-generated. | +| `createReview` | Public | Stores the submitted username, body and integer rating. | +| `deletePriceSighting`, `deleteReview` | Admin | Return `Boolean`; unknown IDs produce `BAD_USER_INPUT`. | + +A custom `DateTime` scalar serialises ISO-8601 strings. Errors use GraphQL extensions: `BAD_USER_INPUT` for invalid/unknown input and cursors, `UNAUTHORIZED` for admin checks, and `BAD_GATEWAY` for failed geocoding. + +### 2.4 Data specification + +Schema: [`packages/db/prisma/schema.prisma`](../packages/db/prisma/schema.prisma). Migrations are the source of truth and live in [`packages/db/prisma/migrations`](../packages/db/prisma/migrations). + +| Model | Key fields | Notes | +| ------------------ | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| `Venue` | UUIDv7 id, name, address, longAddress, lat, lon, city relation | Unique on `(name, address, cityId)` to prevent duplicate entries. | +| `City` | UUIDv7 id, country, name, displayName?, centreLon, centreLat | Local city catalogue; country codes are ISO-2. | +| `OpeningHours` | days (`Day[]`), opening/closing `Timetz` | Multiple intervals per venue, e.g. lunch and evening. | +| `OpeningHoursNote` | days (`Day[]`), note | Free-text exceptions such as holidays. | +| `PriceSighting` | price, size (`GlassSize`), sizeMl?, limitation (`Limitations[]`), timeStart?, timeEnd?, timeSighted | Append-only observations; the latest unrestricted sighting per size is the "current regular price". | +| `Review` | username, body, rating, timeCreated | A venue has many reviews; average and count are aggregated in SQL. | + +Enums: `GlassSize` (`PINT`, `HALF_LITER`, `QUARTER_LITER`, `CAN`, `OTHER`), `Limitations` (`TIME`, `MEMBERSHIP`), `Day` (`MON`–`SUN`). All primary keys use database-generated UUIDv7, which gives time-sortable identifiers without client coordination. + +### 2.5 Non-functional specification + +- **Performance:** filtering, distance calculation, aggregation and counting happen in PostgreSQL; pages contain at most 5 venues; TanStack Query caches for 5 minutes and keeps previous data during filter changes; the map bundle is lazy-loaded behind AVIF posters; hashed assets are cached immutably and served with gzip/Brotli; no webfonts are bundled. +- **Accessibility:** skip link, semantic landmarks and tables, labelled form controls, a combobox/listbox search with arrow-key and Escape support, visible focus states, `role="img"` labels for ratings, `role="status"`/`role="alert"` feedback, and screen-reader text in map cluster markers. The list is the primary interface; the map is complementary. +- **Security:** admin mutations require an HS256 JWT with `role: 'admin'`; invalid tokens are ignored and treated as anonymous. The shared password and long-lived development token are documented in the README and are suitable only for a demo — this is an explicit limitation, not a production design. +- **Reliability and operations:** CI runs formatting checks, lint, typecheck, frontend component tests and backend API tests after migrating and seeding a fresh database. Deployments run `prisma migrate deploy` before restarting applications; images are tagged by commit SHA for deterministic rollback. + +--- + +## 3. System architecture + +### 3.1 Repository layout + +```text +apps/frontend/ TanStack Start (React 19 + Vite + Nitro), port 3000 +apps/backend/ Apollo Server 5 + GraphQL 16 + Pothos + Prisma, port 3001 +packages/db/ Prisma schema, migrations, seed, generated client and Pothos types +infra/cloud/ Terraform for the Azure deployment (bootstrap + prod) +.github/ CI and deployment workflows +scripts/ Local database setup and baseline helpers +``` + +The whole workspace is managed with pnpm; a single `pnpm dev` starts frontend and backend concurrently. + +### 3.2 Request flow + +1. **Browser → frontend.** TanStack Start renders routes on the server (SSR query prefetch on the city and venue pages) and hydrates in the browser. +2. **Frontend → backend.** A small `graphqlFetch` wrapper sends `POST` requests. During SSR it uses `BACKEND_URL` directly; in the browser the VM build uses the absolute backend URL and the Azure build uses the same-origin `/graphql` path, which Nitro proxies to the internal backend service. +3. **Backend → database.** Resolvers use the generated Prisma client. Filtering and sorting use `prisma.$queryRaw`, while the selected GraphQL fields are resolved through a second Prisma query generated by the Pothos Prisma plugin. + +Both targets use PostgreSQL 18: Docker or bare metal on the NTNU VM, and Neon in Azure. + +### 3.3 Venue query pipeline + +[`venue-search.ts`](../apps/backend/src/schema/venue-search.ts) is the core of the application: + +1. Build parameterized SQL predicates for term, city, distance, rating and price/size. +2. Use CTEs to select the newest unrestricted price per `(venue, size, volume)` and the average/count of reviews. +3. Order by `(distance, name, id)` or `(name, id)`, with tuple comparison against the cursor venue for stable keyset pagination. +4. Return IDs plus distance, rating, count and `total_count` from `COUNT(*) OVER ()`. +5. Re-select the requested GraphQL fields with Prisma, restore the SQL order by ID, and reduce price sightings to the current relevant ones before responding. + +This gives one authoritative filter implementation shared by `venue`, `venueCount` and `search`. + +--- + +## 4. Technical choices and justification + +### 4.1 TypeScript everywhere, one pnpm workspace + +**Choice:** All three applications are TypeScript, sharing the generated database client through a workspace package. + +**Why:** GraphQL inputs, Prisma models, route params and search-filter types stay consistent across the stack. A schema change surfaces as a compile error in `pnpm typecheck` rather than a runtime failure. pnpm's workspace linking avoids duplicated installs and keeps the three packages independently buildable. + +**Trade-off:** Two generators (Prisma client and Pothos types) must be run after schema changes. The Pothos output is checked in because its generator hangs inside Docker builds; CI would otherwise fail nondeterministically. + +### 4.2 TanStack Start + React + Vite + Nitro + +**Choice:** Full-stack React with file-based routing, SSR and Nitro output instead of a client-only SPA or a separate BFF. + +**Why:** SSR prefetches the city and venue data so the detail page does not paint a loading shell, improving LCP and giving search engines/crawlers real content. Nitro lets the same build serve static assets, SSR routes and a `/graphql` proxy, which removes CORS from the Azure deployment and lets both Container Apps scale independently. + +**Trade-off:** Nitro configuration is build-target dependent (`APP_BASE_PATH`, proxy target), and SSR requires the backend URL to be available at boot. A Nitro plugin pings the backend on startup and every four minutes in production to absorb scale-to-zero cold starts. + +### 4.3 TanStack Query + URL state, without Apollo Client on the frontend + +**Choice:** `graphqlFetch` is a thin `fetch` wrapper; TanStack Query owns server state, infinite pagination and caching; TanStack Router owns the URL. + +**Why:** The client performs a small, fixed set of queries and mutations. It needs pagination, stale-while-revalidate behaviour and `keepPreviousData`, not a normalized entity cache or subscriptions. URL-driven search/filter state is shareable, survives reloads, and works with browser navigation. React Query query keys include the validated filter variables, so changing a filter cannot leak stale results. + +**Trade-off:** There is no normalized cache; related views may refetch the same venue data. Query keys and filter variables must be kept in sync manually. This is an acceptable cost at the current dataset size and is listed as future work. + +### 4.4 Code-first GraphQL with Apollo Server and Pothos + +**Choice:** The schema is built in TypeScript with Pothos and its Prisma plugin, served by Apollo Server 5. + +**Why:** Types are derived from the Prisma schema instead of duplicated in SDL. The Prisma plugin translates GraphQL selection sets into Prisma `select`/`include`, so a card request does not load reviews when they were not requested. `WithInputPlugin` gives mutations a clean `input:` argument, and unused selections warn during development. Apollo Server is mature, has good error-extension semantics, and runs in a plain Node process on both the VM and in containers. + +**Trade-off:** The schema has no standalone SDL file, so external consumers discover it through introspection. Generators add a build step (§4.1). + +### 4.5 Prisma with migration-managed PostgreSQL + +**Choice:** Prisma for schema and typed queries; committed SQL migrations as the only way to change deployed schemas; raw SQL only where relational work demands it. + +**Why:** Prisma gives safe, typed CRUD for the majority of resolvers and works with the Pothos plugin. Migrations preserve custom SQL such as the haversine function, and `prisma migrate deploy` in CI and deployment jobs makes schema changes reproducible. UUIDv7 IDs keep inserts index-friendly and globally unique. + +**Trade-off:** `prisma db push` must never be used on deployed databases — it skips migration SQL and history. A one-time baseline script exists for databases created before migrations were adopted (documented in the README). + +### 4.6 Database-side filtering with raw SQL and a SQL distance function + +**Choice:** `findFilteredVenues` builds parameterized `$queryRaw` SQL with CTEs for latest prices and ratings; distance uses a SQL `haversine_distance()` function; counts use window functions. + +**Why:** The initial plan required filtering and sorting in the database. Prisma's query API cannot express tuple keyset comparison, `DISTINCT ON` for latest prices, or a shared computed distance expression cleanly. Doing this in SQL avoids downloading and filtering the whole catalogue on the client, keeps ordering deterministic, and guarantees that `venue`, `venueCount` and `search` agree. Parameterized `Prisma.sql` prevents injection. + +**Trade-off:** Raw SQL is coupled to table/column names and is only partly typechecked (row shapes are declared manually). The haversine expression cannot use a normal index; see §6 for indexing work. + +### 4.7 Keyset pagination instead of offsets + +**Choice:** A cursor is the last venue's UUID; the next page continues after its `(sort key, id)` tuple in PostgreSQL. + +**Why:** Offsets drift when venues are inserted or deleted between requests, which would duplicate or skip markers on the map. A unique tuple keeps pages stable. The public UI additionally expands the requested radius outward from 1 km (capped at 100 km) as the list scrolls or the map zooms out, so the first paint stays small. + +**Trade-off:** Each page lookup costs an extra Prisma query, and bad cursors must be rejected explicitly (`BAD_USER_INPUT`). + +### 4.8 Observation-based prices + +**Choice:** Prices are append-only sightings with limitations and timestamps; the "current" price is derived, not stored on the venue. + +**Why:** Prices vary by time and condition (happy hour, membership). Keeping observations preserves the evidence and lets the UI show conflicting or stale reports instead of silently overwriting them. Filtering uses only the newest _regular_ sighting per size so conditional prices never masquerade as the standard price. + +**Trade-off:** Comparing physically different serving sizes is still approximate: `sizeMl` is optional, and no price-per-litre normalisation is implemented (§5). + +### 4.9 Leaflet + MapLibre, lazy-loaded and poster-backed + +**Choice:** React Leaflet with MapLibre vector tiles, marker clustering, and a client-only dynamic import with AVIF posters. + +**Why:** The map is central to the product but expensive. Vector tiles from OpenFreeMap give readable, themeable maps; clustering prevents marker overlap in dense areas. Leaflet touches `window` at module evaluation, so it must be client-only. The poster keeps the largest contentful paint stable before map JavaScript and tiles arrive, and accessibility text is added to cluster controls. + +**Trade-off:** Two mapping libraries and a custom vector-tile layer are more moving parts than using one library, and posters need maintenance when the default view changes. + +### 4.10 Location strategy for a plain-HTTP deployment + +**Choice:** Request real geolocation only on secure origins, cache for one hour, and fall back to a clearly labelled campus position. + +**Why:** The course VM serves the site over HTTP, where browsers block the Geolocation API. Failing silently would make distance features look broken; a labelled fallback keeps the distance filter and map usable while a notice explains why. Secure deployments (localhost or HTTPS/Azure) use the real position. + +**Trade-off:** Distances on the VM deployment are relative to the fallback point unless the user runs the app locally or over HTTPS. + +### 4.11 Demo authentication and admin tooling + +**Choice:** A shared admin password unlocks a long-lived JWT; the backend verifies the `role` claim on admin mutations. Public write mutations are allowed for contributions. + +**Why:** The course deliverable needs a working admin workflow without an identity provider. Keeping all data maintenance behind one UI also makes it possible to correct bad community submissions. + +**Trade-off:** The token is in the frontend bundle and the signing secret is in the backend source — anyone can mint an admin token. This is acceptable only for the demo environment; production requires real accounts, server-side sessions and per-user authorisation (§6). + +### 4.12 Nominatim integration with local-first caching + +**Choice:** Geocode venue addresses on write and cache the resulting coordinates/long address; search the local city table before querying Nominatim. + +**Why:** Coordinates are needed for distance and map features, and geocoding on read would be slow and unreliable. Nominatim's usage policy limits requests to roughly one per second; the admin UI debounces fallback searches by one second and local matches avoid most external calls. Cached coordinates also make the app resilient when Nominatim is unavailable (`BAD_GATEWAY` is surfaced on write). + +**Trade-off:** Coordinates can become stale if an address changes; the venue update mutation re-geocodes when address or city changes, and allows an explicit `longAddress` override. + +### 4.13 Deployment: VM plus Azure, with infrastructure as code + +**Choice:** Keep the required VM deployment (Apache proxy → systemd services → local PostgreSQL) and add an Azure deployment built from Terraform: public frontend Container App, internal backend Container App, Neon PostgreSQL, Azure Container Registry, Cloudflare DNS/TLS, and OIDC-based CI. + +**Why:** The VM satisfies the course requirement; the cloud deployment demonstrates reproducible infrastructure, isolated networking, secret management via a database provider, and scale-to-zero cost savings. A migration job runs before app updates, and backend is updated before frontend so new queries never hit an old schema. Immutable commit-SHA image tags make rollback a revision activation. OIDC avoids long-lived cloud credentials in the repository. + +**Trade-off:** Student-subscription constraints forced Neon instead of Azure Database for PostgreSQL and `docker buildx` instead of ACR Tasks; the runner also needs Docker 28.x because 29.x has a known BuildKit session bug. Scale-to-zero adds cold starts, mitigated by the warm-backend plugin (§4.2). + +### 4.14 Testing strategy + +**Choice:** Vitest + Testing Library + jsdom for frontend components and utilities; Playwright API tests against a running backend and seeded database; a CI workflow that migrates, seeds, checks formatting/lint/types and runs both suites. + +**Why:** Component tests cover search debouncing, filters, forms, routing and map wrappers without a backend. API tests verify real GraphQL behaviour, including filtering and validation, against real PostgreSQL. Together they catch regressions at both boundaries while keeping the feedback loop fast. + +**Trade-off:** Backend tests require a live database and seed data, so they are slower and more stateful than pure unit tests; CI resets the database after each run. + +--- + +## 5. Changes from the initial plan + +### 5.1 Planned but not delivered + +| Initial plan | Delivered instead | Reason / consequence | +| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Sorting by distance, price per volume, rating, number of ratings, name and last updated | Distance ordering when coordinates exist; otherwise name. No sort argument or UI. | Keyset pagination was implemented for the two most useful orderings. Adding a general sort requires extending the cursor tuple to include the new sort key. | +| "Open now" filter | Opening hours and notes are stored, displayed and editable, but never used in filtering. | Opening hours include `Timetz` intervals and exception notes; correct filtering needs timezone/date handling and a decision about notes. Left out rather than implemented incorrectly. | +| Normalised price / price per litre | `sizeMl` is stored and displayed; filtering compares raw NOK for the latest regular sighting. | A useful normalisation requires reliable volume data, which is optional today. See §6. | +| "Relevant indexes" for scalability | Primary keys and the venue unique constraint only; no full-text, trigram, coordinate or timestamp indexes. | The current dataset (tens of venues) is served without them. This is the clearest gap against the plan's scalability statement. | +| Collecting basic pub data from open sources | Fabricated seed data for development/CI; admins add real venues with Nominatim geocoding. | No vetted open dataset was sourced; manual curation avoids importing unverified/opening-hour data. | +| Guinness type and "serves Guinness" flag | Implicit: presence of a venue means Guinness is listed. Glass size is modelled; variant is not. | With a single beverage focus, a boolean would always be true for stored venues. Adding variants later is a schema change. | +| Reporter attached to each price observation | Observations are anonymous; reviews use a free-text username. | No account system was built; the demo prioritised low-friction contributions. | +| Community identity / persistent user data | Anonymous persistent reviews and sightings, plus a shared admin password. | Sufficient for demonstrating community data accumulation, not for attribution or abuse prevention. | +| Backend/server-side caching | Client-side caching (TanStack Query, asset headers, local location cache). | Query results are cheap at current scale; no DataLoader or server cache was added. | + +The initial plan also suggested suppressing distance when a _specific pub_ is searched. The current flow opens the venue detail page with a single-venue map and directions link; nearby alternatives are reached through the city list/map rather than a dedicated comparison panel. + +### 5.2 Added beyond the initial plan + +- Full admin subsystem: venue/city CRUD, opening-hours editor with notes, price and review management. +- Local city catalogue with country codes, display names and centre coordinates; Nominatim geocoding and settlement fallback. +- SSR via TanStack Start/Nitro, same-origin GraphQL proxy on Azure, and a backend warm-up plugin. +- URL-shareable search and filter state with strict validation of hand-edited URLs. +- Mock-location handling with a user-visible notice on insecure origins. +- Accessibility work: skip link, combobox/listbox semantics, screen-reader cluster labels, semantic tables and focus states. +- Image/LCP optimisations (AVIF posters, no webfonts, immutable asset caching, gzip/Brotli). +- Automated CI plus two deployment targets: the NTNU VM (systemd + Apache) and Azure (Terraform, Container Apps, Neon, Cloudflare, OIDC, migration job). +- Frontend component tests and backend end-to-end API tests. + +--- + +## 6. Known limitations + +**Security (must change before any public/production use)** + +1. Replace the shared password and checked-in JWT with a real identity provider and server-side sessions. +2. Move the JWT secret to a managed secret and give the frontend no admin token. +3. Rate-limit and moderate public `createReview` / `createPriceSighting`. + +## 7. Conclusion + +The delivered application implements the core of the initial plan — searchable pub discovery, database-side filtering, distance-aware results, map and list presentation, price observations, reviews and pagination — and adds substantial admin tooling, accessibility work, automated testing and two production-grade deployment paths. The main gaps are concentrated in areas deliberately deferred: configurable sorting, price normalisation, "open now", indexing, and real user identity. Section 6 gives a concrete order in which to close them. From fcf95032737a3faf126605959742c886f23199e1 Mon Sep 17 00:00:00 2001 From: Kristian Date: Fri, 27 Nov 2026 15:36:12 +0100 Subject: [PATCH 5/5] rewritten trade-off --- docs/updated-spec.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/updated-spec.md b/docs/updated-spec.md index 49dbad9..637d087 100644 --- a/docs/updated-spec.md +++ b/docs/updated-spec.md @@ -173,7 +173,7 @@ This gives one authoritative filter implementation shared by `venue`, `venueCoun **Why:** Prisma gives safe, typed CRUD for the majority of resolvers and works with the Pothos plugin. Migrations preserve custom SQL such as the haversine function, and `prisma migrate deploy` in CI and deployment jobs makes schema changes reproducible. UUIDv7 IDs keep inserts index-friendly and globally unique. -**Trade-off:** `prisma db push` must never be used on deployed databases — it skips migration SQL and history. A one-time baseline script exists for databases created before migrations were adopted (documented in the README). +**Trade-off:** Using prisma adds a tiny bit of overhead to the application, but this is negligible due to upsides such as effort spared and overall efficiency from not having to deal with SQL directly. ### 4.6 Database-side filtering with raw SQL and a SQL distance function