# Decision Register

> **Document type:** Living register. It is updated whenever a decision is made or changed.
> **Last updated:** 20 Nov 2026 (Phase 10: D-137. Phase 9 Revision 1: D-136. Phase 9: X-21 resolved by D-131; D-131 to D-135. Phase 8: D-124 to D-130. Phase 7: D-116 to D-123. Phase 6: D-111 to D-115. Phase 5 Revision 1: D-109, D-110; D-67 annotated. Phase 5: D-103 to D-108. Phase 4 Revision 1: D-102. Phase 4: D-94 to D-101 added. Phase 3: D-85 to D-93. Phase 2: D-73 to D-84)
> **Baseline:** SRS v2.0 (`docs/SRS.md`), approved by the user, plus the Master Development Prompt.

## How to read this register

| Prefix | Meaning                                                                                                                                                  | Who can change it                                |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| **C**  | **Confirmed requirement.** Taken from the approved SRS (Appendix A and the body text).                                                                   | Only the user, through a recorded change request |
| **X**  | **Conflict.** The Master Prompt and the SRS (or two parts of the SRS) disagree. Each entry records the text on both sides and the behaviour planned.     | The user                                         |
| **D**  | **Delegated decision.** The user authorised Claude to decide items the SRS leaves open. Each entry records the reason.                                   | The user can override at any time                |
| **P**  | **Pending external dependency.** Needs an account, credential, approval or information that only the user or the client can provide. Nothing is assumed. | Resolved when the information arrives            |

**Precedence rule.** The Master Prompt (§2) says _"The attached SRS is the primary source of truth."_ SRS v2.0 is the later, consolidated document. Where the two disagree, the plan follows the SRS. Every such case is listed under **X** so that none is resolved silently.

---

## C — Confirmed requirements (summary index)

The authoritative text is the SRS. This index lists the decisions most likely to be lost during implementation. It does not restate every requirement.

| ID   | Confirmed decision                                                                                                                                                                                                                                                                                                              | SRS ref        |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
| C-01 | Single gym. Public website plus Admin/Trainer dashboard. Members never log in.                                                                                                                                                                                                                                                  | §1, §2, App. A |
| C-02 | Mobile-first modern SaaS UI. Light and dark themes. Collapsible desktop sidebar. Compact mobile navigation. Touch targets of about 44px.                                                                                                                                                                                        | §13            |
| C-03 | English and Urdu UI. PDFs in English only in the first release. PKR whole rupees. Asia/Karachi time.                                                                                                                                                                                                                            | §1, §17        |
| C-04 | Inquiry management and conversion are Admin-only. A duplicate phone shows a warning but submission is still allowed, and no private data is revealed. The consent checkbox is unchecked by default. The public endpoint is IP rate-limited. The inquiry can be deleted independently of the member it became.                   | §4             |
| C-05 | Admin and Trainer create and edit members. Duplicate phone numbers are prevented. Member IDs look like GYM-001.                                                                                                                                                                                                                 | §5             |
| C-06 | Archiving is blocked while the member has an active membership. Restore reuses the same record and ID. Archived members are excluded from normal totals.                                                                                                                                                                        | §5.2, §5.3     |
| C-07 | When the membership expires, the member becomes Inactive automatically. When a new membership is activated, an Inactive member becomes Active again automatically.                                                                                                                                                              | §5.3, §6.3     |
| C-08 | Admin and Trainer can upload or replace member photos. Only Admin can permanently remove a photo. The old Cloudinary asset is deleted only after the change is committed, and failed clean-ups are logged for retry.                                                                                                            | §5.4           |
| C-09 | Unlimited plans, of type Monthly or Custom. Only Admin manages plans and prices. Admin can set a member-specific custom price, which needs a reason and is logged. There is no discount feature.                                                                                                                                | §6.1           |
| C-10 | One current active membership per member. Membership statuses: Pending Activation, Upcoming, Active, Expired.                                                                                                                                                                                                                   | §6.2           |
| C-11 | Activation needs at least a partial verified payment. A zero paid amount blocks activation.                                                                                                                                                                                                                                     | §6.2, §7.3     |
| C-12 | Calendar-month rule: a membership starting 1 Nov expires 30 Nov (inclusive). An early renewal starts the day after the previous expiry. A late renewal starts on the activation date. Every renewal creates a new record. Expiry dates cannot be edited manually. There is no pause, no early cancellation and no auto-renewal. | §6.2           |
| C-13 | One Payment summary per membership, plus one PaymentEntry for each payment received.                                                                                                                                                                                                                                            | §7.2           |
| C-14 | Payment statuses: Paid, Unpaid, Partially Paid, Pending. Pending or unverified amounts do not count as paid.                                                                                                                                                                                                                    | §7.1, §7.2     |
| C-15 | Overpayment and future-dated payments are blocked. Backdated payments are allowed. Corrections need a mandatory reason and keep the history. Old and new balances stay separate.                                                                                                                                                | §7.2           |
| C-16 | One unique receipt per verified payment event, as a PDF. Admin and Trainer can share it through WhatsApp, subject to consent and opt-out. Sharing is logged.                                                                                                                                                                    | §7.4           |
| C-17 | Financial records are deleted only separately, under safeguards. Nothing cascades. Payment history is kept permanently by default.                                                                                                                                                                                              | §7.5, §12      |
| C-18 | Exercise library (simple). Admin and Trainer can add and edit exercises.                                                                                                                                                                                                                                                        | §8             |
| C-19 | Any Trainer can add a workout note. A Trainer can edit or delete only notes they wrote. Admin can view, edit and delete all notes. Deletion is a soft delete.                                                                                                                                                                   | §8             |
| C-20 | The Admin dashboard metrics are as listed in §9.1, using the definitions in §9.3. The upcoming-expiry widget appears on the Admin dashboard only.                                                                                                                                                                               | §9             |
| C-21 | Reports cover custom date ranges, are PDF only, filter by Cash or Online, and show income and expenses separately. There is no net-profit figure. Archived members appear only when the filter is selected. The full personal-data export needs password confirmation and is logged.                                            | §9.4           |
| C-22 | Expenses have a title, a category (Rent, Utilities, Salaries, Equipment, Maintenance, Other), an amount, a date, a method and the user who created them. Admin can create, edit and delete them, with safeguards.                                                                                                               | §9.5           |
| C-23 | WhatsApp uses the Meta Cloud API directly, not Twilio. Admin manages templates (create, edit, delete). Trainers can view and send templates only. Messages are template-only. The app never shows a false success.                                                                                                              | §10.1          |
| C-24 | Automatic messages are sent for four events: new membership, payment received, expiry reminder and membership expired. Partial-payment and payment-due reminders are not automatic.                                                                                                                                             | §10.2          |
| C-25 | Opt-out blocks all sends, automatic and manual, including receipts. Consent history is kept with timestamps.                                                                                                                                                                                                                    | §10.3          |
| C-26 | Transient failures retry every 15 minutes, up to 3 retries. Permanent failures are not retried. A notification is marked Failed when its retries are used up. Provider IDs and webhook statuses are stored.                                                                                                                     | §10.4          |
| C-27 | Persistent sessions with a 90-day inactivity expiry, httpOnly secure cookies, rotation and revocation. Logins on multiple devices are allowed. Admin can force-logout a Trainer. Deactivating an account cuts access immediately. Trainers cannot change their own password.                                                    | §11.1          |
| C-28 | Passwords have at least 12 characters, common passwords are rejected, and they are stored as hashes. Password reset works by email.                                                                                                                                                                                             | §11.2          |
| C-29 | Repeated failed logins get progressive delays, with no permanent lockout. There is no 2FA in the first release.                                                                                                                                                                                                                 | §11.3, §11.4   |
| C-30 | The first Admin is set up with a one-time token, which is then disabled permanently. There are no default credentials.                                                                                                                                                                                                          | §11.5          |
| C-31 | A Trainer account can be deactivated or deleted without losing their historical records.                                                                                                                                                                                                                                        | §11.6          |
| C-32 | Activity logs and login history are kept 2 years. Payment history is kept permanently. A minimal permanent deletion-audit record is written.                                                                                                                                                                                    | §11.7          |
| C-33 | Every permanent deletion needs password re-entry, a second confirmation, a reason, a deletion-audit record and a dependency check. Nothing cascades.                                                                                                                                                                            | §12            |
| C-34 | The SRS selects the stack: React + Vite, JavaScript, Tailwind, Context, React Hook Form, Zod, Express REST, MongoDB Atlas, Vercel, Render, Cloudinary and Meta Cloud API.                                                                                                                                                       | §14            |
| C-35 | Weekly automatic backups are kept for 8 weeks. Admin sees the backup status. Restores are done by the technical operator only.                                                                                                                                                                                                  | §14.2, §19     |
| C-36 | Separate development, staging and production environments. HTTPS. Secrets are kept in environment variables.                                                                                                                                                                                                                    | §14, §19       |
| C-37 | The custom domain is chosen after development. The WhatsApp sender number is chosen during Meta onboarding.                                                                                                                                                                                                                     | §19            |
| C-38 | **Trainers can both archive and restore members.** Archiving stays blocked while the member has an active membership. Admin has the same rights. (Confirmed by the user on 17 Nov 2026; resolves X-16.)                                                                                                                         | §3.1, §5.2     |

---

## X — Conflicts

Each conflict below has a disagreement in the text itself. The planned behaviour follows the precedence rule. **The user can override any of them.**

**Status:** X-16 is **resolved** (C-38). X-21 is **resolved in the Phase 9 review by D-131** (member deletion stays blocked while protected history exists; nothing is deleted, anonymised or detached; the SRS is unchanged). The rest are resolved by the precedence rule.

