# CompleCare API

Laravel 12 REST + WebSocket API for the CompleCare care platform. Serves:

- **Mobile app** (`mobile-wireframe/` — React Native + Expo) — patient, caregiver, nurse, doctor, specialist
- **Web modules** (`src/portals/*` — React 19 + Vite) — patient, hospital, company, platform admin
- **Partner webhooks** — Paystack, Hubtel, Twilio, hospital EMR systems

This is an **API-only** Laravel app. No Blade views, no Filament. The Platform Admin UI is a React SPA at `src/portals/admin/`.

---

## Stack

| Layer | Tech |
|---|---|
| Runtime | PHP 8.3 · Laravel 12 |
| DB | PostgreSQL 16 (with logical replicas for reporting) |
| Cache · queue · sessions | Redis 7 |
| Auth | Sanctum (SPA cookie + bearer tokens) · Spatie Permission for RBAC |
| Background jobs | Horizon (queues) · Octane (perf) |
| Realtime | Reverb WebSockets |
| Storage | S3 + KMS for PHI |
| Search | OpenSearch (later) |
| Comms | Twilio · Hubtel/mNotify · Postmark · FCM (Expo) |
| Payments | Paystack (primary) · Hubtel · MTN MoMo |
| Observability | Sentry · Pulse · Telescope (dev) · OpenTelemetry |
| Types pipeline | Spatie Data → TypeScript Transformer → `resources/types/types.ts` |

See `composer.json` for the full dep list.

---

## Quick start (local dev)

```bash
# 1. Install deps
composer install

# 2. Bootstrap env
cp .env.example .env
php artisan key:generate

# 3. Local Postgres + Redis (Docker)
#    (Sail is included for full Docker stack)
./vendor/bin/sail up -d

# 4. Migrate + seed
php artisan migrate --seed

# 5. Generate TS contracts for mobile + web
php artisan typescript:transform
# Output → resources/types/types.ts

# 6. Run the API
php artisan serve            # http://127.0.0.1:8000
php artisan horizon          # background workers
php artisan reverb:start     # realtime WS
php artisan octane:start --watch   # perf-mode dev (optional)

# 7. Run tests
composer test
composer lint
composer stan
```

---

## Directory layout

```
backend/
├── app/
│   ├── Console/Commands/            # artisan commands
│   ├── Domain/                      # ★ DDD-style bounded contexts
│   │   ├── Auth/                    # login, OTP, password, biometric pairing
│   │   ├── Tenant/                  # multi-tenancy (CompleCare HQ, hospitals, companies)
│   │   ├── Audit/                   # immutable audit ledger
│   │   ├── Patient/                 # patient + caregiver records (PHASE 2)
│   │   ├── Provider/                # nurse, doctor, specialist (PHASE 2)
│   │   ├── Catalog/                 # admin-driven catalogs (PHASE 2)
│   │   ├── CarePlan/                # plan generation + revisions (PHASE 3)
│   │   ├── Session/                 # Engagement Ledger (PHASE 3)
│   │   ├── Vitals/                  # readings + thresholds (PHASE 3)
│   │   ├── MentalHealth/            # PHQ-9 / GAD-7 / mhGAP (PHASE 3)
│   │   ├── Escalation/              # rules + rotation (PHASE 4)
│   │   ├── Notification/            # multi-channel orchestrator (PHASE 4)
│   │   ├── Subscription/            # plans, grace, defaulter (PHASE 4)
│   │   ├── Billing/                 # Paystack webhooks (PHASE 5)
│   │   └── Resource/                # patient + clinician content (PHASE 5)
│   ├── Http/
│   │   ├── Controllers/Api/V1/      # API surface — versioned
│   │   ├── Middleware/              # tenant scope, RBAC, rate limit, audit
│   │   ├── Requests/                # FormRequests for validation
│   │   └── Resources/               # API JSON shape
│   ├── Providers/
│   └── Support/                     # shared helpers (PHI sanitization, IDs)
├── bootstrap/
├── config/
├── database/
│   ├── migrations/
│   ├── seeders/
│   └── factories/
├── public/                          # only index.php for the API
├── resources/
│   └── types/                       # generated TypeScript types for mobile + web
├── routes/
│   ├── api.php                      # all routes here
│   ├── channels.php                 # broadcast auth (Reverb)
│   └── console.php
├── storage/
└── tests/
    ├── Feature/                     # API + workflow tests (Pest)
    └── Unit/
```

