# PROJECT STATUS — Medical Ticket Management System

| Phase | Title | Status |
|---|---|---|
| 01 | Audit, requirements & architecture | ✅ Done (2026-12-01) |
| 02 | Foundation, DB & admin auth, header UI | ✅ Done (2026-12-01) |
| 03 | Institution & dynamic settings | ✅ Done (2026-12-01) |
| 04 | Registration & number engine | ✅ Done (2026-12-01) |
| 05 | Public QR registration | ✅ Done (2026-12-01) |
| 06 | Thermal print queue | ✅ Done (2026-12-01) |
| 07 | Kiosk API & device approval | ✅ Done (2026-12-01) |
| 08 | Dashboard, reports, exports | ✅ Done (2026-12-01) |
| 09 | `docs/android_tv.txt` | ✅ Done (2026-12-01) |
| 10 | QA & production readiness | ✅ Done (2026-12-01) — decision **NOT READY** (hardware + server pending) |

## Run locally
```bash
composer install && npm install
cp .env.example .env && php artisan key:generate   # set DB_USERNAME/DB_PASSWORD (local: root/root)
php artisan migrate --seed
npm run build            # or: npm run dev (with php artisan serve)
php artisan serve        # http://127.0.0.1:8000/admin
```
**Admin login (local only):** `admin@gmail.com` / `password` (from `ADMIN_EMAIL` / `ADMIN_PASSWORD` in `.env`).

Production admin: `php artisan admin:setup --email=… ` (prompts for a password; strong rule, default/weak passwords refused, password change forced at first login).

## Phase 09 delivered (specification only — no Flutter code)
- **`docs/android_tv.txt`** (≈1,100 lines): product flow, versions/packages, architecture, exact visual contract of the 1024×576 kiosk screen, pairing state machine, device auth (Keystore EC P-256 key generation code, PoP text, canonical request, headers, clock offset, nonce/request-id rules, key rotation), all 13 endpoints with **real captured request/response payloads for every success and error case**, error→action table, form/idempotency, hospital-closed handling, print lifecycle (claim/printing/complete, leases, unknown handling, priority), ESC/POS + USB/BT/LAN, raster Bangla renderer contract with mm→dot sizing, network recovery, success overlay (≈1 s, honest print state), maintenance/diagnostics, security, tests, build/signing, DoD, and the copy-paste master instruction for the next Claude session.
- **`docs/android-kiosk-api-matrix.md`**: screen/action → endpoint → success → errors → spec section.
- Payloads were captured over real HTTP against the running backend (isolated test DB) — 31 request/response cases, ids redacted.
- Backend defect found while capturing and fixed: Bangla validation messages for `enum`/`uuid`/`boolean`/`decimal`/`date_format`/`after_or_equal`/`accepted` and the `client_request_id` attribute fell back to English. Test added.
- Spec facts worth knowing: X-Request-Id must be lowercase (server lowercases before verifying); the request target includes any base-URL path prefix; printer models are **all unverified** (none physically tested).

## Test / build evidence (Phase 09)
- `./vendor/bin/pest` → 155 passed. New `AndroidSpecConsistencyTest`: §7.1 endpoint table == implemented routes; 70+ response field paths the spec references exist in real responses; the documented Code-128 bars for 010482 equal the server barcode library; security rules present and no Bearer header suggested. `OpenApiContractTest` still green.

## Phase 08 delivered
- **Dashboard**: any Dhaka service date (date picker), totals by source, revenue, last SL, previous-day comparison, print jobs by state (clickable), live queue, "needs attention" (failed/unknown), approved/online kiosks, recent registrations and print events, quick actions; live refresh every 30 s on today; nothing cached (statuses never stale).
- **Reports & Exports**: daily / weekly (Sat–Fri) / monthly / custom (≤366 days), source and print-state filters, SQL-aggregated summary (by source, day, gender, print state), paginated rows; **XLSX** (OpenSpout, streamed to private temp file, deleted after send), **CSV** (streamed, UTF-8 BOM, formula-injection safe), **PDF** (mPDF, Bengali shaping verified visually; GNU FreeSans regular — its bold face lacks Bengali so bold is not used); same filters as screen, Admin-only, audited, row limits with guidance, `exports:prune` hourly.
- **Audit Log** page: group/date filters, before/after values, secrets redacted.
- **Kiosk & Ticket Preview** (Settings): 1024×576 landscape kiosk, 360 px mobile, thermal ticket at the selected profile, canonical demo record only, Print Test Ticket (no patient, no serial, audited).
- Patient list: print-state column/filter and sort; every header destination is now a real page (no "Soon" placeholders).
- Backup/restore runbook in `docs/database-design.md`.

