# Heartitude EMR — Progress Snapshot & Handoff to Next Chat

## Where the project stands

**Priorities 1–4 and 6 are closed. Priority 5 is the last remaining feature.**

| # | Priority | Status |
|---|---|---|
| 1 | Sync system (LAN + cloud, queue, conflict resolution) | ✅ Done. Queue drains, push/pull round-trips cleanly, blank-record guard in place, critical-identity-field guard in `EncounterProvider._patchActive`. |
| 2 | Lab workflow redesign | ✅ Done. Order → Send to Lab → lab completes → Pull Back to Consultation works end-to-end. `LabOrdersScreen` pops with the created `DiagnosticOrder`, `EncounterProvider.linkLabOrder` links it, `PatientQueueProvider.pushToLab` flips the status. |
| 3 | Prescription edit | ✅ Done. `PrescriptionDraft.editingPrescriptionId` drives update-in-place; `finalizeDraft` branches on `isEditing`; detail screen shows "Edit" only when status is `pending`; `_canEditPrescription` in the encounter workspace gates the section's edit action; `_findLatestPendingPrescription` re-links after a save. |
| 4 | Encounter-workspace integration | ✅ Done. Autosave through `EncounterTextField` verified against the server; `Send to Lab` button + banner; action bar uses `Wrap`; encounter persistence survives app restart; duplicate-encounter issue resolved by `getOpenEncounterForPatient(patientId, doctorId:)` with orphan adoption. |
| 6 | Retire `MessageService`'s duplicate poller | ✅ Applied. `SyncManager` is the only loop; `MessageService` is now presentation; PHP has `applyMessage` and `message` in `pullChanges`. |
| **5** | **Report attachments (radiology / oncology)** | ❌ **Not started — this is next.** |

Additional things that are done and stable:

- Cloud DB schema: `client_id` and `tenant_id` present on all sync-touched tables (patients, users, medical_records, soap_notes, prescriptions, encounters, diagnostic_orders, invoices, payments, service_items, messages).
- `SyncController.php` has `applyChange` for every entity type, with `findByClientIdOrId` hardened against missing columns.
- `DiagnosticOrder` Hive schema is settled — `attachments: List<String>?` at `@HiveField(30)` is present and unused so far.
- `DiagnosticOrder.createOrder` returns the created order (not bool); `updateOrderFields` accepts `instructions`.
- `Encounter` copyWith and providers are stable; do not casually change `hive_schema.dart` without `build_runner` regen.
- `PatientStatusValidator` and PHP `VALID_TRANSITIONS` both allow `consultation ⇄ lab` round trip.

## What's built for attachments today (context for Priority 5)

The messaging system already has a complete attachment pipeline. Priority 5 should mirror this pattern rather than reinvent it.

**Existing pieces:**

- `lib/services/attachment_service.dart` — the full Flutter-side upload/download service. Handles:
  - Picking images (gallery), photos (camera), files (via `file_picker` with allowed extensions PDF/DOC/DOCX/TXT/XLS/XLSX/PPT/PPTX).
  - Upload to LAN (`http://adminIp:8080/api/attachments/upload`) when connected to admin, else to cloud (`/attachments/upload`).
  - `downloadAttachment({attachmentId, url, fileName})` → returns local path.
  - `getThumbnail(attachmentId)` → returns a cached thumbnail File.
  - `deleteAttachment(attachmentId)` → server-side delete.
  - `cleanupCache({days = 7})` → removes files older than N days from the app documents directory.
  - MIME helpers: `getFileIcon`, `getFileColor`, `formatFileSize`.
- `lib/screens/widgets/attachment_widget.dart` — the file tile UI. Handles images (with thumbnail + download), files (with icon + size + caption), progress indicator during download, delete button gated by `showDelete`/`onDelete`.
- `heartitude-api/controllers/AttachmentController.php` — PHP endpoints:
  - `upload()` — reads `$_FILES['file']`, validates against `allowedTypes` (image/jpeg, png, gif, webp, pdf, doc, docx, xls, xlsx, ppt, pptx, text/plain), max 20 MB, generates a thumbnail for images, inserts into `attachments` table with `expires_at = NOW() + retentionDays`.
  - `download()` — checks ownership (sender or receiver), checks expiry, streams file with `Content-Type` and `Content-Disposition: attachment`.
  - `thumbnail()` — serves the cached JPEG thumbnail.
  - `delete()` — sender-only, unlinks files, soft-deletes row.
  - `cleanup()` — cron-deletes rows past `expires_at`.
