Added Polish language
[openemr.git] / library / Claim.class.php
blobfcc2cf0ebc98ef6eda17940ca15cc51335792832
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 function federalIdType() {
547 if ($this->billing_facility['tax_id_type'])
549 return $this->billing_facility['tax_id_type'];
551 else{
552 return null;
556 # The billing facility and the patient must both accept for this to return true.
557 function billingFacilityAssignment($ins=0) {
558 $tmp = strtoupper($this->payers[$ins]['data']['accept_assignment']);
559 if (strcmp($tmp,'FALSE') == 0) return '0';
560 return !empty($this->billing_facility['accepts_assignment']);
563 function billingContactName() {
564 return x12clean(trim($this->billing_facility['attn']));
567 function billingContactPhone() {
568 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
569 $this->billing_facility['phone'], $tmp))
571 return $tmp[1] . $tmp[2] . $tmp[3];
573 return '';
576 function facilityName() {
577 return x12clean(trim($this->facility['name']));
580 function facilityStreet() {
581 return x12clean(trim($this->facility['street']));
584 function facilityCity() {
585 return x12clean(trim($this->facility['city']));
588 function facilityState() {
589 return x12clean(trim($this->facility['state']));
592 function facilityZip() {
593 return x12clean(trim($this->facility['postal_code']));
596 function facilityETIN() {
597 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
600 function facilityNPI() {
601 return x12clean(trim($this->facility['facility_npi']));
604 function facilityPOS() {
605 return x12clean(trim($this->facility['pos_code']));
608 function clearingHouseName() {
609 return x12clean(trim($this->x12_partner['name']));
612 function clearingHouseETIN() {
613 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
616 function providerNumberType($prockey=-1) {
617 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
618 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
619 return $tmp['provider_number_type'];
622 function providerNumber($prockey=-1) {
623 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
624 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
625 return x12clean(trim(str_replace('-', '', $tmp['provider_number'])));
628 function providerGroupNumber($prockey=-1) {
629 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
630 $this->insurance_numbers : $this->procs[$prockey]['insurance_numbers'];
631 return x12clean(trim(str_replace('-', '', $tmp['group_number'])));
634 // Returns 'P', 'S' or 'T'.
636 function payerSequence($ins=0) {
637 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
640 // Returns the HIPAA code of the patient-to-subscriber relationship.
642 function insuredRelationship($ins=0) {
643 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
644 if (strcmp($tmp,'self' ) == 0) return '18';
645 if (strcmp($tmp,'spouse') == 0) return '01';
646 if (strcmp($tmp,'child' ) == 0) return '19';
647 if (strcmp($tmp,'other' ) == 0) return 'G8';
648 return $tmp; // should not happen
651 function insuredTypeCode($ins=0) {
652 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
653 return '12'; // medicare secondary working aged beneficiary or
654 // spouse with employer group health plan
655 return '';
658 // Is the patient also the subscriber?
660 function isSelfOfInsured($ins=0) {
661 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
662 return (strcmp($tmp,'self') == 0);
665 function planName($ins=0) {
666 return x12clean(trim($this->payers[$ins]['data']['plan_name']));
669 function policyNumber($ins=0) { // "ID"
670 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
673 function groupNumber($ins=0) {
674 return x12clean(trim($this->payers[$ins]['data']['group_number']));
677 function groupName($ins=0) {
678 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
681 // Claim types are:
682 // 16 Other HCFA
683 // MB Medicare Part B
684 // MC Medicaid
685 // CH ChampUSVA
686 // CH ChampUS
687 // BL Blue Cross Blue Shield
688 // 16 FECA
689 // 09 Self Pay
690 // 10 Central Certification
691 // 11 Other Non-Federal Programs
692 // 12 Preferred Provider Organization (PPO)
693 // 13 Point of Service (POS)
694 // 14 Exclusive Provider Organization (EPO)
695 // 15 Indemnity Insurance
696 // 16 Health Maintenance Organization (HMO) Medicare Risk
697 // AM Automobile Medical
698 // CI Commercial Insurance Co.
699 // DS Disability
700 // HM Health Maintenance Organization
701 // LI Liability
702 // LM Liability Medical
703 // OF Other Federal Program
704 // TV Title V
705 // VA Veterans Administration Plan
706 // WC Workers Compensation Health Plan
707 // ZZ Mutually Defined
709 function claimType($ins=0) {
710 if (empty($this->payers[$ins]['object'])) return '';
711 return $this->payers[$ins]['object']->get_freeb_claim_type();
714 function insuredLastName($ins=0) {
715 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
718 function insuredFirstName($ins=0) {
719 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
722 function insuredMiddleName($ins=0) {
723 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
726 function insuredStreet($ins=0) {
727 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
730 function insuredCity($ins=0) {
731 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
734 function insuredState($ins=0) {
735 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
738 function insuredZip($ins=0) {
739 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
742 function insuredPhone($ins=0) {
743 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
744 $this->payers[$ins]['data']['subscriber_phone'], $tmp))
745 return $tmp[1] . $tmp[2] . $tmp[3];
746 return '';
749 function insuredDOB($ins=0) {
750 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
753 function insuredSex($ins=0) {
754 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
757 function payerName($ins=0) {
758 return x12clean(trim($this->payers[$ins]['company']['name']));
761 function payerAttn($ins=0) {
762 return x12clean(trim($this->payers[$ins]['company']['attn']));
765 function payerStreet($ins=0) {
766 if (empty($this->payers[$ins]['object'])) return '';
767 $tmp = $this->payers[$ins]['object'];
768 $tmp = $tmp->get_address();
769 return x12clean(trim($tmp->get_line1()));
772 function payerCity($ins=0) {
773 if (empty($this->payers[$ins]['object'])) return '';
774 $tmp = $this->payers[$ins]['object'];
775 $tmp = $tmp->get_address();
776 return x12clean(trim($tmp->get_city()));
779 function payerState($ins=0) {
780 if (empty($this->payers[$ins]['object'])) return '';
781 $tmp = $this->payers[$ins]['object'];
782 $tmp = $tmp->get_address();
783 return x12clean(trim($tmp->get_state()));
786 function payerZip($ins=0) {
787 if (empty($this->payers[$ins]['object'])) return '';
788 $tmp = $this->payers[$ins]['object'];
789 $tmp = $tmp->get_address();
790 return x12clean(trim($tmp->get_zip()));
793 function payerID($ins=0) {
794 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
797 function payerAltID($ins=0) {
798 return x12clean(trim($this->payers[$ins]['company']['alt_cms_id']));
801 function patientLastName() {
802 return x12clean(trim($this->patient_data['lname']));
805 function patientFirstName() {
806 return x12clean(trim($this->patient_data['fname']));
809 function patientMiddleName() {
810 return x12clean(trim($this->patient_data['mname']));
813 function patientStreet() {
814 return x12clean(trim($this->patient_data['street']));
817 function patientCity() {
818 return x12clean(trim($this->patient_data['city']));
821 function patientState() {
822 return x12clean(trim($this->patient_data['state']));
825 function patientZip() {
826 return x12clean(trim($this->patient_data['postal_code']));
829 function patientPhone() {
830 $ptphone = $this->patient_data['phone_home'];
831 if (!$ptphone) $ptphone = $this->patient_data['phone_biz'];
832 if (!$ptphone) $ptphone = $this->patient_data['phone_cell'];
833 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp))
834 return $tmp[1] . $tmp[2] . $tmp[3];
835 return '';
838 function patientDOB() {
839 return str_replace('-', '', $this->patient_data['DOB']);
842 function patientSex() {
843 return strtoupper(substr($this->patient_data['sex'], 0, 1));
846 // Patient Marital Status: M = Married, S = Single, or something else.
847 function patientStatus() {
848 return strtoupper(substr($this->patient_data['status'], 0, 1));
851 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
852 // indicate employed.
853 function patientOccupation() {
854 return strtoupper(x12clean(trim($this->patient_data['occupation'])));
857 function cptCode($prockey) {
858 return x12clean(trim($this->procs[$prockey]['code']));
861 function cptModifier($prockey) {
862 return x12clean(trim($this->procs[$prockey]['modifier']));
865 // Returns the procedure code, followed by ":modifier" if there is one.
866 function cptKey($prockey) {
867 $tmp = $this->cptModifier($prockey);
868 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
871 function cptCharges($prockey) {
872 return x12clean(trim($this->procs[$prockey]['fee']));
875 function cptUnits($prockey) {
876 if (empty($this->procs[$prockey]['units'])) return '1';
877 return x12clean(trim($this->procs[$prockey]['units']));
880 // NDC drug ID.
881 function cptNDCID($prockey) {
882 $ndcinfo = $this->procs[$prockey]['ndc_info'];
883 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
884 $ndc = $tmp[1];
885 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
886 return sprintf('%05d-%04d-%02d', $tmp[1], $tmp[2], $tmp[3]);
888 return x12clean($ndc); // format is bad but return it anyway
890 return '';
893 // NDC drug unit of measure code.
894 function cptNDCUOM($prockey) {
895 $ndcinfo = $this->procs[$prockey]['ndc_info'];
896 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
897 return x12clean($tmp[2]);
898 return '';
901 // NDC drug number of units.
902 function cptNDCQuantity($prockey) {
903 $ndcinfo = $this->procs[$prockey]['ndc_info'];
904 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
905 return x12clean(ltrim($tmp[3], '0'));
907 return '';
910 function onsetDate() {
911 return str_replace('-', '', substr($this->encounter['onset_date'], 0, 10));
914 function serviceDate() {
915 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
918 function priorAuth() {
919 return x12clean(trim($this->billing_options['prior_auth_number']));
922 function isRelatedEmployment() {
923 return !empty($this->billing_options['employment_related']);
926 function isRelatedAuto() {
927 return !empty($this->billing_options['auto_accident']);
930 function isRelatedOther() {
931 return !empty($this->billing_options['other_accident']);
934 function autoAccidentState() {
935 return x12clean(trim($this->billing_options['accident_state']));
938 function isUnableToWork() {
939 return !empty($this->billing_options['is_unable_to_work']);
942 function offWorkFrom() {
943 return str_replace('-', '', substr($this->billing_options['off_work_from'], 0, 10));
946 function offWorkTo() {
947 return str_replace('-', '', substr($this->billing_options['off_work_to'], 0, 10));
950 function isHospitalized() {
951 return !empty($this->billing_options['is_hospitalized']);
954 function hospitalizedFrom() {
955 return str_replace('-', '', substr($this->billing_options['hospitalization_date_from'], 0, 10));
958 function hospitalizedTo() {
959 return str_replace('-', '', substr($this->billing_options['hospitalization_date_to'], 0, 10));
962 function isOutsideLab() {
963 return !empty($this->billing_options['outside_lab']);
966 function outsideLabAmount() {
967 return sprintf('%.2f', 0 + $this->billing_options['lab_amount']);
970 function medicaidResubmissionCode() {
971 return x12clean(trim($this->billing_options['medicaid_resubmission_code']));
974 function medicaidOriginalReference() {
975 return x12clean(trim($this->billing_options['medicaid_original_reference']));
978 function frequencyTypeCode() {
979 return empty($this->billing_options['replacement_claim']) ? '1' : '7';
982 function additionalNotes() {
983 return x12clean(trim($this->billing_options['comments']));
986 // Returns an array of unique diagnoses. Periods are stripped.
987 function diagArray() {
988 $da = array();
989 foreach ($this->procs as $row) {
990 $atmp = explode(':', $row['justify']);
991 foreach ($atmp as $tmp) {
992 if (!empty($tmp)) {
993 $diag = str_replace('.', '', $tmp);
994 $da[$diag] = $diag;
998 // The above got all the diagnoses used for justification, in the order
999 // used for justification. Next we go through all diagnoses, justified
1000 // or not, to make sure they all get into the claim. We do it this way
1001 // so that the more important diagnoses appear first.
1002 foreach ($this->diags as $diag) {
1003 $diag = str_replace('.', '', $diag);
1004 $da[$diag] = $diag;
1006 return $da;
1009 // Compute one 1-relative index in diagArray for the given procedure.
1010 // This function is obsolete, use diagIndexArray() instead.
1011 function diagIndex($prockey) {
1012 $da = $this->diagArray();
1013 $tmp = explode(':', $this->procs[$prockey]['justify']);
1014 if (empty($tmp)) return '';
1015 $diag = str_replace('.', '', $tmp[0]);
1016 $i = 0;
1017 foreach ($da as $value) {
1018 ++$i;
1019 if (strcmp($value,$diag) == 0) return $i;
1021 return '';
1024 // Compute array of 1-relative diagArray indices for the given procedure.
1025 function diagIndexArray($prockey) {
1026 $dia = array();
1027 $da = $this->diagArray();
1028 $atmp = explode(':', $this->procs[$prockey]['justify']);
1029 foreach ($atmp as $tmp) {
1030 if (!empty($tmp)) {
1031 $diag = str_replace('.', '', $tmp);
1032 $i = 0;
1033 foreach ($da as $value) {
1034 ++$i;
1035 if (strcmp($value,$diag) == 0) $dia[] = $i;
1039 return $dia;
1042 function providerLastName($prockey=-1) {
1043 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1044 $this->provider : $this->procs[$prockey]['provider'];
1045 return x12clean(trim($tmp['lname']));
1048 function providerFirstName($prockey=-1) {
1049 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1050 $this->provider : $this->procs[$prockey]['provider'];
1051 return x12clean(trim($tmp['fname']));
1054 function providerMiddleName($prockey=-1) {
1055 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1056 $this->provider : $this->procs[$prockey]['provider'];
1057 return x12clean(trim($tmp['mname']));
1060 function providerNPI($prockey=-1) {
1061 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1062 $this->provider : $this->procs[$prockey]['provider'];
1063 return x12clean(trim($tmp['npi']));
1066 function providerUPIN($prockey=-1) {
1067 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1068 $this->provider : $this->procs[$prockey]['provider'];
1069 return x12clean(trim($tmp['upin']));
1072 function providerSSN($prockey=-1) {
1073 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1074 $this->provider : $this->procs[$prockey]['provider'];
1075 return x12clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1078 function providerTaxonomy($prockey=-1) {
1079 $tmp = ($prockey < 0 || empty($this->procs[$prockey]['provider_id'])) ?
1080 $this->provider : $this->procs[$prockey]['provider'];
1081 if (empty($tmp['taxonomy'])) return '207Q00000X';
1082 return x12clean(trim($tmp['taxonomy']));
1085 function referrerLastName() {
1086 return x12clean(trim($this->referrer['lname']));
1089 function referrerFirstName() {
1090 return x12clean(trim($this->referrer['fname']));
1093 function referrerMiddleName() {
1094 return x12clean(trim($this->referrer['mname']));
1097 function referrerNPI() {
1098 return x12clean(trim($this->referrer['npi']));
1101 function referrerUPIN() {
1102 return x12clean(trim($this->referrer['upin']));
1105 function referrerSSN() {
1106 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));
1109 function referrerTaxonomy() {
1110 if (empty($this->referrer['taxonomy'])) return '207Q00000X';
1111 return x12clean(trim($this->referrer['taxonomy']));
1114 function supervisorLastName() {
1115 return x12clean(trim($this->supervisor['lname']));
1118 function supervisorFirstName() {
1119 return x12clean(trim($this->supervisor['fname']));
1122 function supervisorMiddleName() {
1123 return x12clean(trim($this->supervisor['mname']));
1126 function supervisorNPI() {
1127 return x12clean(trim($this->supervisor['npi']));
1130 function supervisorUPIN() {
1131 return x12clean(trim($this->supervisor['upin']));
1134 function supervisorSSN() {
1135 return x12clean(trim(str_replace('-', '', $this->supervisor['federaltaxid'])));
1138 function supervisorTaxonomy() {
1139 if (empty($this->supervisor['taxonomy'])) return '207Q00000X';
1140 return x12clean(trim($this->supervisor['taxonomy']));
1143 function supervisorNumberType() {
1144 return $this->supervisor_numbers['provider_number_type'];
1147 function supervisorNumber() {
1148 return x12clean(trim(str_replace('-', '', $this->supervisor_numbers['provider_number'])));