# Phase 2: registration implementation

Implemented locally and deployed on 16 October 2026. Hostname: `elderly.mam-app.org`. See [deployment details](DEPLOYMENT.md) and the [registration source comparison](SOURCE_COMPARISON.md).

This document records the registration phase. [Phase 3](PHASE_3.md) now adds linked monitoring checklists and management, a shared sync engine, and an additive browser storage upgrade while retaining the registration key and data.

## Six delivered tasks

| Task | Implementation |
| --- | --- |
| Registration form | 52 controls in 10 source-based groups, English/Burmese labels, conditional questions, DD/MM/YYYY entry, partial drafts, five core completed-record requirements and explicit save actions |
| Manage Registration | Account-unlocked browser records or authenticated server records, search/filter/pagination, details dialog, edit, queued deletion, completion and sync indicators |
| Database/backend | Dedicated registration, sync-event and counter tables; models/controllers; server validation; module access; encrypted payloads; dedicated login/logout with host-only session cookie |
| Offline entry/sync | Per-account password-wrapped local vault, encrypted records/queue/snapshots, offline reload recovery, Offline-only mode, upload/download, retries, version conflicts and tombstones |
| Separate PWA | Module manifest, start URL/scope, install prompt when browser-supported, own worker/cache/IndexedDB namespaces and a non-personal cached shell |
| Verification | PHP/schema/sync integration checks, JavaScript logic checks and real-browser scenarios against a disposable local MySQL database; desktop/mobile screenshots |

All form questions come from the phase 1 registration mapping, with paper-only details and the agreed structural consolidation. Registration images 1–3 define the form. Follow-up images 4–5 are reserved for the later follow-up phase. The runtime form definition is `resources/data/elderly-support-register.json`; it is a reviewed implementation definition, not regenerated by the phase 1 extraction script.

## Form behavior and source decisions

- Complete requires program ID, name, registration date, age and sex. Save draft permits missing core answers but still validates any supplied date, amount or selection.
- Program ID uses the user-confirmed clinic dropdown (`HTY`, `SPT`, `SDG`, `TL`), year code `26`, and a manually entered five-digit serial (`00001`–`99999`), combined as `HTY-26-00001`. The serial is stored as text so leading zeros survive offline save, reload, sync and export. Browser and server enforce the format. The combined ID is unique within the elderly module, including soft-deleted records; code collisions never merge people. Changing the ID keeps the registration UUID. General ID remains optional and independent.
- An existing browser record with an earlier ID format can still be opened without silently changing its ID. Its saved ID is displayed for review; choose the clinic and enter the serial before saving an updated version. No production record was rewritten for this change.
- Age uses the source's technical 0–130 range. No minimum program eligibility age is invented. The household count is a non-negative integer; no household roster is added.
- A single caregiver age/relationship section writes compatibility aliases for the workbook's duplicated columns. Relationship detail remains available. Registrar name/date are separate controls and also generate the combined compatibility value.
- Original source option values are retained in this phase. This deliberately postpones a new enum coding scheme while avoiding inherited Child Support numeric codes.
- Disease description, other-support amount, caregiver-family yes/no and the two housing “Other” descriptions from the paper are included. Housing damage displays 25%, 50% and 75% while retaining the workbook's fraction values. Caregiver tasks remain narrative text until checkbox/multiple-choice rules are agreed.
- Conditional fields retain earlier answers when their controlling answer changes. Hidden sections are omitted from the screen; retained answers stay encrypted. Future reporting/export must use the controlling answer when interpreting those details.
- Amounts have no assumed currency/time unit. Collector identity is typed text; drawing/uploading signatures is outside this phase.
- Draft completion, Under care/Stopped/Dead and sync state are separate concepts. Current outcome is stored; historical outcome reporting is not implemented.

## Runtime flow

