diff --git a/README.md b/README.md index ba86c53..3c56ef0 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Kork & Krone -**Last updated:** 12 November 2026 -**Submission:** 3 (first complete prototype, beta) -**Status:** In progress. See [Status for submission 3](#status-for-submission-3). +**Last updated:** 16 November 2026 +**Submission:** 4 (working system, ready for feedback on every aspect) +**Status:** In progress. See [Status for submission 4](#status-for-submission-4). +| Continuous integration (CI) | Not yet started | Needs a self-hosted runner | ### What we want feedback on -Although the project is currently a bit behind schedule, we would still like relevant feedback on what is implemented and planned. - -Some suggested options are design and accessibility of the website, API design found in docs/api.md, architectural and technological choices, implemented and planned features and sustainability. +We would like feedback on anything, but these are the parts we are least sure about: +- The landing page: is it too much at once, and is the order of the sections right? +- Student reviews: half stars with the mouse and the keyboard, and whether the distribution is understandable. +- Accessibility, especially with a screen reader, which we have not tested with ourselves. +- Architectural and technological choices, and the API design in docs/api.md. ## Get started @@ -105,12 +106,12 @@ This section describes what users can do. "Backend" means the API supports the f | Sorting | Done | Done | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page | | Pagination | Done | Done | Pages behind an opaque cursor that holds an offset. The user loads more results with a button, not with infinite scroll. Focus moves to the first new wine | | Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&vurdering=&alkohol=&sort=`. Survives reloads. Typing replaces the history entry, so the back button leaves the search instead of stepping through every word | -| Wine detail page | Done (`wine(id)`) | Done | Name, winery, region, grapes, alcohol, body, acidity, vintages and food pairing in Norwegian. Grapes and food link to the search. | +| Wine detail page | Done (`wine(id)`) | Done | Name, winery, region, grapes, alcohol, body, acidity, vintages and food pairing in Norwegian. Grapes and food link to the search | | Student reviews | Done | Done | 0.5–5 stars in half stars and an optional comment, stored in PostgreSQL. Hover the left half of a star for half a star, or use the arrow keys. The page updates at once without a reload. One review per student per wine | | Shared average and distribution | Done | Done | Student reviews count in the average together with X-Wines, also when sorting and filtering. The wine page shows how many gave each score | -| Wishlist ("Vil prøve") | Planned | Done, stored in the browser | Moves to the backend when users and reviews are in place | -| User | Done (Anonymous ID) | Done | An anonymous ID stored in browser until we have login (#29) | - +| Wishlist ("Vil prøve") | Planned | Done | Saved in the browser and shown on «Mine anmeldelser». Moves to the backend when login is in the interface | +| User accounts | Done | Planned | Register, login, logout and `me` in the API. Sessions in PostgreSQL with an `httpOnly` cookie. The interface comes next | +| Anonymous ID | Done | Done | Reviews use a random ID stored in the browser until login is in the interface | ## Architecture and technology choices @@ -137,18 +138,17 @@ Each row explains what we chose, why, and what else we considered. Added as the | Styling | CSS Modules and design tokens in `styles/tokens.css` | No runtime cost and no extra dependency. Tokens make dark mode and consistent colours easy | Tailwind, styled-components | | API | GraphQL with Apollo Server on Express | Required by the course. The client asks only for the fields it shows, which saves data | REST | | Database | PostgreSQL with the `pg_trgm` extension | Fast text search with `ILIKE` also on many rows. Already available on the VM | MongoDB, SQLite | +| Database changes | Migrations with node-pg-migrate | Everyone and the VM get the same database by running one command, without deleting and rebuilding it | Editing a single schema file by hand | | Pagination | GraphQL connection with an opaque cursor that holds an offset. Pages are merged in the Apollo cache | Simple, and works with every sort order. The frontend never reads the cursor, so we can switch to keyset pagination later without changing it | Keyset pagination: faster deep into large results, but harder to combine with many sort orders | | Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser | +| Rating average | Stored on the wine and recalculated when a review is saved or deleted | Sorting and filtering by rating never has to count millions of rows | Calculating the average for every query | +| Batched lookups | DataLoader for reviews and ratings per wine | A page of wines runs one query per field instead of one per wine (the N+1 problem) | One query per wine | | Search state flow | Field text in React state, debounced into the URL, and the query reads only the URL | One source of truth for the search, so reload, shared links and the back button all give the same result | Sending a request directly from the input | | Filter panel on small screens | Native `` with `showModal()` | The browser handles focus trapping, Escape and returning focus, with no extra JavaScript | A dialog library | | Filter counts | One count query per group that leaves out the group's own filter | The user can see what each choice gives before choosing, and values can be combined | Fixed counts for the whole catalogue | | Testing | Vitest, React Testing Library, Playwright, axe | Vitest shares configuration with Vite. Playwright tests real browsers, also on mobile | Jest, Cypress | | Deployment | Apache serves static files, the backend runs with `nohup` | Matches the course VM | systemd service (possible improvement) | - - See [API](docs/api.md) for the schema and example queries. ## Data @@ -187,8 +187,9 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing, - Semantic HTML: landmarks (`header`, `nav`, `main`, `footer`), one `h1` per page, lists for groups of cards, and `
` for each wine card. We try to use `div` and `span` only for layout. See [conventions](#code-quality-and-conventions). - A skip link to the main content, and visible focus on all interactive elements. - After navigation, focus moves to the page's `h1`. Screen reader users then hear that the page has changed. -- Ratings are always shown as text, for example "4,6 av 5 · 23 dommer". The die has a text alternative for screen readers. -- Loading states are announced in a live region. Errors use `role="alert"` and have a "Prøv igjen" button. +- Ratings are always shown as text, for example "4,6 av 5 · 23 dommer". The stars have a text alternative, so a screen reader reads «3,5 av 5 stjerner» instead of five images. +- Giving a review works with the keyboard: the stars are radio buttons, so the arrow keys move through every half star, and each half is at least 24 × 24 px to click (WCAG 2.5.8). +- Loading states are announced in a live region. Errors use `role="alert"` and have a "Prøv igjen" button. The message after saving a review stays in the same live region, so it is announced. - Click targets are at least 44 × 44 px. - Animations respect `prefers-reduced-motion`. - No horizontal scrolling at 320 px width (WCAG 1.4.10, reflow). @@ -202,8 +203,6 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing, - An automated test for reflow at 320 px. - Manual testing with only the keyboard. - - ### Some known gaps - We have not tested with a screen reader yet. @@ -225,6 +224,8 @@ We follow the principle from the course: measure, set a budget and show the numb - Code splitting per page with `React.lazy`. The landing page does not load the code for search and the detail page. - The landing page loads all its data in one GraphQL query, with only the fields it shows. An end-to-end test checks that only one request is sent. - Search, filtering, sorting and pagination run in the database. A page returns at most 50 wines. +- The rating average is stored on the wine, so no query counts millions of rows. +- DataLoader batches the lookups a page needs, so a page of wines runs one query per field instead of one per wine. - The Apollo cache, so we do not fetch the same data twice. - Debounce on the search field (300 ms). An end-to-end test checks that a whole word sends only one search. - Apache compresses HTML, CSS and JavaScript with gzip. The main JavaScript file goes from 435 kB to 136 kB. @@ -250,12 +251,12 @@ and because the test was run over VPN. These are the "before" numbers. Compressi | Level | Tools | What we test | Number of tests | |---|---|---|---| -| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, loading, empty and error states, and axe on each component | 233 | -| Unit (backend) | Vitest | Parsing of X-Wines CSV files, and building SQL for search, filtering and sorting | 2 test files | +| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, the wine page with reviews, the wishlist page, loading, empty and error states, and axe on each component | 269 in 28 files | +| Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting, review validation, and passwords, sessions and rate limiting | 92 in 11 files (6 skipped: they need a test database) | | End-to-end | Playwright with axe-core, desktop and mobile | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, filters, sorting, load more, reload, back button, from search to wine and back, the filter dialog on mobile, no hits, wine not found, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 50 (24 tests in 2 browser projects, and 2 for mobile only) | | API | Not set up yet | Resolvers against a test database: search, filtering, sorting and pagination | Planned | -Counted on 7 November 2026. +Counted on 16 November 2026. The skipped backend tests run the user store against a real database, and need `TEST_DATABASE_URL`. **Coverage (frontend, 7 November 2026):** lines 98.93 %, branches 85.3 %, functions 97.14 %, statements 90.97 %. @@ -302,14 +303,16 @@ If git.ntnu.no has no CI runners, write that, and describe the alternative (for frontend/src/ app/ routes and the app shell components/ shared components (layout/ and ui/) - features/ one folder per feature: landing/, search/, ... + features/ one folder per feature: landing/, search/, wine/, my/ hooks/ shared React hooks lib/ pure functions and types styles/ design tokens and global CSS backend/src/ schema.ts GraphQL schema resolvers.ts GraphQL resolvers + loaders.ts DataLoader batching wine-query.ts builds the SQL for search, filtering and sorting + auth/ user accounts, passwords and sessions scripts/ import of X-Wines backend/migrations/ database migrations (node-pg-migrate) ``` @@ -325,11 +328,6 @@ backend/migrations/ database migrations (node-pg-migrate) - We always try to use the semantic element that exists for the purpose: `button`, `a`, `label`, `fieldset`, `ul`, `article`, `time` and so on. - `div` and `span` are only used for layout. If we use them where a semantic element could fit, a code comment should explain why. - - ## Use of AI We use AI tools as a sparring partner and as a code assistant. AI-generated code goes through the same review as other code, and we run and test it before it is merged. @@ -341,43 +339,41 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a - Help with proper documentation - Help with keeping us in line with project guidelines - ## Plan ahead -### Next: complete the beta - -1. [x] Add Apollo Client to the frontend, with the endpoint `${import.meta.env.BASE_URL}graphql`. -2. [x] Search page: search field with debounce, list of results, number of hits, "Last inn flere", and empty and error states. -3. [x] Filter panel with counts from `filterOptions`, and sorting. All choices stored in the URL. -4. [x] Connect the landing page to the backend. -5. [x] Wine detail page. -6. [x] Start the backend on the VM and load the dataset. +### Next: towards the final submission -### Then: towards the next submission - -- [x] Student reviews: GraphQL mutation, database table, validation, and the new rating shown at once. -- [ ] Wishlist stored in the backend. -- [x] Larger dataset on the VM. -- [ ] Load test with the Full dataset. +- [ ] Login in the interface: forms for register and login, and reviews tied to the account instead of the anonymous ID. +- [ ] Wishlist stored in the backend, so it follows the user between devices. +- [ ] Calmer landing page: less text, a separate «Om» page, and a burger menu on mobile. - [ ] CI, an enforced coverage threshold, and eslint-plugin-jsx-a11y. - [ ] Measure sustainability and fill in the budget table. - [ ] Screen reader test and a written reflection on the use of AI. +- [ ] Prettier and ESLint in the backend, like in the frontend. + +### Done + +- [x] Search, filtering, sorting and pagination in the database, with the whole result set. +- [x] Wine detail page. +- [x] Student reviews: GraphQL mutation, database tables, validation, and the new rating shown at once. +- [x] Half stars, a shared average and the rating distribution. +- [x] «Mine anmeldelser» with the wishlist. +- [x] User accounts in the backend. +- [x] Database migrations. +- [x] Larger dataset on the VM. ### Some known issues -- Some documents in `docs/` still describe the old Vinmonopolet plan and the old test endpoint `/api/hello`. They will be updated. - Search matches the text as one phrase, so "noir pinot" finds nothing. Country is not part of the search text, because the country filter covers it. -- The cursors in the API hold an offset, which is slower deep into large results. To be solved together with the larger dataset. - - +- The cursors in the API hold an offset, which is slower deep into large results. +- The database and its user are still called `vinmonopolet` and `vinmonopolet_app`, from before we switched dataset. Renaming would mean everyone rebuilding their database, so we kept the names. +- Anyone can create any number of anonymous IDs, so there is nothing stopping someone from leaving many reviews. Login will fix that. ## Further documentation - [Setup](docs/setup.md): Git, dependencies, `.env` and local start - [Database](docs/database.md): PostgreSQL on macOS, Windows and Ubuntu - [VM](docs/vm.md): deployment, Apache and running the backend with `nohup` -- [API](docs/api.md): GraphQL queries, test data and the X-Wines citation +- [API](docs/api.md): GraphQL queries, user accounts and the X-Wines citation - [Workflow](docs/workflow.md): branches, reviews and checks - [Tasks](docs/tasks.md): requirements and sketches \ No newline at end of file diff --git a/backend/src/scripts/wine-stats.st b/backend/src/scripts/wine-stats.st new file mode 100644 index 0000000..f60d7f1 --- /dev/null +++ b/backend/src/scripts/wine-stats.st @@ -0,0 +1,112 @@ +// Prints a summary of what is in the catalog. Handy for checking an import. +// Usage: tsx src/scripts/wine-stats.ts +import { pool } from '../db'; + +interface Totals { + wines: number; + ratings: number; + countries: number; + wineries: number; + grapes: number; + regions: number; + average: number; + database_size: string; +} + +const TOTALS = ` + SELECT + (SELECT count(*) FROM wine) AS wines, + (SELECT count(*) FROM community_rating) AS ratings, + (SELECT count(DISTINCT country) FROM wine) AS countries, + (SELECT count(DISTINCT winery_name) FROM wine) AS wineries, + (SELECT count(DISTINCT region_name) FROM wine) AS regions, + (SELECT count(DISTINCT grape) FROM wine, unnest(grapes) AS grape) AS grapes, + (SELECT round(avg(rating), 2) FROM community_rating) AS average, + pg_size_pretty(pg_database_size(current_database())) AS database_size +`; + +const BY_TYPE = ` + SELECT type, count(*) AS wines, round(avg(community_avg), 2) AS average + FROM wine + WHERE community_avg IS NOT NULL + GROUP BY type + ORDER BY wines DESC +`; + +const TOP_COUNTRIES = ` + SELECT country, count(*) AS wines, round(avg(community_avg), 2) AS average + FROM wine + WHERE country IS NOT NULL AND community_avg IS NOT NULL + GROUP BY country + ORDER BY wines DESC + LIMIT 10 +`; + +const TOP_GRAPES = ` + SELECT grape, count(*) AS wines + FROM wine, unnest(grapes) AS grape + GROUP BY grape + ORDER BY wines DESC + LIMIT 10 +`; + +/** The best rated wines that enough people have rated for the average to mean something. */ +const BEST_RATED = ` + SELECT name, winery_name, country, community_avg AS average, community_count AS ratings + FROM wine + WHERE community_count >= 100 + ORDER BY community_avg DESC, community_count DESC + LIMIT 10 +`; + +const RATINGS_PER_YEAR = ` + SELECT extract(year FROM rated_at)::int AS year, count(*) AS ratings + FROM community_rating + GROUP BY year + ORDER BY year +`; + +function heading(text: string): void { + console.log(`\n${text}`); + console.log('-'.repeat(text.length)); +} + +async function rows(sql: string): Promise { + return (await pool.query(sql)).rows; +} + +async function main(): Promise { + const [totals] = await rows(TOTALS); + + heading('Catalog'); + console.log(`Wines: ${Number(totals.wines).toLocaleString('en')}`); + console.log(`Ratings: ${Number(totals.ratings).toLocaleString('en')}`); + console.log(`Countries: ${totals.countries}`); + console.log(`Regions: ${Number(totals.regions).toLocaleString('en')}`); + console.log(`Wineries: ${Number(totals.wineries).toLocaleString('en')}`); + console.log(`Grapes: ${totals.grapes}`); + console.log(`Average: ${totals.average} of 5`); + console.log(`Database: ${totals.database_size}`); + + heading('Wines by type'); + console.table(await rows(BY_TYPE)); + + heading('Countries with most wines'); + console.table(await rows(TOP_COUNTRIES)); + + heading('Most common grapes'); + console.table(await rows(TOP_GRAPES)); + + heading('Best rated wines (at least 100 ratings)'); + console.table(await rows(BEST_RATED)); + + heading('Ratings per year'); + console.table(await rows(RATINGS_PER_YEAR)); +} + +main() + .catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + }) + .finally(() => pool.end()); \ No newline at end of file diff --git a/docs/api.md b/docs/api.md index ea7052c..e474282 100644 --- a/docs/api.md +++ b/docs/api.md @@ -57,7 +57,8 @@ During development, Vite forwards `/graphql` to the backend. On the VM, Apache f ## Student reviews A review is 0.5 to 5 in half stars and an optional comment (max 500 characters). -There is no login yet, so the frontend creates a random UUID once (`crypto.randomUUID()`, or random bytes on plain HTTP, where `randomUUID` does not exist), +The frontend has no login yet (the backend part is described under «Users and login» below), +so it creates a random UUID once (`crypto.randomUUID()`, or random bytes on plain HTTP, where `randomUUID` does not exist), stores it in localStorage and sends it as `userId`. Treat it like a password: the API never returns it, reviews are shown with a display name such as "Student #12". Every student gets their own number the first time they save a review, so two students never share a name. diff --git a/docs/setup.md b/docs/setup.md index d760dc8..1dd316d 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -90,7 +90,7 @@ Open the frontend at [localhost:5173](http://localhost:5173/). Open [localhost:3001](http://localhost:3001/) to check the backend's database connection. Open [localhost:3001/graphql](http://localhost:3001/graphql) to try GraphQL queries. It shows the database name, user, and server time. A failed query returns HTTP 503. -The frontend requests `/api/hello`. Vite forwards that request to the backend's `/` endpoint during local development. +The frontend requests `/graphql`. Vite forwards that request to the backend during local development. To update an existing checkout, stop the development servers and run these commands from the project folder: diff --git a/docs/tasks.md b/docs/tasks.md index b476b2a..6c8798c 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -1,7 +1,6 @@ # Tasks -Kork & Krone lets students search wines, compare their own die rolls with what the wine community thinks, -and keep a list of wines they want to try. +Kork & Krone lets students search wines, compare their own star ratings with what the wine community thinks,and keep a list of wines they want to try. The catalog comes from the [X-Wines](https://github.com/rogerioxavier/X-Wines) dataset, imported into our own PostgreSQL database. The frontend reads it through our GraphQL backend. diff --git a/docs/vm.md b/docs/vm.md index b1e455d..87938ac 100644 --- a/docs/vm.md +++ b/docs/vm.md @@ -175,41 +175,51 @@ For a foreground backend started with `npm start`, press **Ctrl+C** in its termi `nohup` does not restart the backend after a crash or VM reboot. Start it again with the commands above. Use systemd if automatic restarts are needed. -## Apache backend proxy +## Apache configuration + +Apache serves the built frontend and forwards GraphQL requests to the backend. +The frontend asks for `/project2/graphql`, and Apache passes that on to the backend on port 3001. + +`FallbackResource` makes deep links such as `/project2/sok` work on reload: the files do not +exist on disk, so Apache serves `index.html` and React Router takes over. -For the database greeting backend, the frontend requests `/api/hello`. -Apache must forward that request to the backend's `/` endpoint. -Vite's development proxy does not run in a production build. Configure this once, after starting the backend: ```bash -sudo a2enmod proxy proxy_http sudo nano /etc/apache2/conf-available/project2.conf ``` -Add these directives to the file: +The file should contain: ```apache -ProxyPass "/api/hello" "http://127.0.0.1:3001/" -ProxyPassReverse "/api/hello" "http://127.0.0.1:3001/" +ProxyPass "/project2/graphql" "http://127.0.0.1:3001/graphql" +ProxyPassReverse "/project2/graphql" "http://127.0.0.1:3001/graphql" + + + FallbackResource /project2/index.html + ``` Enable the configuration and check its syntax: ```bash +sudo a2enmod proxy proxy_http sudo a2enconf project2 sudo apache2ctl configtest ``` -If the check reports `Syntax OK`, reload Apache: +If the check reports `Syntax OK`, reload Apache and try a query: ```bash sudo systemctl reload apache2 -curl -i http://localhost/api/hello +curl -s -X POST http://localhost/project2/graphql -H 'Content-Type: application/json' -d '{"query":"{ wines(first: 1) { totalCount } }"}' ``` -Expect the same database response as the direct backend request. -If the backend later uses GraphQL, update this mapping to match its endpoint and frontend requests. +Expect a number of wines back. A `503` means Apache is running but cannot reach the backend, +so check that the backend process is still up. + +The file on the VM also has an older `ProxyPass "/api/hello"` from the first submission. +It does nothing now and can be removed the next time the configuration is touched. See Apache's [reverse proxy documentation](https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#examples). ProxyPass "/project2/graphql" "http://127.0.0.1:3001/graphql" ProxyPassReverse "/project2/graphql" "http://127.0.0.1:3001/graphql" diff --git a/frontend/src/features/wine/components/StudentReviews.module.css b/frontend/src/features/wine/components/StudentReviews.module.css index caa9a69..8e82274 100644 --- a/frontend/src/features/wine/components/StudentReviews.module.css +++ b/frontend/src/features/wine/components/StudentReviews.module.css @@ -71,4 +71,4 @@ .message { font-weight: 600; order: 1; -} \ No newline at end of file +}