# Database Design (MongoDB Atlas + Mongoose)

> **Status:** Phase 1 **implemented**: `users`, `sessions`, `passwordResetTokens`, `setupState`, `loginHistory`, `activityLogs`, `deletionAudits`, `gymSettings`, `counters` (Phase 1); `siteContent`, `publicTrainers`, `galleryAssets`, `assetCleanups`, `membershipPlans`, `inquiries`, `consentHistory`, `jobLocks` (Phase 2); `members` (Phase 3); `memberships`, `payments`, `paymentEntries` (Phase 4); `receipts`, `paymentCorrectionLogs` (Phase 5); `exercises`, `workoutNotes` (Phase 6); `notificationTemplates`, `notifications` (Phase 7). Every other collection is **PLANNED**. Indexes are created by `syncIndexes()` at start-up (`server/src/config/db.js`).
> Baseline: SRS §15 conceptual model and §15.1 integrity rules, plus Master Prompt §18. Decision IDs refer to `docs/DECISIONS.md`.

## 1. Conventions

- Every collection gets `timestamps: true` (`createdAt`, `updatedAt` as UTC instants), unless it is marked _immutable_. Immutable collections have `createdAt` only and reject updates through a model hook.
- **Business dates** are `String` values in the form `YYYY-MM-DD` (Asia/Karachi) and are validated with a regex and a real-date check.
- **Money** is an integer number of PKR whole rupees (`Number`, validated as an integer ≥ 0). There are no decimals.
- **Actor snapshot**, embedded wherever "who did it" matters: `{ userId: ObjectId, name: String, role: "admin"|"trainer"|"system" }`. It keeps records attributable after a Trainer is deleted (D-13).
- **References** use `ObjectId` with `ref`. **No cascade hooks exist anywhere.** Deletions go through the safeguarded deletion service (C-33).
- **Protected history** (Phase 9, D-131): `consentHistory`, `notifications`, `workoutNotes`, `paymentCorrectionLogs`, `activityLogs`, `loginHistory` and `deletionAudits` refuse every Mongoose delete (`deleteOne`, `deleteMany`, `findOneAndDelete`, document `deleteOne`). Activity and login history still expire through their TTL index (C-32).
- **Phone numbers** are stored as `phone` (E.164, normalised) and `phoneDisplay` (as entered) (D-16).
- **Localised text** in public content is stored as `{ en: String, ur: String }`, with `en` required (D-52).
- `strict` schemas. Unknown fields are rejected by Zod before they reach Mongoose.

## 2. Collections

The collections named in the SRS are marked **(SRS)**. Each additional collection is justified.

### 2.1 `users` (SRS: User)

| Field                         | Type                | Rules                                                               |
| ----------------------------- | ------------------- | ------------------------------------------------------------------- |
| username                      | String              | required, lowercase, 3–32 chars `[a-z0-9._-]`, **unique**           |
| email                         | String              | lowercase. Required when role = admin. **Unique (partial: exists)** |
| passwordHash                  | String              | argon2id. Never selected by default                                 |
| role                          | String              | `admin` \| `trainer`                                                |
| status                        | String              | `active` \| `deactivated` \| `deleted` (tombstone, D-13)            |
| displayName                   | String              | required                                                            |
| phone / phoneDisplay          | String              | optional                                                            |
| preferredLanguage             | String              | `en` \| `ur`                                                        |
| lastLoginAt                   | Date                |                                                                     |
| failedLogin                   | `{ count, lastAt }` | for progressive delay (D-06)                                        |
| passwordChangedAt             | Date                |                                                                     |
| createdBy                     | actor               |                                                                     |
| deactivatedAt / deactivatedBy | Date / actor        |                                                                     |
| deletedAt / tombstoneLabel    | Date / String       | "Former staff #N"                                                   |

Indexes: `username` unique; `email` unique partial; `{ role, status }`.
Invariants: the last active Admin cannot be deactivated or deleted, and nobody can deactivate or delete themselves (enforced in the service, D-09).

### 2.2 `sessions` (additional — needed for D-01 server-side sessions)

| Field                                  | Type             | Rules                                                         |
| -------------------------------------- | ---------------- | ------------------------------------------------------------- |
| userId                                 | ObjectId → users | required                                                      |
| tokenHash                              | String           | SHA-256 of the cookie token, **unique**                       |
| previousTokenHash / previousValidUntil | String / Date    | rotation grace period (≈60 s)                                 |
| lastSeenAt                             | Date             | updated at most once a minute                                 |
| rotatedAt                              | Date             |                                                               |
| expiresAt                              | Date             | lastSeenAt + 90 days. **TTL index** (`expireAfterSeconds: 0`) |
| revokedAt / revokedReason              | Date / String    | logout, force-logout, deactivation, password change           |
| userAgent / ipHash                     | String           | metadata. The IP is stored as a salted hash                   |

