Here's a complete handoff summary you can paste into a new chat. It captures where the project is, what's in progress, what's next, and the conventions we've established.

---

# Heartitude EMR — Project Handoff

## What this project is

A Flutter EMR (Electronic Medical Record) system for East African clinics, with a PHP/cPanel cloud backend. Multi-tenant, offline-first, syncs across LAN and cloud. Designed to minimize free-text input for clinicians, favoring structured dropdowns and forms.

- **Frontend:** Flutter (`heartitude_new`), Hive for local storage, Provider for state.
- **Backend:** PHP on cPanel (MySQL), JWT auth, REST API.
- **Cloud DB:** `ridcoltd_heartitude_cloud` at `heartitudecloud.ridcoltd.co.ke/heartitude-api`.
- **Devices:** 1 PC (admin), 2 Android devices (satellites).

## The workflow model

Clinical workflow (patient status):
```
waiting → triage → consultation ⇄ lab ⇄ pharmacy → discharge
```
Loop-backs are valid (`lab → consultation`, `pharmacy → consultation`) so doctors can review results and see the patient again.

## Priority roadmap

| # | Priority | Status |
|---|---|---|
| 1 | Sync system (LAN + cloud, entity queue, conflict resolution) | **~90% done — 1 bug left** |
| 2 | Lab workflow redesign (doctor ↔ lab, pull-back loop, structured results) | **Code-complete, untested** |
| 3 | Prescription edit fix | **Not started** |
| 4 | Encounter-workspace integration | Pending |
| 5 | Report attachments (radiology/oncology images, messaging-style) | Design sketched |
| 6 | Cleanup: retire duplicate polling loop (`MessageService` vs `SyncManager`) | Pending |

---

## Priority 1: Sync System — current state

### What's built and working

**Flutter side (in `lib/services/sync/`):**
- `sync_config.dart` — LAN config storage (admin IP, port, pre-shared key).
- `sync_entry.dart` — queue entry model with `fromQueue` factory.
- `sync_manager.dart` — singleton with composite-key queue (`entityType:entityId`), 15s/30s loop, LAN-then-cloud fallback, per-item result handling, coalescing.
- `sync_payload.dart` — wire format for push/pull, tolerates both `data`-wrapped and flat response shapes.
- `sync_status.dart` — status snapshot.
- `sync_diagnostics.dart` — read-only inspection for the Sync Diagnostics screen.

**Modified files:**
- `database_manager.dart` — `savePatient`, `saveStaff`, and all other save/delete methods accept `{bool enqueueForSync = true}`. Every save enqueues unless the caller passes `false`.
- `local_server_service.dart` — dual-role LAN transport (client for satellites, server on admin), PSR auth, `/api/sync/push`, `/api/sync/pull`, `/api/health`.
- `api_service.dart` — `syncPush(changes, deviceId)` and `syncPull({lastSync})`.
- `patient_sync_service.dart` and `staff_sync_service.dart` — pull-only, pass `enqueueForSync: false` (prevents echo loop).
- `main.dart` — `SyncManager.instance.init()` after DB init; lifecycle observer calls `syncNow()` on resume.

**Backend side:**
- `heartitude-api/controllers/SyncController.php` — full rewrite with `findByClientIdOrId`, per-entity `applyPatient`/`applyStaff`/`applyPrescription`/`applyDiagnosticOrder`/etc., per-item `results[]` response. **This file must be uploaded to the cPanel server.**
- Every table on the cloud has a `client_id VARCHAR(64)` column and index.
- `encounters` table created.

### What's still broken

**The one remaining bug:** `/sync/push` returns HTTP 200 with an empty `results` array, so `_applyPushResult` finds nothing to match and the queue never drains.

Latest evidence (from log):
```
📥 Enqueued upsert patient/51ea0521-3544-4b74-adb8-9ed9075593a2
📤 SyncManager: pushing 1 entr(ies)
🌐 Sync Push URL: .../sync/push (1 changes)
📡 Sync Push Response Status: 200
[no "☁️ Push complete" line follows]
```

