Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 34 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Kork & Krone

**Last updated:** 30 October 2026
**Last updated:** 7 November 2026
**Submission:** 3 (first complete prototype, beta)
**Status:** In progress. See [Status for submission 3](#status-for-submission-3).

Expand Down Expand Up @@ -42,15 +42,15 @@ Submission 3 should be the first complete prototype, with search, browsing, sort

| Area | Status | Note |
|---|---|---|
| Landing page | Done | Uses mock data. Not connected to the backend yet |
| Landing page | Done | Shows real data from the API. Reviews are hidden until the API supports them |
| GraphQL API: search, filter, sort, pagination | Done | Queries `wines`, `wine` and `filterOptions` |
| Database schema and X-Wines Test import | Done | 100 wines and 1 000 ratings |
| Frontend deployed on the VM | Done | Deep links such as `/project2/sok` work on reload |
| Backend running on the VM | Currently not running | `/project2/graphql` returns 503 |
| Apollo Client in the frontend | Next | |
| Search page with results | Next | Placeholder page at `/sok` |
| Filtering and sorting in the user interface | Planned | Already supported by the API |
| Wine detail page | Planned | Placeholder page at `/vin/:id` |
| Backend running on the VM | Done | Started with `nohup`, see [VM guide](docs/vm.md) |
| Apollo Client in the frontend | Done | |
| Search page with results | Done | Search with debounce, number of hits and "Last inn flere" at `/sok` |
| Filtering and sorting in the user interface | Done | Filter panel, active filters and sorting on `/sok`. Needs the new backend on the VM |
| Wine detail page | Done | Facts, food pairing and rating at `/vin/:id`. Student reviews are added with the reviews feature |
| Student reviews (stored in the database) | Planned | |
| Larger dataset on the VM | Planned | |
| Continuous integration (CI) | Not yet started | |
Expand Down Expand Up @@ -88,7 +88,7 @@ cd backend && npm run dev # http://localhost:3001/graphql
cd frontend && npm run dev # http://localhost:5173/project2/
```

The frontend can run without the backend for now, because the landing page uses mock data.
The landing page needs the backend for wines and categories. Without it, the page shows an error message with a "Prøv igjen" button.

To deploy on the VM, see the [VM guide](docs/vm.md).

Expand All @@ -98,12 +98,12 @@ This section describes what users can do. "Backend" means the API supports the f

| Feature | Backend | UI | Description |
|---|---|---|---|
| Search | Done | Planned | Ignores case and accents. Matches name, winery, region and grapes |
| Filtering | Done | Planned | Type, country, grapes, food pairing, minimum rating and alcohol range. Shows the number of wines for each option |
| Sorting | Done | Planned | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page |
| Pagination | Done | Planned | Cursor-based. The user loads more results with a button, not with infinite scroll |
| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&sort=`. Survives reloads and works with the back button |
| Wine detail page | Done (`wine(id)`) | Planned | Name, winery, region, grapes, alcohol, food pairing, both ratings, and the latest student reviews |
| Search | Done | Done | Ignores case and accents. Matches name, winery, region and grapes as one phrase. Waits 300 ms after the last key press |
| Filtering | Done | Done | Type, country, grapes, food pairing, minimum rating and alcohol range. Several values can be selected. The counts follow the search and the other filters. On small screens the filters open in a dialog |
| Sorting | Done | Done | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page |
| Pagination | Done | Done | Cursor-based. 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. Student reviews are planned |
| Student reviews | Planned | Planned | Die roll from 1 to 6 and an optional comment, stored in PostgreSQL, the new rating is shown at once without a reload (Apollo cache update) |
| Wishlist ("Vil prøve") | Planned | Done, stored in the browser | Moves to the backend when users and reviews are in place |
| User | Planned | Planned | Login or anonymous ID stored in browser |
Expand All @@ -130,12 +130,15 @@ Each row explains what we chose, why, and what else we considered. Added as the
|---|---|---|---|
| Frontend | React 19, TypeScript, Vite | Required by the course. Vite gives fast builds and splits code per page | – |
| Routing | React Router | Search state lives in the URL, so it can be shared and survives reloads | Keeping state only in React |
| State management | Apollo Client cache (planned) and URL parameters | Server data is kept in the Apollo cache. User choices are kept in the URL. Nothing is left that needs a global store | Redux, Zustand |
| State management | Apollo Client cache and URL parameters | Server data is kept in the Apollo cache. User choices are kept in the URL. Nothing is left that needs a global store | Redux, Zustand |
| 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 |
| Pagination | Cursor-based | Stable when sorting. No duplicates or gaps when new data is added | Offset-based |
| Pagination | Cursor-based, pages merged in the Apollo cache | Stable when sorting. No duplicates or gaps when new data is added | Offset-based |
| Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser |
| 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 `<dialog>` 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) |

