# Technical Handover

**Last updated:** 20 Nov 2026 — end of Phase 10 (final QA, deployment readiness & handover)
**State in one line:** all phases (0–10) are complete. Every SRS v2.0 feature is implemented, tested and documented, and a final QA, security and accessibility audit was done. The app is **ready to deploy but not deployed**: hosting (Render, Vercel, Atlas) and the external services (SMTP, Cloudinary, Meta WhatsApp, backup storage) still need real accounts (P-02 – P-08), so those integrations are built but **untested against the real services**.

## 1. Project overview

A single-gym Gym Management System. It has a public website and an internal dashboard for **Admin** and **Trainer** accounts; members do not log in. The approved requirements are in `docs/SRS.md` and every decision is in `docs/DECISIONS.md` (C = confirmed, X = conflict, D = delegated, P = pending external).

## 2. Technology stack

React 19 + Vite 8 (JavaScript), Tailwind CSS 4, React Router 8, Context API, React Hook Form, Zod 4, i18next, Axios, Lucide, sonner · Node.js (`^22.22.2 || ^24.15.0 || >=26.0.0`, D-110; production Node 24 LTS) + Express 5 REST · MongoDB (Atlas planned) + Mongoose 9 · argon2 · pino · Vitest, Supertest, mongodb-memory-server, Testing Library, Playwright. Versions are in D-67.

## 3. Folder structure