| ID   | Topic                                                            | Master Prompt says                                                                          | SRS v2.0 says                                                                                                                                                                                                                                                                                                                            | Planned behaviour                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ---- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| X-01 | Password minimum                                                 | 8 characters (§17)                                                                          | 12 characters, and common passwords are rejected (§11.2)                                                                                                                                                                                                                                                                                 | **SRS** (stricter)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| X-02 | Login-attempt limit                                              | "SRS records no login-attempt limit"; recommend limiting (§17)                              | Progressive delays, no permanent lockout (§11.3)                                                                                                                                                                                                                                                                                         | **SRS**. The progressive delay is supplemented by D-06                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| X-03 | 2FA                                                              | Optional for Admin and Trainer (§17)                                                        | Not in the first release (§11.4)                                                                                                                                                                                                                                                                                                         | **SRS**: not built                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| X-04 | Session lifetime                                                 | Logged in until manual logout, "according to the selected session policy" (§17)             | 90-day inactivity expiry (§11.1)                                                                                                                                                                                                                                                                                                         | **SRS**. The 90-day policy is the "selected policy"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| X-05 | Trainer and WhatsApp templates                                   | Trainer can edit templates (§6, §14.2)                                                      | Trainer can view and send only; Admin creates, edits and deletes (§3.1, §10.1)                                                                                                                                                                                                                                                           | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-06 | Receipt sharing                                                  | Admin can share (§11.7)                                                                     | Admin and Trainer can share (§7.4)                                                                                                                                                                                                                                                                                                       | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-07 | Payment structure                                                | One payment record per membership, with no separate record for each partial payment (§11.3) | One Payment summary per membership, plus a PaymentEntry for each payment and a receipt for each verified event (§7.2, §7.4)                                                                                                                                                                                                              | **SRS**. The summary rule in the Prompt is kept, and the ledger sits underneath it                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| X-08 | Correction log name                                              | `PaymentChangeLog` (§18)                                                                    | `PaymentCorrectionLog` (§15)                                                                                                                                                                                                                                                                                                             | **SRS name** used                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| X-09 | Notification retry delays                                        | "Sensible progressive retry delays" (§14.4)                                                 | Fixed 15-minute interval, maximum 3 retries, transient errors only (§10.4)                                                                                                                                                                                                                                                               | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-10 | Hosting                                                          | Not yet finalised; do not decide without discussion (§23)                                   | Vercel, Render, Atlas and Cloudinary, subject to cost validation (§14, §19)                                                                                                                                                                                                                                                              | **SRS**. Costs are validated before staging (P-02 to P-05)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| X-11 | Full personal-data export                                        | Format still open (§15)                                                                     | PDF only, with password confirmation, logged (§9.4)                                                                                                                                                                                                                                                                                      | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-12 | Expense fields                                                   | Confirm before implementing (§15)                                                           | Fields and categories defined (§9.5)                                                                                                                                                                                                                                                                                                     | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-13 | Workout-note permissions                                         | Unresolved; ask first (§12)                                                                 | Defined (§8)                                                                                                                                                                                                                                                                                                                             | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-14 | Reactivation                                                     | Confirm the behaviour (§9.5)                                                                | Automatic reactivation (§5.3)                                                                                                                                                                                                                                                                                                            | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-15 | Backup restoration                                               | Admin manages backups and restores, with safeguards (§6)                                    | Technical operator only; Admin views the status (§3.1, §14.2)                                                                                                                                                                                                                                                                            | **SRS**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| X-16 | **Trainer archive and restore**                                  | Archive and restore are listed under **Admin only** (§9.4)                                  | §3.1 matrix: Trainer **can** archive and restore, but cannot archive while a membership is active. §5.2: "Trainers can archive/restore subject to the same active-membership block." **Appendix A**: "archive blocked with active membership; **Admin restore**"                                                                         | **RESOLVED: confirmed by the user on 17 Nov 2026.** Trainers can both archive and restore members, following SRS §3.1 and §5.2. Archiving stays blocked while a membership is active. Recorded as C-38. **The SRS Appendix A Member row was amended to match (revision 4)**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| X-17 | Member permanent deletion                                        | "Do not routinely permanently delete members" (§9.4)                                        | Admin may delete, with safeguards and dependency blocking (§12.2)                                                                                                                                                                                                                                                                        | Compatible. Deletion is Admin-only and protected, not routine                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| X-18 | Custom price and discounts                                       | "No discounts" (§10.2)                                                                      | No discount feature, but Admin can set a custom member price with a reason (§6.1)                                                                                                                                                                                                                                                        | Compatible. Built as a custom agreed price, not a discount                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| X-19 | Email password reset in the SRS itself                           | —                                                                                           | §11.2 "Provide secure email-based password reset" vs §11.1 "Trainer cannot change their own password; Admin manages Trainer password resets"                                                                                                                                                                                             | Resolved by **D-07**: email reset is for Admin accounts only                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| X-20 | Handover document list                                           | PROJECT_STATUS, HANDOVER, CHANGELOG, NEXT_STEPS, docs/ (§24.3)                              | Also README.md and docs/SRS.md (§20.1)                                                                                                                                                                                                                                                                                                   | All of both lists are created                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| X-21 | Member deletion vs records that cannot be deleted (SRS internal) | —                                                                                           | §12.2: a member can be deleted only after linked records are handled, and deletion is blocked if any protected dependency remains. However, workout notes are soft-delete only (§8, §12.2), and §12.2 gives **no** deletion path for consent history or notification history. Every member has a consent-history entry from registration | **RESOLVED in Phase 9 (20 Nov 2026) by D-131**, within the approved SRS and with no amendment: the §12.2 dependency rule is applied as written, so a member with protected history cannot be deleted and is archived instead. _History of this entry:_ **deferred by the user (17 Nov 2026) until the Phase 9 review.** Until a formal decision, and any SRS amendment that is needed, is reviewed before Phase 9, member deletion is built exactly as the SRS says: dependency checks and a block while protected records exist. **Nothing is deleted to get around the block.** Consent history, notification history and soft-deleted workout notes are **not** deleted. Any future approach must keep the SRS no-cascade and retention rules. The workaround suggested in revision 2 is withdrawn and will not be implemented |

---

## D — Delegated decisions

Each decision was made under the authority the user delegated, for points the approved documents leave open. None of them changes a C item.

### Authentication and accounts

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                                                         | Reason                                                                                                                                                                                                                                                                                               |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| D-01 | **Sessions are stored in the database.** The cookie holds a random opaque token (httpOnly, Secure, SameSite=Lax), and only its SHA-256 hash is stored. The token rotates every 24 hours, with a short grace period for requests already in flight. Sessions expire after 90 days of inactivity.                                                                                                                  | SRS §11.1 requires _immediate_ loss of access when an account is deactivated or force-logged-out. Stateless JWT access tokens stay valid until they expire. A database lookup on each request costs little at single-gym scale. Rotation satisfies the "session/refresh-token rotation" requirement. |
| D-02 | **One origin for the app and the API.** Vercel rewrites `/api/*` to the Render service, so the browser only talks to the Vercel domain.                                                                                                                                                                                                                                                                          | Vercel and Render are different sites. Safari on iOS blocks third-party cookies, which would break login on iPhones. Phones are the primary target.                                                                                                                                                  |
| D-03 | **CSRF protection** uses three measures: SameSite=Lax cookies, a strict Origin/Referer check on every state-changing request, and a JSON-only request body (except upload endpoints, which check Origin).                                                                                                                                                                                                        | This is enough protection when the app is same-origin, and it needs no token plumbing.                                                                                                                                                                                                               |
| D-04 | **Passwords are hashed with argon2id** (memory-hard, using OWASP-recommended parameters).                                                                                                                                                                                                                                                                                                                        | SRS: "modern password-hashing algorithm".                                                                                                                                                                                                                                                            |
| D-05 | **Common passwords are rejected** using a bundled list of about 49,000 common passwords (from `@zxcvbn-ts/language-common`, MIT; updated in Phase 1 from the planned 10,000), plus checks that the password does not contain the username, email or gym name.                                                                                                                                                    | Meets SRS §11.2 without calling an external service.                                                                                                                                                                                                                                                 |
| D-06 | **Progressive delay on failed logins.** Failures are counted per account and per IP. From the 3rd consecutive failure, the server waits before answering: 1s, then 2s, 4s, 8s, 16s, capped at 30s. The counter resets after a successful login. There is also a generous per-IP cap on the login endpoint: about 30 attempts per 15 minutes, answered with HTTP 429 and a retry time. Nothing locks permanently. | Meets SRS §11.3 ("progressive delays, no permanent lockout") and the Master Prompt's recommendation to limit repeated attempts. A legitimate user is never locked out permanently.                                                                                                                   |
| D-07 | **Password reset by email is for Admin accounts only.** A Trainer's password is reset directly by an Admin. Reset links are single-use, expire after 30 minutes, are stored as hashes, and the request always returns the same generic response.                                                                                                                                                                 | Reconciles SRS §11.1 with §11.2 (X-19) without weakening "Trainer cannot change their own password".                                                                                                                                                                                                 |
| D-08 | **Login identity.** Every account has a unique username (lowercase). Email is required for Admins, because reset needs it, and optional for Trainers. The login field accepts either the username or the email.                                                                                                                                                                                                  | SRS §11.1: "email/password or username/password according to the configured account identity".                                                                                                                                                                                                       |
| D-09 | **Admin accounts.** Any Admin can create Admin or Trainer accounts and can deactivate or reactivate _another_ Admin. An Admin cannot deactivate or delete themselves. The last active Admin cannot be deactivated or deleted. Force-logout and direct password reset apply to Trainer accounts, as in the SRS. An Admin recovers their own access by email reset (D-07).                                         | The SRS allows several Admins but says nothing about managing them. These rules stop the gym from locking itself out.                                                                                                                                                                                |
| D-10 | Changing your own password (Admin only) requires the current password and revokes your other sessions.                                                                                                                                                                                                                                                                                                           | SRS §11.2.                                                                                                                                                                                                                                                                                           |
| D-11 | **First-Admin setup.** The operator runs a command-line script that prints a single-use token valid for 24 hours, and only its hash is stored. Once the first Admin is created, `setupCompleted` is set permanently and the setup endpoint returns 410 from then on.                                                                                                                                             | SRS §11.5. No default credentials.                                                                                                                                                                                                                                                                   |
| D-12 | **Login responses are generic.** Unknown user, wrong password and deactivated account all get the same message. Login history records the real reason.                                                                                                                                                                                                                                                           | Avoids revealing which accounts exist.                                                                                                                                                                                                                                                               |
| D-13 | **Deleting a Trainer account** turns the User record into a tombstone: credentials and contact details are removed, status is set to `deleted`, and the label becomes "Former staff #N". Business records keep the actor ID and the actor's display name as it was when they acted.                                                                                                                              | SRS §11.6: "retained historical actor reference". Historical records stay attributable, and nothing cascades.                                                                                                                                                                                        |
| D-14 | **A Trainer's own profile.** A Trainer can view their profile and edit their display name, phone and preferred language. They cannot change their username, email, role or password.                                                                                                                                                                                                                             | Covers "Manage own profile" (Prompt §6) within SRS §11.1.                                                                                                                                                                                                                                            |