## Test / build evidence (Phase 08)
- `./vendor/bin/pest` → 150 passed. New: dashboard reconciliation across Dhaka midnight, weekly Sat–Fri / monthly / custom ranges, range limit, latest-job print filter, CSV (Bangla, BOM, filter, audit), XLSX read back with OpenSpout reader (row count, Bangla, totals, temp file removed), PDF (font, temp file removed), too-large refusal, admin-only, prune, audit redaction, preview + test print uses no number, sorting.
- 50k-row synthetic dataset: EXPLAIN ANALYZE for all dashboard/report queries (`docs/database-design.md`); two plan fixes (73 ms → 0.14 ms page; exports 12.6 s → 0.6 s CSV, 14.9 s → 3.0 s XLSX).
- PDF rendered to PNG and inspected: Bangla headings/names/statuses shaped correctly; totals match.
- Browser: dashboard, reports, audit, preview, patients at 1440 px and 390 px — no overflow, no console errors; XLSX downloaded through the UI.

## Phase 07 delivered
- Versioned kiosk API `/api/v1` (13 routes, `routes/api.php`); contract `docs/openapi.yaml`; reference CLI client `tools/kiosk-simulator.php`.
- Device auth without Bearer/JWT or passwords: ECDSA P-256 keys, challenge-based proof of possession at pairing, per-request canonical signature (method, request target, timestamp, nonce, request id, body SHA-256), clock-skew window with server time in the error, nonce replay store, request-id idempotency with stored-response replay. Status gate on every request (pending/rejected/suspended/revoked; can_register/can_print).
- Kiosk registration through the shared `RegisterTicket` (server-side numbers, price, time, source; idempotent `client_request_id` for offline retry; Hospital Closed blocks, Public OFF does not).
- Print API over `PrintQueue`: claim (public first, idempotent on lost response), printing, complete printed/failed/unknown, device-scoped.
- Config endpoint with everything for the reference kiosk screen (identity, logo, Bangla/English clock, price, statuses, labels, age bounds, genders, display toggles, printer profile, poll interval, config_version); heartbeat with printer state; device printer-test; self-release.
- Admin **কিওস্ক ডিভাইস**: pending requests with large pairing code, approve dialog (name, location, permissions), device page (printer health from heartbeat, stats, identifiers), suspend/resume/revoke (confirmed, audited), edit.
- Uniform API error envelope with Bangla + English messages; API rate limits; `devices:prune` hourly.

## Test / build evidence (Phase 07)
- `./vendor/bin/pest` → 138 passed. New security tests: unsigned, unknown device, forged signature (knows device id, wrong key), tampered body, old/future timestamp, repeated nonce, replayed request id (same → stored response, different → 409), pending/rejected/suspended/revoked blocking with immediate effect, capability flags, wrong-device job ownership, pairing proof-of-possession, single-use/expiring challenges, non-P-256 key rejection, rate limiting, pruning. Contract tests: documented paths == implemented routes, all `$ref`s resolve, documented required config keys present in the real response.
- Real HTTP end-to-end (isolated test DB, `tools/kiosk-simulator.php`): pair → blocked while pending → approved in the browser admin UI → heartbeat → kiosk registration 010483/000046 → public QR registration 000047 → claim prints the public job first → kiosk job → nothing left → revoked in UI → next request `403 DEVICE_REVOKED`.

