Fix for encounters having no billing_location.
[openemr.git] / library / Claim.class.php
blob997b6f14671d0a9b9f04469e35fd1ef8cf30de4f
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);
196 // Selecting the billing facility assigned to the encounter. If none,
197 // try the first (and hopefully only) facility marked as a billing location.
198 if (empty($this->encounter['billing_facility'])) {
199 $sql = "SELECT * FROM facility " .
200 "ORDER BY billing_location DESC, id ASC LIMIT 1";
202 else {
203 $sql = "SELECT * FROM facility " .
204 " where id ='" . addslashes($this->encounter['billing_facility']) . "' ";
206 $this->billing_facility = sqlQuery($sql);
208 $sql = "SELECT * FROM insurance_numbers WHERE " .
209 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
210 "' OR insurance_company_id is NULL) AND " .
211 "provider_id = '$provider_id' " .
212 "ORDER BY insurance_company_id DESC LIMIT 1";
213 $this->insurance_numbers = sqlQuery($sql);
215 $sql = "SELECT * FROM patient_data WHERE " .
216 "pid = '{$this->pid}' " .
217 "ORDER BY id LIMIT 1";
218 $this->patient_data = sqlQuery($sql);
220 $sql = "SELECT fpa.* FROM forms JOIN form_misc_billing_options AS fpa " .
221 "ON fpa.id = forms.form_id WHERE " .
222 "forms.encounter = '{$this->encounter_id}' AND " .
223 "forms.pid = '{$this->pid}' AND " .
224 "forms.formdir = 'misc_billing_options' " .
225 "ORDER BY forms.date";
226 $this->billing_options = sqlQuery($sql);
228 $referrer_id = (empty($GLOBALS['MedicareReferrerIsRenderer']) ||
229 $this->insurance_numbers['provider_number_type'] != '1C') ?
230 $this->patient_data['providerID'] : $provider_id;
231 $sql = "SELECT * FROM users WHERE id = '$referrer_id'";
232 $this->referrer = sqlQuery($sql);
233 if (!$this->referrer) $this->referrer = array();
235 $supervisor_id = $this->encounter['supervisor_id'];
236 $sql = "SELECT * FROM users WHERE id = '$supervisor_id'";
237 $this->supervisor = sqlQuery($sql);
238 if (!$this->supervisor) $this->supervisor = array();
240 $sql = "SELECT * FROM insurance_numbers WHERE " .
241 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
242 "' OR insurance_company_id is NULL) AND " .
243 "provider_id = '$supervisor_id' " .
244 "ORDER BY insurance_company_id DESC LIMIT 1";
245 $this->supervisor_numbers = sqlQuery($sql);
246 if (!$this->supervisor_numbers) $this->supervisor_numbers = array();
248 } // end constructor
250 // Return an array of adjustments from the designated prior payer for the
251 // designated procedure key (might be procedure:modifier), or for the claim
252 // level. For each adjustment give date, group code, reason code, amount.
253 // Note this will include "patient responsibility" adjustments which are
254 // not adjustments to OUR invoice, but they reduce the amount that the
255 // insurance company pays.
257 function payerAdjustments($ins, $code='Claim') {
258 $aadj = array();
260 // If we have no modifiers stored in SQL-Ledger for this claim,
261 // then we cannot use a modifier passed in with the key.
262 $tmp = strpos($code, ':');
263 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
265 // For payments, source always starts with "Ins" or "Pt".
266 // Nonzero adjustment reason examples:
267 // Ins1 adjust code 42 (Charges exceed ... (obsolete))
268 // Ins1 adjust code 45 (Charges exceed your contracted/ legislated fee arrangement)
269 // Ins1 adjust code 97 (Payment is included in the allowance for another service/procedure)
270 // Ins1 adjust code A2 (Contractual adjustment)
271 // Ins adjust Ins1
272 // adjust code 45
273 // Zero adjustment reason examples:
274 // Co-pay: 25.00
275 // Coinsurance: 11.46 (code 2) Note: fix remits to identify insurance
276 // To deductible: 0.22 (code 1) Note: fix remits to identify insurance
277 // To copay Ins1 (manual entry)
278 // To ded'ble Ins1 (manual entry)
280 if (!empty($this->invoice[$code])) {
281 $date = '';
282 $deductible = 0;
283 $coinsurance = 0;
284 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
285 $insnumber = substr($inslabel, 3);
287 // Compute this procedure's patient responsibility amount as of this
288 // prior payer, which is the original charge minus all insurance
289 // payments and "hard" adjustments up to this payer.
290 $ptresp = $this->invoice[$code]['chg'] + $this->invoice[$code]['adj'];
291 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
292 if (isset($value['plv'])) {
293 // New method; plv (from ar_activity.payer_type) exists to
294 // indicate the payer level.
295 if (isset($value['pmt']) && $value['pmt'] != 0) {
296 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
297 $ptresp -= $value['pmt'];
299 else if (isset($value['chg']) && trim(substr($key, 0, 10))) {
300 // non-blank key indicates this is an adjustment and not a charge
301 if ($value['plv'] > 0 && $value['plv'] <= $insnumber)
302 $ptresp += $value['chg']; // adjustments are negative charges
305 else {
306 // Old method: With SQL-Ledger payer level was stored in the memo.
307 if (preg_match("/^Ins(\d)/i", $value['src'], $tmp)) {
308 if ($tmp[1] <= $insnumber) $ptresp -= $value['pmt'];
310 else if (trim(substr($key, 0, 10))) { // not an adjustment if no date
311 if (!preg_match("/Ins(\d)/i", $value['rsn'], $tmp) || $tmp[1] <= $insnumber)
312 $ptresp += $value['chg']; // adjustments are negative charges
316 if ($ptresp < 0) $ptresp = 0; // we may be insane but try to hide it
318 // Main loop, to extract adjustments for this payer and procedure.
319 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
320 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
321 if ($tmp) $date = $tmp;
322 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
323 $rsn = $value['rsn'];
324 $chg = 0 - $value['chg']; // adjustments are negative charges
326 $gcode = 'CO'; // default group code = contractual obligation
327 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
329 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
330 // From manual post. Take the defaults.
332 else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
333 $coinsurance = $ptresp; // from manual post
334 continue;
336 else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
337 $deductible = $ptresp; // from manual post
338 continue;
340 else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
341 $coinsurance = $tmp[1]; // from 835 as of 6/2007
342 continue;
344 else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
345 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
346 continue;
348 else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
349 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
350 continue;
352 else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
353 continue; // from 835 as of 6/2007
355 else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
356 $rcode = $tmp[1]; // from 835
358 else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
359 // Take the defaults.
361 else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
362 continue; // it's for some other payer
364 else if ($insnumber == '1') {
365 if (preg_match("/\$\s*adjust code (\S+)/i", $rsn, $tmp)) {
366 $rcode = $tmp[1]; // from 835
368 else if ($chg) {
369 // Other adjustments default to Ins1.
371 else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
372 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
373 $coinsurance = 0 + $tmp[1]; // from 835 before 6/2007
374 continue;
376 else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
377 $deductible = 0 + $tmp[1]; // from 835 before 6/2007
378 continue;
380 else {
381 continue; // there is no adjustment amount
384 else {
385 continue; // it's for primary and that's not us
388 if ($rcode == '42') $rcode= '45'; // reason 42 is obsolete
389 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
391 } // end if
392 } // end foreach
394 // If we really messed it up, at least avoid negative numbers.
395 if ($coinsurance > $ptresp) $coinsurance = $ptresp;
396 if ($deductible > $ptresp) $deductible = $ptresp;
398 // Find out if this payer paid anything at all on this claim. This will
399 // help us allocate any unknown patient responsibility amounts.
400 $thispaidanything = 0;
401 foreach($this->invoice as $codekey => $codeval) {
402 foreach ($codeval['dtl'] as $key => $value) {
403 if (isset($value['plv'])) {
404 // New method; plv exists to indicate the payer level.
405 if ($value['plv'] == $insnumber) {
406 $thispaidanything += $value['pmt'];
409 else {
410 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
411 $thispaidanything += $value['pmt'];
417 // Allocate any unknown patient responsibility by guessing if the
418 // deductible has been satisfied.
419 if ($thispaidanything)
420 $coinsurance = $ptresp - $deductible;
421 else
422 $deductible = $ptresp - $coinsurance;
424 $deductible = sprintf('%.2f', $deductible);
425 $coinsurance = sprintf('%.2f', $coinsurance);
427 if ($date && $deductible != 0)
428 $aadj[] = array($date, 'PR', '1', $deductible);
429 if ($date && $coinsurance != 0)
430 $aadj[] = array($date, 'PR', '2', $coinsurance);
432 } // end if
434 return $aadj;
437 // Return date, total payments and total "hard" adjustments from the given
438 // prior payer. If $code is specified then only that procedure key is
439 // selected, otherwise it's for the whole claim.
441 function payerTotals($ins, $code='') {
442 // If we have no modifiers stored in SQL-Ledger for this claim,
443 // then we cannot use a modifier passed in with the key.
444 $tmp = strpos($code, ':');
445 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
447 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
448 $insnumber = substr($inslabel, 3);
449 $paytotal = 0;
450 $adjtotal = 0;
451 $date = '';
452 foreach($this->invoice as $codekey => $codeval) {
453 if ($code && strcmp($codekey,$code) != 0) continue;
454 foreach ($codeval['dtl'] as $key => $value) {
455 if (isset($value['plv'])) {
456 // New method; plv (from ar_activity.payer_type) exists to
457 // indicate the payer level.
458 if ($value['plv'] == $insnumber) {
459 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
460 $paytotal += $value['pmt'];
463 else {
464 // Old method: With SQL-Ledger payer level was stored in the memo.
465 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
466 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
467 $paytotal += $value['pmt'];
471 $aarr = $this->payerAdjustments($ins, $codekey);
472 foreach ($aarr as $a) {
473 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
474 if (!$date) $date = $a[0];
477 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
480 // Return the amount already paid by the patient.
482 function patientPaidAmount() {
483 // For primary claims $this->invoice is not loaded, so get the co-pay
484 // from the billing table instead.
485 if (empty($this->invoice)) return $this->copay;
487 $amount = 0;
488 foreach($this->invoice as $codekey => $codeval) {
489 foreach ($codeval['dtl'] as $key => $value) {
490 if (isset($value['plv'])) {
491 // New method; plv exists to indicate the payer level.
492 if ($value['plv'] == 0) { // 0 indicates patient
493 $amount += $value['pmt'];
496 else {
497 // Old method: With SQL-Ledger payer level was stored in the memo.
498 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
499 $amount += $value['pmt'];
504 return sprintf('%.2f', $amount);
507 // Return invoice total, including adjustments but not payments.
509 function invoiceTotal() {
510 $amount = 0;
511 foreach($this->invoice as $codekey => $codeval) {
512 $amount += $codeval['chg'];
514 return sprintf('%.2f', $amount);
517 // Number of procedures in this claim.
518 function procCount() {
519 return count($this->procs);
522 // Number of payers for this claim. Ranges from 1 to 3.
523 function payerCount() {
524 return count($this->payers);
527 function x12gsversionstring() {
528 return x12clean(trim($this->x12_partner['x12_version']));
531 function x12gssenderid() {
532 $tmp = $this->x12_partner['x12_sender_id'];
533 while (strlen($tmp) < 15) $tmp .= " ";
534 return $tmp;
537 function x12gsreceiverid() {
538 $tmp = $this->x12_partner['x12_receiver_id'];
539 while (strlen($tmp) < 15) $tmp .= " ";
540 return $tmp;
543 function x12gsisa05() {
544 return $this->x12_partner['x12_isa05'];
547 function x12gsisa07() {
548 return $this->x12_partner['x12_isa07'];
551 function x12gsisa14() {
552 return $this->x12_partner['x12_isa14'];
555 function x12gsisa15() {
556 return $this->x12_partner['x12_isa15'];
559 function x12gsgs02() {
560 $tmp = $this->x12_partner['x12_gs02'];
561 if ($tmp === '') $tmp = $this->x12_partner['x12_sender_id'];
562 return $tmp;
565 function x12gsper06() {
566 return $this->x12_partner['x12_per06'];
569 function cliaCode() {
570 return x12clean(trim($this->facility['domain_identifier']));
573 function billingFacilityName() {
574 return x12clean(trim($this->billing_facility['name']));
577 function billingFacilityStreet() {
578 return x12clean(trim($this->billing_facility['street']));
581 function billingFacilityCity() {
582 return x12clean(trim($this->billing_facility['city']));
585 function billingFacilityState() {
586 return x12clean(trim($this->billing_facility['state']));
589 function billingFacilityZip() {
590 return x12clean(trim($this->billing_facility['postal_code']));
593 function billingFacilityETIN() {
594 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
597 function billingFacilityNPI() {
598 return x12clean(trim($this->billing_facility['facility_npi']));
601 function federalIdType() {
602 if ($this->billing_facility['tax_id_type'])
604 return $this->billing_facility['tax_id_type'];
606 else{
607 return null;
611 # The billing facility and the patient must both accept for this to return true.
612 function billingFacilityAssignment($ins=0) {
613 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
614 if (strcmp($tmp,'FALSE') == 0) return '0';
615 return !empty($this->billing_facility['accepts_assignment']);
618 function billingContactName() {
619 return x12clean(trim($this->billing_facility['attn']));
622 function billingContactPhone() {
623 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
624 $this->billing_facility['phone'], $tmp))
626 return $tmp[1] . $tmp[2] . $tmp[3];
628 return '';
631 function facilityName() {
632 return x12clean(trim($this->facility['name']));
635 function facilityStreet() {
636 return x12clean(trim($this->facility['street']));
639 function facilityCity() {
640 return x12clean(trim($this->facility['city']));
643 function facilityState() {
644 return x12clean(trim($this->facility['state']));
647 function facilityZip() {
648 return x12clean(trim($this->facility['postal_code']));
651 function facilityETIN() {
652 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
655 function facilityNPI() {
656 return x12clean(trim($this->facility['facility_npi']));
659 function facilityPOS() {
660 return sprintf('%02d', trim($this->facility['pos_code']));
663 function clearingHouseName() {
664 return x12clean(trim($this->x12_partner['name']));
667 function clearingHouseETIN() {
668 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
671 function providerNumberType($prockey=-1) {
672 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
673 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
674 return $tmp['provider_number_type'];
677 function providerNumber($prockey=-1) {
678 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
679 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
680 return x12clean(trim(str_replace('-', '', $tmp['provider_number'])));
683 function providerGroupNumber($prockey=-1) {
684 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
685 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
686 return x12clean(trim(str_replace('-', '', $tmp['group_number'])));
689 // Returns 'P', 'S' or 'T'.
691 function payerSequence($ins=0) {
692 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
695 // Returns the HIPAA code of the patient-to-subscriber relationship.
697 function insuredRelationship($ins=0) {
698 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
699 if (strcmp($tmp,'self' ) == 0) return '18';
700 if (strcmp($tmp,'spouse') == 0) return '01';
701 if (strcmp($tmp,'child' ) == 0) return '19';
702 if (strcmp($tmp,'other' ) == 0) return 'G8';
703 return $tmp; // should not happen
706 function insuredTypeCode($ins=0) {
707 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
708 return '12'; // medicare secondary working aged beneficiary or
709 // spouse with employer group health plan
710 return '';
713 // Is the patient also the subscriber?
715 function isSelfOfInsured($ins=0) {
716 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
717 return (strcmp($tmp,'self') == 0);
720 function planName($ins=0) {
721 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
724 function policyNumber($ins=0) { // "ID"
725 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
728 function groupNumber($ins=0) {
729 return x12clean(trim($this->payers[$ins]['data']['group_number']));
732 function groupName($ins=0) {
733 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
736 // Claim types are:
737 // 16 Other HCFA
738 // MB Medicare Part B
739 // MC Medicaid
740 // CH ChampUSVA
741 // CH ChampUS
742 // BL Blue Cross Blue Shield
743 // 16 FECA
744 // 09 Self Pay
745 // 10 Central Certification
746 // 11 Other Non-Federal Programs
747 // 12 Preferred Provider Organization (PPO)
748 // 13 Point of Service (POS)
749 // 14 Exclusive Provider Organization (EPO)
750 // 15 Indemnity Insurance
751 // 16 Health Maintenance Organization (HMO) Medicare Risk
752 // AM Automobile Medical
753 // CI Commercial Insurance Co.
754 // DS Disability
755 // HM Health Maintenance Organization
756 // LI Liability
757 // LM Liability Medical
758 // OF Other Federal Program
759 // TV Title V
760 // VA Veterans Administration Plan
761 // WC Workers Compensation Health Plan
762 // ZZ Mutually Defined
764 function claimType($ins=0) {
765 if (empty($this->payers[$ins]['object'])) return '';
766 return $this->payers[$ins]['object']->get_freeb_claim_type();
769 function insuredLastName($ins=0) {
770 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
773 function insuredFirstName($ins=0) {
774 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
777 function insuredMiddleName($ins=0) {
778 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
781 function insuredStreet($ins=0) {
782 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
785 function insuredCity($ins=0) {
786 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
789 function insuredState($ins=0) {
790 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
793 function insuredZip($ins=0) {
794 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
797 function insuredPhone($ins=0) {
798 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
799 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
800 return $tmp[1] . $tmp[2] . $tmp[3];
801 return '';
804 function insuredDOB($ins=0) {
805 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
808 function insuredSex($ins=0) {
809 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
812 function payerName($ins=0) {
813 return x12clean(trim($this->payers[$ins]['company']['name']));
816 function payerAttn($ins=0) {
817 return x12clean(trim($this->payers[$ins]['company']['attn']));
820 function payerStreet($ins=0) {
821 if (empty($this->payers[$ins]['object'])) return '';
822 $tmp = $this->payers[$ins]['object'];
823 $tmp = $tmp->get_address();
824 return x12clean(trim($tmp->get_line1()));
827 function payerCity($ins=0) {
828 if (empty($this->payers[$ins]['object'])) return '';
829 $tmp = $this->payers[$ins]['object'];
830 $tmp = $tmp->get_address();
831 return x12clean(trim($tmp->get_city()));
834 function payerState($ins=0) {
835 if (empty($this->payers[$ins]['object'])) return '';
836 $tmp = $this->payers[$ins]['object'];
837 $tmp = $tmp->get_address();
838 return x12clean(trim($tmp->get_state()));
841 function payerZip($ins=0) {
842 if (empty($this->payers[$ins]['object'])) return '';
843 $tmp = $this->payers[$ins]['object'];
844 $tmp = $tmp->get_address();
845 return x12clean(trim($tmp->get_zip()));
848 function payerID($ins=0) {
849 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
852 function payerAltID($ins=0) {
853 return x12clean(trim($this->payers[$ins]['company']['alt_cms_id']));
856 function patientLastName() {
857 return x12clean(trim($this->patient_data['lname']));
860 function patientFirstName() {
861 return x12clean(trim($this->patient_data['fname']));
864 function patientMiddleName() {
865 return x12clean(trim($this->patient_data['mname']));
868 function patientStreet() {
869 return x12clean(trim($this->patient_data['street']));
872 function patientCity() {
873 return x12clean(trim($this->patient_data['city']));
876 function patientState() {
877 return x12clean(trim($this->patient_data['state']));
880 function patientZip() {
881 return x12clean(trim($this->patient_data['postal_code']));
884 function patientPhone() {
885 $ptphone = $this->patient_data['phone_home'];
886 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
887 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
888 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
889 return $tmp[1] . $tmp[2] . $tmp[3];
890 return '';
893 function patientDOB() {
894 return str_replace('-', '', $this->patient_data['DOB']);
897 function patientSex() {
898 return strtoupper(substr($this->patient_data['sex'], 0, 1));
901 // Patient Marital Status: M = Married, S = Single, or something else.
902 function patientStatus() {
903 return strtoupper(substr($this->patient_data['status'], 0, 1));
906 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
907 // indicate employed.
908 function patientOccupation() {
909 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
912 function cptCode($prockey) {
913 return x12clean(trim($this->procs[$prockey]['code']));
916 function cptModifier($prockey) {
917 return x12clean(trim($this->procs[$prockey]['modifier']));
920 // Returns the procedure code, followed by ":modifier" if there is one.
921 function cptKey($prockey) {
922 $tmp = $this->cptModifier($prockey);
923 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
926 function cptCharges($prockey) {
927 return x12clean(trim($this->procs[$prockey]['fee']));
930 function cptUnits($prockey) {
931 if (empty($this->procs[$prockey]['units'])) return '1';
932 return x12clean(trim($this->procs[$prockey]['units']));
935 // NDC drug ID.
936 function cptNDCID($prockey) {
937 $ndcinfo = $this->procs[$prockey]['ndc_info'];
938 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
939 $ndc = $tmp[1];
940 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
941 return sprintf('%05d-%04d-%02d', $tmp[1], $tmp[2], $tmp[3]);
943 return x12clean($ndc); // format is bad but return it anyway
945 return '';
948 // NDC drug unit of measure code.
949 function cptNDCUOM($prockey) {
950 $ndcinfo = $this->procs[$prockey]['ndc_info'];
951 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
952 return x12clean($tmp[2]);
953 return '';
956 // NDC drug number of units.
957 function cptNDCQuantity($prockey) {
958 $ndcinfo = $this->procs[$prockey]['ndc_info'];
959 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
960 return x12clean(ltrim($tmp[3], '0'));
962 return '';
965 function onsetDate() {//Without the else clause in the claim zero value is coming.
966 $replace_value=str_replace('-', '', substr($this->encounter['onset_date'], 0, 10));
967 if($replace_value*1<>0)
969 return $replace_value;
971 else{
972 return '';
976 function serviceDate() {
977 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
980 function priorAuth() {
981 return x12clean(trim($this->billing_options['prior_auth_number']));
984 function isRelatedEmployment() {
985 return !empty($this->billing_options['employment_related']);
988 function isRelatedAuto() {
989 return !empty($this->billing_options['auto_accident']);
992 function isRelatedOther() {
993 return !empty($this->billing_options['other_accident']);
996 function autoAccidentState() {
997 return x12clean(trim($this->billing_options['accident_state']));
1000 function isUnableToWork() {
1001 return !empty($this->billing_options['is_unable_to_work']);
1004 function offWorkFrom() {
1005 return str_replace('-', '', substr($this->billing_options['off_work_from'], 0, 10));
1008 function offWorkTo() {
1009 return str_replace('-', '', substr($this->billing_options['off_work_to'], 0, 10));
1012 function isHospitalized() {
1013 return !empty($this->billing_options['is_hospitalized']);
1016 function hospitalizedFrom() {
1017 return str_replace('-', '', substr($this->billing_options['hospitalization_date_from'], 0, 10));
1020 function hospitalizedTo() {
1021 return str_replace('-', '', substr($this->billing_options['hospitalization_date_to'], 0, 10));
1024 function isOutsideLab() {
1025 return !empty($this->billing_options['outside_lab']);
1028 function outsideLabAmount() {
1029 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
1032 function medicaidResubmissionCode() {
1033 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
1036 function medicaidOriginalReference() {
1037 return x12clean(trim($this->billing_options['medicaid_original_reference']));
1040 function frequencyTypeCode() {
1041 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
1044 function additionalNotes() {
1045 return x12clean(trim($this->billing_options['comments']));
1048 // Returns an array of unique diagnoses. Periods are stripped.
1049 function diagArray() {
1050 $da = array();
1051 foreach ($this->procs as $row) {
1052 $atmp = explode(':', $row['justify']);
1053 foreach ($atmp as $tmp) {
1054 if (!empty($tmp)) {
1055 $diag = str_replace('.', '', $tmp);
1056 $da[$diag] = $diag;
1060 // The above got all the diagnoses used for justification, in the order
1061 // used for justification. Next we go through all diagnoses, justified
1062 // or not, to make sure they all get into the claim. We do it this way
1063 // so that the more important diagnoses appear first.
1064 foreach ($this->diags as $diag) {
1065 $diag = str_replace('.', '', $diag);
1066 $da[$diag] = $diag;
1068 return $da;
1071 // Compute one 1-relative index in diagArray for the given procedure.
1072 // This function is obsolete, use diagIndexArray() instead.
1073 function diagIndex($prockey) {
1074 $da = $this->diagArray();
1075 $tmp = explode(':', $this->procs[$prockey]['justify']);
1076 if (empty($tmp)) return '';
1077 $diag = str_replace('.', '', $tmp[0]);
1078 $i = 0;
1079 foreach ($da as $value) {
1080 ++$i;
1081 if (strcmp($value,$diag) == 0) return $i;
1083 return '';
1086 // Compute array of 1-relative diagArray indices for the given procedure.
1087 function diagIndexArray($prockey) {
1088 $dia = array();
1089 $da = $this->diagArray();
1090 $atmp = explode(':', $this->procs[$prockey]['justify']);
1091 foreach ($atmp as $tmp) {
1092 if (!empty($tmp)) {
1093 $diag = str_replace('.', '', $tmp);
1094 $i = 0;
1095 foreach ($da as $value) {
1096 ++$i;
1097 if (strcmp($value,$diag) == 0) $dia[] = $i;
1101 return $dia;
1104 function providerLastName($prockey=-1) {
1105 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1106 $this->provider : $this->procs[$prockey]['provider'];
1107 return x12clean(trim($tmp['lname']));
1110 function providerFirstName($prockey=-1) {
1111 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1112 $this->provider : $this->procs[$prockey]['provider'];
1113 return x12clean(trim($tmp['fname']));
1116 function providerMiddleName($prockey=-1) {
1117 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1118 $this->provider : $this->procs[$prockey]['provider'];
1119 return x12clean(trim($tmp['mname']));
1122 function providerNPI($prockey=-1) {
1123 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1124 $this->provider : $this->procs[$prockey]['provider'];
1125 return x12clean(trim($tmp['npi']));
1128 function providerUPIN($prockey=-1) {
1129 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1130 $this->provider : $this->procs[$prockey]['provider'];
1131 return x12clean(trim($tmp['upin']));
1134 function providerSSN($prockey=-1) {
1135 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1136 $this->provider : $this->procs[$prockey]['provider'];
1137 return x12clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1140 function providerTaxonomy($prockey=-1) {
1141 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1142 $this->provider : $this->procs[$prockey]['provider'];
1143 if (empty($tmp['taxonomy'])) return '207Q00000X';
1144 return x12clean(trim($tmp['taxonomy']));
1147 function referrerLastName() {
1148 return x12clean(trim($this->referrer['lname']));
1151 function referrerFirstName() {
1152 return x12clean(trim($this->referrer['fname']));
1155 function referrerMiddleName() {
1156 return x12clean(trim($this->referrer['mname']));
1159 function referrerNPI() {
1160 return x12clean(trim($this->referrer['npi']));
1163 function referrerUPIN() {
1164 return x12clean(trim($this->referrer['upin']));
1167 function referrerSSN() {
1168 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
1171 function referrerTaxonomy() {
1172 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1173 return x12clean(trim($this->referrer['taxonomy']));
1176 function supervisorLastName() {
1177 return x12clean(trim($this->supervisor['lname']));
1180 function supervisorFirstName() {
1181 return x12clean(trim($this->supervisor['fname']));
1184 function supervisorMiddleName() {
1185 return x12clean(trim($this->supervisor['mname']));
1188 function supervisorNPI() {
1189 return x12clean(trim($this->supervisor['npi']));
1192 function supervisorUPIN() {
1193 return x12clean(trim($this->supervisor['upin']));
1196 function supervisorSSN() {
1197 return x12clean(trim(str_replace('-', '', $this->supervisor['federaltaxid'])));
1200 function supervisorTaxonomy() {
1201 if (empty($this->supervisor['taxonomy'])) return '207Q00000X';
1202 return x12clean(trim($this->supervisor['taxonomy']));
1205 function supervisorNumberType() {
1206 return $this->supervisor_numbers['provider_number_type'];
1209 function supervisorNumber() {
1210 return x12clean(trim(str_replace('-', '', $this->supervisor_numbers['provider_number'])));