# Project Status

**Last updated:** 20 Nov 2026
**Current phase:** **Phase 10 — Final QA, deployment readiness & handover: complete. All phases (0–10) are done.** The system is **ready to deploy but not deployed**: hosting and the external services need real accounts (P-02 – P-08), so those integrations are built but untested against the real services.
**Baseline:** SRS v2.0 (approved, unchanged) + Master Development Prompt + `docs/DECISIONS.md` (C-38 confirmed; **X-21 resolved by D-131** in Phase 9 without an SRS change).

## Overall progress

| Phase                               | Status                                                                                               |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------- |
| 0 — Review & planning               | Complete                                                                                             |
| 1 — Foundation                      | Complete                                                                                             |
| 2 — Public site & inquiries         | Complete                                                                                             |
| 3 — Members                         | Complete (Revision 2: 44 px touch targets)                                                           |
| 4 — Memberships                     | Complete (Revision 1)                                                                                |
| 5 — Payments & receipts             | Complete (Revision 1)                                                                                |
| 6 — Trainer experience              | Complete                                                                                             |
| 7 — WhatsApp                        | Complete (simulated and fake-provider tests; real Meta delivery untested)                            |
| 8 — Dashboards, reports & expenses  | Complete                                                                                             |
| 9 — Settings & operational security | Complete (Revision 1; backups tested with a local folder and a fake S3 server; real bucket untested) |
| **10 — QA, deployment & handover**  | **Complete (deployment prepared and documented; not deployed: no hosting accounts yet)**             |

Development is **complete**. What remains is going live with real accounts (`NEXT_STEPS.md` §1).

## Completed in Phase 10 (final QA)

- **Audit:** the whole project against SRS v2.0 and every decision; all 26 acceptance scenarios re-run through the automated suites; static scan (no TODOs or stray console output, every server file parses, every dependency used); **production-mode start** with only production dependencies (configuration checks refuse unsafe settings; `Secure` cookies, security headers, CORS/CSRF, health check and first-Admin setup verified); **final security audit** (`docs/SECURITY.md` §17).
- **New final QA browser checks:** one realistic journey across all phases, the production Content-Security-Policy on the built app, and an automated accessibility scan (WCAG 2 A/AA) of 13 screens in both themes plus 4 Urdu screens.
- **Fixed:** colour contrast of status badges and coloured text (WCAG AA; amber was 2.7:1), a CSP violation caused by the validation library on every form page, wrong deployment instructions (server build step, index creation, proxy setting), backup/restore scripts not reading `server/.env`, and a flaky browser test (D-137).
- **Documentation:** `docs/ADMIN_GUIDE.md`, `docs/TRAINER_GUIDE.md`, a rewritten `docs/DEPLOYMENT.md` (production variables, step-by-step services, release, troubleshooting), `docs/SETUP.md` tests and troubleshooting, README, handover.

## Phase 9 Revision 1 (20 Nov 2026) — restore failure recovery (D-136)

- **The problem:** a restore that failed after writing left a partly filled, unmarked database, and every retry refused it as "not empty".
- **Now:** the whole backup is validated before any write (`--check` does only that). The restore marks its target first (`restoreState`). A failure is reported as `PARTIAL_RESTORE`, and the database stays marked: the server and every operator script refuse to run on it.
- **Recovery without deleting anything:** `--resume` with the same backup file continues only if every document already there is exactly this backup's data; then it adds only what is missing. Anything else (changed or extra data, another file, a run still in progress) is refused with nothing written. The alternative, restoring into a new empty database, always works. A database that no restore marked is never written to.
- **Also fixed (found by the new tests):** backups now keep every number type (a double `5.0` used to come back as `5`; money is whole rupees, so amounts were not affected), restores recreate empty collections, and nothing is written to a partial database before the start-up check.
- 25 new server tests (339 in total); the browser restore drill also runs `--check`.

## Completed in Phase 9

**X-21 resolved (D-131).** Member deletion stays blocked while protected history exists, exactly as SRS §12.2 says: consent history, WhatsApp message history, workout notes and payment-correction logs are never deleted, anonymised or detached. Every member has consent history, so **members are archived, not deleted**; the deletion dialog and the API now say so. All protected collections (also the activity log, login history and deletion audits) refuse physical deletes at the model level. If an erasure obligation ever arises, it needs an SRS change request.

