# Architecture

> **Status:** the request pipeline (§4), counters (§5.4), the deletion-safeguard service (§5.6, staff accounts only), the frontend foundation (§8: routing for Phase 1 screens, contexts, design system, navigation, localisation) and error handling (§9) are **implemented (Phase 1)**. Phase 2 added image handling (§5.7), the scheduler with the asset clean-up job (§6), the Cloudinary integration code (§7; not yet configured) and the public website, Join form, Plans, Website and Inquiries screens (§8.1). Phase 3 added the members module (registration and inquiry conversion in one transaction, the archive block, read-only archived members, member photos through §5.7, the deletion dependency check through §5.6) and the Members, Add/Edit Member and Member Profile screens. Phase 4 added business-date maths (§5.1), the membership state machine and lifecycle job (§5.2, §6 `membershipLifecycle`), the payment-summary calculation for the initial payment (§5.3, without receipts), the Add Membership, Activate and Upcoming Expiries screens and the memberships section of the member profile. Phase 5 completed §5.3 (all payment entries, verification, rejection, corrections with the immutable log, receipts with void and reissue, PDF receipts, the receipt backfill at start-up, dependency-checked payment deletion) and added the Payment page and the Admin Payments ledger. Phase 6 added the exercises, workout-notes and dashboard modules (server) and the Exercises screen, the workout-notes card on the member profile and the Trainer dashboard sections (client). Phase 7 implemented the notification outbox (§5.5: outbox, guards at enqueue and dispatch, dispatcher with 3 retries, signed webhooks), the jobs `notificationDispatcher`, `expiryReminders` and `templateStatusSync` (§6), the WhatsApp Cloud API and simulated providers (§7) and the WhatsApp screens. Phase 8 added the expenses and reports modules (one shared financial-figures module for the dashboard and reports, on-demand report PDFs with pdfmake) and the Admin dashboard, Expenses and Reports screens. Phase 9 added the backups module (§6 `backup`, encrypted weekly backups, operator-only restore script), the audit viewers and the Settings screen. Phase 10 completed final QA; hosting is prepared (`docs/DEPLOYMENT.md`) but **not deployed**.
> Baseline: approved SRS v2.0 + Master Development Prompt. Decision IDs (C-, D-, X-, P-) refer to `docs/DECISIONS.md`.

---

## 1. System overview

```
                 ┌──────────────────────────── Browser (phone first) ────────────────────────────┐
                 │  React SPA (Vite build)                                                        │
                 │   • Public website  (/, /plans, /trainers, /about, /gallery, /contact, /join)  │
                 │   • Staff app       (/login, /setup, /app/...)  Admin | Trainer views          │
                 └───────────────┬───────────────────────────────────────────────────────────────┘
                                 │ HTTPS, same origin  (D-02)
                 ┌───────────────▼──────────────┐
                 │ Vercel                        │  static assets + rewrite /api/* → Render
                 └───────────────┬──────────────┘
                                 │ HTTPS
                 ┌───────────────▼──────────────────────────────────────────────┐
                 │ Render web service (always-on, D-59)                          │
                 │  Express REST API  /api/v1                                    │
                 │  Scheduler (node-cron, Asia/Karachi) + Mongo lease lock       │
                 │   – membership lifecycle  – expiry reminders                  │
                 │   – notification dispatcher (outbox)  – asset cleanup retry   │
                 │   – weekly backup                                             │
                 └───┬──────────────┬───────────────┬───────────────┬───────────┘
                     │              │               │               │
          ┌──────────▼───┐  ┌───────▼──────┐  ┌─────▼──────┐  ┌─────▼─────────────┐
          │ MongoDB Atlas │  │ Cloudinary   │  │ Meta WA    │  │ SMTP provider     │
          │ (replica set, │  │ images       │  │ Cloud API  │  │ (Admin reset)     │
          │ transactions) │  └──────────────┘  │ + webhooks │  └───────────────────┘
          └───────────────┘                    └────────────┘
                     │
          ┌──────────▼────────────┐
          │ S3-compatible storage  │  encrypted weekly backups (D-61)
          └───────────────────────┘
```