The **Domain/** layout is non-standard for Laravel but pays off as the app grows. Each bounded context owns its models, services, data DTOs, events, jobs, and policies — independent of `app/Http/`. Controllers in `Http/Controllers/Api/V1/` are thin: they validate, dispatch to a domain service, transform the result.

---

## Phased build plan

| Phase | Scope | Status |
|---|---|---|
| **1 — Foundation** | Repo skeleton · composer · env · config · auth (Sanctum) · tenant scoping · RBAC (Spatie) · audit log · TypeScript pipeline · CI scaffolding | ✅ done |
| **2 — Domain core** | Patient + Caregiver + Provider models · Admin-driven catalogs (Conditions, TriageQuestions, CarePackages, Kit, VitalsThresholds, EscalationLevels, GraceRules, NotificationRules) · `/api/v1/catalogs/*` | ✅ done |
| **3 — Workflow heart** | CarePlan + CareAssignment + Session (5-gate Engagement Ledger) + Evidence + Notes + Vitals + MentalHealth + Tasks + Escalations · first-session rule · `/api/v1/patients/*` · `/api/v1/sessions/*` · `/api/v1/vitals` · `/api/v1/mental-health` | ✅ done |
| **4 — Reactive systems** | EscalationEngine + NurseRotationService · NotificationOrchestrator + Hubtel/Expo/Log drivers · Pre-session 24h/2h/15min jobs · Missed-session SLA · DefaulterStateMachine (incl. high-risk safe closure) · Reverb broadcasts (escalation/session/task) | ✅ done |
| **5 — Money + comms** | **Africa's Talking** voice + SMS + WhatsApp · **Hubtel** voice failover for critical calls · **Daily.co** video with on-demand recording + consent gate · Webhooks (AT/Daily/Paystack/Hubtel) with HMAC signature verify · Paystack subscriptions (cards + MoMo via MTN/Vodafone/AirtelTigo) · Reverb-based in-app messaging · Resources library · FHIR R4 Patient export stub | ✅ done |
| **5.5 — Persona surface** | **Patient/Caregiver:** OTP signup + unified onboarding, dashboard, self-record vitals/MH, reschedule/cancel, multi-patient switcher, caregiver invites · **Nurse:** today view, tasks CRUD, escalation ack/resolve, availability · **Doctor:** queue, decision context, care-plan sign-off (immutable rule snapshots), specialist referrals · **Specialist:** dedicated queue, schedule + complete consult (auto-writes note + follow-up task) · **Hospital admin:** discharge enrollment, cohort, sponsor billing · **Company admin:** aggregate cohort with **suppress+warn floor** · **Platform admin:** catalog CRUD (10 kinds incl. medications), tenant/user/role/roster mgmt, audit viewer · **Medications domain:** catalog + orders (prescribe/revise/pause/discontinue) + administrations (adherence tracking, 3-miss-in-7d alert) · **Patient sub-resource reads:** care-plans, vitals, MH, notes, escalations, tasks, medications · **/me:** /provider, /notifications (activity feed derived from existing tables) | ✅ done |
| **5.5g — Complete coverage** | **Med reconciliation:** patient/caregiver self-report (catalog or free-text) → clinician verify/reject/clarify · **Patient/Caregiver completeness:** profile/preferences/quiet hours/locale, privacy + data-sharing toggles, account deletion request, payment history, emergency contacts, saved resources, presigned file uploads (S3), session requests, care-plan acceptance/decline, side-effect reports (severe→auto escalation), refill requests · **Caregiver:** invites sent/received, payer flow, context switch, consent summary · **Nurse:** propose care plan, nurse-friendly schedule, handoff (SBAR), unavailability windows, incoming reassignment queue + decline, ad-hoc notes, refill review, side-effect review, KPIs · **Doctor + Specialist:** availability calendar slots, history (plans/referrals/consults), specialist longitudinal patient view, ad-hoc notes, KPIs · **Hospital admin:** create/manage hospital nurse accounts, quality metrics, sponsor agreements, CSV report export, broadcasts, activity feed · **Company admin:** policy + cohort floor, department slices, billing detail, engagement timeline, employee invite/remove, broadcasts · **Platform admin ops:** audited impersonation, failed jobs viewer + retry/purge, queue + system health, feature flags, FHIR bulk export, notification rule dry-run, audit chain re-anchor · **Cross-cutting:** patient search (blind-index + facets), read receipts (threads + activity feed), file uploads, notification preferences | ✅ done |
| **5.5h — Final closure** | **Provider training:** versioned modules + assets + quizzes + mandatory assignments + progress + auto-issued certificates with public QR-verify · **Patient resources:** read/open/progress/complete tracking + condition-targeted recommendations · **Auth completeness:** Expo push device register/list/revoke, password forgot/reset/change, phone re-verify OTP, email re-verify OTP, 2FA TOTP (begin/confirm/disable + recovery codes) · **Labs domain:** labs_catalog (LOINC, ref ranges) → orders → collect → results → review with critical-result auto-escalation · **Kit inventory:** per-patient issuance, serials, training flag, replacement requests · **Clinician calendar:** unified `/me/calendar` (sessions + slots + tasks + unavailability) · **Health goals:** set/track/log/achieve/abandon · **Right-to-access:** `/me/access-log` (patient sees who viewed/edited their record) · **Patient transfer:** cross-tenant move (initiate→approve→complete) · **Bulk jobs:** admin CSV-driven import queue · **Message search:** in-thread keyword search | ✅ done |
| **5.5i — Renderer-driven completeness** | **MH bands catalog** (PHQ-9/GAD-7/mhGAP score→band + item rules, admin-configurable, evaluator reads catalog) · **Training admin CRUD** (versioned modules, assets, quizzes, assignments, stats) · **Tenant deep config** (subdomain, locale, timezone, currency, phone country code, feature toggles, allowed packages, addon overrides, retention, HIPAA alignment, hashed API keys) · **Tenant catalog overrides** (per-tenant escalation/notification/grace) · **Cross-tenant oversight** (sponsorships, policies, subscriptions, utilisation) · **Custom roles + permissions per tenant** · **Generalized ProviderRotationService** (nurse/escalation_nurse/doctor/specialist with working_hours + unavailability + capacity + specialty subtype) · **Risk-band catalog + RiskBandService** (admin-configured composite scoring) · **Small catalogs** (symptoms, closure reasons, locales, medication frequencies) · **Tenant templates** (Hospital/Company profiles that auto-seed catalog overrides + sponsorships/policies + branding) | ✅ done |
| **6 — Hardening** | Pen-test pass · OWASP audit · Pulse dashboards · DR drill · Performance tuning · Octane prod · Multi-region readiness · BulkImportJob worker · CertificateGenerator PDF worker · Labs admin catalog (held by user) | ⏳ |