Indexes: `tokenHash` unique; `previousTokenHash` (sparse); `{ userId, revokedAt }`; TTL on `expiresAt`.

### 2.3 `passwordResetTokens` (additional — D-07)

`userId`, `tokenHash` (unique), `expiresAt` (TTL, 30 min), `usedAt`, `requestedIpHash`. Single use.

### 2.4 `setupState` (additional — C-30, D-11)

A single document: `{ _id: "setup", tokenHash, tokenExpiresAt, completedAt, completedBy }`. Once `completedAt` is set, the token is cleared and can never be issued again (the script refuses).

### 2.5 `loginHistory` (SRS: LoginHistory)

`userId` (nullable for unknown identifiers), `identifier` (as typed, truncated), `result` (`success` \| `failure`), `reason` (`bad_credentials` \| `deactivated` \| `deleted` \| `rate_limited` \| `ok`), `ipHash`, `userAgent`, `at`, `expireAt` (at + 2 years, **TTL**). Immutable.
Indexes: `{ userId, at: -1 }`, `{ at: -1 }`, TTL `expireAt`.

### 2.6 `activityLogs` (SRS: ActivityLog)

`actor` (actor snapshot), `action` (enum string, for example `member.create`, `payment.entry.correct`, `user.force_logout`), `targetType`, `targetId`, `targetLabel` (non-personal, for example `GYM-014`, `REC-0102`), `reason`, `changes: [{ field, from?, to? }]` (values omitted for personal fields, D-62), `requestId`, `ipHash`, `at`, `expireAt` (at + 2 years, **TTL**). Immutable.
Indexes: `{ at: -1 }`, `{ "actor.userId": 1, at: -1 }`, `{ targetType, targetId, at: -1 }`, `{ action, at: -1 }`, TTL `expireAt`.

### 2.7 `deletionAudits` (additional — SRS §11.7, §12.1 "minimal permanent deletion audit record")

Exactly four fields: `actorId`, `at`, `recordType`, `reason`. There is **no TTL** and no update or delete API, and it holds no personal data or record identifiers.
Index: `{ at: -1 }`.

### 2.8 `gymSettings` (SRS: GymSettings)

A single document: `gymName {en,ur}`, `logo { publicId, url }`, `address {en,ur}`, `contactPhone`, `contactEmail`, `whatsappContactNumber`, `openingTime` (`HH:mm`), `closingTime` (`HH:mm`), `hoursNote {en,ur}`, `mapUrl`, `extraContacts: [{ label{en,ur}, value }]`, `defaultLanguage` (`en`\|`ur`), `expiryReminderDaysBefore` (integer 1–30, default 3), `currency: "PKR"` (fixed), `timezone: "Asia/Karachi"` (fixed), `updatedBy`.

### 2.9 `siteContent` (additional — editable public sections, Prompt §7)

A single document: `hero { title{en,ur}, subtitle{en,ur}, image }`, `about { title{en,ur}, body{en,ur}, image }`, `plansIntro {en,ur}`, `contactIntro {en,ur}`, `updatedBy`. It is kept separate from settings so that content edits do not touch operational settings.

### 2.10 `publicTrainers` (additional — public Trainer cards, SRS §4.1)

`name`, `photo { publicId, url }`, `bio {en,ur}`, `specialties {en,ur}`, `displayOrder`, `isVisible`, `linkedUserId` (optional, informational only), `createdBy`, `updatedBy`. Public cards are content, separate from login accounts, so that public profiles never expose account data.
Index: `{ isVisible, displayOrder }`.

### 2.11 `galleryAssets` (SRS: GalleryAsset)

`image { publicId, url, width, height }`, `caption {en,ur}`, `displayOrder`, `isVisible`, `createdBy`, `updatedBy`.
Index: `{ isVisible, displayOrder }`.

### 2.12 `assetCleanups` (additional — SRS §5.4 "failed cleanup is logged for retry/manual resolution")

`publicId`, `kind` (`member_photo` \| `gallery` \| `logo` \| `trainer_photo`), `attempts`, `lastError`, `nextAttemptAt`, `status` (`pending` \| `done` \| `manual`), `resolvedAt`.

### 2.13 `membershipPlans` (SRS: MembershipPlan)