```
gym-management-system/
├── package.json  eslint.config.js  .prettierrc.json  .editorconfig  .gitignore
├── README.md  PROJECT_STATUS.md  HANDOVER.md  CHANGELOG.md  NEXT_STEPS.md
├── docs/            SRS, DECISIONS, PHASE0_REVIEW, ARCHITECTURE, DATABASE, API, SECURITY,
│                    TESTING, SETUP, DEPLOYMENT, BACKUP_RESTORE, ADMIN_GUIDE, TRAINER_GUIDE
├── server/
│   ├── .env.example  package.json  vitest.config.js
│   ├── scripts/create-setup-token.js · sync-indexes.js · backfill-receipts.js · backup.js · restore.js (operator)
│   ├── src/
│   │   ├── server.js  app.js
│   │   ├── config/        env.js (Zod) · logger.js · db.js (connect, syncIndexes, withTransaction) · constants.js
│   │   ├── http/router.js           route wrapper: every route declares access; route registry
│   │   ├── middleware/    core.js (requestId, context, originCheck, requireJson, errors) · auth.js
│   │   │                  (authenticate, authorize, cookies) · validate.js · rateLimiters.js
│   │   ├── permissions/matrix.js    the permission matrix (SECURITY §4.2)
│   │   ├── modules/
│   │   │   ├── auth/      models (session, tokens), services (auth, session, password), loginThrottle,
│   │   │   │              validators, controller, routes
│   │   │   ├── users/     user.model, users.service/controller/routes/validators
│   │   │   ├── audit/     audit.models (LoginHistory, ActivityLog, DeletionAudit), audit.service, auditViewer.service + routes (Phase 9)
│   │   │   ├── deletion/  deletion.service (safeguards shared by all permanent deletions)
│   │   │   ├── settings/  settings.model (GymSettings singleton, defaults)
│   │   │   ├── content/   public site, gym settings, page content, trainer cards, gallery (Phase 2)
│   │   │   ├── plans/     membership plans (Phase 2)
│   │   │   ├── inquiries/ Join Now inquiries, prefill, member-match flag (Phase 2, D-91)
│   │   │   ├── consent/   immutable ConsentHistory (Phase 2)
│   │   │   ├── media/     upload helpers, asset clean-up queue (Phase 2)
│   │   │   ├── members/   member.model, members.service/controller/routes/validators (Phase 3)
│   │   │   ├── memberships/ membership.model, lifecycle.js (reconcile, daily job), service, routes (Phase 4)
│   │   │   ├── payments/  payment.models, payment.logic, ledger.js (shared add/recompute/receipt), payments.service,
│   │   │   │              receipt.model, receipt.pdf.js (pdfmake), correction.model (immutable), routes (Phase 5)
│   │   │   ├── exercises/ exercise.model (unique name key), service, validators, routes (Phase 6)
│   │   │   ├── notes/     workoutNote.model (soft delete only), notes.service (ownership, archive guard), routes (Phase 6)
│   │   │   ├── dashboard/ dashboard.service (Trainer dashboard Phase 6; Admin dashboard Phase 8), routes
│   │   │   ├── expenses/  expense.model, service (history, version check, safeguarded delete), routes (Phase 8)
│   │   │   ├── reports/   finance.js (shared figures, no net profit), reports.service, reports.pdf, routes (Phase 8)
│   │   │   ├── backups/   backupRun.model, format (EJSON+gzip+AES-GCM), storage (S3/local), backup.service, restore (Phase 9)
│   │   │   ├── whatsapp/  templates, outbox, dispatcher (retries), events, notifications, webhook, routes;
│   │   │   │              providers/ (cloudApi = Meta Cloud API, mock = simulated, errors) (Phase 7)
│   │   │   └── system/    counter.model (atomic sequences), health.routes
│   │   ├── jobs/scheduler.js        lease lock; hourly asset clean-up; daily 00:05 membership lifecycle
│   │   ├── integrations/  email/ (SMTP or console) · cloudinary/ (503 until P-05)
│   │   └── utils/         ApiError, actor, crypto, respond, passwordPolicy, mongoosePlugins
│   └── tests/      unit/ · integration/ · helpers/ (globalSetup, testApp)
└── client/
    ├── index.html  vite.config.js  vercel.json  playwright.config.js  .env.example
    ├── public/     favicon.svg · theme-init.js (theme/language before first paint, CSP-safe)
    ├── scripts/check-i18n.js
    ├── src/
    │   ├── main.jsx  app/ (App.jsx routes + lazy loading, guards.jsx)
    │   ├── layouts/       PublicLayout · AuthLayout · DashboardLayout
    │   ├── components/ui/ design-system primitives (index.js exports all)
    │   ├── components/navigation/  navItems.js · Brand · Preferences (theme/language toggles)
    │   ├── context/       Auth · Locale · Theme · Site
    │   ├── features/      auth/ · dashboard/ · staff/ · profile/ · public-site/ · plans/ · website/
    │   │                  · inquiries/ · members/ (list, form, profile; Phase 3)
    │   │                  · memberships/ (card, add, activate, expiries; Phase 4)
    │   │                  · payments/ (payment page, dialogs, Admin ledger; Phase 5)
    │   │                  · exercises/ · notes/ (WorkoutNotesCard) · dashboard/TrainerDashboard (Phase 6)
    │   │                  · whatsapp/ (page, messages, templates, send and share dialogs; Phase 7)
    │   │                  · dashboard/AdminDashboard · expenses/ · reports/ (Phase 8)
    │   │                  · settings/ (SettingsPage, BackupWarning; Phase 9) · shared/
    │   ├── lib/           api/client.js (axios + error normalisation) · api/endpoints.js · errors.js · format.js · zodConfig.js (CSP)
    │   ├── i18n/          index.js · locales/en.json · locales/ur.json
    │   └── styles/index.css         design tokens (light/dark), Tailwind theme
    └── tests/      unit/ · e2e/ (01-flow, 03-phase2-flow, 04-phase3-flow, 05-phase4-flow, 06-phase5-flow, 07-phase6-flow, 08-phase7-flow, 08-phase8-flow, 08-phase9-flow, 09-visual, 10-final-qa, global-setup, backup-env)
```

## 4. Completed development

Phase 0 (planning), Phase 1 (Foundation), Phase 2 (Public website & inquiries), Phase 3 (Member management), Phase 4 (Membership management, Revision 1), Phase 5 (Payments & receipts, Revision 1), Phase 6 (Trainer experience), Phase 7 (WhatsApp), Phase 8 (Dashboards, reports & expenses), Phase 9 (Settings & operational security, Revision 1) and **Phase 10 (final QA, deployment readiness & handover)**. The full list is in `PROJECT_STATUS.md`.

