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
13 changes: 13 additions & 0 deletions backend/migrations/1794490684727_review-half-stars.sql
Original file line number Diff line number Diff line change
@@ -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);
28 changes: 26 additions & 2 deletions backend/src/loaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<number, WineRow | null>(async (ids) => {
Expand All @@ -63,6 +68,25 @@ export function createLoaders() {
});
});

const ratingDistributions = new DataLoader<number, RatingCount[]>(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<number, DataLoader<number, ReviewRow[]>>();

Expand All @@ -89,7 +113,7 @@ export function createLoaders() {
return loader;
}

return { wines, studentRatings, reviews };
return { wines, studentRatings, ratingDistributions, reviews };
}

export type Loaders = ReturnType<typeof createLoaders>;
Expand Down
38 changes: 38 additions & 0 deletions backend/src/rating-stats.ts
Original file line number Diff line number Diff line change
@@ -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
`;
24 changes: 17 additions & 7 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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.
Expand All @@ -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;
},
},

Expand All @@ -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);
Expand Down
8 changes: 4 additions & 4 deletions backend/src/review-input.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
});
Expand Down
10 changes: 6 additions & 4 deletions backend/src/review-input.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
18 changes: 13 additions & 5 deletions backend/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -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!
Expand All @@ -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
}
Expand Down
16 changes: 2 additions & 14 deletions backend/src/scripts/seed-xwines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<string, string>) {
const grapes = parseTextList(row.Grapes);
return {
Expand Down Expand Up @@ -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.');
}

Expand Down
5 changes: 4 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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 }
}
}
Expand Down