From 5d221aca1078812373274bb8d373d8bd394c19d1 Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 20:09:41 +0100 Subject: [PATCH 1/6] feat: #12 store album average rating with a review trigger --- docs/data-model.md | 6 + server/drizzle/0002_album-average-rating.sql | 48 ++ server/drizzle/meta/0002_snapshot.json | 585 +++++++++++++++++++ server/drizzle/meta/_journal.json | 7 + server/src/db/schema.ts | 4 + server/src/loaders/index.ts | 20 +- 6 files changed, 659 insertions(+), 11 deletions(-) create mode 100644 server/drizzle/0002_album-average-rating.sql create mode 100644 server/drizzle/meta/0002_snapshot.json diff --git a/docs/data-model.md b/docs/data-model.md index 7cc88e5..f51bf21 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -21,6 +21,12 @@ genre and join tables. artist terms when titles, artist names or artist links change. Migration `0001` also backfills existing albums. +`album.average_rating` is the mean of the album's review ratings, or NULL without +reviews. A trigger on `review` recomputes it for the one album a review write +touches, so its cost does not grow with the catalog. The rating sorts and +`Album.averageRating` both read it. Migration `0002` adds it and backfills +existing reviews. + ## User-generated data - A **user** is a simulated identity: a UUID the client keeps in `localStorage` diff --git a/server/drizzle/0002_album-average-rating.sql b/server/drizzle/0002_album-average-rating.sql new file mode 100644 index 0000000..1623e27 --- /dev/null +++ b/server/drizzle/0002_album-average-rating.sql @@ -0,0 +1,48 @@ +ALTER TABLE "album" ADD COLUMN "average_rating" double precision; +--> statement-breakpoint +CREATE FUNCTION refresh_album_average_rating(target_album_id integer) +RETURNS void +LANGUAGE plpgsql +AS $$ +BEGIN + -- Lock the album row first. Two reviews saved at once for the same album + -- then run one after the other, and the second average is computed in a new + -- statement that already sees the first review. + PERFORM 1 FROM album WHERE id = target_album_id FOR UPDATE; + + UPDATE album + SET average_rating = ( + SELECT avg(rating) FROM review WHERE review.album_id = target_album_id + ) + WHERE id = target_album_id; +END; +$$; +--> statement-breakpoint +CREATE FUNCTION refresh_album_average_rating_from_review() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP <> 'DELETE' THEN + PERFORM refresh_album_average_rating(NEW.album_id); + END IF; + + IF TG_OP <> 'INSERT' AND OLD.album_id IS DISTINCT FROM NEW.album_id THEN + PERFORM refresh_album_average_rating(OLD.album_id); + END IF; + RETURN NULL; +END; +$$; +--> statement-breakpoint +CREATE TRIGGER review_refresh_album_average_rating +AFTER INSERT OR UPDATE OF rating, album_id OR DELETE ON review +FOR EACH ROW EXECUTE FUNCTION refresh_album_average_rating_from_review(); +--> statement-breakpoint +UPDATE album +SET average_rating = rated.average_rating +FROM ( + SELECT album_id, avg(rating) AS average_rating + FROM review + GROUP BY album_id +) AS rated +WHERE album.id = rated.album_id; diff --git a/server/drizzle/meta/0002_snapshot.json b/server/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..d9b6661 --- /dev/null +++ b/server/drizzle/meta/0002_snapshot.json @@ -0,0 +1,585 @@ +{ + "id": "b608de7b-01f8-44a4-9f50-34eec05c3b41", + "prevId": "94caae8d-f082-4ee7-8111-f0f8b418bff6", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album": { + "name": "album", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "release_year": { + "name": "release_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "search_vector": { + "name": "search_vector", + "type": "tsvector", + "primaryKey": false, + "notNull": false + }, + "average_rating": { + "name": "average_rating", + "type": "double precision", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_search_vector_idx": { + "name": "album_search_vector_idx", + "columns": [ + { + "expression": "search_vector", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_artist": { + "name": "album_artist", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artist_id": { + "name": "artist_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "album_artist_album_id_album_id_fk": { + "name": "album_artist_album_id_album_id_fk", + "tableFrom": "album_artist", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_artist_artist_id_artist_id_fk": { + "name": "album_artist_artist_id_artist_id_fk", + "tableFrom": "album_artist", + "tableTo": "artist", + "columnsFrom": ["artist_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_artist_album_id_artist_id_pk": { + "name": "album_artist_album_id_artist_id_pk", + "columns": ["album_id", "artist_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_genre": { + "name": "album_genre", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "genre_id": { + "name": "genre_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "album_genre_album_id_album_id_fk": { + "name": "album_genre_album_id_album_id_fk", + "tableFrom": "album_genre", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_genre_genre_id_genre_id_fk": { + "name": "album_genre_genre_id_genre_id_fk", + "tableFrom": "album_genre", + "tableTo": "genre", + "columnsFrom": ["genre_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_genre_album_id_genre_id_pk": { + "name": "album_genre_album_id_genre_id_pk", + "columns": ["album_id", "genre_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_user": { + "name": "app_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.artist": { + "name": "artist", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.crate_item": { + "name": "crate_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "crate_item_user_album_unique": { + "name": "crate_item_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "crate_item_user_added_at_idx": { + "name": "crate_item_user_added_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "added_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "crate_item_user_id_app_user_id_fk": { + "name": "crate_item_user_id_app_user_id_fk", + "tableFrom": "crate_item", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "crate_item_album_id_album_id_fk": { + "name": "crate_item_album_id_album_id_fk", + "tableFrom": "crate_item", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.genre": { + "name": "genre", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "genre_name_unique": { + "name": "genre_name_unique", + "nullsNotDistinct": false, + "columns": ["name"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.review": { + "name": "review", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "rating": { + "name": "rating", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "review_user_album_unique": { + "name": "review_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "review_album_idx": { + "name": "review_album_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "review_user_id_app_user_id_fk": { + "name": "review_user_id_app_user_id_fk", + "tableFrom": "review", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "review_album_id_album_id_fk": { + "name": "review_album_id_album_id_fk", + "tableFrom": "review", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "review_rating_range": { + "name": "review_rating_range", + "value": "\"review\".\"rating\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "public.track": { + "name": "track", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "track_number": { + "name": "track_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_seconds": { + "name": "duration_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "track_album_track_number_unique": { + "name": "track_album_track_number_unique", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "track_album_track_number_idx": { + "name": "track_album_track_number_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "track_album_id_album_id_fk": { + "name": "track_album_id_album_id_fk", + "tableFrom": "track", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index 1781029..6260d80 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1791974033850, "tag": "0001_user-content-and-tracks", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1793041265071, + "tag": "0002_album-average-rating", + "breakpoints": true } ] } diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index c8993c6..9edc708 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -2,6 +2,7 @@ import { sql } from 'drizzle-orm'; import { check, customType, + doublePrecision, index, integer, pgTable, @@ -27,6 +28,9 @@ export const album = pgTable( // The words a search matches: the title plus artist names. The database // trigger keeps this up to date when catalog data changes. searchVector: tsvector('search_vector'), + // Mean of the album's review ratings, NULL with no reviews. A trigger on + // review keeps it current, so the rating sorts page on a stored column. + averageRating: doublePrecision('average_rating'), }, // GIN is the index type for tsvector, so a word lookup does not scan the table. (t) => [index('album_search_vector_idx').using('gin', t.searchVector)], diff --git a/server/src/loaders/index.ts b/server/src/loaders/index.ts index 9e246f2..b91b9bb 100644 --- a/server/src/loaders/index.ts +++ b/server/src/loaders/index.ts @@ -1,7 +1,8 @@ import DataLoader from 'dataloader'; -import { and, asc, avg, count, eq, inArray } from 'drizzle-orm'; +import { and, asc, count, eq, inArray } from 'drizzle-orm'; import type { Db } from '../db/client.js'; import { + album, albumArtist, albumGenre, appUser, @@ -71,18 +72,15 @@ export function createLoaders(db: Db, userId: string | null) { return albumIds.map((id) => counts.get(id) ?? 0); }), + // Reads the stored column the rating sorts use, so the number shown on a + // card is the same one the results were ordered by. It is loaded at + // resolve time, so a review mutation's payload sees the updated value. averageRatingByAlbum: new DataLoader(async (albumIds) => { const rows = await db - .select({ albumId: review.albumId, averageRating: avg(review.rating) }) - .from(review) - .where(inArray(review.albumId, [...albumIds])) - .groupBy(review.albumId); - const averages = new Map( - rows.map((row) => [ - row.albumId, - row.averageRating === null ? null : Number(row.averageRating), - ]), - ); + .select({ id: album.id, averageRating: album.averageRating }) + .from(album) + .where(inArray(album.id, [...albumIds])); + const averages = new Map(rows.map((row) => [row.id, row.averageRating])); return albumIds.map((id) => averages.get(id) ?? null); }), From b6887e0b722ac75a8b53fd8612343fe84fad5f7a Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 20:09:41 +0100 Subject: [PATCH 2/6] feat: #12 title, year and rating sorts in both directions --- README.md | 4 +- docs/architecture.md | 2 +- schema.graphql | 3 + server/src/search/search.test.ts | 78 ++++++++++++++ server/src/search/search.ts | 30 ++++-- server/src/search/sort.postgres.test.ts | 136 ++++++++++++++++++++++++ 6 files changed, 243 insertions(+), 10 deletions(-) create mode 100644 server/src/search/sort.postgres.test.ts diff --git a/README.md b/README.md index a19e1e5..49ba43d 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ The two `AlbumDetailPage` rows are the chunk added by the album detail route (#1 | `schema.graphql` | GraphQL schema | | `docs/` | Architecture, data model, UI, workflow, AI log and VM guide | -**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items. The GraphQL backend supports album and artist search, genre and decade filters, sorting and cursor-based pagination. Supported sorts are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`. `AVERAGE_RATING_DESC` is defined in the schema but currently returns an error because reviews are not implemented yet. +**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items. The GraphQL backend supports album and artist search, genre and decade filters, sorting and cursor-based pagination. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results. The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. It currently shows the first 20 matches ordered by relevance. @@ -202,7 +202,7 @@ The frontend supports searching by album title or artist, committed on Search or ### Backend search behavior -The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year sorting, facet counts and cursor-based pagination. These capabilities are available through GraphQL but are not all exposed in the frontend yet. +The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. These capabilities are available through GraphQL but are not all exposed in the frontend yet. ## Try the application diff --git a/docs/architecture.md b/docs/architecture.md index 91b744d..a4a1982 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,7 +57,7 @@ resolver loads every match into memory. builder is the most complex server code, so it needs tests against a real database. -The implemented search uses PostgreSQL full-text search with weighted album titles and artist names. Genre filters combine with AND, while decade filters combine with OR. Counts and facets cover matching results, not just the current page. The supported sort options are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`; rating-based sorting is not yet implemented. +The implemented search uses PostgreSQL full-text search with weighted album titles and artist names. Genre filters combine with AND, while decade filters combine with OR. Counts and facets cover matching results, not just the current page. Sorting covers relevance, title, release year and average rating, the last three in both directions. Every sort ends with an `album.id` tiebreak and puts NULLs last, so the keyset cursor stays stable. The rating sorts read `album.average_rating`, a column a trigger on `review` keeps current, because a live `AVG()` would be recomputed for the whole result set and would move under a cursor whenever someone saved a review. ## 4. DataLoaders against N+1 diff --git a/schema.graphql b/schema.graphql index d7d1719..e15f0f6 100644 --- a/schema.graphql +++ b/schema.graphql @@ -150,6 +150,9 @@ input UpsertReviewInput { enum AlbumSort { RELEVANCE TITLE_ASC + TITLE_DESC + RELEASE_YEAR_ASC RELEASE_YEAR_DESC + AVERAGE_RATING_ASC AVERAGE_RATING_DESC } diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts index c295052..1856a6b 100644 --- a/server/src/search/search.test.ts +++ b/server/src/search/search.test.ts @@ -5,6 +5,7 @@ import { afterCursor, decodeCursor, encodeCursor, + orderBy, pageSize, searchFilter, sortKey, @@ -70,6 +71,83 @@ describe('afterCursor', () => { }); }); +describe('sortKey for every sort', () => { + it.each([ + ['TITLE_ASC', 'lower(album.title)', 'ASC', false], + ['TITLE_DESC', 'lower(album.title)', 'DESC', false], + ['RELEASE_YEAR_ASC', 'album.release_year', 'ASC', true], + ['RELEASE_YEAR_DESC', 'album.release_year', 'DESC', true], + ['AVERAGE_RATING_ASC', 'album.average_rating', 'ASC', true], + ['AVERAGE_RATING_DESC', 'album.average_rating', 'DESC', true], + ] as const)('%s sorts on %s %s', (sort, expr, direction, nullable) => { + const key = sortKey(input({ sort })); + expect(render(key.expr).sql).toBe(expr); + expect(key.direction).toBe(direction); + expect(key.nullable).toBe(nullable); + // NULLs last in both directions, then the id tiebreak. + expect(render(orderBy(key)).sql).toBe( + `${expr} ${direction} NULLS LAST, album.id ASC`, + ); + }); + + it('sorts by rating on the stored column, not a live aggregate', () => { + const { sql } = render(sortKey(input({ sort: 'AVERAGE_RATING_DESC' })).expr); + expect(sql).not.toMatch(/avg|review/i); + }); +}); + +describe('afterCursor for the descending and rating sorts', () => { + it('continues below the cursor for a descending title sort', () => { + const key = sortKey(input({ sort: 'TITLE_DESC' })); + const { sql, params } = render( + afterCursor(key, { sort: 'TITLE_DESC', value: 'blue', id: 5 }), + ); + expect(sql).toBe( + '(lower(album.title) < $1 OR (lower(album.title) = $2 AND album.id > $3))', + ); + expect(params).toEqual(['blue', 'blue', 5]); + }); + + it('keeps unknown years last when sorting oldest first', () => { + const key = sortKey(input({ sort: 'RELEASE_YEAR_ASC' })); + const { sql } = render( + afterCursor(key, { sort: 'RELEASE_YEAR_ASC', value: 1990, id: 3 }), + ); + expect(sql).toContain('album.release_year > $1'); + expect(sql).toContain('album.release_year IS NULL'); + }); + + // Ratings repeat far more than titles do, so on a tie the id decides which + // rows are left. Without it a page boundary inside a run of 4.5s would skip + // or repeat albums. + it.each(['AVERAGE_RATING_ASC', 'AVERAGE_RATING_DESC'] as const)( + 'breaks %s ties on id', + (sort) => { + const key = sortKey(input({ sort })); + const beyond = sort === 'AVERAGE_RATING_ASC' ? '>' : '<'; + const { sql, params } = render(afterCursor(key, { sort, value: 4.5, id: 12 })); + expect(sql).toBe( + `(album.average_rating ${beyond} $1 OR (album.average_rating = $2 AND album.id > $3) OR album.average_rating IS NULL)`, + ); + expect(params).toEqual([4.5, 4.5, 12]); + }, + ); + + it('pages through unrated albums by id once the cursor reaches them', () => { + const key = sortKey(input({ sort: 'AVERAGE_RATING_DESC' })); + const { sql, params } = render( + afterCursor(key, { sort: 'AVERAGE_RATING_DESC', value: null, id: 9 }), + ); + expect(sql).toBe('(album.average_rating IS NULL AND album.id > $1)'); + expect(params).toEqual([9]); + }); + + it('rejects a cursor from the opposite direction of the same column', () => { + const cursor = encodeCursor({ sort: 'TITLE_ASC', value: 'blue', id: 1 }); + expect(() => decodeCursor(cursor, 'TITLE_DESC')).toThrow('different sort'); + }); +}); + describe('cursor value validation', () => { it('rejects a value of the wrong type for the sort', () => { const yearKey = sortKey(input({ sort: 'RELEASE_YEAR_DESC' })); diff --git a/server/src/search/search.ts b/server/src/search/search.ts index 1ae09c9..9195cdf 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -8,7 +8,13 @@ import { GraphQLError } from 'graphql'; */ export type AlbumSort = - 'RELEVANCE' | 'TITLE_ASC' | 'RELEASE_YEAR_DESC' | 'AVERAGE_RATING_DESC'; + | 'RELEVANCE' + | 'TITLE_ASC' + | 'TITLE_DESC' + | 'RELEASE_YEAR_ASC' + | 'RELEASE_YEAR_DESC' + | 'AVERAGE_RATING_ASC' + | 'AVERAGE_RATING_DESC'; export type AlbumSearchInput = { query: string; @@ -88,7 +94,8 @@ export function searchFilter(input: AlbumSearchInput, omit?: 'decades'): SQL { export type SortKey = { expr: SQL; direction: 'ASC' | 'DESC'; - // Nullable keys (release year) put NULLs last and need extra cursor logic. + // Nullable keys (release year, rating) put NULLs last in both directions and + // need extra cursor logic. nullable: boolean; // What a cursor's value must be for this sort, checked before it reaches SQL. valueType: 'string' | 'number'; @@ -114,23 +121,32 @@ export function sortKey(input: AlbumSearchInput): SortKey { valueType: 'string', }; case 'TITLE_ASC': + case 'TITLE_DESC': return { expr: sql`lower(album.title)`, - direction: 'ASC', + direction: input.sort === 'TITLE_ASC' ? 'ASC' : 'DESC', nullable: false, valueType: 'string', }; + case 'RELEASE_YEAR_ASC': case 'RELEASE_YEAR_DESC': return { expr: sql`album.release_year`, - direction: 'DESC', + direction: input.sort === 'RELEASE_YEAR_ASC' ? 'ASC' : 'DESC', nullable: true, valueType: 'number', }; + // A stored column kept current by a trigger on review, not a live AVG(): + // the cursor needs a value that does not move with every other review. + // Albums without reviews are NULL and come last. + case 'AVERAGE_RATING_ASC': case 'AVERAGE_RATING_DESC': - throw new GraphQLError( - 'Sorting by rating is not available until reviews are stored.', - ); + return { + expr: sql`album.average_rating`, + direction: input.sort === 'AVERAGE_RATING_ASC' ? 'ASC' : 'DESC', + nullable: true, + valueType: 'number', + }; } } diff --git a/server/src/search/sort.postgres.test.ts b/server/src/search/sort.postgres.test.ts new file mode 100644 index 0000000..4b9919b --- /dev/null +++ b/server/src/search/sort.postgres.test.ts @@ -0,0 +1,136 @@ +import { randomUUID } from 'node:crypto'; +import { PgDialect } from 'drizzle-orm/pg-core'; +import { sql } from 'drizzle-orm'; +import { Pool } from 'pg'; +import { afterAll, describe, expect, it } from 'vitest'; +import { + afterCursor, + decodeCursor, + encodeCursor, + orderBy, + sortKey, + type AlbumSort, +} from './search.js'; + +// Set TEST_DATABASE_URL to run these tests. The paging test reads VALUES rows +// only; the trigger test writes inside a transaction it rolls back. +describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL sorting', () => { + const pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }); + const dialect = new PgDialect(); + + afterAll(() => pool.end()); + + // Repeated titles, years and ratings, and NULLs, so every page boundary of + // two rows lands inside a run of ties at least once. + const fixture = sql`(VALUES + (1, 'Blue', 1971, 4.5::float8), + (2, 'blue', 1971, 4.5::float8), + (3, 'Abbey Road', NULL, 4.5::float8), + (4, 'Kid A', 2000, NULL), + (5, 'Blue', 1997, 3::float8), + (6, 'Kid A', NULL, NULL), + (7, 'Abbey Road', 1969, 4.5::float8) + ) AS album(id, title, release_year, average_rating)`; + + async function page(sort: AlbumSort, after: string | null) { + const key = sortKey({ query: '', sort }); + const where = after ? afterCursor(key, decodeCursor(after, sort)) : sql`TRUE`; + const query = dialect.sqlToQuery(sql` + SELECT album.id, ${key.expr} AS "sortValue" + FROM ${fixture} + WHERE ${where} + ORDER BY ${orderBy(key)} + LIMIT 2 + `); + const result = await pool.query<{ id: number; sortValue: string | number | null }>( + query.sql, + query.params, + ); + return result.rows; + } + + it.each([ + 'TITLE_ASC', + 'TITLE_DESC', + 'RELEASE_YEAR_ASC', + 'RELEASE_YEAR_DESC', + 'AVERAGE_RATING_ASC', + 'AVERAGE_RATING_DESC', + ] as const)('pages %s in the same order as one unpaged query', async (sort) => { + const key = sortKey({ query: '', sort }); + const all = dialect.sqlToQuery( + sql`SELECT album.id FROM ${fixture} ORDER BY ${orderBy(key)}`, + ); + const expected = (await pool.query<{ id: number }>(all.sql, all.params)).rows.map( + (row) => row.id, + ); + + const paged: number[] = []; + let after: string | null = null; + for (;;) { + const rows = await page(sort, after); + const last = rows.at(-1); + if (!last) break; + paged.push(...rows.map((row) => row.id)); + after = encodeCursor({ sort, value: last.sortValue, id: last.id }); + } + + expect(paged).toEqual(expected); + expect(new Set(paged).size).toBe(7); + }); + + it('orders ratings with ties on id and unrated albums last', async () => { + const key = sortKey({ query: '', sort: 'AVERAGE_RATING_DESC' }); + const query = dialect.sqlToQuery( + sql`SELECT album.id FROM ${fixture} ORDER BY ${orderBy(key)}`, + ); + const rows = (await pool.query<{ id: number }>(query.sql, query.params)).rows; + expect(rows.map((row) => row.id)).toEqual([1, 2, 3, 7, 5, 4, 6]); + }); + + it('keeps album.average_rating in step with reviews', async () => { + const client = await pool.connect(); + const rating = async (albumId: number) => + ( + await client.query<{ average_rating: number | null }>( + 'SELECT average_rating FROM album WHERE id = $1', + [albumId], + ) + ).rows[0]?.average_rating; + + try { + await client.query('BEGIN'); + const albums = await client.query<{ id: number }>( + `INSERT INTO album (title) VALUES ('Trigger test A'), ('Trigger test B') RETURNING id`, + ); + const [a, b] = albums.rows.map((row) => row.id) as [number, number]; + const [u1, u2] = [randomUUID(), randomUUID()]; + await client.query( + `INSERT INTO app_user (id, display_name) VALUES ($1, 'one'), ($2, 'two')`, + [u1, u2], + ); + + expect(await rating(a)).toBeNull(); + + await client.query( + 'INSERT INTO review (user_id, album_id, rating) VALUES ($1, $3, 5), ($2, $3, 2)', + [u1, u2, a], + ); + expect(await rating(a)).toBe(3.5); + + await client.query('UPDATE review SET rating = 4 WHERE user_id = $1', [u2]); + expect(await rating(a)).toBe(4.5); + + // Moving a review refreshes both albums. + await client.query('UPDATE review SET album_id = $2 WHERE user_id = $1', [u2, b]); + expect(await rating(a)).toBe(5); + expect(await rating(b)).toBe(4); + + await client.query('DELETE FROM review WHERE user_id = $1', [u1]); + expect(await rating(a)).toBeNull(); + } finally { + await client.query('ROLLBACK'); + client.release(); + } + }); +}); From 90845194f1876c9daa78a915f2d7f2b418092578 Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 20:09:41 +0100 Subject: [PATCH 3/6] feat: #12 sort control in the results header --- client/src/App.test.tsx | 37 +++++++++++++- client/src/App.tsx | 2 + client/src/api/searchAlbums.ts | 3 ++ client/src/components/ResultsLayout.css | 7 +++ client/src/components/ResultsLayout.tsx | 12 ++++- client/src/components/SortSelect.css | 17 +++++++ client/src/components/SortSelect.test.tsx | 24 +++++++++ client/src/components/SortSelect.tsx | 60 +++++++++++++++++++++++ client/src/hooks/useAlbumSearch.ts | 4 +- client/src/hooks/useSearchState.test.ts | 2 +- 10 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 client/src/components/SortSelect.css create mode 100644 client/src/components/SortSelect.test.tsx create mode 100644 client/src/components/SortSelect.tsx diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index ec47df6..8a5b9a4 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -6,6 +6,7 @@ import { GraphQLError } from 'graphql'; import App from './App.js'; import { SEARCH_ALBUMS } from './api/searchAlbums.js'; import type { + AlbumSort, AlbumSummary, SearchAlbumsData, SearchAlbumsVariables, @@ -24,11 +25,12 @@ const album: AlbumSummary = { function mockSearch( query: string, albums: AlbumSummary[] = [album], + sort: AlbumSort = 'RELEVANCE', ): MockLink.MockedResponse { return { request: { query: SEARCH_ALBUMS, - variables: { input: { query, sort: 'RELEVANCE' }, first: 20, after: null }, + variables: { input: { query, sort }, first: 20, after: null }, }, result: { data: { @@ -273,6 +275,39 @@ describe('App search', () => { expect(screen.getByRole('status')).toHaveTextContent('Showing 1 of 1 albums.'); }); + it('re-queries the server when the sort changes and keeps it in the URL', async () => { + const lowRated = { ...album, id: '2', title: 'Abbey Lane', averageRating: 2.1 }; + renderApp([ + mockSearch('Abbey', [lowRated, album]), + mockSearch('Abbey', [album, lowRated], 'AVERAGE_RATING_DESC'), + ]); + submitSearch('Abbey'); + await screen.findByRole('article', { name: 'Abbey Lane' }); + const sort = screen.getByRole('combobox', { name: 'Sort by' }); + expect(sort).toHaveValue('RELEVANCE'); + + fireEvent.change(sort, { target: { value: 'AVERAGE_RATING_DESC' } }); + + expect(window.location.search).toBe('?q=Abbey&sort=AVERAGE_RATING_DESC'); + // The order is whatever the server returned, not a client-side re-sort. + await waitFor(() => + expect( + screen + .getAllByRole('article') + .map((card) => within(card).getByRole('heading').textContent), + ).toEqual(['Abbey Road', 'Abbey Lane']), + ); + }); + + it('restores the sort from a shared link', async () => { + window.history.replaceState({}, '', '/?q=Abbey&sort=RELEASE_YEAR_ASC'); + renderApp([mockSearch('Abbey', [album], 'RELEASE_YEAR_ASC')]); + await screen.findByRole('article', { name: 'Abbey Road' }); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue( + 'RELEASE_YEAR_ASC', + ); + }); + it('replaces results for a new query rather than retaining the previous search', async () => { renderApp([mockSearch('Abbey'), mockSearch('missing', [])]); submitSearch('Abbey'); diff --git a/client/src/App.tsx b/client/src/App.tsx index 604b836..23ba023 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -64,6 +64,8 @@ function DiscoveryPage() { albums={search.albums} totalCount={search.totalCount} hasQuery={search.hasQuery} + sort={search.sort} + onSortChange={search.setSort} loading={search.loading} retrying={search.retrying} error={search.error} diff --git a/client/src/api/searchAlbums.ts b/client/src/api/searchAlbums.ts index eb5a00c..1261985 100644 --- a/client/src/api/searchAlbums.ts +++ b/client/src/api/searchAlbums.ts @@ -6,7 +6,10 @@ import type { TypedDocumentNode } from '@apollo/client'; export const ALBUM_SORTS = [ 'RELEVANCE', 'TITLE_ASC', + 'TITLE_DESC', + 'RELEASE_YEAR_ASC', 'RELEASE_YEAR_DESC', + 'AVERAGE_RATING_ASC', 'AVERAGE_RATING_DESC', ] as const; diff --git a/client/src/components/ResultsLayout.css b/client/src/components/ResultsLayout.css index 653b2fb..b1ed5c9 100644 --- a/client/src/components/ResultsLayout.css +++ b/client/src/components/ResultsLayout.css @@ -1,6 +1,13 @@ .results { padding-bottom: 2.5rem; } +.results-header { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 0.5rem 1rem; +} .album-grid { list-style: none; margin: 0; diff --git a/client/src/components/ResultsLayout.tsx b/client/src/components/ResultsLayout.tsx index 8b9c0e8..9bf9ce0 100644 --- a/client/src/components/ResultsLayout.tsx +++ b/client/src/components/ResultsLayout.tsx @@ -1,12 +1,15 @@ import './ResultsLayout.css'; import AlbumCard from './AlbumCard.js'; -import type { AlbumSummary } from '../api/searchAlbums.js'; +import SortSelect from './SortSelect.js'; +import type { AlbumSort, AlbumSummary } from '../api/searchAlbums.js'; interface Props { albums: AlbumSummary[]; totalCount: number; hasQuery: boolean; + sort: AlbumSort; + onSortChange: (sort: AlbumSort) => void; loading: boolean; retrying: boolean; error: boolean; @@ -21,7 +24,12 @@ export default function ResultsLayout(props: Props) { aria-labelledby="results-heading" aria-busy={props.loading} > -