## Phase 06 delivered
- `PrintQueue`: atomic SKIP LOCKED claim in priority order (public 100 first), device ownership, claim/printing leases, idempotent printing/ack, auto-retry with backoff and attempt limit, `unknown` on lost acknowledgement (no silent duplicate printing), admin resolve (printed / failed / reprint), retry, cancel, audited reprint (new linked job, original untouched), targeted test prints, immutable `print_job_events`.
- Scheduled: `print:reap` every minute, `devices:prune` and `exports:prune` hourly (cPanel cron `schedule:run`).
- `TicketRenderer`: one device-independent ticket document from the ticket snapshot plus current printer hardware settings (see `docs/api-plan.md`).
- Browser print view at exact printable width (`/admin/tickets/{id}/print`, `/admin/print-preview?profile=52|80`) with real Code-128 (picqer) and QR (chillerlan); a fallback for OS-driver thermal printers.
- Admin **প্রিন্ট সেন্টার**: status counters/filters, job list, "next to print" in the exact claim order with an explanation, device panel (online/ready only from a recent heartbeat), retry/cancel/resolve dialogs, job timeline page. Ticket page: working Reprint (reason required) and browser print. **প্রিন্টার সেটিংস**: printable dots per profile, density, feed, auto-cut, lease, attempts, backoff, kiosk poll interval, sample previews.
- Ticket previews now show the real verification QR (when enabled).

## Test / build evidence (Phase 06)
- `./vendor/bin/pest` → 109 passed. New: priority order (public before older kiosk/admin; reprint/test last), no pre-emption + ownership, target device, happy path history, idempotent acks, retry/backoff/limit, lease reaper (claimed→pending, printing→unknown, unknown not re-handed), late ack, expired-lease refusal, resolve/reprint audit, reprint keeps original, retry/cancel states, renderer snapshot + profile width, print centre/actions/print views, printer settings, test-print approval; **6 parallel processes claiming 60 jobs → each claimed exactly once**.
- Browser: rendered ticket measured at exactly 72.00 mm (80 profile) and 48.00 mm (52 profile); long Bangla name wraps without overflow; serial fits on one line; QR wraps below barcode on 52 mm (overflow found and fixed); Bangla conjuncts shaped correctly; side-by-side matches the reference photo. Print Centre/resolve/reprint flow exercised; no console errors; phone width OK.
- **Not yet verified on a physical printer** — needs an approved kiosk (Phase 07/09) and the real printer model.

## Phase 05 delivered
- Public form at `/r/{key}` (random, rotatable key): separate patient layout (logo, full name via FitText, server-synced Dhaka clock, language toggle, Admin accent colour), Admin instructions, name / − age + / gender tiles, big Register button, closed/disabled notice instead of the form.
- Server enforcement through the shared `RegisterTicket` + `RegistrationGate`: Hospital Closed / Public OFF reject form and direct JSON posts (423) without touching counters or print queue.
- Abuse protection: IP + session rate limits, honeypot, 2-minute same-person duplicate window, idempotent request id, CSRF.
- Confirmation page: huge Bangla SL, Reg No, fee, server time, "Print queued" (switches to "Printed" when the kiosk reports it), ticket verification QR; visible only to the submitting session.
- Ticket verification `/t/{token}`: validity, institution, date, `••••NN` reference only; rate limited; noindex/no-store.
- Admin **সেটিংস → পাবলিক QR**: QR preview, PNG/SVG download, A4 print poster, copy/open link, live status, confirmed link rotation (old QRs stop working, audited). Server-side QR generation (chillerlan/php-qrcode), no external QR service.
- Print job for public tickets is created in the same transaction as the ticket (priority 100), so a saved ticket cannot lose its print request.
- Performance for cheap phones: admin shell/toasts lazy-loaded (public page no longer downloads them), 2 Bengali font weights instead of 4: 851 KB → 591 KB raw (~265 KB gzipped). `public/.htaccess` gzip + 1-year immutable caching for hashed build files.

## Test / build evidence (Phase 05)
- `./vendor/bin/pest` → 91 passed (19 new public/QR tests: link validity, priority-100 job, session-only confirmation, spoofing, OFF/closed via form + JSON without counter use, retry/duplicate window, honeypot, IP rate limit, validation, verification privacy (HTML contains no name/reg no), invalid tokens, verify rate limit, QR page/PNG/SVG/rotation, auth).
- Browser (isolated test DB, 360px phone, throttled network): register → confirmation → English → verify in a fresh session; no overflow, no console errors, verification page does not contain the patient name. Admin pages + toasts still work with the lazy layout.

