assorted bug fixes
[openemr.git] / library / Claim.class.php
blob66d4e566410cd6ae2c9a0aec8d7214995ca9106c
1 <?php
2 // Copyright (C) 2007 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 $x12_partner; // row from x12_partners table
26 var $encounter; // row from form_encounter table
27 var $facility; // row from facility table
28 var $billing_facility; // row from facility table
29 var $provider; // row from users table (rendering provider)
30 var $referrer; // row from users table (referring provider)
31 var $insurance_numbers; // row from insurance_numbers table for current payer
32 var $patient_data; // row from patient_data table
33 var $billing_options; // row from form_misc_billing_options table
34 var $invoice; // result from get_invoice_summary()
35 var $payers; // array of arrays, for all payers
37 function loadPayerInfo(&$billrow) {
38 global $sl_err;
39 $encounter_date = substr($this->encounter['date'], 0, 10);
41 // Create the $payers array. This contains data for all insurances
42 // with the current one always at index 0, and the others in payment
43 // order starting at index 1.
45 $this->payers = array();
46 $this->payers[0] = array();
47 $query = "SELECT * FROM insurance_data WHERE " .
48 "pid = '{$this->pid}' AND provider != '' AND " .
49 "date <= '$encounter_date' " .
50 "ORDER BY type ASC, date DESC";
51 $dres = sqlStatement($query);
52 $prevtype = '';
53 while ($drow = sqlFetchArray($dres)) {
54 if (strcmp($prevtype, $drow['type']) == 0) continue;
55 $prevtype = $drow['type'];
56 $ins = count($this->payers);
57 if ($drow['provider'] == $billrow['payer_id'] && empty($this->payers[0]['data'])) $ins = 0;
58 $crow = sqlQuery("SELECT * FROM insurance_companies WHERE " .
59 "id = '" . $drow['provider'] . "'");
60 $orow = new InsuranceCompany($drow['provider']);
61 $this->payers[$ins] = array();
62 $this->payers[$ins]['data'] = $drow;
63 $this->payers[$ins]['company'] = $crow;
64 $this->payers[$ins]['object'] = $orow;
67 // This kludge hands most cases of a rare ambiguous situation, where
68 // the primary insurance company is the same as the secondary. It seems
69 // nobody planned for that!
71 for ($i = 1; $i < count($this->payers); ++$i) {
72 if ($billrow['process_date'] &&
73 $this->payers[0]['data']['payer_id'] == $this->payers[$i]['data']['payer_id'])
75 $tmp = $this->payers[0];
76 $this->payers[0] = $this->payers[$i];
77 $this->payers[$i] = $tmp;
81 $this->using_modifiers = true;
83 // Get payment and adjustment details if there are any previous payers.
85 $this->invoice = array();
86 if ($this->payerSequence() != 'P') {
87 SLConnect();
88 $arres = SLQuery("select id from ar where invnumber = " .
89 "'{$this->pid}.{$this->encounter_id}'");
90 if ($sl_err) die($sl_err);
91 $arrow = SLGetRow($arres, 0);
92 if ($arrow) {
93 $this->invoice = get_invoice_summary($arrow['id'], true);
95 SLClose();
96 // Secondary claims might not have modifiers in SQL-Ledger data.
97 // In that case, note that we should not try to match on them.
98 $this->using_modifiers = false;
99 foreach ($this->invoice as $key => $trash) {
100 if (strpos($key, ':')) $this->using_modifiers = true;
105 // Constructor. Loads relevant database information.
107 function Claim($pid, $encounter_id) {
108 $this->pid = $pid;
109 $this->encounter_id = $encounter_id;
110 $this->procs = array();
112 // We need the encounter date before we can identify the payers.
113 $sql = "SELECT * FROM form_encounter WHERE " .
114 "pid = '{$this->pid}' AND " .
115 "encounter = '{$this->encounter_id}'";
116 $this->encounter = sqlQuery($sql);
118 // Sort by procedure timestamp in order to get some consistency. In particular
119 // we determine the provider from the first procedure in this array.
120 $sql = "SELECT * FROM billing WHERE " .
121 "encounter = '{$this->encounter_id}' AND pid = '{$this->pid}' AND " .
122 "(code_type = 'CPT4' OR code_type = 'HCPCS') AND " .
123 "activity = '1' ORDER BY date, id";
124 $res = sqlStatement($sql);
125 while ($row = sqlFetchArray($res)) {
126 if (!$row['units']) $row['units'] = 1;
127 // Load prior payer data at the first opportunity in order to get
128 // the using_modifiers flag that is referenced below.
129 if (empty($this->procs)) $this->loadPayerInfo($row);
130 // Consolidate duplicate procedures.
131 foreach ($this->procs as $key => $trash) {
132 if (strcmp($this->procs[$key]['code'],$row['code']) == 0 &&
133 (strcmp($this->procs[$key]['modifier'],$row['modifier']) == 0 ||
134 !$this->using_modifiers))
136 $this->procs[$key]['units'] += $row['units'];
137 $this->procs[$key]['fee'] += $row['fee'];
138 continue 2; // skip to next table row
141 $this->procs[] = $row;
144 $sql = "SELECT * FROM x12_partners WHERE " .
145 "id = '" . $this->procs[0]['x12_partner_id'] . "'";
146 $this->x12_partner = sqlQuery($sql);
148 $sql = "SELECT * FROM facility WHERE " .
149 "name = '" . addslashes($this->encounter['facility']) . "' " .
150 "ORDER BY id LIMIT 1";
151 $this->facility = sqlQuery($sql);
153 $sql = "SELECT * FROM users WHERE " .
154 "id = '" . $this->procs[0]['provider_id'] . "'";
155 $this->provider = sqlQuery($sql);
157 $sql = "SELECT * FROM facility " .
158 "ORDER BY billing_location DESC, id ASC LIMIT 1";
159 $this->billing_facility = sqlQuery($sql);
161 $sql = "SELECT * FROM insurance_numbers WHERE " .
162 "(insurance_company_id = '" . $this->procs[0]['payer_id'] .
163 "' OR insurance_company_id is NULL) AND " .
164 "provider_id = '" . $this->provider['id'] .
165 "' order by insurance_company_id DESC LIMIT 1";
166 $this->insurance_numbers = sqlQuery($sql);
168 $sql = "SELECT * FROM patient_data WHERE " .
169 "pid = '{$this->pid}' " .
170 "ORDER BY id LIMIT 1";
171 $this->patient_data = sqlQuery($sql);
173 $sql = "SELECT fpa.* FROM forms JOIN form_misc_billing_options AS fpa " .
174 "ON fpa.id = forms.form_id WHERE " .
175 "forms.encounter = '{$this->encounter_id}' AND " .
176 "forms.pid = '{$this->pid}' AND " .
177 "forms.formdir = 'misc_billing_options' " .
178 "ORDER BY forms.date";
179 $this->billing_options = sqlQuery($sql);
181 $sql = "SELECT * FROM users WHERE " .
182 "id = '" . $this->patient_data['providerID'] . "'";
183 $this->referrer = sqlQuery($sql);
184 if (!$this->referrer) $this->referrer = array();
186 } // end constructor
188 // Return an array of adjustments from the designated prior payer for the
189 // designated procedure key (might be procedure:modifier), or for the claim
190 // level. For each adjustment give date, group code, reason code, amount.
191 // Note this will include "patient responsibility" adjustments which are
192 // not adjustments to OUR invoice, but they reduce the amount that the
193 // insurance company pays.
195 function payerAdjustments($ins, $code='Claim') {
196 $aadj = array();
198 // If we have no modifiers stored in SQL-Ledger for this claim,
199 // then we cannot use a modifier passed in with the key.
200 $tmp = strpos($code, ':');
201 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
203 // For payments, source always starts with "Ins" or "Pt".
204 // Nonzero adjustment reason examples:
205 // Ins1 adjust code 42 (Charges exceed ... (obsolete))
206 // Ins1 adjust code 45 (Charges exceed your contracted/ legislated fee arrangement)
207 // Ins1 adjust code 97 (Payment is included in the allowance for another service/procedure)
208 // Ins1 adjust code A2 (Contractual adjustment)
209 // Ins adjust Ins1
210 // adjust code 45
211 // Zero adjustment reason examples:
212 // Co-pay: 25.00
213 // Coinsurance: 11.46 (code 2) Note: fix remits to identify insurance
214 // To deductible: 0.22 (code 1) Note: fix remits to identify insurance
215 // To copay Ins1 (manual entry)
216 // To ded'ble Ins1 (manual entry)
218 if (!empty($this->invoice[$code])) {
219 $date = '';
220 $deductible = 0;
221 $coinsurance = 0;
222 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
223 $insnumber = substr($inslabel, 3);
225 // Compute this procedure's patient responsibility amount as of this
226 // prior payer, which is the original charge minus all insurance
227 // payments and "hard" adjustments up to this payer.
228 $ptresp = $this->invoice[$code]['chg'] + $this->invoice[$code]['adj'];
229 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
230 if (preg_match("/^Ins(\d)/i", $value['src'], $tmp)) {
231 if ($tmp[1] <= $insnumber) $ptresp -= $value['pmt'];
233 else if (trim(substr($key, 0, 10))) { // not an adjustment if no date
234 if (!preg_match("/Ins(\d)/i", $value['rsn'], $tmp) || $tmp[1] <= $insnumber)
235 $ptresp += $value['chg']; // adjustments are negative charges
238 if ($ptresp < 0) $ptresp = 0; // we may be insane but try to hide it
240 // Main loop, to extract adjustments for this payer and procedure.
241 foreach ($this->invoice[$code]['dtl'] as $key => $value) {
242 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
243 if ($tmp) $date = $tmp;
244 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
245 $rsn = $value['rsn'];
246 $chg = 0 - $value['chg']; // adjustments are negative charges
248 $gcode = 'CO'; // default group code = contractual obligation
249 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
251 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
252 // From manual post. Take the defaults.
254 else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
255 $coinsurance = $ptresp; // from manual post
256 continue;
258 else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
259 $deductible = $ptresp; // from manual post
260 continue;
262 else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
263 $coinsurance = $tmp[1]; // from 835 as of 6/2007
264 continue;
266 else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
267 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
268 continue;
270 else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
271 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
272 continue;
274 else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
275 continue; // from 835 as of 6/2007
277 else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
278 $rcode = $tmp[1]; // from 835
280 else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
281 // Take the defaults.
283 else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
284 continue; // it's for some other payer
286 else if ($insnumber == '1') {
287 if (preg_match("/\$\s*adjust code (\S+)/i", $rsn, $tmp)) {
288 $rcode = $tmp[1]; // from 835
290 else if ($chg) {
291 // Other adjustments default to Ins1.
293 else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
294 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
295 $coinsurance = 0 + $tmp[1]; // from 835 before 6/2007
296 continue;
298 else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
299 $deductible = 0 + $tmp[1]; // from 835 before 6/2007
300 continue;
302 else {
303 continue; // there is no adjustment amount
306 else {
307 continue; // it's for primary and that's not us
310 if ($rcode == '42') $rcode= '45'; // reason 42 is obsolete
311 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
313 } // end if
314 } // end foreach
316 // If we really messed it up, at least avoid negative numbers.
317 if ($coinsurance > $ptresp) $coinsurance = $ptresp;
318 if ($deductible > $ptresp) $deductible = $ptresp;
320 // Find out if this payer paid anything at all on this claim. This will
321 // help us allocate any unknown patient responsibility amounts.
322 $thispaidanything = 0;
323 foreach($this->invoice as $codekey => $codeval) {
324 foreach ($codeval['dtl'] as $key => $value) {
325 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
326 $thispaidanything += $value['pmt'];
331 // Allocate any unknown patient responsibility by guessing if the
332 // deductible has been satisfied.
333 if ($thispaidanything)
334 $coinsurance = $ptresp - $deductible;
335 else
336 $deductible = $ptresp - $coinsurance;
338 if ($date && $deductible != 0)
339 $aadj[] = array($date, 'PR', '1', sprintf('%.2f', $deductible));
340 if ($date && $coinsurance != 0)
341 $aadj[] = array($date, 'PR', '2', sprintf('%.2f', $coinsurance));
343 } // end if
345 return $aadj;
348 // Return date, total payments and total "hard" adjustments from the given
349 // prior payer. If $code is specified then only that procedure key is
350 // selected, otherwise it's for the whole claim.
352 function payerTotals($ins, $code='') {
353 // If we have no modifiers stored in SQL-Ledger for this claim,
354 // then we cannot use a modifier passed in with the key.
355 $tmp = strpos($code, ':');
356 if ($tmp && !$this->using_modifiers) $code = substr($code, 0, $tmp);
358 $inslabel = ($this->payerSequence($ins) == 'S') ? 'Ins2' : 'Ins1';
359 $paytotal = 0;
360 $adjtotal = 0;
361 $date = '';
362 foreach($this->invoice as $codekey => $codeval) {
363 if ($code && strcmp($codekey,$code) != 0) continue;
364 foreach ($codeval['dtl'] as $key => $value) {
365 if (preg_match("/$inslabel/i", $value['src'], $tmp)) {
366 if (!$date) $date = str_replace('-', '', trim(substr($key, 0, 10)));
367 $paytotal += $value['pmt'];
370 $aarr = $this->payerAdjustments($ins, $codekey);
371 foreach ($aarr as $a) {
372 if (strcmp($a[1],'PR') != 0) $adjtotal += $a[3];
373 if (!$date) $date = $a[0];
376 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
379 // Return the amount already paid by the patient.
381 function patientPaidAmount() {
383 // TBD: This does not work for a primary claim because $this->invoice
384 // is not loaded. Might be good to get the co-pay from the billing
385 // table in that case.
387 $amount = 0;
388 foreach($this->invoice as $codekey => $codeval) {
389 foreach ($codeval['dtl'] as $key => $value) {
390 if (!preg_match("/Ins/i", $value['src'], $tmp)) {
391 $amount += $value['pmt'];
395 return sprintf('%.2f', $amount);
398 // Return invoice total, including adjustments but not payments.
400 function invoiceTotal() {
401 $amount = 0;
402 foreach($this->invoice as $codekey => $codeval) {
403 $amount += $codeval['chg'];
405 return sprintf('%.2f', $amount);
408 // Number of procedures in this claim.
409 function procCount() {
410 return count($this->procs);
413 // Number of payers for this claim. Ranges from 1 to 3.
414 function payerCount() {
415 return count($this->payers);
418 function x12gsversionstring() {
419 return x12clean(trim($this->x12_partner['x12_version']));
422 function x12gssenderid() {
423 $tmp = $this->x12_partner['x12_sender_id'];
424 while (strlen($tmp) < 15) $tmp .= " ";
425 return $tmp;
428 function x12gsreceiverid() {
429 $tmp = $this->x12_partner['x12_receiver_id'];
430 while (strlen($tmp) < 15) $tmp .= " ";
431 return $tmp;
434 function cliaCode() {
435 return x12clean(trim($this->facility['domain_identifier']));
438 function billingFacilityName() {
439 return x12clean(trim($this->billing_facility['name']));
442 function billingFacilityStreet() {
443 return x12clean(trim($this->billing_facility['street']));
446 function billingFacilityCity() {
447 return x12clean(trim($this->billing_facility['city']));
450 function billingFacilityState() {
451 return x12clean(trim($this->billing_facility['state']));
454 function billingFacilityZip() {
455 return x12clean(trim($this->billing_facility['postal_code']));
458 function billingFacilityETIN() {
459 return x12clean(trim(str_replace('-', '', $this->billing_facility['federal_ein'])));
462 function billingFacilityNPI() {
463 return x12clean(trim($this->billing_facility['facility_npi']));
466 function billingContactName() {
467 return x12clean(trim($this->billing_facility['attn']));
470 function billingContactPhone() {
471 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
472 $this->billing_facility['phone'], $tmp))
474 return $tmp[1] . $tmp[2] . $tmp[3];
476 return '';
479 function facilityName() {
480 return x12clean(trim($this->facility['name']));
483 function facilityStreet() {
484 return x12clean(trim($this->facility['street']));
487 function facilityCity() {
488 return x12clean(trim($this->facility['city']));
491 function facilityState() {
492 return x12clean(trim($this->facility['state']));
495 function facilityZip() {
496 return x12clean(trim($this->facility['postal_code']));
499 function facilityETIN() {
500 return x12clean(trim(str_replace('-', '', $this->facility['federal_ein'])));
503 function facilityNPI() {
504 return x12clean(trim($this->facility['facility_npi']));
507 function facilityPOS() {
508 return x12clean(trim($this->facility['pos_code']));
511 function clearingHouseName() {
512 return x12clean(trim($this->x12_partner['name']));
515 function clearingHouseETIN() {
516 return x12clean(trim(str_replace('-', '', $this->x12_partner['id_number'])));
519 function providerNumberType() {
520 return $this->insurance_numbers['provider_number_type'];
523 function providerNumber() {
524 return x12clean(trim(str_replace('-', '', $this->insurance_numbers['provider_number'])));
527 // Returns 'P', 'S' or 'T'.
529 function payerSequence($ins=0) {
530 return strtoupper(substr($this->payers[$ins]['data']['type'], 0, 1));
533 // Returns the HIPAA code of the patient-to-subscriber relationship.
535 function insuredRelationship($ins=0) {
536 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
537 if (strcmp($tmp,'self' ) == 0) return '18';
538 if (strcmp($tmp,'spouse') == 0) return '01';
539 if (strcmp($tmp,'child' ) == 0) return '19';
540 if (strcmp($tmp,'other' ) == 0) return 'G8';
541 return $tmp; // should not happen
544 function insuredTypeCode($ins=0) {
545 if (strcmp($this->claimType($ins),'MB') == 0 && $this->payerSequence($ins) != 'P')
546 return '12'; // medicare secondary working aged beneficiary or
547 // spouse with employer group health plan
548 return '';
551 // Is the patient also the subscriber?
553 function isSelfOfInsured($ins=0) {
554 $tmp = strtolower($this->payers[$ins]['data']['subscriber_relationship']);
555 return (strcmp($tmp,'self') == 0);
558 function groupNumber($ins=0) {
559 return x12clean(trim($this->payers[$ins]['data']['group_number']));
562 function groupName($ins=0) {
563 return x12clean(trim($this->payers[$ins]['data']['subscriber_employer']));
566 function claimType($ins=0) {
567 if (empty($this->payers[$ins]['object'])) return '';
568 return $this->payers[$ins]['object']->get_freeb_claim_type();
571 function insuredLastName($ins=0) {
572 return x12clean(trim($this->payers[$ins]['data']['subscriber_lname']));
575 function insuredFirstName($ins=0) {
576 return x12clean(trim($this->payers[$ins]['data']['subscriber_fname']));
579 function insuredMiddleName($ins=0) {
580 return x12clean(trim($this->payers[$ins]['data']['subscriber_mname']));
583 function policyNumber($ins=0) { // "ID"
584 return x12clean(trim($this->payers[$ins]['data']['policy_number']));
587 function insuredStreet($ins=0) {
588 return x12clean(trim($this->payers[$ins]['data']['subscriber_street']));
591 function insuredCity($ins=0) {
592 return x12clean(trim($this->payers[$ins]['data']['subscriber_city']));
595 function insuredState($ins=0) {
596 return x12clean(trim($this->payers[$ins]['data']['subscriber_state']));
599 function insuredZip($ins=0) {
600 return x12clean(trim($this->payers[$ins]['data']['subscriber_postal_code']));
603 function insuredDOB($ins=0) {
604 return str_replace('-', '', $this->payers[$ins]['data']['subscriber_DOB']);
607 function insuredSex($ins=0) {
608 return strtoupper(substr($this->payers[$ins]['data']['subscriber_sex'], 0, 1));
611 function payerName($ins=0) {
612 return x12clean(trim($this->payers[$ins]['company']['name']));
615 function payerStreet($ins=0) {
616 if (empty($this->payers[$ins]['object'])) return '';
617 $tmp = $this->payers[$ins]['object'];
618 $tmp = $tmp->get_address();
619 return x12clean(trim($tmp->get_line1()));
622 function payerCity($ins=0) {
623 if (empty($this->payers[$ins]['object'])) return '';
624 $tmp = $this->payers[$ins]['object'];
625 $tmp = $tmp->get_address();
626 return x12clean(trim($tmp->get_city()));
629 function payerState($ins=0) {
630 if (empty($this->payers[$ins]['object'])) return '';
631 $tmp = $this->payers[$ins]['object'];
632 $tmp = $tmp->get_address();
633 return x12clean(trim($tmp->get_state()));
636 function payerZip($ins=0) {
637 if (empty($this->payers[$ins]['object'])) return '';
638 $tmp = $this->payers[$ins]['object'];
639 $tmp = $tmp->get_address();
640 return x12clean(trim($tmp->get_zip()));
643 function payerID($ins=0) {
644 return x12clean(trim($this->payers[$ins]['company']['cms_id']));
647 function patientLastName() {
648 return x12clean(trim($this->patient_data['lname']));
651 function patientFirstName() {
652 return x12clean(trim($this->patient_data['fname']));
655 function patientMiddleName() {
656 return x12clean(trim($this->patient_data['mname']));
659 function patientStreet() {
660 return x12clean(trim($this->patient_data['street']));
663 function patientCity() {
664 return x12clean(trim($this->patient_data['city']));
667 function patientState() {
668 return x12clean(trim($this->patient_data['state']));
671 function patientZip() {
672 return x12clean(trim($this->patient_data['postal_code']));
675 function patientDOB() {
676 return str_replace('-', '', $this->patient_data['DOB']);
679 function patientSex() {
680 return strtoupper(substr($this->patient_data['sex'], 0, 1));
683 function cptCode($prockey) {
684 return x12clean(trim($this->procs[$prockey]['code']));
687 function cptModifier($prockey) {
688 return x12clean(trim($this->procs[$prockey]['modifier']));
691 // Returns the procedure code, followed by ":modifier" if there is one.
692 function cptKey($prockey) {
693 $tmp = $this->cptModifier($prockey);
694 return $this->cptCode($prockey) . ($tmp ? ":$tmp" : "");
697 function cptCharges($prockey) {
698 return x12clean(trim($this->procs[$prockey]['fee']));
701 function cptUnits($prockey) {
702 if (empty($this->procs[$prockey]['units'])) return '1';
703 return x12clean(trim($this->procs[$prockey]['units']));
706 // NDC drug ID.
707 function cptNDCID($prockey) {
708 $ndcinfo = $this->procs[$prockey]['ndc_info'];
709 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
710 $ndc = $tmp[1];
711 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
712 return sprintf('%05d-%04d-%02d', $tmp[1], $tmp[2], $tmp[3]);
714 return x12clean($ndc); // format is bad but return it anyway
716 return '';
719 // NDC drug unit of measure code.
720 function cptNDCUOM($prockey) {
721 $ndcinfo = $this->procs[$prockey]['ndc_info'];
722 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp))
723 return x12clean($tmp[2]);
724 return '';
727 // NDC drug number of units.
728 function cptNDCQuantity($prockey) {
729 $ndcinfo = $this->procs[$prockey]['ndc_info'];
730 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
731 return x12clean(ltrim($tmp[3], '0'));
733 return '';
736 function onsetDate() {
737 return str_replace('-', '', substr($this->encounter['onset_date'], 0, 10));
740 function serviceDate() {
741 return str_replace('-', '', substr($this->encounter['date'], 0, 10));
744 function priorAuth() {
745 return x12clean(trim($this->billing_options['prior_auth_number']));
748 // Returns an array of unique primary diagnoses. Periods are stripped.
749 function diagArray() {
750 $da = array();
751 foreach ($this->procs as $row) {
752 $tmp = explode(':', $row['justify']);
753 if (count($tmp)) {
754 $diag = str_replace('.', '', $tmp[0]);
755 $da[$diag] = $diag;
758 return $da;
761 // Compute the 1-relative index in diagArray for the given procedure.
762 function diagIndex($prockey) {
763 $da = $this->diagArray();
764 $tmp = explode(':', $this->procs[$prockey]['justify']);
765 if (empty($tmp)) return '';
766 $diag = str_replace('.', '', $tmp[0]);
767 $i = 0;
768 foreach ($da as $value) {
769 ++$i;
770 if (strcmp($value,$diag) == 0) return $i;
772 return '';
775 function providerLastName() {
776 return x12clean(trim($this->provider['lname']));
779 function providerFirstName() {
780 return x12clean(trim($this->provider['fname']));
783 function providerMiddleName() {
784 return x12clean(trim($this->provider['mname']));
787 function providerNPI() {
788 return x12clean(trim($this->provider['npi']));
791 function providerUPIN() {
792 return x12clean(trim($this->provider['upin']));
795 function providerSSN() {
796 return x12clean(trim(str_replace('-', '', $this->provider['federaltaxid'])));
799 function referrerLastName() {
800 return x12clean(trim($this->referrer['lname']));
803 function referrerFirstName() {
804 return x12clean(trim($this->referrer['fname']));
807 function referrerMiddleName() {
808 return x12clean(trim($this->referrer['mname']));
811 function referrerNPI() {
812 return x12clean(trim($this->referrer['npi']));
815 function referrerUPIN() {
816 return x12clean(trim($this->referrer['upin']));
819 function referrerSSN() {
820 return x12clean(trim(str_replace('-', '', $this->referrer['federaltaxid'])));