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
20 changes: 14 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
```
Expand All @@ -54,17 +54,25 @@ Send `Authorization: Bearer <access_token>` 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 |
Expand Down
10 changes: 6 additions & 4 deletions shared/api-contract.ts
Original file line number Diff line number Diff line change
@@ -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),
Expand All @@ -13,15 +15,15 @@ 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(),
})
export const updateDateRequestSchema = createDateRequestSchema.partial().refine(value => Object.keys(value).length > 0)
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'),
Expand All @@ -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,
Expand All @@ -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(),
})),
})
Expand Down
11 changes: 11 additions & 0 deletions shared/date-categories.ts
Original file line number Diff line number Diff line change
@@ -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]
40 changes: 40 additions & 0 deletions supabase/migrations/003_date_categories.sql
Original file line number Diff line number Diff line change
@@ -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;
32 changes: 28 additions & 4 deletions tests/api-errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 => {
Expand Down Expand Up @@ -157,13 +157,28 @@ 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] },
{ 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 },
Expand Down Expand Up @@ -203,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 }] },
Expand Down
86 changes: 79 additions & 7 deletions tests/isolation.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -44,16 +45,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()
Expand All @@ -62,10 +68,11 @@ 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]
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])
Expand All @@ -85,6 +92,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]
Expand All @@ -97,22 +105,24 @@ 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')")
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')
})

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]
Expand All @@ -137,3 +147,65 @@ 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()')
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' })
})