Meta webhooks call the Render service URL directly (`/api/v1/webhooks/whatsapp`); they do not go through Vercel.

---

## 2. Approved stack and supporting libraries

| Layer     | Approved (C-34)                                                                         | Supporting choice (recommended)                                                                                                                                                                                |
| --------- | --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Frontend  | React + Vite, JavaScript, Tailwind CSS, React Router, Context API, React Hook Form, Zod | `@hookform/resolvers`, Axios (single API client), Lucide React, Recharts, `i18next` + `react-i18next`, `sonner` (toasts), `@fontsource` Inter + Noto Nastaliq Urdu                                             |
| Backend   | Node.js, Express, REST, Mongoose                                                        | `zod`, `helmet`, `cors`, `cookie-parser`, `express-rate-limit`, `argon2`, `pino` + `pino-http`, `node-cron`, `multer`, `cloudinary`, `pdfmake`, `nodemailer`, `libphonenumber-js`, `date-fns` + `@date-fns/tz` |
| Database  | MongoDB Atlas                                                                           | Transactions, partial unique indexes, TTL indexes                                                                                                                                                              |
| Testing   | —                                                                                       | Vitest, Supertest, `mongodb-memory-server`, Testing Library, Playwright                                                                                                                                        |
| Hosting   | Vercel, Render, Cloudinary, Atlas                                                       | S3-compatible object storage for backups (P-08)                                                                                                                                                                |
| Messaging | Meta WhatsApp Cloud API                                                                 | Native `fetch` (no SDK)                                                                                                                                                                                        |

No TypeScript. No additional framework. No Redis.

---

## 3. Repository layout (planned)

```
gym-management-system/
├── package.json                # npm workspaces: client, server; root scripts
├── README.md  PROJECT_STATUS.md  HANDOVER.md  CHANGELOG.md  NEXT_STEPS.md
├── .env.example (per workspace)  .gitignore  .editorconfig
├── docs/                       # this documentation set
├── client/
│   ├── index.html  vite.config.js  vercel.json
│   ├── public/
│   ├── src/
│   │   ├── main.jsx
│   │   ├── app/                # router.jsx, routes config, guards (RequireAuth, RequireRole), providers
│   │   ├── layouts/            # PublicLayout, AuthLayout, DashboardLayout
│   │   ├── components/
│   │   │   ├── ui/             # design-system primitives (see §8.3)
│   │   │   └── navigation/     # Sidebar, MobileTopBar, BottomNav, MoreDrawer, PageHeader
│   │   ├── features/           # one folder per domain feature:
│   │   │   │                   #   pages/  components/  api.js  schemas.js  hooks.js
│   │   │   ├── public-site/  auth/  dashboard/  inquiries/  members/  memberships/
│   │   │   ├── plans/  payments/  receipts/  exercises/  workout-notes/  whatsapp/
│   │   │   └── reports/  expenses/  users/  settings/  website-content/  audit/  backups/
│   │   ├── context/            # AuthContext, ThemeContext, LocaleContext, SettingsContext
│   │   ├── lib/
│   │   │   ├── api/            # client.js (axios instance), errors.js, endpoints per feature
│   │   │   ├── format.js       # PKR, Asia/Karachi dates, phone display
│   │   │   └── permissions.js  # copy of permission keys for UI visibility only
│   │   ├── i18n/               # index.js, locales/en.json, locales/ur.json
│   │   └── styles/             # tokens.css (light/dark), index.css
│   └── tests/                  # unit/, e2e/
└── server/
    ├── src/
    │   ├── server.js           # boot: env → db → app → scheduler
    │   ├── app.js              # express app + middleware chain + routes
    │   ├── config/             # env.js (Zod-validated), db.js, logger.js, constants.js
    │   ├── middleware/         # requestId, httpLogger, securityHeaders, cors, originCheck,
    │   │                       # authenticate, authorize, validate, rateLimiters, upload,
    │   │                       # notFound, errorHandler
    │   ├── permissions/        # matrix.js (single source of truth), can.js
    │   ├── modules/
    │   │   ├── auth/ users/ settings/ content/ gallery/ public-trainers/
    │   │   ├── plans/ inquiries/ members/ consent/ memberships/
    │   │   ├── payments/ receipts/ exercises/ workout-notes/
    │   │   ├── notifications/ (templates, outbox, webhooks)
    │   │   ├── expenses/ reports/ dashboard/ audit/ backups/
    │   │   └── deletion/       # shared dependency-check + safeguarded delete service
    │   │       # each module: <name>.model.js  <name>.routes.js  <name>.controller.js
    │   │       #              <name>.service.js  <name>.validators.js
    │   ├── jobs/               # scheduler.js, lock.js, membershipLifecycle.js, expiryReminders.js,
    │   │                       # notificationDispatcher.js, assetCleanup.js, weeklyBackup.js
    │   ├── integrations/
    │   │   ├── whatsapp/       # cloudApi.js, mockAdapter.js, errorClassifier.js, webhookVerify.js
    │   │   ├── cloudinary/  email/  pdf/ (receipt.js, reports.js, memberList.js)
    │   │   └── storage/        # S3-compatible backup uploads
    │   └── utils/              # businessDate.js, money.js, counters.js, ApiError.js,
    │                           # pagination.js, phone.js, actor.js, asyncHandler.js
    ├── scripts/                # create-setup-token.js, seed-dev.js, backup.js, restore.js
    └── tests/                  # unit/, integration/, helpers/
```

