Moved diagnoses from orders to individual procedures.
[openemr.git] / interface / orders / gen_hl7_order.inc.php
blob608a875a5f1b0656e966891a3d94983fe37c51ce
1 <?php
2 /**
3 * Functions to support HL7 order generation.
5 * Copyright (C) 2012-2013 Rod Roark <rod@sunsetsystems.com>
7 * LICENSE: This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>.
18 * @package OpenEMR
19 * @author Rod Roark <rod@sunsetsystems.com>
23 * A bit of documentation that will need to go into the manual:
25 * The lab may want a list of your insurances for mapping into their system.
26 * To produce it, go into phpmyadmin and run this query:
28 * SELECT i.id, i.name, a.line1, a.line2, a.city, a.state, a.zip, p.area_code,
29 * p.prefix, p.number FROM insurance_companies AS i
30 * LEFT JOIN addresses AS a ON a.foreign_id = i.id
31 * LEFT JOIN phone_numbers AS p ON p.type = 2 AND p.foreign_id = i.id
32 * ORDER BY i.name, i.id;
34 * Then export as a CSV file and read it into your favorite spreadsheet app.
37 require_once("$srcdir/classes/Address.class.php");
38 require_once("$srcdir/classes/InsuranceCompany.class.php");
39 require_once("$webserver_root/custom/code_types.inc.php");
41 function hl7Text($s) {
42 // See http://www.interfaceware.com/hl7_escape_protocol.html:
43 $s = str_replace('\\', '\\E\\' , $s);
44 $s = str_replace('^' , '\\S\\' , $s);
45 $s = str_replace('|' , '\\F\\' , $s);
46 $s = str_replace('~' , '\\R\\' , $s);
47 $s = str_replace('&' , '\\T\\' , $s);
48 $s = str_replace("\r", '\\X0d\\', $s);
49 return $s;
52 function hl7Zip($s) {
53 return hl7Text(preg_replace('/[-\s]*/','',$s));
56 function hl7Date($s) {
57 return preg_replace('/[^\d]/','',$s);
60 function hl7Time($s) {
61 if (empty($s)) return '';
62 return date('YmdHis', strtotime($s));
65 function hl7Sex($s) {
66 $s = strtoupper(substr($s, 0, 1));
67 if ($s !== 'M' && $s !== 'F') $s = 'U';
68 return $s;
71 function hl7Phone($s) {
72 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
73 return '(' . $tmp[1] . ')' . $tmp[2] . '-' . $tmp[3];
75 if (preg_match("/(\d\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
76 return $tmp[1] . '-' . $tmp[2];
78 return '';
81 function hl7SSN($s) {
82 if (preg_match("/(\d\d\d)\D*(\d\d)\D*(\d\d\d\d)\D*$/", $s, $tmp)) {
83 return $tmp[1] . '-' . $tmp[2] . '-' . $tmp[3];
85 return '';
88 function hl7Priority($s) {
89 return strtoupper(substr($s, 0, 1)) == 'H' ? 'S' : 'R';
92 function hl7Relation($s) {
93 $tmp = strtolower($s);
94 if ($tmp == 'self' || $tmp == '') return 'self';
95 else if ($tmp == 'spouse') return 'spouse';
96 else if ($tmp == 'child' ) return 'child';
97 else if ($tmp == 'other' ) return 'other';
98 // Should not get here so this will probably get noticed if we do.
99 return $s;
103 * Get array of insurance payers for the specified patient as of the specified
104 * date. If no date is passed then the current date is used.
106 * @param integer $pid Patient ID.
107 * @param date $encounter_date YYYY-MM-DD date.
108 * @return array Array containing an array of data for each payer.
110 function loadPayerInfo($pid, $date='') {
111 if (empty($date)) $date = date('Y-m-d');
112 $payers = array();
113 $dres = sqlStatement("SELECT * FROM insurance_data WHERE " .
114 "pid = ? AND date <= ? ORDER BY type ASC, date DESC",
115 array($pid, $date));
116 $prevtype = ''; // type is primary, secondary or tertiary
117 while ($drow = sqlFetchArray($dres)) {
118 if (strcmp($prevtype, $drow['type']) == 0) continue;
119 $prevtype = $drow['type'];
120 // Very important to check for a missing provider because
121 // that indicates no insurance as of the given date.
122 if (empty($drow['provider'])) continue;
123 $ins = count($payers);
124 $crow = sqlQuery("SELECT * FROM insurance_companies WHERE id = ?",
125 array($drow['provider']));
126 $orow = new InsuranceCompany($drow['provider']);
127 $payers[$ins] = array();
128 $payers[$ins]['data'] = $drow;
129 $payers[$ins]['company'] = $crow;
130 $payers[$ins]['object'] = $orow;
132 return $payers;
136 * Generate HL7 for the specified procedure order.
138 * @param integer $orderid Procedure order ID.
139 * @param string &$out Container for target HL7 text.
140 * @return string Error text, or empty if no errors.
142 function gen_hl7_order($orderid, &$out) {
144 // Delimiters
145 $d0 = "\r";
146 $d1 = '|';
147 $d2 = '^';
149 $today = time();
150 $out = '';
152 $porow = sqlQuery("SELECT " .
153 "po.date_collected, po.date_ordered, po.order_priority, " .
154 "pp.*, " .
155 "pd.pid, pd.pubpid, pd.fname, pd.lname, pd.mname, pd.DOB, pd.ss, " .
156 "pd.phone_home, pd.phone_biz, pd.sex, pd.street, pd.city, pd.state, pd.postal_code, " .
157 "f.encounter, u.fname AS docfname, u.lname AS doclname, u.npi AS docnpi " .
158 "FROM procedure_order AS po, procedure_providers AS pp, " .
159 "forms AS f, patient_data AS pd, users AS u " .
160 "WHERE " .
161 "po.procedure_order_id = ? AND " .
162 "pp.ppid = po.lab_id AND " .
163 "f.formdir = 'procedure_order' AND " .
164 "f.form_id = po.procedure_order_id AND " .
165 "pd.pid = f.pid AND " .
166 "u.id = po.provider_id",
167 array($orderid));
168 if (empty($porow)) return "Procedure order or lab is missing for order ID '$orderid'";
170 $pcres = sqlStatement("SELECT " .
171 "pc.procedure_code, pc.procedure_name, pc.procedure_order_seq, pc.diagnoses " .
172 "FROM procedure_order_code AS pc " .
173 "WHERE " .
174 "pc.procedure_order_id = ? " .
175 "ORDER BY pc.procedure_order_seq",
176 array($orderid));
178 // Message Header
179 $out .= "MSH" .
180 $d1 . "$d2~\\&" . // Encoding Characters (delimiters)
181 $d1 . $porow['send_app_id'] . // Sending Application ID
182 $d1 . $porow['send_fac_id'] . // Sending Facility ID
183 $d1 . $porow['recv_app_id'] . // Receiving Application ID
184 $d1 . $porow['recv_fac_id'] . // Receiving Facility ID
185 $d1 . date('YmdHis', $today) . // Date and time of this message
186 $d1 .
187 $d1 . 'ORM' . $d2 . 'O01' . // Message Type
188 $d1 . $orderid . // Unique Message Number
189 $d1 . $porow['DorP'] . // D=Debugging, P=Production
190 $d1 . '2.3' . // HL7 Version ID
191 $d0;
193 // Patient Identification
194 $out .= "PID" .
195 $d1 . "1" . // Set ID (always just 1 of these)
196 $d1 . $porow['pid'] . // Patient ID (not required)
197 $d1 . $porow['pid'] . // Patient ID (required)
198 $d1 . // Alternate Patient ID (not required)
199 $d1 . hl7Text($porow['lname']) .
200 $d2 . hl7Text($porow['fname']);
201 if ($porow['mname']) $out .= $d2 . hl7Text($porow['mname']);
202 $out .=
203 $d1 .
204 $d1 . hl7Date($porow['DOB']) . // DOB
205 $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U
206 $d1 . $d1 .
207 $d1 . hl7Text($porow['street']) .
208 $d2 .
209 $d2 . hl7Text($porow['city']) .
210 $d2 . hl7Text($porow['state']) .
211 $d2 . hl7Zip($porow['zip']) .
212 $d1 .
213 $d1 . hl7Phone($porow['phone_home']) .
214 $d1 . hl7Phone($porow['phone_biz']) .
215 $d1 . $d1 . $d1 .
216 $d1 . $porow['encounter'] .
217 $d1 . hl7SSN($porow['ss']) .
218 $d1 . $d1 . $d1 .
219 $d0;
221 // NTE segment(s) omitted.
223 // Patient Visit.
224 $out .= "PV1" .
225 $d1 . "1" . // Set ID (always just 1 of these)
226 $d1 . // Patient Class (if required, O for Outpatient)
227 $d1 . // Patient Location (for inpatient only?)
228 $d1 . $d1 . $d1 .
229 $d1 . hl7Text($porow['docnpi']) . // Attending Doctor ID
230 $d2 . hl7Text($porow['doclname']) . // Last Name
231 $d2 . hl7Text($porow['docfname']) . // First Name
232 str_repeat($d1, 11) . // PV1 8 to 18 all empty
233 $d1 . $porow['encounter'] . // Encounter Number
234 str_repeat($d1, 13) . // PV1 20 to 32 all empty
235 $d0;
237 // Insurance stuff.
238 $payers = loadPayerInfo($porow['pid'], $porow['date_ordered']);
239 $setid = 0;
240 foreach ($payers as $payer) {
241 $payer_object = $payer['object'];
242 $payer_address = $payer_object->get_address();
243 $out .= "IN1" .
244 $d1 . ++$setid . // Set ID
245 $d1 . // Insurance Plan Identifier ??
246 $d1 . hl7Text($payer['company']['id']) . // Insurance Company ID
247 $d1 . hl7Text($payer['company']['name']) . // Insurance Company Name
248 $d1 . hl7Text($payer_address->get_line1()) . // Street Address
249 $d2 .
250 $d2 . hl7Text($payer_address->get_city()) . // City
251 $d2 . hl7Text($payer_address->get_state()) . // State
252 $d2 . hl7Zip($payer_address->get_zip()) . // Zip Code
253 $d1 .
254 $d1 . hl7Phone($payer_object->get_phone()) . // Phone Number
255 $d1 . hl7Text($payer['data']['group_number']) . // Insurance Company Group Number
256 str_repeat($d1, 7) . // IN1 9-15 all empty
257 $d1 . hl7Text($payer['data']['subscriber_lname']) . // Insured last name
258 $d2 . hl7Text($payer['data']['subscriber_fname']) . // Insured first name
259 $d2 . hl7Text($payer['data']['subscriber_mname']) . // Insured middle name
260 $d1 . hl7Relation($payer['data']['subscriber_relationship']) .
261 $d1 . hl7Date($payer['data']['subscriber_DOB']) . // Insured DOB
262 $d1 . hl7Date($payer['data']['subscriber_street']) . // Insured Street Address
263 $d2 .
264 $d2 . hl7Text($payer['data']['subscriber_city']) . // City
265 $d2 . hl7Text($payer['data']['subscriber_state']) . // State
266 $d2 . hl7Zip($payer['data']['subscriber_postal_code']) . // Zip
267 $d1 .
268 $d1 .
269 $d1 . $setid . // 1=Primary, 2=Secondary, 3=Tertiary
270 str_repeat($d1, 13) . // IN1-23 to 35 all empty
271 $d1 . hl7Text($payer['data']['policy_number']) . // Policy Number
272 str_repeat($d1, 12) . // IN1-37 to 48 all empty
273 $d0;
275 // IN2 segment omitted.
278 // Guarantor. OpenEMR doesn't have these so use the patient.
279 $out .= "GT1" .
280 $d1 . "1" . // Set ID (always just 1 of these)
281 $d1 .
282 $d1 . hl7Text($porow['lname']) .
283 $d2 . hl7Text($porow['fname']);
284 if ($porow['mname']) $out .= $d2 . hl7Text($porow['mname']);
285 $out .=
286 $d1 .
287 $d1 . hl7Text($porow['street']) .
288 $d2 .
289 $d2 . hl7Text($porow['city']) .
290 $d2 . hl7Text($porow['state']) .
291 $d2 . hl7Zip($porow['zip']) .
292 $d1 . hl7Phone($porow['phone_home']) .
293 $d1 . hl7Phone($porow['phone_biz']) .
294 $d1 . hl7Date($porow['DOB']) . // DOB
295 $d1 . hl7Sex($porow['sex']) . // Sex: M, F or U
296 $d1 .
297 $d1 . 'self' . // Relationship
298 $d1 . hl7SSN($porow['ss']) .
299 $d0;
301 // Common Order.
302 $out .= "ORC" .
303 $d1 . "NW" . // New Order
304 $d1 . $orderid . // Placer Order Number
305 str_repeat($d1, 6) . // ORC 3-8 not used
306 $d1 . date('YmdHis') . // Transaction date/time
307 $d1 . $d1 .
308 $d1 . hl7Text($porow['docnpi']) . // Ordering Provider
309 $d2 . hl7Text($porow['doclname']) . // Last Name
310 $d2 . hl7Text($porow['docfname']) . // First Name
311 str_repeat($d1, 7) . // ORC 13-19 not used
312 $d1 . "2" . // ABN Status: 2 = Notified & Signed, 4 = Unsigned
313 $d0;
315 $setid = 0;
316 while ($pcrow = sqlFetchArray($pcres)) {
317 // Observation Request.
318 $out .= "OBR" .
319 $d1 . ++$setid . // Set ID
320 $d1 . $orderid . // Placer Order Number
321 $d1 .
322 $d1 . hl7Text($pcrow['procedure_code']) .
323 $d2 . hl7Text($pcrow['procedure_name']) .
324 $d1 . hl7Priority($porow['order_priority']) . // S=Stat, R=Routine
325 $d1 .
326 $d1 . hl7Time($porow['date_collected']) . // Observation Date/Time
327 str_repeat($d1, 8) . // OBR 8-15 not used
328 $d1 . hl7Text($porow['docnpi']) . // Physician ID
329 $d2 . hl7Text($porow['doclname']) . // Last Name
330 $d2 . hl7Text($porow['docfname']) . // First Name
331 $d1 .
332 $d1 . (count($payers) ? 'I' : 'P') . // I=Insurance, C=Client, P=Self Pay
333 str_repeat($d1, 8) . // OBR 19-26 not used
334 $d1 . '0' . // ?
335 $d0;
337 // Diagnoses. Currently hard-coded for ICD9 and we'll surely want to make
338 // this more flexible (probably when some lab needs another diagnosis type).
339 $setid2 = 0;
340 if (!empty($pcrow['diagnoses'])) {
341 $relcodes = explode(';', $pcrow['diagnoses']);
342 foreach ($relcodes as $codestring) {
343 if ($codestring === '') continue;
344 list($codetype, $code) = explode(':', $codestring);
345 if ($codetype !== 'ICD9') continue;
346 $desc = lookup_code_descriptions($codestring);
347 $out .= "DG1" .
348 $d1 . ++$setid2 . // Set ID
349 $d1 . // Diagnosis Coding Method
350 $d1 . $code . // Diagnosis Code
351 $d1 . hl7Text($desc) . // Diagnosis Description
352 $d0;
356 // Order entry questions and answers.
357 $qres = sqlStatement("SELECT " .
358 "a.question_code, a.answer, q.fldtype " .
359 "FROM procedure_answers AS a " .
360 "LEFT JOIN procedure_questions AS q ON " .
361 "q.lab_id = ? " .
362 "AND q.procedure_code = ? AND " .
363 "q.question_code = a.question_code " .
364 "WHERE " .
365 "a.procedure_order_id = ? AND " .
366 "a.procedure_order_seq = ? " .
367 "ORDER BY q.seq, a.answer_seq",
368 array($porow['ppid'], $pcrow['procedure_code'], $orderid, $pcrow['procedure_order_seq']));
369 $setid2 = 0;
370 while ($qrow = sqlFetchArray($qres)) {
371 // Formatting of these answer values may be lab-specific and we'll figure
372 // out how to deal with that as more labs are supported.
373 $answer = trim($qrow['answer']);
374 $fldtype = $qrow['fldtype'];
375 $datatype = 'ST';
376 if ($fldtype == 'N') {
377 $datatype = "NM";
378 } else if ($fldtype == 'D') {
379 $answer = hl7Date($answer);
380 } else if ($fldtype == 'G') {
381 $weeks = intval($answer / 7);
382 $days = $answer % 7;
383 $answer = $weeks . 'wks ' . $days . 'days';
385 $out .= "OBX" .
386 $d1 . ++$setid2 . // Set ID
387 $d1 . $datatype . // Structure of observation value
388 $d1 . hl7Text($qrow['question_code']) . // Clinical question code
389 $d1 .
390 $d1 . hl7Text($answer) . // Clinical question answer
391 $d0;
395 return '';
399 * Transmit HL7 for the specified lab.
401 * @param integer $ppid Procedure provider ID.
402 * @param string $out The HL7 text to be sent.
403 * @return string Error text, or empty if no errors.
405 function send_hl7_order($ppid, $out) {
406 global $srcdir;
408 $d0 = "\r";
410 $pprow = sqlQuery("SELECT * FROM procedure_providers " .
411 "WHERE ppid = ?", array($ppid));
412 if (empty($pprow)) return xl('Procedure provider') . " $ppid " . xl('not found');
414 $protocol = $pprow['protocol'];
415 $remote_host = $pprow['remote_host'];
417 // Extract MSH-10 which is the message control ID.
418 $segmsh = explode(substr($out, 3, 1), substr($out, 0, strpos($out, $d0)));
419 $msgid = $segmsh[9];
420 if (empty($msgid)) return xl('Internal error: Cannot find MSH-10');
422 if ($protocol == 'SFTP') {
423 ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . "$srcdir/phpseclib");
424 require_once("$srcdir/phpseclib/Net/SFTP.php");
426 // Compute the target path/file name.
427 $filename = $msgid . '.txt';
428 if ($pprow['orders_path']) $filename = $pprow['orders_path'] . '/' . $filename;
430 // Connect to the server and write the file.
431 $sftp = new Net_SFTP($remote_host);
432 if (!$sftp->login($pprow['login'], $pprow['password'])) {
433 return xl('Login to this remote host failed') . ": '$remote_host'";
435 if (!$sftp->put($filename, $out)) {
436 return xl('Creating this file on remote host failed') . ": '$filename'";
440 else if ($protocol == 'DL') {
441 header("Pragma: public");
442 header("Expires: 0");
443 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
444 header("Content-Type: application/force-download");
445 header("Content-Disposition: attachment; filename=order_$msgid.hl7");
446 header("Content-Description: File Transfer");
447 echo $out;
448 exit;
451 // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols.
453 else {
454 return xl('This protocol is not implemented') . ": '$protocol'";
457 // Falling through to here indicates success.
458 newEvent("proc_order_xmit", $_SESSION['authUser'], $_SESSION['authProvider'], 1,
459 "ID: $msgid Protocol: $protocol Host: $remote_host");
460 return '';