# API Specification (planned)

> **Status:** §2 Health, §3 Auth and §4 Users are **implemented (Phase 1)**. §5 Settings/content/gallery/public trainers, §6 Plans and §7 Inquiries are **implemented (Phase 2)**. §8 Members is **implemented (Phase 3)**. §9 Memberships is **implemented (Phase 4)**. §10 Payments and §11 Receipts are **implemented (Phase 5)**, except receipt sharing (Phase 7, D-108). §12 Exercises and workout notes and `GET /dashboard/trainer` (§16) are **implemented (Phase 6)**. §13 WhatsApp and receipt sharing (§11) are **implemented (Phase 7)**. §14 Expenses, §15 Reports and `GET /dashboard/admin` (§16) are **implemented (Phase 8)**. §17 Settings, audit and backups is **implemented (Phase 9)**; every API response is `no-store` except `GET /public/site` (D-134). All sections are now implemented. Changes are recorded in `CHANGELOG.md` and in this file.
> Baseline: SRS §16 functional areas. Permission keys are defined in `docs/SECURITY.md` §4.2. Decision IDs refer to `docs/DECISIONS.md`.

## 1. Conventions

- **Base path:** `/api/v1` (D-64). Through Vercel the browser calls `https://<app>/api/v1/...` (same origin).
- **Auth:** session cookie `gms_session`. In the tables below, **Public** means no session is needed. Every other route needs an active session plus the listed permission.
- **Content type:** `application/json`; upload routes use `multipart/form-data`.
- **Success envelope:**
  ```json
  { "success": true, "data": {}, "meta": { "page": 1, "limit": 20, "total": 134, "totalPages": 7 } }
  ```
- **Error envelope:**
  ```json
  {
    "success": false,
    "error": {
      "code": "VALIDATION_ERROR",
      "message": "…",
      "details": [{ "path": "phone", "message": "…" }],
      "requestId": "…"
    }
  }
  ```
- **Status codes:** 200 OK, 201 Created, 204 No Content, 400 validation, 401 not authenticated, 403 forbidden, 404 not found, 409 conflict (duplicate, business-rule block, concurrency), 410 gone (setup completed), 422 business rule violation with a domain code, 429 rate-limited, 503 integration not configured, 500 unexpected.
- **Lists:** `?page=1&limit=20` (limit at most 100), `?sort=-createdAt`, plus filters per endpoint.
- **Money:** integer PKR. **Business dates:** `YYYY-MM-DD` (Asia/Karachi).
- **Safeguarded delete body** (C-33), used by every `…/delete-permanently` route:
  ```json
  { "password": "<current admin password>", "reason": "5–500 chars", "confirm": true }
  ```
  These routes are `POST` (not `DELETE`), so that a body can be sent reliably. Each has a matching `GET …/dependencies`.

### Common domain error codes

`MEMBER_PHONE_EXISTS`, `MEMBER_ARCHIVED`, `ARCHIVE_BLOCKED_ACTIVE_MEMBERSHIP`, `MEMBERSHIP_SLOT_TAKEN`, `ACTIVATION_REQUIRES_VERIFIED_PAYMENT`, `PLAN_INACTIVE`, `OVERPAYMENT`, `FUTURE_PAYMENT_DATE`, `REASON_REQUIRED`, `VERSION_CONFLICT`, `DEPENDENCIES_EXIST`, `INVALID_PASSWORD`, `LAST_ADMIN`, `SELF_ACTION_FORBIDDEN`, `WHATSAPP_OPTED_OUT`, `WHATSAPP_NO_CONSENT`, `TEMPLATE_NOT_APPROVED`, `INTEGRATION_NOT_CONFIGURED`, `SETUP_COMPLETED`, `RATE_LIMITED`. Added in Phase 3: `MEMBER_NOT_ARCHIVED`, `WHATSAPP_CONSENT_ACTIVE`, `INQUIRY_ALREADY_CONVERTED` (D-88). Added in Phase 4: `MEMBERSHIP_NOT_PENDING` (409), `INVALID_PRICE` (422, D-96). Added in Phase 5: `ENTRY_NOT_PENDING` (409), `ENTRY_REJECTED` (409), `NO_CHANGES` (400), `TOTAL_BELOW_PAID` (422) (D-106). Added in Phase 6: `EXERCISE_NAME_EXISTS` (409), `NOT_NOTE_AUTHOR` (403), `NOTE_DELETED` (409). Added in Phase 8: `FUTURE_EXPENSE_DATE`, `REPORT_TOO_LARGE` (422). Added in Phase 7: `TEMPLATE_EXISTS`, `TEMPLATE_NOT_APPROVED`, `RECEIPT_VOID`, `NO_FOLLOW_UP_NEEDED` (409); `INVALID_WHATSAPP_NUMBER`, `TEMPLATE_NOT_MANUAL`, `VARIABLE_UNAVAILABLE` (422).

---

## 2. Health — ✅ implemented (Phase 1)

| Method | Path      | Access | Notes                                                                    |
| ------ | --------- | ------ | ------------------------------------------------------------------------ |
| GET    | `/health` | Public | `{ status, version, db: "up"\|"down" }`. Used by the Render health check |

## 3. Auth (SRS §11) — ✅ implemented (Phase 1)

The session token is rotated by the authentication middleware on **any** authenticated request once it is older than 24 h, not only on `/auth/me` (D-65).

