5 * @author Rod Roark <rod@sunsetsystems.com>
6 * @author Stephen Waite <stephen.waite@cmsvt.com>
7 * @copyright Copyright (c) 2009 Rod Roark <rod@sunsetsystems.com>
8 * @copyright Copyright (c) 2017 Stephen Waite <stephen.waite@cmsvt.com>
9 * @link https://github.com/openemr/openemr/tree/master
10 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
13 namespace OpenEMR\Billing
;
16 use OpenEMR\Services\FacilityService
;
20 const X12_VERSION
= '005010X222A1';
22 public $pid; // patient id
23 public $encounter_id; // encounter id
24 public $procs; // array of procedure rows from billing table
25 public $diags; // array of icd9 codes from billing table
26 public $diagtype= "ICD10"; // diagnosis code_type; safe to assume ICD10 now
27 public $x12_partner; // row from x12_partners table
28 public $encounter; // row from form_encounter table
29 public $facility; // row from facility table
30 public $billing_facility; // row from facility table
31 public $provider; // row from users table (rendering provider)
32 public $referrer; // row from users table (referring provider)
33 public $supervisor; // row from users table (supervising provider)
34 public $insurance_numbers; // row from insurance_numbers table for current payer
35 public $supervisor_numbers;// row from insurance_numbers table for current payer
36 public $patient_data; // row from patient_data table
37 public $billing_options; // row from form_misc_billing_options table
38 public $invoice; // result from get_invoice_summary()
39 public $payers; // array of arrays, for all payers
40 public $copay; // total of copays from the ar_activity table
41 public $facilityService; // via matthew.vita orm work :)
42 public $pay_to_provider; // to be implemented in facility ui
44 // This enforces the X12 Basic Character Set. Page A2.
45 public function x12Clean($str)
47 return preg_replace('/[^A-Z0-9!"\\&\'()+,\\-.\\/;?=@ ]/', '', strtoupper($str));
50 // X12 likes 9 digit zip codes also moving this from gen_x12
51 // to pursue PSR-0 and PSR-4
52 public function x12Zip($zip)
54 $zip = $this->x12Clean($zip);
55 if (strlen($zip) == 5) {
62 // Make sure dates have no formatting and zero filled becomes blank
63 // Handles date time stamp formats as well
64 public function cleanDate($date_field)
66 $cleandate = str_replace('-', '', substr($date_field, 0, 10));
68 if (substr_count($cleandate, '0')==8) {
75 public function loadPayerInfo(&$billrow)
78 $encounter_date = substr($this->encounter
['date'], 0, 10);
80 // Create the $payers array. This contains data for all insurances
81 // with the current one always at index 0, and the others in payment
82 // order starting at index 1.
84 $this->payers
= array();
85 $this->payers
[0] = array();
86 $query = "SELECT * FROM insurance_data WHERE pid = ? AND date <= ? ORDER BY type ASC, date DESC";
87 $dres = sqlStatement($query, array($this->pid
, $encounter_date));
89 while ($drow = sqlFetchArray($dres)) {
90 if (strcmp($prevtype, $drow['type']) == 0) {
94 $prevtype = $drow['type'];
95 // Very important to look at entries with a missing provider because
96 // they indicate no insurance as of the given date.
97 if (empty($drow['provider'])) {
101 $ins = count($this->payers
);
102 if ($drow['provider'] == $billrow['payer_id'] && empty($this->payers
[0]['data'])) {
106 $crow = sqlQuery("SELECT * FROM insurance_companies WHERE id = ?", array($drow['provider']));
107 $orow = new InsuranceCompany($drow['provider']);
108 $this->payers
[$ins] = array();
109 $this->payers
[$ins]['data'] = $drow;
110 $this->payers
[$ins]['company'] = $crow;
111 $this->payers
[$ins]['object'] = $orow;
114 // This kludge hands most cases of a rare ambiguous situation, where
115 // the primary insurance company is the same as the secondary. It seems
116 // nobody planned for that!
118 for ($i = 1; $i < count($this->payers
); ++
$i) {
119 if ($billrow['process_date'] &&
120 $this->payers
[0]['data']['provider'] == $this->payers
[$i]['data']['provider']) {
121 $tmp = $this->payers
[0];
122 $this->payers
[0] = $this->payers
[$i];
123 $this->payers
[$i] = $tmp;
127 $this->using_modifiers
= true;
129 // Get payment and adjustment details if there are any previous payers.
131 $this->invoice
= array();
132 if ($this->payerSequence() != 'P') {
133 $this->invoice
= ar_get_invoice_summary($this->pid
, $this->encounter_id
, true);
134 // Secondary claims might not have modifiers in SQL-Ledger data.
135 // In that case, note that we should not try to match on them.
136 $this->using_modifiers
= false;
137 foreach ($this->invoice
as $key => $trash) {
138 if (strpos($key, ':')) {
139 $this->using_modifiers
= true;
145 // Constructor. Loads relevant database information.
147 public function __construct($pid, $encounter_id)
150 $this->encounter_id
= $encounter_id;
151 $this->procs
= array();
152 $this->diags
= array();
155 $this->facilityService
= new FacilityService();
156 $this->pay_to_provider
= ''; // will populate from facility someday :)
159 // We need the encounter date before we can identify the payers.
160 $sql = "SELECT * FROM form_encounter WHERE pid = ? AND encounter = ?";
161 $this->encounter
= sqlQuery($sql, array($this->pid
, $this->encounter_id
));
163 // Sort by procedure timestamp in order to get some consistency.
164 $sql = "SELECT b.id, b.date, b.code_type, b.code, b.pid, b.provider_id, " .
165 "b.user, b.groupname, b.authorized, b.encounter, b.code_text, b.billed, " .
166 "b.activity, b.payer_id, b.bill_process, b.bill_date, b.process_date, " .
167 "b.process_file, b.modifier, b.units, b.fee, b.justify, b.target, b.x12_partner_id, " .
168 "b.ndc_info, b.notecodes, b.revenue_code, ct.ct_diag " .
169 "FROM billing as b INNER JOIN code_types as ct " .
170 "ON b.code_type = ct.ct_key " .
171 "WHERE ct.ct_claim = '1' AND ct.ct_active = '1' AND b.encounter = ? AND b.pid = ? AND " .
172 "b.activity = '1' ORDER BY b.date, b.id";
173 $res = sqlStatement($sql, array($this->encounter_id
, $this->pid
));
174 while ($row = sqlFetchArray($res)) {
175 // Save all diagnosis codes.
176 if ($row['ct_diag'] == '1') {
177 $this->diags
[$row['code']] = $row['code'];
181 if (!$row['units']) {
185 // Load prior payer data at the first opportunity in order to get
186 // the using_modifiers flag that is referenced below.
187 if (empty($this->procs
)) {
188 $this->loadPayerInfo($row);
191 // The consolidate duplicate procedures, which was previously here, was removed
192 // from codebase on 12/9/15. Reason: Some insurance companies decline consolidated
193 // procedures, and this can be left up to the billing coder when they input the items.
195 // If there is a row-specific provider then get its details.
196 if (!empty($row['provider_id'])) {
197 // Get service provider data for this row.
198 $sql = "SELECT * FROM users WHERE id = ?";
199 $row['provider'] = sqlQuery($sql, array($row['provider_id']));
200 // Get insurance numbers for this row's provider.
201 $sql = "SELECT * FROM insurance_numbers " .
202 "WHERE (insurance_company_id = ? OR insurance_company_id is NULL) AND provider_id = ?" .
203 "ORDER BY insurance_company_id DESC LIMIT 1";
204 $row['insurance_numbers'] = sqlQuery($sql, array($row['payer_id'], $row['provider_id']));
207 $this->procs
[] = $row;
210 $resMoneyGot = sqlStatement("SELECT pay_amount as PatientPay,session_id as id,".
211 "date(post_time) as date FROM ar_activity WHERE pid = ? AND encounter = ? AND ".
212 "payer_type=0 AND account_code='PCP'", array($this->pid
, $this->encounter_id
));
213 //new fees screen copay gives account_code='PCP'
214 while ($rowMoneyGot = sqlFetchArray($resMoneyGot)) {
215 $PatientPay=$rowMoneyGot['PatientPay']*-1;
216 $this->copay
-= $PatientPay;
219 $sql = "SELECT * FROM x12_partners WHERE id = ?";
220 $this->x12_partner
= sqlQuery($sql, array($this->procs
[0]['x12_partner_id']));
222 $this->facility
= $this->facilityService
->getById($this->encounter
['facility_id']);
224 /*****************************************************************
225 $provider_id = $this->procs[0]['provider_id'];
226 *****************************************************************/
227 $provider_id = $this->encounter
['provider_id'];
228 $sql = "SELECT * FROM users WHERE id = ?";
229 $this->provider
= sqlQuery($sql, array($provider_id));
230 // Selecting the billing facility assigned to the encounter. If none,
231 // try the first (and hopefully only) facility marked as a billing location.
232 if (empty($this->encounter
['billing_facility'])) {
233 $this->billing_facility
= $this->facilityService
->getPrimaryBillingLocation();
235 $this->billing_facility
= $this->facilityService
->getById($this->encounter
['billing_facility']);
238 $sql = "SELECT * FROM insurance_numbers " .
239 "WHERE (insurance_company_id = ? OR insurance_company_id is NULL) AND provider_id = ? " .
240 "ORDER BY insurance_company_id DESC LIMIT 1";
241 $this->insurance_numbers
= sqlQuery($sql, array($this->procs
[0]['payer_id'], $provider_id));
243 $sql = "SELECT * FROM patient_data WHERE pid = ? ORDER BY id LIMIT 1";
244 $this->patient_data
= sqlQuery($sql, array($this->pid
));
246 $sql = "SELECT fpa.* FROM forms JOIN form_misc_billing_options AS fpa " .
247 "ON fpa.id = forms.form_id " .
248 "WHERE forms.encounter = ? AND forms.pid = ? AND forms.deleted = 0 AND forms.formdir = 'misc_billing_options' " .
249 "ORDER BY forms.date";
250 $this->billing_options
= sqlQuery($sql, array($this->encounter_id
, $this->pid
));
252 $referrer_id = (empty($GLOBALS['MedicareReferrerIsRenderer']) ||
253 $this->insurance_numbers
['provider_number_type'] != '1C') ?
254 $this->patient_data
['ref_providerID'] : $provider_id;
255 $sql = "SELECT * FROM users WHERE id = ?";
256 $this->referrer
= sqlQuery($sql, array($referrer_id));
257 if (!$this->referrer
) {
258 $this->referrer
= array();
261 $supervisor_id = $this->encounter
['supervisor_id'];
262 $sql = "SELECT * FROM users WHERE id = ?";
263 $this->supervisor
= sqlQuery($sql, array($supervisor_id));
264 if (!$this->supervisor
) {
265 $this->supervisor
= array();
268 $billing_options_id = $this->billing_options
['provider_id'];
269 $sql = "SELECT * FROM users WHERE id = ?";
270 $this->billing_prov_id
= sqlQuery($sql, array($billing_options_id));
271 if (!$this->billing_prov_id
) {
272 $this->billing_prov_id
= array();
275 $sql = "SELECT * FROM insurance_numbers WHERE " .
276 "(insurance_company_id = ? OR insurance_company_id is NULL) AND provider_id = ? " .
277 "ORDER BY insurance_company_id DESC LIMIT 1";
278 $this->supervisor_numbers
= sqlQuery($sql, array($this->procs
[0]['payer_id'], $supervisor_id));
279 if (!$this->supervisor_numbers
) {
280 $this->supervisor_numbers
= array();
284 // Return an array of adjustments from the designated prior payer for the
285 // designated procedure key (might be procedure:modifier), or for the claim
286 // level. For each adjustment give date, group code, reason code, amount.
287 // Note this will include "patient responsibility" adjustments which are
288 // not adjustments to OUR invoice, but they reduce the amount that the
289 // insurance company pays.
291 public function payerAdjustments($ins, $code = 'Claim')
295 // If we have no modifiers stored in SQL-Ledger for this claim,
296 // then we cannot use a modifier passed in with the key.
297 $tmp = strpos($code, ':');
298 if ($tmp && !$this->using_modifiers
) {
299 $code = substr($code, 0, $tmp);
302 // For payments, source always starts with "Ins" or "Pt".
303 // Nonzero adjustment reason examples:
304 // Ins1 adjust code 42 (Charges exceed ... (obsolete))
305 // Ins1 adjust code 45 (Charges exceed your contracted/ legislated fee arrangement)
306 // Ins1 adjust code 97 (Payment is included in the allowance for another service/procedure)
307 // Ins1 adjust code A2 (Contractual adjustment)
310 // Zero adjustment reason examples:
312 // Coinsurance: 11.46 (code 2) Note: fix remits to identify insurance
313 // To deductible: 0.22 (code 1) Note: fix remits to identify insurance
314 // To copay Ins1 (manual entry)
315 // To ded'ble Ins1 (manual entry)
317 if (!empty($this->invoice
[$code])) {
321 $inslabel = ($this->payerSequence($ins) == 'S') ?
'Ins2' : 'Ins1';
322 $insnumber = substr($inslabel, 3);
324 // Compute this procedure's patient responsibility amount as of this
325 // prior payer, which is the original charge minus all insurance
326 // payments and "hard" adjustments up to this payer.
327 $ptresp = $this->invoice
[$code]['chg'] +
$this->invoice
[$code]['adj'];
328 foreach ($this->invoice
[$code]['dtl'] as $key => $value) {
329 // plv (from ar_activity.payer_type) exists to
330 // indicate the payer level.
331 if (isset($value['pmt']) && $value['pmt'] != 0) {
332 if ($value['plv'] > 0 && $value['plv'] <= $insnumber) {
333 $ptresp -= $value['pmt'];
335 } else if (isset($value['chg']) && trim(substr($key, 0, 10))) {
336 // non-blank key indicates this is an adjustment and not a charge
337 if ($value['plv'] > 0 && $value['plv'] <= $insnumber) {
338 $ptresp +
= $value['chg']; // adjustments are negative charges
342 $msp = isset($value['msp']) ?
$value['msp'] : null; // record the reason for adjustment
346 $ptresp = 0; // we may be insane but try to hide it
349 // Main loop, to extract adjustments for this payer and procedure.
350 foreach ($this->invoice
[$code]['dtl'] as $key => $value) {
351 $tmp = str_replace('-', '', trim(substr($key, 0, 10)));
356 if ($tmp && $value['pmt'] == 0) { // not original charge and not a payment
357 $rsn = $value['rsn'];
358 $chg = 0 - $value['chg']; // adjustments are negative charges
360 $gcode = 'CO'; // default group code = contractual obligation
361 $rcode = '45'; // default reason code = max fee exceeded (code 42 is obsolete)
363 if (preg_match("/Ins adjust $inslabel/i", $rsn, $tmp)) {
364 // From manual post. Take the defaults.
365 } else if (preg_match("/To copay $inslabel/i", $rsn, $tmp) && !$chg) {
366 $coinsurance = $ptresp; // from manual post
368 } else if (preg_match("/To ded'ble $inslabel/i", $rsn, $tmp) && !$chg) {
369 $deductible = $ptresp; // from manual post
371 } else if (preg_match("/$inslabel copay: (\S+)/i", $rsn, $tmp) && !$chg) {
372 $coinsurance = $tmp[1]; // from 835 as of 6/2007
374 } else if (preg_match("/$inslabel coins: (\S+)/i", $rsn, $tmp) && !$chg) {
375 $coinsurance = $tmp[1]; // from 835 and manual post as of 6/2007
377 } else if (preg_match("/$inslabel dedbl: (\S+)/i", $rsn, $tmp) && !$chg) {
378 $deductible = $tmp[1]; // from 835 and manual post as of 6/2007
380 } else if (preg_match("/$inslabel ptresp: (\S+)/i", $rsn, $tmp) && !$chg) {
381 continue; // from 835 as of 6/2007
382 } else if (preg_match("/$inslabel adjust code (\S+)/i", $rsn, $tmp)) {
383 $rcode = $tmp[1]; // from 835
384 } else if (preg_match("/$inslabel/i", $rsn, $tmp)) {
385 // Take the defaults.
386 } else if (preg_match('/Ins(\d)/i', $rsn, $tmp) && $tmp[1] != $insnumber) {
387 continue; // it's for some other payer
388 } else if ($insnumber == '1') {
389 if (preg_match("/Adjust code (\S+)/i", $rsn, $tmp)) {
390 $rcode = $tmp[1]; // from 835
392 // Other adjustments default to Ins1.
393 } else if (preg_match("/Co-pay: (\S+)/i", $rsn, $tmp) ||
394 preg_match("/Coinsurance: (\S+)/i", $rsn, $tmp)) {
395 $coinsurance = 0 +
$tmp[1]; // from 835 before 6/2007
397 } else if (preg_match("/To deductible: (\S+)/i", $rsn, $tmp)) {
398 $deductible = 0 +
$tmp[1]; // from 835 before 6/2007
401 continue; // there is no adjustment amount
404 continue; // it's for primary and that's not us
407 if ($rcode == '42') {
408 $rcode= '45'; // reason 42 is obsolete
411 $aadj[] = array($date, $gcode, $rcode, sprintf('%.2f', $chg));
415 // If we really messed it up, at least avoid negative numbers.
416 if ($coinsurance > $ptresp) {
417 $coinsurance = $ptresp;
420 if ($deductible > $ptresp) {
421 $deductible = $ptresp;
424 // Find out if this payer paid anything at all on this claim. This will
425 // help us allocate any unknown patient responsibility amounts.
426 $thispaidanything = 0;
427 foreach ($this->invoice
as $codekey => $codeval) {
428 foreach ($codeval['dtl'] as $key => $value) {
429 // plv exists to indicate the payer level.
430 if ($value['plv'] == $insnumber) {
431 $thispaidanything +
= $value['pmt'];
436 // Allocate any unknown patient responsibility by guessing if the
437 // deductible has been satisfied.
438 if ($thispaidanything) {
439 $coinsurance = $ptresp - $deductible;
441 $deductible = $ptresp - $coinsurance;
444 $deductible = sprintf('%.2f', $deductible);
445 $coinsurance = sprintf('%.2f', $coinsurance);
447 if ($date && $deductible != 0) {
448 $aadj[] = array($date, 'PR', '1', $deductible, $msp);
451 if ($date && $coinsurance != 0) {
452 $aadj[] = array($date, 'PR', '2', $coinsurance, $msp);
459 // Return date, total payments and total "hard" adjustments from the given
460 // prior payer. If $code is specified then only that procedure key is
461 // selected, otherwise it's for the whole claim.
463 public function payerTotals($ins, $code = '')
465 // If we have no modifiers stored in SQL-Ledger for this claim,
466 // then we cannot use a modifier passed in with the key.
467 $tmp = strpos($code, ':');
468 if ($tmp && !$this->using_modifiers
) {
469 $code = substr($code, 0, $tmp);
472 $inslabel = ($this->payerSequence($ins) == 'S') ?
'Ins2' : 'Ins1';
473 $insnumber = substr($inslabel, 3);
477 foreach ($this->invoice
as $codekey => $codeval) {
478 if ($code && strcmp($codekey, $code) != 0) {
482 foreach ($codeval['dtl'] as $key => $value) {
483 // plv (from ar_activity.payer_type) exists to
484 // indicate the payer level.
485 if ($value['plv'] == $insnumber) {
487 $date = str_replace('-', '', trim(substr($key, 0, 10)));
490 $paytotal +
= $value['pmt'];
494 $aarr = $this->payerAdjustments($ins, $codekey);
495 foreach ($aarr as $a) {
496 if (strcmp($a[1], 'PR') != 0) {
506 return array($date, sprintf('%.2f', $paytotal), sprintf('%.2f', $adjtotal));
509 // Return the amount already paid by the patient.
511 public function patientPaidAmount()
513 // For primary claims $this->invoice is not loaded, so get the co-pay
514 // from the ar_activity table instead.
515 if (empty($this->invoice
)) {
521 foreach ($this->invoice
as $codekey => $codeval) {
522 foreach ($codeval['dtl'] as $key => $value) {
523 // plv exists to indicate the payer level.
524 if ($value['plv'] == 0) { // 0 indicates patient
525 $amount +
= $value['pmt'];
530 return sprintf('%.2f', $amount);
533 // Return invoice total, including adjustments but not payments.
535 public function invoiceTotal()
538 foreach ($this->invoice
as $codekey => $codeval) {
539 $amount +
= $codeval['chg'];
542 return sprintf('%.2f', $amount);
545 // Number of procedures in this claim.
546 public function procCount()
548 return count($this->procs
);
551 // Number of payers for this claim. Ranges from 1 to 3.
552 public function payerCount()
554 return count($this->payers
);
557 public function x12gsversionstring()
559 return Claim
::X12_VERSION
;
562 public function x12gssenderid()
564 $tmp = $this->x12_partner
['x12_sender_id'];
565 while (strlen($tmp) < 15) {
572 public function x12gs03()
575 * GS03: Application Receiver's Code
576 * Code Identifying Party Receiving Transmission
578 * In most cases, the ISA08 and GS03 are the same. However
580 * In some clearing houses ISA08 and GS03 are different
581 * Example: https://www.acs-gcro.com/downloads/DOL/DOL_CG_X12N_5010_837_v1_02.pdf - Page 18
582 * In this .pdf, the ISA08 is specified to be 100000 while the GS03 is specified to be 77044
584 * Therefore if the x12_gs03 segement is explicitly specified we use that value,
585 * otherwise we simply use the same receiver ID as specified for ISA03
587 if ($this->x12_partner
['x12_gs03'] !== '') {
588 return $this->x12_partner
['x12_gs03'];
590 return $this->x12_partner
['x12_receiver_id'];
594 public function x12gsreceiverid()
596 $tmp = $this->x12_partner
['x12_receiver_id'];
597 while (strlen($tmp) < 15) {
604 public function x12gsisa05()
606 return $this->x12_partner
['x12_isa05'];
608 //adding in public functions for isa 01 - isa 04
610 public function x12gsisa01()
612 return $this->x12_partner
['x12_isa01'];
615 public function x12gsisa02()
617 return $this->x12_partner
['x12_isa02'];
620 public function x12gsisa03()
622 return $this->x12_partner
['x12_isa03'];
624 public function x12gsisa04()
626 return $this->x12_partner
['x12_isa04'];
630 public function x12gsisa07()
632 return $this->x12_partner
['x12_isa07'];
635 public function x12gsisa14()
637 return $this->x12_partner
['x12_isa14'];
640 public function x12gsisa15()
642 return $this->x12_partner
['x12_isa15'];
645 public function x12gsgs02()
647 $tmp = $this->x12_partner
['x12_gs02'];
649 $tmp = $this->x12_partner
['x12_sender_id'];
655 public function x12gsper06()
657 return $this->x12_partner
['x12_per06'];
660 public function cliaCode()
662 return $this->x12Clean(trim($this->facility
['domain_identifier']));
665 public function billingFacilityName()
667 return $this->x12Clean(trim($this->billing_facility
['name']));
670 public function billingFacilityStreet()
672 return $this->x12Clean(trim($this->billing_facility
['street']));
675 public function billingFacilityCity()
677 return $this->x12Clean(trim($this->billing_facility
['city']));
680 public function billingFacilityState()
682 return $this->x12Clean(trim($this->billing_facility
['state']));
685 public function billingFacilityZip()
687 return $this->x12Clean(trim($this->billing_facility
['postal_code']));
690 public function billingFacilityETIN()
692 return $this->x12Clean(trim(str_replace('-', '', $this->billing_facility
['federal_ein'])));
695 public function billingFacilityNPI()
697 return $this->x12Clean(trim($this->billing_facility
['facility_npi']));
700 public function federalIdType()
702 if ($this->billing_facility
['tax_id_type']) {
703 return $this->billing_facility
['tax_id_type'];
709 # The billing facility and the patient must both accept for this to return true.
710 public function billingFacilityAssignment($ins = 0)
712 $tmp = strtoupper($this->payers
[$ins]['data']['accept_assignment']);
713 if (strcmp($tmp, 'FALSE') == 0) {
717 return !empty($this->billing_facility
['accepts_assignment']);
720 public function billingContactName()
722 return $this->x12Clean(trim($this->billing_facility
['attn']));
725 public function billingContactPhone()
728 "/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
729 $this->billing_facility
['phone'],
732 return $tmp[1] . $tmp[2] . $tmp[3];
738 public function billingContactEmail()
740 return $this->x12Clean(trim($this->billing_facility
['email']));
743 public function facilityName()
745 return $this->x12Clean(trim($this->facility
['name']));
748 public function facilityStreet()
750 return $this->x12Clean(trim($this->facility
['street']));
753 public function facilityCity()
755 return $this->x12Clean(trim($this->facility
['city']));
758 public function facilityState()
760 return $this->x12Clean(trim($this->facility
['state']));
763 public function facilityZip()
765 return $this->x12Clean(trim($this->facility
['postal_code']));
768 public function facilityETIN()
770 return $this->x12Clean(trim(str_replace('-', '', $this->facility
['federal_ein'])));
773 public function facilityNPI()
775 return $this->x12Clean(trim($this->facility
['facility_npi']));
778 public function facilityPOS()
780 if ($this->encounter
['pos_code']) {
781 return sprintf('%02d', trim($this->encounter
['pos_code']));
783 return sprintf('%02d', trim($this->facility
['pos_code']));
787 public function facilityTaxonomy()
789 return $this->x12Clean(trim($this->facility
['facility_taxonomy']));
792 public function clearingHouseName()
794 return $this->x12Clean(trim($this->x12_partner
['name']));
797 public function clearingHouseETIN()
799 return $this->x12Clean(trim(str_replace('-', '', $this->x12_partner
['id_number'])));
802 public function providerNumberType($prockey = -1)
804 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
805 $this->insurance_numbers
: $this->procs
[$prockey]['insurance_numbers'];
806 return $tmp['provider_number_type'];
809 public function providerNumber($prockey = -1)
811 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
812 $this->insurance_numbers
: $this->procs
[$prockey]['insurance_numbers'];
813 return $this->x12Clean(trim(str_replace('-', '', $tmp['provider_number'])));
816 public function providerGroupNumber($prockey = -1)
818 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
819 $this->insurance_numbers
: $this->procs
[$prockey]['insurance_numbers'];
820 return $this->x12Clean(trim(str_replace('-', '', $tmp['group_number'])));
823 // Returns 'P', 'S' or 'T'.
825 public function payerSequence($ins = 0)
827 return strtoupper(substr($this->payers
[$ins]['data']['type'], 0, 1));
830 // Returns the HIPAA code of the patient-to-subscriber relationship.
832 public function insuredRelationship($ins = 0)
834 $tmp = strtolower($this->payers
[$ins]['data']['subscriber_relationship']);
835 if (strcmp($tmp, 'self') == 0) {
839 if (strcmp($tmp, 'spouse') == 0) {
843 if (strcmp($tmp, 'child') == 0) {
847 if (strcmp($tmp, 'other') == 0) {
851 return $tmp; // should not happen
854 public function insuredTypeCode($ins = 0)
856 if (strcmp($this->claimType($ins), 'MB') == 0 && $this->payerSequence($ins) != 'P') {
857 return $this->payers
[$ins]['data']['policy_type'];
863 // Is the patient also the subscriber?
865 public function isSelfOfInsured($ins = 0)
867 $tmp = strtolower($this->payers
[$ins]['data']['subscriber_relationship']);
868 return (strcmp($tmp, 'self') == 0);
871 public function planName($ins = 0)
873 return $this->x12Clean(trim($this->payers
[$ins]['data']['plan_name']));
876 public function policyNumber($ins = 0)
879 return $this->x12Clean(trim($this->payers
[$ins]['data']['policy_number']));
882 public function groupNumber($ins = 0)
884 return $this->x12Clean(trim($this->payers
[$ins]['data']['group_number']));
887 public function groupName($ins = 0)
889 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_employer']));
894 // MB Medicare Part B
898 // BL Blue Cross Blue Shield
901 // 10 Central Certification
902 // 11 Other Non-Federal Programs
903 // 12 Preferred Provider Organization (PPO)
904 // 13 Point of Service (POS)
905 // 14 Exclusive Provider Organization (EPO)
906 // 15 Indemnity Insurance
907 // 16 Health Maintenance Organization (HMO) Medicare Risk
908 // AM Automobile Medical
909 // CI Commercial Insurance Co.
911 // HM Health Maintenance Organization
913 // LM Liability Medical
914 // OF Other Federal Program
916 // VA Veterans Administration Plan
917 // WC Workers Compensation Health Plan
918 // ZZ Mutually Defined
920 public function claimType($ins = 0)
922 if (empty($this->payers
[$ins]['object'])) {
926 return $this->payers
[$ins]['object']->get_ins_claim_type();
929 public function claimTypeRaw($ins = 0)
931 if (empty($this->payers
[$ins]['object'])) {
935 return $this->payers
[$ins]['object']->get_ins_type_code();
938 public function insuredLastName($ins = 0)
940 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_lname']));
943 public function insuredFirstName($ins = 0)
945 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_fname']));
948 public function insuredMiddleName($ins = 0)
950 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_mname']));
953 public function insuredStreet($ins = 0)
955 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_street']));
958 public function insuredCity($ins = 0)
960 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_city']));
963 public function insuredState($ins = 0)
965 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_state']));
968 public function insuredZip($ins = 0)
970 return $this->x12Clean(trim($this->payers
[$ins]['data']['subscriber_postal_code']));
973 public function insuredPhone($ins = 0)
976 "/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/",
977 $this->payers
[$ins]['data']['subscriber_phone'],
980 return $tmp[1] . $tmp[2] . $tmp[3];
986 public function insuredDOB($ins = 0)
988 return str_replace('-', '', $this->payers
[$ins]['data']['subscriber_DOB']);
991 public function insuredSex($ins = 0)
993 return strtoupper(substr($this->payers
[$ins]['data']['subscriber_sex'], 0, 1));
996 public function payerName($ins = 0)
998 return $this->x12Clean(trim($this->payers
[$ins]['company']['name']));
1001 public function payerAttn($ins = 0)
1003 return $this->x12Clean(trim($this->payers
[$ins]['company']['attn']));
1006 public function payerStreet($ins = 0)
1008 if (empty($this->payers
[$ins]['object'])) {
1012 $tmp = $this->payers
[$ins]['object'];
1013 $tmp = $tmp->get_address();
1014 return $this->x12Clean(trim($tmp->get_line1()));
1017 public function payerCity($ins = 0)
1019 if (empty($this->payers
[$ins]['object'])) {
1023 $tmp = $this->payers
[$ins]['object'];
1024 $tmp = $tmp->get_address();
1025 return $this->x12Clean(trim($tmp->get_city()));
1028 public function payerState($ins = 0)
1030 if (empty($this->payers
[$ins]['object'])) {
1034 $tmp = $this->payers
[$ins]['object'];
1035 $tmp = $tmp->get_address();
1036 return $this->x12Clean(trim($tmp->get_state()));
1039 public function payerZip($ins = 0)
1041 if (empty($this->payers
[$ins]['object'])) {
1045 $tmp = $this->payers
[$ins]['object'];
1046 $tmp = $tmp->get_address();
1047 return $this->x12Clean(trim($tmp->get_zip()));
1050 public function payerID($ins = 0)
1052 return $this->x12Clean(trim($this->payers
[$ins]['company']['cms_id']));
1055 public function payerAltID($ins = 0)
1057 return $this->x12Clean(trim($this->payers
[$ins]['company']['alt_cms_id']));
1060 public function patientLastName()
1062 return $this->x12Clean(trim($this->patient_data
['lname']));
1065 public function patientFirstName()
1067 return $this->x12Clean(trim($this->patient_data
['fname']));
1070 public function patientMiddleName()
1072 return $this->x12Clean(trim($this->patient_data
['mname']));
1075 public function patientStreet()
1077 return $this->x12Clean(trim($this->patient_data
['street']));
1080 public function patientCity()
1082 return $this->x12Clean(trim($this->patient_data
['city']));
1085 public function patientState()
1087 return $this->x12Clean(trim($this->patient_data
['state']));
1090 public function patientZip()
1092 return $this->x12Clean(trim($this->patient_data
['postal_code']));
1095 public function patientPhone()
1097 $ptphone = $this->patient_data
['phone_home'];
1099 $ptphone = $this->patient_data
['phone_biz'];
1103 $ptphone = $this->patient_data
['phone_cell'];
1106 if (preg_match("/([2-9]\d\d)\D*(\d\d\d)\D*(\d\d\d\d)/", $ptphone, $tmp)) {
1107 return $tmp[1] . $tmp[2] . $tmp[3];
1113 public function patientDOB()
1115 return str_replace('-', '', $this->patient_data
['DOB']);
1118 public function patientSex()
1120 return strtoupper(substr($this->patient_data
['sex'], 0, 1));
1123 // Patient Marital Status: M = Married, S = Single, or something else.
1124 public function patientStatus()
1126 return strtoupper(substr($this->patient_data
['status'], 0, 1));
1129 // This should be UNEMPLOYED, STUDENT, PT STUDENT, or anything else to
1130 // indicate employed.
1131 public function patientOccupation()
1133 return strtoupper($this->x12Clean(trim($this->patient_data
['occupation'])));
1136 public function cptCode($prockey)
1138 return $this->x12Clean(trim($this->procs
[$prockey]['code']));
1141 public function cptModifier($prockey)
1143 // Split on the colon or space and clean each modifier
1145 $cln_mods = array();
1146 $mods = preg_split("/[: ]/", trim($this->procs
[$prockey]['modifier']));
1147 foreach ($mods as $mod) {
1148 array_push($cln_mods, $this->x12Clean($mod));
1151 return (implode(':', $cln_mods));
1154 public function cptNotecodes($prockey)
1156 return $this->x12Clean(trim($this->procs
[$prockey]['notecodes']));
1159 // Returns the procedure code, followed by ":modifier" if there is one.
1160 public function cptKey($prockey)
1162 $tmp = $this->cptModifier($prockey);
1163 return $this->cptCode($prockey) . ($tmp ?
":$tmp" : "");
1166 public function cptCharges($prockey)
1168 return $this->x12Clean(trim($this->procs
[$prockey]['fee']));
1171 public function cptUnits($prockey)
1173 if (empty($this->procs
[$prockey]['units'])) {
1177 return $this->x12Clean(trim($this->procs
[$prockey]['units']));
1181 public function cptNDCID($prockey)
1183 $ndcinfo = $this->procs
[$prockey]['ndc_info'];
1184 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
1186 if (preg_match('/^(\d+)-(\d+)-(\d+)$/', $ndc, $tmp)) {
1187 return sprintf('%05d%04d%02d', $tmp[1], $tmp[2], $tmp[3]);
1190 return $this->x12Clean($ndc); // format is bad but return it anyway
1196 // NDC drug unit of measure code.
1197 public function cptNDCUOM($prockey)
1199 $ndcinfo = $this->procs
[$prockey]['ndc_info'];
1200 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
1201 return $this->x12Clean($tmp[2]);
1207 // NDC drug number of units.
1208 public function cptNDCQuantity($prockey)
1210 $ndcinfo = $this->procs
[$prockey]['ndc_info'];
1211 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndcinfo, $tmp)) {
1212 return $this->x12Clean(ltrim($tmp[3], '0'));
1218 public function onsetDate()
1220 return $this->cleanDate($this->encounter
['onset_date']);
1223 public function onsetDateValid()
1225 return $this->onsetDate()!=='';
1228 public function serviceDate()
1230 return str_replace('-', '', substr($this->encounter
['date'], 0, 10));
1233 public function priorAuth()
1235 return $this->x12Clean(trim($this->billing_options
['prior_auth_number']));
1238 public function isRelatedEmployment()
1240 return !empty($this->billing_options
['employment_related']);
1243 public function isRelatedAuto()
1245 return !empty($this->billing_options
['auto_accident']);
1248 public function isRelatedOther()
1250 return !empty($this->billing_options
['other_accident']);
1253 public function autoAccidentState()
1255 return $this->x12Clean(trim($this->billing_options
['accident_state']));
1258 public function isUnableToWork()
1260 return !empty($this->billing_options
['is_unable_to_work']);
1263 public function offWorkFrom()
1265 return $this->cleanDate($this->billing_options
['off_work_from']);
1268 public function offWorkTo()
1270 return $this->cleanDate($this->billing_options
['off_work_to']);
1273 public function isHospitalized()
1275 return !empty($this->billing_options
['is_hospitalized']);
1278 public function hospitalizedFrom()
1280 return $this->cleanDate($this->billing_options
['hospitalization_date_from']);
1283 public function hospitalizedFromDateValid()
1285 return $this->hospitalizedFrom()!=='';
1288 public function hospitalizedTo()
1290 return $this->cleanDate($this->billing_options
['hospitalization_date_to']);
1292 public function hospitalizedToDateValid()
1294 return $this->hospitalizedTo()!=='';
1297 public function isOutsideLab()
1299 return !empty($this->billing_options
['outside_lab']);
1302 public function outsideLabAmount()
1304 return sprintf('%.2f', 0 +
$this->billing_options
['lab_amount']);
1307 public function medicaidReferralCode()
1309 return $this->x12Clean(trim($this->billing_options
['medicaid_referral_code']));
1312 public function epsdtFlag()
1314 return $this->x12Clean(trim($this->billing_options
['epsdt_flag']));
1317 public function medicaidResubmissionCode()
1319 return $this->x12Clean(trim($this->billing_options
['medicaid_resubmission_code']));
1322 public function medicaidOriginalReference()
1324 return $this->x12Clean(trim($this->billing_options
['medicaid_original_reference']));
1327 public function frequencyTypeCode()
1329 return ($this->billing_options
['replacement_claim'] == 1) ?
'7' : '1';
1332 public function icnResubmissionNumber()
1334 return $this->x12Clean($this->billing_options
['icn_resubmission_number']);
1337 public function additionalNotes()
1339 return $this->x12Clean(trim($this->billing_options
['comments']));
1342 public function miscOnsetDate()
1344 return $this->cleanDate($this->billing_options
['onset_date']);
1347 public function miscOnsetDateValid()
1349 return $this->miscOnsetDate()!=='';
1352 public function dateInitialTreatment()
1354 return $this->cleanDate($this->billing_options
['date_initial_treatment']);
1357 public function dateInitialTreatmentValid()
1359 return $this->dateInitialTreatment()!=='';
1362 public function box14Qualifier()
1364 // If no box qualifier specified use "431" indicating Onset
1365 return empty($this->billing_options
['box_14_date_qual']) ?
'431' :
1366 $this->billing_options
['box_14_date_qual'];
1369 public function box15Qualifier()
1371 // If no box qualifier specified use "454" indicating Initial Treatment
1372 return empty($this->billing_options
['box_15_date_qual']) ?
'454' :
1373 $this->billing_options
['box_15_date_qual'];
1376 public function box17Qualifier()
1378 //If no box qualifier specified use "DK" for ordering provider
1379 //someday might make mbo form the place to set referring instead of demographics under choices
1380 return empty($this->billing_options
['provider_qualifier_code']) ?
'' :
1381 $this->billing_options
['provider_qualifier_code'];
1384 // Returns an array of unique diagnoses. Periods are stripped by default
1385 // Option to keep periods is to support HCFA 1500 02/12 version
1386 public function diagArray($strip_periods = true)
1389 foreach ($this->procs
as $row) {
1390 $atmp = explode(':', $row['justify']);
1391 foreach ($atmp as $tmp) {
1393 $code_data = explode('|', $tmp);
1395 // If there was a | in the code data, the the first part of the array is the type, and the second is the identifier
1396 if (!empty($code_data[1])) {
1397 // This is the simplest way to determine if the claim is using ICD9 or ICD10 codes
1398 // a mix of code types is generally not allowed as there is only one specifier for all diagnoses on HCFA-1500 form
1399 // and there would be ambiguity with E and V codes
1400 $this->diagtype
=$code_data[0];
1402 //code is in the second part of the $code_data array.
1403 if ($strip_periods==true) {
1404 $diag = str_replace('.', '', $code_data[1]);
1406 $diag=$code_data[1];
1409 //No prepended code type label
1410 if ($strip_periods) {
1411 $diag = str_replace('.', '', $code_data[0]);
1413 $diag=$code_data[0];
1422 // The above got all the diagnoses used for justification, in the order
1423 // used for justification. Next we go through all diagnoses, justified
1424 // or not, to make sure they all get into the claim. We do it this way
1425 // so that the more important diagnoses appear first.
1426 foreach ($this->diags
as $diag) {
1427 if ($strip_periods) {
1428 $diag = str_replace('.', '', $diag);
1437 // Compute one 1-relative index in diagArray for the given procedure.
1438 // This function is obsolete, use diagIndexArray() instead.
1439 public function diagIndex($prockey)
1441 $da = $this->diagArray();
1442 $tmp = explode(':', $this->procs
[$prockey]['justify']);
1447 $diag = str_replace('.', '', $tmp[0]);
1449 foreach ($da as $value) {
1451 if (strcmp($value, $diag) == 0) {
1459 // Compute array of 1-relative diagArray indices for the given procedure.
1460 public function diagIndexArray($prockey)
1463 $da = $this->diagArray();
1464 $atmp = explode(':', $this->procs
[$prockey]['justify']);
1465 foreach ($atmp as $tmp) {
1467 $code_data = explode('|', $tmp);
1468 if (!empty($code_data[1])) {
1469 //Strip the prepended code type label
1470 $diag = str_replace('.', '', $code_data[1]);
1472 //No prepended code type label
1473 $diag = str_replace('.', '', $code_data[0]);
1477 foreach ($da as $value) {
1479 if (strcmp($value, $diag) == 0) {
1489 public function providerLastName($prockey = -1)
1491 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1492 $this->provider
: $this->procs
[$prockey]['provider'];
1493 return $this->x12Clean(trim($tmp['lname']));
1496 public function providerFirstName($prockey = -1)
1498 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1499 $this->provider
: $this->procs
[$prockey]['provider'];
1500 return $this->x12Clean(trim($tmp['fname']));
1503 public function providerMiddleName($prockey = -1)
1505 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1506 $this->provider
: $this->procs
[$prockey]['provider'];
1507 return $this->x12Clean(trim($tmp['mname']));
1510 public function providerSuffixName($prockey = -1)
1512 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1513 $this->provider
: $this->procs
[$prockey]['provider'];
1514 return $this->x12Clean(trim($tmp['suffix']));
1517 public function providerNPI($prockey = -1)
1519 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1520 $this->provider
: $this->procs
[$prockey]['provider'];
1521 return $this->x12Clean(trim($tmp['npi']));
1524 public function NPIValid($npi)
1526 // A NPI MUST be a 10 digit number
1531 if (strlen($npi)!=10) {
1535 if (!preg_match("/[0-9]*/", $npi)) {
1541 public function providerNPIValid($prockey = -1)
1543 return $this->NPIValid($this->providerNPI($prockey));
1546 public function providerUPIN($prockey = -1)
1548 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1549 $this->provider
: $this->procs
[$prockey]['provider'];
1550 return $this->x12Clean(trim($tmp['upin']));
1553 public function providerSSN($prockey = -1)
1555 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1556 $this->provider
: $this->procs
[$prockey]['provider'];
1557 return $this->x12Clean(trim(str_replace('-', '', $tmp['federaltaxid'])));
1560 public function providerTaxonomy($prockey = -1)
1562 $tmp = ($prockey < 0 ||
empty($this->procs
[$prockey]['provider_id'])) ?
1563 $this->provider
: $this->procs
[$prockey]['provider'];
1564 if (empty($tmp['taxonomy'])) {
1565 return '207Q00000X';
1568 return $this->x12Clean(trim($tmp['taxonomy']));
1571 public function referrerLastName()
1573 return $this->x12Clean(trim($this->referrer
['lname']));
1576 public function referrerFirstName()
1578 return $this->x12Clean(trim($this->referrer
['fname']));
1581 public function referrerMiddleName()
1583 return $this->x12Clean(trim($this->referrer
['mname']));
1586 public function referrerNPI()
1588 return $this->x12Clean(trim($this->referrer
['npi']));
1591 public function referrerUPIN()
1593 return $this->x12Clean(trim($this->referrer
['upin']));
1596 public function referrerSSN()
1598 return $this->x12Clean(trim(str_replace('-', '', $this->referrer
['federaltaxid'])));
1601 public function referrerTaxonomy()
1603 if (empty($this->referrer
['taxonomy'])) {
1604 return '207Q00000X';
1607 return $this->x12Clean(trim($this->referrer
['taxonomy']));
1610 public function supervisorLastName()
1612 return $this->x12Clean(trim($this->supervisor
['lname']));
1615 public function supervisorFirstName()
1617 return $this->x12Clean(trim($this->supervisor
['fname']));
1620 public function supervisorMiddleName()
1622 return $this->x12Clean(trim($this->supervisor
['mname']));
1625 public function supervisorNPI()
1627 return $this->x12Clean(trim($this->supervisor
['npi']));
1630 public function supervisorUPIN()
1632 return $this->x12Clean(trim($this->supervisor
['upin']));
1635 public function supervisorSSN()
1637 return $this->x12Clean(trim(str_replace('-', '', $this->supervisor
['federaltaxid'])));
1640 public function supervisorTaxonomy()
1642 if (empty($this->supervisor
['taxonomy'])) {
1643 return '207Q00000X';
1646 return $this->x12Clean(trim($this->supervisor
['taxonomy']));
1649 public function supervisorNumberType()
1651 return $this->supervisor_numbers
['provider_number_type'];
1654 public function supervisorNumber()
1656 return $this->x12Clean(trim(str_replace('-', '', $this->supervisor_numbers
['provider_number'])));
1659 public function billingProviderLastName()
1661 return $this->x12Clean(trim($this->billing_prov_id
['lname']));
1664 public function billingProviderFirstName()
1666 return $this->x12Clean(trim($this->billing_prov_id
['fname']));
1669 public function billingProviderMiddleName()
1671 return $this->x12Clean(trim($this->billing_prov_id
['mname']));
1674 public function billingProviderNPI()
1676 return $this->x12Clean(trim($this->billing_prov_id
['npi']));
1679 public function billingProviderUPIN()
1681 return $this->x12Clean(trim($this->billing_prov_id
['upin']));
1684 public function billingProviderSSN()
1686 return $this->x12Clean(trim(str_replace('-', '', $this->billing_prov_id
['federaltaxid'])));
1689 public function billingProviderTaxonomy()
1691 if (empty($this->billing_prov_id
['taxonomy'])) {
1692 return '207Q00000X';
1694 return $this->x12Clean(trim($this->billing_prov_id
['taxonomy']));
1697 public function billingProviderStreet()
1699 return $this->x12Clean(trim($this->billing_prov_id
['street']));
1702 public function billingProviderStreetB()
1704 return $this->x12Clean(trim($this->billing_prov_id
['streetb']));
1707 public function billingProviderCity()
1709 return $this->x12Clean(trim($this->billing_prov_id
['city']));
1712 public function billingProviderState()
1714 return $this->x12Clean(trim($this->billing_prov_id
['state']));
1717 public function billingProviderZip()
1719 return $this->x12Clean(trim($this->billing_prov_id
['zip']));