From 64ae63c98ea7c238b26fa4655efa55a42d28a2aa Mon Sep 17 00:00:00 2001 From: Abiola John Oluwaseyi Date: Mon, 30 Nov 2026 10:48:43 +0100 Subject: [PATCH 1/2] feat: establish Supabase migration workflow Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/cpanel_deploy.yml | 3 + backend/schema.sql | 2 + package-lock.json | 207 ++++++++ package.json | 9 +- supabase/.gitignore | 8 + supabase/config.jsonc | 498 ++++++++++++++++++ .../20260921160146_initial_schema.sql | 108 ++++ ...20261128000000_add_membership_interest.sql | 0 .../20261129000000_add_session_version.sql | 0 .../20261129000001_lock_down_supabase_rls.sql | 0 .../20261130000000_add_dashboard_metrics.sql | 0 ...261130000001_add_first_timer_retention.sql | 0 ...1130000002_add_follow_up_note_outcomes.sql | 0 supabase/tests/schema_consistency.test.sql | 128 +++++ 14 files changed, 962 insertions(+), 1 deletion(-) create mode 100644 supabase/.gitignore create mode 100644 supabase/config.jsonc create mode 100644 supabase/migrations/20260921160146_initial_schema.sql rename backend/migrations/20261128_add_membership_interest.sql => supabase/migrations/20261128000000_add_membership_interest.sql (100%) rename backend/migrations/20261129_add_session_version.sql => supabase/migrations/20261129000000_add_session_version.sql (100%) rename backend/migrations/20261129_lock_down_supabase_rls.sql => supabase/migrations/20261129000001_lock_down_supabase_rls.sql (100%) rename backend/migrations/20261130_add_dashboard_metrics.sql => supabase/migrations/20261130000000_add_dashboard_metrics.sql (100%) rename backend/migrations/20261130_add_first_timer_retention.sql => supabase/migrations/20261130000001_add_first_timer_retention.sql (100%) rename backend/migrations/20261130_add_follow_up_note_outcomes.sql => supabase/migrations/20261130000002_add_follow_up_note_outcomes.sql (100%) create mode 100644 supabase/tests/schema_consistency.test.sql diff --git a/.github/workflows/cpanel_deploy.yml b/.github/workflows/cpanel_deploy.yml index c32aaff..d72075a 100644 --- a/.github/workflows/cpanel_deploy.yml +++ b/.github/workflows/cpanel_deploy.yml @@ -45,6 +45,9 @@ jobs: VITE_API_BASE_URL: ${{ vars.VITE_API_BASE_URL }} run: npm run build + - name: Verify fresh database migrations + run: npm run db:verify + - name: Upload frontend build uses: actions/upload-artifact@v4 with: diff --git a/backend/schema.sql b/backend/schema.sql index 00decba..8226083 100644 --- a/backend/schema.sql +++ b/backend/schema.sql @@ -2,6 +2,8 @@ -- HGBC INFLUENCERS - FIRST TIMER & GUEST MANAGEMENT SYSTEM -- SUPABASE / POSTGRESQL DATABASE SCHEMA -- ========================================================================= +-- Reference snapshot of the final schema. Versioned migrations in +-- ../supabase/migrations are the source of truth for database changes. -- 1. EXTENSIONS CREATE EXTENSION IF NOT EXISTS "pgcrypto"; diff --git a/package-lock.json b/package-lock.json index 1d10dfe..bcb4e40 100644 --- a/package-lock.json +++ b/package-lock.json @@ -35,6 +35,7 @@ "globals": "^16.5.0", "jsdom": "^26.1.0", "json-server": "^1.0.0-beta.5", + "supabase": "3.4.0", "vitest": "^3.2.7" } }, @@ -445,6 +446,20 @@ "node": ">=18" } }, + "node_modules/@ecies/ciphers": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/@ecies/ciphers/-/ciphers-0.2.7.tgz", + "integrity": "sha512-gpl+Ipy9BY+MM9S9MGm9+DpvUIwdIaRDSJuDuV67ByLUxEocz/sLlxyX0keKOC1eFl9H0pAWdtMh1TlWs8J4/Q==", + "dev": true, + "engines": { + "bun": ">=1", + "deno": ">=2.7.10", + "node": ">=16" + }, + "peerDependencies": { + "@noble/ciphers": "^1.1.3" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.27.3", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz", @@ -1126,6 +1141,45 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "dev": true, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "dev": true, + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "dev": true, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@polka/url": { "version": "1.0.0-next.29", "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", @@ -1470,6 +1524,110 @@ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==", "license": "MIT" }, + "node_modules/@supabase/cli-darwin-arm64": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-darwin-arm64/-/cli-darwin-arm64-3.4.0.tgz", + "integrity": "sha512-Ax0yRa29XsteePrCRGpUgyylXqPZF2UBCxjWQhMrkY9kNxpflO6aKIzyslzpiqnKxL/lFsfvDeni2mi8UB4mpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@supabase/cli-darwin-x64": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-darwin-x64/-/cli-darwin-x64-3.4.0.tgz", + "integrity": "sha512-iTVVmY0XFUpcT+QsncTss/1F1ez3douPVeUqjpjOZ+oYLrKGYof7P8xIXfmTHDWnOeZG1Ek0oQ+PL27H/zXFYg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@supabase/cli-linux-arm64": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-linux-arm64/-/cli-linux-arm64-3.4.0.tgz", + "integrity": "sha512-BTf0udszAghdOQNm23SBVBhXqVl9sjhtInRz0yjo0FA0pHzTXXPFkQsj2FXNadAzcsEtYVCB7115acGz63IWGA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@supabase/cli-linux-arm64-musl": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-linux-arm64-musl/-/cli-linux-arm64-musl-3.4.0.tgz", + "integrity": "sha512-VPybaNoLBiUpYdD4bqDtxzCRwsJ0Fx8kDbtugy9eIGwqHJCuX8fDLHSLE+NGcqYTtMiljFrm9ry8cycUJlY9yQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@supabase/cli-linux-x64": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-linux-x64/-/cli-linux-x64-3.4.0.tgz", + "integrity": "sha512-NFfuyWBEn7Dugfk2nRSA+EwiaXM5YaKJ9OGXagOD/1hxFhh2ottUjXAHJ6ISdTYEJ7PFTrSgkq1RmUEmNX8ZeQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@supabase/cli-linux-x64-musl": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-linux-x64-musl/-/cli-linux-x64-musl-3.4.0.tgz", + "integrity": "sha512-9jI/4VWiJgzfQpMh8JkLHlQUsJV5nmArDalP9TpgMXtg5mClvkCjT35IBkUYo3ko7nHLSGTiKzfHKmHfDSfVKw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@supabase/cli-windows-arm64": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-windows-arm64/-/cli-windows-arm64-3.4.0.tgz", + "integrity": "sha512-+fJ5CrvGcEItTqelc8hsXeMEpaTzmCg/w3weeUwSl0o48BdNe/Bwf/Gprz4hrTNE0fGvQhL7VsCT7X8B4tnyXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@supabase/cli-windows-x64": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@supabase/cli-windows-x64/-/cli-windows-x64-3.4.0.tgz", + "integrity": "sha512-qh0sXt6bbIBaNiFqqKZ4vEAGOCT25JzQlgkx3Ut0w/bomzPBotk8hArxFJr/ozIN8IsklO8pQQ1Xe1A8d+3lVA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@tailwindcss/node": { "version": "4.1.18", "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz", @@ -2810,6 +2968,23 @@ "node": ">= 0.4" } }, + "node_modules/eciesjs": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/eciesjs/-/eciesjs-0.5.1.tgz", + "integrity": "sha512-R//x3vBdz/DKK/wyuF9WFzsRK7D1Ak3jRErqIdXI4aF5R9F/KiJaBW7THG/pl1nfRL58cI+Cj6W7T0e0Y9lsCw==", + "dev": true, + "dependencies": { + "@ecies/ciphers": "^0.2.7", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "^1.9.7", + "@noble/hashes": "^1.8.0" + }, + "engines": { + "bun": ">=1", + "deno": ">=2.7.10", + "node": ">=16" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.286", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.286.tgz", @@ -3642,6 +3817,15 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/jose": { + "version": "6.2.18", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.18.tgz", + "integrity": "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -4854,6 +5038,29 @@ "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", "dev": true }, + "node_modules/supabase": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/supabase/-/supabase-3.4.0.tgz", + "integrity": "sha512-XxbScAjxaIouchNyrcCMQsxqqT/oteGACWNhngMFy//4idJw1vaBDm4bjyYqFBZGA19xjPkLWWdBebrrP8+IqA==", + "dev": true, + "dependencies": { + "eciesjs": "^0.5.0", + "jose": "^6.2.10" + }, + "bin": { + "supabase": "dist/supabase.js" + }, + "optionalDependencies": { + "@supabase/cli-darwin-arm64": "3.4.0", + "@supabase/cli-darwin-x64": "3.4.0", + "@supabase/cli-linux-arm64": "3.4.0", + "@supabase/cli-linux-arm64-musl": "3.4.0", + "@supabase/cli-linux-x64": "3.4.0", + "@supabase/cli-linux-x64-musl": "3.4.0", + "@supabase/cli-windows-arm64": "3.4.0", + "@supabase/cli-windows-x64": "3.4.0" + } + }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", diff --git a/package.json b/package.json index 44d1639..1b5aaf5 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,13 @@ "test": "npm run test:backend && npm run test:frontend", "test:backend": "npm --prefix backend test", "test:frontend": "vitest run", - "test:frontend:watch": "vitest" + "test:frontend:watch": "vitest", + "db:start": "supabase start", + "db:stop": "supabase stop", + "db:reset": "supabase db reset --no-seed", + "db:status": "supabase migration list", + "db:test": "supabase test db", + "db:verify": "supabase start --exclude logflare,studio,gotrue,realtime,storage-api,imgproxy,kong,mailpit,postgrest,postgres-meta,edge-runtime,vector && supabase db reset --no-seed && supabase test db" }, "dependencies": { "@hookform/resolvers": "^5.2.2", @@ -41,6 +47,7 @@ "globals": "^16.5.0", "jsdom": "^26.1.0", "json-server": "^1.0.0-beta.5", + "supabase": "3.4.0", "vitest": "^3.2.7" } } diff --git a/supabase/.gitignore b/supabase/.gitignore new file mode 100644 index 0000000..ad9264f --- /dev/null +++ b/supabase/.gitignore @@ -0,0 +1,8 @@ +# Supabase +.branches +.temp + +# dotenvx +.env.keys +.env.local +.env.*.local diff --git a/supabase/config.jsonc b/supabase/config.jsonc new file mode 100644 index 0000000..a87a747 --- /dev/null +++ b/supabase/config.jsonc @@ -0,0 +1,498 @@ +{ + "$schema": "https://supabase.com/schemas/config/v1.json", + // For detailed configuration reference documentation, visit: + // https://supabase.com/docs/guides/local-development/cli/config + // A string used to distinguish different Supabase projects on the same host. Defaults to the + // working directory name when running `supabase init`. + "project_id": "hgbc-first-timer-portal", + + "api": { + "enabled": true, + // Port to use for the API URL. + "port": 54321, + // Schemas to expose in your API. Tables, views and stored procedures in this schema will get API + // endpoints. `public` and `graphql_public` schemas are included by default. + "schemas": ["public", "graphql_public"], + // Extra schemas to add to the search_path of every request. + "extra_search_path": ["public", "extensions"], + // The maximum number of rows returned from a view, table, or stored procedure. Limits payload size + // for accidental or malicious requests. + "max_rows": 1000, + // The maximum number of connections in the local PostgREST database pool. Left unset, the default + // pool size is unchanged. + // "db_pool": 10, + // Controls whether new tables, views, sequences and functions created in the `public` schema by + // `postgres` are reachable through the Data API roles (`anon`, `authenticated`, `service_role`) + // without explicit GRANTs, matching the cloud default. Set to `false` to require explicit GRANTs + // instead. Left unset, a fresh project falls back to `true`. + // "auto_expose_new_tables": true, + + "tls": { + // Enable HTTPS endpoints locally using a self-signed certificate. + "enabled": false, + // Paths to self-signed certificate pair. + // "cert_path": "../certs/my-cert.pem", + // "key_path": "../certs/my-key.pem", + } + }, + + "db": { + // Port to use for the local database URL. + "port": 54322, + // Port used by db diff command to initialize the shadow database. + "shadow_port": 54320, + // Maximum amount of time to wait for health check when starting the local database. + "health_timeout": "2m", + // The database major version to use. This has to be the same as your remote database's. Run `SHOW + // server_version;` on the remote database to check. + "major_version": 17, + // OrioleDB version to use as the Postgres storage engine. Leave empty to use the default engine. + "orioledb_version": "", + + "pooler": { + "enabled": false, + // Port to use for the local connection pooler. + "port": 54329, + // Specifies when a server connection can be reused by other clients. + // Configure one of the supported pooler modes: `transaction`, `session`. + "pool_mode": "transaction", + // How many server connections to allow per user/database pair. + "default_pool_size": 20, + // Maximum number of client connections allowed. + "max_client_conn": 100 + }, + + // "vault": { + // "secret_key": "env(SECRET_VALUE)" + // }, + + "migrations": { + // If disabled, migrations will be skipped during a db push or reset. + "enabled": true, + // Specifies an ordered list of schema files, directories, or glob patterns that describe your database. + // Supports paths relative to supabase directory: "./schemas/*.sql", "./database". + "schema_paths": [] + }, + + "seed": { + // If enabled, seeds the database after migrations during a db reset. + "enabled": false, + // Specifies an ordered list of seed files to load during db reset. + // Supports glob patterns relative to supabase directory: "./seeds/*.sql" + "sql_paths": [] + }, + + "network_restrictions": { + // Enable management of network restrictions. + "enabled": false, + // List of IPv4 CIDR blocks allowed to connect to the database. + // Defaults to allow all IPv4 connections. Set empty array to block all IPs. + "allowed_cidrs": ["0.0.0.0/0"], + // List of IPv6 CIDR blocks allowed to connect to the database. + // Defaults to allow all IPv6 connections. Set empty array to block all IPs. + "allowed_cidrs_v6": ["::/0"] + }, + + // Uncomment to reject non-secure connections to the database. + // "ssl_enforcement": { + // "enabled": true + // }, + }, + + "realtime": { + "enabled": true, + // Bind realtime via either IPv4 or IPv6. (default: IPv4) + // "ip_version": "IPv6", + // The maximum length in bytes of HTTP request headers. (default: 4096) + // "max_header_length": 4096, + }, + + "studio": { + "enabled": true, + // Port to use for Supabase Studio. + "port": 54323, + // External URL of the API server that frontend connects to. + "api_url": "http://127.0.0.1", + // OpenAI API Key to use for Supabase AI in the Supabase Studio. + "openai_api_key": "env(OPENAI_API_KEY)" + }, + + // Email testing server. Emails sent with the local dev setup are not actually sent - rather, they + // are monitored, and you can view the emails that would have been sent from the web interface. + "local_smtp": { + "enabled": true, + // Port to use for the email testing server web interface. + "port": 54324, + // Uncomment to expose additional ports for testing user applications that send emails. + // "smtp_port": 54325, + // "pop3_port": 54326, + // "admin_email": "admin@email.com", + // "sender_name": "Admin", + }, + + "storage": { + "enabled": true, + // The maximum file size allowed (e.g. "5MB", "500KB"). + "file_size_limit": "50MiB", + + // Uncomment to configure local storage buckets + // "buckets": { + // "images": { + // "public": false, + // "file_size_limit": "50MiB", + // "allowed_mime_types": ["image/png", "image/jpeg"], + // "objects_path": "./images" + // } + // }, + + // Allow connections via S3 compatible clients + "s3_protocol": { + "enabled": true + }, + + // Image transformation API is available to Supabase Pro plan. + // "image_transformation": { + // "enabled": true + // }, + + // Store analytical data in S3 for running ETL jobs over Iceberg Catalog + // This feature is only available on the hosted platform. + "analytics": { + "enabled": false, + "max_namespaces": 5, + "max_tables": 10, + "max_catalogs": 2, + + // Analytics Buckets is available to Supabase Pro plan. + // "buckets": { + // "my-warehouse": {} + // }, + }, + + // Store vector embeddings in S3 for large and durable datasets + "vector": { + "enabled": true, + "max_buckets": 10, + "max_indexes": 5, + + // Vector Buckets is available to Supabase Pro plan. + // "buckets": { + // "documents-openai": {} + // }, + } + }, + + "auth": { + "enabled": true, + // The base URL of your website. Used as an allow-list for redirects and for constructing URLs used + // in emails. + "site_url": "http://127.0.0.1:3000", + // The public URL that Auth serves on. Defaults to the API external URL with `/auth/v1` appended. + // "external_url": "", + // A list of *exact* URLs that auth providers are permitted to redirect to post authentication. + "additional_redirect_urls": ["https://127.0.0.1:3000"], + // How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week). + "jwt_expiry": 3600, + // JWT issuer URL. If not set, defaults to auth.external_url. + // "jwt_issuer": "", + // Path to JWT signing key. DO NOT commit your signing keys file to git. + // "signing_keys_path": "./signing_keys.json", + // If disabled, the refresh token will never expire. + "enable_refresh_token_rotation": true, + // Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. + // Requires enable_refresh_token_rotation = true. + "refresh_token_reuse_interval": 10, + // Allow/disallow new user signups to your project. Existing users can still sign in. + "enable_signup": true, + // Allow/disallow anonymous sign-ins to your project. + "enable_anonymous_sign_ins": false, + // Allow/disallow testing manual linking of accounts + "enable_manual_linking": false, + // Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more. + "minimum_password_length": 6, + // Passwords that do not meet the following requirements will be rejected as weak. Supported values + // are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols` + "password_requirements": "", + + // Configure passkey sign-ins. + // "passkey": { + // "enabled": false + // }, + + // Configure WebAuthn relying party settings (required when passkey is enabled). + // "webauthn": { + // "rp_display_name": "Supabase", + // "rp_id": "localhost", + // "rp_origins": ["http://127.0.0.1:3000"] + // }, + + "rate_limit": { + // Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled. + "email_sent": 2, + // Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled. + "sms_sent": 30, + // Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true. + "anonymous_users": 30, + // Number of sessions that can be refreshed in a 5 minute interval per IP address. + "token_refresh": 150, + // Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users). + "sign_in_sign_ups": 30, + // Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address. + "token_verifications": 30, + // Number of Web3 logins that can be made in a 5 minute interval per IP address. + "web3": 30 + }, + + // Configure one of the supported captcha providers: `hcaptcha`, `turnstile`. + // "captcha": { + // "enabled": true, + // "provider": "hcaptcha", + // "secret": "" + // }, + + "email": { + // Allow/disallow the email provider. When false, users can't sign up or sign in with email. + // To block new signups only, set enable_signup = false under [auth] instead. + "enabled": true, + // If enabled, a user will be required to confirm any email change on both the old, and new email + // addresses. If disabled, only the new email is required to confirm. + "double_confirm_changes": true, + // If enabled, users need to confirm their email address before signing in. + "enable_confirmations": false, + // If enabled, users will need to reauthenticate or have logged in recently to change their password. + "secure_password_change": false, + // If enabled, users will need to provide their current password to change their password, unless + // they signed in with a one-time password, magic link, or recovery link. + // "require_current_password": true, + // Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email. + "max_frequency": "1s", + // Number of characters used in the email OTP. + "otp_length": 6, + // Number of seconds before the email OTP expires (defaults to 1 hour). + "otp_expiry": 3600, + + // Use a production-ready SMTP server + // "smtp": { + // "enabled": true, + // "host": "smtp.sendgrid.net", + // "port": 587, + // "user": "apikey", + // "pass": "env(SENDGRID_API_KEY)", + // "admin_email": "admin@email.com", + // "sender_name": "Admin" + // }, + + // Uncomment to customize email template + // "template": { + // "invite": { + // "subject": "You have been invited", + // "content_path": "./supabase/templates/invite.html" + // } + // }, + + // Uncomment to customize notification email template + // "notification": { + // "password_changed": { + // "enabled": true, + // "subject": "Your password has been changed", + // "content_path": "./supabase/templates/password_changed_notification.html" + // } + // }, + }, + + "sms": { + // Allow/disallow the phone provider. When false, users can't sign up or sign in with SMS. + // To block new signups only, set enable_signup = false under [auth] instead. + "enabled": false, + // If enabled, users need to confirm their phone number before signing in. + "enable_confirmations": false, + // Template for sending OTP to users + "template": "Your code is {{ .Code }}", + // Controls the minimum amount of time that must pass before sending another sms otp. + "max_frequency": "5s", + + // Use pre-defined map of phone number to OTP for testing. + // Keys are the phone number with country code and without the + prefix. + // "test_otp": { + // "14152127777": "123456" + // }, + + // Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`. + "twilio": { + "enabled": false, + "account_sid": "", + "message_service_sid": "", + // DO NOT commit your Twilio auth token to git. Use environment variable substitution instead: + "auth_token": "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" + } + }, + + // Configure logged in session timeouts. + // "sessions": { + // // Force log out after the specified duration. + // "timebox": "24h", + // // Force log out if the user has been inactive longer than the specified duration. + // "inactivity_timeout": "8h" + // }, + + // This hook runs before a new user is created and allows developers to reject the request based on the incoming user object. + // "hook": { + // "before_user_created": { + // "enabled": true, + // "uri": "pg-functions://postgres/auth/before-user-created-hook" + // }, + // // This hook runs before a token is issued and allows you to add additional claims based on the authentication method used. + // "custom_access_token": { + // "enabled": true, + // "uri": "pg-functions:////" + // } + // }, + + // Multi-factor-authentication is available to Supabase Pro plan. + "mfa": { + // Control how many MFA factors can be enrolled at once per user. + "max_enrolled_factors": 10, + + // Control MFA via App Authenticator (TOTP) + "totp": { + "enroll_enabled": false, + "verify_enabled": false + }, + + // Configure MFA via Phone Messaging + "phone": { + "enroll_enabled": false, + "verify_enabled": false, + "otp_length": 6, + "template": "Your code is {{ .Code }}", + "max_frequency": "5s" + }, + + // Configure MFA via WebAuthn + // "web_authn": { + // "enroll_enabled": true, + // "verify_enabled": true + // }, + }, + + // Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`, + // `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`, + // `twitter`, `x`, `slack_oidc`, `spotify`, `workos`, `zoom`. + "external": { + "apple": { + "enabled": false, + "client_id": "", + // DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead: + "secret": "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)", + // Overrides the default auth callback URL derived from auth.external_url. + "redirect_uri": "", + // Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure, + // or any other third-party OIDC providers. + "url": "", + // If enabled, the nonce check will be skipped. Required for local sign in with Google auth. + "skip_nonce_check": false, + // If enabled, it will allow the user to successfully authenticate when the provider does not return an email address. + "email_optional": false + } + }, + + // Allow Solana wallet holders to sign in to your project via the Sign in with Solana (SIWS) standard. + // You can configure "web3" rate limit in the [auth.rate_limit] section and set up [auth.captcha] if self-hosting. + "web3": { + "solana": { + "enabled": false + }, + + // Allow Ethereum wallet holders to sign in to your project via the Sign in with Ethereum (SIWE, EIP-4361) standard. + // "ethereum": { + // "enabled": true + // }, + }, + + // Use Firebase Auth as a third-party provider alongside Supabase Auth. + "third_party": { + "firebase": { + "enabled": false, + // "project_id": "my-firebase-project", + }, + + // Use Auth0 as a third-party provider alongside Supabase Auth. + "auth0": { + "enabled": false, + // "tenant": "my-auth0-tenant", + // "tenant_region": "us", + }, + + // Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth. + "aws_cognito": { + "enabled": false, + // "user_pool_id": "my-user-pool-id", + // "user_pool_region": "us-east-1", + }, + + // Use Clerk as a third-party provider alongside Supabase Auth. + "clerk": { + "enabled": false, + // Obtain from https://clerk.com/setup/supabase + // "domain": "example.clerk.accounts.dev", + } + }, + + // OAuth server configuration + "oauth_server": { + // Enable OAuth server functionality + "enabled": false, + // Path for OAuth consent flow UI + "authorization_url_path": "/oauth/consent", + // Allow dynamic client registration + "allow_dynamic_registration": false + } + }, + + "edge_runtime": { + "enabled": true, + // Supported request policies: `oneshot`, `per_worker`. + // `per_worker` (default) — enables hot reload during local development. + // `oneshot` — fallback mode if hot reload causes issues (e.g. in large repos or with symlinks). + "policy": "per_worker", + // Port to attach the Chrome inspector for debugging edge functions. + "inspector_port": 8083, + // The Deno major version to use. + "deno_version": 2, + + // "secrets": { + // "secret_key": "env(SECRET_VALUE)" + // }, + }, + + "analytics": { + "enabled": false, + "port": 54327, + // Configure one of the supported backends: `postgres`, `bigquery`. + "backend": "postgres" + }, + + // Experimental features may be deprecated any time + "experimental": { + // Configures S3 bucket URL, eg. .s3-.amazonaws.com + "s3_host": "env(S3_HOST)", + // Configures S3 bucket region, eg. us-east-1 + "s3_region": "env(S3_REGION)", + // Configures AWS_ACCESS_KEY_ID for S3 bucket + "s3_access_key": "env(S3_ACCESS_KEY)", + // Configures AWS_SECRET_ACCESS_KEY for S3 bucket + "s3_secret_key": "env(S3_SECRET_KEY)", + + // pg-delta is the schema diff engine for db diff / db pull. + // Set enabled = false to fall back to the legacy migra engine. + "pgdelta": { + "enabled": true, + // Directory under `supabase/` where declarative files are written. + // "declarative_schema_path": "./schemas", + // JSON string passed through to pg-delta SQL formatting. When omitted, SQL is + // formatted with uppercase keywords, indent 2, max width 180, trailing commas, + // and column/key alignment. Set to "null" to emit raw, unformatted SQL. + // "format_options": "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":180,\"commaStyle\":\"trailing\"}", + } + } +} diff --git a/supabase/migrations/20260921160146_initial_schema.sql b/supabase/migrations/20260921160146_initial_schema.sql new file mode 100644 index 0000000..a3570fe --- /dev/null +++ b/supabase/migrations/20260921160146_initial_schema.sql @@ -0,0 +1,108 @@ +-- ========================================================================= +-- HGBC INFLUENCERS - FIRST TIMER & GUEST MANAGEMENT SYSTEM +-- SUPABASE / POSTGRESQL DATABASE SCHEMA +-- ========================================================================= + +CREATE EXTENSION IF NOT EXISTS "pgcrypto"; + +DO $$ BEGIN + CREATE TYPE gender_type AS ENUM ('male', 'female'); +EXCEPTION + WHEN duplicate_object THEN null; +END $$; + +DO $$ BEGIN + CREATE TYPE status_type AS ENUM ('student', 'professional', 'other'); +EXCEPTION + WHEN duplicate_object THEN null; +END $$; + +DO $$ BEGIN + CREATE TYPE follow_up_status_type AS ENUM ('pending', 'contacted', 'integrated', 'closed'); +EXCEPTION + WHEN duplicate_object THEN null; +END $$; + +DO $$ BEGIN + CREATE TYPE user_role_type AS ENUM ('admin', 'team_member', 'pastor'); +EXCEPTION + WHEN duplicate_object THEN null; +END $$; + +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + full_name TEXT NOT NULL, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + role user_role_type DEFAULT 'team_member', + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS first_timers ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + full_name TEXT NOT NULL, + gender gender_type NOT NULL, + date_of_birth DATE, + phone_number TEXT NOT NULL, + email TEXT NOT NULL, + residence_address TEXT NOT NULL, + status status_type NOT NULL, + student_institution TEXT, + student_faculty TEXT, + student_department TEXT, + student_level TEXT, + professional_organization TEXT, + professional_occupation TEXT, + other_status TEXT, + how_did_you_hear TEXT, + experience_today TEXT, + best_contact_time TEXT, + preferred_contact_method TEXT, + prayer_requests TEXT, + follow_up_status follow_up_status_type DEFAULT 'pending', + assigned_to UUID REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS follow_up_notes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + first_timer_id UUID NOT NULL REFERENCES first_timers(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + note TEXT NOT NULL, + contact_method TEXT, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_first_timers_created_at ON first_timers (created_at DESC); +CREATE INDEX IF NOT EXISTS idx_first_timers_follow_up_status ON first_timers (follow_up_status); +CREATE INDEX IF NOT EXISTS idx_first_timers_status ON first_timers (status); +CREATE INDEX IF NOT EXISTS idx_first_timers_email ON first_timers (email); +CREATE INDEX IF NOT EXISTS idx_first_timers_phone ON first_timers (phone_number); +CREATE INDEX IF NOT EXISTS idx_users_email ON users (email); + +CREATE OR REPLACE FUNCTION trigger_set_timestamp() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS set_timestamp_first_timers ON first_timers; +CREATE TRIGGER set_timestamp_first_timers +BEFORE UPDATE ON first_timers +FOR EACH ROW +EXECUTE PROCEDURE trigger_set_timestamp(); + +DROP TRIGGER IF EXISTS set_timestamp_users ON users; +CREATE TRIGGER set_timestamp_users +BEFORE UPDATE ON users +FOR EACH ROW +EXECUTE PROCEDURE trigger_set_timestamp(); + +ALTER TABLE first_timers ENABLE ROW LEVEL SECURITY; +ALTER TABLE users ENABLE ROW LEVEL SECURITY; +ALTER TABLE follow_up_notes ENABLE ROW LEVEL SECURITY; diff --git a/backend/migrations/20261128_add_membership_interest.sql b/supabase/migrations/20261128000000_add_membership_interest.sql similarity index 100% rename from backend/migrations/20261128_add_membership_interest.sql rename to supabase/migrations/20261128000000_add_membership_interest.sql diff --git a/backend/migrations/20261129_add_session_version.sql b/supabase/migrations/20261129000000_add_session_version.sql similarity index 100% rename from backend/migrations/20261129_add_session_version.sql rename to supabase/migrations/20261129000000_add_session_version.sql diff --git a/backend/migrations/20261129_lock_down_supabase_rls.sql b/supabase/migrations/20261129000001_lock_down_supabase_rls.sql similarity index 100% rename from backend/migrations/20261129_lock_down_supabase_rls.sql rename to supabase/migrations/20261129000001_lock_down_supabase_rls.sql diff --git a/backend/migrations/20261130_add_dashboard_metrics.sql b/supabase/migrations/20261130000000_add_dashboard_metrics.sql similarity index 100% rename from backend/migrations/20261130_add_dashboard_metrics.sql rename to supabase/migrations/20261130000000_add_dashboard_metrics.sql diff --git a/backend/migrations/20261130_add_first_timer_retention.sql b/supabase/migrations/20261130000001_add_first_timer_retention.sql similarity index 100% rename from backend/migrations/20261130_add_first_timer_retention.sql rename to supabase/migrations/20261130000001_add_first_timer_retention.sql diff --git a/backend/migrations/20261130_add_follow_up_note_outcomes.sql b/supabase/migrations/20261130000002_add_follow_up_note_outcomes.sql similarity index 100% rename from backend/migrations/20261130_add_follow_up_note_outcomes.sql rename to supabase/migrations/20261130000002_add_follow_up_note_outcomes.sql diff --git a/supabase/tests/schema_consistency.test.sql b/supabase/tests/schema_consistency.test.sql new file mode 100644 index 0000000..bafe440 --- /dev/null +++ b/supabase/tests/schema_consistency.test.sql @@ -0,0 +1,128 @@ +BEGIN; + +CREATE EXTENSION IF NOT EXISTS pgtap WITH SCHEMA extensions; + +SELECT plan(19); + +SELECT ok(to_regclass('public.users') IS NOT NULL, 'users table exists'); +SELECT ok(to_regclass('public.first_timers') IS NOT NULL, 'first_timers table exists'); +SELECT ok(to_regclass('public.follow_up_notes') IS NOT NULL, 'follow_up_notes table exists'); +SELECT ok( + EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'first_timers' AND column_name = 'membership_interest' + ), + 'membership interest column exists' +); +SELECT ok( + EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'session_version' + ), + 'session version column exists' +); +SELECT ok( + EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'follow_up_notes' AND column_name = 'outcome' + ), + 'follow-up outcome column exists' +); +SELECT ok( + ( + SELECT array_agg(enumlabel::TEXT ORDER BY enumsortorder) + FROM pg_enum + WHERE enumtypid = 'public.user_role_type'::regtype + ) = ARRAY['admin', 'team_member', 'pastor']::TEXT[], + 'database role enum matches supported application roles' +); +SELECT ok( + EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'public.first_timers'::regclass + AND conname = 'first_timers_membership_interest_check' + ), + 'membership interest constraint exists' +); +SELECT ok( + EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'public.follow_up_notes'::regclass + AND conname = 'follow_up_notes_outcome_check' + ), + 'follow-up outcome constraint exists' +); +SELECT ok( + to_regclass('public.idx_follow_up_notes_first_timer_created_at') IS NOT NULL, + 'follow-up history index exists' +); +SELECT ok( + ( + SELECT count(*) = 3 + FROM pg_class + WHERE oid = ANY(ARRAY[ + 'public.users'::regclass, + 'public.first_timers'::regclass, + 'public.follow_up_notes'::regclass + ]) + AND relrowsecurity + ), + 'row-level security is enabled on protected tables' +); +SELECT ok( + NOT EXISTS ( + SELECT 1 FROM pg_policies + WHERE schemaname = 'public' + AND tablename IN ('first_timers', 'users', 'follow_up_notes') + ), + 'protected tables have no direct API policies' +); +SELECT ok( + has_table_privilege('service_role', 'public.first_timers', 'SELECT') + AND has_table_privilege('service_role', 'public.users', 'SELECT') + AND has_table_privilege('service_role', 'public.follow_up_notes', 'SELECT'), + 'service_role retains database access' +); +SELECT ok( + EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgrelid = 'public.users'::regclass + AND tgname = 'users_bump_session_version' + AND NOT tgisinternal + ), + 'user session version trigger exists' +); +SELECT ok( + to_regprocedure('public.get_dashboard_metrics(timestamp with time zone)') IS NOT NULL, + 'dashboard metrics function exists' +); +SELECT ok( + to_regprocedure('public.delete_expired_first_timers()') IS NOT NULL, + 'retention function exists' +); +SELECT ok( + EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_cron'), + 'pg_cron extension is installed' +); +SELECT ok( + EXISTS ( + SELECT 1 FROM cron.job + WHERE jobname = 'delete-expired-first-timer-data' + AND schedule = '0 * * * *' + ), + 'retention job is scheduled hourly' +); +SELECT ok( + EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'public.follow_up_notes'::regclass + AND contype = 'f' + AND confrelid = 'public.first_timers'::regclass + AND confdeltype = 'c' + ), + 'follow-up notes are deleted with expired submissions' +); + +SELECT * FROM finish(); + +ROLLBACK; From 35353876138cc43f6894c93d022d1b8cc07a3670 Mon Sep 17 00:00:00 2001 From: Abiola John Oluwaseyi Date: Mon, 30 Nov 2026 10:49:28 +0100 Subject: [PATCH 2/2] docs: document project setup and database operations Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 84 ++++++++++++++++++++++++++++++++++++-------- backend/.env.example | 3 -- backend/README.md | 65 +++++++++++++++++++++++++--------- 3 files changed, 119 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 0ecaf2f..de7238e 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,91 @@ -# React + Vite +# HGBC First-Timer Portal -This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. +The portal helps HGBC staff manage first-time guest submissions and follow-up. It consists of a React dashboard and public intake form, an Express API, and a Supabase PostgreSQL database. -Currently, two official plugins are available: +## Architecture -- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh -- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh +- `src/`: React/Vite frontend; deployed as static files to cPanel by GitHub Actions. +- `backend/`: Node.js 22+ Express API; connects to Supabase with the server-only service-role key and issues its own versioned JWTs. +- `shared/`: role definitions used by both frontend and backend. +- `supabase/migrations/`: ordered, versioned database history and the source of truth for schema changes. +- `backend/schema.sql`: reference snapshot of the final schema; use the migration workflow below to initialize databases. -## React Compiler +The API is deployed to Render. The frontend calls it using `VITE_API_BASE_URL`; when omitted, it uses `/api`. -The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). +## Requirements -## Expanding the ESLint configuration +- Node.js 22 or newer and npm. +- Docker, for the Supabase local database and migration checks. +- Supabase project credentials for running the API against a hosted database. -If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project. +## Local setup -## Project quality checks - -Install dependencies from the repository root and backend directory: +Install dependencies from the repository root: ```bash npm ci npm ci --prefix backend ``` -Run the checks used by CI: +Start the local Supabase stack and apply the migration chain to its development database: + +```bash +npm run db:start +npm run db:reset +npm run db:status +npm run db:test +``` + +`db:reset` recreates the **local** database and applies every migration. It deletes local database contents; do not use it to reset a hosted project. `db:stop` stops the local stack. + +To run the application against the local Supabase stack, copy `backend/.env.example` to `backend/.env`, use the local URL and service-role key shown by `npx supabase status`, and set a unique `JWT_SECRET` of at least 32 bytes. Create a root `.env.local` for Vite: + +```env +VITE_API_BASE_URL=http://localhost:5000/api +``` + +Then start the API and frontend in separate terminals: + +```bash +npm run dev --prefix backend +npm run dev +``` + +Vite runs on port 3000 and the API defaults to port 5000. Keep `.env`, `.env.local`, database passwords, JWT secrets, and service-role keys out of Git. The backend rejects anon keys and requires `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, and a valid `JWT_SECRET`. `CORS_ORIGIN` is not currently consumed by the server. + +## Database migrations + +Create new migrations with `npx supabase migration new descriptive_name`. Do not edit a migration after it has been applied; add a new forward migration instead. Run `npm run db:verify` to start a minimal local PostgreSQL stack, reset it from migrations, and run database schema tests. CI runs this check on pull requests and pushes to `main`. + +For production, link the CLI to the intended Supabase project, inspect its migration history, preview pending migrations, and apply only after review: + +```bash +npx supabase login +npx supabase link --project-ref +npx supabase migration list --remote +npx supabase db push --dry-run --remote +npx supabase db push --remote +``` + +Existing projects may have changes applied manually and no migration ledger. Follow the [backend database migration guide](./backend/README.md#existing-projects-with-manual-schema-changes) to compare the live schema before marking verified migrations as applied. Never blindly replay the initial schema or use `migration repair` to conceal drift. The project does not retain database backups; schema rollback is not data recovery. Migrations should be additive where possible, and recovery from an incompatible change uses a reviewed forward fix. + +## Tests and quality checks ```bash npm run lint npm test npm run build +npm run db:verify ``` -`npm test` runs the backend suite and frontend component tests. Use `npm run test:frontend:watch` while developing frontend tests. +`npm test` runs backend authorization/API tests and frontend component tests. `npm run db:verify` requires Docker and validates that a fresh database can be built from the committed migrations. + +## Deployment + +- **Frontend:** GitHub Actions builds on pushes and pull requests to `main`; successful pushes to `main` deploy `dist/` to cPanel. Configure `VITE_API_BASE_URL` as a GitHub Actions repository variable for the deployed API URL. +- **Backend:** Deploy the repository to Render with the repository root as the working directory so the shared role module is available. Use `npm ci --prefix backend` as the build command and `npm start --prefix backend` as the start command. Configure the required Supabase URL, service-role key, and JWT secret in Render's secret environment, and use `/api/health` as the health check. +- **Database:** Apply reviewed migrations before deploying code that depends on them. See the [backend deployment and database guide](./backend/README.md). + +## Privacy and data retention + +The portal uses intake details for guest follow-up and outreach analysis. Prayer requests are optional. Administrators and pastors can access all submissions; team members can access only assigned submissions. Submissions and related interaction notes are deleted after 13 months. See the [privacy and retention details](./backend/README.md#privacy-data-use-and-retention). diff --git a/backend/.env.example b/backend/.env.example index 27b6e67..c59a1d7 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -7,6 +7,3 @@ SUPABASE_SERVICE_ROLE_KEY=your-supabase-service-role-key # Generate a unique secret with: openssl rand -base64 48 JWT_SECRET= - -# CORS allowed origins (comma separated or specific domain) -CORS_ORIGIN=http://localhost:5173,https://join.hgbcinfluencers.org,https://hgbcinfluencers.org diff --git a/backend/README.md b/backend/README.md index eba1f84..77d3988 100644 --- a/backend/README.md +++ b/backend/README.md @@ -6,22 +6,55 @@ Production-ready Node.js (Express) & Supabase (PostgreSQL) backend API for the H ## 1. Supabase Database Setup -1. Log into your [Supabase Dashboard](https://supabase.com). -2. Create a new project (e.g. `hgbc-firsttimers`). -3. In the left navigation, go to the **SQL Editor**. -4. Open or copy the contents of `schema.sql` from this directory. -5. Click **Run** to execute the script. -6. For an existing database, run `migrations/20261128_add_membership_interest.sql` in the Supabase SQL Editor to add the optional membership-interest field without changing existing submissions. -7. Before deploying the session-revocation update, run `migrations/20261129_add_session_version.sql` in the Supabase SQL Editor. -8. Before deploying the database-access update, run `migrations/20261129_lock_down_supabase_rls.sql`. -9. Before deploying the dashboard-metrics update, run `migrations/20261130_add_dashboard_metrics.sql`. -10. Before deploying the privacy-retention update, run `migrations/20261130_add_first_timer_retention.sql`. This enables `pg_cron` and schedules an hourly deletion of submissions older than 13 months; related follow-up notes are deleted by the foreign-key cascade. -11. Before deploying follow-up interaction history, run `migrations/20261130_add_follow_up_note_outcomes.sql` to add the outcome field and chronological lookup index. -12. In **Project Settings** > **API**: +Database changes are managed with the Supabase CLI. Migration files are in `../supabase/migrations/`; do not apply or maintain parallel SQL in `backend/migrations/`. + +For a new local database: + +```bash +npm run db:start +npm run db:reset +npm run db:status +npm run db:test +``` + +For a hosted project: + +1. Link the project from the repository root: + ```bash + npx supabase login + npx supabase link --project-ref + ``` +2. Inspect migration status and preview changes: + ```bash + npx supabase migration list --remote + npx supabase db push --dry-run --remote + ``` +3. Apply only a reviewed migration set: + ```bash + npx supabase db push --remote + ``` +4. In **Project Settings** > **API**: - Copy your **Project URL** (`SUPABASE_URL`) - Copy your **service_role** secret (`SUPABASE_SERVICE_ROLE_KEY`) - Keep the service-role secret private; it bypasses database row-level security. +### Existing projects with manual schema changes + +This repository previously used manually applied SQL files and a live migration history may not exist. Do not run the baseline migration over live data without reconciliation. + +Before adopting the migration chain: + +1. Dump only schema metadata or use Supabase Studio to inventory the existing tables, types, constraints, indexes, triggers, functions, RLS policies, grants, and `cron.job` entries. +2. Compare the inventory with `schema.sql` and `../supabase/migrations/`. +3. For changes already verified in production, repair only the matching migration-history rows as applied: + ```bash + npx supabase migration repair --status applied --remote + ``` +4. For missing verified changes, add or apply a forward migration; never edit an applied migration or use repair to conceal missing schema objects. +5. Re-run `migration list --remote` and verify the live catalog, RLS policies, retention job, and dashboard function before deployment. + +No project backups are retained by the application. Migration rollback is therefore a forward schema repair, not a data recovery mechanism. + The schema enables RLS on submissions, users, and follow-up notes without granting anonymous or authenticated table access. Public intake is submitted to the backend API, which validates the request and writes using the service-role key. Do not add a direct anonymous insert policy. --- @@ -48,7 +81,6 @@ Use Node.js 22 or newer, as required by the Supabase client runtime. SUPABASE_URL=https://your-project.supabase.co SUPABASE_SERVICE_ROLE_KEY=your-supabase-service-role-key JWT_SECRET= - CORS_ORIGIN=http://localhost:5173,https://join.hgbcinfluencers.org ``` 5. Start the server in watch mode: ```bash @@ -77,7 +109,6 @@ Use Node.js 22 or newer, as required by the Supabase client runtime. - `SUPABASE_URL`: (Your Supabase Project URL) - `SUPABASE_SERVICE_ROLE_KEY`: (Your Supabase Service Role Key) - `JWT_SECRET`: a unique value generated with `openssl rand -base64 48` (at least 32 bytes) - - `CORS_ORIGIN`: `https://join.hgbcinfluencers.org,http://localhost:5173` - `NODE_ENV`: `production` 6. Click **Create Web Service**. 7. Once deployed, copy your Render URL (e.g., `https://hgbc-firsttimer-api.onrender.com/api`) and set it as `VITE_API_BASE_URL` in your frontend! @@ -87,7 +118,7 @@ Use Node.js 22 or newer, as required by the Supabase client runtime. The backend refuses to start if `JWT_SECRET` is missing or shorter than 32 bytes. Generate a different secret for each environment and store it only in that environment's secret configuration; never commit it. For the T2 deployment: -1. Apply `migrations/20261129_add_session_version.sql`. +1. Apply `../supabase/migrations/20261129000000_add_session_version.sql`. 2. Set a newly generated `JWT_SECRET` in the production environment. 3. Deploy the updated backend and confirm it starts successfully. 4. Require users to sign in again. Rotating the secret invalidates all existing access tokens. @@ -111,7 +142,7 @@ The query should return no rows. Then use only the public anon key from a non-pr ### Dashboard metrics -The dashboard metrics endpoint aggregates totals, follow-up counts, and discovery sources in PostgreSQL, avoiding the submissions endpoint's page size and REST row limit. The daily count uses the `Africa/Lagos` calendar day, from local midnight up to (but excluding) the following local midnight. Because the retention job deletes records after 13 months, these metrics only reflect records still within that retention period. Apply `migrations/20261130_add_dashboard_metrics.sql` to existing databases before deploying the backend. If the endpoint is unavailable, the dashboard displays an explicit unavailable state instead of presenting partial totals. +The dashboard metrics endpoint aggregates totals, follow-up counts, and discovery sources in PostgreSQL, avoiding the submissions endpoint's page size and REST row limit. The daily count uses the `Africa/Lagos` calendar day, from local midnight up to (but excluding) the following local midnight. Because the retention job deletes records after 13 months, these metrics only reflect records still within that retention period. Apply `../supabase/migrations/20261130000000_add_dashboard_metrics.sql` to existing databases before deploying the backend. If the endpoint is unavailable, the dashboard displays an explicit unavailable state instead of presenting partial totals. ### Privacy, data use, and retention @@ -162,6 +193,8 @@ Public account signup is disabled. Administrators provision staff accounts throu ### Protected Endpoints (Requires `Authorization: Bearer `) - `GET /api/first-timers` — Get paginated submissions (`?page=1&limit=10&search=john`) - `GET /api/first-timers/:id` — Get single first-timer details with notes +- `GET /api/first-timers/:id/follow-up-notes` — Get chronological interaction history +- `POST /api/first-timers/:id/follow-up-notes` — Record a follow-up interaction - `PATCH /api/first-timers/:id` — Update status / assigned team member - `DELETE /api/first-timers/:id` — Delete a first-timer submission (admin only) - `GET /api/first-timers/export` — Download submissions as CSV