| Method | Path                    | Access                | Request → Response                                                                                                         |
| ------ | ----------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/auth/setup/status`    | Public                | → `{ setupAvailable: boolean }`                                                                                            |
| POST   | `/auth/setup`           | Public + setup token  | `{ token, username, email, displayName, password }` → 201 with the session cookie. 410 once setup is completed (C-30)      |
| POST   | `/auth/login`           | Public                | `{ identifier, password }` → `{ user }` + cookie. Generic 401. Progressive delay. 429 (D-06)                               |
| POST   | `/auth/logout`          | Session               | → 204. Revokes the current session                                                                                         |
| GET    | `/auth/me`              | Session               | → `{ user: { id, username, displayName, role, preferredLanguage }, permissions: [...] }`. Rotates the token when it is due |
| PATCH  | `/auth/me/profile`      | `profile.self`        | Trainer: `{ displayName?, phone?, preferredLanguage? }`. Admin: the same plus `email?` (D-14)                              |
| POST   | `/auth/me/password`     | `password.changeSelf` | `{ currentPassword, newPassword }` → 204. Revokes other sessions. Trainers get 403 (C-27)                                  |
| POST   | `/auth/password/forgot` | Public                | `{ email }` → always 202. An email is sent only for an active Admin account (D-07)                                         |
| POST   | `/auth/password/reset`  | Public                | `{ token, newPassword }` → 204. Revokes all sessions                                                                       |

## 4. Users / staff accounts (SRS §11.6, D-09) — ✅ implemented (Phase 1)

`GET /users` excludes tombstoned (deleted) accounts unless `status=deleted` is requested. Other error codes in use: `TARGET_NOT_TRAINER` (422), `USERNAME_EXISTS` / `EMAIL_EXISTS` (409), `WEAK_PASSWORD` (400), `CONFIRMATION_REQUIRED` (400), `ORIGIN_REJECTED` (403), `UNSUPPORTED_MEDIA_TYPE` (415), `INVALID_JSON` (400).

| Method | Path                            | Permission            | Notes                                                                                                                                                               |
| ------ | ------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/users`                        | `users.manage`        | Filters: `role`, `status`. Includes `lastLoginAt`                                                                                                                   |
| POST   | `/users`                        | `users.manage`        | `{ role, username, email?, displayName, phone?, password }`. Email required for an admin                                                                            |
| GET    | `/users/:id`                    | `users.manage`        |                                                                                                                                                                     |
| PATCH  | `/users/:id`                    | `users.manage`        | `{ displayName?, email?, phone? }`. Username and role are not editable                                                                                              |
| POST   | `/users/:id/deactivate`         | `users.manage`        | `{ reason? }`. Revokes all sessions. Refused for yourself and for the last active Admin                                                                             |
| POST   | `/users/:id/reactivate`         | `users.manage`        |                                                                                                                                                                     |
| POST   | `/users/:id/reset-password`     | `users.resetPassword` | Trainer targets only: `{ newPassword }`. Revokes the Trainer's sessions                                                                                             |
| POST   | `/users/:id/force-logout`       | `users.forceLogout`   | Trainer targets. Revokes all sessions (C-27)                                                                                                                        |
| GET    | `/users/:id/dependencies`       | `users.manage`        | Counts of historical records that will be kept: `activityLogs`, `loginHistory`; from Phase 6 also `workoutNotes` (authored) and `paymentEntries` (recorded) (D-115) |
| POST   | `/users/:id/delete-permanently` | `users.manage`        | Safeguarded. Tombstones the account (D-13)                                                                                                                          |

## 5. Settings, website content, gallery, public trainers — ✅ implemented (Phase 2)

Uploads use multipart field `file` (JPEG/PNG/WebP by signature, max 5 MB). Without Cloudinary they answer `503 INTEGRATION_NOT_CONFIGURED` (D-75). Other errors: `IMAGE_REQUIRED`, `INVALID_IMAGE` (400), `FILE_TOO_LARGE` (413). `GET`/`PATCH /settings` also return `integrations: { mediaUploads: boolean }`. `GET /public-trainers/:id/dependencies` and `GET /gallery/:id/dependencies` return `{ blocking: [], retained: [] }`. `GET /public/site` sends `Cache-Control: public, max-age=60` and never exposes storage identifiers. Since Phase 9 every other API response is `Cache-Control: no-store` (D-134). `GET /settings/security` (`settings.manage`) returns the approved security and retention rules, read-only (D-133); see §17.

| Method      | Path                                      | Permission        | Notes                                                                                                             |
| ----------- | ----------------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------- |
| GET         | `/public/site`                            | Public            | One call for the public site: settings subset, content, active plans (ordered), visible trainers, visible gallery |
| GET         | `/settings`                               | `settings.manage` | The full settings document                                                                                        |
| PATCH       | `/settings`                               | `settings.manage` | Gym identity, contact, hours, `defaultLanguage`, `expiryReminderDaysBefore` (1–30)                                |
| PUT         | `/settings/logo`                          | `settings.manage` | multipart `file`                                                                                                  |
| GET / PATCH | `/content`                                | `content.manage`  | Hero, About, intros (`{en, ur}` fields)                                                                           |
| PUT         | `/content/:section/image`                 | `content.manage`  | `section` is `hero` or `about`                                                                                    |
| GET         | `/gallery`                                | `gallery.manage`  | Includes hidden items                                                                                             |
| POST        | `/gallery`                                | `gallery.manage`  | multipart `file` + `caption_en`, `caption_ur`                                                                     |
| PATCH       | `/gallery/:id`                            | `gallery.manage`  | `{ caption?, isVisible? }`                                                                                        |
| PUT         | `/gallery/:id/image`                      | `gallery.manage`  | Replace the image. The old asset is cleaned up after commit                                                       |
| POST        | `/gallery/reorder`                        | `gallery.manage`  | `{ orderedIds: [...] }`                                                                                           |
| POST        | `/gallery/:id/delete-permanently`         | `gallery.manage`  | Safeguarded (D-56)                                                                                                |
| GET / POST  | `/public-trainers`                        | `content.manage`  |                                                                                                                   |
| PATCH       | `/public-trainers/:id`                    | `content.manage`  |                                                                                                                   |
| PUT         | `/public-trainers/:id/photo`              | `content.manage`  |                                                                                                                   |
| POST        | `/public-trainers/reorder`                | `content.manage`  |                                                                                                                   |
| POST        | `/public-trainers/:id/delete-permanently` | `content.manage`  | Safeguarded                                                                                                       |

## 6. Membership plans (SRS §6.1) — ✅ implemented (Phase 2)