## 5. Current implementation status

| Area                                                                                                                                                                                                                            | Status                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Auth, sessions, password policy, setup, reset                                                                                                                                                                                   | ✅ Implemented and tested                                                                                              |
| Permission matrix and route access enforcement                                                                                                                                                                                  | ✅ Implemented and tested (all routes)                                                                                 |
| Staff account management                                                                                                                                                                                                        | ✅ Implemented and tested                                                                                              |
| Audit writers (activity, login, deletion)                                                                                                                                                                                       | ✅ Implemented and tested                                                                                              |
| Design system, themes, Urdu/RTL, shells                                                                                                                                                                                         | ✅ Implemented; visual suite passes                                                                                    |
| Public website, Join Now form, plans, website content (settings, content, trainer cards, gallery), inquiries + conversion prefill                                                                                               | ✅ Implemented and tested (Phase 2)                                                                                    |
| Image uploads to Cloudinary                                                                                                                                                                                                     | ⚠️ Code complete; answers 503 until P-05; **real Cloudinary untested**                                                 |
| Members: registration, inquiry conversion, list/search/filters, profile, edit, Admin notes, archive/restore (both roles), photos, WhatsApp opt-out/consent, deletion dependency check                                           | ✅ Implemented and tested (Phase 3). Members with protected history are archived, not deleted (X-21 resolved, D-131)   |
| Memberships: create, Admin custom price, initial payment, activation, early/late renewal, lifecycle job, history, upcoming expiries, dependency-blocked deletion                                                                | ✅ Implemented and tested (Phase 4). Payments beyond the initial entry and receipts are Phase 5 (D-94)                 |
| Payments and receipts: entries, verify/reject, corrections with immutable log, receipts (PDF, void and reissue), backfill for Phase 4 payments, Admin ledger, dependency-checked deletion                                       | ✅ Implemented and tested (Phase 5). Receipt sharing is Phase 7                                                        |
| Exercise library (unique names, no delete), workout notes (author/Admin rules, soft delete, deleted filter, archived read-only), Trainer dashboard, Trainer lifecycle re-verified                                               | ✅ Implemented and tested (Phase 6)                                                                                    |
| WhatsApp: templates (Meta review status), four automatic events, manual sends, receipt sharing with manual fallback, consent/opt-out at queue and send, 3 retries, signed webhooks, history (Admin all, Trainer own), follow-up | ✅ Implemented; tested with a fake provider, a fake Graph server and the simulated mode. **Real Meta untested (P-06)** |
| Admin dashboard (server-computed figures, chart), expenses (Admin, history, safeguarded delete), PDF reports (income, expenses, summary without net profit, member list, password-protected full export)                        | ✅ Implemented and tested (Phase 8)                                                                                    |
| Settings screen, Activity Log and Login history viewers, security/retention rules, encrypted weekly backups, operator-only restore, hardening, protected history undeletable                                                    | ✅ Implemented and tested (Phase 9). **Real backup bucket untested (P-08)**                                            |
| Final QA: cross-phase journey, production CSP, accessibility (axe), production-mode start, security audit; Admin and Trainer guides; deployment guide                                                                           | ✅ Done (Phase 10)                                                                                                     |
| Staging, production, user acceptance on real phones, real-service checks                                                                                                                                                        | ⏳ Needs real accounts (`NEXT_STEPS.md` §1)                                                                            |

## 6. Important files and responsibilities