Expand Down Expand Up @@ -197,10 +200,8 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing,

### Some known gaps

- The search page, filters and detail page are not built yet, so they are not tested.
- We have not tested with a screen reader yet.
- eslint-plugin-jsx-a11y is not set up yet.
- The filter panel on mobile will need a dialog with correct focus handling. This is planned.

## Sustainability

Expand All @@ -216,19 +217,19 @@ We follow the principle from the course: measure, set a budget and show the numb
### Technical choices

- Code splitting per page with `React.lazy`. The landing page does not load the code for search and the detail page.
- The landing page is designed to load all its data in one GraphQL query, with only the fields it shows.
- 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 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.

**Planned:**
- Debounce on the search field (about 300 ms), so we do not send a request for every key press.
- The Apollo cache, so we do not fetch the same data twice.
- Compression (gzip or Brotli) and cache headers in Apache.

### Budget and measurements

| Metric | Budget | Measured | Date | How we measure |
|---|---|---|---|---|
| JavaScript on the landing page (gzip) | Less than 150 kB | 93,43 kB | 30 Oct 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
| JavaScript on the landing page (gzip) | Less than 150 kB | 155,05 kB (over budget after adding Apollo Client) | 7 Nov 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
| Data transferred when loading the landing page | Less than 300 kB | Not measured yet | | Chrome DevTools, Network tab, cache disabled, on the VM |
| Data transferred in a fixed search scenario | Less than 500 kB | Not measured yet | | Same method. Needs the search page |
| Lighthouse (mobile) | Performance at least 90, accessibility 100 | Performance 39, accessibility 100, best practices 100, SEO 100 | 30 Oct 2026 | Lighthouse in Chrome DevTools, incognito, against the VM |
Expand All @@ -242,18 +243,16 @@ and because the test was run over VPN. These are the "before" numbers. We will m

| Level | Tools | What we test | Number of tests |
|---|---|---|---|
| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, data hooks, components, the landing page, loading, empty and error states, and axe on each component | 53 |
| 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 |
| End-to-end | Playwright with axe-core, desktop and mobile | Search from the landing page, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 10 (5 tests in 2 browser projects) |
| 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 30 October 2026.
Counted on 7 November 2026.

**Coverage (frontend, 30 October 2026):** lines 84.78 %, branches 60.16 %, functions 80.82 %, statements 71.05 %.
**Coverage (frontend, 7 November 2026):** lines 98.93 %, branches 85.3 %, functions 97.14 %, statements 90.97 %.

Vitest enforces a minimum of 80 % for lines, functions and statements and 75 % for branches (`vitest.config.ts`).
The coverage run currently fails these limits. The main reasons are hooks without their own tests
(for example `useWishlist`) and placeholder pages for search and wine details that will be replaced.
We will add the missing tests before raising the limits further, and we do not lower the limits to make the run pass.

We leave out `main.tsx`, test files, test helpers and mock data, because they contain no application logic.
Expand Down Expand Up @@ -339,11 +338,11 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a

### Next: complete the beta

1. [ ] Add Apollo Client to the frontend, with the endpoint `${import.meta.env.BASE_URL}graphql`.
2. [ ] Search page: search field with debounce, list of results, number of hits, "Last inn flere", and empty and error states.
3. [ ] Filter panel with counts from `filterOptions`, and sorting. All choices stored in the URL.
4. [ ] Connect the landing page to the backend.
5. [ ] Wine detail page.
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. [ ] Start the backend on the VM and load the dataset.

### Then: towards the next submission
Expand All @@ -357,10 +356,9 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a

### Some known issues

- The backend is not running on the VM, so `/project2/graphql` returns 503.
- The landing page uses mock data. Its query (`LANDING_QUERY`) asks for a `landing` field that the backend does not have yet. The group must decide whether to add that field or build the landing page from the existing queries.
- Some documents in `docs/` still describe the old Vinmonopolet plan and the old test endpoint `/api/hello`. They will be updated.
- Frontend test coverage is below our enforced limits (statements 71.05 %, branches 60.16 %). Tests for `useWishlist` and the remaining components are planned.
- 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.

<!--
Remove known issues as they are fixed.
Expand Down
35 changes: 25 additions & 10 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
// Resolvers: the functions that fetch data for each field in the schema.
import { pool } from './db';
import { buildWinesQuery, encodeCursor, type WinesArgs } from './wine-query';
import {
buildFilterOptionsQueries,
buildWinesQuery,
encodeCursor,
type FilterArgs,
type WinesArgs,
} from './wine-query';

// A row from the wine table, as returned by pg.
interface WineRow {
Expand Down Expand Up @@ -46,6 +52,14 @@ function toWine(row: WineRow) {
};
}

async function filterOptions(
args: FilterArgs,
group: keyof ReturnType<typeof buildFilterOptionsQueries>,
) {
const { sql, params } = buildFilterOptionsQueries(args)[group];
return (await pool.query(sql, params)).rows;
}

