# Developer Setup Guide

> **Status (Phase 10, final):** verified in Claude's workspace with Node 22.23.4, a local MongoDB 8.3 replica set and Chrome 153. For hosting see `docs/DEPLOYMENT.md`; for daily use `docs/ADMIN_GUIDE.md` and `docs/TRAINER_GUIDE.md`.

## 1. Prerequisites

| Tool                         | Version                                                                                      | Notes                                                   |
| ---------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| Node.js                      | **22.22.2+ (22.x), 24.15.0+ (24.x) or 26+** (D-110). Production: Node 24 LTS                 | `node -v`. npm refuses other versions (`engine-strict`) |
| npm                          | Bundled with Node                                                                            | npm workspaces (`server`, `client`)                     |
| Git                          | Any recent version                                                                           |                                                         |
| MongoDB                      | An Atlas dev cluster (P-04), **or** a local MongoDB ≥ 7 run as a **single-node replica set** | Transactions need a replica set                         |
| Chrome / Playwright browsers | `npx playwright install chromium` (or point `PLAYWRIGHT_CHROME` at an installed Chrome)      | E2E and visual tests only                               |

## 2. Accounts needed for full functionality

| Service                 | Needed for                   | Status                                                                                         |
| ----------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------- |
| MongoDB Atlas           | Database                     | P-04 pending (use a local replica set until then)                                              |
| SMTP provider           | Admin password-reset emails  | P-07 pending. Development prints the email, including the reset link, to the server log.       |
| Cloudinary              | Image uploads (from Phase 2) | P-05 pending                                                                                   |
| Meta WhatsApp Cloud API | Real messages (Phase 7)      | P-06 pending. Until then the app runs in the clearly labelled simulated mode (nothing is sent) |
| S3-compatible storage   | Backups (Phase 9)            | P-08 pending                                                                                   |

## 3. Environment variables (names only — never commit values)

Copy `server/.env.example` → `server/.env` and `client/.env.example` → `client/.env`.

### `server/.env`

| Variable                                                                                              | Purpose                                                                                                                                        |
| ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `NODE_ENV`                                                                                            | `development` \| `test` \| `staging` \| `production`                                                                                           |
| `PORT`                                                                                                | API port (development: 4000)                                                                                                                   |
| `APP_ORIGIN`                                                                                          | Comma-separated list of allowed browser origins (dev: `http://localhost:5173`)                                                                 |
| `APP_PUBLIC_URL`                                                                                      | Public web URL used in email links (defaults to the first `APP_ORIGIN`)                                                                        |
| `MONGODB_URI`                                                                                         | Replica-set connection string                                                                                                                  |
| `SESSION_COOKIE_NAME`                                                                                 | Default `gms_session`                                                                                                                          |
| `IP_HASH_SALT`                                                                                        | Random secret of at least 16 characters (IP addresses are stored only as salted hashes)                                                        |
| `TRUST_PROXY`                                                                                         | `0` locally; **`2` behind Vercel + Render** (required in staging/production; verify, `docs/DEPLOYMENT.md` §3 and §8)                           |
| `LOG_LEVEL`                                                                                           | `info` by default                                                                                                                              |
| `LOGIN_DELAY_BASE_MS`                                                                                 | Progressive login delay base (1000 by default)                                                                                                 |
| `SMTP_HOST` · `SMTP_PORT` · `SMTP_USER` · `SMTP_PASS` · `SMTP_SECURE` · `MAIL_FROM`                   | Admin password reset. **Required in staging and production**: the server refuses to start without them                                         |
| `CLOUDINARY_CLOUD_NAME` · `CLOUDINARY_API_KEY` · `CLOUDINARY_API_SECRET` · `CLOUDINARY_FOLDER_PREFIX` | Image uploads (Phase 2). Empty means uploads answer 503 and the UI explains this (P-05)                                                        |
| `SCHEDULER_ENABLED`                                                                                   | `true` on exactly one instance; defaults to true outside tests (D-81)                                                                          |
| `API_RATE_LIMIT`                                                                                      | Optional. General API requests per IP per 15 minutes; default and minimum 600. Leave empty in production unless many staff share one IP (D-93) |

| `WHATSAPP_MODE` | `disabled` \| `mock` \| `live` (Phase 7, D-116). Empty: `mock` (simulated, nothing is sent) in development, `disabled` in staging/production. `mock` is refused in production |
| `WHATSAPP_API_VERSION` · `WHATSAPP_PHONE_NUMBER_ID` · `WHATSAPP_BUSINESS_ACCOUNT_ID` · `WHATSAPP_ACCESS_TOKEN` · `WHATSAPP_APP_SECRET` · `WHATSAPP_VERIFY_TOKEN` | All required for `live` (P-06). The token and secrets are secrets: environment variables only, never in the repository or the client |
| `WHATSAPP_GRAPH_URL` | Tests only (points the live adapter at a fake Graph server). Leave empty |

| `BACKUP_STORAGE` | `none` (default) \| `s3` \| `filesystem` (Phase 9, D-132). `filesystem` is for development only and is refused in staging/production |
| `BACKUP_ENCRYPTION_KEY` | 32 random bytes in base64 (`openssl rand -base64 32`). Required whenever backups are on. Secret: Render secret environment plus an offline copy held by the gym owner and the operator. Without it no backup can be restored |
| `BACKUP_DIR` | Local folder, only with `BACKUP_STORAGE=filesystem` |
| `BACKUP_S3_ENDPOINT` · `BACKUP_S3_REGION` · `BACKUP_S3_BUCKET` · `BACKUP_S3_ACCESS_KEY_ID` · `BACKUP_S3_SECRET_ACCESS_KEY` · `BACKUP_S3_PREFIX` · `BACKUP_S3_FORCE_PATH_STYLE` | S3-compatible storage (P-08). Region, bucket and both keys are required for `s3`; the endpoint is empty for AWS S3 itself. Use a key limited to this one bucket |