**Layering rule.** Routes contain no logic: they apply `authenticate`, `authorize(permission)` and `validate(schema)`, then call a controller. The controller translates HTTP into service calls. Services hold all business rules and are the only code that opens transactions. Models hold schema, indexes and invariants. Integrations are called only from services or jobs.

---

## 4. Request pipeline (server)

```
requestId → pino-http (redacting cookies/passwords) → helmet → cors(allow-list)
→ express.json({limit}) / cookieParser → originCheck (state-changing methods)
→ [route] authenticate → authorize(permissionKey) → validate(zodSchema) → controller
→ service (transaction where needed) → response envelope
→ notFound → errorHandler (maps ApiError/Zod/Mongo errors; no stack in production)
```

The **actor context** (`req.actor = { id, role, displayName }`) is attached by `authenticate`. Services receive the actor explicitly, so every write can record who did it and the activity log does not depend on global state.

---

## 5. Core business logic

### 5.1 Business dates (C-03, D-25)

- Every business date (membership start and end, payment date, expense date, registration date) is a **`YYYY-MM-DD` string interpreted in Asia/Karachi**. Instants (`createdAt`, `recordedAt`, `sentAt`) are UTC `Date` values.
- `utils/businessDate.js` will provide `today()`, `addCalendarMonthsInclusiveEnd(start, n)`, `addDaysInclusiveEnd(start, n)`, `nextDay(date)`, `compare`, `isFuture(date)`.
- Month-end rule (D-25): let `target` be the same day-of-month N months after `start`. If `target` exists, `end = target − 1 day`. If it does not exist (for example 31 Feb), `end = last day of that later month`. Custom plans: `end = start + (N − 1) days`. A full test table is in `docs/TESTING.md`.

### 5.2 Membership state machine (C-10 – C-12, D-26 – D-28)

```
            create (no verified payment)            activate (≥1 verified entry)
  ──────────────► [Pending Activation] ───────────────────────────────┐
                                                                     ▼
   create+pay+activate ─────────────────────────────►  member has Active? ──yes──► [Upcoming]
                                                                     │ no            │ start date reached
                                                                     ▼               ▼ (daily job / on read)
                                                                 [Active] ◄──────────┘
                                                                     │ end date passed (daily job / on read)
                                                                     ▼
                                                                 [Expired]
```

- **Slots:** `slot = "current"` for Active, `slot = "next"` for Pending Activation or Upcoming, no slot for Expired. A partial unique index on `{ member, slot }` enforces at most one of each (D-26).
- **Activation** requires `payment.verifiedPaid > 0`, checked inside the transaction (C-11).
- **Start date:** if an Active membership exists → `start = nextDay(active.endDate)`, status Upcoming. Otherwise → `start = today()`, status Active.
- **Member state** is updated in the same transaction: on activation, `membershipState = active`. When the job expires the last active membership and no Upcoming one takes over, `membershipState = inactive` (C-07).
- Expiry dates are never accepted from clients (C-12).