| Method | Path                                            | Permission     | Notes                                                                                             |
| ------ | ----------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------- |
| GET    | `/plans`                                        | `plans.read`   | `?active=true` for staff renewal pickers                                                          |
| POST   | `/plans`                                        | `plans.manage` | `{ name{en,ur}, description{en,ur}, durationType, durationValue, price, isActive, displayOrder }` |
| PATCH  | `/plans/:id`                                    | `plans.manage` | A price change is logged. Existing memberships are unaffected (D-30)                              |
| POST   | `/plans/:id/activate` · `/plans/:id/deactivate` | `plans.manage` | There is no delete route                                                                          |

## 7. Inquiries (SRS §4) — ✅ implemented (Phase 2; conversion = prefill only, D-79)

| Method | Path                                | Permission           | Notes                                                                                                                                                                                                                                                                                                                                        |
| ------ | ----------------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| POST   | `/public/inquiries`                 | Public, rate-limited | `{ fullName, phone, age, gender, address, preferredPlanId?, whatsappConsent: boolean, acknowledgeDuplicate?: boolean }`. If the phone matches an earlier inquiry and `acknowledgeDuplicate` is not true → 200 `{ requiresConfirmation: true }` and nothing is saved. Otherwise → 201 `{ submitted: true }` (D-17). Never returns member data |
| GET    | `/inquiries`                        | `inquiries.manage`   | Filters: `status`, `q` (name or phone), `from`, `to`, `converted`                                                                                                                                                                                                                                                                            |
| GET    | `/inquiries/counts`                 | `inquiries.manage`   | → `{ new, pending, approved, rejected }` (navigation badge, dashboard card; D-76)                                                                                                                                                                                                                                                            |
| GET    | `/inquiries/:id`                    | `inquiries.manage`   | Includes duplicate metadata and the conversion link                                                                                                                                                                                                                                                                                          |
| PATCH  | `/inquiries/:id/status`             | `inquiries.manage`   | `{ status: new\|pending\|approved\|rejected, note? }`                                                                                                                                                                                                                                                                                        |
| GET    | `/inquiries/:id/conversion-prefill` | `inquiries.manage`   | → the fields for the member form, plus the consent snapshot. 409 `INQUIRY_ALREADY_CONVERTED` if already converted                                                                                                                                                                                                                            |
| GET    | `/inquiries/:id/dependencies`       | `inquiries.manage`   | → nothing blocks; reports a converted member and consent history as retained                                                                                                                                                                                                                                                                 |
| POST   | `/inquiries/:id/delete-permanently` | `inquiries.manage`   | Safeguarded. The member is unaffected (C-04)                                                                                                                                                                                                                                                                                                 |

Conversion itself is `POST /members` with `fromInquiryId` (below).

## 8. Members (SRS §5) — ✅ implemented (Phase 3)

