> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Lab & Diagnostic Orders & Results — Integration Document

> Version: 1.0.0 Last Updated: 2026-02-19 Status: 📝 Planned Spec Reference: specs/cl/specs/CL-09-lab-diagnostic-orders-results.md

**Version:** 1.0.0
**Last Updated:** 2026-02-19
**Status:** 📝 Planned
**Spec Reference:** `specs/cl/specs/CL-09-lab-diagnostic-orders-results.md`

***

## Overview

CL-09 provides lab and diagnostic order entry, result ingestion, abnormal flagging, review workflows, and trending. This document defines all integration points, event contracts, API contracts, and external integration architecture.

***

## Integration Matrix

| Integration                       | Pattern              | Direction             | Status     |
| --------------------------------- | -------------------- | --------------------- | ---------- |
| CL-01 (Patient Chart)             | Data / UI            | CL-09 → CL-01         | 📝 Planned |
| CL-05 (Medication Management)     | Data (via CL-08 CDS) | CL-05 → CL-08 → CL-09 | 📝 Planned |
| CL-08 (Clinical Decision Support) | Event                | CL-09 → CL-08         | 📝 Planned |
| PF-10 (Notifications)             | Event                | CL-09 → PF-10         | 📝 Planned |
| PF-70 (Code Libraries)            | Platform Layer       | PF-70 → CL-09         | 📝 Planned |
| External Labs                     | External API         | Bidirectional         | 📝 Planned |

***

## Internal Integration Points

### CL-01: Patient Chart Display

CL-09 orders and results are displayed in the patient chart under a "Labs & Orders" tab.

**Data Flow:**

* Chart queries `cl_orders` and `cl_order_results` filtered by `chart_id` and `organization_id`
* Results display includes abnormal flagging with color-coded indicators
* Trending view uses `result_value_numeric` for recharts time-series rendering

**Query Pattern:**

```typescript theme={null}
// Orders for a chart
const { data: orders } = await supabase
  .from('cl_orders')
  .select('*, cl_order_results(*)')
  .eq('organization_id', orgId)
  .eq('chart_id', chartId)
  .is('deleted_at', null)
  .order('created_at', { ascending: false });

// Trending query for a specific LOINC code
const { data: trends } = await supabase
  .from('cl_order_results')
  .select('result_value_numeric, created_at')
  .eq('organization_id', orgId)
  .eq('chart_id', chartId)
  .not('result_value_numeric', 'is', null)
  .order('created_at', { ascending: true });
```

### CL-05 → CL-08 → CL-09: Monitoring Protocol Flow

**Ownership:**

* **CL-05** owns medication data and `monitoring_protocol` definitions
* **CL-08** evaluates monitoring gaps using CDS rules and generates reminder alerts
* **CL-09** provides the order entry action (clinician responds to CL-08 alert by creating an order)

**Flow:**

```
CL-05: cl_medications.monitoring_protocol = { frequency_days: 90, loinc_codes: ['2823-3'] }
  ↓ (evaluated at chart_open)
CL-08: CDS engine checks last order date for loinc_code vs frequency_days
  ↓ (gap detected)
CL-08: Creates cl_cds_alerts with type='monitoring', action_url='/cl/chart/{id}/orders/new?loinc=2823-3'
  ↓ (clinician clicks alert)
CL-09: Order entry pre-populated with LOINC code from alert
```

**CDS Rule Type:** `monitoring` (new rule type in CL-08 evaluation engine)

### CL-08: Abnormal Result Alerts

When `cl_lab_result_received` event fires with abnormal\_flag != 'normal':

* CL-08 CDS engine evaluates the result
* Creates `cl_cds_alerts` with severity based on abnormal\_flag:
  * `critical_low`/`critical_high` → severity: `critical`
  * `low`/`high` → severity: `moderate`
  * `abnormal` → severity: `low`

### PF-10: Notifications

| Trigger                  | Notification Type     | Recipients        | Priority |
| ------------------------ | --------------------- | ----------------- | -------- |
| Abnormal/critical result | `lab_result_abnormal` | Ordering provider | high     |
| Result received (normal) | `lab_result_received` | Ordering provider | normal   |
| Order status change      | `lab_order_status`    | Ordering provider | low      |

### PF-70: LOINC Code Library

`cl_loinc_codes` reference table is seeded with common BH codes. Future integration with PF-70 code library for comprehensive LOINC search.

***

## Event Contracts

### cl\_lab\_order\_created

**Channel:** `cl_pm_events`
**Publisher:** CL-09
**Subscribers:** PF-10, FW automations
**Trigger:** Order status transitions from `draft` to `ordered`

```typescript theme={null}
{
  event_type: 'cl_lab_order_created';
  organization_id: string;   // UUID
  timestamp: string;          // ISO 8601
  order_id: string;           // UUID
  chart_id: string;           // UUID
  ordering_provider_id: string; // UUID
  loinc_code: string | null;
  priority: 'stat' | 'urgent' | 'routine';
  lab_id: string | null;      // UUID — reference lab
}
```

