# Munal LMS — Baseline Architectural & System Audit (Session 1 Reference)

> **Generated & Locked**: 2026-09-26  
> **Purpose**: Persistent reference of initial audit findings to prevent redundant token consumption across future sessions.

---

## 1. Architecture

```text
Frontend:
  • Runtime & Build: React 19.x + Vite 6 + TypeScript 5 (Strict Mode, Node 22 in WSL2 Ubuntu)
  • Styling & UI System: Tailwind CSS v3 with centralized design tokens in @/shared/theme, Radix UI headless primitives, Lucide React icons, Sonner toasts
  • Navigation & Routing: Custom browser-history routing shell (MainAppShell.tsx) with route guards (ProtectedRoute.tsx) and workspace dispatchers
  • Data Transport & Boundary: Ky HTTP client with automatic silent JWT refresh interceptor (/api/v1 prefix, reverse proxied in Vite)
  • Client Cache: @tanstack/react-query v5 (QueryClient) + Zustand (auth.store, lab.store, ui.store)

Backend:
  • Runtime & Framework: Python 3.12 + FastAPI + Uvicorn + Pydantic v2
  • Persistence & ORM: PostgreSQL 16 via asyncpg + SQLAlchemy 2.0 (declarative Base with UUIDPrimaryKeyMixin, TimestampMixin, LabScopedMixin)
  • Database Migrations: Alembic (Revision 475b2397161a at HEAD)
  • Caching & Task Queues: Redis 7
  • PDF Compilation: WeasyPrint with Jinja2 templates for diagnostic reports
  • Logging & Telemetry: Structlog (structured JSON) + Prometheus instrumentator

Database:
  • Single-tenant, multi-branch architecture scoped by lab_id
  • 25 core domain entities: LAB, USER, PATIENT, VISIT_ORDER, SAMPLE, REPORT, BILL, PAYMENT, DISCOUNT_RULE, REFERRAL, etc.
  • Primary keys: UUIDv4; Soft-deletion and audit timestamps on critical records

Authentication:
  • Staff & SuperAdmin: JWT Access Token (in-memory + optional 14-day persistent storage) + HTTP-only Refresh Token cookie
  • Role-Based Access Control: Hybrid RBAC (fixed workflow roles: owner, admin, reception, technician, radiologist, pathologist + dynamic granular permission overrides)
  • Public Client Access: Ephemeral tokenized link access for patient report viewing / PDF download (no client password accounts)

State Management:
  • Client state: Zustand stores (auth.store.ts, lab.store.ts, ui.store.ts) — strictly separated from server cache
  • Server cache: TanStack React Query v5

Testing:
  • Frontend: Vitest + @testing-library/react + MSW (Mock Service Worker v2)
  • Backend: Pytest + pytest-asyncio + AsyncClient (httpx) + asyncpg test database fixtures
```

---

## 2. Project Structure

```text
d:/Atulesh/Projects/Munal/
├── munalmedical-be/
│   ├── alembic/                # Database migration scripts & env.py (at HEAD: 475b2397161a)
│   ├── app/
│   │   ├── api/v1/             # 21 REST endpoint routers (auth, patients, orders, samples, bills, reports, etc.)
│   │   ├── core/               # Auth security, JWT handlers, exceptions, Redis client, RBAC guards
│   │   ├── models/             # 25 SQLAlchemy declarative ORM models
│   │   ├── repositories/       # Data access abstractions
│   │   ├── schemas/            # Pydantic v2 validation DTOs (Request / Response envelopes)
│   │   ├── services/           # Core clinical and financial business logic
│   │   ├── templates/          # WeasyPrint HTML/CSS report templates
│   │   └── main.py             # FastAPI app factory, lifespan, CORS, error handlers
│   ├── docker-compose.yml      # Local container stack: Postgres 16, Redis 7, Mailpit
│   ├── docs/                   # Tech specs, ERD, Schema reference, Work_Progress.md
│   └── tests/                  # 27 integration and unit test suites
│
└── munalmedical-fe/
    ├── src/
    │   ├── app/                # MainAppShell.tsx (Root workspace dispatcher and route orchestrator)
    │   ├── features/           # 17 domain feature modules:
    │   │   ├── auth/           # Staff login, client OTP login, password reset, RBAC engine
    │   │   ├── reception/      # Patient intake, desk queues, live counters
    │   │   ├── patients/       # Patient directory, revisit tracking, demographic intake
    │   │   ├── appointments/   # Slot scheduler, capacity grid, guest booking engine
    │   │   ├── orders/         # Diagnostic test/package catalog picker, visit order intake
    │   │   ├── billing/        # Counter register, cash/QR tender modal, itemized invoice preview
    │   │   ├── samples/        # Phlebotomy queue, barcode lookup, rejection modal, thermal label preview
    │   │   ├── results/        # Worksheet parameter entry, dynamic reference range flags (H/L/N/Critical)
    │   │   ├── radiology/      # Narrative impressions, study viewer modal, radiologist sign-off
    │   │   ├── reports/        # Verification queue, WeasyPrint PDF streaming viewer, version lineage
    │   │   ├── dashboard/      # Executive Recharts analytics, KPI grid, operational bottleneck alerts
    │   │   └── admin/          # Staff user CRUD, permission matrix, test catalog, pricing concessions
    │   ├── shared/             # Theme tokens, UI primitives, Layouts (Owner, Staff, Portal), Ky HTTP client
    │   └── tests/              # End-to-end integration tests & MSW v2 mock handlers
    └── docs/                   # Master playbooks, reference specs, missing_api_endpoints.md
```

