# Changelog

All notable changes to this project are recorded here, newest first.

## [Phase 10 — Final QA, deployment readiness & handover] 20 Nov 2026

### Audited

- The whole project against SRS v2.0 and the decision register; all 26 acceptance scenarios (AC-01 – AC-26) re-run through the automated suites; a static scan (no TODOs, no stray console output, every server file parses, every dependency used); a production-mode start with only production dependencies; a final security audit (`docs/SECURITY.md` §17).

### Fixed

- **Accessibility (WCAG AA colour contrast):** status badges and coloured text were below 4.5:1 (amber 2.7:1). Light `success`, `warning`, `danger` and dark `primary` tokens darkened/lightened within the same hues (D-137). Found by the new axe-core checks.
- **Production CSP:** Zod 4's `new Function` probe caused a Content-Security-Policy violation on every page with a form under `vercel.json`'s policy; switched off with `z.config({ jitless: true })` (`client/src/lib/zodConfig.js`). Found by the new CSP check.
- **Deployment docs:** the Render build command referred to a non-existent server build; the index-creation note was wrong; `TRUST_PROXY` guidance for the Vercel + Render proxy chain added. `npm run backup`/`restore` now read `server/.env` like the other scripts. `.mongo-data/` git-ignored.
- **Test robustness:** a Phase 6 browser test could see two "Note added" toasts at once.

### Added