---

## Security posture (OWASP Top 10 — continuous)

| Class | Where it's enforced |
|---|---|
| A01 Broken Access Control | RBAC (Spatie) + tenant row-level scoping middleware + policy on every PHI route. Deny-by-default. |
| A02 Cryptographic Failures | TLS 1.3 · Argon2id passwords · KMS at rest · column-level encryption for National ID + mental scores |
| A03 Injection | FormRequest validation + Eloquent parameterised queries + zod-equivalent Spatie Data DTOs |
| A04 Insecure Design | Threat models in `docs/threat-models/` per feature; security review PR-gating on PHI/payment touches |
| A05 Misconfig | IaC-only changes; CIS-benchmark scan; SSM-only access; secrets never in env files committed |
| A06 Vulnerable Components | Dependabot + Snyk on every PR; SBOM on every release |
| A07 ID & Auth Failures | MFA mandatory for clinicians/admins (Google2FA); OTP rate-limited; passkeys planned |
| A08 Software/Data Integrity | Signed container images (Cosign); signed webhooks (HMAC); hash-chained audit log; immutable session records |
| A09 Logging Failures | Centralised logs (Loki); PII redaction at logging boundary; every PHI read writes an audit row |
| A10 SSRF | Outbound proxy with allowlist; no fetch-by-user-supplied-URL |

Every controller/service/job file carries a `// SECURITY:` comment header listing the OWASP categories that apply — same convention as the mobile wireframe.

---

## Operational invariants (baked into the API contract)

1. **Every patient has an owner** — `patients.primary_nurse_id` is NOT NULL. Rotation history preserved in `assignments`.
2. **Every task has a due time** — every Task / Session / Notification has `due_at`; SLA jobs monitor and auto-rotate.
3. **Every session has evidence** — `sessions.completed_at` only writes when all 5 gates pass (call evidence + structured note + vitals rule + risk + next action). Server-side enforced; client cannot bypass.
4. **Every clinical rule is admin-configurable** — catalogs versioned with `effective_from/until`; clients pin to a version per request. No hardcoded clinical constants in code.

---

## Type sharing with clients

Backend is source-of-truth for shape. After every domain change:

```bash
php artisan typescript:transform
```

emits `resources/types/types.ts`. The mobile + web packages depend on `@complecare/contracts` published from this file. Zero drift between PHP DTOs and TypeScript interfaces.

---

## What's NOT in this repo

- Admin Blade views or Filament panels (admin SPA is React, separate workspace)
- Marketing website (WordPress, separate stack)
- Anything that touches the device-level health APIs (HealthKit / Google Health Connect) — that's mobile-side