**Most likely cause:** the PHP `SyncController.php` on the cPanel server is still the old version, or opcache is serving a cached copy.

### Next step: verify the PHP version on the server

1. Open `SyncController.php` in cPanel's File Manager or editor.
2. Search for `applyChange` — if it's **absent**, the old `syncChanges()` method is still running. Upload the 1c version.
3. Search for `'results' => $results` inside `pushChanges()`. Confirm it exists.
4. Restart PHP via cPanel's "Select PHP Version" panel (there's usually a Restart button).
5. Add these two `error_log` lines to `pushChanges()` for one test:
   - At the very top: `error_log("PUSH CALLED with " . count($changes) . " changes");`
   - Just before the final `ResponseHelper::success(...)`: `error_log("PUSH RESULTS BUILT: " . json_encode(array_slice($results, 0, 3)));`
6. Push once from the app. Check the cPanel error log (`~/logs/error_log` or Error Log viewer).
7. Expected: `PUSH CALLED with 1 changes` and `PUSH RESULTS BUILT: [{"client_id":"...","status":"created"}]`.
8. If log shows nothing → upload didn't take or PHP wasn't restarted.
9. If log shows `PUSH RESULTS BUILT: []` → `applyChange` is failing silently. Add `error_log("applyChange: type=" . ($change['entity_type'] ?? 'NULL'));` inside the switch.

Once this is fixed, the sync loop closes. Then Priority 1 is done.

---

## Priority 2: Lab Workflow — code complete, untested

### What's built

**Doctor side:**
- `lib/screens/widgets/diagnostic/doctor_lab_orders_card.dart` — dashboard tile with live counters (Pending / In Progress / To Review / Urgent). Auto-hides when no orders.
- `lib/screens/doctor/doctor_lab_orders_screen.dart` — tabbed view: Active / To Review / Reviewed / All.
- `lib/screens/widgets/diagnostic/lab_review_sheet.dart` — modal shown when tapping a "To Review" order. Offers "Pull Back to Consultation" or "Send to Pharmacy".

**Lab side:**
- `lib/providers/lab_provider.dart` — thin presentation layer over `DiagnosticProvider`, three-lane queries (pending, inProgress, completedToday), urgency-sorted.
- `lib/screens/lab/lab_dashboard.dart` — three-lane kanban (Pending / In Progress / Completed Today). Responsive: three columns on wide, tabbed on narrow.
- `lib/screens/lab/lab_order_detail_screen.dart` — status-aware. Pending → Start Processing. In Progress → structured result entry + Complete. Completed → read-only.
- `lib/screens/lab/widgets/structured_result_entry.dart` — per-test templates (CBC, LFT, RFT, Lipid, TFT, Cardiac, BMP, Urinalysis) with proper units and reference ranges. Falls back to generic form for unknown tests. Results stored as JSON.

**Data foundation:**
- `DiagnosticOrder` moved from settings-blob to a real Hive box (`HiveBoxes.diagnosticOrders`).
- `DiagnosticProvider` rewritten with rich query surface: `ordersByRequester`, `activeOrdersByRequester`, `awaitingReviewByRequester`, `reviewedByRequester`, `outstandingOrdersForPatient`, `startProcessing`, `completeOrder`, `reviewOrder`, `cancelOrder`.
- `DiagnosticOrder` model has `clientId`, `isSynced`, `lastSyncedAt`, `effectiveClientId` getter.
- `DiagnosticOrderDetailScreen` refactored to call granular methods (not the old `updateOrderStatus`).

**Loop-back flow:**
- `lib/services/patient_status_validator.dart` — client-side mirror of allowed transitions.
- `PatientQueueProvider.pullBackToConsultation(patientId)` and `pushToPharmacyFromLab(patientId)` — transitions with audit trail in `medicalHistory.statusTrail`.
- `EncounterProvider.resumeAfterResults()` — clears "awaiting results" state.
- PHP `PatientController.php` — `VALID_TRANSITIONS` map validates server-side.