| Method | Path                                    | Permission                                                          | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------ | --------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/members`                              | `members.read`                                                      | `q` (name; phone digits; Member ID as `GYM-012`, `gym12` or `12`, D-90), `state=active\|inactive`, `archived=true` (archived only; otherwise archived members are excluded), `registeredFrom`, `registeredTo` (business dates), `sort=newest\|oldest\|name\|memberId`, `page`, `limit`. Paged                                                                                                                                                                                                                                                      |
| GET    | `/members/counts`                       | `members.read`                                                      | `{ active, inactive, archived }` for the list tabs and the dashboard (D-90)                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| POST   | `/members`                              | `members.create` (+ `inquiries.manage` when `fromInquiryId` is set) | `{ fullName, phone, age, gender, address, whatsappConsent, adminNotes?, fromInquiryId? }` → 201 with the profile (`memberId` from the atomic counter, D-36). Duplicate phone → 409 `MEMBER_PHONE_EXISTS` (field `phone`). `adminNotes` from a Trainer → 403. `fromInquiryId` from a Trainer → 403. With `fromInquiryId`, the inquiry gets `conversion` and status Approved in the same transaction (D-19); a second conversion → 409 `INQUIRY_ALREADY_CONVERTED`. Consent history entry: `staff_registration` or `inquiry_conversion` (D-20, D-86) |
| GET    | `/members/:id`                          | `members.read`                                                      | Profile: personal details, photo `{ url, width, height }`, `status` (`active`\|`inactive`\|`archived`), `membershipState`, `archive`, `whatsapp` state, `adminNotes` (both roles can read, D-22), `registeredOn`, `createdBy`, `updatedBy`, and `capabilities.photoUploads`. **No inquiry details or source inquiry** (Prompt §9.3). Memberships, payments and notes are added to this response by Phases 4–6                                                                                                                                      |
| PATCH  | `/members/:id`                          | `members.update`                                                    | Any of `fullName, phone, age, gender, address`; `adminNotes` needs `members.adminNotes.edit` (403 otherwise). Unsent fields are untouched (D-73). Logged with field names only (D-62). 409 `MEMBER_ARCHIVED` if archived; 409 `MEMBER_PHONE_EXISTS`                                                                                                                                                                                                                                                                                                |
| PUT    | `/members/:id/photo`                    | `members.photo.upload`                                              | multipart `file` (JPEG/PNG/WebP, 5 MB, signature-checked). The old asset is removed after the change is saved (C-08). **503 `INTEGRATION_NOT_CONFIGURED` until Cloudinary is set up (P-05).** 409 if archived                                                                                                                                                                                                                                                                                                                                      |
| POST   | `/members/:id/photo/delete-permanently` | `members.photo.remove`                                              | Safeguarded (C-08, C-33). The member stays. 404 if there is no photo. 409 if archived                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| POST   | `/members/:id/archive`                  | `members.archive`                                                   | `{ reason? }`. Admin and Trainer (C-38). 409 `ARCHIVE_BLOCKED_ACTIVE_MEMBERSHIP`; 409 `MEMBER_ARCHIVED` if already archived                                                                                                                                                                                                                                                                                                                                                                                                                        |
| POST   | `/members/:id/restore`                  | `members.restore`                                                   | Admin and Trainer (C-38). The same record and ID (C-06). 409 `MEMBER_NOT_ARCHIVED`                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| GET    | `/members/:id/consent-history`          | `members.read`                                                      | Newest first: `{ id, event, source, actor, note, at }`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| POST   | `/members/:id/whatsapp/opt-out`         | `members.consent.optOut`                                            | `{ note? }`. 409 `WHATSAPP_OPTED_OUT` if already opted out                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| POST   | `/members/:id/whatsapp/consent`         | `members.consent.restore`                                           | `{ note }` (required, 3–300 chars). `consent_restored` after an opt-out, otherwise `consent_given` (D-89). 409 `WHATSAPP_CONSENT_ACTIVE`                                                                                                                                                                                                                                                                                                                                                                                                           |
| GET    | `/members/:id/dependencies`             | `members.delete`                                                    | `{ canDelete, blocking: [{ type, handling: "separate"\|"protected", count }], dependencies: [...all types], retained: [{ type: "sourceInquiry", count }] }` (D-87)                                                                                                                                                                                                                                                                                                                                                                                 |
| POST   | `/members/:id/delete-permanently`       | `members.delete`                                                    | Safeguarded. 409 `DEPENDENCIES_EXIST` while any linked record remains. Consent history is always present, so this is blocked in practice; **D-131 (Phase 9) resolves X-21 by keeping the block**: archive the member instead. `GET …/dependencies` also returns `protectedHistory` and `alternative: "archive"`. Nothing is deleted, anonymised or detached to get past the block                                                                                                                                                                  |

Inquiry responses (§7) now also include `duplicate.matchesExistingMember` (live, Admin only, D-91) and, for a converted inquiry, `conversion.member: { id, memberId } | null` (null if the member has since been deleted).

## 9. Memberships (SRS §6) — ✅ implemented (Phase 4)

A **membership view** is `{ id, memberId, status (pending_activation|upcoming|active|expired), plan: { id, name{en,ur}, durationType, durationValue, advertisedPrice }, agreedPrice, customPrice: { isCustom, reason, setBy }, startDate, endDate, daysLeft (active only), activatedAt, activatedBy, expiredAt, createdAt, createdBy, payment: { id, totalDue, verifiedPaid, pendingAmount, balance, status (paid|partially_paid|pending|unpaid), hasPendingVerification, lastPaymentDate } }`. Dates are business dates computed by the server (C-12). The **initial payment** is `{ amount (integer ≥ 1), method: cash|online, paymentDate (≤ today, backdating allowed), verificationStatus: verified|pending, reference? (≤ 200) }`. **Cash must be `verified`**; cash + `pending` → 400 `VALIDATION_ERROR` on `initialPayment.verificationStatus` (D-102). Online may be either.

| Method | Path                                  | Permission                                                           | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ------ | ------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/members/:id/memberships`            | `members.read`                                                       | `{ current, next, history }`. `history` holds every membership, newest first. Reconciles the lifecycle first (D-28, D-97)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| POST   | `/members/:id/memberships`            | `memberships.create` (+ `memberships.customPrice` for `customPrice`) | `{ planId, customPrice?, customPriceReason?, initialPayment?, activate? }` → 201 with the membership view. Created as Pending Activation in the `next` slot, with its payment summary, all in one transaction. `customPrice` from a Trainer → 403; without a reason → 400; logged as `membership.custom_price` with the old and new price (C-09). `activate: true` needs a **verified** initial payment, otherwise 422 `ACTIVATION_REQUIRES_VERIFIED_PAYMENT` and nothing is saved. Errors: 409 `MEMBER_ARCHIVED` (D-21), 422 `PLAN_INACTIVE`, 422 `INVALID_PRICE` (D-96), 409 `MEMBERSHIP_SLOT_TAKEN` (a Pending Activation or Upcoming membership already exists, D-26), 422 `OVERPAYMENT`, 422 `FUTURE_PAYMENT_DATE`. Unknown fields such as `startDate` → 400 |
| GET    | `/memberships/:id`                    | `members.read`                                                       | The membership view plus `entries: [{ id, amount, method, paymentDate, recordedAt, recordedBy, verificationStatus, reference }]`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| POST   | `/memberships/:id/activate`           | `memberships.activate`                                               | `{ initialPayment? }` (recorded as verified, D-95). Needs `verifiedPaid ≥ 1`, otherwise 422 `ACTIVATION_REQUIRES_VERIFIED_PAYMENT`. With an Active membership → **Upcoming**, starting the day after it ends (early renewal). Otherwise → **Active** from today (late renewal or first membership), and the member becomes Active (C-07). The end date follows D-25 (monthly) or start + days − 1 (custom). 409 `MEMBERSHIP_NOT_PENDING` if already activated; 409 `MEMBER_ARCHIVED`                                                                                                                                                                                                                                                                              |
| GET    | `/memberships/upcoming-expiries`      | `memberships.upcomingExpiries` (Admin)                               | `?days=7                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | 14                                                                            | 30`(default 7). →`{ days, today, items: [{ membershipId, member: { id, memberId, fullName, phone, phoneDisplay }, plan: { name }, endDate, daysLeft, renewal: null | upcoming | pending_activation, balance }] }`. Archived members excluded (D-98) |
| GET    | `/memberships/:id/dependencies`       | `memberships.delete`                                                 | `{ canDelete, blocking: [{ type: payments                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | paymentEntries, handling: "separate", count }], dependencies, retained: [] }` |
| POST   | `/memberships/:id/delete-permanently` | `memberships.delete`                                                 | Safeguarded. 409 `DEPENDENCIES_EXIST` while the payment summary exists, which is always the case in Phase 4 (D-99). No cascade                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |

There are no endpoints that edit start or end dates, pause, cancel or change a plan (C-12). The lifecycle (Upcoming → Active, Active → Expired, member Active/Inactive) runs daily at 00:05 Asia/Karachi, and whenever a member profile or its memberships are read (D-97).

## 10. Payments (SRS §7) — ✅ implemented (Phase 5)