**Server**

- **Backups** (SRS §19, C-35, D-132): weekly (Sundays 03:00 Karachi), encrypted AES-256-GCM, to S3-compatible storage; the newest 8 kept; a failed run never prunes; status records; `npm run backup` for the operator. **Restore is an operator-only script** (`npm run restore`) that only writes into an **empty** database after a typed confirmation and checksum check, recreates indexes, checks counts and records the restore. No restore endpoint.
- **Settings → Audit** (D-133): Admin-only Activity Log viewer (actor, action, record type, dates), Login history (result, account, dates; unknown names masked, device summary), backup status, and the approved security and retention rules (read-only).
- **Hardening** (D-134): `Cache-Control: no-store` on every API response except the public site; backup secrets redacted from logs; dependency audit with **0 vulnerabilities** (test-only pdfjs-dist upgraded); review of every deletion route (all Admin-only, pinned by a test), sessions and account lifecycle, error output, secrets in responses and query handling.
- 28 new server tests (314 in total).

**Client**

- **Settings** screen (`/app/settings`, Admin): Overview (where gym details are edited, the deletion rules, sign-in and password rules, how long records are kept), Activity Log, Login history, Backups. Backup warning on the Admin dashboard. Clear explanation in the blocked member-deletion dialog.
- English and Urdu, light and dark, 44 px targets. 9 new client unit tests, 5 new E2E flows (including the real backup and restore scripts), 4 new visual screens and 3 more Urdu screens.

**Also fixed:** a misplaced row in `docs/TESTING.md` from Phase 8 (the Phase 8 Playwright total sat in the Phase 5 table).

## Completed in Phase 8

**Server**

- **Expenses** (SRS §9.5, Admin only, D-41): create, list with date/category/method filters and the filtered total, edit with version checks (simultaneous edits cannot overwrite each other), change history, safeguarded permanent deletion with the minimal deletion audit. Whole rupees 1–10,000,000, no future dates, the six SRS categories, Cash or Online (D-124).
- **Admin dashboard** (`GET /dashboard/admin`, SRS §9.1/§9.3): Total/Active/Inactive/Expired members (archived counted separately only), today's collections and this month's income split Cash/Online with a daily series, outstanding payments, payment-status counts, Trainer summary with last sign-in, members registered and inquiries received today, upcoming expiries (7 days) and the latest payment corrections. Computed on the server in Asia/Karachi; the same code as the reports, so the numbers match (D-125).
- **Reports** (SRS §9.4): income (verified payments only), expenses and an income-and-expenses summary for any range up to two years, each filterable Cash/Online; **income and expenses are always separate and no net profit is calculated anywhere** (C-21). Member list PDF and the **full personal-data export**, which needs the Admin's password and is logged. Archived members appear only when the Admin chooses them (D-126). **PDF only**, generated on demand, dated and stamped with the user on every page (D-127 – D-129). Every PDF download is logged.
- Trainers get 403 on every expense, report, export and Admin-dashboard route; the route-access test covers them all. 26 new server tests (286 in total), including PDF text checks.

**Client**

- **Admin dashboard** replaces the interim one: money tiles, member tiles, daily income chart (Cash/Online, legend, table view), Today, upcoming expiries, payment status, Trainers and recent corrections, with loading, empty and error states. The Trainer dashboard is unchanged.
- **Expenses** screen: filters, total, add/edit dialog, history, safeguarded delete.
- **Reports** screen: Income, Expenses, Summary and Members, with quick periods (this month, last month, this year) and custom dates, on-screen preview, PDF download, and the full-export dialog with password.
- English and Urdu, light and dark, 44 px targets. 12 new client unit tests, 5 new E2E flows, 5 new screens in the visual suite (6 widths × 2 themes), 4 new dialogs/menus at 360 px and 4 more Urdu screens.

**Also changed:** member registration dates now use the app's business clock (the same as the system clock in production) so every "today" figure agrees (D-130). Two earlier browser tests that described the interim Admin dashboard were updated to the new one (details in `docs/TESTING.md` §18).