| Field                 | Type      | Rules                                                                |
| --------------------- | --------- | -------------------------------------------------------------------- |
| name                  | `{en,ur}` | en required                                                          |
| description           | `{en,ur}` |                                                                      |
| durationType          | String    | `monthly` \| `custom_days` (D-24)                                    |
| durationValue         | Number    | integer 1–36 (months) or 1–730 (days)                                |
| price                 | Number    | integer ≥ 0, PKR                                                     |
| isActive              | Boolean   | only active plans are shown publicly and offered for new memberships |
| displayOrder          | Number    |                                                                      |
| createdBy / updatedBy | actor     |                                                                      |

Plans are never deleted (D-30). Price changes are written to the activity log.
Index: `{ isActive, displayOrder }`.

### 2.14 `inquiries` (SRS: Inquiry)

| Field                             | Type                                                          | Rules                                                    |
| --------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------- |
| fullName                          | String                                                        | required, 2–100 chars                                    |
| phone / phoneDisplay              | String                                                        | required, valid PK number                                |
| age                               | Number                                                        | required, integer 10–100                                 |
| gender                            | String                                                        | `male` \| `female` (D-15)                                |
| address                           | String                                                        | required, ≤ 300 chars                                    |
| preferredPlan                     | `{ planId, name }` \| null                                    | optional snapshot (D-18)                                 |
| whatsappConsent                   | `{ given: Boolean, at: Date }`                                | snapshot. The checkbox defaults to unchecked             |
| status                            | String                                                        | `new` (default) \| `pending` \| `approved` \| `rejected` |
| duplicate                         | `{ isDuplicate, matchedInquiryCount, matchesExistingMember }` | `matchesExistingMember` is shown to Admin only           |
| conversion                        | `{ memberId, convertedAt, convertedBy }` \| null              | D-19                                                     |
| statusUpdatedBy / statusUpdatedAt | actor / Date                                                  |                                                          |
| submittedIpHash                   | String                                                        |                                                          |

Indexes: `{ status, createdAt: -1 }`, `{ phone }`, `{ createdAt: -1 }`, plus a text-free name search (regex on `fullName` with a case-insensitive collation index).

### 2.15 `members` (SRS: Member)

| Field                 | Type                                                                                        | Rules                                                                                                                                   |
| --------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| memberId              | String                                                                                      | `GYM-001` format, **unique**, immutable                                                                                                 |
| memberNumber          | Number                                                                                      | the counter value behind `memberId` (counter `memberId`, D-36). **Unique**, immutable. Used for sorting and for Member ID search (D-90) |
| fullName              | String                                                                                      | required                                                                                                                                |
| phone / phoneDisplay  | String                                                                                      | required, **unique** (C-05)                                                                                                             |
| age                   | Number                                                                                      | required, integer                                                                                                                       |
| gender                | String                                                                                      | D-15 values                                                                                                                             |
| address               | String                                                                                      | required                                                                                                                                |
| photo                 | `{ publicId, url }` \| null                                                                 | optional                                                                                                                                |
| membershipState       | String                                                                                      | `active` \| `inactive`. Driven by the membership lifecycle (C-07). Starts `inactive` (D-85)                                             |
| lifecycleVersion      | Number                                                                                      | incremented by every lifecycle change (activation, expiry, promotion), so it conflicts with a concurrent archive (D-92, D-97)           |
| archive               | `{ isArchived: Boolean, archivedAt, archivedBy, restoredAt, restoredBy }`                   | the separate administrative state (C-06)                                                                                                |
| whatsapp              | `{ consent: Boolean, consentSource, consentAt, optedOut: Boolean, optedOutAt, optedOutBy }` | the current state. The history is in `consentHistory`                                                                                   |
| adminNotes            | String                                                                                      | ≤ 2000 chars. Admin edits (D-22)                                                                                                        |
| registeredOn          | String (business date)                                                                      | the registration date                                                                                                                   |
| sourceInquiryId       | ObjectId \| null                                                                            | a weak reference only. Nothing changes if the inquiry is deleted (C-04)                                                                 |
| createdBy / updatedBy | actor                                                                                       |                                                                                                                                         |

**Displayed status** = `Archived` if `archive.isArchived`, otherwise `Active` or `Inactive` from `membershipState`. The two fields are separate, so a membership status is never confused with the record status (Prompt §9.5).
Indexes: `memberId` unique; `memberNumber` unique; `phone` unique; `{ "archive.isArchived": 1, membershipState: 1 }`; `{ registeredOn: -1 }`; `fullName` with a case-insensitive collation index (`en`, strength 2).
**Implemented (Phase 3):** `server/src/modules/members/member.model.js`. Writes that must not land on an archived record use a conditional update or a transaction (D-88, D-92). The counter document is created before the first transaction so concurrent registrations never clash on its upsert. `whatsapp.consentSource` is `inquiry_conversion`, `staff_registration` or `admin_action`.

### 2.16 `consentHistory` (SRS: ConsentHistory)

