Outbound HL7 Overview
Overview of outbound HL7 message generation APIs and message-type documentation.
HL7 Outbound Overview
Outbound HL7 integrations generate billing, order, patient, specimen, and result messages from LiveHealth/Crelio data. The detailed configuration for each message family now lives in its own page.
Scope
This section documents the legacy outbound HL7 APIs implemented in livehealthapp/labs/views.py. The APIs are used by SFTP/webhook-style integrations where LiveHealth prepares an HL7 message and optionally pushes it to a downstream listener such as Mirth over TCP.
The documentation focuses on two high-use endpoints:
| Endpoint | Function | Purpose |
|---|---|---|
/integration/sftp/hl7/2_3/send_hl7_data/ | sftp_HL7_payload_generation_function | Report-wise HL7 generation for DFT, ORM, OUL, ADT, and ORUR01. |
/integration/sftp/hl7/2_3/send_billwise_hl7_data/ | sftp_billwise_HL7_payload_generation_function | Bill-wise ORUR01 generation and bill-wise DFT forwarding. |
These endpoints are legacy in naming, but still contain the active compatibility behavior for multiple vendor integrations. They combine HL7 generation, vendor-specific mapping, socket delivery, activity logging, and response rendering in one flow.
Mental Model
A request to these APIs is not a raw HL7 payload. It is a JSON request that identifies a report or bill, includes the serialized report/result data, and supplies integrationDetails flags. The API then reloads canonical database records, builds the HL7 segments, normalizes the message, and either returns it or sends it to the configured TCP destination.
Data Sources Used During Generation
The API reloads most business context from the database even when similar values are present in the request. The request is primarily used to choose the flow, supply result arrays/base64 payloads, and override integration behavior.
| Data area | Source used by the API | Used for |
|---|---|---|
| Report identity | labReportId, labReportDetails, or testDetails | Resolving the first labReportRelation record for report-wise generation. |
| Bill identity | bill_id | Loading all synced, non-dismissed reports for bill-wise ORU and creating bill-wise DFT forwarding payloads. |
| Patient demographics | labReportRelation.userDetailsId and selected request fallbacks | PID, contact, address, DOB, gender, race, ethnicity, national id, passport, patient ids. |
| Bill/order data | labReportRelation.billId, billingInfo, BillingICD | ORC, OBR, FT1, DG1, visit id, order number, bill source, ICD and procedure mapping. |
| Organization/provider data | orgId, docId, branch records | Sending/ordering facility, provider identifiers, organization address/contact, branch override behavior. |
| Results | reportFormatAndValues, reportDetails, report format metadata | OBX, NTE, abnormal flags, reference ranges, result status, base64 report blocks. |
| Insurance | PatientInsurance or UserBillInsurance | IN1 segments and insurance-required validation. |
| Attachments/TRF | Attachment models and TRF endpoints | ED OBX blocks for PDF/image/base64 documents. |
Runtime Contract
| Step | Behavior |
|---|---|
| Request parsing | sftp_HL7_payload_generation_function accepts either a JSON object or a one-item JSON array and uses the first object when an array is received. |
| Message control id | A 14-digit value is derived from uuid.uuid4().int; processingId defaults to P. |
| Timestamp format | HL7 timestamps are built as YYYYMMDDHHMMSS; some branches convert report, bill, sample, and accession dates to the lab timezone. |
| Message cleanup | Before return/send, line breaks and selected HTML tokens are normalized; <br> tags are removed or converted depending on branch. |
| ID enrichment | update_message_with_ids(jsonData, message, "HL7") is applied before final response/send in the main outbound paths. |
| Transport | If a non-zero port is resolved, the message is sent to host:port by TCP socket. If not, the generated HL7 is returned with sent_to_mirth: false. |
| Logging | Successful generation writes activity log entries for webhook triggering and generated HL7 text. |
| Error handling | Unhandled exceptions return status 500 with the generated message-so-far and traceback text. |
Report-Wise vs Bill-Wise Behavior
| Behavior | Report-wise endpoint | Bill-wise endpoint |
|---|---|---|
| Primary identifier | labReportId for ORUR01/OUL; first labReportDetails[].labReportId or testDetails[].labReportId for others. | bill_id. |
| Supported payloads | DFT, ORM, OUL, ADT, ORUR01. | ORUR01 and DFT. |
| Report selection | Starts from one report and often uses its bill context. | Loads all reports on the bill where dismissed=0, sampleRedrawFlag=0, and isSynced=1. |
| DFT behavior | Builds DFT in-process for the report/bill context. | Builds a webhook payload and forwards it to the configured DFT URL; it does not directly build the final DFT message in this function. |
| ORU behavior | Builds one report-oriented result message. | Builds a consolidated bill-wise ORU from the supplied/report-derived result details. |
Response Shape
Successful generation returns JSON similar to:
{
"status": 200,
"message": "MSH|^~\\&|...",
"file Name": "",
"sent_to_mirth": true
}For report-wise generation the response may also include MSH_1 and MSH_2. Bill-wise DFT forwarding returns the generated forwarding payload instead of the final HL7 text:
{
"status": 200,
"message": "DFT HL7 sent successfully",
"sent_to_mirth": false,
"payload": {
"Status": "Bill Generation HL7 for SFTP",
"bill_id": 12345,
"payloadType": "DFT"
}
}Operational Cautions
- The
DFTbranch in the report-wise SFTP endpoint readshostandportfrom the root request, while most other branches read them fromintegrationDetails. integration_nameis case-normalized in many branches and activates destination-specific behavior. Treat it as a behavior switch, not only a label.segmentsis an allow-list for optional segment groups. Some base segments are always produced even if the list is empty.- Some branches return status
200for business skips, for example no insurance in the DFT SFTP branch. Consumers should inspect both HTTP status and response body. - Because socket delivery happens synchronously in the request, an unreachable host or port can raise an exception and return status
500.
Integration Name Specifications
The outbound generators use integration_name as a compatibility switch for receiver-specific HL7 structure. ORU flows may also derive an integration_identifier from the order number with integration_differentiator; that identifier is mainly used for dynamic port selection and a few receiver-specific ORU layouts.
| Integration name / identifier | Applies to | Specification |
|---|---|---|
ATHENA | DFT, report-wise ORUR01, bill-wise ORUR01 | DFT uses Athena-aware insurance relation handling and can split comma-separated report integration codes into multiple FT1 rows. ORU validates that the derived/configured identifier belongs to Athena, allows sender/facility overrides, formats provider name as last/first, applies Athena-specific result/specimen behavior, and can route bill-wise output through athena_port. |
EMED | DFT, report-wise ORUR01, bill-wise ORUR01 | DFT prefers report integration code and falls back to procedure/test code. ORU uses the configured lab name as the sending application, maps sending facility to the ordering facility, and uses the sending facility as the receiving facility in the bill-wise branch. |
CERNER | ORM, ADT | ORM uses Cerner-specific patient, visit, order, and observation identifiers including MRN/CMRN/FIN-style fields, collection/cancel/dispatch statuses, and optional HLA/outsourced message routing through HLA_port. ADT uses Cerner-specific PID/PV1 construction and can add medical history, height, and weight observations. |
CPL | ORM | Sets billing type as insurance, credit, or patient pay based on insurance and bill-payment context, and adds configured order comments as NTE content. |
SIGLO | ORM | Prefixes patient contact with country code and prefers national id/SSN formatting expected by the destination. |
TRIBAL | ORM | Updates the bill order number from the manual sample/accession identifier and changes OBR placer/filler ordering for the receiver. |
EMDEON | report-wise ORUR01 | Builds an EMDEON/DOH-style ORU with receiving application FILE, sending application fallback ECL, CLIA-aware sending facility values, dynamic port lookup by integration identifier, and optional secondary DOH routing through doh_port. |
expirity identifier | report-wise ORUR01 | Uses a derived/configured integration_identifier to change ORC placement and report-order formatting inside the EMDEON-style ORU flow. |
ellkay identifier | report-wise ORUR01 | Uses a derived/configured integration_identifier to change OBR layout and method/comment handling inside the EMDEON-style ORU flow. |
CALREDIE | report-wise ORUR01 | Applies public-health style MSH/PID/ORC/OBR formatting with CLIA/LIMS identifiers, provider NPI formatting, normalized race/ethnicity fields, and public-health OBX/SPM construction. |
LOUSIANA | report-wise ORUR01 | Uses the same public-health branch as CALREDIE with Louisiana-specific contact formatting, address shaping, LOINC suffixing, and abnormal-flag vocabulary. The code uses the spelling LOUSIANA; configuration must match that value unless the implementation is changed. |
ILLINOIS | report-wise ORUR01 | Adjusts CLIA/facility formatting and can emit SFT software details when configured. |
TEXAS | report-wise ORUR01 | Uses Texas-specific MSH/PID/ORC/OBR structure, CLIA/OID identifier placement, provider/contact formatting, and LOINC-oriented test descriptions. |
MARYLAND | report-wise ORUR01 | Prefixes sending application with organization context and uses Maryland-specific PID, ORC, OBR, and LOINC/test-description formatting. |
NABIDH | report-wise ORUR01 | Uses integration code as the test code where present, sends nationality/national-id visit context, formats sample type with code/name pairs, and has special base64/CAP-accreditation OBX behavior. |
CATALYST | report-wise ORUR01, bill-wise ORUR01 | Uses the lab bill id as the placer/order identifier in ORU segments where this receiver expects bill-level identifiers instead of report-level ids. |
ECW | report-wise ORUR01, bill-wise ORUR01 | Appends pathologist name and report comments as NTE content after result/document OBX generation. |
| default / blank | All supported payloads | Uses the generic outbound segment templates and direct host/port routing from the applicable request location. Configure explicit integration names only when the receiver needs one of the behaviors above. |
Configuration Guidance
| Field | Guidance |
|---|---|
integration_name | Use the exact receiver switch expected by the branch. The implementation compares most values case-insensitively, but spelling still matters for values such as LOUSIANA. |
integration_identifier | Use when one integration setup needs dynamic ORU routing by destination identifier. If blank, the report-wise ORU branch derives it from the order number prefix before integration_differentiator. |
integration_differentiator | Defaults to -; use it only when order numbers encode destination routing, for example ATHENA-12345. |
<identifier> port keys | ORU dynamic routing can look up integrationDetails[integration_identifier]; some branches also use dedicated keys such as athena_port, doh_port, and HLA_port. |
sendingApplication / sendingFacility | These are normal MSH fields, but several integration names override them. Verify the generated MSH after enabling a receiver-specific branch. |
Message Type Pages
| Payload type | HL7 message | Documentation | Typical trigger |
|---|---|---|---|
ADT | ADT | ADT | Patient/event information outbound |
ORM | ORM^O01 | ORM | Order creation, update, cancellation, or resend |
ORUR01 | ORU^R01 by default | ORUR01 | Result submission |
OUL | OUL result/specimen message | OUL | Specimen/result outbound with OUL formatting |
DFT | DFT^P03 | DFT | Billing/charge outbound |
Outbound Routing Flow
Purpose
This document describes the outbound HL7 generation APIs used by the livehealthapp repository for billing, order, patient, specimen, and result transmission.
It covers the following implementation entry points:
| API | Function | File | Primary use |
|---|---|---|---|
/integration/sftp/hl7/2_3/send_hl7_data/ | sftp_HL7_payload_generation_function | labs/views.py | SFTP-triggered HL7 generation for DFT, ORM, OUL, ADT, and ORUR01. |
/integration/sftp/hl7/2_3/send_billwise_hl7_data/ | sftp_billwise_HL7_payload_generation_function | labs/views.py | Bill-wise ORU generation and bill-wise DFT forwarding. |
/integration/hl7/send_dft_hl7_data/ | DFT_HL7_payload_generation_function | labs/integration_functions.py | Direct DFT P03 generation for HL7 2.3 style billing integrations. |
/integration/hl7/2_4/send_dft_hl7_data/ | DFT_HL7_2_4_payload_generation_function | labs/integration_functions.py | Direct DFT P03 generation for HL7 2.4 style billing integrations and vendor-specific DFT behavior. |
Message Types
| Payload type | HL7 message | Typical trigger | Main segments |
|---|---|---|---|
ADT | ADT | Patient/event information outbound | MSH, PID, optional PV1, OBX, NTE |
ORM | ORM^O01 | Order creation, update, cancellation, or resend | MSH, PID, PV1, ORC, OBR, optional AL1, IN1, GT1, RXO, OBX, FT1, DG1, CST, NTE |
ORUR01 | ORU^R01 by default | Result submission | MSH, PID, ORC, OBR, OBX, SPM, optional PV1, AL1, IN1, FT1, DG1, RXO, CST, NTE |
OUL | OUL result/specimen message | Specimen/result outbound with OUL formatting | MSH, specimen and result segments, optional SPM, OBX, NTE, CST |
DFT | DFT^P03 | Billing/charge outbound | MSH, EVN, PID, PV1, FT1, DG1, optional IN1, GT1, OBX, custom vendor segments |
Request Shape
Most outbound calls expect JSON in the request body. The common structure is:
{
"payloadType": "ORUR01",
"labReportId": 123456,
"labReportDetails": [],
"reportDetails": [],
"dictionaryId": 0,
"integrationDetails": {
"host": "127.0.0.1",
"port": 5000,
"versionId": "2.4"
}
}Bill-wise ORU/DFT uses bill_id as the primary identifier:
{
"payloadType": "ORUR01",
"bill_id": 12345,
"billId": 1001,
"reportDetails": [],
"integrationDetails": {
"host": "127.0.0.1",
"port": 5000
}
}Common Runtime Behavior
- If
portis configured and non-zero, the generated HL7 is sent over TCP socket tohost:port. - If
portis missing or zero, the API can still return the generated HL7 message without sending it to Mirth or another TCP listener. update_message_with_ids(jsonData, message, "HL7")is applied before final return/send in the main outbound paths.- HTML line break tags and some report formatting tokens are normalized before sending.
integrationDetailsis the main configuration object for flags.- Some functions read
hostandportfrom the root payload, while others read them fromintegrationDetails. See the API-specific notes below.
API-Specific Notes
/integration/sftp/hl7/2_3/send_hl7_data/
Function: sftp_HL7_payload_generation_function
Supported payloadType values:
DFTORMOULADTORUR01
Identifier rules:
ORUR01andOULreadlabReportIdfrom the root payload.- Other payloads read the first
labReportIdfromlabReportDetails; if empty,testDetailsis used as a fallback. - If no report id can be resolved, the API returns
400withlabReportId is not valid.
Transport rules:
ORM,OUL,ADT, andORUR01primarily readhostandportfromintegrationDetails.- The
DFTbranch in this function readshostandportfrom the root payload.
/integration/sftp/hl7/2_3/send_billwise_hl7_data/
Function: sftp_billwise_HL7_payload_generation_function
Supported bill-wise behavior:
ORUR01: Generates one bill-wise ORU message using all synced, non-dismissed reports for the bill.DFT: Builds a bill-wise payload and forwards it to a configured URL, defaulting to/integration/hl7/send_dft_hl7_data/.
Identifier rules:
- Requires
bill_id. - If
bill_idis missing, the API returns400withbill_id is not valid.
DFT forwarding rules:
- Reads
host,port, and optionalurlfromintegrationDetails. - Sends a webhook payload containing patient, billing, order, report, and integration details to the configured DFT URL.
/integration/hl7/send_dft_hl7_data/
Function: DFT_HL7_payload_generation_function
Supported payload:
payloadType: "DFT"
Behavior:
- Generates
DFT^P03. - Uses HL7 version
2.3.1by default. - Supports insurance validation, bill-level insurance, timezone conversion, and NextGen-specific segment ordering/formatting.
- Reads
hostandportfrom the root payload.
/integration/hl7/2_4/send_dft_hl7_data/
Function: DFT_HL7_2_4_payload_generation_function
Supported payload:
payloadType: "DFT"
Behavior:
- Generates
DFT^P03. - Supports vendor-specific DFT behavior for integrations such as
PGM,ATHENA,CERMAK, and custom dynamic segment sequencing. - Reads
host,port, and dynamic integration-specific port keys fromintegrationDetails. - Supports additional DFT options such as outsource mapping, custom segment order, base64 result attachment, profile ICD mapping, and drug-wise FT1 generation.
Configuration Key Naming
Different branches expect different key styles.
| Branch | Expected style | Examples |
|---|---|---|
ORM, ADT, ORUR01, DFT | camelCase and mixed legacy keys | sendingApplication, receivingFacility, labName, BillingInsurance |
OUL | snake_case | sending_application, receiving_facility, lab_name |
| DFT 2.4 dynamic port | integration name as key | PGM, ATHENA, or any configured integration_name |
| ORU bill-wise dynamic port | lower-case integration identifier as key | integrationDetails[integration_identifier] |
If the wrong key style is sent, the code usually falls back to blank/default values.
Common Configuration Keys
| Key | Type | Default | Used by | Description |
|---|---|---|---|---|
integration_name | string | "" | All major branches | Enables vendor-specific formatting and validation. |
sendingApplication | string | varies | DFT, ORM, ADT, ORUR01 | Populates MSH-3. |
sending_application | string | "" | OUL | OUL snake_case equivalent of sending application. |
sendingFacility | string | org code / "" | DFT, ORM, ADT, ORUR01 | Populates MSH-4 or related sending facility fields. |
sending_facility | string | "" | OUL | OUL snake_case equivalent of sending facility. |
receivingApplication | string | "" | DFT, ORM, ADT, ORUR01 | Populates MSH-5. |
receiving_application | string | "" | OUL | OUL snake_case equivalent of receiving application. |
receivingFacility | string | "" | DFT, ORM, ADT, ORUR01 | Populates MSH-6. |
receiving_facility | string | "" | OUL | OUL snake_case equivalent of receiving facility. |
host | string | "" | Most outbound paths | TCP destination host. |
port | number/string | 0 or "" | Most outbound paths | TCP destination port. |
versionId | string | 2.3.1 or 2.4 | Most outbound paths | HL7 version populated in MSH-12. |
segments | list | varies | ORM, OUL, ADT, ORUR01 | Optional segment inclusion list. |
lab_time_zone | boolean | 0 | DFT, ORM, ORUR01 | Converts dates to the configured lab timezone before HL7 formatting. |
BillingInsurance | boolean | 0 | DFT, ORM, ORUR01 | Uses bill-level insurance mapping instead of default patient insurance records. |
is_insurance_enable | boolean | 0 | DFT, ORUR01 | Requires insurance data before generating HL7. |
Recommended Segment Configuration
Use the smallest segment list required by the receiving system.
| Use case | Suggested segment list |
|---|---|
| Basic ORM order | ["PV1"] or default mandatory segments only |
| ORM with insurance and diagnoses | ["PV1", "IN1", "DG1"] |
| ORM with medications | ["PV1", "RXO"] plus prescribed_drugs: 1 |
| ORM with custom operational metadata | ["PV1", "CST"] |
| Basic ORU result | [] plus default ORC/OBR/OBX/SPM behavior |
| ORU with visit and insurance | ["PV1", "IN1"] |
| ORU with attachments/TRF | attachments: 1 and/or trf_flag: 1 |
| DFT with insurance | is_insurance_enable: 1, BillingInsurance as required |
Validation and Failure Cases
| Case | Behavior |
|---|---|
Missing labReportId in report-wise endpoint | Returns HTTP 400. |
Missing bill_id in bill-wise endpoint | Returns HTTP 400. |
is_insurance_enable enabled and no insurance is available | DFT/ORU branches return a failure response and do not generate/send HL7. |
testCodes configured for ORM but no matching tests are eligible | ORM can return status 209 with "Test codes are not configured." |
| Disabled DFT integration identifier in DFT 2.4 | Returns status 209 and skips DFT generation. |
| Athena ORU with mismatched integration identifier | Returns status 209 and skips generation for non-Athena data. |
port empty or zero | Message is generated and returned where supported, but TCP send is skipped. |