### Members, inquiries and consent

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                                             | Reason                                                                                                  |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| D-15 | **Gender values:** Male, Female. Kept as one shared constant so they can be changed in a single place.                                                                                                                                                                                                                                                                                               | SRS Appendix B left the values open. This fits a single-gym Pakistani context and is easy to extend.    |
| D-16 | **Phone numbers** are normalised to E.164 with Pakistan as the default region (`03xx…` becomes `+923xx…`) using `libphonenumber-js`. The number as typed is also kept for display. Invalid numbers are rejected.                                                                                                                                                                                     | Duplicate detection and WhatsApp both need one standard format.                                         |
| D-17 | **Duplicate inquiry flow (two steps).** If the phone matches an _earlier inquiry_, the API returns `requiresConfirmation` without saving. The visitor sees a neutral warning ("We already received an inquiry from this number"). If they confirm, the inquiry is saved with duplicate metadata. A match against an existing _member_ is never shown publicly; it is flagged only in the Admin view. | SRS §4.3 and Prompt §7.7: warn, still allow submission, reveal nothing private.                         |
| D-18 | **The preferred plan** on the inquiry form is optional, with a "Not sure yet" choice. When a plan is chosen, its name is stored as a snapshot.                                                                                                                                                                                                                                                       | SRS §4.2 does not mark the field as required. Making it optional reduces friction on mobile.            |
| D-19 | **Inquiry conversion.** Each inquiry can be converted to a member once. Conversion stores `convertedMemberId` and sets the inquiry status to Approved. The member keeps `sourceInquiryId` only as a weak reference; nothing depends on the inquiry continuing to exist.                                                                                                                              | SRS §4.3 and §12.3.                                                                                     |
| D-20 | **Consent on staff-created members.** The member form has a WhatsApp consent checkbox, unchecked by default, that Admin or Trainer can tick at registration. Opting a member out, and recording consent again after an opt-out, are Admin-only. Every change writes an immutable ConsentHistory entry.                                                                                               | SRS §10.3 gives opt-out to Admin. Recording consent at registration is a normal staff task.             |
| D-21 | **Archived members are read-only** apart from viewing and restoring. They cannot get new memberships, new payment entries or WhatsApp sends until restored.                                                                                                                                                                                                                                          | Keeps the separate "archived" record state from being confused with the membership state (Prompt §9.5). |
| D-22 | **Admin notes:** Admin can view and edit them. Trainers can view them read-only on the profile.                                                                                                                                                                                                                                                                                                      | SRS calls them internal Admin notes. Trainers have operational access to the profile (Prompt §9.3).     |
| D-23 | **Member search:** case-insensitive "contains" search on the name (input is escaped), exact or prefix match on the Member ID, and a contains search on the normalised phone. Lists show 20 per page by default, 100 at most.                                                                                                                                                                         | Practical at single-gym scale without a search engine.                                                  |

### Memberships

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                                                 | Reason                                                                                               |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| D-24 | **The custom-duration unit is days.** Monthly plans use calendar months (a duration value of N months).                                                                                                                                                                                                                                                                                                  | SRS Appendix B. Days are unambiguous.                                                                |
| D-25 | **Month-end rule.** End date = the day before the same calendar date N months later. If that later date does not exist, the end date is the last day of that later month. Examples: 1 Nov → 30 Nov. 15 Nov → 14 Dec. 31 Jan → 28 Feb (29 in leap years). 30 Jan → 28/29 Feb. 29 Feb 2028 → 28 Mar 2028. For custom plans, end = start + N − 1 days.                                                      | Matches the SRS example (1 Nov → 30 Nov inclusive) and is deterministic for every edge case.         |
| D-26 | **At most one "next" membership.** A member can have at most one Active membership plus one Pending Activation or Upcoming membership. This is enforced by a unique index.                                                                                                                                                                                                                               | Supports early renewal without letting renewals stack up indefinitely. Consistent with "one active". |
| D-27 | **Activation flow.** Staff can create a membership, record its first verified payment and activate it in one atomic action. A Pending Activation membership can also be activated later. If the member already has an Active membership when activation happens, the new one becomes Upcoming and starts the day after the current one ends. Otherwise it becomes Active, starting today (Asia/Karachi). | SRS §6.2 and §7.3: early renewal starts after expiry, late renewal starts on the activation date.    |
| D-28 | **Membership lifecycle job.** A daily job at 00:05 Asia/Karachi expires memberships whose end date has passed, promotes Upcoming memberships to Active when they reach their start date, and updates member states. The same rules are also checked whenever a member is read, so a missed job cannot leave wrong statuses on screen.                                                                    | Automatic expiry (SRS §6.2) that stays correct even if a job run is missed.                          |
| D-29 | **The upcoming-expiry widget** shows memberships ending in the next 7 days by default, with 14 and 30-day filters.                                                                                                                                                                                                                                                                                       | The SRS leaves the window open.                                                                      |
| D-30 | A membership's **plan details are snapshotted** (name, duration, advertised price) when it is created. Changing a plan's price later does not alter existing memberships. Plans are never deleted, only deactivated.                                                                                                                                                                                     | Historical accuracy. The SRS lists no plan deletion.                                                 |

### Payments and receipts

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Reason                                                                                                        |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| D-31 | **PaymentEntry verification states:** `pending`, `verified` and `rejected`. Cash is recorded as verified. Online can be recorded as verified (screenshot already checked) or pending (awaiting a check). Only **verified** entries count towards the paid total. A pending entry is later verified or rejected; rejecting needs a reason.                                                                                                                   | SRS §7.1: "Pending/unverified amounts do not count".                                                          |
| D-32 | **Payment summary status** is worked out from the entries: **Paid** when the balance is 0; **Partially Paid** when some verified money has been received but the balance is above 0; **Pending** when no verified money has been received and at least one entry awaits verification; **Unpaid** when no verified money has been received and nothing awaits verification. A separate `hasPendingVerification` flag is shown whenever any entry is pending. | Keeps all four SRS statuses and the "pending does not count" rule.                                            |
| D-33 | **Overpayment check.** A new or corrected entry is rejected if verified + pending + new amount would exceed the total due.                                                                                                                                                                                                                                                                                                                                  | SRS §7.2: overpayment is blocked.                                                                             |
| D-34 | **Corrections.** On an entry, staff can correct the amount, method, payment date and reference; a reason is required, and the result cannot be an overpayment or a future date. Correcting a summary's **total due** is Admin-only, needs a reason, and cannot go below the verified paid amount. This is consistent with Admin-only custom pricing. Every correction writes an immutable PaymentCorrectionLog entry.                                       | SRS §7.2 and §6.1.                                                                                            |
| D-35 | **Receipts are immutable.** If a verified entry with a receipt is corrected, the original receipt is marked _Void — corrected_ (still viewable and downloadable with a VOID watermark), and a new receipt with a new number is issued and linked to it. Rejecting a pending entry issues no receipt.                                                                                                                                                        | Original values are preserved (SRS §7.2) and receipts always match the ledger.                                |
| D-36 | **Number formats grow naturally:** GYM-001 … GYM-999, GYM-1000; REC-0001 … REC-9999, REC-10000. Numbers come from an atomic counter, are never reused, and have unique indexes.                                                                                                                                                                                                                                                                             | Concurrency-safe and unique (Prompt §9.1, §11.7).                                                             |
| D-37 | **A receipt shows the cumulative paid amount and the balance as they stood at that payment event** (a snapshot), with the gym name and logo as they were when the receipt was issued.                                                                                                                                                                                                                                                                       | SRS §7.4 receipt contents.                                                                                    |
| D-38 | **"Today's collections"** = verified entries whose payment date is today (Asia/Karachi). **"Monthly income"** = verified entries whose payment date falls in the current calendar month. **"Outstanding payments"** = the sum of balances across non-archived members' payment summaries. Backdated entries count on their payment date.                                                                                                                    | SRS §9.1 and §9.3 define the metric names but not the date basis. The payment date is what reports filter on. |

### Notes, exercises, expenses and reports

| ID   | Decision                                                                                                                                                                                                            | Reason                                                                                                                                                                                                                   |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| D-39 | **Exercises have no delete endpoint** in the first release; they can only be edited.                                                                                                                                | The SRS lists add and edit only, and §12.2 lists no exercise deletion.                                                                                                                                                   |
| D-40 | Soft-deleted **workout notes** are hidden from Trainers. An Admin can see them using a "show deleted" filter. There is no un-delete in the first release.                                                           | SRS §8: soft delete keeps history.                                                                                                                                                                                       |
| D-41 | **Expenses are Admin-only** (create, edit, view, delete). Trainers have no expense screens or endpoints.                                                                                                            | The SRS §3.1 matrix gives Trainers no expense rights, and Prompt §6 lists "Record expenses" under Admin only. _Interpretation_: SRS §9.5's "Trainer cannot permanently delete expenses" is read as consistent with this. |
| D-42 | **Reports are generated on demand.** Each PDF shows when it was generated, who generated it, the date range and the filters. No report snapshots are stored.                                                        | SRS Appendix B: "historical exports are clearly dated".                                                                                                                                                                  |
| D-43 | **PDFs are generated on the server with `pdfmake`.**                                                                                                                                                                | Real PDFs (Prompt §11.7) in pure JavaScript, with no headless browser on Render.                                                                                                                                         |
| D-44 | **Trainer dashboard:** a member overview (counts), a payment-status overview (counts by status, with no money totals), recent workout notes, notifications the Trainer sent, and the Trainer's own recent activity. | Prompt §13.2 and SRS §9.2, without exposing Admin financial reports.                                                                                                                                                     |