| File                                                    | Responsibility                                                                                                                                                                                                                    |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `server/src/permissions/matrix.js`                      | **The** source of role permissions. Add keys here only                                                                                                                                                                            |
| `server/src/http/router.js`                             | `createRouter(base, env, registry)`. Routes must pass `{public:true}`, `{session:true}` or a permission key                                                                                                                       |
| `server/src/middleware/auth.js`                         | Session lookup, user status check, sliding expiry, rotation, `authorize()`                                                                                                                                                        |
| `server/src/modules/auth/session.service.js`            | Create, find, touch, rotate and revoke sessions                                                                                                                                                                                   |
| `server/src/modules/deletion/deletion.service.js`       | Password + reason + confirm safeguards and the deletion audit. Reuse for every permanent delete                                                                                                                                   |
| `server/src/modules/audit/audit.service.js`             | `logActivity`, `logLogin`, `diffChanges` (personal fields logged by name only)                                                                                                                                                    |
| `server/src/modules/system/counter.model.js`            | `nextSequence(name, session)` for Member IDs (Phase 3) and receipt numbers (Phase 5)                                                                                                                                              |
| `server/src/modules/memberships/lifecycle.js`           | `reconcileMember` (expire, promote, member state, `lifecycleVersion`), `reconcileIfStale` (on read), `runMembershipLifecycle` (daily job). Idempotent (D-97)                                                                      |
| `server/src/modules/memberships/memberships.service.js` | Create (snapshot, custom price, summary, initial payment), activate (dates, member Active), history, upcoming expiries, deletion. Uses the injected `clock`                                                                       |
| `server/src/modules/payments/ledger.js`                 | The only place that adds entries, recomputes summaries (with the `version` check) and issues receipts. Used by memberships and payments                                                                                           |
| `server/src/modules/payments/payments.service.js`       | Record, verify, reject, correct, correct total, receipts, backfill, deletion order                                                                                                                                                |
| `server/src/utils/businessDate.js`                      | `today`, `addDays`, `nextDay`, `monthlyEndDate` (D-25), `customEndDate`, `daysBetween`, `systemClock`                                                                                                                             |
| `server/src/modules/members/members.service.js`         | Member rules: registration and conversion (one transaction), archive block, read-only archived members, consent history, `MEMBER_DEPENDENCIES` for deletion (D-87). Phase 4 must write the member document when activating (D-92) |
| `server/src/modules/reports/finance.js`                 | The only place income, expense and outstanding figures are computed; used by the Admin dashboard and the reports so they agree (D-125). No net profit (C-21)                                                                      |
| `server/src/modules/reports/reports.pdf.js`             | Report PDF layout: header, filters, generation stamp, page numbers (D-129)                                                                                                                                                        |
| `server/src/modules/backups/backup.service.js`          | Weekly encrypted backup, keep 8, prune after success, status (D-132)                                                                                                                                                              |
| `server/src/modules/backups/restore.js`                 | Operator-only restore: full validation, `restoreState` marker, `PARTIAL_RESTORE`, verified `--resume`, lease; `assertNotPartialRestore` used by the server and scripts (D-136). Never deletes or overwrites                       |
| `server/src/utils/mongoosePlugins.js`                   | `immutable` and `undeletable` (protected history, D-131). Apply `undeletable` to any new history collection                                                                                                                       |
| `client/src/styles/index.css`                           | Design tokens. Tailwind's default palette is disabled                                                                                                                                                                             |
| `client/src/components/ui/*`                            | Reusable components. Use them; do not restyle per screen                                                                                                                                                                          |
| `client/src/components/navigation/navItems.js`          | Add a nav entry when a new section ships                                                                                                                                                                                          |
| `client/src/i18n/locales/*.json`                        | All UI text. Run `npm run i18n:check -w client`                                                                                                                                                                                   |

## 7. Database collections and relationships

Implemented: `users`, `sessions` (TTL), `passwordResetTokens` (TTL), `setupState`, `loginHistory` (TTL 2y, immutable), `activityLogs` (TTL 2y, immutable), `deletionAudits` (immutable), `gymSettings`, `counters` (Phase 1); `siteContent`, `publicTrainers`, `galleryAssets`, `assetCleanups`, `membershipPlans`, `inquiries`, `consentHistory` (immutable), `jobLocks` (Phase 2); `members` (Phase 3); `memberships`, `payments`, `paymentEntries` (Phase 4); `receipts`, `paymentCorrectionLogs` (Phase 5); `exercises`, `workoutNotes` (Phase 6); `notificationTemplates`, `notifications` (Phase 7); `expenses` (Phase 8); `backupRuns` (Phase 9); `restoreState` (only in a restored database, Revision 1). Fields and indexes follow `docs/DATABASE.md`. The other collections are planned there.