### What's still missing / untested

- No end-to-end test of the full lab loop yet (order on doctor → lab tech completes → doctor reviews → pull back).
- Lab order creation from the doctor's `LabOrdersScreen` now flows through `DiagnosticProvider.createOrder` with `specimenType` and `notes` passed through.
- Sync of `diagnostic_order` entities depends on Priority 1 being fixed.

### Test plan when ready

Single device first:
1. Register patient, push through `waiting → triage → consultation`.
2. Create CBC lab order.
3. Open My Lab Orders → CBC under **Active**.
4. Open Lab Dashboard → CBC under **Pending**.
5. Start Processing → **In Progress**.
6. Enter Hgb 12.5, WBC 7.2, Platelets 250. Complete.
7. Back to doctor's lab screen → **To Review**.
8. Tap → review sheet → Pull Back to Consultation.
9. Patient status → `consultation`. Order → **Reviewed**.

Multi-device version: same flow with doctor on one device, lab tech on another, connected via LAN with correct PSR.

---

## Priority 3: Prescription edit fix

### The problem

`PrescriptionDetailScreen` supports "Repeat as Draft" but not **edit**. `ClinicalProvider.finalizeDraft` always creates a new prescription — it doesn't accept an existing ID to update. If a doctor tries to edit a pending prescription, they end up with a duplicate.

### The fix (three files)

**1. `lib/providers/clinical_provider.dart`:**
- Change `finalizeDraft({String? existingPrescriptionId})` — if provided, update instead of create.
- Add `loadPrescriptionIntoDraft(String prescriptionId)` — populates `currentDraft` from an existing prescription's medications and instructions.

**2. `lib/screens/doctor/prescription_detail_screen.dart`:**
- Add an "Edit" action for prescriptions in `pending` status.
- When tapped, calls `loadPrescriptionIntoDraft` then navigates to `PrescriptionDraftScreen` with an `editingPrescriptionId` parameter.

**3. `lib/screens/doctor/prescription_draft_screen.dart`:**
- Accept an optional `editingPrescriptionId` parameter.
- Title changes to "Edit Prescription" when editing.
- Add a confirmation dialog on "Discard" to prevent accidental loss.

**Also worth fixing:**
- `Prescription` model may need `clientId`/`isSynced`/`lastSyncedAt` if not already present (verify during implementation).
- `PharmacyProvider` interactions — make sure an edited prescription's status is correctly reset to `pending` if it was previously dispensed (edge case).

---

## Priority 4: Encounter-workspace integration

The `EncounterWorkspaceScreen` exists and works for consultation flows. What's missing:

- When a patient is pulled back after labs, the workspace should resume showing the "awaiting results" state clearly.
- The vitals reference card, differential section, impression section, treatment plan section, and disposition section are all built but need end-to-end testing in the loop-back context.
- When the doctor orders a lab from the encounter workspace, the order should link to the encounter (`encounter.labOrderIds`), and completion should clear the "awaiting" flag.

## Priority 5: Report attachments

Design sketched, not built:

- `DiagnosticOrder` already has an `attachments: List<String>?` field (`@HiveField(30)`).
- Plan: model attachments the same way as `MessageAttachment` — separate file storage, sync by reference. A future `DiagnosticAttachmentService` mirrors `AttachmentService` from messaging.
- Radiology and oncology workflows need image support (X-rays, CTs, scans, histology slides).
- Group D in the plan reserved a "future follow-up group" for the upload UI.

## Priority 6: Cleanup — dual polling

Two sync loops are running:

1. **`MessageService`** — old timer-based polling, hits `/messages/pull` on its own cadence. Called from `MessageService.init()` and again from `UnifiedRealtimeService.startListening()`. This is why logs show duplicate `📡 Smart polling started (30s interval)`.

