From 45a7d322c76c1eb04d56e1dbfbeb0149a5649b44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 14:28:05 +0100 Subject: [PATCH 1/2] chore(data): write real seed descriptions and seed demo ratings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace the generated "A homemade … recipe" filler with a hand-written description for each of the 51 demo recipes, checked against their ingredients and steps. Seeding now fails if a recipe has none. - Add four demo taster accounts that give deterministic 3-5 star ratings to about 80 % of the public demo recipes, so Highest rated sorting has data. Private recipes are not rated. Re-running the seed adds nothing. Not done here (needs the team and VM access): deleting the "4" test recipe from production and re-running the seed on the VM. Refs #75 --- apps/api/src/db/seedData.ts | 47 ++++++++++++++ apps/api/src/db/seedRecipes.ts | 108 +++++++++++++++++++++++++++++++-- scripts/test-recipe-api.ts | 36 +++++++++++ 3 files changed, 185 insertions(+), 6 deletions(-) diff --git a/apps/api/src/db/seedData.ts b/apps/api/src/db/seedData.ts index 3bf04a6..0b45577 100644 --- a/apps/api/src/db/seedData.ts +++ b/apps/api/src/db/seedData.ts @@ -11,6 +11,10 @@ import { seedRecipes } from './seedRecipes.js'; const AUTHOR_ID = '11111111-1111-4111-8111-111111111111'; +// Extra demo accounts that rate the public demo recipes (see seedRatings). +const TASTER_COUNT = 4; +const RATING_SCORES = [3, 4, 4, 5, 5] as const; + const IMAGE_SOURCE_DIR = fileURLToPath( new URL('./seed-images/', import.meta.url), ); @@ -223,9 +227,52 @@ export async function seedDatabase( console.log(`Seeded: ${recipe.title}`); } + /* + * Demo ratings, so "Highest rated" has data to sort. Four taster + * accounts (sharing SEED_PASSWORD) rate about 80 % of the public + * recipes with 3–5 stars. Scores come from a hash of recipe and taster, + * so every run produces the same data. Existing users and ratings are + * kept, as for the rest of the seed. Private recipes are not rated, as + * the API also forbids it. + */ + let ratingCount = 0; + for (let taster = 1; taster <= TASTER_COUNT; taster += 1) { + const tasterId = stableUuid(`taster:${taster}`); + await client.query( + `INSERT INTO ${schema}.users (id, name, email, password_hash) + VALUES ($1, $2, $3, $4) + ON CONFLICT DO NOTHING`, + [ + tasterId, + `Demo Taster ${taster}`, + `demo-taster-${taster}@example.invalid`, + passwordHash, + ], + ); + for (const item of prepared) { + if (item.recipe.visibility !== 'public') continue; + const hash = createHash('sha256') + .update(`rating:${item.recipe.slug}:${taster}`) + .digest(); + if (hash[0]! % 5 === 0) continue; // About one in five is left unrated. + const result = await client.query( + `INSERT INTO ${schema}.ratings (recipe_id, user_id, score) + VALUES ($1, $2, $3) + ON CONFLICT DO NOTHING`, + [ + item.recipeId, + tasterId, + RATING_SCORES[hash[1]! % RATING_SCORES.length], + ], + ); + ratingCount += result.rowCount ?? 0; + } + } + await client.query('COMMIT'); console.log(`Successfully seeded ${prepared.length} recipes.`); + console.log(`Added ${ratingCount} demo ratings.`); } catch (error) { await client.query('ROLLBACK'); throw error; diff --git a/apps/api/src/db/seedRecipes.ts b/apps/api/src/db/seedRecipes.ts index 5061940..5b6730e 100644 --- a/apps/api/src/db/seedRecipes.ts +++ b/apps/api/src/db/seedRecipes.ts @@ -574,17 +574,112 @@ const recipes: Record = { const PRIVATE_RECIPES = new Set(['raw-egg', 'car-muffin']); -const DESCRIPTION_OVERRIDES: Record = { +/* + * Hand-written card descriptions, one per recipe (max 200 characters, the + * same limit the API enforces). Seeding fails if a recipe has none, so new + * demo recipes cannot fall back to generated filler text. + */ +const DESCRIPTIONS: Record = { lasagna: 'A comforting Italian-style lasagna layered with rich beef tomato sauce, pasta sheets, creamy béchamel and melted mozzarella.', - 'norsk-matpakke': - 'A traditional Norwegian packed lunch with wholegrain bread, cheese and fresh toppings. Simple, practical and perfect for work or school.', + 'fish-burger': + 'Breaded white fish fried until crisp, served in a toasted bun with lettuce and a quick lemon mayonnaise.', + 'beef-burger': + 'A juicy beef patty with melted cheddar, crisp lettuce and tomato in a soft bun. Ready in half an hour.', + 'potato-boats': + 'Baked potatoes scooped out, mashed with butter and cheddar, refilled and baked until golden. Served with sour cream.', + 'baked-potatoes': + 'Crisp-skinned oven potatoes with a fluffy inside. Serve with butter and sea salt, or as a side for fish and meat.', + shells: + 'Pasta shells in a creamy garlic and Parmesan sauce. A quick weeknight dinner made with pantry staples.', + salmon: + 'Salmon fillets brushed with lemon, dill and garlic, then baked. Light, quick and good with potatoes or vegetables.', + cod: 'Tender cod baked in butter with lemon and parsley. A simple Nordic dinner that is ready in under 30 minutes.', + 'fried-chicken': + 'Chicken thighs marinated in buttermilk, coated in paprika-spiced flour and fried until golden and crunchy.', + 'beef-dinner': + 'Pan-seared beef steaks with buttery potatoes and green beans. A classic plate for a slightly special evening.', + sausage: + 'Sausages roasted on one tray with sweet bell peppers and red onion. Few dishes to wash and lots of flavour.', + 'fried-sausages': + 'Sausages fried with slowly softened onions in butter. A hearty breakfast or a quick lunch.', + 'fish-n-chips': + 'Cod in a light, crisp batter made with sparkling water, served with thick-cut chips. A British favourite at home.', + masala: + 'A mild vegetable curry with chickpeas, tomatoes and coconut milk, warmed by garam masala and fresh ginger.', + 'tiki-masala': + 'Yogurt-marinated chicken simmered in a creamy, spiced tomato sauce. Serve with rice or naan.', + 'roasted-chicken': + 'A whole chicken roasted with herb butter, lemon and garlic until the skin is golden. Great for Sunday dinner.', + 'indian-dish-with-rice': + 'Chickpeas simmered in a spiced tomato and onion sauce, served over fluffy basmati rice. Vegetarian and filling.', + 'yellow-rice-with-chikcen': + 'Chicken and rice cooked together in one pot with turmeric and broth, giving every grain a warm golden colour.', + 'peanut-soup': + 'A rich soup of sweet potato, peanut butter and tomato, inspired by West African groundnut stews.', + 'tomato-soup': + 'Ripe tomatoes, onion and garlic simmered and blended into a smooth, creamy soup. Perfect with grilled cheese.', + 'sweet-potato-soup': + 'Sweet potatoes blended with onion, garlic and broth into a velvety, naturally sweet soup.', + 'broth-soup': + 'A clear vegetable broth with carrots, celery and egg noodles. Light, warming and easy on the stomach.', + pancakes: + 'Thin Norwegian pancakes (pannekaker) made from a simple batter of flour, milk and eggs. Serve with jam or sugar.', + 'american-pancakes': + 'Thick, fluffy pancakes raised with baking powder. Stack them high and finish with syrup or berries.', + 'slovenian-pancakes': + 'Slovenian palačinke: thin crêpe-like pancakes rolled around jam. A favourite breakfast or dessert.', + 'peppered-eggs': + 'Softly scrambled eggs cooked slowly in butter with a splash of milk and plenty of black pepper.', + 'fried-egg': + 'Eggs fried gently in butter until the whites set and the yolks stay runny. Breakfast in ten minutes.', + 'english-breakfast': + 'Eggs, sausages, baked beans, mushrooms and toast on one plate. A full English breakfast for a slow morning.', + 'raw-egg': + 'Eggs simmered for 8–10 minutes for firm yolks, then cooled in cold water so they peel easily.', 'roasted-coffee-beans': 'A freshly brewed cup of filter coffee made from aromatic roasted coffee beans.', + 'shrimp-salad': + 'Cooked shrimp with avocado, cucumber and mixed lettuce, tossed in a light dressing. Fresh and quick.', + 'homemade-fries': + 'Potato sticks seasoned with paprika and garlic and baked until crisp, using far less oil than deep frying.', + 'grilled-cheese': + 'Sourdough fried in butter around melted cheddar with a thin layer of Dijon mustard. Crisp outside, gooey inside.', + 'norsk-matpakke': + 'A traditional Norwegian packed lunch with wholegrain bread, cheese and fresh toppings. Simple, practical and perfect for work or school.', + baguette: + 'A fresh baguette filled with ham, cheddar and crisp lettuce. A quick lunch to make in ten minutes.', + chips: + 'Thinly sliced potatoes baked with olive oil, sea salt and paprika until golden and crunchy.', + 'plain-rice': + 'Fluffy long-grain rice cooked by the absorption method, so the grains stay separate every time.', + cake: 'A classic vanilla sponge for birthdays and celebrations, ready to decorate however you like.', + 'carrot-cake': + 'A moist carrot cake spiced with cinnamon and topped with a smooth cream cheese frosting.', + 'orange-cake': + 'A soft, buttery sponge cake flavoured with the zest and juice of fresh oranges.', + 'vanilla-cake': + 'A simple, fluffy vanilla sponge. Good on its own with coffee or as the base for a layered cake.', 'car-cake': 'A colorful homemade birthday cake decorated in the shape of a car.', 'car-wheels-cake': 'A chocolate celebration cake with playful wheel-shaped decorations.', + 'oatmeal-muffin': + 'Wholesome muffins with rolled oats, lightly sweetened with honey, so they work for breakfast too.', + 'chocolate-muffin': + 'Rich cocoa muffins with chocolate chips folded into the batter. Soft, moist and quick to make.', + 'bringebær-muffins': + 'Light muffins packed with fresh raspberries (bringebær). Best eaten warm on the day they are baked.', + 'colored-cupcakes': + 'Vanilla cupcakes topped with swirls of brightly coloured frosting. Made for parties and birthdays.', + 'car-muffin': + 'Vanilla birthday muffins piped with buttercream icing and decorated as little cars.', + 'white-cookies': + 'Simple vanilla sugar cookies, rolled and cut into shapes. Decorate them with icing or enjoy them plain.', + 'gingerbread-cookies': + 'Traditional Nordic gingerbread (pepperkaker) spiced with ginger and cinnamon and sweetened with golden syrup.', + 'chocolate-cookies': + 'Soft and chewy cookies with brown sugar and plenty of chocolate chips. Ready in under 30 minutes.', }; function parseIngredients( @@ -634,12 +729,13 @@ export const seedRecipes: DemoRecipe[] = Object.entries(recipes).map( ? 'private' : 'public'; + const description = DESCRIPTIONS[slug]; + if (!description) throw new Error(`Missing seed description: ${slug}`); + return { slug, title, - description: - DESCRIPTION_OVERRIDES[slug] ?? - `A homemade ${title.toLowerCase()} recipe featuring flavorful ingredients and straightforward preparation. Suitable for ${category} and inspired by ${cuisine.toLowerCase()} cooking.`, + description, category, cuisine, difficulty, diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index 75befa0..2605e04 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -910,7 +910,43 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { ); assert.match(seededRecipe.image_url, /^\/uploads\/[a-f0-9-]+\.webp$/); + // Hand-written descriptions, not the old generated filler text. + assert.doesNotMatch(recipe.description, /^A homemade /); } + + // Demo tasters rate most public recipes and never private ones. + const rated = await pool.query<{ + visibility: string; + ratings: number; + min: number | null; + max: number | null; + }>( + `SELECT r.visibility, count(x.score)::int AS ratings, + min(x.score) AS min, max(x.score) AS max + FROM "${schema}".recipes r + LEFT JOIN "${schema}".ratings x ON x.recipe_id = r.id + WHERE r.author_id = $1 + GROUP BY r.id, r.visibility`, + ['11111111-1111-4111-8111-111111111111'], + ); + const publicRows = rated.rows.filter( + (row) => row.visibility === 'public', + ); + assert.ok( + publicRows.filter((row) => row.ratings > 0).length >= + publicRows.length * 0.8, + 'Most public demo recipes should have ratings.', + ); + assert.ok( + rated.rows + .filter((row) => row.visibility === 'private') + .every((row) => row.ratings === 0), + ); + assert.ok( + publicRows.every( + (row) => row.ratings === 0 || (row.min! >= 3 && row.max! <= 5), + ), + ); }, ); } finally { From 16824e5b0f6993775c13a5cd62cbef78bf6a5776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 19:04:43 +0100 Subject: [PATCH 2/2] fix(data): make the demo seed robust to taken taster emails Review on #94: - If another account already uses a taster address, the seed now skips that taster's ratings with a warning instead of failing a foreign key and rolling back the whole seed. - Registration refuses the reserved demo addresses (demo@ and demo-taster-N@example.invalid), answered like an existing email. - The seed test checks descriptions stored in the database, after first setting them to stale text, so it catches failed updates; it also covers a pre-existing account on a taster address. Refs #75 --- apps/api/src/db/demoAccounts.ts | 14 ++++++++++ apps/api/src/db/seedData.ts | 24 ++++++++++++----- .../api/src/features/auth/authService.test.ts | 14 ++++++++++ apps/api/src/features/auth/authService.ts | 4 ++- scripts/test-recipe-api.ts | 26 +++++++++++++++++-- 5 files changed, 72 insertions(+), 10 deletions(-) create mode 100644 apps/api/src/db/demoAccounts.ts diff --git a/apps/api/src/db/demoAccounts.ts b/apps/api/src/db/demoAccounts.ts new file mode 100644 index 0000000..1376d32 --- /dev/null +++ b/apps/api/src/db/demoAccounts.ts @@ -0,0 +1,14 @@ +/* + * E-mail addresses of the accounts created by the demo seed (seedData.ts). + * They use the reserved .invalid domain, and registration refuses them, so + * a real user can never take an address the seed relies on. + */ +export const DEMO_COOK_EMAIL = 'demo@example.invalid'; + +export function demoTasterEmail(taster: number) { + return `demo-taster-${taster}@example.invalid`; +} + +export function isReservedDemoEmail(email: string) { + return /^demo(-taster-\d+)?@example\.invalid$/i.test(email.trim()); +} diff --git a/apps/api/src/db/seedData.ts b/apps/api/src/db/seedData.ts index 0b45577..508fd76 100644 --- a/apps/api/src/db/seedData.ts +++ b/apps/api/src/db/seedData.ts @@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url'; import type { Pool } from 'pg'; import { seedRecipes } from './seedRecipes.js'; +import { DEMO_COOK_EMAIL, demoTasterEmail } from './demoAccounts.js'; const AUTHOR_ID = '11111111-1111-4111-8111-111111111111'; @@ -105,7 +106,7 @@ export async function seedDatabase( (id, name, email, password_hash) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING`, - [AUTHOR_ID, 'Demo Cook', 'demo@example.invalid', passwordHash], + [AUTHOR_ID, 'Demo Cook', DEMO_COOK_EMAIL, passwordHash], ); for (const item of prepared) { @@ -238,17 +239,26 @@ export async function seedDatabase( let ratingCount = 0; for (let taster = 1; taster <= TASTER_COUNT; taster += 1) { const tasterId = stableUuid(`taster:${taster}`); + const email = demoTasterEmail(taster); await client.query( `INSERT INTO ${schema}.users (id, name, email, password_hash) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`, - [ - tasterId, - `Demo Taster ${taster}`, - `demo-taster-${taster}@example.invalid`, - passwordHash, - ], + [tasterId, `Demo Taster ${taster}`, email, passwordHash], + ); + // If another account already uses the address (e.g. registered before + // it was reserved), the insert was skipped. Rating with tasterId would + // then break a foreign key and roll back the whole seed, so skip it. + const owner = await client.query<{ id: string }>( + `SELECT id FROM ${schema}.users WHERE email = $1`, + [email], ); + if (owner.rows[0]?.id !== tasterId) { + console.warn( + `Skipping demo ratings from ${email}: the address belongs to another account.`, + ); + continue; + } for (const item of prepared) { if (item.recipe.visibility !== 'public') continue; const hash = createHash('sha256') diff --git a/apps/api/src/features/auth/authService.test.ts b/apps/api/src/features/auth/authService.test.ts index 609c041..984f6d5 100644 --- a/apps/api/src/features/auth/authService.test.ts +++ b/apps/api/src/features/auth/authService.test.ts @@ -106,6 +106,20 @@ describe('authService', () => { expect(repository.createSession).not.toHaveBeenCalled(); }); + it('reserves the demo seed addresses', async () => { + const repository = createRepository(); + const service = createAuthService(repository, createPasswordHasher()); + + for (const email of [ + 'demo@example.invalid', + 'Demo-Taster-3@example.invalid', + ]) + await expect( + service.register('Hasan', email, 'secret123'), + ).rejects.toThrow('An account with this email already exists.'); + expect(repository.createUserWithSession).not.toHaveBeenCalled(); + }); + it('logs in with the correct password', async () => { const repository = createRepository({ findUserByEmail: vi.fn(async () => storedUser), diff --git a/apps/api/src/features/auth/authService.ts b/apps/api/src/features/auth/authService.ts index 4034ca6..44ef38b 100644 --- a/apps/api/src/features/auth/authService.ts +++ b/apps/api/src/features/auth/authService.ts @@ -1,3 +1,4 @@ +import { isReservedDemoEmail } from '../../db/demoAccounts.js'; import { loginSchema, registerSchema, @@ -54,7 +55,8 @@ export function createAuthService( const existingUser = await repository.findUserByEmail(normalizedEmail); - if (existingUser) { + // Demo seed addresses are reserved even before the seed has run. + if (existingUser || isReservedDemoEmail(normalizedEmail)) { throw new GraphQLError('An account with this email already exists.', { extensions: { code: 'EMAIL_TAKEN' }, }); diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts index 2605e04..b6ab80e 100644 --- a/scripts/test-recipe-api.ts +++ b/scripts/test-recipe-api.ts @@ -823,7 +823,25 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { await t.test( 'demo seed is repeatable and preserves existing passwords', async () => { + // Someone already holds one taster address (e.g. registered before it + // was reserved): the seed must still succeed, skipping that taster. + await pool.query( + `INSERT INTO "${schema}".users (name, email, password_hash) VALUES ('Squatter', 'demo-taster-2@example.invalid', 'x')`, + ); await seedDatabase(pool, 'demo-test-password', schema, imageDirectory); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS n FROM "${schema}".ratings x JOIN "${schema}".users u ON u.id = x.user_id WHERE u.email = 'demo-taster-2@example.invalid'`, + ) + ).rows[0].n, + 0, + ); + // Re-seeding must update descriptions already in the database. + await pool.query( + `UPDATE "${schema}".recipes SET description = 'Old generated text' WHERE author_id = $1`, + ['11111111-1111-4111-8111-111111111111'], + ); const originalHash = ( await pool.query( @@ -856,6 +874,7 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { const seeded = await pool.query<{ title: string; + description: string; visibility: string; image_url: string; ingredient_count: number; @@ -863,6 +882,7 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { }>( `SELECT r.title, + r.description, r.visibility, r.image_url, ( @@ -910,8 +930,10 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => { ); assert.match(seededRecipe.image_url, /^\/uploads\/[a-f0-9-]+\.webp$/); - // Hand-written descriptions, not the old generated filler text. - assert.doesNotMatch(recipe.description, /^A homemade /); + // The stored description is the hand-written one, also after the + // stale value set above (checks the database, not the seed input). + assert.equal(seededRecipe.description, recipe.description); + assert.doesNotMatch(seededRecipe.description, /^A homemade /); } // Demo tasters rate most public recipes and never private ones.