From df8f641ee843a77aef40117651e7e1137b0b9d7a Mon Sep 17 00:00:00 2001 From: Sven Rieseler <243339203+ChargingCrystal@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:16:16 +0100 Subject: [PATCH 1/2] Specify date category migration and validation --- tests/api-errors.test.ts | 15 +++++++++ tests/isolation.test.mjs | 68 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/tests/api-errors.test.ts b/tests/api-errors.test.ts index f82c4b1..dfc4763 100644 --- a/tests/api-errors.test.ts +++ b/tests/api-errors.test.ts @@ -157,6 +157,21 @@ test('returns internal for unexpected upstream errors without claiming a pairing await expectError(await request('GET', '/dashboard'), 500, 'internal') }) +test.each([ + ['POST', '/dates', { title: 'Cinema', category: 'Kino' }], + ['PATCH', '/dates/' + id, { category: 'cinema' }], + ['GET', '/dates?category=film'], + ['GET', '/dates?category='], + ['GET', '/dates?category=%20movie%20'], +] as const)('rejects a non-key category on %s %s before reaching Supabase', async (method, path, body) => { + if (method === 'POST') { + upstream.mockResolvedValueOnce(Response.json(id)) + } + upstream.mockResolvedValueOnce(Response.json(method === 'GET' ? [] : date)) + await expectError(await request(method, path, body ? JSON.stringify(body) : undefined), 400, 'validation_failed') + expect(upstream).not.toHaveBeenCalled() +}) + test.each([ { method: 'GET', path: '/health', schema: contract.healthResponseSchema, upstreamData: [] }, { method: 'GET', path: '/space', schema: contract.spaceResponseSchema, upstreamData: [space] }, diff --git a/tests/isolation.test.mjs b/tests/isolation.test.mjs index 0c0fbdc..41244a0 100644 --- a/tests/isolation.test.mjs +++ b/tests/isolation.test.mjs @@ -44,16 +44,21 @@ beforeEach(async () => { grant select, insert, delete on storage.objects to authenticated; `) users = (await pg.query('select id from auth.users order by id')).rows +}, 15_000) +async function migrate(seedLegacyDates) { const migrationFiles = (await readdir(migrations)) .filter(name => /^\d+_.+\.sql$/.test(name)) .sort((a, b) => a.localeCompare(b, 'en', { numeric: true })) for (const filename of migrationFiles) { await pg.exec(await readFile(new URL(filename, migrations), 'utf8')) + if (filename === '002_private_gallery.sql' && seedLegacyDates) { + await seedLegacyDates() + } } await pg.exec('set role authenticated') -}, 15_000) +} afterEach(async () => { await pg.close() @@ -62,6 +67,7 @@ afterEach(async () => { const login = i => pg.query("select set_config('request.jwt.claim.sub',$1,false)", [users[i].id]) test('pairing, one-time invite, shared dates, private locations and outsider isolation', async () => { + await migrate() await login(0) await pg.query('select create_space()') const { invite } = (await pg.query('select invite from spaces')).rows[0] @@ -85,6 +91,7 @@ test('pairing, one-time invite, shared dates, private locations and outsider iso }) test('a partner can read the other partner’s location', async () => { + await migrate() await login(0) await pg.query('select create_space()') const { invite } = (await pg.query('select invite from spaces')).rows[0] @@ -97,6 +104,7 @@ test('a partner can read the other partner’s location', async () => { }) test('dashboard returns the earliest upcoming planned meeting in the caller’s space', async () => { + await migrate() await login(1) await pg.query('select create_space()') await pg.query("insert into dates(title, category, meeting_at) values ('Other space', 'film', now() + interval '1 hour')") @@ -113,6 +121,7 @@ test('dashboard returns the earliest upcoming planned meeting in the caller’s }) test('the private gallery allows shared access and enforces space boundaries for reads, uploads and deletions', async () => { + await migrate() await login(0) const { id } = (await pg.query('select create_space() as id')).rows[0] const { invite } = (await pg.query('select invite from spaces')).rows[0] @@ -137,3 +146,60 @@ test('the private gallery allows shared access and enforces space boundaries for assert.deepEqual((await removePhoto()).rows, [{ name: photo }]) assert.deepEqual((await listPhotos()).rows, []) }) + +test('migrates legacy dates and combines localized aliases in the dashboard', async () => { + const mapping = [ + ['dinner', 'dinner'], + [' Abendessen ', 'dinner'], + ['AVONDETEN', 'dinner'], + ['movie', 'movie'], + ['film', 'movie'], + ['cinema', 'movie'], + ['\tKiNo\n', 'movie'], + ['bioscoop', 'movie'], + ['walk', 'walk'], + ['Spaziergang', 'walk'], + ['wandeling', 'walk'], + ['trip', 'trip'], + ['Ausflug', 'trip'], + ['uitstapje', 'trip'], + ['video_call', 'video_call'], + ['video call', 'video_call'], + ['Videoanruf', 'video_call'], + ['videobellen', 'video_call'], + ['game', 'game'], + ['Spiel', 'game'], + ['spel', 'game'], + ['other', 'other'], + ['Unknown legacy category', 'other'], + ] + const legacyDates = mapping.map(([category], index) => ({ + title: 'Legacy date ' + String(index).padStart(2, '0'), + category, + })) + await migrate(async () => { + await pg.exec('set role authenticated') + await login(0) + await pg.query('select create_space()') + for (const { title, category } of legacyDates) { + await pg.query("insert into dates(title, category, meeting_at) values ($1, $2, '2099-01-01T00:00:00Z')", [title, category]) + } + await pg.exec('reset role') + }) + + await login(0) + const { rows } = await pg.query('select title, category from dates order by title') + assert.deepEqual(rows, legacyDates.map(({ title }, index) => ({ title, category: mapping[index][1] }))) + const { data } = (await pg.query('select dashboard() as data')).rows[0] + assert.equal(data.categoriesByMonth.find(({ category }) => category === 'movie')?.total, 5) + assert.ok(mapping.some(([, category]) => category === data.nextMeeting.category)) +}) + +test('Postgres rejects unsupported categories on insert and update', async () => { + await migrate() + await login(0) + await pg.query('select create_space()') + await pg.query("insert into dates(title, category) values ('Cinema', 'movie')") + await assert.rejects(pg.query("insert into dates(title, category) values ('Cinema', 'cinema')"), { code: '23514' }) + await assert.rejects(pg.query("update dates set category = 'Movie'"), { code: '23514' }) +}) From be57e4a667bae583cf5a677fa0d5f31ee9ca46f3 Mon Sep 17 00:00:00 2001 From: Sven Rieseler <243339203+ChargingCrystal@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:18:55 +0100 Subject: [PATCH 2/2] Use fixed date category keys --- README.md | 20 +++++++---- shared/api-contract.ts | 10 +++--- shared/date-categories.ts | 11 ++++++ supabase/migrations/003_date_categories.sql | 40 +++++++++++++++++++++ tests/api-errors.test.ts | 17 ++++++--- tests/isolation.test.mjs | 20 +++++++---- 6 files changed, 97 insertions(+), 21 deletions(-) create mode 100644 shared/date-categories.ts create mode 100644 supabase/migrations/003_date_categories.sql diff --git a/README.md b/README.md index d1449bb..f6da0c0 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ cp .env.example .env Copy the public or anon key from `supabase status` to `NUXT_PUBLIC_SUPABASE_KEY` and start the app with `npm run dev`. Local Auth allows test signups without email confirmation. The home page links to the process health check. -For a new hosted Supabase project, apply both SQL migrations in numerical order. Set the public Supabase URL and key in Vercel, allow the app's HTTPS origin in Supabase Auth URL Configuration, and enable email confirmation for public signups. To enable Google login, configure the Google provider in Supabase Auth and register the callback URL shown there in the Google Console. +For a new hosted Supabase project, apply all SQL migrations in numerical order. Set the public Supabase URL and key in Vercel, allow the app's HTTPS origin in Supabase Auth URL Configuration, and enable email confirmation for public signups. To enable Google login, configure the Google provider in Supabase Auth and register the callback URL shown there in the Google Console. ## Auth and demo @@ -39,7 +39,7 @@ api() { api "$A" space -X POST CODE=$(api "$A" space | jq -r .invite) api "$B" space/join -d "$(jq -nc --arg code "$CODE" '{code:$code}')" -api "$A" dates -d '{"title":"Movie night","category":"cinema","meeting_at":"2027-01-15T18:00:00Z"}' +api "$A" dates -d '{"title":"Movie night","category":"movie","meeting_at":"2027-01-15T18:00:00Z"}' api "$B" dates api "$B" dashboard ``` @@ -54,17 +54,25 @@ Send `Authorization: Bearer ` on authenticated routes and `Accept: | `GET /api/space` | Bearer | — | `200` with `id`, `invite`, and `members`, or `204` when unpaired | `unauthorized`, `internal` | | `POST /api/space` | Bearer | — | `200` with the new space `id` | `already_paired`, `unauthorized`, `internal` | | `POST /api/space/join` | Bearer | JSON `code`, 32 lowercase hex characters | `200` with the joined space `id`. Joining consumes the invite. | `invite_invalid`, `already_paired`, `validation_failed`, `unauthorized`, `internal` | -| `GET /api/dates` | Bearer | Optional `q`, `category`, `status`, `sort`, `order`, `offset` | `200` with up to 50 date rows | `validation_failed`, `unauthorized`, `internal` | -| `POST /api/dates` | Bearer | JSON `title`, `category`, optional `status` and `meeting_at` | `200` with the created date row | `validation_failed`, `no_space`, `unauthorized`, `internal` | -| `PATCH /api/dates/:id` | Bearer | UUID `id` and at least one writable date field | `200` with the updated date row | `validation_failed`, `not_found`, `unauthorized`, `internal` | +| `GET /api/dates` | Bearer | Optional `q`, `category` key, `status`, `sort`, `order`, `offset` | `200` with up to 50 date rows containing category keys | `validation_failed`, `unauthorized`, `internal` | +| `POST /api/dates` | Bearer | JSON `title`, `category` key, optional `status` and `meeting_at` | `200` with the created date row | `validation_failed`, `no_space`, `unauthorized`, `internal` | +| `PATCH /api/dates/:id` | Bearer | UUID `id` and at least one writable date field. A supplied `category` must be a key. | `200` with the updated date row | `validation_failed`, `not_found`, `unauthorized`, `internal` | | `DELETE /api/dates/:id` | Bearer | UUID `id` | `204` | `validation_failed`, `not_found`, `unauthorized`, `internal` | | `GET /api/location` | Bearer | — | `200` with `partners`, `distanceKm`, and `midpoint`. Unavailable derived values are null. | `unauthorized`, `internal` | | `PUT /api/location` | Bearer | JSON `lat` and `lon` | `200` with the saved location row | `validation_failed`, `no_space`, `unauthorized`, `internal` | -| `GET /api/dashboard` | Bearer | — | `200` with `serverTime`, `nextMeeting`, and `categoriesByMonth` using UTC months | `unauthorized`, `internal` | +| `GET /api/dashboard` | Bearer | — | `200` with `serverTime`, `nextMeeting`, and `categoriesByMonth` grouped by UTC month and category key | `unauthorized`, `internal` | | `GET /api/photos` | Bearer | Optional `offset` | `200` with up to 30 uploads newest first, with signed URLs valid for five minutes | `validation_failed`, `no_space`, `unauthorized`, `internal` | | `POST /api/photos` | Bearer | Raw JPEG, PNG, or WebP bytes with matching `Content-Type`, up to 5 MiB in Nitro | `200` with Storage `id`, `path`, and `fullPath` | `validation_failed`, `no_space`, `unauthorized`, `internal` | | `DELETE /api/photos/:name` | Bearer | UUID `name` from the gallery | `204`, including when the name is absent from the caller's gallery | `validation_failed`, `no_space`, `unauthorized`, `internal` | +### Date category keys + +Import `DATE_CATEGORIES` and `DateCategory` from [shared/date-categories.ts](shared/date-categories.ts). The keys are `dinner`, `movie`, `walk`, `trip`, `video_call`, `game`, and `other`. Use them for date forms, the list filter, date responses, and dashboard charts. Translate their display labels in German, English, and Dutch. + +For example, `GET /api/dates?category=movie` filters by movie dates. Create or update requests use `"category":"movie"`, and the returned date row contains the same key. To clear the filter, omit `category`. An empty `category`, a translated label such as `Kino`, or any other non-key returns HTTP `400` with `data.code = "validation_failed"`. + +Migration `003` trims surrounding whitespace and maps known legacy aliases case-insensitively. For example, `Kino`, `film`, and `cinema` become `movie` and share one dashboard category. Unrecognized values become `other`. Apply the migration before serving this API version. + ### Error codes and statuses | `data.code` | HTTP | Meaning | diff --git a/shared/api-contract.ts b/shared/api-contract.ts index 6b69203..fbce813 100644 --- a/shared/api-contract.ts +++ b/shared/api-contract.ts @@ -1,9 +1,11 @@ import { z } from 'zod' +import { DATE_CATEGORIES } from './date-categories' const uuid = z.uuid() const timestamp = z.iso.datetime({ offset: true }) const invite = z.string().regex(/^[a-f0-9]{32}$/) const dateStatus = z.enum(['planned', 'done']) +export const dateCategorySchema = z.enum(DATE_CATEGORIES) const offset = z.coerce.number().int().nonnegative().default(0) const coordinates = { lat: z.number().min(-90).max(90), @@ -13,7 +15,7 @@ const coordinates = { export const joinSpaceRequestSchema = z.strictObject({ code: invite }) export const createDateRequestSchema = z.strictObject({ title: z.string().trim().min(1).max(160), - category: z.string().trim().min(1).max(60), + category: dateCategorySchema, status: dateStatus.optional(), meeting_at: timestamp.nullable().optional(), }) @@ -21,7 +23,7 @@ export const updateDateRequestSchema = createDateRequestSchema.partial().refine( export const dateParamsSchema = z.object({ id: uuid }) export const datesQuerySchema = z.object({ q: z.string().max(160).optional(), - category: z.string().optional(), + category: dateCategorySchema.optional(), status: dateStatus.optional(), sort: z.enum(['title', 'meeting_at', 'created_at']).default('created_at'), order: z.enum(['asc', 'desc']).default('desc'), @@ -48,7 +50,7 @@ export const dateResponseSchema = z.object({ id: uuid, space_id: uuid, title: z.string(), - category: z.string(), + category: dateCategorySchema, status: dateStatus, meeting_at: timestamp.nullable(), created_at: timestamp, @@ -66,7 +68,7 @@ export const dashboardResponseSchema = z.object({ nextMeeting: dateResponseSchema.nullable(), categoriesByMonth: z.array(z.object({ month: z.string().regex(/^\d{4}-\d{2}$/), - category: z.string(), + category: dateCategorySchema, total: z.number().int().nonnegative(), })), }) diff --git a/shared/date-categories.ts b/shared/date-categories.ts new file mode 100644 index 0000000..7f13e5f --- /dev/null +++ b/shared/date-categories.ts @@ -0,0 +1,11 @@ +export const DATE_CATEGORIES = [ + 'dinner', + 'movie', + 'walk', + 'trip', + 'video_call', + 'game', + 'other', +] as const + +export type DateCategory = typeof DATE_CATEGORIES[number] diff --git a/supabase/migrations/003_date_categories.sql b/supabase/migrations/003_date_categories.sql new file mode 100644 index 0000000..727258e --- /dev/null +++ b/supabase/migrations/003_date_categories.sql @@ -0,0 +1,40 @@ +-- Guard new writes while existing rows are normalized. +alter table public.dates + add constraint dates_category_key_check + check (category in ('dinner', 'movie', 'walk', 'trip', 'video_call', 'game', 'other')) + not valid; + +with mapped as ( + select id, case lower(regexp_replace(category, '^[[:space:]]+|[[:space:]]+$', '', 'g')) + when 'dinner' then 'dinner' + when 'abendessen' then 'dinner' + when 'avondeten' then 'dinner' + when 'movie' then 'movie' + when 'film' then 'movie' + when 'cinema' then 'movie' + when 'kino' then 'movie' + when 'bioscoop' then 'movie' + when 'walk' then 'walk' + when 'spaziergang' then 'walk' + when 'wandeling' then 'walk' + when 'trip' then 'trip' + when 'ausflug' then 'trip' + when 'uitstapje' then 'trip' + when 'video_call' then 'video_call' + when 'video call' then 'video_call' + when 'videoanruf' then 'video_call' + when 'videobellen' then 'video_call' + when 'game' then 'game' + when 'spiel' then 'game' + when 'spel' then 'game' + else 'other' + end as category + from public.dates +) +update public.dates as dates +set category = mapped.category +from mapped +where dates.id = mapped.id + and dates.category is distinct from mapped.category; + +alter table public.dates validate constraint dates_category_key_check; diff --git a/tests/api-errors.test.ts b/tests/api-errors.test.ts index dfc4763..ee01c6f 100644 --- a/tests/api-errors.test.ts +++ b/tests/api-errors.test.ts @@ -19,9 +19,9 @@ let origin: string const now = '2026-11-26T10:00:00+00:00' const coordinates = { lat: 52, lon: 12 } const partner = { user_id: id, ...coordinates } -const date = { id, space_id: id, title: 'Cinema', category: 'film', status: 'planned', meeting_at: null, created_at: now } +const date = { id, space_id: id, title: 'Cinema', category: 'movie', status: 'planned', meeting_at: null, created_at: now } const space = { id, invite, members: [{ user_id: id, slot: 1 }] } -const dashboard = { serverTime: now, nextMeeting: null, categoriesByMonth: [{ month: '2026-11', category: 'film', total: 1 }] } +const dashboard = { serverTime: now, nextMeeting: null, categoriesByMonth: [{ month: '2026-11', category: 'movie', total: 1 }] } const photo = { id, path: id + '/' + id, fullPath: 'gallery/' + id + '/' + id } beforeAll(async () => { @@ -101,7 +101,7 @@ test.each(['/space', '/space/join'])('returns already_paired for membership conf }) test.each([ - ['POST', '/dates', { title: 'Cinema', category: 'film' }], + ['POST', '/dates', { title: 'Cinema', category: 'movie' }], ['PUT', '/location', { lat: 52, lon: 12 }], ] as const)('returns no_space for an unpaired %s %s', async (method, path, body) => { upstream.mockImplementation(async input => { @@ -178,7 +178,7 @@ test.each([ { method: 'POST', path: '/space', schema: contract.spaceIdResponseSchema, upstreamData: [id] }, { method: 'POST', path: '/space/join', schema: contract.spaceIdResponseSchema, upstreamData: [id], body: { code: invite } }, { method: 'GET', path: '/dates', schema: contract.datesResponseSchema, upstreamData: [[date]] }, - { method: 'POST', path: '/dates', schema: contract.dateResponseSchema, upstreamData: [id, date], body: { title: 'Cinema', category: 'film' } }, + { method: 'POST', path: '/dates', schema: contract.dateResponseSchema, upstreamData: [id, date], body: { title: 'Cinema', category: 'movie' } }, { method: 'PATCH', path: '/dates/' + id, schema: contract.dateResponseSchema, upstreamData: [date], body: { title: 'Cinema' } }, { method: 'GET', path: '/location', schema: contract.locationResponseSchema, upstreamData: [[partner]] }, { method: 'PUT', path: '/location', schema: contract.savedLocationResponseSchema, upstreamData: [id, { ...partner, space_id: id }], body: coordinates }, @@ -218,6 +218,15 @@ test('photo uploads match the shared response schema', async () => { expect(upload.fullPath).toBe('gallery/' + upload.path) }) +test('filters dates by a category key and returns the shared date shape', async () => { + upstream.mockResolvedValueOnce(Response.json([date])) + const response = await request('GET', '/dates?category=movie') + expect(response.status).toBe(200) + expect(contract.datesResponseSchema.parse(await response.json())).toEqual([date]) + const upstreamUrl = new URL(String(upstream.mock.calls[0][0])) + expect(upstreamUrl.searchParams.get('category')).toBe('eq.movie') +}) + test.each([ { method: 'GET', path: '/space', upstreamData: [null] }, { method: 'DELETE', path: '/dates/' + id, upstreamData: [{ id }] }, diff --git a/tests/isolation.test.mjs b/tests/isolation.test.mjs index 41244a0..8f9036b 100644 --- a/tests/isolation.test.mjs +++ b/tests/isolation.test.mjs @@ -2,6 +2,7 @@ import assert from 'node:assert/strict' import { readdir, readFile } from 'node:fs/promises' import { PGlite } from '@electric-sql/pglite' import { afterEach, beforeEach, test } from 'vitest' +import { DATE_CATEGORIES } from '../shared/date-categories' let pg let users @@ -71,7 +72,7 @@ test('pairing, one-time invite, shared dates, private locations and outsider iso await login(0) await pg.query('select create_space()') const { invite } = (await pg.query('select invite from spaces')).rows[0] - await pg.query("insert into dates(title,category) values('Cinema','film')") + await pg.query("insert into dates(title,category) values('Cinema','movie')") await pg.query('insert into locations(lat,lon) values(52,12)') await login(1) await pg.query('select join_space($1)', [invite]) @@ -107,15 +108,15 @@ test('dashboard returns the earliest upcoming planned meeting in the caller’s await migrate() await login(1) await pg.query('select create_space()') - await pg.query("insert into dates(title, category, meeting_at) values ('Other space', 'film', now() + interval '1 hour')") + await pg.query("insert into dates(title, category, meeting_at) values ('Other space', 'movie', now() + interval '1 hour')") await login(0) await pg.query('select create_space()') await pg.query(`insert into dates(title, category, status, meeting_at) values - ('Past', 'film', 'planned', now() - interval '1 day'), - ('Done', 'film', 'done', now() + interval '2 hours'), - ('Next', 'film', 'planned', now() + interval '1 day'), - ('Later', 'film', 'planned', now() + interval '2 days')`) + ('Past', 'movie', 'planned', now() - interval '1 day'), + ('Done', 'movie', 'done', now() + interval '2 hours'), + ('Next', 'movie', 'planned', now() + interval '1 day'), + ('Later', 'movie', 'planned', now() + interval '2 days')`) const { data } = (await pg.query('select dashboard() as data')).rows[0] assert.equal(data.nextMeeting.title, 'Next') }) @@ -199,7 +200,12 @@ test('Postgres rejects unsupported categories on insert and update', async () => await migrate() await login(0) await pg.query('select create_space()') - await pg.query("insert into dates(title, category) values ('Cinema', 'movie')") + const { rows } = await pg.query(` + insert into dates(title, category) + select 'Date ' || category, category from unnest($1::text[]) as category + returning category + `, [DATE_CATEGORIES]) + assert.deepEqual(rows.map(row => row.category).sort(), [...DATE_CATEGORIES].sort()) await assert.rejects(pg.query("insert into dates(title, category) values ('Cinema', 'cinema')"), { code: '23514' }) await assert.rejects(pg.query("update dates set category = 'Movie'"), { code: '23514' }) })