Support for storing code type in justify column of billing sql table
[openemr.git] / library / Claim.class.php
blobff65883a44bcdeafa299e964d04cb7b1d87aa1d2
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 billing 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 * FROM billing WHERE " .
149 "encounter = '{$this->encounter_id}' AND pid = '{$this->pid}' AND " .
150 "(code_type = 'CPT4' OR code_type = 'HCPCS' OR code_type = 'COPAY' OR code_type = 'ICD9') AND " .
151 "activity = '1' ORDER BY date, id";
152 $res = sqlStatement($sql);
153 while ($row = sqlFetchArray($res)) {
154 if ($row['code_type'] == 'COPAY') {
155 $this->copay -= $row['fee'];
156 continue;
158 // Save all diagnosis codes.
159 if ($row['code_type'] == 'ICD9') {
160 $this->diags[$row['code']] = $row['code'];
161 continue;
163 if (!$row['units']) $row['units'] = 1;
164 // Load prior payer data at the first opportunity in order to get
165 // the using_modifiers flag that is referenced below.
166 if (empty($this->procs)) $this->loadPayerInfo($row);
167 // Consolidate duplicate procedures.
168 foreach ($this->procs as $key => $trash) {
169 if (strcmp($this->procs[$key]['code'],$row['code']) == 0 &&
170 (strcmp($this->procs[$key]['modifier'],$row['modifier']) == 0 ||
171 !$this->using_modifiers))
173 $this->procs[$key]['units'] += $row['units'];
174 $this->procs[$key]['fee'] += $row['fee'];
175 continue 2; // skip to next table row
179 // If there is a row-specific provider then get its details.
180 if (!empty($row['provider_id'])) {
181 // Get service provider data for this row.
182 $sql = "SELECT * FROM users WHERE id = '" . $row['provider_id'] . "'";
183 $row['provider'] = sqlQuery($sql);
184 // Get insurance numbers for this row's provider.
185 $sql = "SELECT * FROM insurance_numbers WHERE " .
186 "(insurance_company_id = '" . $row['payer_id'] .
187 "' OR insurance_company_id is NULL) AND " .
188 "provider_id = '" . $row['provider_id'] . "' " .
189 "ORDER BY insurance_company_id DESC LIMIT 1";
190 $row['insurance_numbers'] = sqlQuery($sql);
193 $this->procs[] = $row;
196 $resMoneyGot = sqlStatement("SELECT pay_amount as PatientPay,session_id as id,".
197 "date(post_time) as date FROM ar_activity where pid ='{$this->pid}' and encounter ='{$this->encounter_id}' ".
198 "and payer_type=0 and account_code='PCP'");
199 //new fees screen copay gives account_code='PCP'
200 while($rowMoneyGot = sqlFetchArray($resMoneyGot)){
201 $PatientPay=$rowMoneyGot['PatientPay']*-1;
202 $this->copay -= $PatientPay;
205 $sql = "SELECT * FROM x12_partners WHERE " .
206 "id = '" . $this->procs[0]['x12_partner_id'] . "'";
207 $this->x12_partner = sqlQuery($sql);
209 $sql = "SELECT * FROM facility WHERE " .
210 "id = '" . addslashes($this->encounter['facility_id']) . "' " .
211 "LIMIT 1";
212 $this->facility = sqlQuery($sql);
214 /*****************************************************************
215 $provider_id = $this->procs[0]['provider_id'];
216 *****************************************************************/
217 $provider_id = $this->encounter['provider_id'];
218 $sql = "SELECT * FROM users WHERE id = '$provider_id'";
219 $this->provider = sqlQuery($sql);
220 // Selecting the billing facility assigned to the encounter. If none,
221 // try the first (and hopefully only) facility marked as a billing location.
222 if (empty($this->encounter['billing_facility'])) {
223 $sql = "SELECT * FROM facility " .
224 "ORDER BY billing_location DESC, id ASC LIMIT 1";
226 else {
227 $sql = "SELECT * FROM facility " .
228 " where id ='" . addslashes($this->encounter['billing_facility']) . "' ";
230 $this->billing_facility = sqlQuery($sql);
232 $sql = "SELECT * FROM insurance_numbers WHERE " .
233 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
234 "' OR insurance_company_id is NULL) AND " .
235 "provider_id = '$provider_id' " .
236 "ORDER BY insurance_company_id DESC LIMIT 1";
237 $this->insurance_numbers = sqlQuery($sql);
239 $sql = "SELECT * FROM patient_data WHERE " .
240 "pid = '{$this->pid}' " .
241 "ORDER BY id LIMIT 1";
242 $this->patient_data = sqlQuery($sql);
244 $sql = "SELECT fpa.* FROM forms JOIN form_misc_billing_options AS fpa " .
245 "ON fpa.id = forms.form_id WHERE " .
246 "forms.encounter = '{$this->encounter_id}' AND " .
247 "forms.pid = '{$this->pid}' AND " .
248 "forms.deleted = 0 AND " .
249 "forms.formdir = 'misc_billing_options' " .
250 "ORDER BY forms.date";
251 $this->billing_options = sqlQuery($sql);
253 $referrer_id = (empty($GLOBALS['MedicareReferrerIsRenderer']) ||
254 $this->insurance_numbers['provider_number_type'] != '1C') ?
255 $this->patient_data['ref_providerID'] : $provider_id;
256 $sql = "SELECT * FROM users WHERE id = '$referrer_id'";
257 $this->referrer = sqlQuery($sql);
258 if (!$this->referrer) $this->referrer = array();
260 $supervisor_id = $this->encounter['supervisor_id'];
261 $sql = "SELECT * FROM users WHERE id = '$supervisor_id'";
262 $this->supervisor = sqlQuery($sql);
263 if (!$this->supervisor) $this->supervisor = array();
265 $sql = "SELECT * FROM insurance_numbers WHERE " .
266 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
267 "' OR insurance_company_id is NULL) AND " .
268 "provider_id = '$supervisor_id' " .
269 "ORDER BY insurance_company_id DESC LIMIT 1";
270 $this->supervisor_numbers = sqlQuery($sql);
271 if (!$this->supervisor_numbers) $this->supervisor_numbers = array();
273 } // end constructor
275 // Return an array of adjustments from the designated prior payer for the
276 // designated procedure key (might be procedure:modifier), or for the claim
277 // level. For each adjustment give date, group code, reason code, amount.
278 // Note this will include "patient responsibility" adjustments which are
279 // not adjustments to OUR invoice, but they reduce the amount that the
280 // insurance company pays.
282 function payerAdjustments($ins, $code='Claim') {
283 $aadj = array();
285 // If we have no modifiers stored in SQL-Ledger for this claim,
286 // then we cannot use a modifier passed in with the key.
287 $tmp = strpos($code, ':');
288 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
290 // For payments, source always starts with "Ins" or "Pt".
291 // Nonzero adjustment reason examples:
292 // Ins1 adjust code 42 (Charges exceed ... (obsolete))
293 // Ins1 adjust code 45 (Charges exceed your contracted/ legislated fee arrangement)
294 // Ins1 adjust code 97 (Payment is included in the allowance for another service/procedure)
295 // Ins1 adjust code A2 (Contractual adjustment)
296 // Ins adjust Ins1
297 // adjust code 45
298 // Zero adjustment reason examples:
299 // Co-pay: 25.00
300 // Coinsurance: 11.46 (code 2) Note: fix remits to identify insurance
301 // To deductible: 0.22 (code 1) Note: fix remits to identify insurance
302 // To copay Ins1 (manual entry)
303 // To ded'ble Ins1 (manual entry)
305 if (!empty($this->invoice[$code])) {
306 $date = '';
307 $deductible = 0;
308 $coinsurance = 0;
309 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
310 $insnumber = substr($inslabel, 3);
312 // Compute this procedure's patient responsibility amount as of this
313 // prior payer, which is the original charge minus all insurance
314 // payments and "hard" adjustments up to this payer.
315 $ptresp = $this->invoice[$code]['chg'] + $this->invoice[$code]['adj'];
316 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
317 if (isset($value['plv'])) {
318 // New method; plv (from ar_activity.payer_type) exists to
319 // indicate the payer level.
320 if (isset($value['pmt']) && $value['pmt'] != 0) {
321 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
322 $ptresp -= $value['pmt'];
324 else if (isset($value['chg']) && trim(substr($key, 0, 10))) {
325 // non-blank key indicates this is an adjustment and not a charge
326 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
327 $ptresp += $value['chg']; // adjustments are negative charges
330 $msp = isset( $value['msp'] ) ? $value['msp'] : null; // record the reason for adjustment
332 else {
333 // Old method: With SQL-Ledger payer level was stored in the memo.
334 if (preg_match("/^Ins(\d)/i", $value['src'], $tmp)) {
335 if ($tmp[1] <= $insnumber) $ptresp -= $value['pmt'];
337 else if (trim(substr($key, 0, 10))) { // not an adjustment if no date
338 if (!preg_match("/Ins(\d)/i", $value['rsn'], $tmp) || $tmp[1] <= $insnumber)
339 $ptresp += $value['chg']; // adjustments are negative charges
343 if ($ptresp < 0) $ptresp = 0; // we may be insane but try to hide it
345 // Main loop, to extract adjustments for this payer and procedure.
346 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
347 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
348 if ($tmp) $date = $tmp;
349 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
350 $rsn = $value['rsn'];
351 $chg = 0 - $value['chg']; // adjustments are negative charges
353 $gcode = 'CO'; // default group code = contractual obligation
354 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
356 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
357 // From manual post. Take the defaults.
359 else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
360 $coinsurance = $ptresp; // from manual post
361 continue;
363 else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
364 $deductible = $ptresp; // from manual post
365 continue;
367 else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
368 $coinsurance = $tmp[1]; // from 835 as of 6/2007
369 continue;
371 else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
372 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
373 continue;
375 else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
376 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
377 continue;
379 else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
380 continue; // from 835 as of 6/2007
382 else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
383 $rcode = $tmp[1]; // from 835
385 else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
386 // Take the defaults.
388 else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
389 continue; // it's for some other payer
391 else if ($insnumber == '1') {
392 if (preg_match("/\$\s*adjust code (\S+)/i", $rsn, $tmp)) {
393 $rcode = $tmp[1]; // from 835
395 else if ($chg) {
396 // Other adjustments default to Ins1.
398 else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
399 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
400 $coinsurance = 0 + $tmp[1]; // from 835 before 6/2007
401 continue;
403 else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
404 $deductible = 0 + $tmp[1]; // from 835 before 6/2007
405 continue;
407 else {
408 continue; // there is no adjustment amount
411 else {
412 continue; // it's for primary and that's not us
415 if ($rcode == '42') $rcode= '45'; // reason 42 is obsolete
416 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
418 } // end if
419 } // end foreach
421 // If we really messed it up, at least avoid negative numbers.
422 if ($coinsurance > $ptresp) $coinsurance = $ptresp;
423 if ($deductible > $ptresp) $deductible = $ptresp;
425 // Find out if this payer paid anything at all on this claim. This will
426 // help us allocate any unknown patient responsibility amounts.
427 $thispaidanything = 0;
428 foreach($this->invoice as $codekey => $codeval) {
429 foreach ($codeval['dtl'] as $key => $value) {
430 if (isset($value['plv'])) {
431 // New method; plv exists to indicate the payer level.
432 if ($value['plv'] == $insnumber) {
433 $thispaidanything += $value['pmt'];
436 else {
437 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
438 $thispaidanything += $value['pmt'];
444 // Allocate any unknown patient responsibility by guessing if the
445 // deductible has been satisfied.
446 if ($thispaidanything)
447 $coinsurance = $ptresp - $deductible;
448 else
449 $deductible = $ptresp - $coinsurance;
451 $deductible = sprintf('%.2f', $deductible);
452 $coinsurance = sprintf('%.2f', $coinsurance);
454 if ($date && $deductible != 0)
455 $aadj[] = array($date, 'PR', '1', $deductible, $msp);
456 if ($date && $coinsurance != 0)
457 $aadj[] = array($date, 'PR', '2', $coinsurance, $msp);
459 } // end if
461 return $aadj;
464 // Return date, total payments and total "hard" adjustments from the given
465 // prior payer. If $code is specified then only that procedure key is
466 // selected, otherwise it's for the whole claim.
468 function payerTotals($ins, $code='') {
469 // If we have no modifiers stored in SQL-Ledger for this claim,
470 // then we cannot use a modifier passed in with the key.
471 $tmp = strpos($code, ':');
472 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
474 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
475 $insnumber = substr($inslabel, 3);
476 $paytotal = 0;
477 $adjtotal = 0;
478 $date = '';
479 foreach($this->invoice as $codekey => $codeval) {
480 if ($code && strcmp($codekey,$code) != 0) continue;
481 foreach ($codeval['dtl'] as $key => $value) {
482 if (isset($value['plv'])) {
483 // New method; plv (from ar_activity.payer_type) exists to
484 // indicate the payer level.
485 if ($value['plv'] == $insnumber) {
486 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
487 $paytotal += $value['pmt'];
490 else {
491 // Old method: With SQL-Ledger payer level was stored in the memo.
492 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
493 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
494 $paytotal += $value['pmt'];
498 $aarr = $this->payerAdjustments($ins, $codekey);
499 foreach ($aarr as $a) {
500 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
501 if (!$date) $date = $a[0];
504 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
507 // Return the amount already paid by the patient.
509 function patientPaidAmount() {
510 // For primary claims $this->invoice is not loaded, so get the co-pay
511 // from the billing table instead.
512 if (empty($this->invoice)) return $this->copay;
514 $amount = 0;
515 foreach($this->invoice as $codekey => $codeval) {
516 foreach ($codeval['dtl'] as $key => $value) {
517 if (isset($value['plv'])) {
518 // New method; plv exists to indicate the payer level.
519 if ($value['plv'] == 0) { // 0 indicates patient
520 $amount += $value['pmt'];
523 else {
524 // Old method: With SQL-Ledger payer level was stored in the memo.
525 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
526 $amount += $value['pmt'];
531 return sprintf('%.2f', $amount);
534 // Return invoice total, including adjustments but not payments.
536 function invoiceTotal() {
537 $amount = 0;
538 foreach($this->invoice as $codekey => $codeval) {
539 $amount += $codeval['chg'];
541 return sprintf('%.2f', $amount);
544 // Number of procedures in this claim.
545 function procCount() {
546 return count($this->procs);
549 // Number of payers for this claim. Ranges from 1 to 3.
550 function payerCount() {
551 return count($this->payers);
554 function x12gsversionstring() {
555 return x12clean(trim($this->x12_partner['x12_version']));
558 function x12gssenderid() {
559 $tmp = $this->x12_partner['x12_sender_id'];
560 while (strlen($tmp) < 15) $tmp .= " ";
561 return $tmp;
564 function x12gs03() {
566 * GS03: Application Receiver's Code
567 * Code Identifying Party Receiving Transmission
569 * In most cases, the ISA08 and GS03 are the same. However
571 * In some clearing houses ISA08 and GS03 are different
572 * Example: http://www.acs-gcro.com/downloads/DOL/DOL_CG_X12N_5010_837_v1_02.pdf - Page 18
573 * In this .pdf, the ISA08 is specified to be 100000 while the GS03 is specified to be 77044
575 * Therefore if the x12_gs03 segement is explicitly specified we use that value,
576 * otherwise we simply use the same receiver ID as specified for ISA03
578 if($this->x12_partner['x12_gs03'] !== '')
579 return $this->x12_partner['x12_gs03'];
580 else
581 return $this->x12_partner['x12_receiver_id'];
584 function x12gsreceiverid() {
585 $tmp = $this->x12_partner['x12_receiver_id'];
586 while (strlen($tmp) < 15) $tmp .= " ";
587 return $tmp;
590 function x12gsisa05() {
591 return $this->x12_partner['x12_isa05'];
593 //adding in functions for isa 01 - isa 04
595 function x12gsisa01() {
596 return $this->x12_partner['x12_isa01'];
599 function x12gsisa02() {
600 return $this->x12_partner['x12_isa02'];
603 function x12gsisa03() {
604 return $this->x12_partner['x12_isa03'];
606 function x12gsisa04() {
607 return $this->x12_partner['x12_isa04'];
610 /////////
611 function x12gsisa07() {
612 return $this->x12_partner['x12_isa07'];
615 function x12gsisa14() {
616 return $this->x12_partner['x12_isa14'];
619 function x12gsisa15() {
620 return $this->x12_partner['x12_isa15'];
623 function x12gsgs02() {
624 $tmp = $this->x12_partner['x12_gs02'];
625 if ($tmp === '') $tmp = $this->x12_partner['x12_sender_id'];
626 return $tmp;
629 function x12gsper06() {
630 return $this->x12_partner['x12_per06'];
633 function cliaCode() {
634 return x12clean(trim($this->facility['domain_identifier']));
637 function billingFacilityName() {
638 return x12clean(trim($this->billing_facility['name']));
641 function billingFacilityStreet() {
642 return x12clean(trim($this->billing_facility['street']));
645 function billingFacilityCity() {
646 return x12clean(trim($this->billing_facility['city']));
649 function billingFacilityState() {
650 return x12clean(trim($this->billing_facility['state']));
653 function billingFacilityZip() {
654 return x12clean(trim($this->billing_facility['postal_code']));
657 function billingFacilityETIN() {
658 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
661 function billingFacilityNPI() {
662 return x12clean(trim($this->billing_facility['facility_npi']));
665 function federalIdType() {
666 if ($this->billing_facility['tax_id_type'])
668 return $this->billing_facility['tax_id_type'];
670 else{
671 return null;
675 # The billing facility and the patient must both accept for this to return true.
676 function billingFacilityAssignment($ins=0) {
677 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
678 if (strcmp($tmp,'FALSE') == 0) return '0';
679 return !empty($this->billing_facility['accepts_assignment']);
682 function billingContactName() {
683 return x12clean(trim($this->billing_facility['attn']));
686 function billingContactPhone() {
687 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
688 $this->billing_facility['phone'], $tmp))
690 return $tmp[1] . $tmp[2] . $tmp[3];
692 return '';
695 function facilityName() {
696 return x12clean(trim($this->facility['name']));
699 function facilityStreet() {
700 return x12clean(trim($this->facility['street']));
703 function facilityCity() {
704 return x12clean(trim($this->facility['city']));
707 function facilityState() {
708 return x12clean(trim($this->facility['state']));
711 function facilityZip() {
712 return x12clean(trim($this->facility['postal_code']));
715 function facilityETIN() {
716 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
719 function facilityNPI() {
720 return x12clean(trim($this->facility['facility_npi']));
723 function facilityPOS() {
724 return sprintf('%02d', trim($this->facility['pos_code']));
727 function clearingHouseName() {
728 return x12clean(trim($this->x12_partner['name']));
731 function clearingHouseETIN() {
732 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
735 function providerNumberType($prockey=-1) {
736 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
737 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
738 return $tmp['provider_number_type'];
741 function providerNumber($prockey=-1) {
742 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
743 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
744 return x12clean(trim(str_replace('-', '', $tmp['provider_number'])));
747 function providerGroupNumber($prockey=-1) {
748 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
749 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
750 return x12clean(trim(str_replace('-', '', $tmp['group_number'])));
753 // Returns 'P', 'S' or 'T'.
755 function payerSequence($ins=0) {
756 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
759 // Returns the HIPAA code of the patient-to-subscriber relationship.
761 function insuredRelationship($ins=0) {
762 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
763 if (strcmp($tmp,'self' ) == 0) return '18';
764 if (strcmp($tmp,'spouse') == 0) return '01';
765 if (strcmp($tmp,'child' ) == 0) return '19';
766 if (strcmp($tmp,'other' ) == 0) return 'G8';
767 return $tmp; // should not happen
770 function insuredTypeCode($ins=0) {
771 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
772 return $this->payers[$ins]['data']['policy_type'];
773 return '';
776 // Is the patient also the subscriber?
778 function isSelfOfInsured($ins=0) {
779 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
780 return (strcmp($tmp,'self') == 0);
783 function planName($ins=0) {
784 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
787 function policyNumber($ins=0) { // "ID"
788 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
791 function groupNumber($ins=0) {
792 return x12clean(trim($this->payers[$ins]['data']['group_number']));
795 function groupName($ins=0) {
796 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
799 // Claim types are:
800 // 16 Other HCFA
801 // MB Medicare Part B
802 // MC Medicaid
803 // CH ChampUSVA
804 // CH ChampUS
805 // BL Blue Cross Blue Shield
806 // 16 FECA
807 // 09 Self Pay
808 // 10 Central Certification
809 // 11 Other Non-Federal Programs
810 // 12 Preferred Provider Organization (PPO)
811 // 13 Point of Service (POS)
812 // 14 Exclusive Provider Organization (EPO)
813 // 15 Indemnity Insurance
814 // 16 Health Maintenance Organization (HMO) Medicare Risk
815 // AM Automobile Medical
816 // CI Commercial Insurance Co.
817 // DS Disability
818 // HM Health Maintenance Organization
819 // LI Liability
820 // LM Liability Medical
821 // OF Other Federal Program
822 // TV Title V
823 // VA Veterans Administration Plan
824 // WC Workers Compensation Health Plan
825 // ZZ Mutually Defined
827 function claimType($ins=0) {
828 if (empty($this->payers[$ins]['object'])) return '';
829 return $this->payers[$ins]['object']->get_freeb_claim_type();
832 function insuredLastName($ins=0) {
833 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
836 function insuredFirstName($ins=0) {
837 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
840 function insuredMiddleName($ins=0) {
841 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
844 function insuredStreet($ins=0) {
845 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
848 function insuredCity($ins=0) {
849 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
852 function insuredState($ins=0) {
853 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
856 function insuredZip($ins=0) {
857 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
860 function insuredPhone($ins=0) {
861 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
862 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
863 return $tmp[1] . $tmp[2] . $tmp[3];
864 return '';
867 function insuredDOB($ins=0) {
868 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
871 function insuredSex($ins=0) {
872 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
875 function payerName($ins=0) {
876 return x12clean(trim($this->payers[$ins]['company']['name']));
879 function payerAttn($ins=0) {
880 return x12clean(trim($this->payers[$ins]['company']['attn']));
883 function payerStreet($ins=0) {
884 if (empty($this->payers[$ins]['object'])) return '';
885 $tmp = $this->payers[$ins]['object'];
886 $tmp = $tmp->get_address();
887 return x12clean(trim($tmp->get_line1()));
890 function payerCity($ins=0) {
891 if (empty($this->payers[$ins]['object'])) return '';
892 $tmp = $this->payers[$ins]['object'];
893 $tmp = $tmp->get_address();
894 return x12clean(trim($tmp->get_city()));
897 function payerState($ins=0) {
898 if (empty($this->payers[$ins]['object'])) return '';
899 $tmp = $this->payers[$ins]['object'];
900 $tmp = $tmp->get_address();
901 return x12clean(trim($tmp->get_state()));
904 function payerZip($ins=0) {
905 if (empty($this->payers[$ins]['object'])) return '';
906 $tmp = $this->payers[$ins]['object'];
907 $tmp = $tmp->get_address();
908 return x12clean(trim($tmp->get_zip()));
911 function payerID($ins=0) {
912 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
915 function payerAltID($ins=0) {
916 return x12clean(trim($this->payers[$ins]['company']['alt_cms_id']));
919 function patientLastName() {
920 return x12clean(trim($this->patient_data['lname']));
923 function patientFirstName() {
924 return x12clean(trim($this->patient_data['fname']));
927 function patientMiddleName() {
928 return x12clean(trim($this->patient_data['mname']));
931 function patientStreet() {
932 return x12clean(trim($this->patient_data['street']));
935 function patientCity() {
936 return x12clean(trim($this->patient_data['city']));
939 function patientState() {
940 return x12clean(trim($this->patient_data['state']));
943 function patientZip() {
944 return x12clean(trim($this->patient_data['postal_code']));
947 function patientPhone() {
948 $ptphone = $this->patient_data['phone_home'];
949 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
950 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
951 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
952 return $tmp[1] . $tmp[2] . $tmp[3];
953 return '';
956 function patientDOB() {
957 return str_replace('-', '', $this->patient_data['DOB']);
960 function patientSex() {
961 return strtoupper(substr($this->patient_data['sex'], 0, 1));
964 // Patient Marital Status: M = Married, S = Single, or something else.
965 function patientStatus() {
966 return strtoupper(substr($this->patient_data['status'], 0, 1));
969 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
970 // indicate employed.
971 function patientOccupation() {
972 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
975 function cptCode($prockey) {
976 return x12clean(trim($this->procs[$prockey]['code']));
979 function cptModifier($prockey) {
980 // Split on the colon or space and clean each modifier
981 $mods = array();
982 $cln_mods = array();
983 $mods = preg_split("/[: ]/",trim($this->procs[$prockey]['modifier']));
984 foreach ($mods as $mod) {
985 array_push($cln_mods, x12clean($mod));
987 return (implode (':', $cln_mods));
990 function cptNotecodes($prockey) {
991 return x12clean(trim($this->procs[$prockey]['notecodes']));
994 // Returns the procedure code, followed by ":modifier" if there is one.
995 function cptKey($prockey) {
996 $tmp = $this->cptModifier($prockey);
997 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
1000 function cptCharges($prockey) {
1001 return x12clean(trim($this->procs[$prockey]['fee']));
1004 function cptUnits($prockey) {
1005 if (empty($this->procs[$prockey]['units'])) return '1';
1006 return x12clean(trim($this->procs[$prockey]['units']));
1009 // NDC drug ID.
1010 function cptNDCID($prockey) {
1011 $ndcinfo = $this->procs[$prockey]['ndc_info'];
1012 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
1013 $ndc = $tmp[1];
1014 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
1015 return sprintf('%05d%04d%02d', $tmp[1], $tmp[2], $tmp[3]);
1017 return x12clean($ndc); // format is bad but return it anyway
1019 return '';
1022 // NDC drug unit of measure code.
1023 function cptNDCUOM($prockey) {
1024 $ndcinfo = $this->procs[$prockey]['ndc_info'];
1025 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
1026 return x12clean($tmp[2]);
1027 return '';
1030 // NDC drug number of units.
1031 function cptNDCQuantity($prockey) {
1032 $ndcinfo = $this->procs[$prockey]['ndc_info'];
1033 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
1034 return x12clean(ltrim($tmp[3], '0'));
1036 return '';
1039 function onsetDate() {
1040 return cleanDate($this->encounter['onset_date']);
1043 function onsetDateValid()
1045 return $this->onsetDate()!=='';
1048 function serviceDate() {
1049 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
1052 function priorAuth() {
1053 return x12clean(trim($this->billing_options['prior_auth_number']));
1056 function isRelatedEmployment() {
1057 return !empty($this->billing_options['employment_related']);
1060 function isRelatedAuto() {
1061 return !empty($this->billing_options['auto_accident']);
1064 function isRelatedOther() {
1065 return !empty($this->billing_options['other_accident']);
1068 function autoAccidentState() {
1069 return x12clean(trim($this->billing_options['accident_state']));
1072 function isUnableToWork() {
1073 return !empty($this->billing_options['is_unable_to_work']);
1076 function offWorkFrom() {
1077 return cleanDate($this->billing_options['off_work_from']);
1080 function offWorkTo() {
1081 return cleanDate($this->billing_options['off_work_to']);
1084 function isHospitalized() {
1085 return !empty($this->billing_options['is_hospitalized']);
1088 function hospitalizedFrom() {
1089 return cleanDate($this->billing_options['hospitalization_date_from']);
1092 function hospitalizedTo() {
1093 return cleanDate($this->billing_options['hospitalization_date_to']);
1096 function isOutsideLab() {
1097 return !empty($this->billing_options['outside_lab']);
1100 function outsideLabAmount() {
1101 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
1104 function medicaidResubmissionCode() {
1105 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
1108 function medicaidOriginalReference() {
1109 return x12clean(trim($this->billing_options['medicaid_original_reference']));
1112 function frequencyTypeCode() {
1113 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
1116 function additionalNotes() {
1117 return x12clean(trim($this->billing_options['comments']));
1120 function dateInitialTreatment() {
1121 return cleanDate($this->billing_options['date_initial_treatment']);
1124 // Returns an array of unique diagnoses. Periods are stripped.
1125 function diagArray() {
1126 $da = array();
1127 foreach ($this->procs as $row) {
1128 $atmp = explode(':', $row['justify']);
1129 foreach ($atmp as $tmp) {
1130 if (!empty($tmp)) {
1131 $code_data = explode('|',$tmp);
1132 if (!empty($code_data[1])) {
1133 //Strip the prepended code type label
1134 $diag = str_replace('.', '', $code_data[1]);
1136 else {
1137 //No prepended code type label
1138 $diag = str_replace('.', '', $code_data[0]);
1140 $da[$diag] = $diag;
1144 // The above got all the diagnoses used for justification, in the order
1145 // used for justification. Next we go through all diagnoses, justified
1146 // or not, to make sure they all get into the claim. We do it this way
1147 // so that the more important diagnoses appear first.
1148 foreach ($this->diags as $diag) {
1149 $diag = str_replace('.', '', $diag);
1150 $da[$diag] = $diag;
1152 return $da;
1155 // Compute one 1-relative index in diagArray for the given procedure.
1156 // This function is obsolete, use diagIndexArray() instead.
1157 function diagIndex($prockey) {
1158 $da = $this->diagArray();
1159 $tmp = explode(':', $this->procs[$prockey]['justify']);
1160 if (empty($tmp)) return '';
1161 $diag = str_replace('.', '', $tmp[0]);
1162 $i = 0;
1163 foreach ($da as $value) {
1164 ++$i;
1165 if (strcmp($value,$diag) == 0) return $i;
1167 return '';
1170 // Compute array of 1-relative diagArray indices for the given procedure.
1171 function diagIndexArray($prockey) {
1172 $dia = array();
1173 $da = $this->diagArray();
1174 $atmp = explode(':', $this->procs[$prockey]['justify']);
1175 foreach ($atmp as $tmp) {
1176 if (!empty($tmp)) {
1177 $code_data = explode('|',$tmp);
1178 if (!empty($code_data[1])) {
1179 //Strip the prepended code type label
1180 $diag = str_replace('.', '', $code_data[1]);
1182 else {
1183 //No prepended code type label
1184 $diag = str_replace('.', '', $code_data[0]);
1186 $i = 0;
1187 foreach ($da as $value) {
1188 ++$i;
1189 if (strcmp($value,$diag) == 0) $dia[] = $i;
1193 return $dia;
1196 function providerLastName($prockey=-1) {
1197 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1198 $this->provider : $this->procs[$prockey]['provider'];
1199 return x12clean(trim($tmp['lname']));
1202 function providerFirstName($prockey=-1) {
1203 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1204 $this->provider : $this->procs[$prockey]['provider'];
1205 return x12clean(trim($tmp['fname']));
1208 function providerMiddleName($prockey=-1) {
1209 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1210 $this->provider : $this->procs[$prockey]['provider'];
1211 return x12clean(trim($tmp['mname']));
1214 function providerNPI($prockey=-1) {
1215 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1216 $this->provider : $this->procs[$prockey]['provider'];
1217 return x12clean(trim($tmp['npi']));
1220 function NPIValid($npi)
1222 // A NPI MUST be a 10 digit number
1223 if($npi==='') return false;
1224 if(strlen($npi)!=10) return false;
1225 if(!preg_match("/[0-9]*/",$npi)) return false;
1226 return true;
1229 function providerNPIValid($prockey=-1)
1231 return $this->NPIValid($this->providerNPI($prockey));
1234 function providerUPIN($prockey=-1) {
1235 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1236 $this->provider : $this->procs[$prockey]['provider'];
1237 return x12clean(trim($tmp['upin']));
1240 function providerSSN($prockey=-1) {
1241 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1242 $this->provider : $this->procs[$prockey]['provider'];
1243 return x12clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1246 function providerTaxonomy($prockey=-1) {
1247 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1248 $this->provider : $this->procs[$prockey]['provider'];
1249 if (empty($tmp['taxonomy'])) return '207Q00000X';
1250 return x12clean(trim($tmp['taxonomy']));
1253 function referrerLastName() {
1254 return x12clean(trim($this->referrer['lname']));
1257 function referrerFirstName() {
1258 return x12clean(trim($this->referrer['fname']));
1261 function referrerMiddleName() {
1262 return x12clean(trim($this->referrer['mname']));
1265 function referrerNPI() {
1266 return x12clean(trim($this->referrer['npi']));
1269 function referrerUPIN() {
1270 return x12clean(trim($this->referrer['upin']));
1273 function referrerSSN() {
1274 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
1277 function referrerTaxonomy() {
1278 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1279 return x12clean(trim($this->referrer['taxonomy']));
1282 function supervisorLastName() {
1283 return x12clean(trim($this->supervisor['lname']));
1286 function supervisorFirstName() {
1287 return x12clean(trim($this->supervisor['fname']));
1290 function supervisorMiddleName() {
1291 return x12clean(trim($this->supervisor['mname']));
1294 function supervisorNPI() {
1295 return x12clean(trim($this->supervisor['npi']));
1298 function supervisorUPIN() {
1299 return x12clean(trim($this->supervisor['upin']));
1302 function supervisorSSN() {
1303 return x12clean(trim(str_replace('-', '', $this->supervisor['federaltaxid'])));
1306 function supervisorTaxonomy() {
1307 if (empty($this->supervisor['taxonomy'])) return '207Q00000X';
1308 return x12clean(trim($this->supervisor['taxonomy']));
1311 function supervisorNumberType() {
1312 return $this->supervisor_numbers['provider_number_type'];
1315 function supervisorNumber() {
1316 return x12clean(trim(str_replace('-', '', $this->supervisor_numbers['provider_number'])));