- `attachments` table: id, tenant_id, thread_id, sender_id, receiver_id, file_name, file_path, thumbnail_path, mime_type, file_size, caption, expires_at, created_by, created_at, updated_at, deleted_at.
- Retention: currently `7 days` (via `$this->retentionDays = 7`).
- Routes: `POST /attachments/upload`, `GET /attachments/download`, `GET /attachments/thumbnail`, `POST /attachments/delete`.

## Priority 5 — Design and scope

### Product requirements

Attachments on diagnostic orders serve two different clinical use cases with different constraints:

**Radiology (X-ray, CT, MRI, ultrasound, mammogram, PET):**
- Large images: 2–10 MB per image, sometimes series of 20+ images.
- Retention: **permanent while the patient record is active** — radiology images are legally required medical records, not transient messages.
- Consumers: ordering doctor, radiology technician, patient (via patient app, eventually).
- Often attached *after* the order is completed (`findings` + `attachments`).

**Oncology (histology slides, PET, planning scans, treatment reports):**
- Large images + PDFs (pathology reports, treatment plans).
- Retention: same as radiology — permanent.
- Consumers: oncologist, pathologist, patient.
- Often attached during treatment (regimens), not just at diagnosis.

**Key differences from messaging attachments:**

| Aspect | Messaging | Diagnostic |
|---|---|---|
| Retention | 7 days | Permanent (while order active) |
| Who can upload | Sender | Requesting doctor, performing technician, reviewing doctor |
| Who can view | Sender + receiver only | All clinical staff in tenant (patient care team) |
| Size limit | 20 MB | Maybe 50 MB (radiology) |
| Series support | No | Yes — multiple images per order |
| DICOM | No | Maybe (future) |

### Design decisions to make

1. **New table vs. reuse `attachments`.** Recommendation: **new table `diagnostic_attachments`** with a FK to `order_id` (soft FK — no enforcement, consistent with the "no FKs" convention). Reason: retention policy differs, ACL differs (tenant-wide view vs. sender-receiver), and the `attachments` table has a `thread_id` column that would be semantically wrong.

2. **New PHP controller vs. reuse `AttachmentController`.** Recommendation: **new `DiagnosticAttachmentController.php`.** Reusing would mean a lot of conditional logic keyed on the presence of `threadId` vs `orderId`. Cleaner to fork.

3. **New Flutter service vs. reuse `AttachmentService`.** Recommendation: **new `DiagnosticAttachmentService`** that *wraps* `AttachmentService` for the file-picking and thumbnail-cache utilities, but overrides the upload URL, the query params (orderId instead of threadId), and the retention handling. This avoids duplicating ~150 lines of MIME helpers, thumbnail cleanup, and file-system code.

4. **New widget vs. reuse `AttachmentWidget`.** Recommendation: **reuse `AttachmentWidget` as-is** if its `onDelete` and `showDelete` are already parameterized (they are, based on your earlier file). It just takes a `Map<String, dynamic>` with `id`, `url`, `thumbnailUrl`, `fileName`, `fileSize`, `mimeType`, `caption`. No forking needed. This is the best news — UI-wise, Priority 5 is nearly free.

5. **Series support.** Design the `attachments` payload as a `List<Map<String, dynamic>>` on `DiagnosticOrder.attachments` (it already is). No schema change. Each entry mirrors a message attachment: `{id, url, thumbnailUrl, fileName, fileSize, mimeType, caption}`. If the doctor uploads 5 images, that's 5 entries in the list, displayed as a grid in the results view.

6. **Retention.** Add a nullable `expires_at` column on `diagnostic_attachments`. For Priority 5 v1, set it to `NULL` (never expires) — matches the "legal medical record" requirement. The existing `AttachmentController.cleanup()` cron will not touch this table.

7. **Sync.** Attachments sync by reference (URL + id). `DiagnosticOrder.attachments` is a Hive field that already serializes through `toJson`/`fromJson`. `SyncManager._resolveEntityData('diagnostic_order')` returns the full order JSON, which now includes `attachments`. So **sync is free** — no changes needed to `SyncManager` or the PHP `applyDiagnosticOrder`. That's a big win from the earlier work.