`subjectType` (`inquiry` \| `member`), `subjectId`, `event` (`consent_given` \| `consent_not_given` \| `opted_out` \| `consent_restored`), `source` (`public_form` \| `inquiry_conversion` \| `staff_registration` \| `admin_action`), `actor` (null for public), `note`, `at`. **Immutable.**
Index: `{ subjectType, subjectId, at: -1 }`.

### 2.17 `memberships` (SRS: Membership)

| Field                     | Type                                                             | Rules                                                                           |
| ------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| member                    | ObjectId → members                                               | required                                                                        |
| plan                      | `{ planId, name, durationType, durationValue, advertisedPrice }` | snapshot (D-30)                                                                 |
| agreedPrice               | Number                                                           | the plan price, or the Admin custom price                                       |
| customPrice               | `{ isCustom: Boolean, reason, setBy }`                           | reason required when `isCustom` (C-09)                                          |
| status                    | String                                                           | `pending_activation` \| `upcoming` \| `active` \| `expired`                     |
| slot                      | String \| absent                                                 | `current` (active), `next` (pending_activation / upcoming), absent when expired |
| startDate / endDate       | String (business date)                                           | set at activation by the server only (C-12)                                     |
| activatedAt / activatedBy | Date / actor                                                     |                                                                                 |
| expiredAt                 | Date                                                             | set by the lifecycle job                                                        |
| previousMembership        | ObjectId \| null                                                 | the membership it renews (history chain)                                        |
| createdBy                 | actor                                                            |                                                                                 |

Indexes: **partial unique `{ member: 1, slot: 1 }` where `slot` exists** (enforces one Active plus one next, C-10 and D-26); `{ member: 1, createdAt: -1 }`; `{ status: 1, endDate: 1 }` (expiry job, upcoming expiries); `{ status: 1, startDate: 1 }` (promotion).
**Implemented (Phase 4):** `server/src/modules/memberships/membership.model.js`. `agreedPrice` is an integer ≥ 1 (D-96). `plan.name` is the `{en, ur}` snapshot.

### 2.18 `payments` (SRS: Payment — one summary per membership)

| Field                  | Type                   | Rules                                                      |
| ---------------------- | ---------------------- | ---------------------------------------------------------- |
| membership             | ObjectId → memberships | **unique** (C-13)                                          |
| member                 | ObjectId → members     |                                                            |
| totalDue               | Number                 | = agreedPrice at creation. Corrected by Admin only (D-34)  |
| verifiedPaid           | Number                 | recomputed from the entries                                |
| pendingAmount          | Number                 | recomputed                                                 |
| balance                | Number                 | totalDue − verifiedPaid, ≥ 0                               |
| status                 | String                 | `paid` \| `partially_paid` \| `pending` \| `unpaid` (D-32) |
| hasPendingVerification | Boolean                |                                                            |
| lastPaymentDate        | String                 | the latest verified payment date                           |
| version                | Number                 | optimistic concurrency                                     |

Indexes: `membership` unique; `{ member: 1 }`; `{ status: 1 }`; `{ balance: 1 }` (outstanding lists).
**Implemented (Phase 4):** `server/src/modules/payments/payment.models.js`, recomputed from the entries by `payment.logic.js` `summarize()` with an optimistic `version` check.

### 2.19 `paymentEntries` (SRS: PaymentEntry — one per payment received)

| Field                                     | Type                   | Rules                                                        |
| ----------------------------------------- | ---------------------- | ------------------------------------------------------------ |
| payment / membership / member             | ObjectId               | required                                                     |
| amount                                    | Number                 | integer ≥ 1                                                  |
| method                                    | String                 | `cash` \| `online`                                           |
| paymentDate                               | String (business date) | ≤ today. Backdating allowed (C-15)                           |
| recordedAt                                | Date                   | server time of entry (Prompt §11.5)                          |
| recordedBy                                | actor                  |                                                              |
| verificationStatus                        | String                 | `verified` \| `pending` \| `rejected` (D-31)                 |
| verifiedAt / verifiedBy                   | Date / actor           |                                                              |
| rejectedAt / rejectedBy / rejectionReason |                        | reason required                                              |
| reference                                 | String                 | online transaction reference or screenshot note, ≤ 200 chars |
| receipt                                   | ObjectId \| null       | the current valid receipt                                    |
| correctionCount                           | Number                 |                                                              |

