Files
Bookra/apps/backend/migrations/00012_memberships_and_manage_token.sql
T
Tomas DvorakandDevin 50c8440a06 fix: backfill memberships, handle booking create errors
- Migration 00012: populate tenant_memberships from tenant_users join
  users, not only the seeded demo owner (Codex P1)
- bookings-page: check response.error so 4xx failures do not close the
  modal silently; refetch dashboard summary after create (Codex P2)

Authored By: TDvorak <[email protected]>

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-17 20:33:53 +02:00

52 lines
1.8 KiB
SQL

-- +goose Up
-- Tenant memberships keyed by the auth subject (Neon Auth `sub`).
-- The auth middleware resolves JWT subjects to memberships through users.neon_subject.
CREATE TABLE IF NOT EXISTS tenant_memberships (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
user_neon_subject text NOT NULL,
role text NOT NULL DEFAULT 'staff',
joined_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (tenant_id, user_neon_subject)
);
CREATE INDEX IF NOT EXISTS idx_tenant_memberships_subject ON tenant_memberships (user_neon_subject);
-- Unguessable per-booking management token used by /v1/public/bookings/:reference endpoints.
ALTER TABLE bookings
ADD COLUMN IF NOT EXISTS manage_token text;
CREATE UNIQUE INDEX IF NOT EXISTS idx_bookings_manage_token
ON bookings (manage_token)
WHERE manage_token IS NOT NULL;
-- Backfill tokens for pre-existing bookings.
UPDATE bookings
SET manage_token = replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', '')
WHERE manage_token IS NULL;
-- locations.updated_at is written by the repository update path.
ALTER TABLE locations
ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT now();
-- Backfill memberships for every existing user linked via tenant_users.
-- Covers the seeded demo owner (users.neon_subject = 'demo-owner').
INSERT INTO tenant_memberships (tenant_id, user_neon_subject, role)
SELECT tu.tenant_id, u.neon_subject, tu.role
FROM tenant_users tu
JOIN users u ON u.id = tu.user_id
WHERE u.neon_subject IS NOT NULL
ON CONFLICT (tenant_id, user_neon_subject) DO NOTHING;
-- +goose Down
ALTER TABLE locations
DROP COLUMN IF EXISTS updated_at;
DROP INDEX IF EXISTS idx_bookings_manage_token;
ALTER TABLE bookings
DROP COLUMN IF EXISTS manage_token;
DROP TABLE IF EXISTS tenant_memberships;