## 8. API endpoints implemented

Phase 9: `/audit/activity` (+ `/filters`) · `/audit/logins` · `/settings/security` · `/backups` (all Admin, read-only; no restore route), see `docs/API.md` §17. Phase 8: `/expenses` (list, create, detail with history, edit, dependencies, safeguarded delete) · `/reports/income|expenses|summary|members` (+ `.pdf`) · `POST /reports/members/full-export` · `GET /dashboard/admin`, see `docs/API.md` §14–16. Phase 7: `/whatsapp/status|templates|preview|send` · `/notifications` (list, detail, follow-up) · `/receipts/:id/share/whatsapp|manual` · `/webhooks/whatsapp` (GET verify, POST signed), see `docs/API.md` §11 and §13. Phase 6: `/exercises` (list, create, detail, edit; no delete) · `/members/:memberId/workout-notes` (list with `status`, create) · `/workout-notes/:id` (edit) · `/workout-notes/:id/delete` (soft) · `GET /dashboard/trainer`, see `docs/API.md` §12 and §16. Phase 5: `/members/:id/payments|receipts` · `/payments` (ledger, detail, entries, correct-total, dependencies, delete) · `/payment-entries/:id/verify|reject|correct|dependencies|delete-permanently` · `/receipts/:id` (+ `/pdf`, dependencies, delete), see `docs/API.md` §10–11. Phase 4: `/members/:id/memberships` (list, create) · `/memberships/:id` · `/memberships/:id/activate` · `/memberships/upcoming-expiries` · `/memberships/:id/dependencies|delete-permanently`, see `docs/API.md` §9. Phase 3: `/members` (list, counts, create incl. `fromInquiryId`, profile, edit, archive, restore, photo upload and safeguarded removal, consent history, WhatsApp opt-out and consent, dependencies, safeguarded delete), see `docs/API.md` §8. Phase 2: `GET /public/site` · `POST /public/inquiries` · `/settings` (+ `/logo`) · `/content` (+ `/:section/image`) · `/public-trainers` (CRUD, photo, reorder, delete) · `/gallery` (CRUD, image, reorder, delete) · `/plans` (list, create, edit, activate/deactivate) · `/inquiries` (list, counts, detail, status, conversion-prefill, dependencies, delete). Phase 1: `GET /api/v1/health` · `/auth/setup/status` · `POST /auth/setup` · `/auth/login` · `/auth/logout` · `GET /auth/me` · `PATCH /auth/me/profile` · `POST /auth/me/password` · `/auth/password/forgot` · `/auth/password/reset` · `GET/POST /users` · `GET/PATCH /users/:id` · `POST /users/:id/deactivate|reactivate|reset-password|force-logout|delete-permanently` · `GET /users/:id/dependencies`. Contracts are in `docs/API.md` §2–11.

## 9. Authentication and authorization

An opaque 256-bit token sits in the `gms_session` cookie (httpOnly, SameSite=Lax, Secure when deployed); the DB stores only its SHA-256 hash. The session is checked on every request, together with `user.status === 'active'`, so deactivation is immediate. Sessions slide to 90 days of inactivity and the token rotates after 24 hours with a 60-second grace period. Passwords use argon2id. Login applies the progressive delay plus an IP rate limit. Non-GET requests need an allowed Origin. Trainers get 403 on every Admin-only route, which an automated test verifies across the whole route registry.

## 10. Environment variable names

`server/.env.example` and `client/.env.example`. Details are in `docs/SETUP.md` §3.

## 11. Installation

`npm install` at the root (workspaces). See `docs/SETUP.md` §4.

## 12. Start the frontend

`npm run dev:client` → http://localhost:5173. It proxies `/api` to `localhost:4000`.

## 13. Start the backend

`npm run dev:server`. It needs `server/.env` with `MONGODB_URI` (replica set) and `IP_HASH_SALT`. Then run `npm run setup-token -w server`.

## 14. Build and test

`npm run build` · `npm run lint` · `npm run test:server` · `npm run test:client` · `npm run test:e2e`. Restricted-network notes are in `docs/SETUP.md` §6.