## Completed in Phase 7

**Server**

- **Meta WhatsApp Cloud API adapter** (no Twilio): template messages, receipt PDF as a document, template submission, edit, status and deletion. Credentials only in server environment variables; never logged or returned. **Tested only against a local fake Graph server.**
- **Modes:** simulated (`mock`, default in development, refused in production), `disabled` (default when deployed without credentials) and `live` (needs all six Meta settings). Simulated results are labelled everywhere and never reported as delivered.
- **Templates:** Admin creates, edits and deletes (safeguarded); Trainers see and send only approved templates. Status is what Meta (or the simulation) reports; edited templates go back for approval; one default template per automatic event.
- **Automatic messages (SRS §10.2):** membership confirmation, payment received, expiry reminder (Admin-set days before, sent at 10:00) and membership expired (sent at 10:00), each queued once in the transaction that causes it. No partial-payment or payment-due reminders (as the SRS says).
- **Consent and opt-out:** checked when queued and again just before sending; members without consent, opted out, archived or without a mobile number get nothing; direct API requests are refused too.
- **Retries:** temporary errors retried every 15 minutes, **3 times**, then Failed with a follow-up; permanent errors (invalid number, rejected template …) not retried; no message is ever sent twice (unique keys, atomic claim, request IDs); an interrupted send is never re-sent automatically.
- **History and statuses:** every message with its status history; delivered/read only from signed webhooks; Admins see all, Trainers only their own; Admin follow-up; history can never be deleted.
- **Receipt sharing:** by WhatsApp with the PDF, or the manual route (download, share yourself, record it) when no approved receipt template exists.
- 45 new server tests (260 in total).

**Client**

- **WhatsApp** screen: Messages (filters, details with the status history, Admin follow-up) and Templates (review status, editor with placeholder mapping, Admin configuration card with the expiry-reminder days).
- Member profile: **Send WhatsApp message** with a server preview, and the member's messages. Payment page: **Share REC-…**. Trainer dashboard: **Messages you sent**.
- English and Urdu, light and dark, 44 px targets. 10 new client unit tests, 5 new E2E flows (simulated), 4 new visual screens, 4 dialogs at 360 px, 2 more Urdu screens.

**Test environment fix:** the browser suite now builds the database indexes after resetting its database (`npm run sync-indexes -w server`); before, it had run without unique indexes since Phase 1 (production unaffected; see `docs/TESTING.md` §17).

## Completed in Phase 6

**Server**

- **Exercise library** (SRS §8): Admin and Trainer add and edit exercises (name, short description, instructions, created/updated by). Names are unique ignoring letter case and extra spaces, also when two people add the same name at once. Search by name, paged. No deletion (D-39, D-111).
- **Workout notes**: any staff member adds a note to a member. A Trainer edits or deletes only their own notes; an Admin edits and deletes any note, and the author always stays the author. Deletion is a soft delete: the note is kept, hidden from Trainers, and Admins can list deleted notes. Notes on archived members are read-only. Edits are protected against overwriting each other. The author's name is the one recorded when the note was written, so it survives the account being deleted; the model refuses physical deletes (C-19, D-40, D-112).
- **Trainer dashboard** (`GET /dashboard/trainer`): member counts, payment-status counts only (no amounts), the 5 latest notes and the Trainer's own 10 latest actions. No upcoming expiries. Admins get 403 (D-44, D-113).
- **Trainer lifecycle re-verified** with notes and payments: deactivation ends the open session at once, reactivation and force logout work, deletion keeps every note, payment and log with the original name; the deletion dialog now lists notes and recorded payments as kept (D-115).
- All permissions are enforced on the server; the route-access test covers every new route. 18 new server tests (215 in total).

**Client**

