Documents Module: Added features for document SHA-1 checks and document encryption.
[openemr.git] / library / Claim.class.php
blobc9413d4b56c1eb8fa5f6a71d24288afbaf743998
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 $deductible = sprintf('%.2f', $deductible);
410 $coinsurance = sprintf('%.2f', $coinsurance);
412 if ($date && $deductible != 0)
413 $aadj[] = array($date, 'PR', '1', $deductible);
414 if ($date && $coinsurance != 0)
415 $aadj[] = array($date, 'PR', '2', $coinsurance);
417 } // end if
419 return $aadj;
422 // Return date, total payments and total "hard" adjustments from the given
423 // prior payer. If $code is specified then only that procedure key is
424 // selected, otherwise it's for the whole claim.
426 function payerTotals($ins, $code='') {
427 // If we have no modifiers stored in SQL-Ledger for this claim,
428 // then we cannot use a modifier passed in with the key.
429 $tmp = strpos($code, ':');
430 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
432 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
433 $insnumber = substr($inslabel, 3);
434 $paytotal = 0;
435 $adjtotal = 0;
436 $date = '';
437 foreach($this->invoice as $codekey => $codeval) {
438 if ($code && strcmp($codekey,$code) != 0) continue;
439 foreach ($codeval['dtl'] as $key => $value) {
440 if (isset($value['plv'])) {
441 // New method; plv (from ar_activity.payer_type) exists to
442 // indicate the payer level.
443 if ($value['plv'] == $insnumber) {
444 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
445 $paytotal += $value['pmt'];
448 else {
449 // Old method: With SQL-Ledger payer level was stored in the memo.
450 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
451 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
452 $paytotal += $value['pmt'];
456 $aarr = $this->payerAdjustments($ins, $codekey);
457 foreach ($aarr as $a) {
458 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
459 if (!$date) $date = $a[0];
462 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
465 // Return the amount already paid by the patient.
467 function patientPaidAmount() {
468 // For primary claims $this->invoice is not loaded, so get the co-pay
469 // from the billing table instead.
470 if (empty($this->invoice)) return $this->copay;
472 $amount = 0;
473 foreach($this->invoice as $codekey => $codeval) {
474 foreach ($codeval['dtl'] as $key => $value) {
475 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
476 $amount += $value['pmt'];
480 return sprintf('%.2f', $amount);
483 // Return invoice total, including adjustments but not payments.
485 function invoiceTotal() {
486 $amount = 0;
487 foreach($this->invoice as $codekey => $codeval) {
488 $amount += $codeval['chg'];
490 return sprintf('%.2f', $amount);
493 // Number of procedures in this claim.
494 function procCount() {
495 return count($this->procs);
498 // Number of payers for this claim. Ranges from 1 to 3.
499 function payerCount() {
500 return count($this->payers);
503 function x12gsversionstring() {
504 return x12clean(trim($this->x12_partner['x12_version']));
507 function x12gssenderid() {
508 $tmp = $this->x12_partner['x12_sender_id'];
509 while (strlen($tmp) < 15) $tmp .= " ";
510 return $tmp;
513 function x12gsreceiverid() {
514 $tmp = $this->x12_partner['x12_receiver_id'];
515 while (strlen($tmp) < 15) $tmp .= " ";
516 return $tmp;
519 function x12gsisa05() {
520 return $this->x12_partner['x12_isa05'];
523 function x12gsisa07() {
524 return $this->x12_partner['x12_isa07'];
527 function x12gsisa14() {
528 return $this->x12_partner['x12_isa14'];
531 function x12gsisa15() {
532 return $this->x12_partner['x12_isa15'];
535 function x12gsgs02() {
536 $tmp = $this->x12_partner['x12_gs02'];
537 if ($tmp === '') $tmp = $this->x12_partner['x12_sender_id'];
538 return $tmp;
541 function x12gsper06() {
542 return $this->x12_partner['x12_per06'];
545 function cliaCode() {
546 return x12clean(trim($this->facility['domain_identifier']));
549 function billingFacilityName() {
550 return x12clean(trim($this->billing_facility['name']));
553 function billingFacilityStreet() {
554 return x12clean(trim($this->billing_facility['street']));
557 function billingFacilityCity() {
558 return x12clean(trim($this->billing_facility['city']));
561 function billingFacilityState() {
562 return x12clean(trim($this->billing_facility['state']));
565 function billingFacilityZip() {
566 return x12clean(trim($this->billing_facility['postal_code']));
569 function billingFacilityETIN() {
570 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
573 function billingFacilityNPI() {
574 return x12clean(trim($this->billing_facility['facility_npi']));
577 function federalIdType() {
578 if ($this->billing_facility['tax_id_type'])
580 return $this->billing_facility['tax_id_type'];
582 else{
583 return null;
587 # The billing facility and the patient must both accept for this to return true.
588 function billingFacilityAssignment($ins=0) {
589 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
590 if (strcmp($tmp,'FALSE') == 0) return '0';
591 return !empty($this->billing_facility['accepts_assignment']);
594 function billingContactName() {
595 return x12clean(trim($this->billing_facility['attn']));
598 function billingContactPhone() {
599 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
600 $this->billing_facility['phone'], $tmp))
602 return $tmp[1] . $tmp[2] . $tmp[3];
604 return '';
607 function facilityName() {
608 return x12clean(trim($this->facility['name']));
611 function facilityStreet() {
612 return x12clean(trim($this->facility['street']));
615 function facilityCity() {
616 return x12clean(trim($this->facility['city']));
619 function facilityState() {
620 return x12clean(trim($this->facility['state']));
623 function facilityZip() {
624 return x12clean(trim($this->facility['postal_code']));
627 function facilityETIN() {
628 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
631 function facilityNPI() {
632 return x12clean(trim($this->facility['facility_npi']));
635 function facilityPOS() {
636 return sprintf('%02d', trim($this->facility['pos_code']));
639 function clearingHouseName() {
640 return x12clean(trim($this->x12_partner['name']));
643 function clearingHouseETIN() {
644 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
647 function providerNumberType($prockey=-1) {
648 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
649 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
650 return $tmp['provider_number_type'];
653 function providerNumber($prockey=-1) {
654 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
655 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
656 return x12clean(trim(str_replace('-', '', $tmp['provider_number'])));
659 function providerGroupNumber($prockey=-1) {
660 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
661 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
662 return x12clean(trim(str_replace('-', '', $tmp['group_number'])));
665 // Returns 'P', 'S' or 'T'.
667 function payerSequence($ins=0) {
668 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
671 // Returns the HIPAA code of the patient-to-subscriber relationship.
673 function insuredRelationship($ins=0) {
674 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
675 if (strcmp($tmp,'self' ) == 0) return '18';
676 if (strcmp($tmp,'spouse') == 0) return '01';
677 if (strcmp($tmp,'child' ) == 0) return '19';
678 if (strcmp($tmp,'other' ) == 0) return 'G8';
679 return $tmp; // should not happen
682 function insuredTypeCode($ins=0) {
683 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
684 return '12'; // medicare secondary working aged beneficiary or
685 // spouse with employer group health plan
686 return '';
689 // Is the patient also the subscriber?
691 function isSelfOfInsured($ins=0) {
692 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
693 return (strcmp($tmp,'self') == 0);
696 function planName($ins=0) {
697 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
700 function policyNumber($ins=0) { // "ID"
701 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
704 function groupNumber($ins=0) {
705 return x12clean(trim($this->payers[$ins]['data']['group_number']));
708 function groupName($ins=0) {
709 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
712 // Claim types are:
713 // 16 Other HCFA
714 // MB Medicare Part B
715 // MC Medicaid
716 // CH ChampUSVA
717 // CH ChampUS
718 // BL Blue Cross Blue Shield
719 // 16 FECA
720 // 09 Self Pay
721 // 10 Central Certification
722 // 11 Other Non-Federal Programs
723 // 12 Preferred Provider Organization (PPO)
724 // 13 Point of Service (POS)
725 // 14 Exclusive Provider Organization (EPO)
726 // 15 Indemnity Insurance
727 // 16 Health Maintenance Organization (HMO) Medicare Risk
728 // AM Automobile Medical
729 // CI Commercial Insurance Co.
730 // DS Disability
731 // HM Health Maintenance Organization
732 // LI Liability
733 // LM Liability Medical
734 // OF Other Federal Program
735 // TV Title V
736 // VA Veterans Administration Plan
737 // WC Workers Compensation Health Plan
738 // ZZ Mutually Defined
740 function claimType($ins=0) {
741 if (empty($this->payers[$ins]['object'])) return '';
742 return $this->payers[$ins]['object']->get_freeb_claim_type();
745 function insuredLastName($ins=0) {
746 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
749 function insuredFirstName($ins=0) {
750 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
753 function insuredMiddleName($ins=0) {
754 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
757 function insuredStreet($ins=0) {
758 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
761 function insuredCity($ins=0) {
762 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
765 function insuredState($ins=0) {
766 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
769 function insuredZip($ins=0) {
770 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
773 function insuredPhone($ins=0) {
774 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
775 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
776 return $tmp[1] . $tmp[2] . $tmp[3];
777 return '';
780 function insuredDOB($ins=0) {
781 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
784 function insuredSex($ins=0) {
785 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
788 function payerName($ins=0) {
789 return x12clean(trim($this->payers[$ins]['company']['name']));
792 function payerAttn($ins=0) {
793 return x12clean(trim($this->payers[$ins]['company']['attn']));
796 function payerStreet($ins=0) {
797 if (empty($this->payers[$ins]['object'])) return '';
798 $tmp = $this->payers[$ins]['object'];
799 $tmp = $tmp->get_address();
800 return x12clean(trim($tmp->get_line1()));
803 function payerCity($ins=0) {
804 if (empty($this->payers[$ins]['object'])) return '';
805 $tmp = $this->payers[$ins]['object'];
806 $tmp = $tmp->get_address();
807 return x12clean(trim($tmp->get_city()));
810 function payerState($ins=0) {
811 if (empty($this->payers[$ins]['object'])) return '';
812 $tmp = $this->payers[$ins]['object'];
813 $tmp = $tmp->get_address();
814 return x12clean(trim($tmp->get_state()));
817 function payerZip($ins=0) {
818 if (empty($this->payers[$ins]['object'])) return '';
819 $tmp = $this->payers[$ins]['object'];
820 $tmp = $tmp->get_address();
821 return x12clean(trim($tmp->get_zip()));
824 function payerID($ins=0) {
825 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
828 function payerAltID($ins=0) {
829 return x12clean(trim($this->payers[$ins]['company']['alt_cms_id']));
832 function patientLastName() {
833 return x12clean(trim($this->patient_data['lname']));
836 function patientFirstName() {
837 return x12clean(trim($this->patient_data['fname']));
840 function patientMiddleName() {
841 return x12clean(trim($this->patient_data['mname']));
844 function patientStreet() {
845 return x12clean(trim($this->patient_data['street']));
848 function patientCity() {
849 return x12clean(trim($this->patient_data['city']));
852 function patientState() {
853 return x12clean(trim($this->patient_data['state']));
856 function patientZip() {
857 return x12clean(trim($this->patient_data['postal_code']));
860 function patientPhone() {
861 $ptphone = $this->patient_data['phone_home'];
862 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
863 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
864 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
865 return $tmp[1] . $tmp[2] . $tmp[3];
866 return '';
869 function patientDOB() {
870 return str_replace('-', '', $this->patient_data['DOB']);
873 function patientSex() {
874 return strtoupper(substr($this->patient_data['sex'], 0, 1));
877 // Patient Marital Status: M = Married, S = Single, or something else.
878 function patientStatus() {
879 return strtoupper(substr($this->patient_data['status'], 0, 1));
882 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
883 // indicate employed.
884 function patientOccupation() {
885 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
888 function cptCode($prockey) {
889 return x12clean(trim($this->procs[$prockey]['code']));
892 function cptModifier($prockey) {
893 return x12clean(trim($this->procs[$prockey]['modifier']));
896 // Returns the procedure code, followed by ":modifier" if there is one.
897 function cptKey($prockey) {
898 $tmp = $this->cptModifier($prockey);
899 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
902 function cptCharges($prockey) {
903 return x12clean(trim($this->procs[$prockey]['fee']));
906 function cptUnits($prockey) {
907 if (empty($this->procs[$prockey]['units'])) return '1';
908 return x12clean(trim($this->procs[$prockey]['units']));
911 // NDC drug ID.
912 function cptNDCID($prockey) {
913 $ndcinfo = $this->procs[$prockey]['ndc_info'];
914 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
915 $ndc = $tmp[1];
916 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
917 return sprintf('%05d-%04d-%02d', $tmp[1], $tmp[2], $tmp[3]);
919 return x12clean($ndc); // format is bad but return it anyway
921 return '';
924 // NDC drug unit of measure code.
925 function cptNDCUOM($prockey) {
926 $ndcinfo = $this->procs[$prockey]['ndc_info'];
927 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
928 return x12clean($tmp[2]);
929 return '';
932 // NDC drug number of units.
933 function cptNDCQuantity($prockey) {
934 $ndcinfo = $this->procs[$prockey]['ndc_info'];
935 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
936 return x12clean(ltrim($tmp[3], '0'));
938 return '';
941 function onsetDate() {
942 return str_replace('-', '', substr($this->encounter['onset_date'], 0, 10));
945 function serviceDate() {
946 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
949 function priorAuth() {
950 return x12clean(trim($this->billing_options['prior_auth_number']));
953 function isRelatedEmployment() {
954 return !empty($this->billing_options['employment_related']);
957 function isRelatedAuto() {
958 return !empty($this->billing_options['auto_accident']);
961 function isRelatedOther() {
962 return !empty($this->billing_options['other_accident']);
965 function autoAccidentState() {
966 return x12clean(trim($this->billing_options['accident_state']));
969 function isUnableToWork() {
970 return !empty($this->billing_options['is_unable_to_work']);
973 function offWorkFrom() {
974 return str_replace('-', '', substr($this->billing_options['off_work_from'], 0, 10));
977 function offWorkTo() {
978 return str_replace('-', '', substr($this->billing_options['off_work_to'], 0, 10));
981 function isHospitalized() {
982 return !empty($this->billing_options['is_hospitalized']);
985 function hospitalizedFrom() {
986 return str_replace('-', '', substr($this->billing_options['hospitalization_date_from'], 0, 10));
989 function hospitalizedTo() {
990 return str_replace('-', '', substr($this->billing_options['hospitalization_date_to'], 0, 10));
993 function isOutsideLab() {
994 return !empty($this->billing_options['outside_lab']);
997 function outsideLabAmount() {
998 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
1001 function medicaidResubmissionCode() {
1002 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
1005 function medicaidOriginalReference() {
1006 return x12clean(trim($this->billing_options['medicaid_original_reference']));
1009 function frequencyTypeCode() {
1010 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
1013 function additionalNotes() {
1014 return x12clean(trim($this->billing_options['comments']));
1017 // Returns an array of unique diagnoses. Periods are stripped.
1018 function diagArray() {
1019 $da = array();
1020 foreach ($this->procs as $row) {
1021 $atmp = explode(':', $row['justify']);
1022 foreach ($atmp as $tmp) {
1023 if (!empty($tmp)) {
1024 $diag = str_replace('.', '', $tmp);
1025 $da[$diag] = $diag;
1029 // The above got all the diagnoses used for justification, in the order
1030 // used for justification. Next we go through all diagnoses, justified
1031 // or not, to make sure they all get into the claim. We do it this way
1032 // so that the more important diagnoses appear first.
1033 foreach ($this->diags as $diag) {
1034 $diag = str_replace('.', '', $diag);
1035 $da[$diag] = $diag;
1037 return $da;
1040 // Compute one 1-relative index in diagArray for the given procedure.
1041 // This function is obsolete, use diagIndexArray() instead.
1042 function diagIndex($prockey) {
1043 $da = $this->diagArray();
1044 $tmp = explode(':', $this->procs[$prockey]['justify']);
1045 if (empty($tmp)) return '';
1046 $diag = str_replace('.', '', $tmp[0]);
1047 $i = 0;
1048 foreach ($da as $value) {
1049 ++$i;
1050 if (strcmp($value,$diag) == 0) return $i;
1052 return '';
1055 // Compute array of 1-relative diagArray indices for the given procedure.
1056 function diagIndexArray($prockey) {
1057 $dia = array();
1058 $da = $this->diagArray();
1059 $atmp = explode(':', $this->procs[$prockey]['justify']);
1060 foreach ($atmp as $tmp) {
1061 if (!empty($tmp)) {
1062 $diag = str_replace('.', '', $tmp);
1063 $i = 0;
1064 foreach ($da as $value) {
1065 ++$i;
1066 if (strcmp($value,$diag) == 0) $dia[] = $i;
1070 return $dia;
1073 function providerLastName($prockey=-1) {
1074 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1075 $this->provider : $this->procs[$prockey]['provider'];
1076 return x12clean(trim($tmp['lname']));
1079 function providerFirstName($prockey=-1) {
1080 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1081 $this->provider : $this->procs[$prockey]['provider'];
1082 return x12clean(trim($tmp['fname']));
1085 function providerMiddleName($prockey=-1) {
1086 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1087 $this->provider : $this->procs[$prockey]['provider'];
1088 return x12clean(trim($tmp['mname']));
1091 function providerNPI($prockey=-1) {
1092 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1093 $this->provider : $this->procs[$prockey]['provider'];
1094 return x12clean(trim($tmp['npi']));
1097 function providerUPIN($prockey=-1) {
1098 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1099 $this->provider : $this->procs[$prockey]['provider'];
1100 return x12clean(trim($tmp['upin']));
1103 function providerSSN($prockey=-1) {
1104 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1105 $this->provider : $this->procs[$prockey]['provider'];
1106 return x12clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1109 function providerTaxonomy($prockey=-1) {
1110 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1111 $this->provider : $this->procs[$prockey]['provider'];
1112 if (empty($tmp['taxonomy'])) return '207Q00000X';
1113 return x12clean(trim($tmp['taxonomy']));
1116 function referrerLastName() {
1117 return x12clean(trim($this->referrer['lname']));
1120 function referrerFirstName() {
1121 return x12clean(trim($this->referrer['fname']));
1124 function referrerMiddleName() {
1125 return x12clean(trim($this->referrer['mname']));
1128 function referrerNPI() {
1129 return x12clean(trim($this->referrer['npi']));
1132 function referrerUPIN() {
1133 return x12clean(trim($this->referrer['upin']));
1136 function referrerSSN() {
1137 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
1140 function referrerTaxonomy() {
1141 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1142 return x12clean(trim($this->referrer['taxonomy']));
1145 function supervisorLastName() {
1146 return x12clean(trim($this->supervisor['lname']));
1149 function supervisorFirstName() {
1150 return x12clean(trim($this->supervisor['fname']));
1153 function supervisorMiddleName() {
1154 return x12clean(trim($this->supervisor['mname']));
1157 function supervisorNPI() {
1158 return x12clean(trim($this->supervisor['npi']));
1161 function supervisorUPIN() {
1162 return x12clean(trim($this->supervisor['upin']));
1165 function supervisorSSN() {
1166 return x12clean(trim(str_replace('-', '', $this->supervisor['federaltaxid'])));
1169 function supervisorTaxonomy() {
1170 if (empty($this->supervisor['taxonomy'])) return '207Q00000X';
1171 return x12clean(trim($this->supervisor['taxonomy']));
1174 function supervisorNumberType() {
1175 return $this->supervisor_numbers['provider_number_type'];
1178 function supervisorNumber() {
1179 return x12clean(trim(str_replace('-', '', $this->supervisor_numbers['provider_number'])));