## Phase 10 result (2026-12-01)
Decision: **NOT READY** for full go-live — software complete and verified; physical printing (no kiosk app yet, printer not connected) and the production server are unverified. Details: `docs/production-readiness-report.md`, `docs/test-cases.md`, `docs/security-review.md`, `docs/query-performance-report.md`, `docs/deployment-guide.md`, `docs/flutter-api-compatibility-report.md`.
Evidence: 173 tests / 1,559 assertions pass; 0 dependency vulnerabilities; 0 overflow / clipped text / axe violations / CSP violations across 17 pages × 5 resolutions; backup/restore of 50k tickets verified; clean migrate + full rollback verified.
Fixed in Phase 10: CSP, secure cookies, JSON-compare bug in the 58mm migration, claim-query filesort (descending index), tablet overflow, name truncation, accessibility issues, Bangla validation gaps, demo data removal, 58mm profile.

## Corrections during Phase 10 (2026-12-01) — supersede older notes below
- Thermal profiles are now **58 mm (Xprinter XP-58IIL, 48 mm / 384 dots printable)** and **80 mm** (printable dots configurable); "52 mm" no longer exists (migrated). Single source: `app/Printing/PrinterProfiles.php`.
- **No demo patient data anywhere in the app.** Forms start empty (exact placeholders, no age, no gender); the canonical fixture lives only in `tests/Support/DemoTicketFixture.php`. Mentions of `DemoTicketSeeder` / 010482 below are historical.

## Owner change requests (2026-12-01, after Phase 04)
- Institution name never cut off: new `FitText` component (shrinks to fit, wraps only if needed, never "…") in kiosk preview, admin header and login. Verified in Chromium at 1440/1024/768/412/360/320 px: no clipping. Kiosk header badges wrap below the name on narrow screens. Rule added to `docs/reference-ui-and-demo-data.md` for the Flutter kiosk.
- `/admin/security/password` is now **Account & Security**: profile photo (upload/replace/remove, re-encoded PNG, shown in header), name + login email (requires current password, audited), password change.
- Institution logo = favicon (server-rendered on load + swapped live after upload/removal).
- Login page no longer shows or pre-fills development credentials (also absent from the JS bundle).
- Stored files now use relative `/storage/...` URLs so images work when opened via LAN IP/phone; the kiosk config API gets absolute URLs.
- Tests: 74 passed.

## Phase 04 delivered
- `RegisterTicket` action (single entry point for all sources): gate check → idempotency → one transaction allocating Reg No + Daily SL, inserting ticket (price/institution/layout snapshots, 22-char random verify token) and its pending original print job (priority by source), plus audit row.
- `NumberAllocator`: exclusive-lock-first counters, fixed lock order, 999999 exhaustion stop, configured start values.
- Admin **রেজিস্ট্রেশন** page (reference kiosk hierarchy: big name input, − age +, three gender tiles, big submit; summary card with huge Bangla SL, smaller Reg No, fee, date/time, "print pending"; next-number badges; toast).
- Admin **রোগী** list (search reg no / serial incl. Bangla digits / Bangla+English name via ngram full-text; date range; source; 25/page; mobile cards) and ticket detail (snapshot-rendered ticket preview, print job history, activity). Reprint button disabled until Phase 06.
- Demo fixture `DemoTicketSeeder` (local/testing only, production refused): 010482 / 000045 / 2026-12-01 10:15; counters only move forward → next 010483 / 000046.
- Indexes added from EXPLAIN ANALYZE on 50k rows (`daily_sl`, `service_date`); full-text stopwords disabled (they broke English name search).

## Test / build evidence (Phase 04)
- `./vendor/bin/pest` → 67 passed (Feature + `tests/Committed`): sequential 6-digit numbers, Dhaka-midnight reset (and no reset at UTC midnight), start values, idempotency (same/different payload, per-source namespace), spoofing ignored, exhaustion for both sequences, gate, price snapshot, demo seeder (+ no rewind, production refusal), admin HTTP flow, validation incl. infants, double submit, search, detail.
- Real concurrency (forked processes, own MySQL connections, committed data): 8×15 parallel registrations → 120 unique Reg No and SL, no errors; 10 simultaneous first-of-day requests → one counter row; 8 parallel duplicates with one key → one ticket. Passed 5/5 runs after fixing a real deadlock (shared→exclusive lock upgrade).
- Browser (isolated test DB): registration, list, search, detail at 1440px and 390px; no overflow, no console errors.