Search results

+
+

Search results

+ {props.hasQuery && ( + + )} +

{!props.hasQuery ? 'Search for an album or artist to get started.' diff --git a/client/src/components/SortSelect.css b/client/src/components/SortSelect.css new file mode 100644 index 0000000..0264698 --- /dev/null +++ b/client/src/components/SortSelect.css @@ -0,0 +1,17 @@ +.sort-select { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.9rem; +} +.sort-select label { + color: var(--muted); +} +.sort-select select { + padding: 0.45rem 0.6rem; + border: 1px solid var(--border-strong); + border-radius: 6px; + background: var(--surface); + color: var(--text); + font: inherit; +} diff --git a/client/src/components/SortSelect.test.tsx b/client/src/components/SortSelect.test.tsx new file mode 100644 index 0000000..7022c7e --- /dev/null +++ b/client/src/components/SortSelect.test.tsx @@ -0,0 +1,24 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, within } from '@testing-library/react'; +import SortSelect from './SortSelect.js'; +import { ALBUM_SORTS } from '../api/searchAlbums.js'; + +describe('SortSelect', () => { + it('is labelled and offers every sort the schema accepts', () => { + render(); + const select = screen.getByRole('combobox', { name: 'Sort by' }); + const values = within(select) + .getAllByRole('option') + .map((option) => (option as HTMLOptionElement).value); + expect([...values].sort()).toEqual([...ALBUM_SORTS].sort()); + }); + + it('shows the current sort and reports a change', () => { + const onSortChange = vi.fn(); + render(); + const select = screen.getByRole('combobox', { name: 'Sort by' }); + expect(select).toHaveValue('TITLE_ASC'); + fireEvent.change(select, { target: { value: 'AVERAGE_RATING_DESC' } }); + expect(onSortChange).toHaveBeenCalledExactlyOnceWith('AVERAGE_RATING_DESC'); + }); +}); diff --git a/client/src/components/SortSelect.tsx b/client/src/components/SortSelect.tsx new file mode 100644 index 0000000..476f29a --- /dev/null +++ b/client/src/components/SortSelect.tsx @@ -0,0 +1,60 @@ +import './SortSelect.css'; + +import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js'; + +const LABELS: Record = { + RELEVANCE: 'Best match', + TITLE_ASC: 'Title A–Z', + TITLE_DESC: 'Title Z–A', + RELEASE_YEAR_DESC: 'Newest first', + RELEASE_YEAR_ASC: 'Oldest first', + AVERAGE_RATING_DESC: 'Highest rated', + AVERAGE_RATING_ASC: 'Lowest rated', +}; + +// Grouped by what is being sorted rather than in enum order. +const OPTIONS: readonly AlbumSort[] = [ + 'RELEVANCE', + 'TITLE_ASC', + 'TITLE_DESC', + 'RELEASE_YEAR_DESC', + 'RELEASE_YEAR_ASC', + 'AVERAGE_RATING_DESC', + 'AVERAGE_RATING_ASC', +]; + +interface Props { + sort: AlbumSort; + onSortChange: (sort: AlbumSort) => void; +} + +function isAlbumSort(value: string): value is AlbumSort { + return (ALBUM_SORTS as readonly string[]).includes(value); +} + +/** + * A native select, so keyboard and screen reader support come from the + * browser. Changing it only writes the URL: the order itself comes from the + * server, over the whole result set, never from rearranging loaded cards. + */ +export default function SortSelect({ sort, onSortChange }: Props) { + return ( +

