Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
34 changes: 26 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Kork & Krone

**Last updated:** 17 November 2026
**Last updated:** 18 November 2026
**Submission:** 4 (working system, ready for feedback on every aspect)
**Status:** In progress. See [Status for submission 4](#status-for-submission-4).

Expand All @@ -24,7 +24,7 @@ Students can search, filter and sort a catalogue of wines. Each wine shows one a
## Contents

1. [Status for submission 4](#status-for-submission-4)
2. [Get started](#get-started)
2. [Get started](#get-started) (and the [demo user](#demo-user))
3. [Features](#features)
4. [Architecture and technology choices](#architecture-and-technology-choices)
5. [Data](#data)
Expand Down Expand Up @@ -59,6 +59,8 @@ yet, depending on when the review is made.
| «Mine anmeldelser» page | Done | Shows the «Vil prøve» list. Own reviews come with login in the interface |
| User accounts | Done | Register, log in and log out at `/konto`, with sessions in PostgreSQL and an `httpOnly` cookie |
| Reviews tied to accounts | Done | Writing a review requires login, and the username is shown as the author. Older anonymous reviews are kept as «Anonym student» |
| Favourites, top 4, «Vil prøve» and «Har prøvd» per user | Backend done | API and rules in [API](docs/api.md#wine-lists). The interface comes next |
| Demo user for testing | Done | `demo` / `kork-og-krone`, see [Demo user](#demo-user) |
| Larger dataset on the VM | Done | Full version: 100 646 wines and 21 013 536 ratings |
| Continuous integration (CI) | Not yet started | Needs a self-hosted runner |

Expand All @@ -83,6 +85,7 @@ npm ci --prefix frontend
cp backend/.env.example backend/.env # then set your database password
npm run db:migrate --prefix backend
npm run db:seed:test --prefix backend
npm run db:seed:demo --prefix backend # the demo user below
```

Start the backend and the frontend in two terminals:
Expand All @@ -96,6 +99,19 @@ The landing page needs the backend for wines and categories. Without it, the pag

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

### Demo user

To try the features that need login without registering, log in at `/konto` with:

| Username | Password |
|---|---|
| `demo` | `kork-og-krone` |

The user has favourites with a top 4, wines on «Vil prøve» and «Har prøvd», and some reviews. It exists
on the VM, and locally after `npm run db:seed:demo`, which also resets it if someone has changed it.
Everyone can see the password, so do not store anything private on this user. Searching and reading
reviews never require login.

## Features

This section describes what users can do. "Backend" means the API supports the feature. "UI" means it is visible on the site.
Expand All @@ -110,7 +126,8 @@ This section describes what users can do. "Backend" means the API supports the f
| 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 | Saved in the browser and shown on «Mine anmeldelser». Moves to the backend when login is in the interface |
| Wishlist ("Vil prøve") | Done | Done | Saved in the browser and shown on «Mine anmeldelser». The interface moves to the backend list next |
| Favourites, top 4 and «Har prøvd» | Done | Planned | Stored per user and public. «Har prøvd» takes a wine off «Vil prøve», and a saved review marks the wine as tried. See [API](docs/api.md#wine-lists) |
| User accounts | Done | Done | Register, log in and log out at `/konto`. Errors are shown next to the field they are about, in Norwegian. Sessions in PostgreSQL with an `httpOnly` cookie |
| Reviews with login | Done | Done | Only logged-in users can write, change or delete a review, and only their own. Visitors see the reviews and a link to log in, which brings them back to the wine. `User.reviews` lists a user's reviews for the profile page |

Expand Down Expand Up @@ -284,7 +301,7 @@ and because the test was run over VPN. These are the "before" numbers. Compressi
| 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 | Vitest with Apollo Server (`executeOperation`) | Login and reviews through real GraphQL requests, with a fake browser per user that keeps the cookie. The review tests run against a separate test database (`TEST_DATABASE_URL`), see [API](docs/api.md#database-tests) | Count again |
| API | Vitest with Apollo Server (`executeOperation`) | Login, reviews, wine lists, the top 4 and the demo user through real GraphQL requests, with a fake browser per user that keeps the cookie. The review tests run against a separate test database (`TEST_DATABASE_URL`), see [API](docs/api.md#database-tests) | Count again |

Counted on 16 November 2026. The skipped backend tests run the user store against a real database, and need `TEST_DATABASE_URL`.

Expand Down Expand Up @@ -374,9 +391,10 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
### Next: towards the final submission

- [x] Login in the interface: forms for register and login, and reviews tied to the account instead of the anonymous ID.
- [ ] Favourites with a top 4, «Vil prøve» and «Har prøvd» stored per user.
- [x] Favourites with a top 4, «Vil prøve» and «Har prøvd» stored per user (backend and API).
- [ ] The lists in the interface: heart, bookmark and «Har prøvd» on the wines.
- [ ] Profile page with the top 4, the lists and the user's reviews.
- [ ] Wishlist stored in the backend, so it follows the user between devices.
- [ ] Wishlist stored in the backend, so it follows the user between devices. The API is ready.
- [ ] 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.
Expand Down Expand Up @@ -411,8 +429,8 @@ Remove known issues as they are fixed.
- [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, user accounts, reviews, database tests and the X-Wines citation
- [Manual testing](docs/manual-testing.md): how to test login, reviews and other user data by hand
- [API](docs/api.md): GraphQL queries, user accounts, reviews, wine lists, the demo user, database tests and the X-Wines citation
- [Manual testing](docs/manual-testing.md): how to test login, reviews, wine lists and the demo user by hand
- [Screen reader testing](docs/screen-reader.md): what we found, what we fixed and the VoiceOver script
- [Workflow](docs/workflow.md): branches, reviews and checks
- [Tasks](docs/tasks.md): requirements and sketches
11 changes: 11 additions & 0 deletions backend/migrations/1794998259977_review-user-index-by-id.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- Up Migration

-- A user's reviews are now listed by id, newest first, so an edit does not move a review while
-- someone pages through the list. The index follows the new ORDER BY (user_id, id DESC).
DROP INDEX review_user_updated;
CREATE INDEX review_user_id ON review (user_id, id DESC);

-- Down Migration

DROP INDEX review_user_id;
CREATE INDEX review_user_updated ON review (user_id, updated_at DESC);
35 changes: 35 additions & 0 deletions backend/migrations/1794998971543_create-user-wine.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
-- Up Migration

-- A user's wine lists: favourites, «Vil prøve» and «Har prøvd». One row per wine per list.
-- All lists are public on the profile, so nothing here is secret.
CREATE TABLE user_wine (
-- Used to sort a list (newest first) and as the page cursor, like review.id.
-- An id never changes, so paging is stable while the list changes.
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id integer NOT NULL REFERENCES app_user (id) ON DELETE CASCADE,
wine_id integer NOT NULL REFERENCES wine (id) ON DELETE CASCADE,
-- Text with a CHECK instead of an enum type: a new list is one more value here, in a plain
-- migration. The values are the GraphQL enum WineList, and must be changed together with it.
list text NOT NULL CHECK (list IN ('FAVOURITE', 'WANT_TO_TRY', 'TRIED')),
added_at timestamptz NOT NULL DEFAULT now(),
-- 1-4 for the favourites chosen for the top of the profile, otherwise null.
top_position smallint CHECK (top_position BETWEEN 1 AND 4),

-- A wine is on each list at most once.
CONSTRAINT user_wine_once UNIQUE (user_id, list, wine_id),
-- Only favourites can be in the top 4. Removing a favourite removes it from the top 4 too.
CONSTRAINT user_wine_top_only_favourites CHECK (top_position IS NULL OR list = 'FAVOURITE')
);

-- Each place in the top 4 holds one wine.
CREATE UNIQUE INDEX user_wine_top ON user_wine (user_id, top_position) WHERE top_position IS NOT NULL;

-- One list for a user, newest first, page by page (User.wines).
CREATE INDEX user_wine_list_newest ON user_wine (user_id, list, id DESC);

-- Which lists a page of wines is on for one user (Wine.myLists).
CREATE INDEX user_wine_user_wine ON user_wine (user_id, wine_id);

-- Down Migration

DROP TABLE user_wine;
1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"typecheck": "tsc --noEmit",
"test": "vitest run",
"db:seed:test": "tsx src/scripts/seed-xwines.ts data/xwines-test/wines.csv data/xwines-test/ratings.csv",
"db:seed:demo": "tsx src/scripts/seed-demo-user.ts",
"db:migrate": "node-pg-migrate up",
"db:migrate:down": "node-pg-migrate down",
"db:migrate:create": "node-pg-migrate create --migration-file-language sql"
Expand Down
46 changes: 46 additions & 0 deletions backend/src/connection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { decodeIdCursor, encodeIdCursor, toConnection } from './connection';

describe('toConnection', () => {
const page = (rows: number[], first: number) =>
toConnection({
rows,
first,
totalCount: 10,
toNode: (row) => ({ id: row }),
cursorFor: (row) => encodeIdCursor(row),
});

it('uses the extra row only to tell that there is a next page', () => {
const result = page([9, 8, 7], 2);
expect(result.edges.map((edge) => edge.node.id)).toEqual([9, 8]);
expect(result.pageInfo).toEqual({ hasNextPage: true, endCursor: encodeIdCursor(8) });
expect(result.totalCount).toBe(10);
});

it('has no next page and no end cursor when the page is empty', () => {
expect(page([], 2).pageInfo).toEqual({ hasNextPage: false, endCursor: null });
});
});

describe('id cursors', () => {
it('round-trips an id', () => {
expect(decodeIdCursor(encodeIdCursor(4821))).toBe(4821);
expect(decodeIdCursor(encodeIdCursor(2_147_483_647))).toBe(2_147_483_647);
expect(decodeIdCursor(null)).toBeNull();
expect(decodeIdCursor(undefined)).toBeNull();
});

it.each([
['not base64 at all', 'not-a-cursor'],
['an offset cursor', Buffer.from('offset:10').toString('base64')],
['a negative id', Buffer.from('id:-1').toString('base64')],
['id 0', Buffer.from('id:0').toString('base64')],
['an id above the largest database integer', Buffer.from('id:2147483648').toString('base64')],
['a very long number', Buffer.from(`id:${'9'.repeat(25)}`).toString('base64')],
])('rejects %s with BAD_USER_INPUT', (_name, cursor) => {
expect(() => decodeIdCursor(cursor)).toThrow(
expect.objectContaining({ extensions: { code: 'BAD_USER_INPUT' } }),
);
});
});
57 changes: 57 additions & 0 deletions backend/src/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Pages in the GraphQL connection format ({ totalCount, edges, pageInfo }), shared by the wine
// search, a user's reviews and a user's wine lists.
import { GraphQLError } from 'graphql';

/**
* A page from `rows`, which holds one row more than `first` when there is a next page.
* That extra row is only used to set hasNextPage.
*/
export function toConnection<Row, Node>({
rows,
first,
totalCount,
toNode,
cursorFor,
}: {
rows: Row[];
first: number;
totalCount: number;
toNode: (row: Row) => Node;
/** The cursor that points just after this row. `index` is its place on the page. */
cursorFor: (row: Row, index: number) => string;
}) {
const edges = rows.slice(0, first).map((row, index) => ({
cursor: cursorFor(row, index),
node: toNode(row),
}));
return {
totalCount,
edges,
pageInfo: { hasNextPage: rows.length > first, endCursor: edges.at(-1)?.cursor ?? null },
};
}

/*
* Cursors for lists that belong to a user (reviews, wine lists). They hold the id of the last row
* on the page, and the next page asks for ids below it ("keyset pagination"). Rows are sorted by
* id, newest first, and an id never changes, so a row that is edited while someone is paging is
* neither skipped nor shown twice. An offset would move when rows are added or removed.
*/

/** The largest value of a PostgreSQL `integer`. A larger id cannot exist, and the query would fail. */
const MAX_INTEGER = 2_147_483_647;

export function encodeIdCursor(id: number): string {
return Buffer.from(`id:${id}`).toString('base64');
}

/** The id in the cursor, or null without one. A cursor the API did not make gives BAD_USER_INPUT. */
export function decodeIdCursor(cursor: string | null | undefined): number | null {
if (!cursor) return null;
const match = /^id:(\d{1,10})$/.exec(Buffer.from(cursor, 'base64').toString('utf8'));
const id = match ? Number(match[1]) : NaN;
if (!Number.isInteger(id) || id <= 0 || id > MAX_INTEGER) {
throw new GraphQLError('Invalid cursor.', { extensions: { code: 'BAD_USER_INPUT' } });
}
return id;
}
16 changes: 16 additions & 0 deletions backend/src/db-errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest';
import { isForeignKeyViolation } from './db-errors';

describe('isForeignKeyViolation', () => {
it('matches the code and the constraint name', () => {
const error = { code: '23503', constraint: 'review_wine_id_fkey' };
expect(isForeignKeyViolation(error, 'review_wine_id_fkey')).toBe(true);
expect(isForeignKeyViolation(error, 'review_user_id_fkey')).toBe(false);
});

it('ignores other errors', () => {
expect(isForeignKeyViolation({ code: '23505', constraint: 'review_wine_id_fkey' }, 'review_wine_id_fkey')).toBe(false);
expect(isForeignKeyViolation(new Error('Connection lost'), 'review_wine_id_fkey')).toBe(false);
expect(isForeignKeyViolation(null, 'review_wine_id_fkey')).toBe(false);
});
});
19 changes: 19 additions & 0 deletions backend/src/db-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Recognises PostgreSQL errors by code and constraint name, so a resolver can turn them into
// errors the frontend understands. Codes: https://www.postgresql.org/docs/current/errcodes-appendix.html

const FOREIGN_KEY_VIOLATION = '23503';

interface PgError {
code?: unknown;
constraint?: unknown;
}

/**
* True when `error` is a foreign key violation on the named constraint, for example
* `review_wine_id_fkey` when the wine does not exist. The name tells which reference failed,
* since one table can have several.
*/
export function isForeignKeyViolation(error: unknown, constraint: string): boolean {
const pgError = error as PgError | null;
return pgError?.code === FOREIGN_KEY_VIOLATION && pgError.constraint === constraint;
}
23 changes: 21 additions & 2 deletions backend/src/db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync } from 'node:fs';
import path from 'node:path';
import { Pool } from 'pg';
import { Pool, type PoolClient } from 'pg';

// Load backend/.env if it exists. Variables already set in the shell take priority.
const envFile = path.join(__dirname, '..', '.env');
Expand All @@ -10,4 +10,23 @@ if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is required. See docs/setup.md.');
}

export const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const pool = new Pool({ connectionString: process.env.DATABASE_URL });

/**
* Runs `work` in one transaction on one connection: either everything in it is saved, or
* nothing is. Use the `client` it gets, not `pool`, for every query that belongs to it.
*/
export async function withTransaction<T>(work: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
Loading