A **payment detail** is the summary view (§9) plus `version`, `membership: { id, status, plan, startDate, endDate }`, `member: { id, memberId, fullName, isArchived }`, `entries: [{ id, amount, method, paymentDate, reference, verificationStatus (verified|pending|rejected), recordedAt, recordedBy, verifiedAt, verifiedBy, rejectedAt, rejectedBy, rejectionReason, correctionCount, receipt: { id, receiptNumber } | null, voidReceipts: [{ id, receiptNumber }] }]` and `corrections: [{ id, targetType: entry|summary, entryId, changes: [{ field, from, to }], reason, actor, at }]` (newest first). Every write returns the updated detail. Archived members → 409 `MEMBER_ARCHIVED` on every write (D-21). A stale `expectedVersion` → 409 `VERSION_CONFLICT` (D-105).

| Method | Path                                                                           | Permission                       | Notes                                                                                                                                                                                                                                                                                                                       |
| ------ | ------------------------------------------------------------------------------ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/members/:id/payments`                                                        | `payments.read.member`           | Every payment detail of the member (one per membership), newest first                                                                                                                                                                                                                                                       |
| GET    | `/payments/:id`                                                                | `payments.read.member`           | Payment detail                                                                                                                                                                                                                                                                                                              |
| GET    | `/payments`                                                                    | `payments.read.all` (Admin)      | Ledger: `status`, `hasBalance=true`, `q` (member name or ID), `page`, `limit`. Rows: summary + `member` + `membership`                                                                                                                                                                                                      |
| POST   | `/payments/:id/entries`                                                        | `payments.record`                | `{ amount, method, paymentDate, verificationStatus: verified\|pending, reference?, expectedVersion }` → 201. Cash must be verified (400). 422 `OVERPAYMENT` (verified + pending + new > total), 422 `FUTURE_PAYMENT_DATE`. A verified entry gets its receipt in the same transaction                                        |
| POST   | `/payment-entries/:id/verify`                                                  | `payments.verify`                | `{ expectedVersion? }`. Pending → verified; issues the receipt. 409 `ENTRY_NOT_PENDING`. Does not activate the membership (D-108)                                                                                                                                                                                           |
| POST   | `/payment-entries/:id/reject`                                                  | `payments.verify`                | `{ reason (5–500), expectedVersion? }`. Pending → rejected; it never counts. 409 `ENTRY_NOT_PENDING`                                                                                                                                                                                                                        |
| POST   | `/payment-entries/:id/correct`                                                 | `payments.correct.entry`         | `{ amount?, method?, paymentDate?, reference?, reason, expectedVersion }`. Writes an immutable PaymentCorrectionLog. For a verified entry, the receipt is voided and a new one issued (D-104). 409 `ENTRY_REJECTED`; 400 `NO_CHANGES`; 400 when a pending entry would become cash; overpayment and future-date guards apply |
| POST   | `/payments/:id/correct-total`                                                  | `payments.correct.total` (Admin) | `{ totalDue, reason, expectedVersion }`. Not below `max(1, verified + pending)` → 422 `TOTAL_BELOW_PAID`. Logged as a summary correction; receipts are not reissued                                                                                                                                                         |
| GET    | `/payments/:id/dependencies` · `/payment-entries/:id/dependencies`             | `payments.delete` (Admin)        | Summary: blocked by entries. Entry: blocked by receipts (valid or void). `retained` lists correction logs                                                                                                                                                                                                                   |
| POST   | `/payments/:id/delete-permanently` · `/payment-entries/:id/delete-permanently` | `payments.delete` (Admin)        | Safeguarded, no cascade (C-17, D-107). Deleting an entry recalculates the summary                                                                                                                                                                                                                                           |

## 11. Receipts (SRS §7.4) — ✅ implemented (Phase 5; sharing in Phase 7)

A **receipt** is `{ id, receiptNumber (REC-0001…), status: valid|void, entryId, paymentId, memberId, snapshot: { gymName, logoUrl, memberName, memberCode, planName, startDate, endDate, totalDue, eventAmount, cumulativePaid, balance, method, paymentDate, reference }, issuedAt, issuedBy, voidReason, voidedAt, voidedBy, replacedBy, replaces, backfilled }`. `snapshot` is a plain object with exactly these 14 fields (missing values are `null`); `GET /receipts/:id` adds `replacedByNumber`. A receipt for a payment taken when the membership is activated carries its start and end dates; one recorded while the membership is still Pending Activation has empty dates (D-109). One valid receipt per verified entry (C-16).

| Method | Path                                                                   | Permission                | Notes                                                                                                                                                                                                                                                                                                                                                      |
| ------ | ---------------------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/members/:id/receipts`                                                | `receipts.read`           | Newest first, valid and void                                                                                                                                                                                                                                                                                                                               |
| GET    | `/receipts/:id`                                                        | `receipts.read`           | The receipt, plus `replacedByNumber`                                                                                                                                                                                                                                                                                                                       |
| GET    | `/receipts/:id/pdf`                                                    | `receipts.read`           | `application/pdf` (pdfmake, English, `Cache-Control: no-store`). Void receipts carry a VOID watermark and name their replacement                                                                                                                                                                                                                           |
| GET    | `/receipts/:id/dependencies` · POST `/receipts/:id/delete-permanently` | `receipts.delete` (Admin) | Nothing blocks. The entry records `receiptDeletedAt`, so the receipt is not re-issued (D-107)                                                                                                                                                                                                                                                              |
| POST   | `/receipts/:id/share/whatsapp`                                         | `receipts.share`          | ✅ Phase 7. `{ requestId }` → 202 with the message (the receipt PDF as a document header). Needs the default `receipt_share` template to be sendable, else 409 `TEMPLATE_NOT_APPROVED` with `details: [{ path: fallback, message: manual }]`. 409 `RECEIPT_VOID`, `WHATSAPP_OPTED_OUT`, `WHATSAPP_NO_CONSENT`, `MEMBER_ARCHIVED`. It never claims delivery |
| POST   | `/receipts/:id/share/manual`                                           | `receipts.share`          | ✅ Phase 7. `{ requestId, note? }` → 201: records that staff shared the PDF themselves (status `manual_share`, never shown as sent or delivered, D-49). Refused for opted-out or non-consenting members and for void receipts                                                                                                                              |

