A couple of fixes for secondary X12 claims
[openemr.git] / library / Claim.class.php
blobd507ce2f4161fc9c5a63f1a2f7a6af6e95bda026
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 class Claim {
22 var $pid; // patient id
23 var $encounter_id; // encounter id
24 var $procs; // array of procedure rows from billing table
25 var $diags; // array of icd9 codes from billing table
26 var $x12_partner; // row from x12_partners table
27 var $encounter; // row from form_encounter table
28 var $facility; // row from facility table
29 var $billing_facility; // row from facility table
30 var $provider; // row from users table (rendering provider)
31 var $referrer; // row from users table (referring provider)
32 var $supervisor; // row from users table (supervising provider)
33 var $insurance_numbers; // row from insurance_numbers table for current payer
34 var $supervisor_numbers; // row from insurance_numbers table for current payer
35 var $patient_data; // row from patient_data table
36 var $billing_options; // row from form_misc_billing_options table
37 var $invoice; // result from get_invoice_summary()
38 var $payers; // array of arrays, for all payers
39 var $copay; // total of copays from the billing table
41 function loadPayerInfo(&$billrow) {
42 global $sl_err;
43 $encounter_date = substr($this->encounter['date'], 0, 10);
45 // Create the $payers array. This contains data for all insurances
46 // with the current one always at index 0, and the others in payment
47 // order starting at index 1.
49 $this->payers = array();
50 $this->payers[0] = array();
51 $query = "SELECT * FROM insurance_data WHERE " .
52 "pid = '{$this->pid}' AND " .
53 "date <= '$encounter_date' " .
54 "ORDER BY type ASC, date DESC";
55 $dres = sqlStatement($query);
56 $prevtype = '';
57 while ($drow = sqlFetchArray($dres)) {
58 if (strcmp($prevtype, $drow['type']) == 0) continue;
59 $prevtype = $drow['type'];
60 // Very important to look at entries with a missing provider because
61 // they indicate no insurance as of the given date.
62 if (empty($drow['provider'])) continue;
63 $ins = count($this->payers);
64 if ($drow['provider'] == $billrow['payer_id'] && empty($this->payers[0]['data'])) $ins = 0;
65 $crow = sqlQuery("SELECT * FROM insurance_companies WHERE " .
66 "id = '" . $drow['provider'] . "'");
67 $orow = new InsuranceCompany($drow['provider']);
68 $this->payers[$ins] = array();
69 $this->payers[$ins]['data'] = $drow;
70 $this->payers[$ins]['company'] = $crow;
71 $this->payers[$ins]['object'] = $orow;
74 // This kludge hands most cases of a rare ambiguous situation, where
75 // the primary insurance company is the same as the secondary. It seems
76 // nobody planned for that!
78 for ($i = 1; $i < count($this->payers); ++$i) {
79 if ($billrow['process_date'] &&
80 $this->payers[0]['data']['provider'] == $this->payers[$i]['data']['provider'])
82 $tmp = $this->payers[0];
83 $this->payers[0] = $this->payers[$i];
84 $this->payers[$i] = $tmp;
88 $this->using_modifiers = true;
90 // Get payment and adjustment details if there are any previous payers.
92 $this->invoice = array();
93 if ($this->payerSequence() != 'P') {
94 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
95 $this->invoice = ar_get_invoice_summary($this->pid, $this->encounter_id, true);
97 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
98 SLConnect();
99 $arres = SLQuery("select id from ar where invnumber = " .
100 "'{$this->pid}.{$this->encounter_id}'");
101 if ($sl_err) die($sl_err);
102 $arrow = SLGetRow($arres, 0);
103 if ($arrow) {
104 $this->invoice = get_invoice_summary($arrow['id'], true);
106 SLClose();
108 // Secondary claims might not have modifiers in SQL-Ledger data.
109 // In that case, note that we should not try to match on them.
110 $this->using_modifiers = false;
111 foreach ($this->invoice as $key => $trash) {
112 if (strpos($key, ':')) $this->using_modifiers = true;
117 // Constructor. Loads relevant database information.
119 function Claim($pid, $encounter_id) {
120 $this->pid = $pid;
121 $this->encounter_id = $encounter_id;
122 $this->procs = array();
123 $this->diags = array();
124 $this->copay = 0;
126 // We need the encounter date before we can identify the payers.
127 $sql = "SELECT * FROM form_encounter WHERE " .
128 "pid = '{$this->pid}' AND " .
129 "encounter = '{$this->encounter_id}'";
130 $this->encounter = sqlQuery($sql);
132 // Sort by procedure timestamp in order to get some consistency.
133 $sql = "SELECT * FROM billing WHERE " .
134 "encounter = '{$this->encounter_id}' AND pid = '{$this->pid}' AND " .
135 "(code_type = 'CPT4' OR code_type = 'HCPCS' OR code_type = 'COPAY' OR code_type = 'ICD9') AND " .
136 "activity = '1' ORDER BY date, id";
137 $res = sqlStatement($sql);
138 while ($row = sqlFetchArray($res)) {
139 if ($row['code_type'] == 'COPAY') {
140 $this->copay -= $row['fee'];
141 continue;
143 // Save all diagnosis codes.
144 if ($row['code_type'] == 'ICD9') {
145 $this->diags[$row['code']] = $row['code'];
146 continue;
148 if (!$row['units']) $row['units'] = 1;
149 // Load prior payer data at the first opportunity in order to get
150 // the using_modifiers flag that is referenced below.
151 if (empty($this->procs)) $this->loadPayerInfo($row);
152 // Consolidate duplicate procedures.
153 foreach ($this->procs as $key => $trash) {
154 if (strcmp($this->procs[$key]['code'],$row['code']) == 0 &&
155 (strcmp($this->procs[$key]['modifier'],$row['modifier']) == 0 ||
156 !$this->using_modifiers))
158 $this->procs[$key]['units'] += $row['units'];
159 $this->procs[$key]['fee'] += $row['fee'];
160 continue 2; // skip to next table row
164 // If there is a row-specific provider then get its details.
165 if (!empty($row['provider_id'])) {
166 // Get service provider data for this row.
167 $sql = "SELECT * FROM users WHERE id = '" . $row['provider_id'] . "'";
168 $row['provider'] = sqlQuery($sql);
169 // Get insurance numbers for this row's provider.
170 $sql = "SELECT * FROM insurance_numbers WHERE " .
171 "(insurance_company_id = '" . $row['payer_id'] .
172 "' OR insurance_company_id is NULL) AND " .
173 "provider_id = '" . $row['provider_id'] . "' " .
174 "ORDER BY insurance_company_id DESC LIMIT 1";
175 $row['insurance_numbers'] = sqlQuery($sql);
178 $this->procs[] = $row;
181 $sql = "SELECT * FROM x12_partners WHERE " .
182 "id = '" . $this->procs[0]['x12_partner_id'] . "'";
183 $this->x12_partner = sqlQuery($sql);
185 $sql = "SELECT * FROM facility WHERE " .
186 "id = '" . addslashes($this->encounter['facility_id']) . "' " .
187 "LIMIT 1";
188 $this->facility = sqlQuery($sql);
190 /*****************************************************************
191 $provider_id = $this->procs[0]['provider_id'];
192 *****************************************************************/
193 $provider_id = $this->encounter['provider_id'];
194 $sql = "SELECT * FROM users WHERE id = '$provider_id'";
195 $this->provider = sqlQuery($sql);
197 $sql = "SELECT * FROM facility " .
198 "ORDER BY billing_location DESC, id ASC LIMIT 1";
199 $this->billing_facility = sqlQuery($sql);
201 $sql = "SELECT * FROM insurance_numbers WHERE " .
202 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
203 "' OR insurance_company_id is NULL) AND " .
204 "provider_id = '$provider_id' " .
205 "ORDER BY insurance_company_id DESC LIMIT 1";
206 $this->insurance_numbers = sqlQuery($sql);
208 $sql = "SELECT * FROM patient_data WHERE " .
209 "pid = '{$this->pid}' " .
210 "ORDER BY id LIMIT 1";
211 $this->patient_data = sqlQuery($sql);
213 $sql = "SELECT fpa.* FROM forms JOIN form_misc_billing_options AS fpa " .
214 "ON fpa.id = forms.form_id WHERE " .
215 "forms.encounter = '{$this->encounter_id}' AND " .
216 "forms.pid = '{$this->pid}' AND " .
217 "forms.formdir = 'misc_billing_options' " .
218 "ORDER BY forms.date";
219 $this->billing_options = sqlQuery($sql);
221 $referrer_id = (empty($GLOBALS['MedicareReferrerIsRenderer']) ||
222 $this->insurance_numbers['provider_number_type'] != '1C') ?
223 $this->patient_data['providerID'] : $provider_id;
224 $sql = "SELECT * FROM users WHERE id = '$referrer_id'";
225 $this->referrer = sqlQuery($sql);
226 if (!$this->referrer) $this->referrer = array();
228 $supervisor_id = $this->encounter['supervisor_id'];
229 $sql = "SELECT * FROM users WHERE id = '$supervisor_id'";
230 $this->supervisor = sqlQuery($sql);
231 if (!$this->supervisor) $this->supervisor = array();
233 $sql = "SELECT * FROM insurance_numbers WHERE " .
234 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
235 "' OR insurance_company_id is NULL) AND " .
236 "provider_id = '$supervisor_id' " .
237 "ORDER BY insurance_company_id DESC LIMIT 1";
238 $this->supervisor_numbers = sqlQuery($sql);
239 if (!$this->supervisor_numbers) $this->supervisor_numbers = array();
241 } // end constructor
243 // Return an array of adjustments from the designated prior payer for the
244 // designated procedure key (might be procedure:modifier), or for the claim
245 // level. For each adjustment give date, group code, reason code, amount.
246 // Note this will include "patient responsibility" adjustments which are
247 // not adjustments to OUR invoice, but they reduce the amount that the
248 // insurance company pays.
250 function payerAdjustments($ins, $code='Claim') {
251 $aadj = array();
253 // If we have no modifiers stored in SQL-Ledger for this claim,
254 // then we cannot use a modifier passed in with the key.
255 $tmp = strpos($code, ':');
256 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
258 // For payments, source always starts with "Ins" or "Pt".
259 // Nonzero adjustment reason examples:
260 // Ins1 adjust code 42 (Charges exceed ... (obsolete))
261 // Ins1 adjust code 45 (Charges exceed your contracted/ legislated fee arrangement)
262 // Ins1 adjust code 97 (Payment is included in the allowance for another service/procedure)
263 // Ins1 adjust code A2 (Contractual adjustment)
264 // Ins adjust Ins1
265 // adjust code 45
266 // Zero adjustment reason examples:
267 // Co-pay: 25.00
268 // Coinsurance: 11.46 (code 2) Note: fix remits to identify insurance
269 // To deductible: 0.22 (code 1) Note: fix remits to identify insurance
270 // To copay Ins1 (manual entry)
271 // To ded'ble Ins1 (manual entry)
273 if (!empty($this->invoice[$code])) {
274 $date = '';
275 $deductible = 0;
276 $coinsurance = 0;
277 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
278 $insnumber = substr($inslabel, 3);
280 // Compute this procedure's patient responsibility amount as of this
281 // prior payer, which is the original charge minus all insurance
282 // payments and "hard" adjustments up to this payer.
283 $ptresp = $this->invoice[$code]['chg'] + $this->invoice[$code]['adj'];
284 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
285 if (isset($value['plv'])) {
286 // New method; plv (from ar_activity.payer_type) exists to
287 // indicate the payer level.
288 if (isset($value['pmt']) && $value['pmt'] != 0) {
289 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
290 $ptresp -= $value['pmt'];
292 else if (isset($value['chg']) && trim(substr($key, 0, 10))) {
293 // non-blank key indicates this is an adjustment and not a charge
294 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
295 $ptresp += $value['chg']; // adjustments are negative charges
298 else {
299 // Old method: With SQL-Ledger payer level was stored in the memo.
300 if (preg_match("/^Ins(\d)/i", $value['src'], $tmp)) {
301 if ($tmp[1] <= $insnumber) $ptresp -= $value['pmt'];
303 else if (trim(substr($key, 0, 10))) { // not an adjustment if no date
304 if (!preg_match("/Ins(\d)/i", $value['rsn'], $tmp) || $tmp[1] <= $insnumber)
305 $ptresp += $value['chg']; // adjustments are negative charges
309 if ($ptresp < 0) $ptresp = 0; // we may be insane but try to hide it
311 // Main loop, to extract adjustments for this payer and procedure.
312 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
313 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
314 if ($tmp) $date = $tmp;
315 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
316 $rsn = $value['rsn'];
317 $chg = 0 - $value['chg']; // adjustments are negative charges
319 $gcode = 'CO'; // default group code = contractual obligation
320 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
322 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
323 // From manual post. Take the defaults.
325 else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
326 $coinsurance = $ptresp; // from manual post
327 continue;
329 else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
330 $deductible = $ptresp; // from manual post
331 continue;
333 else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
334 $coinsurance = $tmp[1]; // from 835 as of 6/2007
335 continue;
337 else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
338 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
339 continue;
341 else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
342 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
343 continue;
345 else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
346 continue; // from 835 as of 6/2007
348 else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
349 $rcode = $tmp[1]; // from 835
351 else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
352 // Take the defaults.
354 else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
355 continue; // it's for some other payer
357 else if ($insnumber == '1') {
358 if (preg_match("/\$\s*adjust code (\S+)/i", $rsn, $tmp)) {
359 $rcode = $tmp[1]; // from 835
361 else if ($chg) {
362 // Other adjustments default to Ins1.
364 else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
365 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
366 $coinsurance = 0 + $tmp[1]; // from 835 before 6/2007
367 continue;
369 else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
370 $deductible = 0 + $tmp[1]; // from 835 before 6/2007
371 continue;
373 else {
374 continue; // there is no adjustment amount
377 else {
378 continue; // it's for primary and that's not us
381 if ($rcode == '42') $rcode= '45'; // reason 42 is obsolete
382 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
384 } // end if
385 } // end foreach
387 // If we really messed it up, at least avoid negative numbers.
388 if ($coinsurance > $ptresp) $coinsurance = $ptresp;
389 if ($deductible > $ptresp) $deductible = $ptresp;
391 // Find out if this payer paid anything at all on this claim. This will
392 // help us allocate any unknown patient responsibility amounts.
393 $thispaidanything = 0;
394 foreach($this->invoice as $codekey => $codeval) {
395 foreach ($codeval['dtl'] as $key => $value) {
396 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
397 $thispaidanything += $value['pmt'];
402 // Allocate any unknown patient responsibility by guessing if the
403 // deductible has been satisfied.
404 if ($thispaidanything)
405 $coinsurance = $ptresp - $deductible;
406 else
407 $deductible = $ptresp - $coinsurance;
409 if ($date && $deductible != 0)
410 $aadj[] = array($date, 'PR', '1', sprintf('%.2f', $deductible));
411 if ($date && $coinsurance != 0)
412 $aadj[] = array($date, 'PR', '2', sprintf('%.2f', $coinsurance));
414 } // end if
416 return $aadj;
419 // Return date, total payments and total "hard" adjustments from the given
420 // prior payer. If $code is specified then only that procedure key is
421 // selected, otherwise it's for the whole claim.
423 function payerTotals($ins, $code='') {
424 // If we have no modifiers stored in SQL-Ledger for this claim,
425 // then we cannot use a modifier passed in with the key.
426 $tmp = strpos($code, ':');
427 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
429 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
430 $insnumber = substr($inslabel, 3);
431 $paytotal = 0;
432 $adjtotal = 0;
433 $date = '';
434 foreach($this->invoice as $codekey => $codeval) {
435 if ($code && strcmp($codekey,$code) != 0) continue;
436 foreach ($codeval['dtl'] as $key => $value) {
437 if (isset($value['plv'])) {
438 // New method; plv (from ar_activity.payer_type) exists to
439 // indicate the payer level.
440 if ($value['plv'] == $insnumber) {
441 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
442 $paytotal += $value['pmt'];
445 else {
446 // Old method: With SQL-Ledger payer level was stored in the memo.
447 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
448 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
449 $paytotal += $value['pmt'];
453 $aarr = $this->payerAdjustments($ins, $codekey);
454 foreach ($aarr as $a) {
455 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
456 if (!$date) $date = $a[0];
459 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
462 // Return the amount already paid by the patient.
464 function patientPaidAmount() {
465 // For primary claims $this->invoice is not loaded, so get the co-pay
466 // from the billing table instead.
467 if (empty($this->invoice)) return $this->copay;
469 $amount = 0;
470 foreach($this->invoice as $codekey => $codeval) {
471 foreach ($codeval['dtl'] as $key => $value) {
472 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
473 $amount += $value['pmt'];
477 return sprintf('%.2f', $amount);
480 // Return invoice total, including adjustments but not payments.
482 function invoiceTotal() {
483 $amount = 0;
484 foreach($this->invoice as $codekey => $codeval) {
485 $amount += $codeval['chg'];
487 return sprintf('%.2f', $amount);
490 // Number of procedures in this claim.
491 function procCount() {
492 return count($this->procs);
495 // Number of payers for this claim. Ranges from 1 to 3.
496 function payerCount() {
497 return count($this->payers);
500 function x12gsversionstring() {
501 return x12clean(trim($this->x12_partner['x12_version']));
504 function x12gssenderid() {
505 $tmp = $this->x12_partner['x12_sender_id'];
506 while (strlen($tmp) < 15) $tmp .= " ";
507 return $tmp;
510 function x12gsreceiverid() {
511 $tmp = $this->x12_partner['x12_receiver_id'];
512 while (strlen($tmp) < 15) $tmp .= " ";
513 return $tmp;
516 function x12gsisa05() {
517 return $this->x12_partner['x12_isa05'];
520 function x12gsisa07() {
521 return $this->x12_partner['x12_isa07'];
524 function x12gsisa14() {
525 return $this->x12_partner['x12_isa14'];
528 function x12gsisa15() {
529 return $this->x12_partner['x12_isa15'];
532 function x12gsgs02() {
533 $tmp = $this->x12_partner['x12_gs02'];
534 if ($tmp === '') $tmp = $this->x12_partner['x12_sender_id'];
535 return $tmp;
538 function x12gsper06() {
539 return $this->x12_partner['x12_per06'];
542 function cliaCode() {
543 return x12clean(trim($this->facility['domain_identifier']));
546 function billingFacilityName() {
547 return x12clean(trim($this->billing_facility['name']));
550 function billingFacilityStreet() {
551 return x12clean(trim($this->billing_facility['street']));
554 function billingFacilityCity() {
555 return x12clean(trim($this->billing_facility['city']));
558 function billingFacilityState() {
559 return x12clean(trim($this->billing_facility['state']));
562 function billingFacilityZip() {
563 return x12clean(trim($this->billing_facility['postal_code']));
566 function billingFacilityETIN() {
567 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
570 function billingFacilityNPI() {
571 return x12clean(trim($this->billing_facility['facility_npi']));
574 function federalIdType() {
575 if ($this->billing_facility['tax_id_type'])
577 return $this->billing_facility['tax_id_type'];
579 else{
580 return null;
584 # The billing facility and the patient must both accept for this to return true.
585 function billingFacilityAssignment($ins=0) {
586 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
587 if (strcmp($tmp,'FALSE') == 0) return '0';
588 return !empty($this->billing_facility['accepts_assignment']);
591 function billingContactName() {
592 return x12clean(trim($this->billing_facility['attn']));
595 function billingContactPhone() {
596 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
597 $this->billing_facility['phone'], $tmp))
599 return $tmp[1] . $tmp[2] . $tmp[3];
601 return '';
604 function facilityName() {
605 return x12clean(trim($this->facility['name']));
608 function facilityStreet() {
609 return x12clean(trim($this->facility['street']));
612 function facilityCity() {
613 return x12clean(trim($this->facility['city']));
616 function facilityState() {
617 return x12clean(trim($this->facility['state']));
620 function facilityZip() {
621 return x12clean(trim($this->facility['postal_code']));
624 function facilityETIN() {
625 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
628 function facilityNPI() {
629 return x12clean(trim($this->facility['facility_npi']));
632 function facilityPOS() {
633 return x12clean(trim($this->facility['pos_code']));
636 function clearingHouseName() {
637 return x12clean(trim($this->x12_partner['name']));
640 function clearingHouseETIN() {
641 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
644 function providerNumberType($prockey=-1) {
645 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
646 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
647 return $tmp['provider_number_type'];
650 function providerNumber($prockey=-1) {
651 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
652 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
653 return x12clean(trim(str_replace('-', '', $tmp['provider_number'])));
656 function providerGroupNumber($prockey=-1) {
657 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
658 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
659 return x12clean(trim(str_replace('-', '', $tmp['group_number'])));
662 // Returns 'P', 'S' or 'T'.
664 function payerSequence($ins=0) {
665 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
668 // Returns the HIPAA code of the patient-to-subscriber relationship.
670 function insuredRelationship($ins=0) {
671 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
672 if (strcmp($tmp,'self' ) == 0) return '18';
673 if (strcmp($tmp,'spouse') == 0) return '01';
674 if (strcmp($tmp,'child' ) == 0) return '19';
675 if (strcmp($tmp,'other' ) == 0) return 'G8';
676 return $tmp; // should not happen
679 function insuredTypeCode($ins=0) {
680 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
681 return '12'; // medicare secondary working aged beneficiary or
682 // spouse with employer group health plan
683 return '';
686 // Is the patient also the subscriber?
688 function isSelfOfInsured($ins=0) {
689 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
690 return (strcmp($tmp,'self') == 0);
693 function planName($ins=0) {
694 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
697 function policyNumber($ins=0) { // "ID"
698 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
701 function groupNumber($ins=0) {
702 return x12clean(trim($this->payers[$ins]['data']['group_number']));
705 function groupName($ins=0) {
706 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
709 // Claim types are:
710 // 16 Other HCFA
711 // MB Medicare Part B
712 // MC Medicaid
713 // CH ChampUSVA
714 // CH ChampUS
715 // BL Blue Cross Blue Shield
716 // 16 FECA
717 // 09 Self Pay
718 // 10 Central Certification
719 // 11 Other Non-Federal Programs
720 // 12 Preferred Provider Organization (PPO)
721 // 13 Point of Service (POS)
722 // 14 Exclusive Provider Organization (EPO)
723 // 15 Indemnity Insurance
724 // 16 Health Maintenance Organization (HMO) Medicare Risk
725 // AM Automobile Medical
726 // CI Commercial Insurance Co.
727 // DS Disability
728 // HM Health Maintenance Organization
729 // LI Liability
730 // LM Liability Medical
731 // OF Other Federal Program
732 // TV Title V
733 // VA Veterans Administration Plan
734 // WC Workers Compensation Health Plan
735 // ZZ Mutually Defined
737 function claimType($ins=0) {
738 if (empty($this->payers[$ins]['object'])) return '';
739 return $this->payers[$ins]['object']->get_freeb_claim_type();
742 function insuredLastName($ins=0) {
743 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
746 function insuredFirstName($ins=0) {
747 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
750 function insuredMiddleName($ins=0) {
751 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
754 function insuredStreet($ins=0) {
755 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
758 function insuredCity($ins=0) {
759 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
762 function insuredState($ins=0) {
763 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
766 function insuredZip($ins=0) {
767 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
770 function insuredPhone($ins=0) {
771 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
772 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
773 return $tmp[1] . $tmp[2] . $tmp[3];
774 return '';
777 function insuredDOB($ins=0) {
778 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
781 function insuredSex($ins=0) {
782 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
785 function payerName($ins=0) {
786 return x12clean(trim($this->payers[$ins]['company']['name']));
789 function payerAttn($ins=0) {
790 return x12clean(trim($this->payers[$ins]['company']['attn']));
793 function payerStreet($ins=0) {
794 if (empty($this->payers[$ins]['object'])) return '';
795 $tmp = $this->payers[$ins]['object'];
796 $tmp = $tmp->get_address();
797 return x12clean(trim($tmp->get_line1()));
800 function payerCity($ins=0) {
801 if (empty($this->payers[$ins]['object'])) return '';
802 $tmp = $this->payers[$ins]['object'];
803 $tmp = $tmp->get_address();
804 return x12clean(trim($tmp->get_city()));
807 function payerState($ins=0) {
808 if (empty($this->payers[$ins]['object'])) return '';
809 $tmp = $this->payers[$ins]['object'];
810 $tmp = $tmp->get_address();
811 return x12clean(trim($tmp->get_state()));
814 function payerZip($ins=0) {
815 if (empty($this->payers[$ins]['object'])) return '';
816 $tmp = $this->payers[$ins]['object'];
817 $tmp = $tmp->get_address();
818 return x12clean(trim($tmp->get_zip()));
821 function payerID($ins=0) {
822 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
825 function payerAltID($ins=0) {
826 return x12clean(trim($this->payers[$ins]['company']['alt_cms_id']));
829 function patientLastName() {
830 return x12clean(trim($this->patient_data['lname']));
833 function patientFirstName() {
834 return x12clean(trim($this->patient_data['fname']));
837 function patientMiddleName() {
838 return x12clean(trim($this->patient_data['mname']));
841 function patientStreet() {
842 return x12clean(trim($this->patient_data['street']));
845 function patientCity() {
846 return x12clean(trim($this->patient_data['city']));
849 function patientState() {
850 return x12clean(trim($this->patient_data['state']));
853 function patientZip() {
854 return x12clean(trim($this->patient_data['postal_code']));
857 function patientPhone() {
858 $ptphone = $this->patient_data['phone_home'];
859 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
860 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
861 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
862 return $tmp[1] . $tmp[2] . $tmp[3];
863 return '';
866 function patientDOB() {
867 return str_replace('-', '', $this->patient_data['DOB']);
870 function patientSex() {
871 return strtoupper(substr($this->patient_data['sex'], 0, 1));
874 // Patient Marital Status: M = Married, S = Single, or something else.
875 function patientStatus() {
876 return strtoupper(substr($this->patient_data['status'], 0, 1));
879 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
880 // indicate employed.
881 function patientOccupation() {
882 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
885 function cptCode($prockey) {
886 return x12clean(trim($this->procs[$prockey]['code']));
889 function cptModifier($prockey) {
890 return x12clean(trim($this->procs[$prockey]['modifier']));
893 // Returns the procedure code, followed by ":modifier" if there is one.
894 function cptKey($prockey) {
895 $tmp = $this->cptModifier($prockey);
896 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
899 function cptCharges($prockey) {
900 return x12clean(trim($this->procs[$prockey]['fee']));
903 function cptUnits($prockey) {
904 if (empty($this->procs[$prockey]['units'])) return '1';
905 return x12clean(trim($this->procs[$prockey]['units']));
908 // NDC drug ID.
909 function cptNDCID($prockey) {
910 $ndcinfo = $this->procs[$prockey]['ndc_info'];
911 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
912 $ndc = $tmp[1];
913 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
914 return sprintf('%05d-%04d-%02d', $tmp[1], $tmp[2], $tmp[3]);
916 return x12clean($ndc); // format is bad but return it anyway
918 return '';
921 // NDC drug unit of measure code.
922 function cptNDCUOM($prockey) {
923 $ndcinfo = $this->procs[$prockey]['ndc_info'];
924 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
925 return x12clean($tmp[2]);
926 return '';
929 // NDC drug number of units.
930 function cptNDCQuantity($prockey) {
931 $ndcinfo = $this->procs[$prockey]['ndc_info'];
932 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
933 return x12clean(ltrim($tmp[3], '0'));
935 return '';
938 function onsetDate() {
939 return str_replace('-', '', substr($this->encounter['onset_date'], 0, 10));
942 function serviceDate() {
943 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
946 function priorAuth() {
947 return x12clean(trim($this->billing_options['prior_auth_number']));
950 function isRelatedEmployment() {
951 return !empty($this->billing_options['employment_related']);
954 function isRelatedAuto() {
955 return !empty($this->billing_options['auto_accident']);
958 function isRelatedOther() {
959 return !empty($this->billing_options['other_accident']);
962 function autoAccidentState() {
963 return x12clean(trim($this->billing_options['accident_state']));
966 function isUnableToWork() {
967 return !empty($this->billing_options['is_unable_to_work']);
970 function offWorkFrom() {
971 return str_replace('-', '', substr($this->billing_options['off_work_from'], 0, 10));
974 function offWorkTo() {
975 return str_replace('-', '', substr($this->billing_options['off_work_to'], 0, 10));
978 function isHospitalized() {
979 return !empty($this->billing_options['is_hospitalized']);
982 function hospitalizedFrom() {
983 return str_replace('-', '', substr($this->billing_options['hospitalization_date_from'], 0, 10));
986 function hospitalizedTo() {
987 return str_replace('-', '', substr($this->billing_options['hospitalization_date_to'], 0, 10));
990 function isOutsideLab() {
991 return !empty($this->billing_options['outside_lab']);
994 function outsideLabAmount() {
995 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
998 function medicaidResubmissionCode() {
999 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
1002 function medicaidOriginalReference() {
1003 return x12clean(trim($this->billing_options['medicaid_original_reference']));
1006 function frequencyTypeCode() {
1007 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
1010 function additionalNotes() {
1011 return x12clean(trim($this->billing_options['comments']));
1014 // Returns an array of unique diagnoses. Periods are stripped.
1015 function diagArray() {
1016 $da = array();
1017 foreach ($this->procs as $row) {
1018 $atmp = explode(':', $row['justify']);
1019 foreach ($atmp as $tmp) {
1020 if (!empty($tmp)) {
1021 $diag = str_replace('.', '', $tmp);
1022 $da[$diag] = $diag;
1026 // The above got all the diagnoses used for justification, in the order
1027 // used for justification. Next we go through all diagnoses, justified
1028 // or not, to make sure they all get into the claim. We do it this way
1029 // so that the more important diagnoses appear first.
1030 foreach ($this->diags as $diag) {
1031 $diag = str_replace('.', '', $diag);
1032 $da[$diag] = $diag;
1034 return $da;
1037 // Compute one 1-relative index in diagArray for the given procedure.
1038 // This function is obsolete, use diagIndexArray() instead.
1039 function diagIndex($prockey) {
1040 $da = $this->diagArray();
1041 $tmp = explode(':', $this->procs[$prockey]['justify']);
1042 if (empty($tmp)) return '';
1043 $diag = str_replace('.', '', $tmp[0]);
1044 $i = 0;
1045 foreach ($da as $value) {
1046 ++$i;
1047 if (strcmp($value,$diag) == 0) return $i;
1049 return '';
1052 // Compute array of 1-relative diagArray indices for the given procedure.
1053 function diagIndexArray($prockey) {
1054 $dia = array();
1055 $da = $this->diagArray();
1056 $atmp = explode(':', $this->procs[$prockey]['justify']);
1057 foreach ($atmp as $tmp) {
1058 if (!empty($tmp)) {
1059 $diag = str_replace('.', '', $tmp);
1060 $i = 0;
1061 foreach ($da as $value) {
1062 ++$i;
1063 if (strcmp($value,$diag) == 0) $dia[] = $i;
1067 return $dia;
1070 function providerLastName($prockey=-1) {
1071 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1072 $this->provider : $this->procs[$prockey]['provider'];
1073 return x12clean(trim($tmp['lname']));
1076 function providerFirstName($prockey=-1) {
1077 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1078 $this->provider : $this->procs[$prockey]['provider'];
1079 return x12clean(trim($tmp['fname']));
1082 function providerMiddleName($prockey=-1) {
1083 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1084 $this->provider : $this->procs[$prockey]['provider'];
1085 return x12clean(trim($tmp['mname']));
1088 function providerNPI($prockey=-1) {
1089 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1090 $this->provider : $this->procs[$prockey]['provider'];
1091 return x12clean(trim($tmp['npi']));
1094 function providerUPIN($prockey=-1) {
1095 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1096 $this->provider : $this->procs[$prockey]['provider'];
1097 return x12clean(trim($tmp['upin']));
1100 function providerSSN($prockey=-1) {
1101 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1102 $this->provider : $this->procs[$prockey]['provider'];
1103 return x12clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1106 function providerTaxonomy($prockey=-1) {
1107 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1108 $this->provider : $this->procs[$prockey]['provider'];
1109 if (empty($tmp['taxonomy'])) return '207Q00000X';
1110 return x12clean(trim($tmp['taxonomy']));
1113 function referrerLastName() {
1114 return x12clean(trim($this->referrer['lname']));
1117 function referrerFirstName() {
1118 return x12clean(trim($this->referrer['fname']));
1121 function referrerMiddleName() {
1122 return x12clean(trim($this->referrer['mname']));
1125 function referrerNPI() {
1126 return x12clean(trim($this->referrer['npi']));
1129 function referrerUPIN() {
1130 return x12clean(trim($this->referrer['upin']));
1133 function referrerSSN() {
1134 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
1137 function referrerTaxonomy() {
1138 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1139 return x12clean(trim($this->referrer['taxonomy']));
1142 function supervisorLastName() {
1143 return x12clean(trim($this->supervisor['lname']));
1146 function supervisorFirstName() {
1147 return x12clean(trim($this->supervisor['fname']));
1150 function supervisorMiddleName() {
1151 return x12clean(trim($this->supervisor['mname']));
1154 function supervisorNPI() {
1155 return x12clean(trim($this->supervisor['npi']));
1158 function supervisorUPIN() {
1159 return x12clean(trim($this->supervisor['upin']));
1162 function supervisorSSN() {
1163 return x12clean(trim(str_replace('-', '', $this->supervisor['federaltaxid'])));
1166 function supervisorTaxonomy() {
1167 if (empty($this->supervisor['taxonomy'])) return '207Q00000X';
1168 return x12clean(trim($this->supervisor['taxonomy']));
1171 function supervisorNumberType() {
1172 return $this->supervisor_numbers['provider_number_type'];
1175 function supervisorNumber() {
1176 return x12clean(trim(str_replace('-', '', $this->supervisor_numbers['provider_number'])));