- **Exercises** screen (both roles; in a Trainer's phone bottom bar): search, cards with description and expandable instructions, add/edit dialog.
- **Workout notes** card on the member profile: add, edit, delete as allowed; Admin filter Current / Deleted / All; "Edited by", "Deleted by", "Former staff" and "Deactivated" labels; read-only notice for archived members.
- **Trainer dashboard**: payment status, recent workout notes (linked to the member) and "Your recent activity".
- English and Urdu, light and dark, 44 px targets. 9 new client unit tests, 5 new E2E flows, 2 new visual screens, the note and exercise dialogs at 360 px and 2 more Urdu screens.

## Phase 5 Revision 1 (18 Nov 2026)

- **Receipt snapshot in the API (D-109):** `GET /receipts/:id` and `GET /members/:memberId/receipts` returned Mongoose internals instead of the snapshot fields, because the subdocument was spread. They now return a plain snapshot with all 14 fields. The receipt PDF was already correct, and no screen showed the snapshot, so nothing visible changed.
- **Receipt dates at activation (D-109):** found by the new tests. A payment taken in the same step as activation ("Activate now", or Activate with a first payment) got a receipt with blank start and end dates. The receipt is now issued after activation, so it shows the membership's dates (for an early renewal, the Upcoming dates). A payment recorded before activation still shows no dates, because receipts record their own moment and are never rewritten.
- **Node.js (D-110):** supported versions are now `^22.22.2 || ^24.15.0 || >=26.0.0` (was `>=22`), from the strictest requirements in the lockfile (jsdom 31, w3c-xmlserializer 6, react-router 8.5, undici 8), and npm refuses unsupported versions (`engine-strict`). Production: Node 24 LTS, 24.15.0 or later.
- 5 new server tests (197 in total).

## Completed in Phase 5

**Server**

- Full payment entry: further payments on any membership's summary by Admin and Trainer (cash always verified, online verified or pending), guarded against overpayment, future dates (backdating allowed), archived members, and stale or duplicate submissions (optimistic `expectedVersion`, 409 VERSION_CONFLICT; exactly one of two identical submissions succeeds).
- Pending online payments: **Verify** (both roles) issues the receipt; **Reject** (both roles, reason required) keeps the entry but it never counts. Two simultaneous Verify presses give one verified entry and one valid receipt.
- Balances are always recomputed from all entries (paid = verified only; pending shown separately); an old balance stays on its own summary after a renewal (C-15).
- **Receipts** REC-0001 onwards from an atomic counter, with a frozen snapshot; one valid receipt per entry (unique index). A5 PDF (pdfmake, built-in fonts, no network or file access); void receipts carry a VOID watermark and the replacement number. **Backfill** for Phase 4 verified payments runs once at start-up under a job lock (also `npm run backfill-receipts`), idempotent.
- **Corrections** (reason required) of amount, method, date, reference or note: never silent; the old receipt is voided and a new one issued, and an immutable correction log keeps old and new values. Admin-only correction of the total due, never below paid + pending.
- Admin ledger with filters (status, balance, member). Admin-only safeguarded deletion of receipts, entries and summaries in dependency order; deleting the summary unblocks membership deletion (D-99). Correction logs are protected records (X-21 stays deferred).
- 20 new server tests (192 in total).

**Client**

- **Payment page** (`/app/payments/:id`): summary, entries with Verify / Reject / Correct, receipt links (PDF), correction history; Admin extras (correct total, delete with safeguards).
- **Record payment**, Reject, Correct entry and Correct total dialogs; a version conflict reloads the data.
- **Payments ledger** (`/app/payments`, Admin only) and links from the member's memberships.
- English and Urdu, light and dark, 44 px targets. 6 new client unit tests, 5 new E2E tests, 3 new visual screens plus 2 Urdu screens and the Correct dialog at 360 px.

## Completed in Phase 4

**Server**

- Membership plans: already complete from Phase 2 (Admin creates and edits unlimited Monthly or Custom-days plans and their prices; Trainers read only). Phase 4 adds the **Admin-only custom price** per membership, with a mandatory reason, logged with the old and new price (C-09). No discount feature.
- Membership model with the plan snapshot, the agreed price and the `current`/`next` slot index: one Active plus at most one Upcoming or Pending Activation membership (C-10, D-26).
- Creation by Admin and Trainer, refused for archived members, inactive plans and a zero price. The payment summary is created in the same transaction, with an optional **initial payment** (cash or online, verified or pending), guarded against overpayment and future dates (backdating allowed).
- **Activation needs at least a partial verified payment**; zero verified payment is refused (C-11). Activation sets the member to Active in the same transaction (C-07).
- Server-side dates only (Asia/Karachi): the calendar-month rule with the month-end fallback (D-25), custom days, early renewal starting the day after expiry as Upcoming, late renewal starting on the activation date. Every renewal is a new record; history is kept. No date editing, pause, cancellation or plan change.
- Daily lifecycle job (00:05 Karachi) under a non-re-entrant lease lock: Upcoming → Active, Active → Expired, member Inactive/Active. Idempotent, catches up missed days, and runs on read too (D-97).
- Archive and activation conflict safely (exactly one succeeds), using the member `lifecycleVersion` (D-92).
- Upcoming expiries (7/14/30 days) for Admins only (C-20, D-98). Membership deletion is Admin-only and safeguarded, and blocked while the payment summary exists (D-99).
- 48 new server tests (167 in total).

**Client**

- Member profile: a **Memberships** section with the current membership (dates, days left, paid, balance, pending amount, custom price note), the next one (Upcoming, or Pending activation with **Activate**), and the earlier memberships.
- **Add membership / Renew** screen: plan cards, the Admin custom price with reason, the first payment (cash, or online with "I have checked the online payment"), and **Activate now**, only possible with a verified payment. It explains when the membership will start using the server's dates.
- **Activate** dialog that records the first verified payment if there is none yet.
- **Upcoming expiries** screen (7, 14, 30 days) and an "Ending in the next 7 days" dashboard card, for Admins only.
- English and Urdu for every new screen; light and dark; cards on phones; 44 px touch targets.
- 7 new client unit tests, 6 new E2E tests, 4 new screens in the visual suite plus the membership dialog and 2 more Urdu screens.

## Phase 4 Revision 1 (18 Nov 2026)

- **Cash is always verified (D-102):** a cash payment marked pending is refused with 400 by the API schema, the service and the data model, for Admin and Trainer alike. Online payments may be verified or pending.
- **Fully pending online payment:** when pending online payments already cover the whole price and nothing is verified, the profile no longer offers Activate or a payment form. It explains that the pending payment must be verified first, and the membership stays Pending Activation. A partial pending payment can still be completed with a verified payment for the rest and activated.

## Phase 3 Revision 2 (18 Nov 2026)

- The automated touch-target check now requires **44 × 44 px** (SRS §13, C-02); before it allowed 36 px. Checkboxes and radios are measured by the label that wraps them, and tabs and menu items are now checked too. Layout and target problems are collected for every screen before the test fails, so one run shows all of them.
- Controls fixed to reach 44 px: small buttons (`size="sm"`, e.g. "Upload image"), small icon buttons, segmented filters (staff and plans), pagination arrows, the dialog close button, on/off switches (the visible track is unchanged; the tappable area is 44 px), the "Call" buttons on the member and inquiry pages, the dashboard "Edit profile" link, the public header section links, and the logo link in the collapsed sidebar.
- Test counts reconciled from an actual run, file by file (see `docs/TESTING.md` §11).

## In progress

- None.

## Not started

- None. Going live needs real accounts (`NEXT_STEPS.md` §1).

## Known bugs

- None open.

## Known limitations

- **Real WhatsApp has not been tested** (P-06: no Meta account, sender number or approved templates yet). Everything ran against a fake provider, a local fake Graph server or the simulated mode. Sending the receipt PDF through Meta (media upload) is built but unverified; the manual route is the fallback (SRS §7.4).
- Delivered/read statuses depend on Meta's webhooks, which have only been tested with test-signed payloads.
- A message whose send was interrupted (server crash) is marked Failed for a follow-up rather than re-sent, to avoid duplicates; staff must check it.

- **Image uploads (website and member photos) are untested against real Cloudinary** (no account yet). The UI disables them with an explanation.
- The public site has no photos until Cloudinary is connected. The hero shows an "At a glance" card instead.
- **Members cannot be deleted, only archived** (D-131, X-21 resolved): every member has consent history, which is kept permanently. The dialog explains this and lists the records.
- **No external payment provider** is integrated: online payments are checked by staff and marked verified by hand.
- Receipt PDFs show the gym name but **no logo** yet (logos need Cloudinary, P-05).
- Membership deletion needs its payment records deleted first (Admin, safeguarded).
- **Backups have not run against a real bucket** (P-08). Until storage and the key are set, the Admin sees "Backups are not set up yet". The backup is built in memory (fine for one gym's data). Restore needs the technical operator and the encryption key; **losing the key makes the backups unusable**.
- Retention periods are shown, not configurable (approved defaults, D-133).
- Membership statuses are updated by the daily job at 00:05 and whenever a member is opened; the members list itself may show yesterday's state until the job runs.
- Workout notes record only the latest edit (who and when, and how many edits); earlier wording is not kept (D-112). Deleted notes cannot be restored.
- Reports are generated when asked for and not stored (D-42); a PDF can list up to 5,000 records and cover up to two years (D-127). Income counts verified payments only.
- Expense history comes from the Activity Log, which is kept for 2 years (C-32); older edit history of an expense is then no longer shown.
- Report PDFs are English only (C-03) and have no logo yet (P-05).
- Server field-level validation messages are in English, even in Urdu mode. Client-side messages and known error codes are translated.
- Urdu translations are drafts and need review by a native speaker (P-10).

## Blocked tasks

- None blocked. Cloudinary uploads are waiting on P-05; the safe behaviour is in place.

## Open decisions and external items

| ID                           | Item                                                                                                                                               | Needed by                                                              |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| P-05                         | **Cloudinary account** (cloud name, API key, API secret)                                                                                           | To enable photos (member photos, logo, hero, gallery, trainer cards)   |
| P-01                         | GitHub repository                                                                                                                                  | Recommended (checkpoints are ZIP-only until then)                      |
| P-04, P-07                   | Atlas dev cluster, SMTP provider                                                                                                                   | Before staging                                                         |
| P-11                         | Real gym content (name, address, hours, plans, prices, trainer bios, photos)                                                                       | Before UAT. Entered by the Admin through the Website and Plans screens |
| **P-06**                     | **Meta WhatsApp: business verification, WhatsApp Business Account, sender number, system-user token, app secret, verify token, template approval** | **To send real messages (Phase 7 is built and waiting)**               |
| **P-08**                     | **Backup storage: S3-compatible bucket, a key limited to it, and custody of the encryption key**                                                   | **Before staging (Phase 9 is built and waiting)**                      |
| P-02, P-03, P-09, P-10, P-12 | Hosting, domain, Urdu reviewer, cost checks                                                                                                        | Phase 10                                                               |

## Latest testing status (details: `docs/TESTING.md` §21, final runs on 20 Nov 2026, Node 22.23.4)

| Suite                                                                                                                        | Passed | Failed | Blocked | Not tested |
| ---------------------------------------------------------------------------------------------------------------------------- | ------ | ------ | ------- | ---------- |
| Server (unit + API; backups with a local folder and a fake S3 server; WhatsApp with a fake provider)                         | 339    | 0      | 0       | 0          |
| Client unit                                                                                                                  | 78     | 0      | 0       | 0          |
| E2E flows incl. the final cross-phase journey (WhatsApp simulated; real PDFs; real backup/restore scripts)                   | 49     | 0      | 0       | 0          |
| Visual/responsive (46 screens × 6 widths × 2 themes + Urdu; 44 px touch targets)                                             | 14     | 0      | 0       | 0          |
| Production CSP on the built app; accessibility (axe-core WCAG 2 A/AA, both themes, Urdu)                                     | 4      | 0      | 0       | 0          |
| **Real hosting (Render/Vercel/Atlas), WhatsApp (Meta), backup bucket, Cloudinary, SMTP**; Node 24.x/26.x; real phones/WebKit | —      | —      | —       | Not tested |

## Next recommended tasks

1. Create the accounts and deploy to staging (`docs/DEPLOYMENT.md`, `NEXT_STEPS.md` §1).
2. On staging: verify `TRUST_PROXY`, password-reset email, the first backup and a restore drill.
3. User acceptance on real phones, Urdu review, real gym content; then production.