### WhatsApp

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                                    | Reason                                                                                                                                                                                              |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| D-45 | **Template model.** Each in-app template is linked to a Meta template (name, language and variable mapping). Creating or editing a template submits it to Meta through the WhatsApp Business Management API, and its approval status is synced. Only _approved and enabled_ templates can be sent. Editing a template marks it "awaiting Meta approval".                                    | SRS §10.1: in-app editing without an internal approval workflow, while still respecting Meta approval and never showing a false success. _To verify in Phase 7 against current Meta API behaviour._ |
| D-46 | **Sending uses an outbox.** Every send, automatic or manual, creates a Notification record first, with a unique idempotency key (for example `payment_received:<entryId>`). A dispatcher running every minute claims due records atomically. Consent and opt-out are checked again at dispatch time.                                                                                        | No duplicate messages (Prompt §14.4), survives restarts, and no background job can skip the consent check.                                                                                          |
| D-47 | **Retry policy.** Transient errors are network errors, timeouts, HTTP 5xx and Meta throttling codes. Permanent errors are an invalid recipient, a template that is not approved or was rejected, bad parameters, and opt-out. Transient errors are retried every 15 minutes, up to 3 retries (4 attempts in total), and the notification is then marked Failed with `needsFollowUp = true`. | SRS §10.4.                                                                                                                                                                                          |
| D-48 | **Send times.** Expiry reminders and expired notices are queued for 10:00 Asia/Karachi, so members are not messaged around midnight. Confirmations (new membership, payment received) are sent immediately.                                                                                                                                                                                 | A practical courtesy that changes no rule.                                                                                                                                                          |
| D-49 | **Receipt sharing** sends the PDF as a document header on an approved template. If this cannot be done (template not approved, media upload failure, API limits), the UI clearly offers the manual route: download the PDF and share it yourself. That manual route is logged as "manual share" and never as "delivered".                                                                   | SRS §7.4. _To verify in Phase 7._                                                                                                                                                                   |
| D-50 | **Webhooks.** Each request's `X-Hub-Signature-256` is checked with the app secret. Each status is stored once per (provider message ID, status). "Delivered" or "read" is shown only when Meta reports it.                                                                                                                                                                                  | SRS §10.4: no false status.                                                                                                                                                                         |
| D-51 | **Without credentials, a mock adapter** is used, labelled "WhatsApp not configured — simulated" in the UI and in logs. Its results are never reported as real sends.                                                                                                                                                                                                                        | Master Prompt §14 and §26.                                                                                                                                                                          |

### Content, localisation, UI

| ID   | Decision                                                                                                                                                                                                                                             | Reason                                                               |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| D-52 | **Public website content is bilingual.** Text fields are stored as `{ en, ur }`, with English required and Urdu optional; if the Urdu text is missing, English is shown.                                                                             | SRS requires English and Urdu UI, and Admin edits the content.       |
| D-53 | **Language preference.** The Admin sets the default language in settings. Each staff user can switch language, and the choice is saved on their profile. Public visitors' choice is saved in their browser. Urdu switches the page to right-to-left. | Localization-ready (Prompt §16).                                     |
| D-54 | **Theme preference** is saved in the browser and defaults to the device's system theme.                                                                                                                                                              | Prompt §5.7: "remember the user's theme preference".                 |
| D-55 | **Fonts:** Inter for Latin text and Noto Nastaliq Urdu for Urdu, both self-hosted.                                                                                                                                                                   | Inter has no Urdu glyphs.                                            |
| D-56 | **Every permanent deletion uses the full SRS §12.1 safeguards**, including gallery images, public trainer cards, WhatsApp templates, member photos and Trainer accounts.                                                                             | SRS §12.1 says "every permanent deletion". It is applied as written. |
| D-57 | **Browser support:** the last 2 versions of Chrome for Android, Samsung Internet and desktop Chrome, Edge, Firefox and Safari, plus Safari on iOS 16 and later.                                                                                      | SRS Appendix B.                                                      |
| D-58 | **Performance targets:** public pages LCP ≤ 2.5s on a typical 4G phone; common API reads p95 ≤ 500ms with the API and database in the same region; images served at a suitable size through Cloudinary transforms.                                   | SRS Appendix B and §17.                                              |

### Infrastructure and operations

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                               | Reason                                                                                                                    |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| D-59 | **One always-on Render web service per environment** runs both the API and the scheduler. A MongoDB lease lock ensures only one instance runs scheduled jobs.                                                                                                                                                                                                                          | Avoids paying for a separate background worker at single-gym scale. Still safe if it is ever scaled out.                  |
| D-60 | **Region:** Render Singapore and Atlas Singapore (AWS ap-southeast-1), in the same region.                                                                                                                                                                                                                                                                                             | Keeps API-to-database latency low, which matters most. Render has no South Asia region. _To verify at deployment._        |
| D-61 | **Backups.** A scheduled Node script exports every collection through the MongoDB driver (canonical EJSON), compresses and encrypts the export (AES-256-GCM), and uploads it to S3-compatible object storage. It keeps the latest 8 weekly backups and writes a BackupRun record. There is a matching command-line restore script for the operator only; restore has no HTTP endpoint. | SRS §19. Atlas M0 has no cloud backups, and this method works on any tier and on Render without the `mongodump` binaries. |
| D-62 | **Activity-log privacy.** For personal fields (name, phone, address, age, gender, notes), the log records the _field names_ that changed, not their values. Financial and status values are recorded as before and after.                                                                                                                                                              | SRS §11.7 says deletion audits must not keep personal data, and logs must not quietly keep data that was later deleted.   |
| D-63 | **Runtime and tooling:** the current Node.js LTS (24.x at the time of writing) and the current major versions of Vite, React, React Router and Tailwind CSS, all checked at the start of Phase 1.                                                                                                                                                                                      | Stable and actively maintained (Prompt §4).                                                                               |
| D-64 | **API conventions:** base path `/api/v1`, a standard JSON response envelope, page and limit pagination, `sort` parameters, and correct HTTP status codes (see `docs/API.md`).                                                                                                                                                                                                          | Prompt §19 and SRS §16.                                                                                                   |

### Phase 1 implementation decisions

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                  | Reason                                                                                                                               |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| D-65 | **Session rotation runs in the authentication middleware** on any authenticated request once the token is older than 24 h, using a conditional update so that only one of several parallel requests rotates it.                                                                                                                                           | A superset of the "rotate on `/auth/me`" plan. Rotation happens even if the app never calls `/me`.                                   |
| D-66 | **Guarding the last active Admin against races.** Every Admin deactivation or deletion writes a shared guard counter inside its transaction. If two Admins remove each other at the same moment, the transactions conflict, one retries and is refused with `LAST_ADMIN`.                                                                                 | MongoDB snapshot isolation would otherwise allow write skew, which could leave zero active Admins (D-09). This is covered by a test. |
| D-67 | **Versions at the start of Phase 1:** Express 5.3, Mongoose 9.12, Zod 4.6, argon2 0.45, React 19.3, React Router 8.5, Vite 8.3, Tailwind CSS 4.3, i18next 27, Vitest 5.1, Playwright 1.65. `engines.node >= 22` (_replaced in Phase 5 Revision 1 by D-110_). Claude's workspace runs Node 22. Production should use the current Node LTS (24.x) per D-63. | Current stable majors (D-63).                                                                                                        |
| D-68 | _(Phase 1; the holding page and the use of `VITE_APP_NAME` were replaced in Phase 2 by D-74.)_ **The Phase 1 public home page is a simple holding page** (gym name and a short note), with no Join or Plans buttons until Phase 2 builds them. The gym name comes from `VITE_APP_NAME` until the Gym Settings screen exists.                              | Prompt §26: no placeholder buttons that do nothing.                                                                                  |
| D-69 | **Tailwind's default colour palette is switched off.** Only the official palette tokens (`bg-card`, `text-muted`, `bg-primary` …) can be used in markup.                                                                                                                                                                                                  | Prompt §5.2: no random colours across screens.                                                                                       |
| D-70 | **Completing first-Admin setup counts as that Admin's first sign-in** (`lastLoginAt` is set and a session starts).                                                                                                                                                                                                                                        | The owner is signed in straight away, so the dashboard shows an accurate "last sign-in".                                             |
| D-71 | **Staff screens are code-split** from the public page bundle using React `lazy`.                                                                                                                                                                                                                                                                          | D-58 performance. Further splitting is planned for Phase 2.                                                                          |
| D-72 | **Every route is declared through a wrapper that requires an access level** (public, session or permission key) and records the route in a registry. An automated test calls every registered route as an anonymous visitor, a Trainer and an Admin.                                                                                                      | Deny by default (SECURITY §1), and the 403 matrix test stays complete automatically as routes are added.                             |

### Phase 2 implementation decisions

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                   | Reason                                                                                                                                                                                                            |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| D-73 | **Update (PATCH) schemas never contain defaults.** Defaults are used only in create schemas (`.prefault()` / `.default()`).                                                                                                                                                                                                                                                | In Zod 4 a default inside a `.partial()` schema fills in fields that were not sent, so an update could silently erase stored text. This was found during Phase 2 testing, fixed, and covered by regression tests. |
| D-74 | **The public website loads everything from one endpoint, `GET /public/site`** (60-second cache). The staff app uses the same data for the gym name and logo, so `VITE_APP_NAME` is now only the fallback before settings load. Sections with no content (trainers, About, gallery) are hidden; nothing is invented.                                                        | One round trip on mobile (D-58). Prompt §26: no hard-coded business data.                                                                                                                                         |
| D-75 | **Image uploads without Cloudinary:** upload endpoints answer `503 INTEGRATION_NOT_CONFIGURED`. `GET`/`PATCH /settings` include `integrations.mediaUploads` so the UI can disable upload controls and explain why. Automated tests use a clearly labelled in-memory fake media store. **Real Cloudinary has not been tested (P-05).**                                      | The user's instruction and Prompt §26: safe, documented behaviour, with no invented credentials and no false claims.                                                                                              |
| D-76 | **`GET /inquiries/counts`** (Admin) returns counts per status. It drives the "N new" badge in the navigation and the "New inquiries" dashboard card.                                                                                                                                                                                                                       | Prompt §8: the new-inquiry notification is dashboard-only. A small addition to API.md §7.                                                                                                                         |
| D-77 | **Inquiry consent history:** every submission writes an immutable ConsentHistory entry (`consent_given` or `consent_not_given`, source `public_form`). Deleting an inquiry leaves these entries in place.                                                                                                                                                                  | C-25 (store consent history) and C-33 (no cascade). They contain no personal data. This is the existing no-cascade rule, not an X-21 decision.                                                                    |
| D-78 | **Inquiry status changes** are free between New, Pending, Approved and Rejected. An optional note is stored as the activity-log reason.                                                                                                                                                                                                                                    | SRS §4: Admin can change status. Nothing restricts the order.                                                                                                                                                     |
| D-79 | _(Phase 2; Phase 3 added the "Add member" action and the conversion itself.)_ **Phase 2 provides only the conversion prefill** (`GET /inquiries/:id/conversion-prefill`). There is no "Add member" button yet; the inquiry page says this arrives with Phase 3. Recording the conversion and setting the status to Approved (D-19) happen when Phase 3 creates the member. | The user's instruction: prefill only; no Phase 3 functionality.                                                                                                                                                   |
| D-80 | **Duplicate checks:** the public warning compares against earlier _inquiries_ only. The Admin-only `matchesExistingMember` flag is computed only once the Member model exists (Phase 3) and is `false` until then. _(Turned on in Phase 3; see D-91.)_                                                                                                                     | D-17. No member data exists before Phase 3.                                                                                                                                                                       |
| D-81 | **The scheduler starts in Phase 2** with a single job: the hourly asset clean-up retry (minute 17, Asia/Karachi), under a MongoDB lease lock. `SCHEDULER_ENABLED` controls it (on by default outside tests).                                                                                                                                                               | C-08: failed clean-ups are retried. D-59 and D-81 keep a single process.                                                                                                                                          |
| D-82 | **Public mobile layout:** a sticky "Join now" bar at the bottom of the screen; phone, WhatsApp and email contact cards are fully tappable (`tel:`, `wa.me`, `mailto:`); English fallback text in Urdu mode is marked `lang="en" dir="ltr"`.                                                                                                                                | Prompt §5.5 (easy actions, tap targets) and D-52. The `wa.me` link opens the visitor's own WhatsApp; it is not a WhatsApp Business API integration.                                                               |
| D-83 | **An invalid plan duration on update** answers `400 VALIDATION_ERROR`, the same as on create, even though the check runs in the service because it needs the stored duration type.                                                                                                                                                                                         | Consistent error handling for the UI.                                                                                                                                                                             |
| D-84 | **Inquiry search** matches the name (case-insensitive, escaped) or the phone digits (a leading 0 is dropped to match E.164). Date filters use Karachi calendar days.                                                                                                                                                                                                       | D-23 and C-03.                                                                                                                                                                                                    |