+ + +
+ ); +} diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index 22d248d..0db13a3 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -8,7 +8,7 @@ import { useSearchState } from './useSearchState.js'; const PAGE_SIZE = 20; export function useAlbumSearch() { - const { state, setQuery } = useSearchState(); + const { state, setQuery, setSort } = useSearchState(); const query = state.q; const hasQuery = query.length > 0; const retryInFlight = useRef(false); @@ -67,6 +67,8 @@ export function useAlbumSearch() { return { query, + sort: state.sort, + setSort, search, hasQuery, albums: hasQuery ? (data?.searchAlbums.edges.map((edge) => edge.node) ?? []) : [], diff --git a/client/src/hooks/useSearchState.test.ts b/client/src/hooks/useSearchState.test.ts index 561d365..7cb1e12 100644 --- a/client/src/hooks/useSearchState.test.ts +++ b/client/src/hooks/useSearchState.test.ts @@ -34,7 +34,7 @@ describe('parseSearchState', () => { }); it('falls back to the default sort for a value the schema does not accept', () => { - expect(parseSearchState('?sort=TITLE_DESC').sort).toBe(DEFAULT_SORT); + expect(parseSearchState('?sort=YEAR_DESC').sort).toBe(DEFAULT_SORT); expect(parseSearchState('?sort=').sort).toBe(DEFAULT_SORT); expect(parseSearchState('?').sort).toBe(DEFAULT_SORT); }); From 7d4d869b725baaadfda3a647aa7ce457c9fad044 Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 20:09:41 +0100 Subject: [PATCH 4/6] docs: #12 log AI usage --- docs/AI-USAGE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index c3b744c..4f10b39 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -65,6 +65,7 @@ the part that matters most. | 2026-10-22 | erikhfj | opencode | #18, dark theme under `prefers-color-scheme`. Lifted the eight hard-coded colours into custom properties first so the light palette stays byte-identical. Did not take the generated palette as-is: `--border-strong` at `#556055` measured 2.5:1 against the surface, under the 3:1 a form-control border needs, so it became `#6b766b` at 3.4:1. Computed every ratio by hand rather than trusting the values that came back. | | 2026-10-22 | erikhfj | opencode | #17, axe-core over all four states of the search page. A green suite proves nothing on its own, so the harness asserts axe found passing rules before asserting it found no violations, and I checked it against a deliberately broken tree first to confirm it reports failures. `color-contrast` is disabled because jsdom paints nothing; that limitation is written into the PR rather than quietly omitted. | | 2026-10-23 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing prefix search (#55), performance testing with 100,000 albums, and updating documentation. | +| 2026-10-26 | evenkkl | Claude | #12, server-side sorting. Read the issue first; it settles the names (`RELEASE_YEAR`, `AVERAGE_RATING`) and that the rating sorts need a stored column, not a live `AVG()`. Claude added the five missing sorts with keyset cursors, `album.average_rating` kept current by a trigger on `review`, the sort control above the results via `setSort`, and tests. I had the trigger and paging across rating ties checked against a real PostgreSQL instance, not only the generated SQL. | ## Notes From c36711f68449e6e040f31aa5e293b389d3a676ec Mon Sep 17 00:00:00 2001 From: Even Date: Wed, 28 Oct 2026 16:14:55 +0100 Subject: [PATCH 5/6] docs: #12 update README status for sorting and paging --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 84d220a..18654e9 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ Repository for team IT2810-H26-T19 in IT2810-H26. -**Crate** is an album catalog where users can search for music. The GraphQL API -already supports filtering, sorting and cursor-based pagination, while the -frontend controls for these features are planned for later milestones. Album -details, ratings, reviews and a personal wantlist ("crate") are also planned. +**Crate** is an album catalog where users can search for music, sort and page +through the results, open an album for detail, rate and review it, and add it to +a personal wantlist ("crate"). The GraphQL API also supports genre and decade +filters; the frontend filter controls are planned. IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`. @@ -228,15 +228,15 @@ The two `AlbumDetailPage` rows represent the separate chunks for the album detai | `schema.graphql` | GraphQL schema | | `docs/` | Architecture, data model, UI, workflow, AI log and VM guide | -**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items. The GraphQL backend supports album and artist search, genre and decade filters, sorting and cursor-based pagination. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results. +**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items, with a real catalog imported from MusicBrainz. The GraphQL backend supports album and artist search, genre and decade filters, sorting, cursor-based pagination, album details, reviews and adding or removing albums from the crate. Users are simulated: the client sends an `X-User-Id` header on every request and the server reads it into the request context. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results. -The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. +The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance, and the sort control re-queries the server so the new order covers the whole result set. The sort is kept in the URL with the query. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. Opening an album shows its tracks, average rating and reviews, and lets the user write, edit or delete their own review. Albums can be added to or removed from the crate from the results and the album page. -**Planned:** Frontend filters and sorting controls; album details; reviews, ratings and wantlist functionality; and Playwright end-to-end tests (M4). The database tables for reviews and crate items exist, but their GraphQL functionality is still planned. `X-User-Id` is also defined but not yet handled at runtime. Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker. +**Planned:** Frontend filter controls (#13), a page listing the user's crate (`myCrate`), and Playwright end-to-end tests (M4). Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker. ### Backend search behavior -The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. These capabilities are available through GraphQL but are not all exposed in the frontend yet. +The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. Everything except the filters and facet counts is exposed in the frontend. ## Try the application From 989bfc8b77b134545c369192ddc67b2712a4dfe0 Mon Sep 17 00:00:00 2001 From: Even Date: Wed, 28 Oct 2026 16:14:55 +0100 Subject: [PATCH 6/6] docs: #12 log AI usage for review fixes --- docs/AI-USAGE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 762199d..70438c8 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -71,6 +71,7 @@ the part that matters most. | 2026-10-26 | robertky | Codex (ChatGPT) | Assisted me when I implemented #16: idempotent add/remove mutations, per-request crate-state loading, and accessible list/detail toggles. I reviewed the implementation and test results before using it. | | 2026-10-26 | evenkkl | Claude | #12, server-side sorting. Read the issue first; it settles the names (`RELEASE_YEAR`, `AVERAGE_RATING`) and that the rating sorts need a stored column, not a live `AVG()`. Claude added the five missing sorts with keyset cursors, `album.average_rating` kept current by a trigger on `review`, the sort control above the results via `setSort`, and tests. I had the trigger and paging across rating ties checked against a real PostgreSQL instance, not only the generated SQL. | | 2026-10-27 | robertky | Codex (ChatGPT) | Assisted me with #63's MusicBrainz snapshot fetcher, non-destructive catalog import and documentation. | +| 2026-10-28 | evenkkl | Claude | #12, review fixes on #66. Robert asked for an up-to-date branch, a correct README and green CI. Claude merged main, renumbered our migration to `0003` after #63's `0002`, kept both sides of the other conflicts, fixed a duplicate import from the merge, updated the README status sections and added the sort control to the Load more keyboard test. I checked the diff against main contains only our sorting work and these fixes. | ## Notes