1. Open `/elderly-support/register` or `/elderly-support/register/manage` on the configured host. Both return identical non-personal shells; no names, records, keys or CSRF token are embedded in them.
2. Sign in at `/login` using the familiar MAM login design and an authorized existing MAM account. `/elderly-support/login` redirects there. Administrators and the configured user type 21 have access; every data endpoint checks authorization. The username field accepts the existing `ElderlyEntry@MAM` name. Login uses the module's host-only session and returns to registration.
3. On first use, create an offline password of at least 10 characters for this account/browser. Later page loads require that password to unlock the vault. The offline password is separate from the account password and cannot be recovered by the server.
4. Save locally, then use Sync now. There is no automatic network upload and no dependence on Background Sync. Download refreshes server changes without discarding pending browser work.
5. Resolve conflicts by comparing saved browser/server answers. Keeping local changes creates a new operation against the latest version. A deleted/missing server entity can be copied explicitly as a new draft with a new UUID and blank program ID.

Local and server keys are separate. The browser uses a random per-account/device AES-GCM key, wrapped with an offline-password-derived PBKDF2 key. Only the wrapped key, salt/iteration metadata and ciphertext persist. The unwrapped key stays in memory. Server encryption uses its configured module secret and authenticated AES-GCM envelopes. API record data travels through authenticated HTTPS, with `no-store` responses; this is not end-to-end encryption.

Lock clears the active form, decrypted dialogs/list and in-memory key. Online logout also invalidates the module session. Offline or Offline-only sign-out locks the vault and tells the user that server sign-out still requires a connection. Encrypted pending work remains available for the account's next unlock. Losing the offline password makes that browser vault unrecoverable; the app does not silently reset or delete it.

Clearing browser data is scoped to the active account. It warns about pending items and requires typing `DELETE`. Browser JSON export is an explicit readable export of that browser's records and sync status; it is not a server-complete or source-format Excel export. No export is stored in Cache Storage.

## Sync and storage details

- `elderly_support_registers` stores indexed IDs, date, age, sex, outcome and completion status plus the encrypted full form payload. Names, address, phone and clinical detail are not duplicated in plaintext columns.
- `elderly_support_sync_events` stores encrypted authoritative snapshots, UUID/version, operation receipt/fingerprint and committed sequence. All CRUD mutations go through the same service.
- `elderly_support_sync_counters` serializes sequence allocation inside the mutation transaction. Download holds a fixed high-water mark across 100-event pages. First download replays the retained event feed, including tombstones; no race-prone live-table snapshot is needed.
- Client UUIDs are permanent. Numeric server IDs do not replace them. Successful-operation retries return the original acknowledgement; changing a reused operation ID or actor is rejected.
- Updates/deletes require the edited server version. Stale writes return the server copy for review. Acknowledgements preserve later local revisions; a local revision check also rejects stale form saves from another tab.
- A local record and its pending queue change commit together. Once transmitted, an operation's content is frozen. A later edit waits for its predecessor and is rebased on acknowledgement.
- Browser keys/records/queue/cursors/snapshots are account-partitioned in `artcareElderlySupportDB`. The worker uses only `elderly-support-shell-*` caches and controls `/elderly-support/`.
- Server search uses program/General ID. Browser search additionally uses decrypted names. The implementation does not run SQL `LIKE` against encrypted names.
- Deletion is soft deletion with a change-feed tombstone. Code reuse and automatic pruning are disabled. A guard blocks parent deletion if the later `elderly_support_followups` table contains active children.

## Deployment and configuration

The module is deployed at `/var/www/html/artcare` on `mamserver`. Only the specific registration migration was applied to the verified `MAM_NAP` database. Port 8089 serves the same Laravel `public/` directory through its own Apache virtual host and dedicated Cloudflare tunnel. Existing ART, Child Support, PHP and the original Cloudflare tunnel were left running. Production key material was generated on the server and was not copied into the local workspace. See [DEPLOYMENT.md](DEPLOYMENT.md) for verification and backup paths.

Set these values in that installation's environment:

```dotenv
ELDERLY_SUPPORT_DOMAIN=elderly.mam-app.org
ELDERLY_SUPPORT_DB_CONNECTION=MAM_NAP
ELDERLY_SUPPORT_ALLOWED_TYPES=21
ELDERLY_SUPPORT_CRYPTO_KEY=<a persistent random secret of at least 32 characters>
```

The configured type is 21. An explicitly empty access list means administrators only; additional allowed types can be comma-separated. Users granted module access can access the module dataset; site-specific ownership filtering is not implemented because no site-assignment policy was supplied.