### Phase 3 implementation decisions

| ID   | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Reason                                                                                                                                                                             |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| D-85 | **A newly registered member starts with membership state Inactive** (shown as "Inactive: no active membership"). It becomes Active only when a membership is activated in Phase 4 (C-07).                                                                                                                                                                                                                                                                                                                                                                                                                                            | The member has no membership yet. Showing "Active" would confuse the record with the membership (Prompt §9.5).                                                                     |
| D-86 | **Consent at inquiry conversion.** The Add Member form is prefilled with the visitor's own answer. Staff change it only if the person says otherwise. The member's first consent-history entry has source `inquiry_conversion` and a note saying whether the answer was carried over or changed. When it is unchanged, the visitor's original consent time is kept. The inquiry's own consent history stays with the inquiry; nothing is copied or moved.                                                                                                                                                                            | D-19, D-20 and C-25. The history stays immutable and stays truthful about who gave consent and when.                                                                               |
| D-87 | **Member deletion dependencies** are counted per type. Memberships, payment summaries, payment entries and receipts are _"delete separately first"_ records. Workout notes, WhatsApp message history, payment corrections and consent history are _protected_ records with no deletion path. Any count above zero blocks deletion with `409 DEPENDENCIES_EXIST`, and the screen lists the records with no way to continue. **Because every member has a consent-history entry from registration, member deletion is in practice always blocked until X-21 is decided (Phase 9).** Nothing is deleted or detached to get around this. | SRS §12.2 applied exactly, as the user instructed (X-21 stays deferred, no workaround). The deletion code path itself exists and is tested by clearing the test database directly. |
| D-88 | **Archived members are fully read-only (D-21):** no edits, photo changes, opt-out or consent changes until restored. New codes: `MEMBER_NOT_ARCHIVED` (restore a member who is not archived) and `WHATSAPP_CONSENT_ACTIVE` (consent recorded twice).                                                                                                                                                                                                                                                                                                                                                                                 | D-21 says read-only apart from viewing and restoring. The extra codes keep repeated clicks clear.                                                                                  |
| D-89 | **Consent after registration is Admin-only** (D-20), with a required note. After an opt-out the entry is `consent_restored`. For a member who never consented it is `consent_given`. Both have source `admin_action`.                                                                                                                                                                                                                                                                                                                                                                                                                | D-20 makes opt-out and consent again Admin-only. Using the existing event names keeps the history schema unchanged.                                                                |
| D-90 | **Member search** matches the name (case-insensitive, escaped), the phone digits (3 or more, with a leading 0 dropped) or the Member ID (`GYM-012`, `gym12` or just `12`). The "All" tab shows Active and Inactive members; archived members appear only on the Archived tab (`archived=true`). `GET /members/counts` returns the counts for the tabs and the dashboard.                                                                                                                                                                                                                                                             | SRS §5.2 and C-06 (archived only on request).                                                                                                                                      |
| D-91 | **`matchesExistingMember` is computed live** in the Admin inquiry list and details, so a member registered after the inquiry is still flagged. The member an inquiry was converted into does not count as a match for that same inquiry. The value saved at submission is kept for history. It is never shown publicly.                                                                                                                                                                                                                                                                                                              | D-17 and D-80. This turns the flag on in Phase 3.                                                                                                                                  |
| D-92 | **Archiving runs in a transaction** that reads the member's memberships and writes the member document. Phase 4 activation must also write the member document (to set Active, C-07) in its transaction, so the two conflict instead of skipping each other's check.                                                                                                                                                                                                                                                                                                                                                                 | Keeps "archiving is blocked while a membership is active" true under concurrency (same approach as D-66).                                                                          |
| D-93 | **Optional `API_RATE_LIMIT` setting** raises the general per-IP API limit (default 600 per 15 minutes; values below 600 are refused). Only the automated browser suite sets it, because the extended visual run makes thousands of requests from one address. Production keeps the default.                                                                                                                                                                                                                                                                                                                                          | Found in Phase 3 testing: the suite was hitting the limit. The default protection is unchanged.                                                                                    |

### Phase 4 implementation decisions

| ID    | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Reason                                                                                                                       |
| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| D-94  | **Phase 4 payment scope.** Every membership gets its payment summary in the same transaction (C-13). Only the **initial** payment entry can be recorded (when the membership is created, or when it is activated). It can be `verified` or `pending`. Verifying or rejecting a pending entry, further entries, corrections, receipts and the payment screens are **Phase 5**. **Verified entries recorded in Phase 4 have no receipt yet (`receipt: null`). Phase 5 must issue their receipts**, so that C-16 holds for them too.                                                                                                                                                                                                                                                             | The user's instruction: only the minimum needed for activation (C-11).                                                       |
| D-95  | **`POST /memberships/:id/activate` accepts an optional `initialPayment`** (always recorded as verified). It records the first verified payment and activates in one transaction. Without it, activation needs an existing verified payment.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | Keeps the "Activate with the first payment" workflow atomic without the Phase 5 payment endpoints. An addition to API.md §9. |
| D-96  | **The agreed price must be at least Rs 1** (`422 INVALID_PRICE`). Plans priced Rs 0 are not offered in the membership form.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | A zero price could never be activated, because activation needs a verified payment of at least Rs 1 (C-11).                  |
| D-97  | **Lifecycle implementation (D-28).** Each member is reconciled in its own transaction: an expired Active membership loses its slot, then a due Upcoming one is promoted, repeating until nothing changes (to catch up missed days). The member is then set Active or Inactive and `lifecycleVersion` is incremented. The daily job runs at 00:05 Asia/Karachi under the lease lock. The same reconcile runs when a member profile or its memberships are read, and inside every create or activate. Expire and promote steps are logged as the `system` actor. **The lease lock is not re-entrant**: each run uses its own token, so an overlapping run in the same process is skipped too. Phase 2's lock let the same process take it twice; this was found by the Phase 4 tests and fixed. | C-07 and D-28, made idempotent and safe against concurrent runs.                                                             |
| D-98  | **Upcoming expiries** list Active memberships whose end date is from today to today + 7, 14 or 30 days, soonest first. Archived members are excluded. Each row shows whether a renewal is already waiting and the balance. They appear on the Admin dashboard (next 7 days) and on the Admin "Expiries" screen, and never for Trainers (C-20).                                                                                                                                                                                                                                                                                                                                                                                                                                                | D-29 and C-20.                                                                                                               |
| D-99  | **Membership deletion** is blocked with `409 DEPENDENCIES_EXIST` while the membership's payment summary exists (SRS §12.2). The summary is created with every membership and payment deletion arrives in Phase 5, so **membership deletion is always blocked in Phase 4**. The deletion code path exists and is tested by clearing the test database directly. When a membership is deleted, the member's state is reconciled. Nothing cascades.                                                                                                                                                                                                                                                                                                                                              | SRS §12.2, applied as written; same approach as D-87.                                                                        |
| D-100 | **Online payments in the form.** Cash is recorded as verified. For an online payment, staff tick "I have checked the online payment" to record it as verified; otherwise it is recorded as pending, which does not count as paid and cannot activate the membership.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | D-31: verification is a staff check of the evidence (SRS §7.1).                                                              |
| D-101 | **Dates in the browser are only defaults and limits**: today's Karachi date as the default and maximum payment date. Every membership date is computed by the server. The form only explains when a membership will start, using the end date the server returned.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | C-12: all date calculations happen on the server.                                                                            |
| D-102 | _(Phase 4 Revision 1)_ **Cash is always verified.** A cash payment with `verificationStatus: pending` (or rejected) is refused with `400 VALIDATION_ERROR` by the request schema, again by the service, and by the PaymentEntry model, so no code path can store it. Online payments may be verified or pending. **When pending online payments already cover the whole price and nothing is verified,** the profile does not offer Activate or a payment form (no further payment could fit, D-33). It explains that the pending payment must be verified first, and the membership stays Pending Activation. With a partial pending payment, the rest can still be paid as verified and the membership activated.                                                                           | D-31 (cash is recorded as verified) enforced on the server; avoids offering an impossible action.                            |

### Phase 5 implementation decisions