### Work breakdown for Priority 5

**Backend (~2 hours):**

1. `heartitude-api/controllers/DiagnosticAttachmentController.php` — new file, mirrors `AttachmentController` but keyed on `order_id`:
   - `upload()` — reads `$_FILES['file']`, `$_POST['orderId']`, `$_POST['caption']`. Validates MIME + size. Saves file, generates thumbnail for images, inserts into `diagnostic_attachments` with `expires_at = NULL`.
   - `download()` — verifies `order.tenant_id == user.tenant_id`, streams file.
   - `thumbnail()` — same.
   - `delete()` — verifies `user.id == order.requested_by` OR `user.role IN (admin, manager, seniorDoctor)`.
   - `cleanup()` — no-op for v1 (retention = forever). Leave the method for future use.
2. `heartitude-api/config/routes.php` — add four routes: `POST /attachments/diagnostic/upload`, `GET /attachments/diagnostic/download`, `GET /attachments/diagnostic/thumbnail`, `POST /attachments/diagnostic/delete`.
3. SQL migration:
   ```sql
   CREATE TABLE diagnostic_attachments (
     id VARCHAR(64) PRIMARY KEY,
     tenant_id VARCHAR(64) NOT NULL,
     order_id VARCHAR(64) NOT NULL,
     uploaded_by VARCHAR(64) NOT NULL,
     file_name VARCHAR(255) NOT NULL,
     file_path VARCHAR(500) NOT NULL,
     thumbnail_path VARCHAR(500) NULL,
     mime_type VARCHAR(100) NOT NULL,
     file_size INT NOT NULL,
     caption TEXT NULL,
     expires_at DATETIME NULL,
     deleted_at DATETIME NULL,
     created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
     updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
     INDEX idx_diag_att_order (order_id, tenant_id),
     INDEX idx_diag_att_uploader (uploaded_by),
     INDEX idx_diag_att_expires (expires_at)
   );
   ```
4. Increase upload size in PHP config if 20 MB is too small for radiology. The current `upload_max_filesize` and `post_max_size` in cPanel should be checked. If they're 20 MB or less, raise to 50 MB for this endpoint's sake, or use chunked upload (out of scope for v1).

**Flutter service (~2 hours):**

5. `lib/services/diagnostic_attachment_service.dart` — new file. Wraps `AttachmentService` for picking (image/gallery/camera/file) but implements:
   - `uploadToOrder({required File file, required String orderId, String? caption})` → returns `Map<String, dynamic>` matching the message attachment shape.
   - `deleteFromOrder(String attachmentId)`.
   - `downloadFromOrder({required String attachmentId, required String url, required String fileName})` → delegates to `AttachmentService.downloadAttachment`.
6. Reuse `AttachmentService.pickImage`, `pickFile`, `takePhoto`, `getFileIcon`, `getFileColor`, `formatFileSize` directly — do not duplicate.

**UI (~3 hours):**

7. `lib/screens/lab/widgets/order_attachments_section.dart` — new widget. Takes a `DiagnosticOrder` and an optional `onChanged` callback. Renders:
   - A `Wrap` or `GridView` of `AttachmentWidget` tiles.
   - An "Add attachment" FAB or button (visible when `order.status` is `inProgress`, `completed`, or `reviewed` — not when `cancelled`).
   - Tap on a non-image tile → download + open.
   - Tap on a delete icon → confirm + delete + re-save order.
8. Wire it into `LabOrderDetailScreen`:
   - Show the section between `_buildResultsSection` and `_buildStatusTimeline`, or as its own expandable card.
   - Upload is available in `inProgress` (technician attaching during work) and `completed`/`reviewed` (doctor attaching extra documents).
9. Wire it into `DoctorLabOrdersScreen`'s review sheet (`LabReviewSheet`) — the doctor should be able to view (and perhaps add a document to) attachments during review, before pulling the patient back.
10. On upload success, save the updated order through `DatabaseManager().saveDiagnosticOrder(order)` — which enqueues for sync. Reuse the existing flow. No new sync code.

**Testing (~2 hours):**

11. Single device: order test → attach X-ray image → save → reopen order → image displayed → download → open.
12. Multi-device LAN: attach on device A → sync → open on device B → image displayed.
13. Cloud-only: same as above with LAN off.
14. PDF attachment (radiology report) — download → opens in system viewer.
15. Delete attachment → confirms → disappears on both devices after sync.
16. Retention check: verify `expires_at` is `NULL` in the DB.

