2 // Copyright (C) 2006-2010 Rod Roark <rod@sunsetsystems.com>
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 // This processes X12 835 remittances and produces a report.
11 // Buffer all output so we can archive it to a file.
14 require_once("../globals.php");
15 require_once("$srcdir/invoice_summary.inc.php");
16 require_once("$srcdir/sl_eob.inc.php");
17 require_once("$srcdir/parse_era.inc.php");
18 require_once("claim_status_codes.php");
19 require_once("adjustment_reason_codes.php");
20 require_once("remark_codes.php");
21 require_once("$srcdir/formatting.inc.php");
23 $debug = $_GET['debug'] ?
1 : 0; // set to 1 for debugging mode
24 $paydate = parse_date($_GET['paydate']);
30 $invoice_total = 0.00;
32 $INTEGRATED_AR = $GLOBALS['oer_config']['ws_accounting']['enabled'] === 2;
34 ///////////////////////// Assorted Functions /////////////////////////
36 function parse_date($date) {
37 $date = substr(trim($date), 0, 10);
38 if (preg_match('/^(\d\d\d\d)\D*(\d\d)\D*(\d\d)$/', $date, $matches)) {
39 return $matches[1] . '-' . $matches[2] . '-' . $matches[3];
44 function writeMessageLine($bgcolor, $class, $description) {
46 " <tr bgcolor='$bgcolor'>\n" .
47 " <td class='$class' colspan='4'> </td>\n" .
48 " <td class='$class'>$description</td>\n" .
49 " <td class='$class' colspan='2'> </td>\n" .
54 function writeDetailLine($bgcolor, $class, $ptname, $invnumber,
55 $code, $date, $description, $amount, $balance)
57 global $last_ptname, $last_invnumber, $last_code;
58 if ($ptname == $last_ptname) $ptname = ' ';
59 else $last_ptname = $ptname;
60 if ($invnumber == $last_invnumber) $invnumber = ' ';
61 else $last_invnumber = $invnumber;
62 if ($code == $last_code) $code = ' ';
63 else $last_code = $code;
64 if ($amount ) $amount = sprintf("%.2f", $amount );
65 if ($balance) $balance = sprintf("%.2f", $balance);
67 " <tr bgcolor='$bgcolor'>\n" .
68 " <td class='$class'>$ptname</td>\n" .
69 " <td class='$class'>$invnumber</td>\n" .
70 " <td class='$class'>$code</td>\n" .
71 " <td class='$class'>" . oeFormatShortDate($date) . "</td>\n" .
72 " <td class='$class'>$description</td>\n" .
73 " <td class='$class' align='right'>" . oeFormatMoney($amount) . "</td>\n" .
74 " <td class='$class' align='right'>" . oeFormatMoney($balance) . "</td>\n" .
79 // This writes detail lines that were already in SQL-Ledger for a given
82 function writeOldDetail(&$prev, $ptname, $invnumber, $dos, $code, $bgcolor) {
83 global $invoice_total;
84 // $prev['total'] = 0.00; // to accumulate total charges
86 foreach ($prev['dtl'] as $dkey => $ddata) {
87 $ddate = substr($dkey, 0, 10);
88 $description = $ddata['src'] . $ddata['rsn'];
89 if ($ddate == ' ') { // this is the service item
91 $description = 'Service Item';
93 $amount = sprintf("%.2f", $ddata['chg'] - $ddata['pmt']);
94 $invoice_total = sprintf("%.2f", $invoice_total +
$amount);
95 writeDetailLine($bgcolor, 'olddetail', $ptname, $invnumber,
96 $code, $ddate, $description, $amount, $invoice_total);
100 // This is called back by parse_era() once per claim.
102 function era_callback(&$out) {
103 global $encount, $debug, $claim_status_codes, $adjustment_reasons, $remark_codes;
104 global $invoice_total, $last_code, $paydate, $INTEGRATED_AR;
106 // Some heading information.
108 writeMessageLine('#ffffff', 'infdetail',
109 "Payer: " . htmlentities($out['payer_name']));
111 writeMessageLine('#ffffff', 'infdetail',
112 "WITHOUT UPDATE is selected; no changes will be applied.");
117 $invoice_total = 0.00;
118 $bgcolor = (++
$encount & 1) ?
"#ddddff" : "#ffdddd";
119 list($pid, $encounter, $invnumber) = slInvoiceNumber($out);
121 // Get details, if we have them, for the invoice.
124 if ($pid && $encounter) {
125 // Get invoice data into $arrow or $ferow.
126 if ($INTEGRATED_AR) {
127 $ferow = sqlQuery("SELECT e.*, p.fname, p.mname, p.lname " .
128 "FROM form_encounter AS e, patient_data AS p WHERE " .
129 "e.pid = '$pid' AND e.encounter = '$encounter' AND ".
132 $pid = $encounter = 0;
133 $invnumber = $out['our_claim_id'];
136 $codes = ar_get_invoice_summary($pid, $encounter, true);
137 // $svcdate = substr($ferow['date'], 0, 10);
139 } // end internal a/r
141 $arres = SLQuery("SELECT ar.id, ar.notes, ar.shipvia, customer.name " .
142 "FROM ar, customer WHERE ar.invnumber = '$invnumber' AND " .
143 "customer.id = ar.customer_id");
144 if ($sl_err) die($sl_err);
145 $arrow = SLGetRow($arres, 0);
148 $codes = get_invoice_summary($arrow['id'], true);
149 } else { // oops, no such invoice
150 $pid = $encounter = 0;
151 $invnumber = $out['our_claim_id'];
153 } // end not internal a/r
157 foreach ($codes as $cdata) {
159 $insurance_id = $cdata['ins'];
164 // Show the claim status.
165 $csc = $out['claim_status_code'];
167 if ($csc == '1' ||
$csc == '19') $inslabel = 'Ins1';
168 if ($csc == '2' ||
$csc == '20') $inslabel = 'Ins2';
169 if ($csc == '3' ||
$csc == '21') $inslabel = 'Ins3';
170 $primary = ($inslabel == 'Ins1');
171 writeMessageLine($bgcolor, 'infdetail',
172 "Claim status $csc: " . $claim_status_codes[$csc]);
174 // Show an error message if the claim is missing or already posted.
176 writeMessageLine($bgcolor, 'errdetail',
177 "The following claim is not in our database");
180 // Skip this test. Claims can get multiple CLPs from the same payer!
182 // $insdone = strtolower($arrow['shipvia']);
183 // if (strpos($insdone, 'ins1') !== false) {
185 // writeMessageLine($bgcolor, 'errdetail',
186 // "Primary insurance EOB was already posted for the following claim");
192 writeMessageLine($bgcolor, 'errdetail',
193 "Not posting adjustments for denied claims, please follow up manually!");
195 else if ($csc == '22') {
197 writeMessageLine($bgcolor, 'errdetail',
198 "Payment reversals are not automated, please enter manually!");
201 if ($out['warnings']) {
202 writeMessageLine($bgcolor, 'infdetail', nl2br(rtrim($out['warnings'])));
205 // Simplify some claim attributes for cleaner code.
206 $service_date = parse_date($out['dos']);
207 $check_date = $paydate ?
$paydate : parse_date($out['check_date']);
208 $production_date = $paydate ?
$paydate : parse_date($out['production_date']);
210 if ($INTEGRATED_AR) {
211 if (empty($ferow['lname'])) {
212 $patient_name = $out['patient_fname'] . ' ' . $out['patient_lname'];
214 $patient_name = $ferow['fname'] . ' ' . $ferow['lname'];
217 $patient_name = $arrow['name'] ?
$arrow['name'] :
218 ($out['patient_fname'] . ' ' . $out['patient_lname']);
223 // This loops once for each service item in this claim.
224 foreach ($out['svc'] as $svc) {
226 // Treat a modifier in the remit data as part of the procedure key.
227 // This key will then make its way into SQL-Ledger.
228 $codekey = $svc['code'];
229 if ($svc['mod']) $codekey .= ':' . $svc['mod'];
230 $prev = $codes[$codekey];
232 // This reports detail lines already on file for this service item.
234 writeOldDetail($prev, $patient_name, $invnumber, $service_date, $codekey, $bgcolor);
235 // Check for sanity in amount charged.
236 $prevchg = sprintf("%.2f", $prev['chg'] +
$prev['adj']);
237 if ($prevchg != abs($svc['chg'])) {
238 writeMessageLine($bgcolor, 'errdetail',
239 "EOB charge amount " . $svc['chg'] . " for this code does not match our invoice");
243 // Check for already-existing primary remittance activity.
244 // Removed this check because it was not allowing for copays manually
245 // entered into the invoice under a non-copay billing code.
247 if ((sprintf("%.2f",$prev['chg']) != sprintf("%.2f",$prev['bal']) ||
248 $prev['adj'] != 0) && $primary)
250 writeMessageLine($bgcolor, 'errdetail',
251 "This service item already has primary payments and/or adjustments!");
256 unset($codes[$codekey]);
259 // If the service item is not in our database...
262 // This is not an error. If we are not in error mode and not debugging,
263 // insert the service item into SL. Then display it (in green if it
264 // was inserted, or in red if we are in error mode).
265 $description = "CPT4:$codekey Added by $inslabel $production_date";
266 if (!$error && !$debug) {
267 if ($INTEGRATED_AR) {
268 arPostCharge($pid, $encounter, 0, $svc['chg'], 1, $service_date,
269 $codekey, $description, $debug);
271 slPostCharge($arrow['id'], $svc['chg'], 1, $service_date, $codekey,
272 $insurance_id, $description, $debug);
274 $invoice_total +
= $svc['chg'];
276 $class = $error ?
'errdetail' : 'newdetail';
277 writeDetailLine($bgcolor, $class, $patient_name, $invnumber,
278 $codekey, $production_date, $description,
279 $svc['chg'], ($error ?
'' : $invoice_total));
283 $class = $error ?
'errdetail' : 'newdetail';
285 // Report Allowed Amount.
286 if ($svc['allowed']) {
287 // A problem here is that some payers will include an adjustment
288 // reflecting the allowed amount, others not. So here we need to
289 // check if the adjustment exists, and if not then create it. We
290 // assume that any nonzero CO (Contractual Obligation) or PI
291 // (Payer Initiated) adjustment is good enough.
292 $contract_adj = sprintf("%.2f", $svc['chg'] - $svc['allowed']);
293 foreach ($svc['adj'] as $adj) {
294 if (($adj['group_code'] == 'CO' ||
$adj['group_code'] == 'PI') && $adj['amount'] != 0)
297 if ($contract_adj > 0) {
298 $svc['adj'][] = array('group_code' => 'CO', 'reason_code' => 'A2',
299 'amount' => $contract_adj);
301 writeMessageLine($bgcolor, 'infdetail',
302 'Allowed amount is ' . sprintf("%.2f", $svc['allowed']));
305 // Report miscellaneous remarks.
306 if ($svc['remark']) {
307 $rmk = $svc['remark'];
308 writeMessageLine($bgcolor, 'infdetail', "$rmk: " . $remark_codes[$rmk]);
311 // Post and report the payment for this service item from the ERA.
312 // By the way a 'Claim' level payment is probably going to be negative,
313 // i.e. a payment reversal.
315 if (!$error && !$debug) {
316 if ($INTEGRATED_AR) {
317 arPostPayment($pid, $encounter, 0, $svc['paid'], $codekey,
318 substr($inslabel,3), $out['check_number'], $debug);
320 slPostPayment($arrow['id'], $svc['paid'], $check_date,
321 "$inslabel/" . $out['check_number'], $codekey, $insurance_id, $debug);
323 $invoice_total -= $svc['paid'];
325 $description = "$inslabel/" . $out['check_number'] . ' payment';
326 if ($svc['paid'] < 0) $description .= ' reversal';
327 writeDetailLine($bgcolor, $class, $patient_name, $invnumber,
328 $codekey, $check_date, $description,
329 0 - $svc['paid'], ($error ?
'' : $invoice_total));
332 // Post and report adjustments from this ERA. Posted adjustment reasons
333 // must be 25 characters or less in order to fit on patient statements.
334 foreach ($svc['adj'] as $adj) {
335 $description = $adj['reason_code'] . ': ' . $adjustment_reasons[$adj['reason_code']];
336 if ($adj['group_code'] == 'PR' ||
!$primary) {
337 // Group code PR is Patient Responsibility. Enter these as zero
338 // adjustments to retain the note without crediting the claim.
341 $reason = 'Pt resp: '; // Reasons should be 25 chars or less.
342 if ($adj['reason_code'] == '1') $reason = 'To deductible: ';
343 else if ($adj['reason_code'] == '2') $reason = 'Coinsurance: ';
344 else if ($adj['reason_code'] == '3') $reason = 'Co-pay: ';
346 $reason = "$inslabel ptresp: "; // Reasons should be 25 chars or less.
347 if ($adj['reason_code'] == '1') $reason = "$inslabel dedbl: ";
348 else if ($adj['reason_code'] == '2') $reason = "$inslabel coins: ";
349 else if ($adj['reason_code'] == '3') $reason = "$inslabel copay: ";
351 // Non-primary insurance adjustments are garbage, either repeating
352 // the primary or are not adjustments at all. Report them as notes
353 // but do not post any amounts.
355 $reason = "$inslabel note " . $adj['reason_code'] . ': ';
357 $reason .= sprintf("%.2f", $adj['amount']);
360 $reason .= sprintf("%.2f", $adj['amount']);
361 // Post a zero-dollar adjustment just to save it as a comment.
362 if (!$error && !$debug) {
363 if ($INTEGRATED_AR) {
364 arPostAdjustment($pid, $encounter, 0, 0, $codekey,
365 substr($inslabel,3), $reason, $debug);
367 slPostAdjustment($arrow['id'], 0, $production_date,
368 $out['check_number'], $codekey, $insurance_id,
372 writeMessageLine($bgcolor, $class, $description . ' ' .
373 sprintf("%.2f", $adj['amount']));
375 // Other group codes for primary insurance are real adjustments.
377 if (!$error && !$debug) {
378 if ($INTEGRATED_AR) {
379 arPostAdjustment($pid, $encounter, 0, $adj['amount'], $codekey,
381 "Adjust code " . $adj['reason_code'], $debug);
383 slPostAdjustment($arrow['id'], $adj['amount'], $production_date,
384 $out['check_number'], $codekey, $insurance_id,
385 "$inslabel adjust code " . $adj['reason_code'], $debug);
387 $invoice_total -= $adj['amount'];
389 writeDetailLine($bgcolor, $class, $patient_name, $invnumber,
390 $codekey, $production_date, $description,
391 0 - $adj['amount'], ($error ?
'' : $invoice_total));
395 } // End of service item
397 // Report any existing service items not mentioned in the ERA, and
398 // determine if any of them are still missing an insurance response
399 // (if so, then insurance is not yet done with the claim).
400 $insurance_done = true;
401 foreach ($codes as $code => $prev) {
402 // writeOldDetail($prev, $arrow['name'], $invnumber, $service_date, $code, $bgcolor);
403 writeOldDetail($prev, $patient_name, $invnumber, $service_date, $code, $bgcolor);
404 $got_response = false;
405 foreach ($prev['dtl'] as $ddata) {
406 if ($ddata['pmt'] ||
$ddata['rsn']) $got_response = true;
408 if (!$got_response) $insurance_done = false;
411 // Cleanup: If all is well, mark Ins<x> done and check for secondary billing.
412 if (!$error && !$debug && $insurance_done) {
413 if ($INTEGRATED_AR) {
414 $level_done = 0 +
substr($inslabel, 3);
415 sqlStatement("UPDATE form_encounter " .
416 "SET last_level_closed = $level_done WHERE " .
417 "pid = '$pid' AND encounter = '$encounter'");
418 // Check for secondary insurance.
419 if ($primary && arGetPayerID($pid, $service_date, 2)) {
420 arSetupSecondary($pid, $encounter, $debug);
421 writeMessageLine($bgcolor, 'infdetail',
422 'This claim is now re-queued for secondary paper billing');
425 $shipvia = 'Done: Ins1';
426 if ($inslabel != 'Ins1') $shipvia .= ',Ins2';
427 if ($inslabel == 'Ins3') $shipvia .= ',Ins3';
428 $query = "UPDATE ar SET shipvia = '$shipvia' WHERE id = " . $arrow['id'];
430 if ($sl_err) die($sl_err);
431 // Check for secondary insurance.
432 $insgot = strtolower($arrow['notes']);
433 if ($primary && strpos($insgot, 'ins2') !== false) {
434 slSetupSecondary($arrow['id'], $debug);
435 writeMessageLine($bgcolor, 'infdetail',
436 'This claim is now re-queued for secondary paper billing');
443 /////////////////////////// End Functions ////////////////////////////
447 $eraname = $_GET['eraname'];
448 if (! $eraname) die(xl("You cannot access this page directly."));
450 // Open the output file early so that in case it fails, we do not post a
451 // bunch of stuff without saving the report. Also be sure to retain any old
452 // report files. Do not save the report if this is a no-update situation.
455 $nameprefix = "$webserver_root/era/$eraname";
457 for ($i = 1; is_file("$nameprefix$namesuffix.html"); ++
$i) {
460 $fnreport = "$nameprefix$namesuffix.html";
461 $fhreport = fopen($fnreport, 'w');
462 if (!$fhreport) die(xl("Cannot create") . " '$fnreport'");
465 if (!$INTEGRATED_AR) slInitialize();
469 <?
html_header_show();?
>
470 <link rel
=stylesheet href
="<?php echo $css_header;?>" type
="text/css">
471 <style type
="text/css">
472 body
{ font
-family
:sans
-serif
; font
-size
:8pt
; font
-weight
:normal
}
473 .dehead
{ color
:#000000; font-family:sans-serif; font-size:9pt; font-weight:bold }
474 .olddetail
{ color
:#000000; font-family:sans-serif; font-size:9pt; font-weight:normal }
475 .newdetail
{ color
:#00dd00; font-family:sans-serif; font-size:9pt; font-weight:normal }
476 .errdetail
{ color
:#dd0000; font-family:sans-serif; font-size:9pt; font-weight:normal }
477 .infdetail
{ color
:#0000ff; font-family:sans-serif; font-size:9pt; font-weight:normal }
479 <title
><?php
xl('EOB Posting - Electronic Remittances','e')?
></title
>
480 <script language
="JavaScript">
483 <body leftmargin
='0' topmargin
='0' marginwidth
='0' marginheight
='0'>
486 <table border
='0' cellpadding
='2' cellspacing
='0' width
='100%'>
488 <tr bgcolor
="#cccccc">
490 <?php
xl('Patient','e') ?
>
493 <?php
xl('Invoice','e') ?
>
496 <?php
xl('Code','e') ?
>
499 <?php
xl('Date','e') ?
>
502 <?php
xl('Description','e') ?
>
504 <td
class="dehead" align
="right">
505 <?php
xl('Amount','e') ?
> 
;
507 <td
class="dehead" align
="right">
508 <?php
xl('Balance','e') ?
> 
;
513 $alertmsg = parse_era("$webserver_root/era/$eraname.edi", 'era_callback');
515 if (!$INTEGRATED_AR) slTerminate();
519 <script language
="JavaScript">
521 if ($alertmsg) echo " alert('" . htmlentities($alertmsg) . "');\n";
527 // Save all of this script's output to a report file.
529 fwrite($fhreport, ob_get_contents());