## Phase 03 delivered
- Settings pages (header → সেটিংস): **প্রতিষ্ঠান** (identity, bilingual address, contact, logo upload, public registration link + copy), **সিস্টেম সেটিংস** (Hospital Open / Public Registration switches with confirmation and per-source effective status, ticket price, default language, public instructions, numbering start values), **টিকেট ও ডিসপ্লে** (thermal layout + live 52/80mm ticket preview matching the reference; kiosk/public display + live kiosk preview).
- `SettingsSchema` = typed defaults + validation + audit flags; `SettingsRepository::update()` saves atomically, audits old→new for audited keys, flushes cache.
- `RegistrationGate` enforces Hospital Closed (all sources) / Public OFF (public only) / unapproved kiosk, server-side.
- Ticket snapshots (`institutionSnapshot()`, `ticketSnapshot()`, price) ready for Phase 04; tested that later edits never change an existing ticket.
- Logo: MIME/size/dimension validation, GD re-encode to PNG, random filename, old file deleted, no partial save on failure.
- `ClientDisplayConfig` = documented config payload for public form and Flutter kiosk.
- Code-128 preview encoder verified bar-for-bar against picqer/php-barcode-generator (installed for Phase 06).

## Test / build evidence (Phase 03)
- `./vendor/bin/pest` → 42 passed, 265 assertions. `vue-tsc` clean, `npm run build` OK.
- Headless Chromium: desktop 1440, tablet 820, phone 390 for all three pages; no horizontal overflow, no console errors; logo upload and close-registration confirm exercised in the browser.

## Phase 02 delivered
- Laravel 13.44 + Inertia 3 + Vue 3.5/TS + Tailwind 4 + shadcn-vue (starter kit minus Fortify/passkeys/2FA/registration/dark mode/sidebar).
- MySQL `medical_ticket` (+ `medical_ticket_test`), app tz `Asia/Dhaka`, DB session tz `+06:00`, database session/cache/queue.
- Full domain schema migrated now: settings, sequence_counters, daily_sl_counters, tickets, print_jobs, print_job_events, kiosk_devices, device_nonces, audit_logs (indexes + unique constraints per `docs/database-design.md`), models, enums and relationships.
- Single Super Admin: model guard (`SingleAdminViolation`), env-driven seeder, `admin:setup` CLI, login throttle (5/min per email+IP), session regeneration, CSRF, hashed passwords, forced password change, logout of other sessions on password change, audit log for login/logout/failures/password change.
- Security headers middleware; Bangla-default locale with English switch (user preference + cookie); `lang/bn`.
- Professional two-tier header navigation (green nav bar, dropdown for Settings), mobile drawer, status pills, language switch, account menu; nostalgic paper-token login; dashboard reading real tables; change-password page.
- Self-hosted Noto Sans Bengali + Inter. Larger inputs (48–56px) and buttons (44–52px).
- Nav items for later phases are visibly disabled with "Soon · Phase N" (no fake screens).

## Test / build evidence (Phase 02)
- `./vendor/bin/pest` → 27 passed, 128 assertions (MySQL test DB).
- `npx vue-tsc --noEmit` → clean. `npm run build` → success.
- Headless Chromium at 1440×900 and 390×844: login, dashboard, mobile drawer, EN switch; no horizontal overflow, no console errors.

## Verified facts
- Reference images are in `reference_images/` (renamed). The ticket's large number is Bangla `০৪৫`; no serial mismatch.
- PHP 8.3.6, MySQL 8.0.46 (tz tables empty), Node 24. Not a git repo yet.

## Known notes / follow-ups
- JS chunk `format-*.js` is ~296 kB (vue-i18n with message compiler); revisit (runtime-only build/precompiled messages) in Phase 10.
- `/` redirects to `/admin`; patients use the QR link `/r/{key}`.
- vue-i18n message compiler (~55 KB source) still ships; precompiling messages could trim it (Phase 10).
- vue-tsc mis-parses `//` inside static template attributes; bind such values instead (see Institution.vue).
- Ticket preview QR box (thermal layout preview) is still a placeholder; real QR rendering on the printed ticket comes with Phase 06.

## Notes for the owner
- You changed the admin password from the default on 2026-12-01 02:28 (audit log entry `auth.password_changed`). Browser checks since then run against the separate test database so your data and password are untouched. If you forget the new password: `php artisan admin:setup`.

## Owner actions
- Upload the official institution logo: সেটিংস → প্রতিষ্ঠান (placeholder shown until then).
- Confirm production host: PHP 8.3+, MySQL 8 (not old MariaDB).