- `docs/ADMIN_GUIDE.md`, `docs/TRAINER_GUIDE.md`; `docs/DEPLOYMENT.md` rewritten as a step-by-step guide with the full production environment-variable table and troubleshooting; `docs/SETUP.md` tests and troubleshooting sections; README rewritten.
- `client/tests/e2e/10-final-qa.spec.js` (5): a cross-phase journey (public inquiry → conversion → partial cash payment and activation → Trainer's pending online payment, verification, receipt, note → Admin correction with void and reissue → dashboard, report and Activity Log agree → archive blocked, inquiry deleted, member intact), the production CSP on the built app, and axe-core WCAG 2 A/AA scans (13 screens × 2 themes, 4 Urdu screens). Dev dependency `@axe-core/playwright`.

### Not changed

- No SRS requirement, business rule, permission or feature. Nothing deployed: no hosting or external account exists yet.

## [Phase 9 — Revision 1] 20 Nov 2026 — restore failure recovery

### Fixed

- A restore that failed after writing left an unmarked, partly filled database that every later attempt refused as "not empty". Now (D-136):
  - `format.js` validates the whole backup before any write: manifest (format, app, time, collection names, counts and total, index definitions, no excluded collection) and every document (`_id` present, no duplicates, known collection, counts).
  - `restore.js` writes a `restoreState` marker first; a failure marks it `failed` and reports `PARTIAL_RESTORE` with the two recovery routes. `--resume` (same backup file only) checks every existing document against the backup, refuses changed, extra or unknown data, inserts only what is missing, and holds a 10-minute lease so two runs cannot overlap. A database without a marker is never written to.
  - The server and the operator scripts (`backup`, `sync-indexes`, `setup-token`, `backfill-receipts`) refuse a partially restored database before writing (`connectDatabase({ guard })`, Mongoose `autoCreate` off).
  - `scripts/restore.js`: `--check` (validate and report the target's state, no writes), `--resume`, error codes in messages, progress output.
- Found by the new tests: backups read documents with number promotion, so a double such as `5.0` came back as the integer `5`; they now keep every number type. Restores now also recreate empty collections. (Money is stored as whole rupees, so amounts were not affected.)
- `restoreState` is excluded from backups and refused inside one. Restore records carry `restoreId` (one record per restore, also after resuming).

### Tests

- Server +25 (339): `unit/phase9-restore.test.js` (16: validation of manifests, documents and files before writing) and `integration/phase9-restore.test.js` (9: failure part-way, several failures, failure inside a collection, resume to an exact copy, start-up refusal of the server and a script, refusal to resume over changed/extra/unknown data or with another file, lease after a crash, simultaneous restores, wrong confirmation, non-empty targets, empty-target resume, a successful one-go restore, `--check` and the CLI). The E2E restore drill also runs `--check`.

### Not changed

- Restore stays operator-only with typed confirmation; no route, screen, SRS requirement or Phase 1–8 behaviour changed. Phase 10 not started.

## [Phase 9 — Settings & operational security] 20 Nov 2026

### Decided

- **X-21 resolved by D-131** within the approved SRS: member deletion stays blocked while protected history exists; archive instead. Nothing is deleted, anonymised or detached. The SRS is unchanged.

### Added — server

- `modules/backups/`: `backupRun.model.js`, `format.js` (EJSON + gzip + AES-256-GCM with an authenticated header), `storage.js` (S3-compatible via `@aws-sdk/client-s3`, or a local folder for development and tests; never overwrites), `backup.service.js` (run, keep the newest 8, prune only after success, status and health), `restore.js` (empty target only, typed confirmation, checksum, index rebuild, count check, restore record).
- `scripts/backup.js` (`npm run backup -w server`) and `scripts/restore.js` (`npm run restore -w server`, operator only). Weekly scheduler job `backup` (Sundays 03:00 Karachi).
- `modules/audit/auditViewer.service.js` and `audit.routes.js`: `GET /audit/activity`, `/audit/activity/filters`, `/audit/logins`, `/settings/security`, `/backups` (all Admin-only, read-only). `GET /dashboard/admin` adds `backup`.
- `utils/mongoosePlugins.js` `undeletable`: consent history, payment-correction logs, activity log, login history and deletion audits now refuse Mongoose deletes, like notifications and workout notes already did.
- Member dependencies return `protectedHistory` and `alternative: "archive"`.
- `config/env.js`: `BACKUP_*` settings (key must be 32 bytes; S3 needs region, bucket and keys; local folder refused in staging/production). Log redaction for backup secrets.
- `app.js`: `Cache-Control: no-store` on every API response (the public site keeps its 60 s cache).
- Tests: `integration/phase9.test.js` (19), `unit/phase9.test.js` (9, including the S3 adapter against a local fake S3 server). Server total 314.

### Added — client

- `features/settings/SettingsPage.jsx` (`/app/settings`, Admin): Overview, Activity Log, Login history, Backups; `BackupWarning.jsx` (also on the Admin dashboard). "Settings" in the Admin navigation. The blocked member-deletion dialog explains protected history and archiving. 132 English/Urdu strings; parity passes.
- Tests: `unit/phase9.test.jsx` (9), `e2e/08-phase9-flow.spec.js` (5, with the real backup and restore scripts); visual suite +4 screens, +3 Urdu screens. The browser suite backs up to a temporary folder with a test-only key (`tests/e2e/backup-env.js`).

### Changed

- Dev dependency `pdfjs-dist` 5 → 6 (high-severity advisory; test-only) and `tests/helpers/pdfText.js` for its API. `npm audit`: 0 vulnerabilities.
- `server/.env.example`: `BACKUP_*` placeholder names. Docs: `BACKUP_RESTORE.md` rewritten as built; SETUP, DEPLOYMENT, API §17, DATABASE §1/§2.29/§6/§7, SECURITY, ARCHITECTURE.

### Fixed

- `docs/TESTING.md`: the Phase 8 Playwright total row had been placed in the Phase 5 table; moved to §18.

### Decisions

- D-131 to D-135 added. No new settings or features beyond the SRS; no Phase 10 work.

### Not verified

- A real backup bucket (P-08): only a local folder and a local fake S3 server were used. Real WhatsApp (P-06) still untested.

## [Phase 8 — Dashboards, reports & expenses] 20 Nov 2026

### Added — server

- `modules/expenses/`: `expense.model.js` (title, category, amount, date, method, created/updated by, `version`), `expenses.validators.js`, `expenses.service.js`, `expenses.routes.js`. `GET/POST /expenses`, `GET/PATCH /expenses/:id`, `/expenses/:id/dependencies`, safeguarded `/expenses/:id/delete-permanently`. Admin only (D-41, D-124).
- `modules/reports/`: `finance.js` (shared income/expense/outstanding figures for the dashboard and the reports), `reports.validators.js`, `reports.pdf.js` (dated, stamped A4 report PDFs), `reports.service.js`, `reports.routes.js`. `/reports/income|expenses|summary|members` (JSON preview and `.pdf`) and `POST /reports/members/full-export` (password) (C-21, D-126 – D-129).
- `GET /dashboard/admin` in `modules/dashboard/` (D-125).
- New error codes `FUTURE_EXPENSE_DATE`, `REPORT_TOO_LARGE`.
- Tests: `integration/phase8.test.js` (18), `unit/phase8.test.js` (8); `tests/helpers/pdfText.js` reads the text of generated PDFs (dev dependency `pdfjs-dist`). Server total 286.

### Added — client

- `features/dashboard/AdminDashboard.jsx` (money, members, daily income chart, Today, expiries, payment status, Trainers, corrections); `features/expenses/ExpensesPage.jsx` (`/app/expenses`); `features/reports/ReportsPage.jsx` (`/app/reports`). "Expenses" and "Reports" in the Admin navigation. Chart colour tokens for light and dark. About 150 English/Urdu strings; parity passes.
- Tests: `unit/phase8.test.jsx` (12), `e2e/08-phase8-flow.spec.js` (5, with real PDF downloads); visual suite +5 screens, +4 dialogs/menus at 360 px, +4 Urdu screens.

### Changed

- The Admin dashboard replaces the interim Admin view (new inquiries, expiries, member and staff counts). The Trainer dashboard is unchanged; `PaymentStatusSummary` is now shared.
- Member registration takes its date from the injected business clock (the system clock in production) (D-130).
- E2E: the Phase 2 check for the "New inquiries" card now checks the new "Today" card; the Phase 6 check that the Admin dashboard has no "Payment status" block now checks that the Admin gets the Admin dashboard and not the Trainer's sections.

### Decisions

- D-124 to D-130 added. No net-profit figure anywhere; no Excel/CSV exports. X-21 still deferred. The approved SRS is unchanged. No Phase 9 work.

## [Phase 7 — WhatsApp] 18 Nov 2026

### Added — server

- `modules/whatsapp/`: `template.model.js` (NotificationTemplate, one default per event), `notification.model.js` (Notification outbox; unique idempotency key; physical deletes refused), `variables.js` (placeholder mapping and server-side values), `outbox.js` (queueing with consent, opt-out, archive, mobile-number and template checks), `dispatcher.js` (atomic claim, 3 retries 15 minutes apart, stuck-send recovery, re-check before sending, superseded notices), `events.js` (the four automatic events and the daily expiry reminders), `templates.service.js`, `notifications.service.js` (history, follow-up, preview, manual send, receipt sharing, manual share), `webhook.js` (signature, idempotent statuses, template review updates), `whatsapp.routes.js`.
- `providers/`: `cloudApi.js` (Meta WhatsApp Cloud API: template messages, PDF media upload, template submit/edit/status/delete; 10 s timeout), `mock.js` (simulated provider and the disabled provider), `errors.js` (temporary vs permanent), `index.js` (mode selection, configuration summary without secrets).
- Endpoints (docs/API.md §13, §11): `/whatsapp/status`, `/whatsapp/templates` (CRUD, sync, dependencies, safeguarded delete), `/whatsapp/preview`, `/whatsapp/send`, `/notifications` (list, detail, follow-up), `/receipts/:id/share/whatsapp`, `/receipts/:id/share/manual`, `/webhooks/whatsapp` (GET verify, POST signed).
- Automatic events hooked into activation (`memberships.service.js`), payment verification (`ledger.js`, `payments.service.js`) and the lifecycle (`lifecycle.js`), each in the same transaction as its cause.
- Scheduler: `notificationDispatcher` (every minute), `expiryReminders` (00:10), `templateStatusSync` (06:00, live only).
- `config/env.js`: `WHATSAPP_*` settings (live requires all credentials; mock refused in production); logger redaction for tokens and recipient phones. `GET /dashboard/trainer` adds `myRecentNotifications`.
- Tests: `integration/whatsapp.test.js` (29, fake provider), `unit/whatsapp.test.js` (16, including the live adapter against a local fake Graph server). Server total 260.

### Added — client

- `features/whatsapp/`: `WhatsAppPage` (`/app/whatsapp`, tabs Messages and Templates), `MessagesTab` (filters, details, timeline, Admin follow-up), `TemplatesTab` (review status, Admin editor with placeholder mapping, configuration card with the expiry-reminder days, safeguarded delete), `SendMessageDialog`, `ShareReceiptDialog`, `shared.jsx`.
- Member profile: **Send WhatsApp message** (consenting members) and the member's messages. Payment page: **Share REC-…** in the entry menu. Trainer dashboard: **Messages you sent**. "WhatsApp" in the navigation. About 230 English/Urdu strings; parity passes.
- Tests: `unit/phase7.test.jsx` (10), `e2e/08-phase7-flow.spec.js` (5, simulated provider); visual suite +4 screens, 4 dialogs at 360 px, +2 Urdu screens.

### Changed

- Phase 6 dashboard test: the Trainer dashboard now also returns `myRecentNotifications`.
- `.env.example`: `WHATSAPP_*` placeholder names. `playwright.config.js`: the E2E server runs in mock mode with test-only webhook secrets.

### Decisions

- D-116 to D-123 added. X-21 still deferred; notification and consent history are never deleted. The approved SRS is unchanged. No Phase 8 work.

### Not verified

- Real WhatsApp delivery, real Meta template approval and real webhooks (P-06). Only the fake provider, the simulated mode and a local fake Graph server were used.

## [Phase 6 — Trainer experience] 18 Nov 2026

### Added — server

- `modules/exercises/`: `exercise.model.js` (name, description, instructions, created/updated by; unique `nameKey` ignoring letter case and extra spaces), `exercises.validators.js`, `exercises.service.js`, `exercises.routes.js`. `GET/POST /exercises`, `GET/PATCH /exercises/:id`; no delete (D-39, D-111).
- `modules/notes/`: `workoutNote.model.js` (author snapshot, edit and soft-delete metadata, `version`; physical deletes refused), `notes.validators.js`, `notes.service.js` (ownership, Admin override, deleted-note visibility, archived read-only, optimistic concurrency), `notes.routes.js`. `GET/POST /members/:memberId/workout-notes`, `PATCH /workout-notes/:id`, `POST /workout-notes/:id/delete` (D-112).
- `modules/dashboard/`: `GET /dashboard/trainer` (member counts, payment-status counts only, 5 recent notes, own 10 latest activities; D-113).
- Tests: `integration/phase6.test.js` (12), `unit/phase6.test.js` (6). Server total 215.

### Added — client

- `features/exercises/ExercisesPage.jsx` (`/app/exercises`, both roles): search, cards, add/edit dialog, duplicate name shown on the field.
- `features/notes/WorkoutNotesCard.jsx` on the member profile: add, edit, soft-delete as the server allows; Admin filter Current / Deleted / All; author shown as recorded, with "Former staff" or "Deactivated"; read-only for archived members; only the latest list response is applied.
- `features/dashboard/TrainerDashboard.jsx`: payment status, recent workout notes, your recent activity.
- "Exercises" in the navigation (Trainer phone bottom bar; D-114). `exercisesApi`, `notesApi`, `dashboardApi`. About 120 English/Urdu strings; parity passes.
- Tests: `unit/phase6.test.jsx` (9), `e2e/07-phase6-flow.spec.js` (5); visual suite +2 screens (exercises for Admin and Trainer), note and exercise dialogs at 360 px, +2 Urdu screens.

### Changed (minimal integration, D-115)

- `users.service.js` `userDependencies()` and the staff deletion dialog also list authored workout notes and recorded payments as kept.
- `members.service.js`: `memberCounts()` is now a standalone export (same behaviour).
- `DashboardLayout.jsx`: a nav item's `bottom` can name a role.

### Decisions

- D-111 to D-115 added. X-21 still deferred; notes are never hard-deleted. The approved SRS is unchanged. No Phase 7 (WhatsApp) work.

## [Phase 5 — Revision 1] 18 Nov 2026 — receipt snapshot in the API, Node.js versions

### Fixed

- `payments.service.js` `receiptView()`: the receipt `snapshot` was built by spreading a Mongoose subdocument, so `GET /receipts/:id` and `GET /members/:memberId/receipts` returned Mongoose internals (`$__parent`, `$__`, `_doc`, `$basePath`) instead of the snapshot fields; `$__parent` also carried the whole receipt document. New `snapshotView()` converts with `toObject()` and returns exactly the 14 snapshot fields (D-109). The PDF was not affected (it reads the document directly).
- Receipts for a payment recorded in the same step as activation (create with "Activate now", or Activate with a first payment) were issued before activation and had **empty start and end dates**. They are now issued after activation in the same transaction (`addEntry({ deferReceipt })` + `issueDeferredReceipt`, D-109). Existing receipts are not rewritten (D-37).

### Changed

- Node.js engines: `^22.22.2 || ^24.15.0 || >=26.0.0` in the root, `server` and `client` `package.json` (was `>=22`; the client had none), and `.npmrc` with `engine-strict=true`. `package-lock.json` changed only in these engine fields. Docs: `docs/SETUP.md` §1, `docs/DEPLOYMENT.md` §3.1–3.2, D-110 (D-67 annotated).

### Tests

- Server +5 (197): 4 API tests in `integration/payments.test.js` (every snapshot field from both endpoints for Admin and Trainer; VOID receipt keeps its original snapshot and links to its replacement both ways; receipt dates after activation including an early renewal; a receipt issued before activation keeps empty dates and is not rewritten) and 1 unit test for `snapshotView()` (hydrated and lean). The new snapshot tests failed against the previous code (snapshot had 4 internal keys) and the date tests failed without the date fix.

### Not changed

- No payment rule, permission, Phase 4 Revision 1 behaviour or client screen. X-21 still deferred; the approved SRS is unchanged. Phase 6 not started.

## [Phase 5 — Payments & receipts] 18 Nov 2026

### Added — server

- `modules/payments/ledger.js`: `addEntry` (cash always verified, no future dates, no overpayment), `recomputeSummary` with an optimistic version check, `touchActiveMember`, `issueReceipt`.
- `payments.service.js`, `payments.validators.js`, `payments.routes.js`: record payments, verify and reject pending online payments, correct entries (receipt voided and reissued) and the total due (Admin), Admin ledger, receipts (detail, PDF), dependencies and safeguarded deletion of receipts, entries and summaries (docs/API.md §10–11).
- `receipt.model.js` (REC-0001 numbering, one valid receipt per entry), `correction.model.js` (immutable correction log), `receipt.pdf.js` (pdfmake 0.3.14, A5, VOID watermark), `ensureSequence` on counters.
- Receipt backfill for Phase 4 verified payments: at start-up under `withJobLock('receiptBackfill')` and `npm run backfill-receipts`.
- Memberships now use the shared ledger, so initial payments get receipts.
- Tests: `integration/payments.test.js` (18), +2 receipt unit tests. Server total 192.

### Added — client

- `features/payments/`: `PaymentPage`, `PaymentsLedgerPage`, `PaymentDialogs` (record, reject, correct entry, correct total, delete).
- Routes `/app/payments/:id` and `/app/payments` (Admin); "Payments" in the Admin navigation; payment links from the memberships card. English and Urdu strings.
- Tests: `unit/phase5.test.jsx` (6), `e2e/06-phase5-flow.spec.js` (5); visual suite +3 screens, +2 Urdu, the Correct dialog at 360 px.

### Changed

- The fully pending warning now says "Open Payments to verify (or reject) it".

### Decisions

- D-103 to D-108 added. X-21 still deferred; the approved SRS is unchanged.

## [Phase 4 — Revision 1] 18 Nov 2026 — cash validation, fully pending online payments

### Fixed

- `memberships.validators.js`: cash + `pending` is refused (`400 VALIDATION_ERROR`, path `initialPayment.verificationStatus`). The same rule is enforced in `memberships.service.js` and by a `pre('validate')` hook on `PaymentEntry` (D-102).
- `MembershipsCard.jsx`: when pending online payments cover the whole price and nothing is verified, there is no Activate button and no payment form; a warning explains that the payment must be verified first (`memberships.activate.fullPending`, English and Urdu). The Activate dialog guards the same case.

### Tests

- Server +5 (172), client +2 (32), E2E +1 (23); one Phase 4 test's data changed from cash-pending to online-pending.

### Not changed

- No other rule, API or data model. Phase 5 not started at this checkpoint.

## [Phase 4 — Membership management] 18 Nov 2026

### Added — server

- `utils/businessDate.js`: `addDays`, `nextDay`, `monthlyEndDate` (D-25), `customEndDate`, `membershipEndDate`, `daysBetween`, `systemClock`.
- `modules/memberships/`: `membership.model.js` (plan snapshot, agreed/custom price, statuses, `current`/`next` slot with a partial unique index), `lifecycle.js` (`reconcileMember`, `reconcileIfStale`, `runMembershipLifecycle`), `memberships.service.js`, `memberships.validators.js`, `memberships.routes.js`.
- `modules/payments/`: `payment.models.js` (Payment summary, PaymentEntry) and `payment.logic.js` (`summarize`, `wouldOverpay`). Initial payment only (D-94).
- Endpoints (docs/API.md §9): member memberships list and create, membership detail, activate (with optional first verified payment, D-95), upcoming expiries (Admin), dependencies and safeguarded deletion (Admin).
- `members.lifecycleVersion`; the member profile reconciles the lifecycle on read.
- Scheduler: daily `membershipLifecycle` job at 00:05 Asia/Karachi. The lease lock is now non-re-entrant (D-97).
- `createApp({ clock })` and the test helper `testClock()` so tests can set today's business date.
- Tests: `unit/memberships.test.js` (25), `integration/memberships.test.js` (23). Server total 167.

### Added — client

- `features/memberships/`: `MembershipsCard` (current, next, history, activate, Admin delete), `AddMembershipPage` (plan, Admin custom price, first payment, activate now), `PaymentFields`, `UpcomingExpiriesPage` (+ `ExpiryList`), `shared.jsx`.
- Routes `/app/members/:id/memberships/new` (`memberships.create`) and `/app/expiries` (`memberships.upcomingExpiries`); "Expiries" in the Admin navigation; the Admin dashboard card "Ending in the next 7 days".
- `membershipsApi`; about 110 new English/Urdu strings; dashboard intro texts updated.
- Tests: `unit/phase4.test.jsx` (7), `e2e/05-phase4-flow.spec.js` (6); visual suite +4 screens, the membership deletion dialog at 360 px, +2 Urdu screens.

### Decisions

- D-94 to D-101 added.

### Fixed during Phase 4

- The job lease lock let the same process take it twice; each run now uses its own token (D-97).
- Add membership: the amount now follows a custom price, so a valid form is no longer refused.

### Not changed

- X-21 remains deferred to Phase 9. No Phase 5 functionality (no receipts, no verification of pending payments, no corrections, no payment deletion). The SRS was not changed.

## [Phase 3 — Revision 2] 18 Nov 2026 — 44 px touch targets, test-count reconciliation

### Changed

- `client/tests/e2e/09-visual.spec.js`: the minimum touch target is now **44 px** (`MIN_TARGET`), up from 36 px. Checkboxes and radios are measured by their wrapping label; tabs and menu items are included; overflow and target problems are soft assertions, so every screen is reported in one run.
- `components/ui/Button.jsx`: `size="sm"` buttons are 44 px tall (compact padding only); `IconButton` is always 44 × 44.
- `components/ui/Segmented.jsx`: options are at least 44 × 44.
- Pagination arrows (`components/ui/Segmented.jsx`) and the dialog close button (`components/ui/Dialog.jsx`): 44 × 44. Pagination appears only on lists longer than 20, which the visual suite does not reach, so a client unit test checks it.
- `components/ui/Media.jsx`: `Switch` has a 44 × 44 tappable button around the unchanged visible track.
- `components/navigation/Brand.jsx`: the collapsed logo link is at least 44 px wide.
- `layouts/PublicLayout.jsx` (header section links), `features/dashboard/DashboardPage.jsx` ("Edit profile"), `features/members/MemberProfilePage.jsx` and `features/inquiries/InquiryDetailPage.jsx` ("Call"): 44 px tall.

### Fixed — documentation

- `PROJECT_STATUS.md` and this changelog said Phase 3 added 37 server tests for a total of 118. An actual run counts **119** (38 added). `docs/TESTING.md` §11 lists the counts per file.

### Not changed

- No requirement, decision, API or data model changed. Phase 4 not started.

## [Phase 3 — Member management] 17 Nov 2026

### Added — server

- `modules/members/`: `member.model.js` (GYM-001 IDs from the atomic counter, unique normalised phone, separate archive and membership state), `members.validators.js`, `members.service.js`, `members.controller.js`, `members.routes.js`.
- Endpoints (docs/API.md §8): list with search, state, archived and registration-date filters and sorting; `GET /members/counts`; create (both roles) and inquiry conversion with `fromInquiryId` (Admin, one transaction: member, consent history, inquiry `conversion` and status Approved); profile; edit (Admin notes Admin-only, field names only in the log); archive and restore (both roles, C-38; blocked while a membership is active); photo upload/replace (both roles) and safeguarded removal (Admin); consent history; WhatsApp opt-out and consent (Admin); dependencies and safeguarded deletion, blocked while linked records exist (D-87).
- Inquiries: `matchesExistingMember` is computed live in the Admin list and details (D-91); converted inquiries return `conversion.member`.
- Optional `API_RATE_LIMIT` setting (minimum 600, default unchanged) for the automated browser suite (D-93).
- Tests: `integration/members.test.js` (36) plus unit tests for the Member ID format and the new setting (119 server tests in total; corrected in Revision 2 from 118).

### Added — client

- `features/members/`: `MembersPage` (tabs with counts, search, date range, sort; cards on phones, table from tablet width), `MemberFormPage` (Add member, Add member from an inquiry with prefill, Edit member), `MemberProfilePage` (personal details, Admin notes read-only for Trainers, photo, WhatsApp consent with history, archive/restore, Admin-only photo removal and deletion with the dependency list), `shared.jsx`.
- Members in the navigation (both roles, phone bottom bar) and a member-count card on the dashboard. The inquiry detail page has **Add member** and links to the converted member; the inquiry list shows a "Member" badge for numbers that belong to a member.
- `formatDate` for business dates; `membersApi` and `inquiriesApi.prefill`; dialogs can show their own field errors (`silent` errors).
- About 140 new English/Urdu strings; parity check passes.
- Tests: `unit/phase3.test.jsx` (6), `e2e/04-phase3-flow.spec.js` (6); the visual suite now covers 24 screens (8 new member screens), member dialogs at 360 px and 4 more Urdu screens.

### Decisions

- D-85 to D-93 added. D-79 and D-80 annotated as superseded in part by Phase 3.

### Fixed during Phase 3

- The table name link and the converted-member link were smaller than the 36 px tap target; both are now full-height targets.
- The automated browser suite exceeded the general API rate limit during the longer visual run (D-93).
- An E2E permission check was passing for the wrong reason (the CSRF check answered 403 before the permission check). The checks now send the allowed Origin and assert the `FORBIDDEN` code.

### Not changed

- X-21 remains deferred to Phase 9. Member deletion follows SRS §12.2 exactly; nothing is deleted or detached to get around the block. No Phase 4 functionality was added.

## [Phase 2 — Public website & inquiries] 17 Nov 2026

### Added — server

- Models: SiteContent, PublicTrainer, GalleryAsset, AssetCleanup, MembershipPlan, Inquiry, ConsentHistory, JobLock.
- Modules: `content` (public site, settings, content, trainer cards, gallery), `plans`, `inquiries`, `media` (upload helpers, clean-up queue), `consent`. Also `integrations/cloudinary`, `middleware/upload.js`, `jobs/scheduler.js`, and the utils `businessDate.js`, `phone.js`, `zodShared.js`.
- Endpoints: see docs/API.md §5–7, plus `GET /inquiries/counts` (D-76). Settings responses include `integrations.mediaUploads` (D-75).
- Inquiry rate limit (5 per IP per hour); multipart allowed for upload routes; env `CLOUDINARY_*`, `SCHEDULER_ENABLED`.
- Packages: cloudinary, libphonenumber-js, multer, node-cron.
- Tests: `unit/utils.test.js`, `integration/content.test.js`, `plans.test.js`, `inquiries.test.js` (35 new; 81 total).

### Added — client

- `SiteContext` (`GET /public/site`); Brand uses the gym name and logo from settings (D-74).
- Public: redesigned `PublicLayout` (section links, mobile menu, sticky Join bar, footer with staff login), `HomePage` (hero, plans, trainers, About, gallery, contact), `JoinPage`.
- Admin: `PlansPage`, `WebsitePage` (+ `GymTab`, `ContentTab`, `TrainersTab`, `GalleryTab`), `InquiriesPage`, `InquiryDetailPage`; nav entries and new-inquiry badge; dashboard "New inquiries" card.
- Components: `ImageUpload`, `Switch`, `BilingualFields`; `Badge` gets a `wrap` option. Helpers: `formatPKR`, `formatTime`, `pickLang`, `textProps`, `imageUrl`, `waLink`, `isValidPkPhone`.
- About 200 new English/Urdu strings; parity check passes.
- Tests: `unit/phase2.test.js` (8), `e2e/03-phase2-flow.spec.js` (6); visual suite renamed `09-visual.spec.js` and extended to 16 screens + 10 Urdu screens, now reporting what overflows.

### Decisions

- D-73 to D-84 added; D-68 partly superseded by D-74.

### Fixed during Phase 2

- Zod 4 defaults inside partial update schemas could overwrite unsent fields (plan display order, bilingual text). Defaults are removed from update schemas, with regression tests (D-73).
- Phone links on the contact section were below the tap-target size; contact cards are now fully tappable.
- The Inquiries date filters and the inquiry detail columns overflowed at 360 px; the status control truncated labels (now a select menu).
- English fallback text was rendered right-to-left in Urdu mode (D-82).

### Not changed

- X-21 remains deferred to Phase 9. No Phase 3 functionality was added (conversion is prefill only).

## [Phase 1 — Foundation] 17 Nov 2026

### Added — server

- npm workspaces monorepo (`server`, `client`), ESLint (flat config), Prettier, EditorConfig, `.gitignore`, `server/.env.example`.
- Express 5 app (`src/app.js`, `src/server.js`) with the middleware chain from ARCHITECTURE §4, a standard envelope, an error mapper, and `GET /health`.
- Config: Zod-validated env (`config/env.js`), pino logger with redaction, DB connection with `syncIndexes`, `withTransaction`.
- Models: User, Session, PasswordResetToken, SetupState, LoginHistory, ActivityLog, DeletionAudit, GymSettings, Counter (with append-only plugin and TTL indexes).
- Auth: first-Admin setup (token script + endpoint), login/logout/me, DB-backed sessions (rotation, grace period, 90-day sliding expiry), progressive login delay, IP rate limits, own profile, Admin own-password change, Admin email reset (console transport in development).
- Permission matrix (all keys, C-38 included); `createRouter` access wrapper and route registry (D-72).
- Staff accounts: list, create, edit, deactivate/reactivate, Trainer password reset, force logout, dependencies, safeguarded tombstone delete; last-Admin protection with a race guard (D-66).
- Shared deletion-safeguard service; activity, login and deletion audit writers.
- Tests: 15 unit + 31 API integration (in-memory MongoDB replica set).

### Added — client

- Vite + React 19 + Tailwind 4 with a token-only palette (light/dark), Inter + Noto Nastaliq Urdu, a pre-paint theme/language script.
- i18n (English/Urdu, RTL) with a key-parity checker; Theme, Locale and Auth contexts; Axios API layer with error normalisation.
- UI components, the public/auth/dashboard layouts (sidebar, bottom nav, More sheet), and the screens: home (holding page), login, setup, forgot/reset, dashboard, staff, profile.
- `vercel.json` (same-origin `/api` rewrite, security headers; the Render URL placeholder must be set at deployment).
- Tests: 8 unit (Vitest/jsdom), Playwright E2E flow (4) and visual/responsive suite (14; 106 screenshots).

### Changed — docs

- `docs/API.md`, `SECURITY.md`, `DATABASE.md`, `ARCHITECTURE.md`: implemented parts marked; API rate-limit wording (per IP).
- `docs/DECISIONS.md`: D-05 updated (common-password list of about 49k); D-65 to D-72 added.
- `docs/SETUP.md` (working instructions), `docs/TESTING.md` (commands + Phase 1 report), `PROJECT_STATUS.md`, `HANDOVER.md`, `NEXT_STEPS.md`.

### Fixed during Phase 1

- Route paths were not prefixed with the module base path (found by the tests, fixed in `http/router.js`).
- The dialog re-focused its first field on every render (onClose kept in a ref).
- Design review: removed the duplicated page title in the mobile top bar, compact stat tiles on phones, `@username` kept left-to-right in Urdu, a select chevron, the profile grid no longer stretches, disabled primary buttons are clearly neutral.

## [Phase 0 — revision 4] 17 Nov 2026 — SRS Appendix A alignment

### Changed

- `docs/SRS.md` Appendix A, **Member** row: "archive blocked with active membership; Admin restore" now reads "**Admin/Trainer archive and restore; archiving blocked while an active membership exists**". It matches SRS §3.1, §5.2 and C-38. A dated amendment note was added under the status note. No other SRS text changed.
- `docs/DECISIONS.md`, `docs/PHASE0_REVIEW.md`, `PROJECT_STATUS.md`, `HANDOVER.md`: notes that the SRS was aligned.

### Verified

- A search of all documentation found no other statement that only Admin can restore members. The remaining mentions of "Admin restore" are historical quotes, in X-16 and R-02, of the wording that has now been corrected.

### Not changed

- X-16 stays resolved and X-21 stays deferred to Phase 9. No other requirement or decision changed. No application code. Phase 1 not started.

## [Phase 0 — revision 3] 17 Nov 2026 — User decisions applied

### Decisions (by the user)

- **X-16 resolved.** Trainers can both archive and restore members, following SRS §3.1 and §5.2. Archiving stays blocked while a membership is active. Added as **C-38**.
- **X-21 deferred** to the Phase 9 review. The workaround suggested in revision 2 (deleting consent history, notification history and soft-deleted notes together with a member) is **withdrawn and will not be implemented**. Member deletion stays dependency-blocked, as the SRS says, and the no-cascade and retention rules are unchanged.

### Changed (files)

- `docs/DECISIONS.md` (C-38 added; X-16 and X-21 updated; status note), `docs/PHASE0_REVIEW.md` (revision 3), `docs/SECURITY.md`, `docs/DATABASE.md`, `docs/API.md`, `docs/TESTING.md` (AC-07 covers Trainer restore), `PROJECT_STATUS.md`, `NEXT_STEPS.md`, `HANDOVER.md`.

### Not changed

- No other requirement or delegated decision. No application code. Phase 1 not started.

## [Phase 0 — revision 2] 17 Nov 2026 — Documentation completion

### Added

- `docs/DECISIONS.md`: the decision register (C-01 to C-37, X-01 to X-21, D-01 to D-64, P-01 to P-12).
- `docs/ARCHITECTURE.md`, `docs/DATABASE.md`, `docs/API.md`, `docs/SECURITY.md`, `docs/TESTING.md`, `docs/SETUP.md`, `docs/DEPLOYMENT.md`, `docs/BACKUP_RESTORE.md` (all marked PLANNED).
- Root files: `README.md`, `PROJECT_STATUS.md`, `HANDOVER.md`, `CHANGELOG.md`, `NEXT_STEPS.md`.

### Changed

- `docs/SRS.md`: approval-status wording only (header, Document Control, Revision Summary, §20.2), to reflect the user's approval. No requirement was changed.
- `docs/PHASE0_REVIEW.md`: rewritten as revision 2, with corrections R-01 to R-12, the consistency checklist and the stack validation.

### Decisions (made under delegated authority)

- D-01 to D-64. Most significant: DB-backed sessions (D-01), same-origin `/api` rewrite (D-02), Admin-only email reset (D-07), the four-status payment rule (D-32), immutable receipts with void and reissue (D-35), the outbox with idempotency (D-46), scripted encrypted backups (D-61).

### Conflicts identified

- X-01 to X-21. User action requested on X-16 and X-21.

### Not changed

- No application code, packages, models or endpoints were created.

## [Phase 0 — revision 1] 17 Nov 2026 — Initial review

### Added

- `docs/SRS.md` (Markdown copy of SRS v2.0).
- `docs/PHASE0_REVIEW.md` revision 1 (initial architecture and plan).
- Git repository initialised in the workspace.