## 15. External integrations

| Integration                    | Status                                                                                                                                               |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| SMTP email                     | Code ready. Console transport in development. **Real SMTP untested (P-07)**                                                                          |
| MongoDB Atlas                  | Not connected (P-04). A local replica set is used                                                                                                    |
| Cloudinary                     | Code ready (`server/src/integrations/cloudinary`), used by website images and member photos. **Not configured, untested (P-05)**; uploads answer 503 |
| Meta WhatsApp                  | Code ready (Phase 7). **Real Meta untested (P-06)**; simulated mode in development                                                                   |
| Backup storage (S3-compatible) | Code ready (Phase 9). Tested with a local folder and a local fake S3 server. **Real bucket untested (P-08)**                                         |
| Vercel/Render                  | Not started (P-02, P-03), Phase 10                                                                                                                   |

## 16. Remaining tasks

No development phase remains. Going live (accounts, staging, real-service checks, UAT, production) is listed in `NEXT_STEPS.md` §1 and described in `docs/DEPLOYMENT.md`.

## 17. Known bugs and limitations

No open bugs. Limitations are listed in `PROJECT_STATUS.md`: real Cloudinary untested, members archived rather than deleted (D-131), real backup bucket untested, receipt and report PDFs without a logo, workout notes keep only their latest edit (D-112), report size limits (D-127), English server field messages, draft Urdu, real WhatsApp untested.

## 18. Open technical decisions

None open in the register (X-21 resolved by D-131). External items P-01 to P-12.

## 19. Exact next steps

1. The owner and operator follow `NEXT_STEPS.md` §1 (accounts → staging → backups and restore drill → UAT on real phones → Urdu review → WhatsApp → production), using `docs/DEPLOYMENT.md`.
2. Changes beyond the approved SRS (`NEXT_STEPS.md` §2) need a change request first.
3. For any future maintenance: keep protected history undeletable (D-131), restore only into an empty database or resume a verified partial restore (D-132, D-136), income and expenses separate (C-21), the WhatsApp outbox rules (D-116 – D-123), and run the full suite (`docs/SETUP.md` §5a) before every release.

## 20. Instructions for another Claude conversation

Paste this into a new conversation, preferably in the same claude.ai Project ("GYM-Website"), and attach the latest ZIP plus the SRS .docx:

```text
We are continuing an existing project: the Gym Management System (single gym, MERN, JavaScript).
Do NOT start a new project and do NOT rebuild or overwrite completed work.

1. Unzip the attached checkpoint. Read, in order: docs/SRS.md (approved SRS v2.0), HANDOVER.md,
   PROJECT_STATUS.md, CHANGELOG.md, NEXT_STEPS.md, docs/DECISIONS.md, then the rest of docs/.
   The original Master Development Prompt also applies; ask me for it if it is not attached.
2. Verify the real state before changing anything: npm install; npm run lint; npm run test:server;
   npm run test:client; npm run build (and npm run test:e2e if MongoDB and a browser are available).
   If MongoDB/Playwright downloads are blocked, follow docs/SETUP.md §6. Report any difference
   from PROJECT_STATUS.md.
3. All phases are complete; work only on what I ask (fixes or approved change requests), from NEXT_STEPS.md.
4. Preserve every confirmed requirement (C-entries) and recorded decision (D/X/P). Never silently
   change, simplify or remove a requirement; record new decisions in docs/DECISIONS.md.
   X-21 is resolved (D-131): never delete, anonymise or detach protected history.
5. Reuse the existing design system (client/src/components/ui, tokens in styles/index.css), the route
   wrapper (server/src/http/router.js), the permission matrix and the deletion-safeguard service.
6. Run tests before and after changes. Never report mocked integrations as working.
7. After each milestone update PROJECT_STATUS.md, HANDOVER.md, CHANGELOG.md, NEXT_STEPS.md and
   docs/, make a git commit, and provide a ZIP (no node_modules, no .env, no secrets).
Do not assume you remember anything from earlier conversations.
```