| ID    | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | Reason                                                                  |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| D-103 | **Receipts for Phase 4 payments (backfill).** A one-off, idempotent step issues a receipt for every verified entry that has none. It runs at server start under the `receiptBackfill` lease lock, and as `npm run backfill-receipts -w server`. These receipts are marked `backfilled` and issued by "System". Their snapshot is computed when they are issued: the paid-to-date total follows verification order, with the gym name and total due as they are at that time. Pending and rejected entries are skipped, and so are entries whose receipt an Admin deleted on purpose (`receiptDeletedAt`). Two runs at once cannot create duplicates (one valid receipt per entry, partial unique index). | D-94 required Phase 5 to issue them; C-16.                              |
| D-104 | **Receipt snapshot (D-37):** gym name, member, plan and dates, payment date, method, reference, amount of this payment, **paid to date** (verified entries of the same summary in verification order, up to and including this one) and the balance. **Every correction of a verified entry voids its receipt** (kept, with a VOID watermark and "Replaced by REC-…") **and issues a new one**, because any corrected field is on the receipt. A total-due correction does not reissue receipts: they record their own moment. The PDF is generated on the server (pdfmake, built-in fonts, English) and fetches nothing external, so it shows no logo yet.                                              | D-35 and D-43; SRS §7.4.                                                |
| D-105 | **Concurrency and duplicate submissions.** Every payment change checks the summary's `version`. `expectedVersion` is required to record a payment, correct an entry or correct the total, and optional to verify or reject. A stale version gets `409 VERSION_CONFLICT`, and the screen reloads the record. Two identical submissions therefore cannot both succeed. Payment changes also write the member document (`lifecycleVersion`), so they conflict with a concurrent archive. Archived members' payments are read-only (D-21).                                                                                                                                                                   | docs/ARCHITECTURE.md §5.3; Prompt §11 (no duplicates).                  |
| D-106 | **Correction rules.** A rejected entry cannot be corrected (`409 ENTRY_REJECTED`). A pending entry cannot be changed to cash (`400`; verify it first, D-102). A correction that changes nothing is refused (`400 NO_CHANGES`). Overpayment and future-date guards apply to the corrected values. The total due can be corrected by an Admin only, never below `max(1, verified + pending)` (`422 TOTAL_BELOW_PAID`). The membership's agreed price is not changed: it records what was agreed, and the summary's total due is what is owed.                                                                                                                                                              | C-15, D-33, D-34.                                                       |
| D-107 | **Deletion order without cascades (C-17):** receipts, then entries (blocked while any receipt, valid or void, exists), then the summary (blocked while any entry exists). Deleting an entry recalculates the summary. Deleting a receipt records `receiptDeletedAt` on the entry so it is never re-issued. Correction logs are kept and count as protected records for member deletion. Membership deletion becomes possible once its summary is deleted (D-99).                                                                                                                                                                                                                                         | SRS §12.2; DATABASE.md §7.                                              |
| D-108 | **Workflow.** Verifying a pending payment issues its receipt but **does not activate** the membership by itself; staff still press Activate (D-27 unchanged). Payments are reached from each membership on the member profile (both roles), and Admins also have a **Payments** ledger (`/app/payments`) with status, balance and member filters. Sharing receipts by WhatsApp, and recording a manual share, remain Phase 7 (D-49).                                                                                                                                                                                                                                                                     | Keeps activation an explicit step; the SRS assigns WhatsApp to Phase 7. |

### Phase 5 Revision 1 decisions

| ID    | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Reason                                                                                                                            |
| ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| D-109 | **Receipts and activation in one step.** When a payment is recorded in the same transaction that activates the membership (create with "Activate now", or `POST /memberships/:id/activate` with `initialPayment`, D-95), the receipt is issued **after** activation, so its snapshot carries the membership's start and end dates (for an early renewal, the Upcoming dates). A payment recorded while the membership is still Pending Activation keeps an empty start and end date on its receipt: receipts record their own moment and are never rewritten (D-37, D-104). API responses return the snapshot as a plain object with exactly the D-104 fields (`snapshotView()`); a Mongoose subdocument is never spread into a response.                                                                                                 | Found while adding the Revision 1 snapshot API tests: such receipts had blank dates. SRS §7.4 receipt contents.                   |
| D-110 | **Supported Node.js versions: `^22.22.2 \|\| ^24.15.0 \|\| >=26.0.0`**, declared in the root, `server` and `client` `package.json`, and enforced with `engine-strict=true` in `.npmrc` (npm refuses to install on an unsupported Node instead of warning). This is the intersection of every `engines.node` in the lockfile; the binding constraints are jsdom 31 and w3c-xmlserializer 6 (`^22.22.2 \|\| ^24.15.0 \|\| >=26.0.0`), react-router 8.5 (`>=22.22.0`, a runtime dependency) and undici 8 (`>=22.19.0`). Node 23 and 25 (short-lived releases) are excluded by jsdom. Pinning older versions was rejected: it would mean downgrading react-router (a runtime major) and the test stack to support Node versions that are already superseded in their own release lines. Production uses Node 24 LTS (D-63), at least 24.15.0. | Replaces `>=22` (D-67), which allowed Node versions that 44 of the 313 locked packages with an engine requirement do not support. |

### Phase 6 implementation decisions

| ID    | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Reason                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| D-111 | **Exercise fields and uniqueness.** An exercise has a name (2–100 characters), an optional short description (≤ 500) and optional instructions (≤ 2000), plus created/updated by. Inner spaces are collapsed and the name is **unique ignoring letter case and extra spaces**, enforced by a unique index on a lower-cased key (Unicode NFC), so two simultaneous additions of "Plank" and "PLANK" cannot both succeed (`409 EXERCISE_NAME_EXISTS`). Changing only the letter case of an exercise's own name is allowed. Exercises are never deleted (D-39); edits are logged (the name with its old and new value, the long text by field name).                                                                                                                                                                                                                                              | SRS §8 and Appendix A (name, description/instructions, created/updated by); the user asked for case-insensitive uniqueness. A key field is more predictable than a collation index for spaces as well as case.                                                                                                                                                                                                                                                                                                                                                                                                                            |
| D-112 | **Workout-note rules.** Admin and Trainer can add notes (`notes.create` is Admin + Trainer, as in the Phase 1 matrix). A Trainer edits or soft-deletes only notes they wrote (`403 NOT_NOTE_AUTHOR`, checked in the service); an Admin edits and soft-deletes any note, and **the author never changes** (the edit is recorded as `editedBy`). Edits need `expectedVersion` (`409 VERSION_CONFLICT`); a delete may send it. A deleted note cannot be edited or deleted again (`409 NOTE_DELETED` for Admins); for Trainers it does not exist (`404`), and `status=deleted                                                                                                                                                                                                                                                                                                                      | all` is Admin-only (D-40). There is no un-delete. **Only the latest edit is recorded** (`editedAt`, `editedBy`, `editCount`); earlier wording is not kept, because the SRS asks to retain history for deletion, not a version history of notes. Notes on archived members are read-only (`409 MEMBER_ARCHIVED`): every note write goes through the same member-document guard as payments (`touchActiveMember`), so a note write and a concurrent archive conflict instead of slipping past each other (D-92). The activity log records note actions with the field name only, never the text (D-62). The model refuses physical deletes. | SRS §8, C-19, D-40, D-21; X-21 stays deferred: notes are never hard-deleted. |
| D-113 | **Trainer dashboard (D-44) definitions.** `GET /dashboard/trainer` (Trainer only) returns: member counts (Active, Inactive, Archived, the same as the Members tabs); **payment-status counts only** (Paid, Partially paid, Pending, Unpaid, plus how many have a payment awaiting verification) for the payment summaries of **current and next** memberships (Active, Upcoming, Pending Activation) of members who are not archived, i.e. the ones staff still act on; the **5 newest non-deleted notes** from all trainers, with the member; and the signed-in user's **10 latest activity-log entries**, shown with translated action names and the non-personal target label. No amounts, no upcoming expiries (C-20), no inquiries, accounts, settings or reports. "Notifications I sent" is added in Phase 7. The Admin dashboard is unchanged until Phase 8 and has no trainer widgets. | SRS §9.2 ("limited member-level payment status information only"), D-44.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| D-114 | **Navigation.** "Exercises" (`/app/exercises`) is in the navigation for both roles. In the phone bottom bar it replaces nothing for Admins (who keep Dashboard, Members, Inquiries, Plans; Exercises is under More) and is shown for Trainers (Dashboard, Members, Exercises, Profile). Nav items can now name the role whose bottom bar they belong to (`bottom: 'trainer'`). Workout notes live on the member profile.                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Trainers use exercises daily; Admins' existing bar is kept.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| D-115 | **Phase 6 integration changes to earlier code (minimal).** (1) A Trainer account's deletion dialog and `GET /users/:id/dependencies` also list the workout notes the person wrote and the payments they recorded, as **retained** records; nothing blocks and nothing is deleted (D-13). (2) Member counts were moved out of the members service factory into an exported `memberCounts()` so the dashboard can reuse it; behaviour is unchanged. (3) Cards that tests and screen readers navigate by name (workout notes, recent notes, recent activity) have an accessible name.                                                                                                                                                                                                                                                                                                             | The user asked to re-verify the Trainer lifecycle with Phase 6 data; the dialog should say that notes are kept.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |

### Phase 7 implementation decisions

