Security fix - html escape sql error messages
[openemr.git] / library / Claim.class.php
blob1ddfc24cba77b2fd4afeec4156cb7f1a7a0fb9cc
1 <?php
2 // Copyright (C) 2007-2009 Rod Roark <rod@sunsetsystems.com>
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License
6 // as published by the Free Software Foundation; either version 2
7 // of the License, or (at your option) any later version.
9 require_once(dirname(__FILE__) . "/classes/Address.class.php");
10 require_once(dirname(__FILE__) . "/classes/InsuranceCompany.class.php");
11 require_once(dirname(__FILE__) . "/sql-ledger.inc");
12 require_once(dirname(__FILE__) . "/invoice_summary.inc.php");
14 // This enforces the X12 Basic Character Set. Page A2.
16 function x12clean($str) {
17 return preg_replace('/[^A-Z0-9!"\\&\'()+,\\-.\\/;?= ]/', '', strtoupper($str));
20 // Make sure dates have no formatting and zero filled becomes blank
21 // Handles date time stamp formats as well
23 function cleanDate($date_field)
25 $cleandate = str_replace('-', '', substr($date_field, 0, 10));
27 if(substr_count($cleandate,'0')==8)
29 $cleandate='';
32 return ($cleandate);
35 class Claim {
37 var $pid; // patient id
38 var $encounter_id; // encounter id
39 var $procs; // array of procedure rows from billing table
40 var $diags; // array of icd9 codes from billing table
41 var $x12_partner; // row from x12_partners table
42 var $encounter; // row from form_encounter table
43 var $facility; // row from facility table
44 var $billing_facility; // row from facility table
45 var $provider; // row from users table (rendering provider)
46 var $referrer; // row from users table (referring provider)
47 var $supervisor; // row from users table (supervising provider)
48 var $insurance_numbers; // row from insurance_numbers table for current payer
49 var $supervisor_numbers; // row from insurance_numbers table for current payer
50 var $patient_data; // row from patient_data table
51 var $billing_options; // row from form_misc_billing_options table
52 var $invoice; // result from get_invoice_summary()
53 var $payers; // array of arrays, for all payers
54 var $copay; // total of copays from the ar_activity table
56 function loadPayerInfo(&$billrow) {
57 global $sl_err;
58 $encounter_date = substr($this->encounter['date'], 0, 10);
60 // Create the $payers array. This contains data for all insurances
61 // with the current one always at index 0, and the others in payment
62 // order starting at index 1.
64 $this->payers = array();
65 $this->payers[0] = array();
66 $query = "SELECT * FROM insurance_data WHERE " .
67 "pid = '{$this->pid}' AND " .
68 "date <= '$encounter_date' " .
69 "ORDER BY type ASC, date DESC";
70 $dres = sqlStatement($query);
71 $prevtype = '';
72 while ($drow = sqlFetchArray($dres)) {
73 if (strcmp($prevtype, $drow['type']) == 0) continue;
74 $prevtype = $drow['type'];
75 // Very important to look at entries with a missing provider because
76 // they indicate no insurance as of the given date.
77 if (empty($drow['provider'])) continue;
78 $ins = count($this->payers);
79 if ($drow['provider'] == $billrow['payer_id'] && empty($this->payers[0]['data'])) $ins = 0;
80 $crow = sqlQuery("SELECT * FROM insurance_companies WHERE " .
81 "id = '" . $drow['provider'] . "'");
82 $orow = new InsuranceCompany($drow['provider']);
83 $this->payers[$ins] = array();
84 $this->payers[$ins]['data'] = $drow;
85 $this->payers[$ins]['company'] = $crow;
86 $this->payers[$ins]['object'] = $orow;
89 // This kludge hands most cases of a rare ambiguous situation, where
90 // the primary insurance company is the same as the secondary. It seems
91 // nobody planned for that!
93 for ($i = 1; $i < count($this->payers); ++$i) {
94 if ($billrow['process_date'] &&
95 $this->payers[0]['data']['provider'] == $this->payers[$i]['data']['provider'])
97 $tmp = $this->payers[0];
98 $this->payers[0] = $this->payers[$i];
99 $this->payers[$i] = $tmp;
103 $this->using_modifiers = true;
105 // Get payment and adjustment details if there are any previous payers.
107 $this->invoice = array();
108 if ($this->payerSequence() != 'P') {
109 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
110 $this->invoice = ar_get_invoice_summary($this->pid, $this->encounter_id, true);
112 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
113 SLConnect();
114 $arres = SLQuery("select id from ar where invnumber = " .
115 "'{$this->pid}.{$this->encounter_id}'");
116 if ($sl_err) die($sl_err);
117 $arrow = SLGetRow($arres, 0);
118 if ($arrow) {
119 $this->invoice = get_invoice_summary($arrow['id'], true);
121 SLClose();
123 // Secondary claims might not have modifiers in SQL-Ledger data.
124 // In that case, note that we should not try to match on them.
125 $this->using_modifiers = false;
126 foreach ($this->invoice as $key => $trash) {
127 if (strpos($key, ':')) $this->using_modifiers = true;
132 // Constructor. Loads relevant database information.
134 function Claim($pid, $encounter_id) {
135 $this->pid = $pid;
136 $this->encounter_id = $encounter_id;
137 $this->procs = array();
138 $this->diags = array();
139 $this->copay = 0;
141 // We need the encounter date before we can identify the payers.
142 $sql = "SELECT * FROM form_encounter WHERE " .
143 "pid = '{$this->pid}' AND " .
144 "encounter = '{$this->encounter_id}'";
145 $this->encounter = sqlQuery($sql);
147 // Sort by procedure timestamp in order to get some consistency.
148 $sql = "SELECT b.id, b.date, b.code_type, b.code, b.pid, b.provider_id, " .
149 "b.user, b.groupname, b.authorized, b.encounter, b.code_text, b.billed, " .
150 "b.activity, b.payer_id, b.bill_process, b.bill_date, b.process_date, " .
151 "b.process_file, b.modifier, b.units, b.fee, b.justify, b.target, b.x12_partner_id, " .
152 "b.ndc_info, b.notecodes, ct.ct_diag " .
153 "FROM billing as b INNER JOIN code_types as ct " .
154 "ON b.code_type = ct.ct_key " .
155 "WHERE ct.ct_claim = '1' AND ct.ct_active = '1' AND " .
156 "b.encounter = '{$this->encounter_id}' AND b.pid = '{$this->pid}' AND " .
157 "b.activity = '1' ORDER BY b.date, b.id";
158 $res = sqlStatement($sql);
159 while ($row = sqlFetchArray($res)) {
160 // Save all diagnosis codes.
161 if ($row['ct_diag'] == '1') {
162 $this->diags[$row['code']] = $row['code'];
163 continue;
165 if (!$row['units']) $row['units'] = 1;
166 // Load prior payer data at the first opportunity in order to get
167 // the using_modifiers flag that is referenced below.
168 if (empty($this->procs)) $this->loadPayerInfo($row);
169 // Consolidate duplicate procedures.
170 foreach ($this->procs as $key => $trash) {
171 if (strcmp($this->procs[$key]['code'],$row['code']) == 0 &&
172 (strcmp($this->procs[$key]['modifier'],$row['modifier']) == 0 ||
173 !$this->using_modifiers))
175 $this->procs[$key]['units'] += $row['units'];
176 $this->procs[$key]['fee'] += $row['fee'];
177 continue 2; // skip to next table row
181 // If there is a row-specific provider then get its details.
182 if (!empty($row['provider_id'])) {
183 // Get service provider data for this row.
184 $sql = "SELECT * FROM users WHERE id = '" . $row['provider_id'] . "'";
185 $row['provider'] = sqlQuery($sql);
186 // Get insurance numbers for this row's provider.
187 $sql = "SELECT * FROM insurance_numbers WHERE " .
188 "(insurance_company_id = '" . $row['payer_id'] .
189 "' OR insurance_company_id is NULL) AND " .
190 "provider_id = '" . $row['provider_id'] . "' " .
191 "ORDER BY insurance_company_id DESC LIMIT 1";
192 $row['insurance_numbers'] = sqlQuery($sql);
195 $this->procs[] = $row;
198 $resMoneyGot = sqlStatement("SELECT pay_amount as PatientPay,session_id as id,".
199 "date(post_time) as date FROM ar_activity where pid ='{$this->pid}' and encounter ='{$this->encounter_id}' ".
200 "and payer_type=0 and account_code='PCP'");
201 //new fees screen copay gives account_code='PCP'
202 while($rowMoneyGot = sqlFetchArray($resMoneyGot)){
203 $PatientPay=$rowMoneyGot['PatientPay']*-1;
204 $this->copay -= $PatientPay;
207 $sql = "SELECT * FROM x12_partners WHERE " .
208 "id = '" . $this->procs[0]['x12_partner_id'] . "'";
209 $this->x12_partner = sqlQuery($sql);
211 $sql = "SELECT * FROM facility WHERE " .
212 "id = '" . addslashes($this->encounter['facility_id']) . "' " .
213 "LIMIT 1";
214 $this->facility = sqlQuery($sql);
216 /*****************************************************************
217 $provider_id = $this->procs[0]['provider_id'];
218 *****************************************************************/
219 $provider_id = $this->encounter['provider_id'];
220 $sql = "SELECT * FROM users WHERE id = '$provider_id'";
221 $this->provider = sqlQuery($sql);
222 // Selecting the billing facility assigned to the encounter. If none,
223 // try the first (and hopefully only) facility marked as a billing location.
224 if (empty($this->encounter['billing_facility'])) {
225 $sql = "SELECT * FROM facility " .
226 "ORDER BY billing_location DESC, id ASC LIMIT 1";
228 else {
229 $sql = "SELECT * FROM facility " .
230 " where id ='" . addslashes($this->encounter['billing_facility']) . "' ";
232 $this->billing_facility = sqlQuery($sql);
234 $sql = "SELECT * FROM insurance_numbers WHERE " .
235 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
236 "' OR insurance_company_id is NULL) AND " .
237 "provider_id = '$provider_id' " .
238 "ORDER BY insurance_company_id DESC LIMIT 1";
239 $this->insurance_numbers = sqlQuery($sql);
241 $sql = "SELECT * FROM patient_data WHERE " .
242 "pid = '{$this->pid}' " .
243 "ORDER BY id LIMIT 1";
244 $this->patient_data = sqlQuery($sql);
246 $sql = "SELECT fpa.* FROM forms JOIN form_misc_billing_options AS fpa " .
247 "ON fpa.id = forms.form_id WHERE " .
248 "forms.encounter = '{$this->encounter_id}' AND " .
249 "forms.pid = '{$this->pid}' AND " .
250 "forms.deleted = 0 AND " .
251 "forms.formdir = 'misc_billing_options' " .
252 "ORDER BY forms.date";
253 $this->billing_options = sqlQuery($sql);
255 $referrer_id = (empty($GLOBALS['MedicareReferrerIsRenderer']) ||
256 $this->insurance_numbers['provider_number_type'] != '1C') ?
257 $this->patient_data['ref_providerID'] : $provider_id;
258 $sql = "SELECT * FROM users WHERE id = '$referrer_id'";
259 $this->referrer = sqlQuery($sql);
260 if (!$this->referrer) $this->referrer = array();
262 $supervisor_id = $this->encounter['supervisor_id'];
263 $sql = "SELECT * FROM users WHERE id = '$supervisor_id'";
264 $this->supervisor = sqlQuery($sql);
265 if (!$this->supervisor) $this->supervisor = array();
267 $sql = "SELECT * FROM insurance_numbers WHERE " .
268 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
269 "' OR insurance_company_id is NULL) AND " .
270 "provider_id = '$supervisor_id' " .
271 "ORDER BY insurance_company_id DESC LIMIT 1";
272 $this->supervisor_numbers = sqlQuery($sql);
273 if (!$this->supervisor_numbers) $this->supervisor_numbers = array();
275 } // end constructor
277 // Return an array of adjustments from the designated prior payer for the
278 // designated procedure key (might be procedure:modifier), or for the claim
279 // level. For each adjustment give date, group code, reason code, amount.
280 // Note this will include "patient responsibility" adjustments which are
281 // not adjustments to OUR invoice, but they reduce the amount that the
282 // insurance company pays.
284 function payerAdjustments($ins, $code='Claim') {
285 $aadj = array();
287 // If we have no modifiers stored in SQL-Ledger for this claim,
288 // then we cannot use a modifier passed in with the key.
289 $tmp = strpos($code, ':');
290 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
292 // For payments, source always starts with "Ins" or "Pt".
293 // Nonzero adjustment reason examples:
294 // Ins1 adjust code 42 (Charges exceed ... (obsolete))
295 // Ins1 adjust code 45 (Charges exceed your contracted/ legislated fee arrangement)
296 // Ins1 adjust code 97 (Payment is included in the allowance for another service/procedure)
297 // Ins1 adjust code A2 (Contractual adjustment)
298 // Ins adjust Ins1
299 // adjust code 45
300 // Zero adjustment reason examples:
301 // Co-pay: 25.00
302 // Coinsurance: 11.46 (code 2) Note: fix remits to identify insurance
303 // To deductible: 0.22 (code 1) Note: fix remits to identify insurance
304 // To copay Ins1 (manual entry)
305 // To ded'ble Ins1 (manual entry)
307 if (!empty($this->invoice[$code])) {
308 $date = '';
309 $deductible = 0;
310 $coinsurance = 0;
311 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
312 $insnumber = substr($inslabel, 3);
314 // Compute this procedure's patient responsibility amount as of this
315 // prior payer, which is the original charge minus all insurance
316 // payments and "hard" adjustments up to this payer.
317 $ptresp = $this->invoice[$code]['chg'] + $this->invoice[$code]['adj'];
318 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
319 if (isset($value['plv'])) {
320 // New method; plv (from ar_activity.payer_type) exists to
321 // indicate the payer level.
322 if (isset($value['pmt']) && $value['pmt'] != 0) {
323 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
324 $ptresp -= $value['pmt'];
326 else if (isset($value['chg']) && trim(substr($key, 0, 10))) {
327 // non-blank key indicates this is an adjustment and not a charge
328 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
329 $ptresp += $value['chg']; // adjustments are negative charges
332 $msp = isset( $value['msp'] ) ? $value['msp'] : null; // record the reason for adjustment
334 else {
335 // Old method: With SQL-Ledger payer level was stored in the memo.
336 if (preg_match("/^Ins(\d)/i", $value['src'], $tmp)) {
337 if ($tmp[1] <= $insnumber) $ptresp -= $value['pmt'];
339 else if (trim(substr($key, 0, 10))) { // not an adjustment if no date
340 if (!preg_match("/Ins(\d)/i", $value['rsn'], $tmp) || $tmp[1] <= $insnumber)
341 $ptresp += $value['chg']; // adjustments are negative charges
345 if ($ptresp < 0) $ptresp = 0; // we may be insane but try to hide it
347 // Main loop, to extract adjustments for this payer and procedure.
348 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
349 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
350 if ($tmp) $date = $tmp;
351 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
352 $rsn = $value['rsn'];
353 $chg = 0 - $value['chg']; // adjustments are negative charges
355 $gcode = 'CO'; // default group code = contractual obligation
356 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
358 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
359 // From manual post. Take the defaults.
361 else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
362 $coinsurance = $ptresp; // from manual post
363 continue;
365 else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
366 $deductible = $ptresp; // from manual post
367 continue;
369 else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
370 $coinsurance = $tmp[1]; // from 835 as of 6/2007
371 continue;
373 else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
374 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
375 continue;
377 else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
378 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
379 continue;
381 else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
382 continue; // from 835 as of 6/2007
384 else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
385 $rcode = $tmp[1]; // from 835
387 else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
388 // Take the defaults.
390 else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
391 continue; // it's for some other payer
393 else if ($insnumber == '1') {
394 if (preg_match("/\$\s*adjust code (\S+)/i", $rsn, $tmp)) {
395 $rcode = $tmp[1]; // from 835
397 else if ($chg) {
398 // Other adjustments default to Ins1.
400 else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
401 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
402 $coinsurance = 0 + $tmp[1]; // from 835 before 6/2007
403 continue;
405 else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
406 $deductible = 0 + $tmp[1]; // from 835 before 6/2007
407 continue;
409 else {
410 continue; // there is no adjustment amount
413 else {
414 continue; // it's for primary and that's not us
417 if ($rcode == '42') $rcode= '45'; // reason 42 is obsolete
418 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
420 } // end if
421 } // end foreach
423 // If we really messed it up, at least avoid negative numbers.
424 if ($coinsurance > $ptresp) $coinsurance = $ptresp;
425 if ($deductible > $ptresp) $deductible = $ptresp;
427 // Find out if this payer paid anything at all on this claim. This will
428 // help us allocate any unknown patient responsibility amounts.
429 $thispaidanything = 0;
430 foreach($this->invoice as $codekey => $codeval) {
431 foreach ($codeval['dtl'] as $key => $value) {
432 if (isset($value['plv'])) {
433 // New method; plv exists to indicate the payer level.
434 if ($value['plv'] == $insnumber) {
435 $thispaidanything += $value['pmt'];
438 else {
439 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
440 $thispaidanything += $value['pmt'];
446 // Allocate any unknown patient responsibility by guessing if the
447 // deductible has been satisfied.
448 if ($thispaidanything)
449 $coinsurance = $ptresp - $deductible;
450 else
451 $deductible = $ptresp - $coinsurance;
453 $deductible = sprintf('%.2f', $deductible);
454 $coinsurance = sprintf('%.2f', $coinsurance);
456 if ($date && $deductible != 0)
457 $aadj[] = array($date, 'PR', '1', $deductible, $msp);
458 if ($date && $coinsurance != 0)
459 $aadj[] = array($date, 'PR', '2', $coinsurance, $msp);
461 } // end if
463 return $aadj;
466 // Return date, total payments and total "hard" adjustments from the given
467 // prior payer. If $code is specified then only that procedure key is
468 // selected, otherwise it's for the whole claim.
470 function payerTotals($ins, $code='') {
471 // If we have no modifiers stored in SQL-Ledger for this claim,
472 // then we cannot use a modifier passed in with the key.
473 $tmp = strpos($code, ':');
474 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
476 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
477 $insnumber = substr($inslabel, 3);
478 $paytotal = 0;
479 $adjtotal = 0;
480 $date = '';
481 foreach($this->invoice as $codekey => $codeval) {
482 if ($code && strcmp($codekey,$code) != 0) continue;
483 foreach ($codeval['dtl'] as $key => $value) {
484 if (isset($value['plv'])) {
485 // New method; plv (from ar_activity.payer_type) exists to
486 // indicate the payer level.
487 if ($value['plv'] == $insnumber) {
488 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
489 $paytotal += $value['pmt'];
492 else {
493 // Old method: With SQL-Ledger payer level was stored in the memo.
494 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
495 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
496 $paytotal += $value['pmt'];
500 $aarr = $this->payerAdjustments($ins, $codekey);
501 foreach ($aarr as $a) {
502 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
503 if (!$date) $date = $a[0];
506 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
509 // Return the amount already paid by the patient.
511 function patientPaidAmount() {
512 // For primary claims $this->invoice is not loaded, so get the co-pay
513 // from the ar_activity table instead.
514 if (empty($this->invoice)) return $this->copay;
516 $amount = 0;
517 foreach($this->invoice as $codekey => $codeval) {
518 foreach ($codeval['dtl'] as $key => $value) {
519 if (isset($value['plv'])) {
520 // New method; plv exists to indicate the payer level.
521 if ($value['plv'] == 0) { // 0 indicates patient
522 $amount += $value['pmt'];
525 else {
526 // Old method: With SQL-Ledger payer level was stored in the memo.
527 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
528 $amount += $value['pmt'];
533 return sprintf('%.2f', $amount);
536 // Return invoice total, including adjustments but not payments.
538 function invoiceTotal() {
539 $amount = 0;
540 foreach($this->invoice as $codekey => $codeval) {
541 $amount += $codeval['chg'];
543 return sprintf('%.2f', $amount);
546 // Number of procedures in this claim.
547 function procCount() {
548 return count($this->procs);
551 // Number of payers for this claim. Ranges from 1 to 3.
552 function payerCount() {
553 return count($this->payers);
556 function x12gsversionstring() {
557 return x12clean(trim($this->x12_partner['x12_version']));
560 function x12gssenderid() {
561 $tmp = $this->x12_partner['x12_sender_id'];
562 while (strlen($tmp) < 15) $tmp .= " ";
563 return $tmp;
566 function x12gs03() {
568 * GS03: Application Receiver's Code
569 * Code Identifying Party Receiving Transmission
571 * In most cases, the ISA08 and GS03 are the same. However
573 * In some clearing houses ISA08 and GS03 are different
574 * Example: http://www.acs-gcro.com/downloads/DOL/DOL_CG_X12N_5010_837_v1_02.pdf - Page 18
575 * In this .pdf, the ISA08 is specified to be 100000 while the GS03 is specified to be 77044
577 * Therefore if the x12_gs03 segement is explicitly specified we use that value,
578 * otherwise we simply use the same receiver ID as specified for ISA03
580 if($this->x12_partner['x12_gs03'] !== '')
581 return $this->x12_partner['x12_gs03'];
582 else
583 return $this->x12_partner['x12_receiver_id'];
586 function x12gsreceiverid() {
587 $tmp = $this->x12_partner['x12_receiver_id'];
588 while (strlen($tmp) < 15) $tmp .= " ";
589 return $tmp;
592 function x12gsisa05() {
593 return $this->x12_partner['x12_isa05'];
595 //adding in functions for isa 01 - isa 04
597 function x12gsisa01() {
598 return $this->x12_partner['x12_isa01'];
601 function x12gsisa02() {
602 return $this->x12_partner['x12_isa02'];
605 function x12gsisa03() {
606 return $this->x12_partner['x12_isa03'];
608 function x12gsisa04() {
609 return $this->x12_partner['x12_isa04'];
612 /////////
613 function x12gsisa07() {
614 return $this->x12_partner['x12_isa07'];
617 function x12gsisa14() {
618 return $this->x12_partner['x12_isa14'];
621 function x12gsisa15() {
622 return $this->x12_partner['x12_isa15'];
625 function x12gsgs02() {
626 $tmp = $this->x12_partner['x12_gs02'];
627 if ($tmp === '') $tmp = $this->x12_partner['x12_sender_id'];
628 return $tmp;
631 function x12gsper06() {
632 return $this->x12_partner['x12_per06'];
635 function cliaCode() {
636 return x12clean(trim($this->facility['domain_identifier']));
639 function billingFacilityName() {
640 return x12clean(trim($this->billing_facility['name']));
643 function billingFacilityStreet() {
644 return x12clean(trim($this->billing_facility['street']));
647 function billingFacilityCity() {
648 return x12clean(trim($this->billing_facility['city']));
651 function billingFacilityState() {
652 return x12clean(trim($this->billing_facility['state']));
655 function billingFacilityZip() {
656 return x12clean(trim($this->billing_facility['postal_code']));
659 function billingFacilityETIN() {
660 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
663 function billingFacilityNPI() {
664 return x12clean(trim($this->billing_facility['facility_npi']));
667 function federalIdType() {
668 if ($this->billing_facility['tax_id_type'])
670 return $this->billing_facility['tax_id_type'];
672 else{
673 return null;
677 # The billing facility and the patient must both accept for this to return true.
678 function billingFacilityAssignment($ins=0) {
679 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
680 if (strcmp($tmp,'FALSE') == 0) return '0';
681 return !empty($this->billing_facility['accepts_assignment']);
684 function billingContactName() {
685 return x12clean(trim($this->billing_facility['attn']));
688 function billingContactPhone() {
689 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
690 $this->billing_facility['phone'], $tmp))
692 return $tmp[1] . $tmp[2] . $tmp[3];
694 return '';
697 function facilityName() {
698 return x12clean(trim($this->facility['name']));
701 function facilityStreet() {
702 return x12clean(trim($this->facility['street']));
705 function facilityCity() {
706 return x12clean(trim($this->facility['city']));
709 function facilityState() {
710 return x12clean(trim($this->facility['state']));
713 function facilityZip() {
714 return x12clean(trim($this->facility['postal_code']));
717 function facilityETIN() {
718 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
721 function facilityNPI() {
722 return x12clean(trim($this->facility['facility_npi']));
725 function facilityPOS() {
726 return sprintf('%02d', trim($this->facility['pos_code']));
729 function clearingHouseName() {
730 return x12clean(trim($this->x12_partner['name']));
733 function clearingHouseETIN() {
734 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
737 function providerNumberType($prockey=-1) {
738 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
739 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
740 return $tmp['provider_number_type'];
743 function providerNumber($prockey=-1) {
744 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
745 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
746 return x12clean(trim(str_replace('-', '', $tmp['provider_number'])));
749 function providerGroupNumber($prockey=-1) {
750 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
751 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
752 return x12clean(trim(str_replace('-', '', $tmp['group_number'])));
755 // Returns 'P', 'S' or 'T'.
757 function payerSequence($ins=0) {
758 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
761 // Returns the HIPAA code of the patient-to-subscriber relationship.
763 function insuredRelationship($ins=0) {
764 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
765 if (strcmp($tmp,'self' ) == 0) return '18';
766 if (strcmp($tmp,'spouse') == 0) return '01';
767 if (strcmp($tmp,'child' ) == 0) return '19';
768 if (strcmp($tmp,'other' ) == 0) return 'G8';
769 return $tmp; // should not happen
772 function insuredTypeCode($ins=0) {
773 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
774 return $this->payers[$ins]['data']['policy_type'];
775 return '';
778 // Is the patient also the subscriber?
780 function isSelfOfInsured($ins=0) {
781 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
782 return (strcmp($tmp,'self') == 0);
785 function planName($ins=0) {
786 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
789 function policyNumber($ins=0) { // "ID"
790 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
793 function groupNumber($ins=0) {
794 return x12clean(trim($this->payers[$ins]['data']['group_number']));
797 function groupName($ins=0) {
798 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
801 // Claim types are:
802 // 16 Other HCFA
803 // MB Medicare Part B
804 // MC Medicaid
805 // CH ChampUSVA
806 // CH ChampUS
807 // BL Blue Cross Blue Shield
808 // 16 FECA
809 // 09 Self Pay
810 // 10 Central Certification
811 // 11 Other Non-Federal Programs
812 // 12 Preferred Provider Organization (PPO)
813 // 13 Point of Service (POS)
814 // 14 Exclusive Provider Organization (EPO)
815 // 15 Indemnity Insurance
816 // 16 Health Maintenance Organization (HMO) Medicare Risk
817 // AM Automobile Medical
818 // CI Commercial Insurance Co.
819 // DS Disability
820 // HM Health Maintenance Organization
821 // LI Liability
822 // LM Liability Medical
823 // OF Other Federal Program
824 // TV Title V
825 // VA Veterans Administration Plan
826 // WC Workers Compensation Health Plan
827 // ZZ Mutually Defined
829 function claimType($ins=0) {
830 if (empty($this->payers[$ins]['object'])) return '';
831 return $this->payers[$ins]['object']->get_freeb_claim_type();
834 function insuredLastName($ins=0) {
835 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
838 function insuredFirstName($ins=0) {
839 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
842 function insuredMiddleName($ins=0) {
843 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
846 function insuredStreet($ins=0) {
847 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
850 function insuredCity($ins=0) {
851 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
854 function insuredState($ins=0) {
855 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
858 function insuredZip($ins=0) {
859 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
862 function insuredPhone($ins=0) {
863 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
864 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
865 return $tmp[1] . $tmp[2] . $tmp[3];
866 return '';
869 function insuredDOB($ins=0) {
870 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
873 function insuredSex($ins=0) {
874 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
877 function payerName($ins=0) {
878 return x12clean(trim($this->payers[$ins]['company']['name']));
881 function payerAttn($ins=0) {
882 return x12clean(trim($this->payers[$ins]['company']['attn']));
885 function payerStreet($ins=0) {
886 if (empty($this->payers[$ins]['object'])) return '';
887 $tmp = $this->payers[$ins]['object'];
888 $tmp = $tmp->get_address();
889 return x12clean(trim($tmp->get_line1()));
892 function payerCity($ins=0) {
893 if (empty($this->payers[$ins]['object'])) return '';
894 $tmp = $this->payers[$ins]['object'];
895 $tmp = $tmp->get_address();
896 return x12clean(trim($tmp->get_city()));
899 function payerState($ins=0) {
900 if (empty($this->payers[$ins]['object'])) return '';
901 $tmp = $this->payers[$ins]['object'];
902 $tmp = $tmp->get_address();
903 return x12clean(trim($tmp->get_state()));
906 function payerZip($ins=0) {
907 if (empty($this->payers[$ins]['object'])) return '';
908 $tmp = $this->payers[$ins]['object'];
909 $tmp = $tmp->get_address();
910 return x12clean(trim($tmp->get_zip()));
913 function payerID($ins=0) {
914 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
917 function payerAltID($ins=0) {
918 return x12clean(trim($this->payers[$ins]['company']['alt_cms_id']));
921 function patientLastName() {
922 return x12clean(trim($this->patient_data['lname']));
925 function patientFirstName() {
926 return x12clean(trim($this->patient_data['fname']));
929 function patientMiddleName() {
930 return x12clean(trim($this->patient_data['mname']));
933 function patientStreet() {
934 return x12clean(trim($this->patient_data['street']));
937 function patientCity() {
938 return x12clean(trim($this->patient_data['city']));
941 function patientState() {
942 return x12clean(trim($this->patient_data['state']));
945 function patientZip() {
946 return x12clean(trim($this->patient_data['postal_code']));
949 function patientPhone() {
950 $ptphone = $this->patient_data['phone_home'];
951 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
952 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
953 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
954 return $tmp[1] . $tmp[2] . $tmp[3];
955 return '';
958 function patientDOB() {
959 return str_replace('-', '', $this->patient_data['DOB']);
962 function patientSex() {
963 return strtoupper(substr($this->patient_data['sex'], 0, 1));
966 // Patient Marital Status: M = Married, S = Single, or something else.
967 function patientStatus() {
968 return strtoupper(substr($this->patient_data['status'], 0, 1));
971 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
972 // indicate employed.
973 function patientOccupation() {
974 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
977 function cptCode($prockey) {
978 return x12clean(trim($this->procs[$prockey]['code']));
981 function cptModifier($prockey) {
982 // Split on the colon or space and clean each modifier
983 $mods = array();
984 $cln_mods = array();
985 $mods = preg_split("/[: ]/",trim($this->procs[$prockey]['modifier']));
986 foreach ($mods as $mod) {
987 array_push($cln_mods, x12clean($mod));
989 return (implode (':', $cln_mods));
992 function cptNotecodes($prockey) {
993 return x12clean(trim($this->procs[$prockey]['notecodes']));
996 // Returns the procedure code, followed by ":modifier" if there is one.
997 function cptKey($prockey) {
998 $tmp = $this->cptModifier($prockey);
999 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
1002 function cptCharges($prockey) {
1003 return x12clean(trim($this->procs[$prockey]['fee']));
1006 function cptUnits($prockey) {
1007 if (empty($this->procs[$prockey]['units'])) return '1';
1008 return x12clean(trim($this->procs[$prockey]['units']));
1011 // NDC drug ID.
1012 function cptNDCID($prockey) {
1013 $ndcinfo = $this->procs[$prockey]['ndc_info'];
1014 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
1015 $ndc = $tmp[1];
1016 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
1017 return sprintf('%05d%04d%02d', $tmp[1], $tmp[2], $tmp[3]);
1019 return x12clean($ndc); // format is bad but return it anyway
1021 return '';
1024 // NDC drug unit of measure code.
1025 function cptNDCUOM($prockey) {
1026 $ndcinfo = $this->procs[$prockey]['ndc_info'];
1027 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
1028 return x12clean($tmp[2]);
1029 return '';
1032 // NDC drug number of units.
1033 function cptNDCQuantity($prockey) {
1034 $ndcinfo = $this->procs[$prockey]['ndc_info'];
1035 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
1036 return x12clean(ltrim($tmp[3], '0'));
1038 return '';
1041 function onsetDate() {
1042 return cleanDate($this->encounter['onset_date']);
1045 function onsetDateValid()
1047 return $this->onsetDate()!=='';
1050 function serviceDate() {
1051 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
1054 function priorAuth() {
1055 return x12clean(trim($this->billing_options['prior_auth_number']));
1058 function isRelatedEmployment() {
1059 return !empty($this->billing_options['employment_related']);
1062 function isRelatedAuto() {
1063 return !empty($this->billing_options['auto_accident']);
1066 function isRelatedOther() {
1067 return !empty($this->billing_options['other_accident']);
1070 function autoAccidentState() {
1071 return x12clean(trim($this->billing_options['accident_state']));
1074 function isUnableToWork() {
1075 return !empty($this->billing_options['is_unable_to_work']);
1078 function offWorkFrom() {
1079 return cleanDate($this->billing_options['off_work_from']);
1082 function offWorkTo() {
1083 return cleanDate($this->billing_options['off_work_to']);
1086 function isHospitalized() {
1087 return !empty($this->billing_options['is_hospitalized']);
1090 function hospitalizedFrom() {
1091 return cleanDate($this->billing_options['hospitalization_date_from']);
1094 function hospitalizedTo() {
1095 return cleanDate($this->billing_options['hospitalization_date_to']);
1098 function isOutsideLab() {
1099 return !empty($this->billing_options['outside_lab']);
1102 function outsideLabAmount() {
1103 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
1106 function medicaidResubmissionCode() {
1107 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
1110 function medicaidOriginalReference() {
1111 return x12clean(trim($this->billing_options['medicaid_original_reference']));
1114 function frequencyTypeCode() {
1115 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
1118 function additionalNotes() {
1119 return x12clean(trim($this->billing_options['comments']));
1122 function dateInitialTreatment() {
1123 return cleanDate($this->billing_options['date_initial_treatment']);
1126 // Returns an array of unique diagnoses. Periods are stripped.
1127 function diagArray() {
1128 $da = array();
1129 foreach ($this->procs as $row) {
1130 $atmp = explode(':', $row['justify']);
1131 foreach ($atmp as $tmp) {
1132 if (!empty($tmp)) {
1133 $code_data = explode('|',$tmp);
1134 if (!empty($code_data[1])) {
1135 //Strip the prepended code type label
1136 $diag = str_replace('.', '', $code_data[1]);
1138 else {
1139 //No prepended code type label
1140 $diag = str_replace('.', '', $code_data[0]);
1142 $da[$diag] = $diag;
1146 // The above got all the diagnoses used for justification, in the order
1147 // used for justification. Next we go through all diagnoses, justified
1148 // or not, to make sure they all get into the claim. We do it this way
1149 // so that the more important diagnoses appear first.
1150 foreach ($this->diags as $diag) {
1151 $diag = str_replace('.', '', $diag);
1152 $da[$diag] = $diag;
1154 return $da;
1157 // Compute one 1-relative index in diagArray for the given procedure.
1158 // This function is obsolete, use diagIndexArray() instead.
1159 function diagIndex($prockey) {
1160 $da = $this->diagArray();
1161 $tmp = explode(':', $this->procs[$prockey]['justify']);
1162 if (empty($tmp)) return '';
1163 $diag = str_replace('.', '', $tmp[0]);
1164 $i = 0;
1165 foreach ($da as $value) {
1166 ++$i;
1167 if (strcmp($value,$diag) == 0) return $i;
1169 return '';
1172 // Compute array of 1-relative diagArray indices for the given procedure.
1173 function diagIndexArray($prockey) {
1174 $dia = array();
1175 $da = $this->diagArray();
1176 $atmp = explode(':', $this->procs[$prockey]['justify']);
1177 foreach ($atmp as $tmp) {
1178 if (!empty($tmp)) {
1179 $code_data = explode('|',$tmp);
1180 if (!empty($code_data[1])) {
1181 //Strip the prepended code type label
1182 $diag = str_replace('.', '', $code_data[1]);
1184 else {
1185 //No prepended code type label
1186 $diag = str_replace('.', '', $code_data[0]);
1188 $i = 0;
1189 foreach ($da as $value) {
1190 ++$i;
1191 if (strcmp($value,$diag) == 0) $dia[] = $i;
1195 return $dia;
1198 function providerLastName($prockey=-1) {
1199 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1200 $this->provider : $this->procs[$prockey]['provider'];
1201 return x12clean(trim($tmp['lname']));
1204 function providerFirstName($prockey=-1) {
1205 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1206 $this->provider : $this->procs[$prockey]['provider'];
1207 return x12clean(trim($tmp['fname']));
1210 function providerMiddleName($prockey=-1) {
1211 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1212 $this->provider : $this->procs[$prockey]['provider'];
1213 return x12clean(trim($tmp['mname']));
1216 function providerNPI($prockey=-1) {
1217 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1218 $this->provider : $this->procs[$prockey]['provider'];
1219 return x12clean(trim($tmp['npi']));
1222 function NPIValid($npi)
1224 // A NPI MUST be a 10 digit number
1225 if($npi==='') return false;
1226 if(strlen($npi)!=10) return false;
1227 if(!preg_match("/[0-9]*/",$npi)) return false;
1228 return true;
1231 function providerNPIValid($prockey=-1)
1233 return $this->NPIValid($this->providerNPI($prockey));
1236 function providerUPIN($prockey=-1) {
1237 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1238 $this->provider : $this->procs[$prockey]['provider'];
1239 return x12clean(trim($tmp['upin']));
1242 function providerSSN($prockey=-1) {
1243 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1244 $this->provider : $this->procs[$prockey]['provider'];
1245 return x12clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1248 function providerTaxonomy($prockey=-1) {
1249 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1250 $this->provider : $this->procs[$prockey]['provider'];
1251 if (empty($tmp['taxonomy'])) return '207Q00000X';
1252 return x12clean(trim($tmp['taxonomy']));
1255 function referrerLastName() {
1256 return x12clean(trim($this->referrer['lname']));
1259 function referrerFirstName() {
1260 return x12clean(trim($this->referrer['fname']));
1263 function referrerMiddleName() {
1264 return x12clean(trim($this->referrer['mname']));
1267 function referrerNPI() {
1268 return x12clean(trim($this->referrer['npi']));
1271 function referrerUPIN() {
1272 return x12clean(trim($this->referrer['upin']));
1275 function referrerSSN() {
1276 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
1279 function referrerTaxonomy() {
1280 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1281 return x12clean(trim($this->referrer['taxonomy']));
1284 function supervisorLastName() {
1285 return x12clean(trim($this->supervisor['lname']));
1288 function supervisorFirstName() {
1289 return x12clean(trim($this->supervisor['fname']));
1292 function supervisorMiddleName() {
1293 return x12clean(trim($this->supervisor['mname']));
1296 function supervisorNPI() {
1297 return x12clean(trim($this->supervisor['npi']));
1300 function supervisorUPIN() {
1301 return x12clean(trim($this->supervisor['upin']));
1304 function supervisorSSN() {
1305 return x12clean(trim(str_replace('-', '', $this->supervisor['federaltaxid'])));
1308 function supervisorTaxonomy() {
1309 if (empty($this->supervisor['taxonomy'])) return '207Q00000X';
1310 return x12clean(trim($this->supervisor['taxonomy']));
1313 function supervisorNumberType() {
1314 return $this->supervisor_numbers['provider_number_type'];
1317 function supervisorNumber() {
1318 return x12clean(trim(str_replace('-', '', $this->supervisor_numbers['provider_number'])));