export const resolvers = {
Query: {
async wines(_parent: unknown, args: WinesArgs) {
Expand Down Expand Up @@ -78,15 +92,16 @@ export const resolvers = {
return result.rows[0] ? toWine(result.rows[0]) : null;
},

async filterOptions() {
const [types, countries] = await Promise.all([
pool.query(`SELECT type AS value, type AS label, count(*)::int AS count
FROM wine GROUP BY type ORDER BY count DESC, type`),
pool.query(`SELECT country_code AS value, max(country) AS label, count(*)::int AS count
FROM wine WHERE country_code IS NOT NULL
GROUP BY country_code ORDER BY count DESC, label`),
]);
return { types: types.rows, countries: countries.rows };
// The counts are in the fields below, so a query only pays for the groups it asks for.
filterOptions(_parent: unknown, args: FilterArgs) {
return args;
},
},

FilterOptions: {
types: (args: FilterArgs) => filterOptions(args, 'types'),
countries: (args: FilterArgs) => filterOptions(args, 'countries'),
grapes: (args: FilterArgs) => filterOptions(args, 'grapes'),
harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'),
},
};
8 changes: 6 additions & 2 deletions backend/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ export const typeDefs = `#graphql
type FilterOptions {
types: [FilterOption!]!
countries: [FilterOption!]!
"The most common grapes."
grapes: [FilterOption!]!
"The most common food pairings."
harmonize: [FilterOption!]!
}

type Query {
Expand All @@ -82,7 +86,7 @@ export const typeDefs = `#graphql

wine(id: ID!): Wine

"Values for the filter panel, with the number of wines for each value."
filterOptions: FilterOptions!
"Values for the filter panel. The counts follow the search and the filters in the other groups."
filterOptions(search: String, filter: WineFilter): FilterOptions!
}
`;
65 changes: 64 additions & 1 deletion backend/src/wine-query.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
import { buildWinesQuery, decodeCursor, encodeCursor, MAX_PAGE_SIZE } from './wine-query';
import {
buildFilterOptionsQueries,
buildWinesQuery,
decodeCursor,
encodeCursor,
MAX_FACET_VALUES,
MAX_PAGE_SIZE,
} from './wine-query';

describe('buildWinesQuery', () => {
it('returns all wines sorted by top rating when there are no arguments', () => {
Expand Down Expand Up @@ -50,6 +57,62 @@ describe('buildWinesQuery', () => {
});
});

describe('buildFilterOptionsQueries', () => {
const args = {
search: 'pinot',
filter: {
types: ['Red'],
countryCodes: ['FR'],
grapes: ['Merlot'],
harmonize: ['Beef'],
minRating: 4,
},
};

it('counts all wines when there is no search or filter', () => {
const { types } = buildFilterOptionsQueries({});
expect(types.sql).not.toContain('WHERE');
expect(types.params).toEqual([]);
});

it('leaves out its own filter, so the other values in the group still have a count', () => {
const { types, countries, grapes, harmonize } = buildFilterOptionsQueries(args);
expect(types.params).toEqual(['%pinot%', ['FR'], ['Merlot'], ['Beef'], 4]);
expect(countries.params).toEqual(['%pinot%', ['Red'], ['Merlot'], ['Beef'], 4]);
expect(grapes.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Beef'], 4]);
expect(harmonize.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Merlot'], 4]);
});

it('keeps the search and the other filters', () => {
const { types } = buildFilterOptionsQueries(args);
expect(types.sql).toContain('search_text ILIKE $1');
expect(types.sql).toContain('country_code = ANY($2)');
expect(types.sql).not.toContain('type = ANY');
});

it('leaves out wines without a country', () => {
expect(buildFilterOptionsQueries({}).countries.sql).toContain('WHERE country_code IS NOT NULL');
expect(buildFilterOptionsQueries(args).countries.sql).toContain('AND country_code IS NOT NULL');
});

it('splits the lists of grapes and food into one row per value', () => {
const { grapes, harmonize } = buildFilterOptionsQueries({});
expect(grapes.sql).toContain('unnest(grapes)');
expect(harmonize.sql).toContain('unnest(harmonize)');
});

it('limits the number of grapes and food values, since there can be thousands', () => {
const { grapes, harmonize } = buildFilterOptionsQueries({});
expect(grapes.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`);
expect(harmonize.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`);
});

it('never puts the search text in the SQL itself', () => {
const { grapes } = buildFilterOptionsQueries({ search: "'; DROP TABLE wine; --" });
expect(grapes.sql).not.toContain('DROP TABLE');
});
});

describe('cursor', () => {
it('round-trips an offset', () => {
expect(decodeCursor(encodeCursor(48))).toBe(48);
Expand Down
Loading