From b8a2c29e7e47e380295008608bfc405684690778 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Thu, 12 Nov 2026 14:41:32 +0100 Subject: [PATCH 1/2] feat(backend): allow half stars from 0.5 to 5 in reviews (#51) --- .../migrations/1794490684727_review-half-stars.sql | 13 +++++++++++++ backend/src/review-input.test.ts | 8 ++++---- backend/src/review-input.ts | 10 ++++++---- 3 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 backend/migrations/1794490684727_review-half-stars.sql diff --git a/backend/migrations/1794490684727_review-half-stars.sql b/backend/migrations/1794490684727_review-half-stars.sql new file mode 100644 index 0000000..a09873a --- /dev/null +++ b/backend/migrations/1794490684727_review-half-stars.sql @@ -0,0 +1,13 @@ +-- Up Migration + +-- Student reviews use half stars from 0.5 to 5, the same steps as the X-Wines ratings. +ALTER TABLE review DROP CONSTRAINT review_rating_check; +ALTER TABLE review ALTER COLUMN rating TYPE numeric(2, 1); +ALTER TABLE review ADD CONSTRAINT review_rating_check + CHECK (rating BETWEEN 0.5 AND 5 AND rating * 2 = round(rating * 2)); + +-- Down Migration + +ALTER TABLE review DROP CONSTRAINT review_rating_check; +ALTER TABLE review ALTER COLUMN rating TYPE smallint USING round(rating); +ALTER TABLE review ADD CONSTRAINT review_rating_check CHECK (rating BETWEEN 1 AND 5); \ No newline at end of file diff --git a/backend/src/review-input.test.ts b/backend/src/review-input.test.ts index 968f530..1cd69cd 100644 --- a/backend/src/review-input.test.ts +++ b/backend/src/review-input.test.ts @@ -9,14 +9,14 @@ describe('validateReviewInput', () => { expect(review).toEqual({ wineId: 100062, userId: USER_ID, rating: 5, comment: 'Godt!' }); }); - it('accepts', () => { - for (const rating of [1, 2, 3, 4, 5]) { + it('accepts whole and half stars from 0.5 to 5', () => { + for (const rating of [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]) { expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating }).rating).toBe(rating); } }); - it('rejects ratings outside the range and half values', () => { - for (const rating of [0, 6, -1, 3.5]) { + it('rejects ratings outside the range and values that are not half stars', () => { + for (const rating of [0, 5.5, 6, -1, 1.25, 3.3]) { expect(() => validateReviewInput({ wineId: '1', userId: USER_ID, rating })).toThrow('rating'); } }); diff --git a/backend/src/review-input.ts b/backend/src/review-input.ts index 8a995ba..60e6283 100644 --- a/backend/src/review-input.ts +++ b/backend/src/review-input.ts @@ -1,8 +1,9 @@ // Checks and cleans the input to saveReview. Kept separate from the database so it is easy to test. import { GraphQLError } from 'graphql'; -export const MIN_RATING = 1; -export const MAX_RATING = 5; // Die roll. Change together with the CHECK in the review migration. + // Half stars from 0.5 to 5. Change together with the CHECK in the review migrations. +export const MIN_RATING = 0.5; +export const MAX_RATING = 5; export const MAX_COMMENT_LENGTH = 500; export interface ReviewInput { @@ -38,8 +39,9 @@ export function validateUserId(value: string): string { export function validateReviewInput(input: ReviewInput): ValidReview { const { rating } = input; - if (!Number.isInteger(rating) || rating < MIN_RATING || rating > MAX_RATING) { - throw badInput(`The rating must be a whole number from ${MIN_RATING} to ${MAX_RATING}.`); + // Whole or half stars: the rating times two must be a whole number. + if (!Number.isInteger(rating * 2) || rating < MIN_RATING || rating > MAX_RATING) { + throw badInput(`The rating must be from ${MIN_RATING} to ${MAX_RATING} in half stars.`); } // An empty or blank comment is stored as no comment. From d1a1e1104da2186e681479722f34d9ea74bba584 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Thu, 12 Nov 2026 15:01:15 +0100 Subject: [PATCH 2/2] feat(backend): shared average and rating distribution with student reviews (#51) --- backend/src/loaders.ts | 28 ++++++++++++++++++++-- backend/src/rating-stats.ts | 38 ++++++++++++++++++++++++++++++ backend/src/resolvers.ts | 24 +++++++++++++------ backend/src/schema.ts | 18 ++++++++++---- backend/src/scripts/seed-xwines.ts | 16 ++----------- docs/api.md | 5 +++- 6 files changed, 100 insertions(+), 29 deletions(-) create mode 100644 backend/src/rating-stats.ts diff --git a/backend/src/loaders.ts b/backend/src/loaders.ts index b7349e4..ce29bb5 100644 --- a/backend/src/loaders.ts +++ b/backend/src/loaders.ts @@ -29,7 +29,7 @@ export interface ReviewRow { id: number; wine_id: number; student_id: number; - rating: number; + rating: string; // pg returns numeric columns as strings comment: string | null; created_at: Date; updated_at: Date; @@ -40,6 +40,11 @@ export interface StudentRating { count: number; } +export interface RatingCount { + rating: number; + count: number; +} + /** New loaders for every request, so data is never cached between users or requests. */ export function createLoaders() { const wines = new DataLoader(async (ids) => { @@ -63,6 +68,25 @@ export function createLoaders() { }); }); + const ratingDistributions = new DataLoader(async (wineIds) => { + const result = await pool.query<{ wine_id: number; rating: number; count: number }>( + `SELECT wine_id, rating::float AS rating, count(*)::int AS count + FROM ( + SELECT wine_id, rating FROM community_rating WHERE wine_id = ANY($1) + UNION ALL + SELECT wine_id, rating FROM review WHERE wine_id = ANY($1) + ) AS all_ratings + GROUP BY wine_id, rating + ORDER BY rating DESC`, + [[...wineIds]], + ); + return wineIds.map((id) => + result.rows + .filter((row) => row.wine_id === id) + .map(({ rating, count }) => ({ rating, count })), + ); + }); + // One loader per page size, because "first" is part of the query. const reviewLoaders = new Map>(); @@ -89,7 +113,7 @@ export function createLoaders() { return loader; } - return { wines, studentRatings, reviews }; + return { wines, studentRatings, ratingDistributions, reviews }; } export type Loaders = ReturnType; diff --git a/backend/src/rating-stats.ts b/backend/src/rating-stats.ts new file mode 100644 index 0000000..455236f --- /dev/null +++ b/backend/src/rating-stats.ts @@ -0,0 +1,38 @@ +// The average and count stored on the wine table include every rating: from the X-Wines +// community and from our students. They are stored on the wine, so sorting and filtering by +// rating never has to count all the ratings. + +const ALL_RATINGS = ` + SELECT wine_id, rating FROM community_rating + UNION ALL + SELECT wine_id, rating FROM review +`; + +/** Recalculates the average and count for every wine. Used after an import. */ +export const UPDATE_ALL_RATING_STATS = ` + UPDATE wine SET + community_avg = stats.avg_rating, + community_count = stats.rating_count + FROM ( + SELECT wine_id, round(avg(rating), 2) AS avg_rating, count(*) AS rating_count + FROM (${ALL_RATINGS}) AS all_ratings + GROUP BY wine_id + ) AS stats + WHERE wine.id = stats.wine_id +`; + +/** + * Recalculates the average and count for one wine ($1). Used after a review is saved or deleted. + * Without ratings, the average becomes null and the count 0. + */ +export const UPDATE_WINE_RATING_STATS = ` + UPDATE wine SET + community_avg = stats.avg_rating, + community_count = stats.rating_count + FROM ( + SELECT round(avg(rating), 2) AS avg_rating, count(*) AS rating_count + FROM (${ALL_RATINGS}) AS all_ratings + WHERE wine_id = $1 + ) AS stats + WHERE wine.id = $1 +`; \ No newline at end of file diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index 0265c05..eccec16 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -16,6 +16,7 @@ import { type FilterArgs, type WinesArgs, } from './wine-query'; +import { UPDATE_WINE_RATING_STATS } from './rating-stats'; // The most reviews one query can ask for. const MAX_REVIEWS = 50; @@ -48,7 +49,7 @@ function toReview(row: ReviewRow) { return { id: String(row.id), wineId: row.wine_id, - rating: row.rating, + rating: Number(row.rating), comment: row.comment, author: authorName(row.student_id), createdAt: row.created_at.toISOString(), @@ -145,6 +146,8 @@ export const resolvers = { RETURNING *`, [review.wineId, review.userId, review.rating, review.comment], ); + // The new review counts in the wine's average right away. + await pool.query(UPDATE_WINE_RATING_STATS, [review.wineId]); return toReview(result.rows[0]); } catch (error) { // 23503 = foreign key violation: the wine does not exist. @@ -156,13 +159,16 @@ export const resolvers = { }, async deleteReview(_parent: unknown, args: { wineId: string; userId: string }) { - const result = await pool.query( - `DELETE FROM review - USING student - WHERE review.student_id = student.id AND review.wine_id = $1 AND student.user_id = $2`, - [validateWineId(args.wineId), validateUserId(args.userId)], + const wineId = validateWineId(args.wineId); + const result = await pool.query( + `DELETE FROM review + USING student + WHERE review.student_id = student.id AND review.wine_id = $1 AND student.user_id = $2`, + [wineId, validateUserId(args.userId)], ); - return (result.rowCount ?? 0) > 0; + const deleted = (result.rowCount ?? 0) > 0; + if (deleted) await pool.query(UPDATE_WINE_RATING_STATS, [wineId]); + return deleted; }, }, @@ -180,6 +186,10 @@ export const resolvers = { return loaders.studentRatings.load(Number(wine.id)); }, + ratingDistribution(wine: { id: string }, _args: unknown, { loaders }: Context) { + return loaders.ratingDistributions.load(Number(wine.id)); + }, + async reviews(wine: { id: string }, args: { first?: number | null }, { loaders }: Context) { const rows = await loaders.reviews(limitReviews(args.first, 10)).load(Number(wine.id)); return rows.map(toReview); diff --git a/backend/src/schema.ts b/backend/src/schema.ts index b5710fa..3c9572a 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -37,9 +37,12 @@ export const typeDefs = `#graphql wineryName: String website: String vintages: [Int!]! - "Average X-Wines rating (1-5), or null if nobody has rated the wine." + "Average of all ratings (0.5-5), from X-Wines and from students, or null if nobody has rated the wine." communityRating: Float + "Number of ratings, from X-Wines and from students." communityRatingCount: Int! + "How many gave each score, from X-Wines and students together. Only scores someone has given, highest first." + ratingDistribution: [RatingCount!]! "Average die roll from students on Kork & Krone." studentRating: StudentRating! "The newest student reviews of this wine." @@ -78,16 +81,21 @@ export const typeDefs = `#graphql harmonize: [FilterOption!]! } + type RatingCount { + rating: Float! + count: Int! + } + type StudentRating { - "Average die roll (1-6), or null if no student has reviewed the wine." + "Average stars (0.5-5), or null if no student has reviewed the wine." average: Float count: Int! } type Review { id: ID! - "Rating 1 to 5." - rating: Int! + "Stars 0.5 to 5 in half stars." + rating: Float! comment: String "Display name such as 'Student #4821'. The user ID is never shown." author: String! @@ -100,7 +108,7 @@ export const typeDefs = `#graphql wineId: ID! "The anonymous ID stored in the browser." userId: ID! - rating: Int! + rating: Float! comment: String } diff --git a/backend/src/scripts/seed-xwines.ts b/backend/src/scripts/seed-xwines.ts index ed6b730..beb8363 100644 --- a/backend/src/scripts/seed-xwines.ts +++ b/backend/src/scripts/seed-xwines.ts @@ -5,6 +5,7 @@ import { readFileSync } from 'node:fs'; import { parseCsv } from '../csv'; import { pool } from '../db'; import { parseNumber, parseTextList, parseYearList, toSearchText } from '../xwines-parse'; +import { UPDATE_ALL_RATING_STATS } from '../rating-stats'; const BATCH_SIZE = 1000; @@ -39,19 +40,6 @@ const INSERT_RATINGS = ` ON CONFLICT (id) DO NOTHING `; -// Calculated once here, so sorting by rating never has to count all ratings. -const UPDATE_COMMUNITY_STATS = ` - UPDATE wine SET - community_avg = stats.avg_rating, - community_count = stats.rating_count - FROM ( - SELECT wine_id, round(avg(rating), 2) AS avg_rating, count(*) AS rating_count - FROM community_rating - GROUP BY wine_id - ) AS stats - WHERE wine.id = stats.wine_id -`; - function toWineRow(row: Record) { const grapes = parseTextList(row.Grapes); return { @@ -106,7 +94,7 @@ async function main() { console.log(`Saved ${wines.length} wines.`); await insertInBatches(INSERT_RATINGS, ratings); console.log(`Saved ${ratings.length} ratings.`); - await pool.query(UPDATE_COMMUNITY_STATS); + await pool.query(UPDATE_ALL_RATING_STATS); console.log('Updated average ratings.'); } diff --git a/docs/api.md b/docs/api.md index 387f5b9..5fb2983 100644 --- a/docs/api.md +++ b/docs/api.md @@ -56,13 +56,15 @@ During development, Vite forwards `/graphql` to the backend. On the VM, Apache f ## Student reviews -A review is 1 to 5 stars and an optional comment (max 500 characters). +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), 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. Each user has one review per wine. Saving again replaces the old review, including the comment. + Student reviews count in `communityRating` and `communityRatingCount` on every wine, together with the X-Wines ratings. The average is calculated again every time a review is saved or deleted, so sorting and filtering by rating also follow the students. `ratingDistribution` gives how many gave each score, for example to draw a bar chart on the wine page. + ```graphql mutation SaveReview($input: ReviewInput!) { saveReview(input: $input) { id rating comment author updatedAt } @@ -71,6 +73,7 @@ mutation SaveReview($input: ReviewInput!) { query WineReviews($id: ID!) { wine(id: $id) { studentRating { average count } + ratingDistribution { rating count } reviews(first: 10) { id rating comment author updatedAt } } }