Generate the encryption secret on the intended installation and retain it securely across deployments. Do not reuse the Child Support key. Replacing this secret without re-encrypting the existing data will make old payloads unreadable; automatic key rotation is not included.

For another installation, confirm the target connection and apply only the elderly migration. This command has already been completed on mamserver:

```bash
php artisan migrate --database=MAM_NAP --path=database/migrations/2026_10_16_000100_create_elderly_support_registration_tables.php
```

If choosing another connection, change both the environment setting and the command's `--database` argument. The migration repository and the module tables should use that same connection. Use the project's normal configuration cache/deployment procedure after environment changes; do not run all unrelated pending migrations as a shortcut.

Point the new host's DNS/TLS and web-server virtual host at the same Laravel `public/` directory. Serve the worker and manifest under `/elderly-support/`. Ensure HTTPS, static assets and Laravel route rewriting work, and verify login at the real hostname before enrolling devices. The module sets its own host-only `elderly_support_session` cookie without changing other modules' session settings.

Expected entry paths:

```text
/login
/elderly-support/register
/elderly-support/register/manage
```

Root `/` on the elderly hostname redirects guests to the MAM-style login and authorized users to registration. The directly opened PWA shell shows sign-in/unlock until access is established, including offline reloads. API endpoints are unavailable on other hosts. A blank configured domain disables module routes rather than exposing a global fallback.

## Verification and reproducibility

The QA bootstrap rejects database sockets outside `/tmp/elderly-support-phase2-*/mysql.sock`, uses a fixed disposable `elderly_support_qa` database, overrides database connections and loads no project `.env`. The fixture accounts and case examples are synthetic. The CLI QA router must never be used as a production entry point.

| Check | Result |
| --- | --- |
| Elderly PHP syntax and JavaScript parse checks | Passed |
| JavaScript date/validation/identifier/acknowledgement checks | 5 passed |
| Backend integration checks on disposable MySQL | 31 passed |
| Browser registration/management/PWA scenarios | 20 passed; desktop/mobile screenshot artifacts in `outputs/elderly-support-phase2/` |
| Live origin, login shell, guest API protection and every worker dependency | 19 passed; read-only checks through port 8089 |
| Domain route list | Resolved to `elderly.mam-app.org` with unique route names |
| Existing Child Support common checks | 4 passed |
| Existing Child Support workbook-export test | Fails independently: its test injects `window.XLSX`, while the existing exporter requires `window.ExcelJS.Workbook`. Neither file was changed by this work |

Backend checks include validation, encryption/tamper rejection, exact retry acknowledgements, operation actor/content checks, code uniqueness, stale versions, high-water mark downloads, partial batch success, deletion propagation and access denial. Browser checks use real Chrome/Playwright, including offline reload, wrapped-key persistence, conditional details, Offline-only, edits during upload, explicit conflict resolution, shell/cache privacy, search/details, responsive layout and account isolation.

Run logic checks from the project root:

```bash
node tests/elderly-support-core.test.js
```

Against an already initialized disposable local MySQL instance:

```bash
ELDERLY_QA_SOCKET=/tmp/elderly-support-phase2-<run>/mysql.sock php tests/elderly-support-backend.php
ELDERLY_QA_SOCKET=/tmp/elderly-support-phase2-<run>/mysql.sock php -S 127.0.0.1:8876 -t public scripts/elderly-support/qa-router.php
```

In a separate terminal with Playwright available:

```bash
ELDERLY_PLAYWRIGHT_MODULE=/absolute/path/to/playwright/index.mjs node tests/elderly-support-browser.mjs
```

The backend test resets only its disposable fixture tables. Browser tests require that fixture setup and create unique synthetic registrations. Public TLS verification passed, and the user confirmed reaching the Elderly Support page through Cloudflare Access. Live origin smoke checks are read-only; the browser write/sync suite was run on disposable local MySQL. Device-specific PWA installation, storage eviction, Firefox/Safari and a real-device offline cycle remain to be confirmed. Follow-up, monthly reports, historical outcomes, signatures, cross-device offline-key recovery and workbook-compatible Excel exports remain later work.