### 5.3 Payment calculations (C-13 – C-15, D-31 – D-35)

```
verifiedPaid   = Σ entries.amount where verificationStatus = verified
pendingAmount  = Σ entries.amount where verificationStatus = pending
balance        = totalDue − verifiedPaid                (never negative)
status         = balance == 0                → Paid
                 verifiedPaid > 0            → Partially Paid
                 pendingAmount > 0           → Pending
                 otherwise                   → Unpaid
guard (new/corrected entry): verifiedPaid + pendingAmount + Δ ≤ totalDue      (D-33)
guard: paymentDate ≤ today()                                                     (C-15)
```

- The summary is **recomputed from the entries** on every change, inside the same transaction. It is never adjusted incrementally.
- **Optimistic concurrency:** the summary carries a `version` field. Updates use `findOneAndUpdate({ _id, version })`; on a conflict the operation retries once and then returns 409.
- **A verified entry creates a receipt in the same transaction** (receipt number from the atomic counter).
- **A correction** writes a PaymentCorrectionLog, voids and reissues the receipt where one exists (D-35), and triggers no "payment received" message.
- Old memberships keep their own summaries. Balances are never merged (C-15).

### 5.4 Counters (D-36)

`counters` documents `{ _id: "memberId" | "receiptNumber", seq }` are advanced with `findOneAndUpdate({ $inc: { seq: 1 } }, { upsert: true, new: true, session })` inside the business transaction. Unique indexes on `memberId` and `receiptNumber` provide a second safeguard. If a transaction aborts after incrementing, that number is skipped, never duplicated. Gaps are acceptable and documented.

### 5.5 Notification outbox (C-23 – C-26, D-45 – D-51)

1. **Enqueue.** A business event (activation, verified payment, a reminder that is due, expiry) or a manual send creates a `Notification` with `status = queued`, a unique `idempotencyKey` and `nextAttemptAt`. A duplicate key means the event was already queued, so nothing more happens.
2. **Guards at enqueue _and_ dispatch.** The member is not archived, has consent and has not opted out. The template is enabled and approved by Meta. The WhatsApp integration is configured. If any guard fails → `status = blocked`, with a reason and no retries.
3. **Dispatcher** (every minute, holding the lock) claims due records with `findOneAndUpdate({ status: queued|retrying, nextAttemptAt ≤ now }, { status: sending, lockedAt })`.
4. **Send** through the adapter (`cloudApi` or `mock`).
5. **Result.** Success → `sent` + provider message ID. Transient error → `retrying`, `retryCount += 1`, `nextAttemptAt = now + 15 min`, until `retryCount = 3`; after that → `failed`, `needsFollowUp = true`. A permanent error → `failed` immediately.
6. **Webhooks** move the status on to `delivered`, `read` or `failed` only when Meta reports it.

### 5.6 Safeguarded permanent deletion (C-33, D-56)

A shared `deletion` service with one entry point, `deleteRecord(type, id, { password, reason, confirm }, actor)`:

1. Re-verify the actor's password (argon2 verify).
2. Run the dependency check for that record type. If protected dependencies remain → 409 with the list of linked records.
3. Delete inside a transaction. Write a `DeletionAudit` record (actor, timestamp, record type and reason only) and an ActivityLog entry that contains no personal data.
4. After the commit, queue external clean-up (for example Cloudinary), with retries through `AssetCleanup`.
   The UI always calls `GET …/dependencies` first, and then shows the DangerConfirm dialog (second confirmation with consequences, password and reason).

### 5.7 Image handling (C-08)

Uploads arrive through `multer` (memory storage, 5 MB limit, JPEG/PNG/WebP, file-signature check) and are sent to Cloudinary in the `gym/<env>/<kind>/` folder. The database update is committed first, and the old asset is deleted afterwards. A failed deletion is written to `AssetCleanup` and retried hourly (up to 5 attempts), then flagged for manual resolution.

---

## 6. Scheduled jobs (Asia/Karachi)