## 12. Exercises and workout notes (SRS §8) — ✅ implemented (Phase 6)

An **exercise** is `{ id, name, description, instructions, createdAt, createdBy, updatedAt, updatedBy }` (names of the staff members). A **note** is `{ id, memberId, text, author: { id, name, role, accountStatus: active|deactivated|deleted|null }, createdAt, editedAt, editedBy, editCount, isDeleted, deletedAt, deletedBy, version, canEdit, canDelete }`. `author.name` is the name recorded when the note was written (D-13); `accountStatus` is the author's account today. `canEdit` / `canDelete` say what the signed-in user may do; the server checks again.

| Method | Path                               | Permission         | Notes                                                                                                                                                                                                                                                                                     |
| ------ | ---------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/exercises`                       | `exercises.read`   | `q` (name contains, case-insensitive, escaped), `page`, `limit` (≤ 100). Sorted by name. Paged                                                                                                                                                                                            |
| POST   | `/exercises`                       | `exercises.create` | `{ name (2–100), description? (≤ 500), instructions? (≤ 2000) }` → 201. Spaces are collapsed; the name is unique **ignoring letter case and extra spaces** → 409 `EXERCISE_NAME_EXISTS` (field `name`), also when two people add it at once (D-111). Unknown fields → 400                 |
| GET    | `/exercises/:id`                   | `exercises.read`   |                                                                                                                                                                                                                                                                                           |
| PATCH  | `/exercises/:id`                   | `exercises.update` | Any of `name`, `description`, `instructions`; unsent fields are untouched; `{}` → 400. Renaming to another exercise's name → 409. **There is no delete route** (D-39)                                                                                                                     |
| GET    | `/members/:memberId/workout-notes` | `notes.read`       | `status=active` (default) \| `deleted` \| `all`; `deleted` and `all` need `notes.viewDeleted` (Admin), otherwise 403 (D-40). Newest first, paged. For Admins `meta.deletedCount` counts the member's deleted notes. 404 for an unknown member. Archived members' notes can be read        |
| POST   | `/members/:memberId/workout-notes` | `notes.create`     | `{ text }` (trimmed, 1–2000) → 201. 409 `MEMBER_ARCHIVED` for an archived member                                                                                                                                                                                                          |
| PATCH  | `/workout-notes/:id`               | `notes.update`     | `{ text, expectedVersion }`. A Trainer may edit only notes they wrote → 403 `NOT_NOTE_AUTHOR`; an Admin may edit any (the author stays the author). Stale version → 409 `VERSION_CONFLICT`. A deleted note → 409 `NOTE_DELETED` for an Admin and 404 for a Trainer. 409 `MEMBER_ARCHIVED` |
| POST   | `/workout-notes/:id/delete`        | `notes.delete`     | `{ expectedVersion? }`. **Soft delete**: the note is kept with `deletedAt` and `deletedBy` (C-19). Same ownership, archive and version rules as PATCH. There is no un-delete and no route that removes a note                                                                             |

Activity log actions: `exercise.create`, `exercise.update` (the name with old and new value, the other fields by name), `note.create`, `note.update`, `note.delete` (field name only, never the note text, D-62; the target label is the Member ID).

## 13. WhatsApp (SRS §10) — ✅ implemented (Phase 7; tested with a fake provider and the simulated mode only, P-06)

**Modes (D-116):** `WHATSAPP_MODE=disabled|mock|live`. _mock_ is the clearly labelled simulation: nothing leaves the server and every result has `simulated: true`. _live_ calls the Meta WhatsApp Cloud API directly (no Twilio). Credentials stay in server environment variables and are never returned.

A **template** is `{ id, name, eventType: membership_confirmation|payment_received|expiry_reminder|membership_expired|receipt_share|manual, language, category: UTILITY|MARKETING, bodyText, variables: [{ position, key }], headerType: none|document, enabled, isDefault, sendable, meta: { status: not_submitted|pending|approved|rejected|paused|disabled, mode, simulated, rejectionReason, lastError*, lastSyncedAt* }, updatedAt, updatedBy }` (* Admin only). `sendable` = enabled, approved, and approved in the current mode. Variable keys per event: see `server/src/modules/whatsapp/variables.js` (D-118).

A **message** is `{ id, eventType, source: automatic|manual, member: { id, memberId, fullName }, receiptNumber, template: { name, language }, preview, sentBy, status: queued|sending|sent|delivered|read|retrying|failed|blocked|manual_share, blockedReason, simulated, retryCount, attempts, nextAttemptAt, lastError, providerMessageId*, statusHistory: [{ status, at, source: system|provider|staff, detail }], sentAt, needsFollowUp, followUp, note, createdAt }` (* Admin only). **"sent" means accepted by WhatsApp**; delivered and read appear only when the webhook reports them (SRS §10.4).

| Method | Path                                         | Permission                                                    | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ------ | -------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/whatsapp/status`                           | `templates.read`                                              | `{ mode, configured, simulated, defaults: { <event>: { id, name, sendable } \| null }, expiryReminderDaysBefore }`. Admins also get `webhookPath`, `webhookReady` and `settings` (which settings are present, `true`/`false`, plus the API version) — never a secret                                                                                                                                                                                                                                |
| GET    | `/whatsapp/templates`                        | `templates.read`                                              | Admin: all. Trainer: only sendable templates                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| POST   | `/whatsapp/templates`                        | `templates.manage`                                            | `{ name (^[a-z0-9_]+$), eventType, language (en, en_US, ur …), category?, bodyText (≤ 1024, {{1}}…{{n}} without gaps), variables (one per placeholder, keys allowed for the event), headerType? (document required for receipt_share, refused otherwise), enabled?, isDefault? (not for manual) }` → 201. Submitted to the provider after saving; the stored status is what it answered. 409 `TEMPLATE_EXISTS` (name + language)                                                                    |
| GET    | `/whatsapp/templates/:id`                    | `templates.read`                                              | Trainer: 404 unless sendable                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| PATCH  | `/whatsapp/templates/:id`                    | `templates.manage`                                            | Any of `category, bodyText, variables, headerType, enabled, isDefault`. A content change sets `pending` and re-submits (D-45); `enabled`/`isDefault` do not. Name, language and event cannot change. Setting `isDefault` clears the previous default of that event                                                                                                                                                                                                                                  |
| POST   | `/whatsapp/templates/:id/sync`               | `templates.manage`                                            | Reads the review status from the provider (submits if it never reached it)                                                                                                                                                                                                                                                                                                                                                                                                                          |
| GET    | `/whatsapp/templates/:id/dependencies`       | `templates.manage`                                            | `{ canDelete: true, blocking: [], retained: [{ type: notifications, count }], automaticEvent }`                                                                                                                                                                                                                                                                                                                                                                                                     |
| POST   | `/whatsapp/templates/:id/delete-permanently` | `templates.manage`                                            | Safeguarded (C-33, D-56). Messages keep their snapshot. In live mode the Meta template is deleted after the commit (best effort)                                                                                                                                                                                                                                                                                                                                                                    |
| POST   | `/whatsapp/preview`                          | `whatsapp.send`                                               | `{ memberId, templateId }` (a sendable `manual` template) → `{ text, missing: [keys], blockers: [opted_out \| no_consent \| archived \| invalid_phone \| not_configured], simulated }`. Sends nothing                                                                                                                                                                                                                                                                                               |
| POST   | `/whatsapp/send`                             | `whatsapp.send`                                               | `{ memberId, templateId, requestId (uuid) }` → 202 with the message after an immediate send attempt (or 200 `duplicate: true` for a repeated `requestId`). Refused, with nothing recorded or sent: 409 `WHATSAPP_OPTED_OUT`, `WHATSAPP_NO_CONSENT`, `MEMBER_ARCHIVED`, `TEMPLATE_NOT_APPROVED`; 422 `INVALID_WHATSAPP_NUMBER`, `TEMPLATE_NOT_MANUAL`, `VARIABLE_UNAVAILABLE`; 503 `INTEGRATION_NOT_CONFIGURED`                                                                                      |
| GET    | `/notifications`                             | session; `notifications.read.all` (Admin) or `.own` (Trainer) | Filters `status, source, eventType, memberId, needsFollowUp=true\|false, from, to` (Karachi days), paged, newest first. **Trainers always get only messages they sent** (C-26); automatic messages are Admin-only                                                                                                                                                                                                                                                                                   |
| GET    | `/notifications/:id`                         | as above                                                      | A Trainer gets 404 for a message they did not send                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| POST   | `/notifications/:id/follow-up`               | `notifications.followUp`                                      | `{ note (3–500) }`. Only while `needsFollowUp`; otherwise 409 `NO_FOLLOW_UP_NEEDED`                                                                                                                                                                                                                                                                                                                                                                                                                 |
| GET    | `/webhooks/whatsapp`                         | Public (Meta)                                                 | Verification: `hub.mode=subscribe`, `hub.verify_token` = `WHATSAPP_VERIFY_TOKEN` → 200 with `hub.challenge`; otherwise 403                                                                                                                                                                                                                                                                                                                                                                          |
| POST   | `/webhooks/whatsapp`                         | Public (Meta), **signature required**                         | `X-Hub-Signature-256` = HMAC-SHA256 of the raw body with `WHATSAPP_APP_SECRET`, compared in constant time; invalid → 401; no secret configured → 503. Message statuses (`entry[].changes[].value.statuses[]`) are applied once each and never move backwards; `failed` marks the message Failed with a follow-up; template review updates (`message_template_status_update`) update the template. Always 200 for a valid signature. Exempt from the browser Origin check and the general rate limit |