### cl\_lab\_result\_received

**Channel:** `cl_pm_events`
**Publisher:** CL-09 (ingestion edge function)
**Subscribers:** CL-08 (abnormal alert evaluation), PF-10
**Trigger:** Result record inserted via ingestion or manual entry

```typescript theme={null}
{
  event_type: 'cl_lab_result_received';
  organization_id: string;   // UUID
  timestamp: string;          // ISO 8601
  result_id: string;          // UUID
  order_id: string;           // UUID
  chart_id: string;           // UUID
  abnormal_flag: 'normal' | 'low' | 'high' | 'critical_low' | 'critical_high' | 'abnormal';
  result_code: string | null;
}
```

### cl\_lab\_result\_reviewed

**Channel:** `cl_pm_events`
**Publisher:** CL-09
**Subscribers:** PF-10
**Trigger:** Clinician signs off on a result (reviewed\_by/reviewed\_at set)

```typescript theme={null}
{
  event_type: 'cl_lab_result_reviewed';
  organization_id: string;   // UUID
  timestamp: string;          // ISO 8601
  result_id: string;          // UUID
  order_id: string;           // UUID
  chart_id: string;           // UUID
  reviewed_by: string;        // UUID
}
```

***

## External Integration: Lab Result Ingestion

### Architecture

```
External Lab System (Quest, LabCorp, local)
  ↓ (HTTPS POST with API key)
Edge Function: cl-lab-result-ingestion
  ↓ (parse HL7v2 ORU or FHIR DiagnosticReport)
  ↓ (validate org_id + lab API key)
  ↓ (map to cl_order_results rows)
  ↓ (insert via service-role client)
  ↓ (publish cl_lab_result_received event)
  ↓ (return ACK/NAK response)
```

### Edge Function: `cl-lab-result-ingestion`

**Authentication:** Custom API key per lab per organization. Stored in `cl_reference_labs.connection_config.api_key` (encrypted). `verify_jwt: false`.

**Request Format:**

```typescript theme={null}
// Option A: FHIR DiagnosticReport (JSON)
POST /functions/v1/cl-lab-result-ingestion
Content-Type: application/json
X-Lab-API-Key: <api_key>

{
  "format": "fhir",
  "organization_id": "<uuid>",
  "resource": { /* FHIR DiagnosticReport */ }
}

// Option B: HL7v2 ORU (text)
POST /functions/v1/cl-lab-result-ingestion
Content-Type: text/plain
X-Lab-API-Key: <api_key>
X-Organization-ID: <uuid>

MSH|^~\&|LAB|...
PID|...
OBR|...
OBX|...
```

**HL7v2 Parsing Strategy:**

* Custom segment parser in edge function (no external library dependency)
* Parse MSH, PID, OBR, OBX segments
* Map OBX-3 (LOINC) → result\_code, OBX-5 → result\_value/result\_value\_numeric, OBX-6 → result\_units, OBX-7 → reference\_range, OBX-8 → abnormal\_flag

**FHIR Mapping:**

* `DiagnosticReport.result[]` → individual `cl_order_results` rows
* `Observation.code.coding[0].code` → result\_code (LOINC)
* `Observation.valueQuantity.value` → result\_value\_numeric
* `Observation.interpretation` → abnormal\_flag

**Response:**

* 200 + ACK on success
* 400 + NAK on validation failure
* 401 on invalid API key
* 500 + error on server failure

### Security Controls

1. **TLS 1.2+** required for all inbound connections
2. **API key validation** against `cl_reference_labs.connection_config`
3. **Service-role client** for database operations (bypasses RLS)
4. **Audit logging** — all ingested results logged to `pf_audit_logs` with source lab identifier
5. **PHI handling** — result values stored only in RLS-protected tables; no PHI in edge function logs
6. **Rate limiting** — per-lab rate limiting via `pf_rate_limit_buckets`

***

## Security Patterns

* All CL-09 tables use composite FKs `(organization_id, entity_id)` for tenant isolation
* UPDATE RLS policies include `WITH CHECK` to prevent organization\_id modification
* DELETE is blocked on `cl_orders` and `cl_order_results` (soft delete via `deleted_at`)
* Lab ingestion uses `SECURITY DEFINER` functions when inserting via service-role to maintain audit trails

***

## Related Documents

* **Spec:** `specs/cl/specs/CL-09-lab-diagnostic-orders-results.md`
* **Task Breakdown:** `specs/cl/tasks/CL-09-TASKS.md`
* **CL-05 Integration:** `docs/architecture/integrations/CL-05-medication-management-INTEGRATION.md`
* **CL-08 Integration:** `docs/architecture/integrations/CL-08-clinical-decision-support-INTEGRATION.md`
* **Event Contracts:** `docs/architecture/integrations/EVENT_CONTRACTS.md`
* **CROSS\_CORE\_INTEGRATIONS:** `docs/architecture/integrations/CROSS_CORE_INTEGRATIONS.md`