---

## 3. Current Implementation Status

| Feature / Domain Flow | Status | Ground-Truth Finding |
| :--- | :--- | :--- |
| **Authentication & RBAC** | 🟡 **Partially Working** | Staff and Admin login flows exist; session rehydration and role mapping implemented. Needs live end-to-end verification. |
| **Patient Registration & Revisit** | 🟡 **Partially Working** | Forms and validation in place; TypeScript error on pagination metadata (`total` missing on `PaginationMetadata`). |
| **Appointment Scheduler & Guest Booking** | 🟡 **Partially Working** | Visual slot capacity grid and 4-step guest wizard built; needs live verification with backend slot generation. |
| **Visit Order Creation & Catalog** | 🔴 **Broken (Compile Error)** | `VisitBookingWizard.tsx` has type mismatches (`priceOverrides` missing on props, implicit `any`). |
| **Counter Billing & Payment Settlement** | 🟡 **Partially Working** | Cash & manual QR modal, discount rules, invoice print preview designed; requires live settlement verification. |
| **Phlebotomy & Sample Accessioning** | 🟡 **Partially Working** | Specimen collection, thermal barcode printing preview (50×25mm), and rejection modals present. |
| **Result Entry & Dynamic Range Flagging** | 🟡 **Partially Working** | Parameter worksheet with H/L/N/Critical alert badge component built; dynamic ranges wired. |
| **Radiology Narrative Reporting** | 🟡 **Partially Working** | Radiologist queue and impression drafting modal present. |
| **Pathologist Verification & PDF Lineage** | 🟡 **Partially Working** | Digital sign-off, streaming PDF viewer, versioned amendment (`v+1`) lineage modal implemented. |
| **Executive Dashboards & Analytics** | 🟡 **Partially Working** | Recharts charts, revenue area plots, and top performer cards wired to `/api/v1/dashboard/*`. |
| **Catalog & Tariff Administration** | 🔴 **Broken (Compile Error)** | `csv-helpers.ts` has strict type errors (`undefined` checks and unused variables in `CatalogAnalyteRangeModal.tsx`). |
| **Public Verification Route (`/verify`)** | 🟢 **Working** | Public route mounted in `MainAppShell.tsx` with cryptographic report card. |

---

## 4. Technical Risks

1. **Frontend TypeScript Compile Failures (P1 - High)**:
   - `tsc --noEmit -p tsconfig.app.json` errors in `CatalogAnalyteRangeModal.tsx`, `csv-helpers.ts`, `VisitBookingWizard.tsx`, `VisitOrdersView.tsx`, `PatientRegistryView.tsx`, `LiveOperationsView.tsx`, `StaffLayout.tsx`.
2. **Backend Uvicorn Worker Process Drop (P1 - High)**:
   - When libraries or files reload, worker child drop can cause port 8765 to accept TCP connections without responding until clean restart.
3. **Backend Test Suite Concurrency / Fixture Lock (P2 - Medium)**:
   - In `tests/conftest.py`, `asyncio.run(_init())` inside the synchronous session fixture can block if `munal_lms_test` does not exist or event loops conflict.
4. **Router Discrepancy (P2 - Medium)**:
   - Custom browser-history router (`MainAppShell.tsx`) used instead of `@tanstack/react-router`.

---

## 5. Testing Status

- **Frontend Tests**: 35 Vitest test suites (Vitest v1.6.1 + React Testing Library + MSW v2).
- **Backend Tests**: 27 Pytest test suites (FastAPI AsyncClient + pytest-asyncio).
- **Database Status**: PostgreSQL migration at HEAD (`475b2397161a`).

---

## 6. UI/UX Assessment

- **Design Language**: Solid Tailwind CSS clinical palette (Teal, Slate, semantic badges).
- **Worksheet Ergonomics**: Results Entry worksheet needs compact row heights and clear visual flags so technicians can rapidly tab through 30+ analytes.
- **Thermal Barcode**: Preview must strictly match 50mm × 25mm label geometry.
- **Empty States**: Explicit empty state cards needed when filters yield 0 results across lists.

---

## 7. Recommended Verification Order

1. **Phase A — Foundation & Compilation Cleanup**: Resolve TypeScript compilation errors; verify live backend health.
2. **Phase B — Authentication, Sessions & RBAC**: Test Staff & Admin logins, JWT renewal, and role redirection.
3. **Phase C — Reception & Patient Registration Flow**: Intake new patient, verify revisit indicator.
4. **Phase D — Appointment Scheduling & Guest Booking**: Test capacity grid and guest booking wizard.
5. **Phase E — Visit Order Creation & Counter Billing**: Order tests/packages with analyte-level pricing and counter settlement.
6. **Phase F — Phlebotomy, Sample Accessioning & Thermal Barcodes**: Collect specimen, test barcode preview.
7. **Phase G — Laboratory Worksheet & Result Entry**: Enter values, verify dynamic range flags.
8. **Phase H — Radiology & Pathologist Verification**: Impression drafting, senior sign-off, WeasyPrint PDF generation.
9. **Phase I — Patient Report Delivery & Public Verification**: Token link and public QR card.
10. **Phase J — Owner Dashboards, Tariffs & Audit Controls**: Financial & operational metrics.
