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
3 changes: 3 additions & 0 deletions .github/workflows/cpanel_deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
84 changes: 70 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -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 <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).
3 changes: 0 additions & 3 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
65 changes: 49 additions & 16 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <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 <migration-version>
```
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.

---
Expand All @@ -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=<output of openssl rand -base64 48>
CORS_ORIGIN=http://localhost:5173,https://join.hgbcinfluencers.org
```
5. Start the server in watch mode:
```bash
Expand Down Expand Up @@ -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!
Expand All @@ -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.
Expand All @@ -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

Expand Down Expand Up @@ -162,6 +193,8 @@ Public account signup is disabled. Administrators provision staff accounts throu
### Protected Endpoints (Requires `Authorization: Bearer <token>`)
- `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
Expand Down
2 changes: 2 additions & 0 deletions backend/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Loading
Loading