2. **`SyncManager`** — the new loop, 15s/30s, calls `/sync/pull` (which currently doesn't include messages).

**Recommended fix (Option A):**
- Remove the `Timer.periodic` calls from `MessageService`.
- Add `message` entity type to `sync/pull` on the PHP side.
- `SyncManager._runTick()` merges messages into the same cycle.
- `UnifiedRealtimeService` keeps its Hive listener but stops calling `MessageService.syncMessages()`.
- UI keeps listening to `MessageService`'s streams — those still work because the underlying Hive data updates either way.

---

## Files that are stable and should not change casually

- `lib/models/hive_schema.dart` — schema is settled. Any field addition requires `flutter pub run build_runner build --delete-conflicting-outputs`.
- `lib/models/billing_models.dart`, `lib/models/diagnostic_models.dart`, `lib/models/message_models.dart` — same.
- `lib/services/sync/*.dart` — the sync infrastructure is written. Only bug-fix changes needed.
- `SyncController.php` — the 1c version is the correct one.

## Known bugs / gotchas to remember

1. **`enqueueForSync: false` must be passed** on every save inside `HeartbeatService`, `StaffSyncService.syncAllStaff`, `PatientSyncService.syncAllPatients`, and `AuthProvider.login`. Otherwise presence and pull-echo writes flood the queue.
2. **The queue key is composite** (`entityType:entityId`) — Hive `put` coalesces automatically. `_pendingBatch` returns `MapEntry<String, SyncEntry>`.
3. **`sync_payload.dart` tolerates both** `{success, results}` and `{success, data: {results}}` shapes.
4. **`SyncEntry.fromQueue`** is the correct parser for queue entries (not `fromMap`).
5. **`Patient.effectiveClientId`** and equivalents fall back to `id` for records created before the sync fields existed.
6. **`SyncManager.enqueue` in `HeartbeatService` and login flow** must always pass `enqueueForSync: false` — otherwise every 30s heartbeat creates a new queue entry.

## Conventions

- **Debug prints** use emoji prefixes: `📤` push, `📡` network, `☁️` cloud, `📥` pull/enqueue, `⚠️` warning, `❌` error, `✅` success, `🔬` diagnostic.
- **Wire format** between Flutter and PHP is camelCase for the client, snake_case for the DB. Each `apply*` method in PHP maps them explicitly.
- **Conflict resolution** — server's `updated_at` wins. Client sees `status: "server_wins"` in the push response, deletes the local change from the queue, and the next pull overwrites the local record.
- **No foreign keys** on the cloud DB — multi-tenant sync is easier without them. Referential integrity enforced at the app layer.
- **Assets** — drug knowledge base at `assets/knowledge_base/phase2/` (kb_metadata.json, drugs.json.gz, tier1.json.gz, tier2.json.gz) and diagnostic engine at `assets/knowledge_base/optimized/`.

## Where to start in the new chat

**First**, fix the push response issue. Test: does `SyncController.php` on the server contain `applyChange`? Restart PHP. Add the two `error_log` lines. Push once. Check cPanel error log.

**Once sync is confirmed working**, move to **Priority 3 (prescription edit)** — it's small, surgical, and unblocks clinical use.

**After that**, test Priority 2 (lab workflow) end-to-end with multi-device LAN sync.

**Then** tackle Priority 4 (encounter integration) and Priority 5 (attachments).

**Finally**, do the Priority 6 cleanup (retire `MessageService`'s duplicate poller).

## Key user preferences

- Prefers **complete files, not snippets**, when replacing code.
- Wants **brief explanations**, then the code.
- Values **structured input over free text** — always look for dropdown/selection opportunities.
- Test environment: **1 PC + 2 Android devices** on same WiFi.
- Sync frequency: **15–30 seconds** is acceptable.
- Conflict policy: **server timestamp wins, losing device gets notified**.
- Patient status flow is **server-authoritative** (with client-side validation mirroring for immediate feedback).

---

That's the complete state. Paste this into a fresh chat and you can resume seamlessly.