| ID    | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | Reason                                                                                                       |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| D-116 | **Provider modes.** `WHATSAPP_MODE` is `disabled`, `mock` or `live`. Without a setting it is `mock` in development and tests and `disabled` in staging and production; **`mock` is refused in production**. `live` requires `WHATSAPP_API_VERSION`, `WHATSAPP_PHONE_NUMBER_ID`, `WHATSAPP_BUSINESS_ACCOUNT_ID`, `WHATSAPP_ACCESS_TOKEN`, `WHATSAPP_APP_SECRET` and `WHATSAPP_VERIFY_TOKEN`, or the server refuses to start. The mock provider never sends anything; every message and template approval it produces is marked **Simulated** in the database and on screen, and it never reports delivered or read. For trying failure handling by hand, it fails numbers ending in 0000 permanently and 9999 temporarily. Credentials exist only in server environment variables; the status endpoint returns which are present (true/false), never their values; the logger redacts them.                                                               | SRS §10.1 (Cloud API directly), D-51, Prompt §23; real credentials are pending (P-06).                       |
| D-117 | **Templates.** An in-app template mirrors a Meta template: name and language are fixed after creation (as in Meta); category Utility or Marketing; one **default** template per event type is used for the automatic message (and for receipt sharing). Creating or changing the content submits it to the provider; editing content sets it to _waiting for approval_ until the provider approves it again; turning it on/off or making it the default does not. A template is sendable only if enabled, approved **and approved in the current mode** (a simulated approval never counts once live). Rejection reasons and submission errors are stored and shown. Deletion is safeguarded (D-56); sent messages keep their snapshot; in live mode the Meta template is deleted after the commit, best effort. Trainers see only sendable templates. A daily job (06:00) and webhook updates refresh Meta's review status.                             | SRS §10.1: Admin edits without an internal approval workflow, Meta approval still applies, no false success. |
| D-118 | **Template content.** The body uses Meta's positional placeholders `{{1}}…{{n}}` without gaps, and each position is mapped to a fixed key that is allowed for the event (member name, Member ID, gym name, plan, dates, amount, payment date, paid so far, balance, receipt number, method, days left). Values are resolved on the server from stored data when the message is queued — staff never type message text (C-23). If a value is missing the message is not sent (recorded as blocked, or refused for a manual send). Amounts and dates are written in English like the receipts ("Rs 2,000", "18 Nov 2026").                                                                                                                                                                                                                                                                                                                                 | SRS §10.1: only predefined, template-based messages.                                                         |
| D-119 | **Recipient checks** before queueing and again before sending: not archived, WhatsApp consent given, not opted out, and the phone is a **mobile** number (libphonenumber type MOBILE or FIXED_LINE_OR_MOBILE). Otherwise nothing is sent. Automatic messages are still recorded as **Not sent** with the reason, so the history is complete; manual sends are refused with an error and nothing is recorded.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | SRS §10.3, C-25; WhatsApp cannot reach landlines.                                                            |
| D-120 | **Dispatcher and retries.** Every minute, under the lease lock, due messages are claimed one by one with a single atomic update, so two dispatchers (or the job and an immediate manual send) can never send the same message. A temporary error (network, timeout after 10 s, HTTP 429/5xx, Meta codes 1, 2, 4, 17, 341, 80007, 130429, 131000, 131016, 131048, 133004) is retried after 15 minutes, **at most 3 times (4 attempts)**; then the message is **Failed** with _needs follow-up_. Any other error is permanent: Failed at once, no retry. A message left in _sending_ for more than 10 minutes (crashed process) may or may not have reached WhatsApp, so it is **never re-sent automatically**: it is marked Failed (_outcome unknown_) for staff to check. A failure reported later by the webhook marks the message Failed with a follow-up, without an automatic retry. An Admin records the follow-up with a note.                     | SRS §10.4, C-26, D-47; no duplicate messages (Prompt §14.4).                                                 |
| D-121 | **Automatic events.** _New membership confirmation_: when a membership is activated (Active, or Upcoming for an early renewal), queued in the activation transaction. _Payment received_: when a payment becomes verified and its receipt is issued (recorded verified, or a pending payment verified) — not for corrections or the Phase 4 receipt backfill. _Expiry reminder_: daily at 00:10 for Active memberships ending in exactly `expiryReminderDaysBefore` days (Admin setting, 1–30, on the WhatsApp configuration card), sent at 10:00; skipped when the renewal is already activated. _Membership expired_: when a membership expires and the member becomes Inactive (no renewal took over), sent at 10:00. Scheduled notices are checked again when due: an expired notice is not sent if the member is Active again by then, and a reminder is not sent once the renewal is activated (`superseded`).                                     | SRS §10.2, C-24, D-48; avoids telling a renewed member their membership ended.                               |
| D-122 | **Manual sends and receipt sharing.** Admin and Trainer send only templates of the _manual_ kind, after a server preview that lists any reason it cannot be sent. Each send carries a `requestId` from the screen; repeats with the same ID (double tap, retry after a network error) return the same message. A manual send is attempted at once and the screen shows the real result: _Sent to WhatsApp_ (accepted; delivery shown only when reported), _Simulated_, _Will retry_ or _Failed_. A simulated result never looks like success. Receipt sharing uses the default receipt template and attaches the receipt PDF (uploaded as media); void receipts cannot be shared. If no approved receipt template exists, the screen explains it and offers the manual route: download the PDF, share it yourself, record it (_Shared by staff_, never shown as sent or delivered). Opt-out and missing consent block WhatsApp and manual sharing alike. | SRS §7.4, §10.3, D-49.                                                                                       |
| D-123 | **History visibility and retention.** Admins see every message; Trainers only messages they sent (automatic messages are Admin-only); a Trainer asking for another message gets 404. The provider message ID is shown to Admins only. Webhook statuses are stored once each and never move a message backwards (sent → delivered → read). Notification history is **never deleted**: the model refuses physical deletes, and messages remain protected dependencies that block member deletion (D-87, X-21 deferred). The member profile shows the member's messages (Admin: all; Trainer: their own); the Trainer dashboard lists the Trainer's 5 latest.                                                                                                                                                                                                                                                                                               | SRS §10.4, C-26, D-50.                                                                                       |

### Phase 8 — Dashboards, reports and expenses (20 Nov 2026)