**Automatic messages (SRS §10.2, C-24, D-121)** are queued in the same transaction as their cause, once each (idempotency keys): membership confirmation (on activation), payment received (when a payment becomes verified and its receipt is issued — not on corrections or the receipt backfill), expiry reminder (daily 00:10 for memberships ending in `expiryReminderDaysBefore` days, sent at 10:00) and membership expired (when the member becomes Inactive, sent at 10:00). They use the event's default template; without an approved one they are recorded as `blocked`.

**Sending and retries (SRS §10.4, D-47, D-120):** the dispatcher runs every minute and re-checks consent, opt-out, archive, phone and template before sending. A temporary error (network, timeout, HTTP 429/5xx, Meta codes 1, 2, 4, 17, 341, 80007, 130429, 131000, 131016, 131048, 133004) is retried every 15 minutes **up to 3 times**; then, or at once for any other error, the message is Failed and needs a follow-up.

## 14. Expenses (SRS §9.5) — ✅ implemented (Phase 8, D-41, D-124)

Admin only: every route needs `expenses.manage`; Trainers get 403.

| Method | Path                               | Notes                                                                                                                                                                                                      |
| ------ | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/expenses`                        | `from`, `to` (inclusive business dates), `category`, `method`, `page`, `limit`. Newest first. `meta.totalAmount` = sum of the whole filtered set                                                           |
| POST   | `/expenses`                        | `{ title, category, amount, date, method }`, all required. Amount: integer 1–10,000,000. A future date → 422 `FUTURE_EXPENSE_DATE`. Unknown fields → 400. 201 with the expense (`createdBy`, `version: 0`) |
| GET    | `/expenses/:id`                    | The expense plus `history: [{ action, actor, at, changes: [{ field, from, to }] }]` from the Activity Log                                                                                                  |
| PATCH  | `/expenses/:id`                    | Any of the five fields plus `expectedVersion` (required). A stale version → 409 `VERSION_CONFLICT`. Unchanged values → 200, nothing logged                                                                 |
| GET    | `/expenses/:id/dependencies`       | Always `canDelete: true` (nothing depends on an expense)                                                                                                                                                   |
| POST   | `/expenses/:id/delete-permanently` | Safeguarded (§1). Writes the deletion audit (`recordType: expense`) and `expense.delete`. Excluded from all later reports                                                                                  |

## 15. Reports and exports (SRS §9.4) — ✅ implemented (Phase 8, C-21, D-42, D-126 – D-129)

Admin only (`reports.view`; the full export also `members.export.full`). Range filters: `from` and `to` required, inclusive, `from ≤ to`, at most 731 days. `method` = `all` (default) \| `cash` \| `online`. JSON routes are previews (totals + first 50 rows + `rowCount`); `.pdf` routes return `application/pdf` as an attachment, are logged as `report.download`, and answer 422 `REPORT_TOO_LARGE` above 5,000 records.

| Method | Path                           | Filters / body                                                                      | Returns                                                                                                                                                                                                                              |
| ------ | ------------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| GET    | `/reports/income` · `.pdf`     | range, `method`, `includeArchived=true\|false`                                      | `totals { count, total, cash, online }` (verified entries by payment date), `archivedSummary` (unnamed archived-member line, or null when listed), `rows [{ paymentDate, receiptNumber, member, plan, method, amount, recordedBy }]` |
| GET    | `/reports/expenses` · `.pdf`   | range, `method`, `category=all\|rent\|…`                                            | `totals { count, total, cash, online, byCategory }`, `rows` (expenses)                                                                                                                                                               |
| GET    | `/reports/summary` · `.pdf`    | range, `method`                                                                     | `{ filters, income, expenses }` — **separate; no net figure**                                                                                                                                                                        |
| GET    | `/reports/members` · `.pdf`    | `state=all\|active\|inactive`, `archive=exclude\|include\|only` (default `exclude`) | `rowCount`, `rows [{ memberId, fullName, state, registeredOn }]`; the PDF adds phone, current plan and end date                                                                                                                      |
| POST   | `/reports/members/full-export` | `{ password, archive? }`                                                            | PDF with full personal data (D-128). Wrong password → 422 `INVALID_PASSWORD`. Logged as `member.export.full` (filter and count only)                                                                                                 |

## 16. Dashboards (SRS §9)

| Method | Path                 | Permission          | Returns                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ------ | -------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| GET    | `/dashboard/admin`   | `dashboard.admin`   | ✅ **Implemented (Phase 8, D-125).** `{ asOf { today, monthStart, generatedAt }, members { total, active, inactive, expired, archived }, todayCollections { count, total, cash, online }, monthlyIncome { count, total, cash, online, byDay [{ date, cash, online }] }, outstanding { total, count }, paymentStatus (as the Trainer dashboard), trainers { activeCount, list [{ id, name, status, lastLoginAt }] }, today { newMembers { count, latest }, newInquiries { today, newStatus } }, upcomingExpiries { days: 7, count, items (5) }, recentPaymentCorrections (5) }`. Trainers get 403 |
| GET    | `/dashboard/trainer` | `dashboard.trainer` | ✅ **Implemented (Phase 6, D-113).** `{ members: { active, inactive, archived }, payments: { paid, partially_paid, pending, unpaid, awaitingVerification } (counts only, for current and next memberships of non-archived members), recentNotes: [5 newest non-deleted notes with member { id, memberId, fullName, archived }], myRecentActivity: [10 newest { id, action, targetType, targetLabel, at } of the signed-in user] }`. **No upcoming expiries and no money** (C-20, D-44). `myRecentNotifications` (Phase 7): the 5 latest messages the Trainer sent. Admins get 403                |

## 17. Settings, audit and backups — ✅ implemented (Phase 9, D-131 – D-135)

All Admin-only; Trainers get 403 `FORBIDDEN`, anonymous requests 401. All are read-only: **there is no route that changes or deletes audit records, and no restore endpoint** (C-35, D-131). Dates are Asia/Karachi business dates (`YYYY-MM-DD`, inclusive); lists are newest first, `page` (≥ 1) and `limit` (1–100, default 20). Unknown query parameters are refused (400).

| Method | Path                      | Permission            | Notes                                                                                                                                                                                                                                                                                                                                                                                             |
| ------ | ------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| GET    | `/audit/activity`         | `audit.activity.read` | Filters: `actorId`, `action` (prefix, e.g. `member.`), `targetType`, `from`, `to`. Items: `{ id, at, actor { id, name, role }, action, targetType, targetId, targetLabel, reason, changes [{ field, from, to }], requestId }`. Personal fields were logged by name only (D-62)                                                                                                                    |
| GET    | `/audit/activity/filters` | `audit.activity.read` | `{ actions [], targetTypes [], actors [{ id, name, role, status }] }`: the values that occur in the log                                                                                                                                                                                                                                                                                           |
| GET    | `/audit/logins`           | `audit.logins.read`   | Filters: `userId`, `result` (`success` \| `failure`), `from`, `to`. Items: `{ id, at, result, reason, user { id, name, role, status } \| null, identifier, device }`. `identifier` is shown as typed only when it matched an account, otherwise its first three characters + `…`; `device` is "browser · OS". No IP hash, no raw user agent (D-133)                                               |
| GET    | `/settings/security`      | `settings.manage`     | Read-only approved rules: `{ sessions { idleDays, rotateHours, multipleDevices, cookie }, passwords { minLength, rejectsCommon, hashing, resetLinkMinutes, trainerSelfChange }, login { delayFromFailure, maxDelaySeconds, permanentLockout }, twoFactor, retention { activityLogDays, loginHistoryDays, payments, deletionAudit, consentHistory, notificationHistory, workoutNotes, backups } }` |
| GET    | `/backups`                | `backups.status.read` | `{ configured, warning (not_configured \| last_failed \| none_yet \| stale \| null), lastRunAt, lastRunStatus, lastSuccessAt, storage (s3 \| filesystem \| null), encrypted, schedule { cron, timezone }, retention { keep: 8 }, keptCount, restore: "operator_only", runs [20 latest BackupRun views] }`. Never returns the key, bucket, endpoint or credentials                                 |

`GET /dashboard/admin` (§16) also returns `backup { configured, warning, lastRunAt, lastRunStatus, lastSuccessAt }` for the dashboard warning (Phase 9). Restore is the operator script `server/scripts/restore.js` (`docs/BACKUP_RESTORE.md` §5).