Indexes: `{ payment: 1, createdAt: 1 }`; `{ member: 1, paymentDate: -1 }`; `{ verificationStatus: 1, paymentDate: 1, method: 1 }` (reports, dashboard).
**Implemented (Phase 4, completed in Phase 5)** (collection `paymentEntries`). Cash is always verified (model hook, D-102). Phase 5 adds `receiptDeletedAt` (set when an Admin deletes the entry's receipt, so the backfill never re-issues it, D-103, D-107).

### 2.20 `paymentCorrectionLogs` (SRS: PaymentCorrectionLog — X-08)

`targetType` (`entry` \| `summary`), `payment`, `entry` (nullable), `membership`, `member`, `changes: [{ field, from, to }]`, `reason` (required), `actor`, `at`, `voidedReceipt`, `newReceipt`. **Immutable. Kept permanently by default** (C-32). **Implemented (Phase 5):** `server/src/modules/payments/correction.model.js`.
Index: `{ payment: 1, at: -1 }`, `{ at: -1 }` (dashboard "recent payment corrections").

### 2.21 `receipts` (SRS: Receipt)

| Field                                         | Type                                                                                                                                              | Rules                         |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| receiptNumber                                 | String                                                                                                                                            | `REC-0001` format, **unique** |
| entry / payment / membership / member         | ObjectId                                                                                                                                          |                               |
| snapshot                                      | `{ gymName, logoUrl, memberName, memberCode, planName, startDate, endDate, totalDue, eventAmount, cumulativePaid, balance, method, paymentDate }` | frozen at issue time (D-37)   |
| issuedBy / issuedAt                           | actor / Date                                                                                                                                      |                               |
| status                                        | String                                                                                                                                            | `valid` \| `void`             |
| voidReason / voidedAt / replacedBy / replaces |                                                                                                                                                   | D-35                          |

Indexes: `receiptNumber` unique; **partial unique `{ entry: 1 }` where `status = "valid"`** (one valid receipt per verified event, C-16); `{ member: 1, issuedAt: -1 }`; `{ payment: 1 }`.
**Implemented (Phase 5):** `server/src/modules/payments/receipt.model.js`. The snapshot also holds `reference`; `backfilled` marks receipts issued later for Phase 4 payments (D-103, D-104).

### 2.22 `exercises` (SRS: Exercise)

| Field                 | Type   | Rules                                                                                                                                                |
| --------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                  | String | required, 2–100 chars, inner spaces collapsed                                                                                                        |
| nameKey               | String | the cleaned name in lower case (Unicode NFC). **Unique** (`exercise_name_unique_ci`): names are unique ignoring letter case and extra spaces (D-111) |
| description           | String | ≤ 500 chars                                                                                                                                          |
| instructions          | String | ≤ 2000 chars                                                                                                                                         |
| createdBy / updatedBy | actor  |                                                                                                                                                      |

No delete (D-39). Sorted by `nameKey`.
**Implemented (Phase 6):** `server/src/modules/exercises/exercise.model.js`. A unique-index clash from two simultaneous additions is answered as `409 EXERCISE_NAME_EXISTS`.

### 2.23 `workoutNotes` (SRS: WorkoutNote)

| Field                             | Type                   | Rules                                                                                        |
| --------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------- |
| member                            | ObjectId → members     | required, immutable                                                                          |
| text                              | String                 | 1–2000 chars                                                                                 |
| author                            | actor                  | required, **immutable**: the name stays as written, also after the account is deleted (D-13) |
| editedAt / editedBy / editCount   | Date / actor / Number  | the latest edit and how many edits. Earlier text is not kept (D-112)                         |
| isDeleted / deletedAt / deletedBy | Boolean / Date / actor | soft delete (C-19). No un-delete (D-40)                                                      |
| version                           | Number                 | optimistic concurrency for edits and deletes (D-112)                                         |

Indexes: `{ member: 1, isDeleted: 1, createdAt: -1 }`, `{ "author.userId": 1, createdAt: -1 }`, `{ isDeleted: 1, createdAt: -1 }` (dashboard).
**Implemented (Phase 6):** `server/src/modules/notes/workoutNote.model.js`. **Notes are never physically deleted:** the model refuses `deleteOne`, `deleteMany` and `findOneAndDelete`, and no route removes a note. Notes stay protected dependencies of their member (D-87, X-21 deferred).

### 2.24 `expenses` (SRS: Expense) — implemented (Phase 8)

`title` (2–200), `category` (`rent` \| `utilities` \| `salaries` \| `equipment` \| `maintenance` \| `other`), `amount` (integer 1–10,000,000), `date` (business date, not in the future — checked by the service), `method` (`cash` \| `online`), `createdBy`, `updatedBy` (actors), `version` (optimistic concurrency), timestamps (C-22, D-124).
Indexes: `{ date: -1, _id: -1 }`, `{ category: 1, date: -1 }`, `{ method: 1, date: -1 }`. History is in `activityLogs` (`targetType: 'Expense'`). Permanent deletion only through the safeguarded route; nothing references an expense.

### 2.25 `notificationTemplates` (SRS: NotificationTemplate)

| Field                 | Type                                                                     | Rules                                                                                                                                                                              |
| --------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                  | String                                                                   | Meta template name `^[a-z0-9_]+$`, ≤ 512. Unique with `language`; fixed after creation                                                                                             |
| eventType             | String                                                                   | `membership_confirmation` \| `payment_received` \| `expiry_reminder` \| `membership_expired` \| `receipt_share` \| `manual`                                                        |
| language              | String                                                                   | Meta language code (`en`, `en_US`, `ur` …)                                                                                                                                         |
| category              | String                                                                   | `UTILITY` \| `MARKETING`                                                                                                                                                           |
| bodyText              | String                                                                   | ≤ 1024, positional placeholders `{{1}}…{{n}}` without gaps                                                                                                                         |
| variables             | `[{ position, key }]`                                                    | one per placeholder; keys allowed for the event (D-118)                                                                                                                            |
| headerType            | String                                                                   | `document` (receipt PDF) for `receipt_share` only, otherwise `none`                                                                                                                |
| enabled               | Boolean                                                                  |                                                                                                                                                                                    |
| isDefault             | Boolean                                                                  | the template used for the event automatically (or for receipt sharing). **Partial unique `{ eventType }` where `isDefault`** (`one_default_per_event`)                             |
| meta                  | `{ status, mode, templateId, rejectionReason, lastError, lastSyncedAt }` | status: `not_submitted` \| `pending` \| `approved` \| `rejected` \| `paused` \| `disabled`; `mode`: `mock` \| `live` — an approval only counts in the mode it was given in (D-117) |
| createdBy / updatedBy | actor                                                                    |                                                                                                                                                                                    |

**Implemented (Phase 7):** `server/src/modules/whatsapp/template.model.js`. Deleted with safeguards (D-56); messages keep their own snapshot.

### 2.26 `notifications` (SRS: Notification)

| Field                              | Type                                                        | Rules                                                                                                                                                                                                                                                                                                             |
| ---------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| idempotencyKey                     | String                                                      | **unique** (`notification_once`, D-46): `membership_confirmation:<membershipId>`, `payment_received:<entryId>`, `expiry_reminder:<membershipId>:<endDate>`, `membership_expired:<membershipId>`, `manual:<userId>:<requestId>`, `receipt_share:<receiptId>:<requestId>`, `receipt_manual:<receiptId>:<requestId>` |
| eventType / source                 | String                                                      | the template event; `automatic` \| `manual`                                                                                                                                                                                                                                                                       |
| member / membership / receipt      | ObjectId                                                    | member required; `memberCode` keeps the Member ID                                                                                                                                                                                                                                                                 |
| recipientPhone                     | String                                                      | E.164 mobile number used                                                                                                                                                                                                                                                                                          |
| template                           | `{ templateId, name, language }`                            | snapshot                                                                                                                                                                                                                                                                                                          |
| variables / preview                | `[{ position, key, value }]` / String                       | resolved on the server when queued; the text the member reads                                                                                                                                                                                                                                                     |
| sentBy                             | actor \| null                                               | null for automatic messages (Trainer visibility, C-26)                                                                                                                                                                                                                                                            |
| status                             | String                                                      | `queued` \| `sending` \| `sent` \| `delivered` \| `read` \| `retrying` \| `failed` \| `blocked` \| `manual_share`                                                                                                                                                                                                 |
| blockedReason                      | String                                                      | `opted_out` \| `no_consent` \| `archived` \| `invalid_phone` \| `no_template` \| `template_not_approved` \| `not_configured` \| `receipt_void` \| `missing_values` \| `superseded`                                                                                                                                |
| simulated                          | Boolean                                                     | true when the mock provider handled it (nothing was sent)                                                                                                                                                                                                                                                         |
| retryCount / attempts              | Number                                                      | retries used (0–3) / send attempts (≤ 4)                                                                                                                                                                                                                                                                          |
| nextAttemptAt / lockedAt / claimId | Date / Date / String                                        | scheduling and the atomic claim (D-120)                                                                                                                                                                                                                                                                           |
| lastError                          | `{ code, message, permanent }`                              |                                                                                                                                                                                                                                                                                                                   |
| providerMessageId                  | String                                                      | indexed (sparse); webhook matching                                                                                                                                                                                                                                                                                |
| statusHistory                      | `[{ status, at, source: system\|provider\|staff, detail }]` | every change, including each webhook status once                                                                                                                                                                                                                                                                  |
| sentAt                             | Date                                                        | when WhatsApp accepted it                                                                                                                                                                                                                                                                                         |
| needsFollowUp / followUp           | Boolean / `{ resolvedAt, resolvedBy, note }`                | Admin follow-up of failed messages                                                                                                                                                                                                                                                                                |
| note                               | String                                                      | staff note (manual receipt share)                                                                                                                                                                                                                                                                                 |

Indexes: `idempotencyKey` unique; `{ status, nextAttemptAt }`; `providerMessageId` (sparse); `{ "sentBy.userId", createdAt: -1 }`; `{ member, createdAt: -1 }`; `{ needsFollowUp, createdAt: -1 }`; `{ createdAt: -1 }`.
**Implemented (Phase 7):** `server/src/modules/whatsapp/notification.model.js`. **Never deleted:** the model refuses `deleteOne`, `deleteMany` and `findOneAndDelete`; messages stay protected dependencies of their member (D-87, D-131).

### 2.27 `counters` (additional — D-36)

`{ _id: "memberId" | "receiptNumber" | "tombstone", seq: Number }`.

### 2.28 `jobLocks` (additional — D-59)

`{ _id: jobName, holder, lockedUntil }` with a TTL on `lockedUntil`.

### 2.29 `backupRuns` (additional — SRS §19 "Admin can view backup status") — implemented (Phase 9)

`kind` (`backup` \| `restore`), `trigger` (`schedule` \| `operator`), `storage` (`s3` \| `filesystem` \| `local_file`), `status` (`running` \| `success` \| `failed`), `startedAt`, `finishedAt`, `fileName` (the file name in storage; no bucket or path), `sizeBytes`, `sha256`, `collectionCounts`, `totalDocuments`, `error` (short, scrubbed), `prunedKeys` (files this run pruned), `prunedAt` (set when a later run removed this backup), `restoredFrom { fileName, takenAt, sha256 }` (restore runs, written into the restored database). No personal data, no secrets.
Indexes: `{ startedAt: -1 }`, `{ kind, status, startedAt: -1 }`. Implemented in `server/src/modules/backups/backupRun.model.js` (D-132). Restore runs also carry `restoreId` (Revision 1), so a resumed restore records exactly one run.

### 2.30 `restoreState` (additional — Phase 9 Revision 1, D-136)

Exists only in a database written by `server/scripts/restore.js`. One document `_id: "restore"`: `restoreId`, `status` (`in_progress` \| `failed` \| `complete`), `fileName`, `sha256` (of the backup file), `takenAt`, `startedAt`, `leaseUntil`, `attempts`, `completedCollections`, `error`, `failedAt`, `completedAt`. Written first by a restore; while `status` is not `complete`, the server and the operator scripts refuse the database. Never included in a backup; no application code reads or writes it.

## 3. Relationships

```
users ──< sessions, passwordResetTokens, loginHistory
users (actor snapshots) ··· referenced by almost everything (not a hard FK)

inquiries ··(weak)··> members.sourceInquiryId          inquiry deletion never touches members
members ──< memberships ──1 payments ──< paymentEntries ──1(valid) receipts
                         │                     └──< paymentCorrectionLogs
members ──< workoutNotes
members ──< consentHistory  (also inquiries ──< consentHistory)
members ──< notifications >── notificationTemplates (snapshot)
receipts ──< notifications (receipt_share)
membershipPlans ··(snapshot)··> memberships.plan
```

`──<` means one-to-many by reference; `··>` means a snapshot or weak reference that does not affect integrity.

## 4. Integrity rules and how they are enforced

| #   | Rule (SRS §15.1 / Prompt §18)                                       | Enforcement                                                                                                                            |
| --- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| 1   | Member IDs unique                                                   | Atomic counter in a transaction + unique index                                                                                         |
| 2   | Receipt numbers unique                                              | Atomic counter in a transaction + unique index                                                                                         |
| 3   | Membership references a valid member                                | Service check inside the transaction; archived members rejected (D-21)                                                                 |
| 4   | Only one current active membership per member                       | Partial unique index `{member, slot}` + service check                                                                                  |
| 5   | One Payment summary per membership                                  | Unique index on `payments.membership`; created in the same transaction as the membership                                               |
| 6   | Many PaymentEntry per summary; one valid receipt per verified entry | Partial unique `receipts.entry` where valid                                                                                            |
| 7   | Payment corrections and deletions auditable                         | Immutable PaymentCorrectionLog + ActivityLog + DeletionAudit                                                                           |
| 8   | Historical records traceable                                        | Snapshots (plan, receipt, actor) + no cascades                                                                                         |
| 9   | Deleting an inquiry never deletes a converted member                | Weak reference only; deletion service has no member logic for inquiries                                                                |
| 10  | Opted-out members excluded from all sends                           | Guard at enqueue and at dispatch (D-46); manual send endpoint checks too                                                               |
| 11  | Deactivated users have no usable sessions                           | Deactivation revokes all sessions in the same transaction; `authenticate` also rejects any user whose status ≠ active on every request |
| 12  | Dates use Asia/Karachi business-date rules                          | `businessDate` utility only; lint rule against `new Date()` in business services                                                       |
| 13  | No overpayment, no future-dated payments                            | Service guards (D-33) + Zod                                                                                                            |
| 14  | Activation requires a verified payment                              | Service guard inside the activation transaction                                                                                        |
| 15  | Archive blocked while a membership is active                        | Service guard                                                                                                                          |
| 16  | Duplicate member phone prevented                                    | Unique index on normalised `phone` + friendly 409                                                                                      |

## 5. Transactions (critical multi-document operations)

- Create member (counter, member, consent history, inquiry conversion link, activity log).
- Create membership (+ payment summary) and optionally the first entry, its receipt and activation.
- Add, verify, reject or correct a payment entry (entry, summary recompute, receipt issue/void, correction log, notification enqueue).
- Activate, expire or promote a membership (membership, member state, notification enqueue).
- Deactivate a user or force logout (user, session revocation, activity log).
- Every permanent deletion (record, deletion audit, activity log).

Atlas clusters are replica sets, so they support multi-document transactions on every tier, including M0.

## 6. Retention

| Data                                              | Retention                                          | Mechanism                                      |
| ------------------------------------------------- | -------------------------------------------------- | ---------------------------------------------- |
| Activity logs                                     | 2 years by default                                 | TTL `expireAt`                                 |
| Login history                                     | 2 years by default                                 | TTL `expireAt`                                 |
| Payment summaries, entries, corrections, receipts | Permanent by default                               | No TTL; separate Admin deletion only           |
| Deletion audits                                   | Permanent                                          | No TTL, no delete API                          |
| Consent history, WhatsApp messages, workout notes | Permanent (protected history, D-131)               | No TTL, no delete route; model refuses deletes |
| Backups (files)                                   | Newest 8 successful weekly backups (C-35)          | Pruned after a successful run (D-132)          |
| Backup runs                                       | Kept                                               | No delete route                                |
| Sessions                                          | 90 days after last activity                        | TTL `expiresAt`                                |
| Reset tokens                                      | 30 minutes                                         | TTL                                            |
| Everything else                                   | Until explicitly deleted by Admin under safeguards | —                                              |

## 7. Dependency checks for permanent deletion (SRS §12.2)

| Record                                                     | Blocks deletion while…                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Inquiry                                                    | Nothing blocks. A converted member is independent.                                                                                                                                                                                                                                                                                                                                                                                                |
| Member                                                     | Any membership, payment, entry, receipt, workout note (including soft-deleted ones), notification or consent-history record still exists for the member. The dialog lists them. As written, this blocks deletion for almost every member. **X-21 is resolved by D-131 (Phase 9): the block stays; archive instead.** Consent history, notification history, notes and correction logs are never deleted, anonymised or detached to get around it. |
| Membership                                                 | Its payment summary still exists (D-99). Delete receipts, entries and the summary first (Phase 5, D-107).                                                                                                                                                                                                                                                                                                                                         |
| Payment summary                                            | Any entries still exist.                                                                                                                                                                                                                                                                                                                                                                                                                          |
| PaymentEntry                                               | Its receipt (valid or void) still exists.                                                                                                                                                                                                                                                                                                                                                                                                         |
| Receipt                                                    | Nothing blocks. Deleting it removes the entry's receipt link and logs this.                                                                                                                                                                                                                                                                                                                                                                       |
| Expense                                                    | Nothing blocks.                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Trainer account                                            | Nothing blocks. It is tombstoned, not removed (D-13).                                                                                                                                                                                                                                                                                                                                                                                             |
| Member photo, gallery image, public trainer card, template | Nothing blocks. The asset or record is removed after the commit.                                                                                                                                                                                                                                                                                                                                                                                  |

Workout notes can only be soft-deleted (C-19). The SRS also defines no deletion path for consent history or notification history. Taken as written, those records permanently block member deletion. This was conflict X-21. **D-131 (Phase 9) resolves it within the approved SRS:** the §12.2 rule is applied as written, so those records keep blocking member deletion, and archiving is the way to retire a member. Every protected collection refuses physical deletes at the model level (`undeletable` plugin, `server/src/utils/mongoosePlugins.js`). A future erasure procedure would need an SRS change request.

## 8. Seed data

A development-only seed script (`server/scripts/seed-dev.js`) will create clearly fake records tagged `seed: true`. The script refuses to run when `NODE_ENV=production` (Prompt §20).