Total: **~1 working day** end to end.

### Files to create

| File | Purpose |
|---|---|
| `heartitude-api/controllers/DiagnosticAttachmentController.php` | New controller, mirrors `AttachmentController` |
| `lib/services/diagnostic_attachment_service.dart` | New service, wraps `AttachmentService` |
| `lib/screens/lab/widgets/order_attachments_section.dart` | New widget for the lab detail screen |

### Files to modify

| File | Change |
|---|---|
| `heartitude-api/config/routes.php` (or wherever routes are defined) | Add 4 new routes |
| `lib/screens/lab/lab_order_detail_screen.dart` | Add `OrderAttachmentsSection` |
| `lib/screens/widgets/diagnostic/lab_review_sheet.dart` | Add a compact attachments preview |
| Cloud DB | Run the `CREATE TABLE diagnostic_attachments` migration |

### Files to NOT touch

- `sync_manager.dart` — attachment sync rides on `diagnostic_order` sync, free.
- `SyncController.php` — same.
- `attachment_widget.dart` — reuse as-is.
- `attachment_service.dart` — reuse the picker + utility methods.
- `diagnostic_models.dart` — `attachments: List<String>?` already exists; it just needs to hold the richer `Map<String, dynamic>` list. **One decision:** `attachments` is currently `List<String>?` in Hive. To store `{id, url, fileName, ...}`, either:
  - **Option A:** change the type to `List<Map<String, dynamic>>?` — needs a Hive adapter regeneration and a migration for existing rows (none have attachments, so a plain regen with `null` defaults is safe).
  - **Option B:** keep `List<String>?` and store JSON-encoded maps as strings — ugly, but no schema change.
  
  **Recommendation: Option A.** Since no diagnostic orders currently have attachments (field is unused), the migration is trivially safe. Just change the type, delete old adapters, run `build_runner`, reinstall. Document it as a breaking schema change.

## Suggested prompt for the next chat

Something like:

> Continuing Heartitude EMR. Priorities 1–4 and 6 are done (sync, lab workflow, prescription edit, encounter workspace, polling cleanup). Priority 5 (report attachments for radiology/oncology) is next.
>
> Please build Priority 5 as specified in the previous handoff:
> 1. New PHP `DiagnosticAttachmentController` (mirrors `AttachmentController`, keyed on `order_id`, retention = permanent).
> 2. New `diagnostic_attachments` table (schema in the handoff).
> 3. New 4 routes.
> 4. New Flutter `DiagnosticAttachmentService` (wraps `AttachmentService` for picking + utilities, overrides upload URL + payload).
> 5. New `OrderAttachmentsSection` widget, reused `AttachmentWidget`.
> 6. Change `DiagnosticOrder.attachments` from `List<String>?` to `List<Map<String, dynamic>>?` — run `build_runner`, delete local Hive data for dev.
> 7. Wire into `LabOrderDetailScreen` and `LabReviewSheet`.
>
> Give complete files. Follow the emoji-debug convention (📎 for attachments). Match the style of `AttachmentController.php` and `AttachmentService`.
>
> Start with the PHP controller — I want to review it before we move to Flutter.

That prompt tells the next chat exactly what to build, what the invariants are, and where to start. Paste the same "Progress Snapshot" section above as context if the next chat is a fresh session.

## One thing to double-check before Priority 5 starts

**Increase PHP `upload_max_filesize` and `post_max_size` on the cPanel server.** The current `AttachmentController` is capped at 20 MB at the application level, but the PHP runtime cap may be lower. Radiology images frequently exceed 20 MB, especially CT series. Check:

```
php -i | grep -E "upload_max_filesize|post_max_size"
```

If it's 2 MB (common default on shared hosting), you must raise it in cPanel's **MultiPHP INI Editor** for the domain, or use `.user.ini` in `public_html/heartitude-api/`. Set both to `64M` at minimum. Otherwise the 20 MB application cap is meaningless — the runtime will reject the upload before PHP sees it.

Do that check **before** writing the controller so the size limits you code to are actually achievable.

---

That's the full handoff. Four priorities closed, one to go. Ping me when you've reviewed this and are ready to open the Priority 5 chat, or if anything in the snapshot doesn't match your local state.