| Job                    | Schedule                   | Purpose                                                                                                                                                    |
| ---------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| membershipLifecycle    | daily 00:05                | Expire memberships whose end date has passed, promote Upcoming ones, set member Active/Inactive, queue "membership expired" messages (sent at 10:00, D-48) |
| expiryReminders        | daily 00:10                | Queue reminders for memberships whose `endDate − today = settings.expiryReminderDaysBefore` (sent at 10:00)                                                |
| notificationDispatcher | every minute               | Send queued notifications and retry due ones                                                                                                               |
| templateStatusSync     | daily 06:00, and on demand | Sync Meta template approval statuses                                                                                                                       |
| assetCleanup           | hourly                     | Retry failed Cloudinary deletions                                                                                                                          |
| backup                 | Sunday 03:00               | Encrypted backup and prune to the newest 8 (Phase 9, D-132; skipped while storage is not configured; see `docs/BACKUP_RESTORE.md`)                         |

Retention of activity logs and login history (2 years) is handled by MongoDB **TTL indexes**, not by a job. Every job is **idempotent** and acquires a lease lock (`jobLocks` collection, with a TTL). Each run is logged with counts.

---

## 7. Integrations

| Integration             | Module                    | Configured when                  | Behaviour without configuration                                                                                         |
| ----------------------- | ------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Meta WhatsApp Cloud API | `integrations/whatsapp`   | P-06 resolved                    | Mock adapter, clearly labelled; no real-send claims (D-51)                                                              |
| Cloudinary              | `integrations/cloudinary` | P-05                             | Upload endpoints return `503 INTEGRATION_NOT_CONFIGURED`; the UI explains this                                          |
| SMTP email              | `integrations/email`      | P-07                             | Development: the email is printed to the server log. Staging and production: refuse to start without SMTP configuration |
| Backup storage          | `integrations/storage`    | P-08                             | Backup job records `status = failed: not configured`; Admin sees it                                                     |
| PDF                     | `integrations/pdf`        | Always available (local library) | —                                                                                                                       |

---

## 8. Frontend architecture

### 8.1 Routing (planned)

| Path                                                                  | Access                                                           | Notes                                                                    |
| --------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `/`, `/plans`, `/trainers`, `/about`, `/gallery`, `/contact`, `/join` | Public                                                           | Single-page landing with anchor sections plus a `/join` form route       |
| `/login`, `/forgot-password`, `/reset-password`, `/setup`             | Public (guarded)                                                 | `/setup` only while setup is incomplete                                  |
| `/app`                                                                | Admin, Trainer                                                   | Role dashboard                                                           |
| `/app/members`, `/app/members/new`, `/app/members/:id`                | Admin, Trainer                                                   | Profile tabs: Overview, Memberships, Payments, Receipts, Notes, Messages |
| `/app/inquiries`, `/app/inquiries/:id`                                | Admin                                                            |                                                                          |
| `/app/plans`                                                          | Admin (manage); Trainer reads plans inside the renewal flow only |                                                                          |
| `/app/payments`                                                       | Admin                                                            | Ledger-wide list. Trainers work with payments from the member profile    |
| `/app/exercises`                                                      | Admin, Trainer                                                   |                                                                          |
| `/app/whatsapp/templates`, `/app/whatsapp/history`                    | Admin (all); Trainer (view/send, own history)                    |                                                                          |
| `/app/expenses`, `/app/reports`                                       | Admin                                                            |                                                                          |
| `/app/staff`                                                          | Admin                                                            | Trainer and Admin accounts                                               |
| `/app/settings/*`                                                     | Admin                                                            | Gym, website content, gallery, public trainers, reminders, language      |
| `/app/audit/activity`, `/app/audit/logins`, `/app/backups`            | Admin                                                            |                                                                          |
| `/app/profile`                                                        | Admin, Trainer                                                   |                                                                          |

The route guards hide screens, **but the server enforces every rule** (Prompt §6).

### 8.2 State

- `AuthContext`: current user, role, permissions and login/logout. Bootstrapped from `GET /auth/me`.
- `SettingsContext`: public gym settings (name, logo, currency, default language).
- `ThemeContext`, `LocaleContext`.
- Server data is fetched per feature through small hooks (`useMembers`, `useMember(id)`, …) built on the API layer, with explicit loading, error and empty states. No global data cache library (Context only, as approved).

