Merge branch 'master' of git://github.com/openemr/openemr
[openemr.git] / library / Claim.class.php
blob8ba418cd33aa0b92faa17c3c8fa51450a8d49529
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 (preg_match("/^Ins(\d)/i", $value['src'], $tmp)) {
286 if ($tmp[1] <= $insnumber) $ptresp -= $value['pmt'];
288 else if (trim(substr($key, 0, 10))) { // not an adjustment if no date
289 if (!preg_match("/Ins(\d)/i", $value['rsn'], $tmp) || $tmp[1] <= $insnumber)
290 $ptresp += $value['chg']; // adjustments are negative charges
293 if ($ptresp < 0) $ptresp = 0; // we may be insane but try to hide it
295 // Main loop, to extract adjustments for this payer and procedure.
296 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
297 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
298 if ($tmp) $date = $tmp;
299 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
300 $rsn = $value['rsn'];
301 $chg = 0 - $value['chg']; // adjustments are negative charges
303 $gcode = 'CO'; // default group code = contractual obligation
304 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
306 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
307 // From manual post. Take the defaults.
309 else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
310 $coinsurance = $ptresp; // from manual post
311 continue;
313 else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
314 $deductible = $ptresp; // from manual post
315 continue;
317 else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
318 $coinsurance = $tmp[1]; // from 835 as of 6/2007
319 continue;
321 else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
322 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
323 continue;
325 else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
326 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
327 continue;
329 else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
330 continue; // from 835 as of 6/2007
332 else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
333 $rcode = $tmp[1]; // from 835
335 else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
336 // Take the defaults.
338 else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
339 continue; // it's for some other payer
341 else if ($insnumber == '1') {
342 if (preg_match("/\$\s*adjust code (\S+)/i", $rsn, $tmp)) {
343 $rcode = $tmp[1]; // from 835
345 else if ($chg) {
346 // Other adjustments default to Ins1.
348 else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
349 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
350 $coinsurance = 0 + $tmp[1]; // from 835 before 6/2007
351 continue;
353 else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
354 $deductible = 0 + $tmp[1]; // from 835 before 6/2007
355 continue;
357 else {
358 continue; // there is no adjustment amount
361 else {
362 continue; // it's for primary and that's not us
365 if ($rcode == '42') $rcode= '45'; // reason 42 is obsolete
366 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
368 } // end if
369 } // end foreach
371 // If we really messed it up, at least avoid negative numbers.
372 if ($coinsurance > $ptresp) $coinsurance = $ptresp;
373 if ($deductible > $ptresp) $deductible = $ptresp;
375 // Find out if this payer paid anything at all on this claim. This will
376 // help us allocate any unknown patient responsibility amounts.
377 $thispaidanything = 0;
378 foreach($this->invoice as $codekey => $codeval) {
379 foreach ($codeval['dtl'] as $key => $value) {
380 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
381 $thispaidanything += $value['pmt'];
386 // Allocate any unknown patient responsibility by guessing if the
387 // deductible has been satisfied.
388 if ($thispaidanything)
389 $coinsurance = $ptresp - $deductible;
390 else
391 $deductible = $ptresp - $coinsurance;
393 if ($date && $deductible != 0)
394 $aadj[] = array($date, 'PR', '1', sprintf('%.2f', $deductible));
395 if ($date && $coinsurance != 0)
396 $aadj[] = array($date, 'PR', '2', sprintf('%.2f', $coinsurance));
398 } // end if
400 return $aadj;
403 // Return date, total payments and total "hard" adjustments from the given
404 // prior payer. If $code is specified then only that procedure key is
405 // selected, otherwise it's for the whole claim.
407 function payerTotals($ins, $code='') {
408 // If we have no modifiers stored in SQL-Ledger for this claim,
409 // then we cannot use a modifier passed in with the key.
410 $tmp = strpos($code, ':');
411 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
413 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
414 $paytotal = 0;
415 $adjtotal = 0;
416 $date = '';
417 foreach($this->invoice as $codekey => $codeval) {
418 if ($code && strcmp($codekey,$code) != 0) continue;
419 foreach ($codeval['dtl'] as $key => $value) {
420 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
421 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
422 $paytotal += $value['pmt'];
425 $aarr = $this->payerAdjustments($ins, $codekey);
426 foreach ($aarr as $a) {
427 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
428 if (!$date) $date = $a[0];
431 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
434 // Return the amount already paid by the patient.
436 function patientPaidAmount() {
437 // For primary claims $this->invoice is not loaded, so get the co-pay
438 // from the billing table instead.
439 if (empty($this->invoice)) return $this->copay;
441 $amount = 0;
442 foreach($this->invoice as $codekey => $codeval) {
443 foreach ($codeval['dtl'] as $key => $value) {
444 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
445 $amount += $value['pmt'];
449 return sprintf('%.2f', $amount);
452 // Return invoice total, including adjustments but not payments.
454 function invoiceTotal() {
455 $amount = 0;
456 foreach($this->invoice as $codekey => $codeval) {
457 $amount += $codeval['chg'];
459 return sprintf('%.2f', $amount);
462 // Number of procedures in this claim.
463 function procCount() {
464 return count($this->procs);
467 // Number of payers for this claim. Ranges from 1 to 3.
468 function payerCount() {
469 return count($this->payers);
472 function x12gsversionstring() {
473 return x12clean(trim($this->x12_partner['x12_version']));
476 function x12gssenderid() {
477 $tmp = $this->x12_partner['x12_sender_id'];
478 while (strlen($tmp) < 15) $tmp .= " ";
479 return $tmp;
482 function x12gsreceiverid() {
483 $tmp = $this->x12_partner['x12_receiver_id'];
484 while (strlen($tmp) < 15) $tmp .= " ";
485 return $tmp;
488 function x12gsisa05() {
489 return $this->x12_partner['x12_isa05'];
492 function x12gsisa07() {
493 return $this->x12_partner['x12_isa07'];
496 function x12gsisa14() {
497 return $this->x12_partner['x12_isa14'];
500 function x12gsisa15() {
501 return $this->x12_partner['x12_isa15'];
504 function x12gsgs02() {
505 $tmp = $this->x12_partner['x12_gs02'];
506 if ($tmp === '') $tmp = $this->x12_partner['x12_sender_id'];
507 return $tmp;
510 function x12gsper06() {
511 return $this->x12_partner['x12_per06'];
514 function cliaCode() {
515 return x12clean(trim($this->facility['domain_identifier']));
518 function billingFacilityName() {
519 return x12clean(trim($this->billing_facility['name']));
522 function billingFacilityStreet() {
523 return x12clean(trim($this->billing_facility['street']));
526 function billingFacilityCity() {
527 return x12clean(trim($this->billing_facility['city']));
530 function billingFacilityState() {
531 return x12clean(trim($this->billing_facility['state']));
534 function billingFacilityZip() {
535 return x12clean(trim($this->billing_facility['postal_code']));
538 function billingFacilityETIN() {
539 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
542 function billingFacilityNPI() {
543 return x12clean(trim($this->billing_facility['facility_npi']));
546 # The billing facility and the patient must both accept for this to return true.
547 function billingFacilityAssignment($ins=0) {
548 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
549 if (strcmp($tmp,'FALSE') == 0) return '0';
550 return !empty($this->billing_facility['accepts_assignment']);
553 function billingContactName() {
554 return x12clean(trim($this->billing_facility['attn']));
557 function billingContactPhone() {
558 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
559 $this->billing_facility['phone'], $tmp))
561 return $tmp[1] . $tmp[2] . $tmp[3];
563 return '';
566 function facilityName() {
567 return x12clean(trim($this->facility['name']));
570 function facilityStreet() {
571 return x12clean(trim($this->facility['street']));
574 function facilityCity() {
575 return x12clean(trim($this->facility['city']));
578 function facilityState() {
579 return x12clean(trim($this->facility['state']));
582 function facilityZip() {
583 return x12clean(trim($this->facility['postal_code']));
586 function facilityETIN() {
587 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
590 function facilityNPI() {
591 return x12clean(trim($this->facility['facility_npi']));
594 function facilityPOS() {
595 return x12clean(trim($this->facility['pos_code']));
598 function clearingHouseName() {
599 return x12clean(trim($this->x12_partner['name']));
602 function clearingHouseETIN() {
603 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
606 function providerNumberType($prockey=-1) {
607 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
608 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
609 return $tmp['provider_number_type'];
612 function providerNumber($prockey=-1) {
613 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
614 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
615 return x12clean(trim(str_replace('-', '', $tmp['provider_number'])));
618 function providerGroupNumber($prockey=-1) {
619 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
620 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
621 return x12clean(trim(str_replace('-', '', $tmp['group_number'])));
624 // Returns 'P', 'S' or 'T'.
626 function payerSequence($ins=0) {
627 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
630 // Returns the HIPAA code of the patient-to-subscriber relationship.
632 function insuredRelationship($ins=0) {
633 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
634 if (strcmp($tmp,'self' ) == 0) return '18';
635 if (strcmp($tmp,'spouse') == 0) return '01';
636 if (strcmp($tmp,'child' ) == 0) return '19';
637 if (strcmp($tmp,'other' ) == 0) return 'G8';
638 return $tmp; // should not happen
641 function insuredTypeCode($ins=0) {
642 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
643 return '12'; // medicare secondary working aged beneficiary or
644 // spouse with employer group health plan
645 return '';
648 // Is the patient also the subscriber?
650 function isSelfOfInsured($ins=0) {
651 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
652 return (strcmp($tmp,'self') == 0);
655 function planName($ins=0) {
656 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
659 function policyNumber($ins=0) { // "ID"
660 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
663 function groupNumber($ins=0) {
664 return x12clean(trim($this->payers[$ins]['data']['group_number']));
667 function groupName($ins=0) {
668 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
671 // Claim types are:
672 // 16 Other HCFA
673 // MB Medicare Part B
674 // MC Medicaid
675 // CH ChampUSVA
676 // CH ChampUS
677 // BL Blue Cross Blue Shield
678 // 16 FECA
679 // 09 Self Pay
680 // 10 Central Certification
681 // 11 Other Non-Federal Programs
682 // 12 Preferred Provider Organization (PPO)
683 // 13 Point of Service (POS)
684 // 14 Exclusive Provider Organization (EPO)
685 // 15 Indemnity Insurance
686 // 16 Health Maintenance Organization (HMO) Medicare Risk
687 // AM Automobile Medical
688 // CI Commercial Insurance Co.
689 // DS Disability
690 // HM Health Maintenance Organization
691 // LI Liability
692 // LM Liability Medical
693 // OF Other Federal Program
694 // TV Title V
695 // VA Veterans Administration Plan
696 // WC Workers Compensation Health Plan
697 // ZZ Mutually Defined
699 function claimType($ins=0) {
700 if (empty($this->payers[$ins]['object'])) return '';
701 return $this->payers[$ins]['object']->get_freeb_claim_type();
704 function insuredLastName($ins=0) {
705 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
708 function insuredFirstName($ins=0) {
709 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
712 function insuredMiddleName($ins=0) {
713 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
716 function insuredStreet($ins=0) {
717 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
720 function insuredCity($ins=0) {
721 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
724 function insuredState($ins=0) {
725 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
728 function insuredZip($ins=0) {
729 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
732 function insuredPhone($ins=0) {
733 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
734 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
735 return $tmp[1] . $tmp[2] . $tmp[3];
736 return '';
739 function insuredDOB($ins=0) {
740 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
743 function insuredSex($ins=0) {
744 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
747 function payerName($ins=0) {
748 return x12clean(trim($this->payers[$ins]['company']['name']));
751 function payerAttn($ins=0) {
752 return x12clean(trim($this->payers[$ins]['company']['attn']));
755 function payerStreet($ins=0) {
756 if (empty($this->payers[$ins]['object'])) return '';
757 $tmp = $this->payers[$ins]['object'];
758 $tmp = $tmp->get_address();
759 return x12clean(trim($tmp->get_line1()));
762 function payerCity($ins=0) {
763 if (empty($this->payers[$ins]['object'])) return '';
764 $tmp = $this->payers[$ins]['object'];
765 $tmp = $tmp->get_address();
766 return x12clean(trim($tmp->get_city()));
769 function payerState($ins=0) {
770 if (empty($this->payers[$ins]['object'])) return '';
771 $tmp = $this->payers[$ins]['object'];
772 $tmp = $tmp->get_address();
773 return x12clean(trim($tmp->get_state()));
776 function payerZip($ins=0) {
777 if (empty($this->payers[$ins]['object'])) return '';
778 $tmp = $this->payers[$ins]['object'];
779 $tmp = $tmp->get_address();
780 return x12clean(trim($tmp->get_zip()));
783 function payerID($ins=0) {
784 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
787 function payerAltID($ins=0) {
788 return x12clean(trim($this->payers[$ins]['company']['alt_cms_id']));
791 function patientLastName() {
792 return x12clean(trim($this->patient_data['lname']));
795 function patientFirstName() {
796 return x12clean(trim($this->patient_data['fname']));
799 function patientMiddleName() {
800 return x12clean(trim($this->patient_data['mname']));
803 function patientStreet() {
804 return x12clean(trim($this->patient_data['street']));
807 function patientCity() {
808 return x12clean(trim($this->patient_data['city']));
811 function patientState() {
812 return x12clean(trim($this->patient_data['state']));
815 function patientZip() {
816 return x12clean(trim($this->patient_data['postal_code']));
819 function patientPhone() {
820 $ptphone = $this->patient_data['phone_home'];
821 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
822 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
823 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
824 return $tmp[1] . $tmp[2] . $tmp[3];
825 return '';
828 function patientDOB() {
829 return str_replace('-', '', $this->patient_data['DOB']);
832 function patientSex() {
833 return strtoupper(substr($this->patient_data['sex'], 0, 1));
836 // Patient Marital Status: M = Married, S = Single, or something else.
837 function patientStatus() {
838 return strtoupper(substr($this->patient_data['status'], 0, 1));
841 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
842 // indicate employed.
843 function patientOccupation() {
844 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
847 function cptCode($prockey) {
848 return x12clean(trim($this->procs[$prockey]['code']));
851 function cptModifier($prockey) {
852 return x12clean(trim($this->procs[$prockey]['modifier']));
855 // Returns the procedure code, followed by ":modifier" if there is one.
856 function cptKey($prockey) {
857 $tmp = $this->cptModifier($prockey);
858 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
861 function cptCharges($prockey) {
862 return x12clean(trim($this->procs[$prockey]['fee']));
865 function cptUnits($prockey) {
866 if (empty($this->procs[$prockey]['units'])) return '1';
867 return x12clean(trim($this->procs[$prockey]['units']));
870 // NDC drug ID.
871 function cptNDCID($prockey) {
872 $ndcinfo = $this->procs[$prockey]['ndc_info'];
873 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
874 $ndc = $tmp[1];
875 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
876 return sprintf('%05d-%04d-%02d', $tmp[1], $tmp[2], $tmp[3]);
878 return x12clean($ndc); // format is bad but return it anyway
880 return '';
883 // NDC drug unit of measure code.
884 function cptNDCUOM($prockey) {
885 $ndcinfo = $this->procs[$prockey]['ndc_info'];
886 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
887 return x12clean($tmp[2]);
888 return '';
891 // NDC drug number of units.
892 function cptNDCQuantity($prockey) {
893 $ndcinfo = $this->procs[$prockey]['ndc_info'];
894 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
895 return x12clean(ltrim($tmp[3], '0'));
897 return '';
900 function onsetDate() {
901 return str_replace('-', '', substr($this->encounter['onset_date'], 0, 10));
904 function serviceDate() {
905 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
908 function priorAuth() {
909 return x12clean(trim($this->billing_options['prior_auth_number']));
912 function isRelatedEmployment() {
913 return !empty($this->billing_options['employment_related']);
916 function isRelatedAuto() {
917 return !empty($this->billing_options['auto_accident']);
920 function isRelatedOther() {
921 return !empty($this->billing_options['other_accident']);
924 function autoAccidentState() {
925 return x12clean(trim($this->billing_options['accident_state']));
928 function isUnableToWork() {
929 return !empty($this->billing_options['is_unable_to_work']);
932 function offWorkFrom() {
933 return str_replace('-', '', substr($this->billing_options['off_work_from'], 0, 10));
936 function offWorkTo() {
937 return str_replace('-', '', substr($this->billing_options['off_work_to'], 0, 10));
940 function isHospitalized() {
941 return !empty($this->billing_options['is_hospitalized']);
944 function hospitalizedFrom() {
945 return str_replace('-', '', substr($this->billing_options['hospitalization_date_from'], 0, 10));
948 function hospitalizedTo() {
949 return str_replace('-', '', substr($this->billing_options['hospitalization_date_to'], 0, 10));
952 function isOutsideLab() {
953 return !empty($this->billing_options['outside_lab']);
956 function outsideLabAmount() {
957 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
960 function medicaidResubmissionCode() {
961 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
964 function medicaidOriginalReference() {
965 return x12clean(trim($this->billing_options['medicaid_original_reference']));
968 function frequencyTypeCode() {
969 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
972 function additionalNotes() {
973 return x12clean(trim($this->billing_options['comments']));
976 // Returns an array of unique diagnoses. Periods are stripped.
977 function diagArray() {
978 $da = array();
979 foreach ($this->procs as $row) {
980 $atmp = explode(':', $row['justify']);
981 foreach ($atmp as $tmp) {
982 if (!empty($tmp)) {
983 $diag = str_replace('.', '', $tmp);
984 $da[$diag] = $diag;
988 // The above got all the diagnoses used for justification, in the order
989 // used for justification. Next we go through all diagnoses, justified
990 // or not, to make sure they all get into the claim. We do it this way
991 // so that the more important diagnoses appear first.
992 foreach ($this->diags as $diag) {
993 $diag = str_replace('.', '', $diag);
994 $da[$diag] = $diag;
996 return $da;
999 // Compute one 1-relative index in diagArray for the given procedure.
1000 // This function is obsolete, use diagIndexArray() instead.
1001 function diagIndex($prockey) {
1002 $da = $this->diagArray();
1003 $tmp = explode(':', $this->procs[$prockey]['justify']);
1004 if (empty($tmp)) return '';
1005 $diag = str_replace('.', '', $tmp[0]);
1006 $i = 0;
1007 foreach ($da as $value) {
1008 ++$i;
1009 if (strcmp($value,$diag) == 0) return $i;
1011 return '';
1014 // Compute array of 1-relative diagArray indices for the given procedure.
1015 function diagIndexArray($prockey) {
1016 $dia = array();
1017 $da = $this->diagArray();
1018 $atmp = explode(':', $this->procs[$prockey]['justify']);
1019 foreach ($atmp as $tmp) {
1020 if (!empty($tmp)) {
1021 $diag = str_replace('.', '', $tmp);
1022 $i = 0;
1023 foreach ($da as $value) {
1024 ++$i;
1025 if (strcmp($value,$diag) == 0) $dia[] = $i;
1029 return $dia;
1032 function providerLastName($prockey=-1) {
1033 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1034 $this->provider : $this->procs[$prockey]['provider'];
1035 return x12clean(trim($tmp['lname']));
1038 function providerFirstName($prockey=-1) {
1039 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1040 $this->provider : $this->procs[$prockey]['provider'];
1041 return x12clean(trim($tmp['fname']));
1044 function providerMiddleName($prockey=-1) {
1045 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1046 $this->provider : $this->procs[$prockey]['provider'];
1047 return x12clean(trim($tmp['mname']));
1050 function providerNPI($prockey=-1) {
1051 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1052 $this->provider : $this->procs[$prockey]['provider'];
1053 return x12clean(trim($tmp['npi']));
1056 function providerUPIN($prockey=-1) {
1057 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1058 $this->provider : $this->procs[$prockey]['provider'];
1059 return x12clean(trim($tmp['upin']));
1062 function providerSSN($prockey=-1) {
1063 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1064 $this->provider : $this->procs[$prockey]['provider'];
1065 return x12clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1068 function providerTaxonomy($prockey=-1) {
1069 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1070 $this->provider : $this->procs[$prockey]['provider'];
1071 if (empty($tmp['taxonomy'])) return '207Q00000X';
1072 return x12clean(trim($tmp['taxonomy']));
1075 function referrerLastName() {
1076 return x12clean(trim($this->referrer['lname']));
1079 function referrerFirstName() {
1080 return x12clean(trim($this->referrer['fname']));
1083 function referrerMiddleName() {
1084 return x12clean(trim($this->referrer['mname']));
1087 function referrerNPI() {
1088 return x12clean(trim($this->referrer['npi']));
1091 function referrerUPIN() {
1092 return x12clean(trim($this->referrer['upin']));
1095 function referrerSSN() {
1096 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
1099 function referrerTaxonomy() {
1100 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1101 return x12clean(trim($this->referrer['taxonomy']));
1104 function supervisorLastName() {
1105 return x12clean(trim($this->supervisor['lname']));
1108 function supervisorFirstName() {
1109 return x12clean(trim($this->supervisor['fname']));
1112 function supervisorMiddleName() {
1113 return x12clean(trim($this->supervisor['mname']));
1116 function supervisorNPI() {
1117 return x12clean(trim($this->supervisor['npi']));
1120 function supervisorUPIN() {
1121 return x12clean(trim($this->supervisor['upin']));
1124 function supervisorSSN() {
1125 return x12clean(trim(str_replace('-', '', $this->supervisor['federaltaxid'])));
1128 function supervisorTaxonomy() {
1129 if (empty($this->supervisor['taxonomy'])) return '207Q00000X';
1130 return x12clean(trim($this->supervisor['taxonomy']));
1133 function supervisorNumberType() {
1134 return $this->supervisor_numbers['provider_number_type'];
1137 function supervisorNumber() {
1138 return x12clean(trim(str_replace('-', '', $this->supervisor_numbers['provider_number'])));