| ID    | Decision                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Reason                                                                                                                                                                                                                                                                                                                                                                          |
| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| D-124 | **Expense rules.** Title 2–200 characters; category from the six SRS categories; amount in whole rupees from Rs 1 to Rs 10,000,000 (a typing-error guard); a valid Karachi date that is **not in the future** (backdating allowed); Cash or Online; "created by" from the session. Edits send `expectedVersion` and a stale edit gets 409 `VERSION_CONFLICT` (atomic compare-and-set). Creation, every edit (field, old value, new value) and deletion are written to the Activity Log; `GET /expenses/:id` returns that history. Deletion is the standard safeguarded delete (password, reason, confirmation, minimal deletion audit); nothing depends on an expense. Still Admin-only (D-41).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | SRS §9.5 (required fields, PKR whole rupees, Asia/Karachi date, minimal feature) and C-33. An expense describes money already spent, as payments block future dates (C-15). Expense text is business data, not personal data, so values are logged (D-62).                                                                                                                      |
| D-125 | **Admin dashboard figures** (`GET /dashboard/admin`), all from the server clock in Asia/Karachi: _Total_ = Active + Inactive non-archived members; _Active_/_Inactive_ = membership state; _Expired_ = non-archived Inactive members with at least one expired membership (members who never had one are Inactive but not Expired); _Archived_ shown only as a separate count. _Today's collections_ and _Income this month_ (1st of the month to today) follow D-38, split Cash/Online, with a daily series for the chart. _Outstanding_ follows D-38 and also gives the number of memberships with a balance. _Trainers_: every account not deleted, with status and last sign-in, and the active count. _Today_: members registered today (not archived; latest 5) and inquiries received today, plus inquiries still marked New. _Upcoming expiries_: 7 days, first 5. _Recent payment corrections_: the latest 5 with changes, reason and actor. _Payment status_: the same counts as the Trainer dashboard. The dashboard and the reports use one shared module (`reports/finance.js`), so their totals always agree.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | SRS §9.1, §9.3, C-20, D-38. "Expired" in §9.3 is "inactive due to membership expiry".                                                                                                                                                                                                                                                                                           |
| D-126 | **Archived members in reports.** Member reports take `archive = exclude` (default) `\| include \| only`. In the income report, payments of archived members still count in the totals (the money was received) but are **not listed by name** unless the Admin ticks _List archived members_; otherwise they appear as one unnamed line ("n payments, Rs x, from archived members"). The dashboard's outstanding total leaves archived members out (D-38).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | SRS §5.2 and §9.4 (archived members appear only on request) without making income totals wrong.                                                                                                                                                                                                                                                                                 |
| D-127 | **Report ranges and size.** Ranges are inclusive Karachi dates, `from ≤ to`, at most **731 days** (two years, so any calendar year and the year before fit). A PDF lists at most **5,000 records**; beyond that the request is refused with 422 `REPORT_TOO_LARGE` rather than silently truncated. On-screen previews show totals plus the first 50 rows. Unknown filters are refused (400).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Keeps generation on the single Render instance fast and bounded; a truncated financial report would be misleading.                                                                                                                                                                                                                                                              |
| D-128 | **What the exports contain.** _Member list_ PDF: Member ID, name, phone, state, registration date, current plan and end date (no address). _Full personal-data export_: Member ID, name, phone, age, gender, address, registration date, state and WhatsApp consent state. Admin notes and photos are not exported. The full export needs the Admin's password again (wrong password → 422 `INVALID_PASSWORD`, nothing exported) and is logged as `member.export.full` with the filter and the row count only. Every PDF download is logged as `report.download` with its filters; on-screen previews are not logged.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | SRS §9.4 (export PDF only, password, Activity Log). Logs never copy personal data (D-62). Internal notes stay inside the app.                                                                                                                                                                                                                                                   |
| D-129 | **Report PDFs** are A4 (landscape for tables), English (C-03), generated on demand (D-42) with pdfmake (D-43). Every report shows the gym, the title, the period, the filters, "Generated <date, time> (Asia/Karachi) by <user>", and a footer with the same stamp and "Page x of y" on every page. Income and expenses are always separate sections; **no figure subtracts one from the other** (C-21). Sent as `attachment` with `Cache-Control: no-store`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | SRS §9.4 and Appendix B (historical exports clearly dated).                                                                                                                                                                                                                                                                                                                     |
| D-130 | **Dashboard chart.** One stacked bar chart, daily income this month (Cash and Online), with a legend, the selected day's values as text, and a table view, so colour is never the only cue. The two series colours are new tokens (`--gms-chart-cash`, `--gms-chart-online`) chosen separately for light and dark and checked for colour-blind separation and 3:1 contrast. No chart library was added. Member registration now uses the injected business clock (the system clock in production) like every other business date.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | Accessibility (C-02) and a small bundle. The clock change only affects tests that set the day.                                                                                                                                                                                                                                                                                  |
| D-131 | **X-21 resolved: protected history is never deleted, so member deletion stays dependency-blocked.** SRS §12.2 is applied as written: a member can be permanently deleted only when no linked record remains; memberships, payment summaries, entries and receipts can be deleted separately first, but **consent history, WhatsApp message history, workout notes (including soft-deleted ones) and payment-correction logs have no deletion path** and keep blocking. Because every member has consent history from registration, **in practice members are archived, not deleted.** Archive is the SRS mechanism for retiring a member: the record leaves the active lists and reports, every history stays intact and attributable, and it can be restored. **Not implemented** (each would weaken an approved rule): deleting or cascading protected history with the member, anonymising the member record (receipts and logs keep their frozen snapshots), detaching history from the member, or soft-deleting members. The dependency check now returns `protectedHistory: true` and `alternative: "archive"`, and the dialog says so. All protected collections (consent history, notifications, workout notes, payment-correction logs, activity log, login history, deletion audits) now **refuse every Mongoose delete** (`undeletable` plugin); the activity log and login history still expire through their 2-year TTL index (C-32). **Implication:** a member's personal data is kept until the gym decides otherwise; if a legal erasure request ever has to be honoured, that needs a change request to the SRS (for example an approved anonymisation procedure), decided by the user.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | SRS §5.2, §11.7, §12.1–12.4, C-19, C-25, C-33. The user asked for the safest practical solution consistent with the approved SRS, with no destructive workaround and no deletion of protected history (Phase 9 prompt §2). Every alternative either deletes protected history, rewrites frozen financial snapshots, or silently detaches records, which §12.2 and §12.4 forbid. |
| D-132 | **Backups as built** (implements D-61): EJSON documents in a gzip of newline-delimited JSON (instead of the planned tar, simpler and streamable), AES-256-GCM with the header authenticated, file `gms_<Karachi date>_<time>.gmsbak`; storage `s3` (any S3-compatible bucket, `@aws-sdk/client-s3`) or `filesystem` (development and tests only, refused in staging/production because Render's disk does not survive deploys); Sundays 03:00 Karachi under the job lock; the newest 8 successful backups kept, pruning only after a success and only of files the service recorded; files never overwritten. **Restore only into an empty database** (the planned `--drop-existing` option was dropped): a restore can never delete or overwrite data, and a production rollback goes into a new database. Restore checks the key and file integrity (GCM), an optional SHA-256, a typed confirmation equal to the target database name, recreates the indexes, checks counts and records a `restore` run. No HTTP route for restore. Excluded from backups: sessions, reset tokens, job locks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | SRS §14.2, §19, C-35, D-61. Safety over convenience: the operator cannot destroy current data by mistyping a URI.                                                                                                                                                                                                                                                               |
| D-133 | **Settings → Audit viewers.** `GET /audit/activity` (filters: actor, action prefix, record type, Karachi date range; 20 per page, newest first), `GET /audit/activity/filters` (actions, record types and actors that occur), `GET /audit/logins` (account, result, dates) and `GET /settings/security` (the approved security and retention rules, read-only), all Admin-only. Login history shows the identifier as typed only when it matched an account; otherwise only its first three characters (it may be a mistyped password), plus a short device summary (browser · OS). IP hashes and raw user agents are not returned. **Retention is shown, not configurable:** 2 years for activity and login history and permanent for financial and protected history are approved defaults (C-32); an authorised deletion stays possible through the existing safeguarded routes only.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | SRS §3.1 ("View all login history"), §11.7, §16 "Settings/Audit". A retention editor would be an unapproved feature and could shorten the payment-history rule.                                                                                                                                                                                                                 |
| D-134 | **Hardening from the Phase 9 review.** (1) Every API response is `Cache-Control: no-store` by default (personal and financial data on shared front-desk devices); the public site keeps its 60-second cache. (2) Protected history refuses Mongoose deletes (D-131). (3) Backup secrets are added to log redaction; backup errors shown to the Admin are shortened and scrubbed. (4) The test-only `pdfjs-dist` was upgraded to 6.x for a high-severity advisory; `npm audit` now reports 0 vulnerabilities (production dependencies had none). (5) Verified, no change needed: Express 5's query parser keeps `a[$op]` as a plain key, so query strings cannot carry database operators; every route declares access and all 13 deletion routes are Admin-only except the workout-note soft delete (pinned by a test); there is no route that deletes consent, notification, audit or correction records; generic 500 responses without internals; deactivation, force logout, password reset and account deletion take effect on the next request. **Noted, not changed:** the signed WhatsApp webhook is not behind the per-IP limit (Meta sends bursts; the HMAC check is cheap); CSP for the app is set by `client/vercel.json`, the API serves JSON and PDFs only.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | SRS §11.3, §14.2, Phase 9 prompt §4–5.                                                                                                                                                                                                                                                                                                                                          |
| D-135 | **Settings screen structure.** `/app/settings` (Admin): _Overview_ (links to where gym details and reminder days are already edited, the deletion rules including D-131, and the read-only security and retention rules), _Activity Log_, _Login history_, _Backups_. Gym identity, contact, hours, logo and language stay on **Website → Gym** and the expiry-reminder days on **WhatsApp → Templates** (Phases 2 and 7), so nothing is edited in two places. The Admin dashboard shows the backup warning. Trainers have no Settings entry and `/app/settings` sends them to the dashboard.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | SRS §16 "Settings/Audit", §3.1. No new settings were introduced.                                                                                                                                                                                                                                                                                                                |
| D-136 | **Restore failure recovery (Phase 9 Revision 1).** (1) **Validate before writing:** checksum, decryption, the manifest (format, app, time, collection names, counts adding up, index definitions, no excluded collection), every line and document (an object with an `_id`, no duplicate `_id`, only listed collections, counts) and the typed confirmation; `restore.js --check` does all of this and reports the target's state without writing. (2) **Marker first:** a fresh restore into an empty database first writes `restoreState/restore` (`in_progress`, file name, SHA-256, `restoreId`, lease, attempts, completed collections). Any failure after that sets it to `failed` (a crash leaves `in_progress`; its 10-minute lease expires) and reports `PARTIAL_RESTORE` with both recovery routes. (3) **Recover by resuming, never by deleting:** `--resume` with the **same** backup file (SHA-256 must match the marker) claims the marker (one run at a time), then checks that **every** document already in the target equals the backup exactly (number types included) and that no other collection or record exists; anything else is refused (`RESUME_FOREIGN_DATA`, `RESUME_MISMATCH`) and nothing is written. It then inserts only the missing documents, recreates indexes, checks counts, records one `restore` BackupRun (upserted by `restoreId`) and marks the marker `complete`. The other route is always available: restore into a new, empty database. (4) A database without a marker that holds data is never written to; an empty one cannot be "resumed". (5) **Partial databases are identifiable and refused:** the server and every operator script (backup, sync-indexes, setup token, receipt backfill) stop with a clear message before writing anything (`connectDatabase({ guard })`; Mongoose `autoCreate` is off so not even empty collections are created first). (6) `restoreState` is never backed up and is refused inside a backup. (7) Restores now recreate empty collections too, and backups read documents without number promotion, so a double such as `5.0` no longer comes back as the integer `5` (found by the new tests; money is stored as whole rupees, so amounts were not affected). Nothing deletes, drops or overwrites data; cleaning up an abandoned partial database stays a deliberate manual step by the operator. | Phase 9 Revision 1 request; SRS §19 (restore protected, confirmed and logged), C-35, D-131, D-132.                                                                                                                                                                                                                                                                              |
| D-137 | **Phase 10 QA fixes (no rule or feature changed).** (1) **Colour contrast (WCAG AA):** light theme `--gms-success` #24834b → #227c47, `--gms-warning` #c58a24 → #91661a (was 2.7:1 on its pale background), `--gms-danger` #c74747 → #b94242; dark theme `--gms-primary` #6b91f0 → #789bf1. Every status badge, avatar and coloured text now has at least 4.5:1, and dark text on blue buttons 6.9:1. Same hues, so the design system is unchanged in character. (2) **CSP:** Zod 4's `new Function` probe is switched off (`z.config({ jitless: true })` in `client/src/lib/zodConfig.js`), so the strict `script-src 'self'` policy reports no violations; validation results are the same. (3) **Deployment:** the server has no build step (it runs from source); Render installs with `npm ci --omit=dev -w server --include-workspace-root=false`; `TRUST_PROXY` is expected to be `2` behind Vercel + Render and must be verified on staging. (4) `npm run backup`/`restore` read `server/.env` like the other operator scripts. (5) Test-only: `@axe-core/playwright` (dev dependency) for the accessibility checks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | Phase 10 audit findings; SRS §13 (accessibility), §11.3 (secure headers), §19.                                                                                                                                                                                                                                                                                                  |

---

## P — Pending external dependencies

| ID   | Dependency                                                                                                                           | Needed by                                                                 | Status                                                    |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------- | --------------------------------------------------------- |
| P-01 | GitHub repository for code checkpoints                                                                                               | Phase 1 (strongly recommended)                                            | **Pending — user**                                        |
| P-02 | Render account, and approval of paid always-on instances for staging and production                                                  | Before staging                                                            | **Pending — user**                                        |
| P-03 | Vercel account and projects (staging and production)                                                                                 | Before staging                                                            | **Pending — user**                                        |
| P-04 | MongoDB Atlas account, clusters for dev, staging and prod, and the production tier choice                                            | Dev cluster for Phase 1 integration testing; others before staging        | **Pending — user**                                        |
| P-05 | Cloudinary account (upload preset, API key and secret)                                                                               | Phase 2 (gallery) and Phase 3 (member photos)                             | **Pending — user**                                        |
| P-06 | Meta Business verification, WhatsApp Business Account, sender phone number, system-user access token, app secret, template approvals | Phase 7 real testing (the code can be built against the mock before then) | **Pending — deferred by SRS until Meta onboarding**       |
| P-07 | Email provider (SMTP) and a verified sender domain or address for Admin password reset                                               | Before staging (development prints emails to the console)                 | **Pending — user**                                        |
| P-08 | S3-compatible backup storage account (for example Cloudflare R2 or Backblaze B2) and safe custody of the backup encryption key       | Phase 9                                                                   | **Pending — user**                                        |
| P-09 | Custom domain                                                                                                                        | After development                                                         | **Deferred by SRS**                                       |
| P-10 | A native Urdu speaker to review the translations                                                                                     | Before UAT                                                                | **Pending — client**                                      |
| P-11 | Real gym content: name, logo, address, hours, plans and prices, trainer bios and photos, gallery images, About text                  | Before staging content entry (Admin enters it through the app)            | **Pending — client**                                      |
| P-12 | Confirmation of current pricing and free-tier limits for Render, Vercel, Atlas and Cloudinary                                        | Before staging                                                            | **Pending — checked at deployment time (SRS Appendix B)** |