### 8.3 Design system

- **Tokens** (`styles/tokens.css`) map the official palettes to CSS variables for `:root` (light) and `[data-theme="dark"]`:
  - Light: `--bg #FFFFFF`, `--bg-subtle #F5F7FA`, `--text #172B4D`, `--text-muted #667085`, `--primary #3266D5`, `--border #E5EAF1`, `--card #FFFFFF`
  - Dark: `--bg #101828`, `--card #182438`, `--sidebar #111C2E`, `--text #F2F4F7`, `--text-muted #AAB5C5`, `--primary #6B91F0`, plus a derived dark border
  - Status: success `#24834B`, warning `#C58A24`, error `#C74747`, each with a soft background tint for badges
  - Tailwind's theme refers **only** to these variables, so no colour can be used outside the palette.
- **Shape:** 8–12px radius, 1px subtle borders, at most a single soft shadow level, a 4px spacing scale.
- **Type:** Inter with a restrained scale (mobile headings 18–22px, body 14–16px, numbers with tabular figures). Urdu uses Noto Nastaliq Urdu with increased line height.
- **Primitives:** Button, IconButton, Input, Textarea, Select, Checkbox, Switch, DateField, MoneyField, PhoneField, Field (label, hint, error), Card, StatCard, Badge, StatusBadge, DataTable (md and up), MobileList (cards), Pagination, Tabs, Modal (desktop), BottomSheet (mobile), ConfirmDialog, DangerConfirm (password and reason), Toast, Skeleton, EmptyState, ErrorState, PageHeader, FilterBar, SearchInput.

### 8.4 Navigation (C-02)

- **Phone (< 768px):** top bar (page title, back, theme and language, account) and a bottom navigation bar: Dashboard · Members · Payments (Admin) or Exercises (Trainer) · **+** quick actions (bottom sheet: Add member, Record payment, Renew) · More (a drawer with every other permitted section). Safe-area insets are respected. Content is never hidden behind fixed bars.
- **Tablet (768–1023px):** collapsed icon sidebar and a wider content grid.
- **Desktop (≥ 1024px):** collapsible sidebar (labels and icons, state remembered), top bar, 12-column grid.
- Lists render as cards on phones and as tables from `md` up. Tables that must stay wide scroll inside their own container (C-02, SRS §13).

### 8.5 Localisation (C-03, D-52, D-53)

- All UI strings live in `i18n/locales/{en,ur}.json`, using namespaced keys (`members.form.phone.label`). No hard-coded UI text in components.
- `<html lang dir>` is switched by `LocaleContext`. Layouts use Tailwind logical utilities (`ms-*`, `me-*`, `ps-*`, `start-*`), and direction-dependent icons are mirrored.
- Numbers and dates are formatted with `Intl` (`en-PK` and `ur-PK`), with the currency shown as "Rs". PDFs stay English (C-03).

---

## 9. Error handling and responses

- One `ApiError(status, code, message, details)` class. Zod errors map to `400 VALIDATION_ERROR` with field details. Mongo duplicate-key errors map to `409` with a domain code (for example `MEMBER_PHONE_EXISTS`).
- In production no stack traces or internal messages leave the server. Each response carries a `requestId` for support.
- The client normalises errors in `lib/api/errors.js`. Forms map `details` to field errors, and everything else shows a toast.

---

## 10. Environments

| Environment | Frontend                                   | Backend                   | Database                           | Integrations                                        |
| ----------- | ------------------------------------------ | ------------------------- | ---------------------------------- | --------------------------------------------------- |
| Development | Vite dev server (proxy `/api` → localhost) | Local Node                | Atlas dev cluster or local MongoDB | Mock WhatsApp, console email, Cloudinary dev folder |
| Staging     | Vercel (staging project or preview)        | Render staging service    | Atlas staging                      | Meta test number when available; real SMTP          |
| Production  | Vercel production                          | Render production service | Atlas production                   | Live                                                |

The details are in `docs/DEPLOYMENT.md`.