### `client/.env`

| Variable        | Purpose                                             |
| --------------- | --------------------------------------------------- |
| `VITE_APP_NAME` | Gym name shown until Gym Settings exist (Phase 2/9) |
| `VITE_API_BASE` | `/api/v1` (same origin everywhere)                  |

Client variables are public by nature. **No secrets go in the client.**

## 4. First run

```bash
git clone <repository-url> gym-management-system      # P-01: repository pending — or unzip the checkpoint
cd gym-management-system
npm install                                            # installs both workspaces
cp server/.env.example server/.env                     # fill in MONGODB_URI and IP_HASH_SALT at least
cp client/.env.example client/.env

# Local MongoDB as a single-node replica set (skip if using Atlas):
mkdir -p .mongo-data                                   # git-ignored
mongod --replSet rs0 --dbpath ./.mongo-data --port 27017 --bind_ip 127.0.0.1
#   then once:  mongosh --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"127.0.0.1:27017"}]})'
#   MONGODB_URI=mongodb://127.0.0.1:27017/gms_dev?replicaSet=rs0

npm run dev:server                                     # API on http://localhost:4000
npm run dev:client                                     # Vite on http://localhost:5173 (proxies /api)
npm run setup-token -w server                          # prints the one-time first-Admin token (24 h)
# open http://localhost:5173/setup, paste the token, create the first Admin
```

## 5. Scripts

| Command                                     | Purpose                                                                                      |
| ------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `npm run dev:server` / `npm run dev:client` | Run the API / the web app (watch mode)                                                       |
| `npm run build`                             | Production build of the client → `client/dist`                                               |
| `npm run lint` / `npm run format`           | ESLint / Prettier                                                                            |
| `npm run test:server`                       | Server unit + API tests (in-memory MongoDB replica set)                                      |
| `npm run test:client`                       | Client unit tests (jsdom)                                                                    |
| `npm run test:e2e`                          | Playwright end-to-end + visual suite (needs MongoDB at `E2E_MONGODB_URI` and a built client) |
| `npm run i18n:check -w client`              | Checks that English and Urdu have the same keys                                              |
| `npm run setup-token -w server`             | Operator: first-Admin setup token                                                            |
| `npm run sync-indexes -w server`            | Creates every collection and index (deployments, the browser suite)                          |
| `npm run backup -w server`                  | Operator: take a backup now (the weekly job does the same; Phase 9)                          |
| `npm run restore -w server -- …`            | Operator only: restore a backup into an **empty** database (`docs/BACKUP_RESTORE.md` §5)     |

## 5a. Running the tests

```bash
npm run lint                                  # ESLint (there is no type checker: the project is JavaScript by decision, Master Prompt §4)
npm run test:server                           # starts its own in-memory MongoDB replica set
npm run test:client
npm run i18n:check -w client                  # English and Urdu have the same keys
npm run build                                 # production build of the client (the server has no build step)
# Browser tests need a local replica set at E2E_MONGODB_URI (default mongodb://127.0.0.1:27017/gms_e2e?replicaSet=rs0)
# and a built client; the suite drops and recreates that database:
npm run build && npm run test:e2e             # about 20 minutes, including the visual suite
```

## 5b. Troubleshooting (local)

| Symptom                                                                        | Fix                                                                                                    |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `npm ci` / `npm install` says "Unsupported engine"                             | Use Node 22.22.2+, 24.15.0+ or 26+ (`node -v`)                                                         |
| Server: "Invalid environment configuration"                                    | It lists every missing or invalid variable; at least `MONGODB_URI` and `IP_HASH_SALT` (16+ characters) |
| Server: "Transaction numbers are only allowed on a replica set"                | MongoDB is not running as a replica set: start it with `--replSet rs0` and run `rs.initiate` once      |
| Health check says `"db":"down"`                                                | MongoDB not running or wrong `MONGODB_URI`                                                             |
| `/setup` says setup is complete                                                | An Admin already exists; sign in, or use a fresh database                                              |
| Setup token expired or lost                                                    | Run `npm run setup-token -w server` again (only while no Admin exists)                                 |
| "This request was blocked because it did not come from the app" in development | Open the app on `http://localhost:5173` (the address in `APP_ORIGIN`), not `127.0.0.1`                 |
| Password reset email "not arriving" in development                             | It is printed in the server log (no SMTP in development)                                               |
| Server: "holds an unfinished restore"                                          | `MONGODB_URI` points at a partially restored database (`docs/BACKUP_RESTORE.md` §5)                    |

## 6. Notes for restricted networks (e.g. Claude's workspace)

- `mongodb-memory-server` downloads a MongoDB binary on first use. If `fastdl.mongodb.org` is blocked, install MongoDB another way and set `MONGOMS_SYSTEM_BINARY=/path/to/mongod` (optionally `MONGOMS_VERSION` to match). In the workspace, MongoDB 8.3 was installed from conda-forge with micromamba.
- Playwright browser downloads may be blocked too. Set `PLAYWRIGHT_CHROME=/path/to/chrome` to use an installed Chrome.

## 7. Coding conventions

- JavaScript (ES modules) only, with no TypeScript (Master Prompt §4).
- Business logic lives in services only. Routes are thin and must declare their access (D-72).
- Every UI string goes in `client/src/i18n/locales/{en,ur}.json`. Colours come from design tokens only (D-69).
- Each change updates `CHANGELOG.md` and, when relevant, `docs/API.md` or `docs/DATABASE.md`.
