2 // Copyright (C) 2006 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.
12 // Currently we assume that all 835's come from primary insurance, and
13 // that secondary claims always go out on paper. This should be made
14 // more general at some point. So far we have only tested with a
15 // family practice clinic using Zirmed.
17 // Buffer all output so we can archive it to a file.
20 include_once("../globals.php");
21 include_once("../../library/invoice_summary.inc.php");
22 include_once("../../library/sl_eob.inc.php");
23 include_once("../../library/parse_era.inc.php");
24 include_once("claim_status_codes.php");
25 include_once("adjustment_reason_codes.php");
26 include_once("remark_codes.php");
28 $debug = $_GET['debug'] ?
1 : 0; // set to 1 for debugging mode
34 $invoice_total = 0.00;
36 ///////////////////////// Assorted Functions /////////////////////////
38 function parse_date($date) {
39 $date = substr(trim($date), 0, 10);
40 if (preg_match('/^(\d\d\d\d)(\d\d)(\d\d)$/', $date, $matches)) {
41 return $matches[1] . '-' . $matches[2] . '-' . $matches[3];
46 function writeMessageLine($bgcolor, $class, $description) {
48 " <tr bgcolor='$bgcolor'>\n" .
49 " <td class='$class' colspan='4'> </td>\n" .
50 " <td class='$class'>$description</td>\n" .
51 " <td class='$class' colspan='2'> </td>\n" .
56 function writeDetailLine($bgcolor, $class, $ptname, $invnumber,
57 $code, $date, $description, $amount, $balance)
59 global $last_ptname, $last_invnumber, $last_code;
60 if ($ptname == $last_ptname) $ptname = ' ';
61 else $last_ptname = $ptname;
62 if ($invnumber == $last_invnumber) $invnumber = ' ';
63 else $last_invnumber = $invnumber;
64 if ($code == $last_code) $code = ' ';
65 else $last_code = $code;
66 if ($amount ) $amount = sprintf("%.2f", $amount );
67 if ($balance) $balance = sprintf("%.2f", $balance);
69 " <tr bgcolor='$bgcolor'>\n" .
70 " <td class='$class'>$ptname</td>\n" .
71 " <td class='$class'>$invnumber</td>\n" .
72 " <td class='$class'>$code</td>\n" .
73 " <td class='$class'>$date</td>\n" .
74 " <td class='$class'>$description</td>\n" .
75 " <td class='$class' align='right'>$amount</td>\n" .
76 " <td class='$class' align='right'>$balance</td>\n" .
81 // This writes detail lines that were already in SQL-Ledger for a given
84 function writeOldDetail(&$prev, $ptname, $invnumber, $dos, $code, $bgcolor) {
85 global $invoice_total;
86 // $prev['total'] = 0.00; // to accumulate total charges
88 foreach ($prev['dtl'] as $dkey => $ddata) {
89 $ddate = substr($dkey, 0, 10);
90 $description = $ddata['src'] . $ddata['rsn'];
91 if ($ddate == ' ') { // this is the service item
93 $description = 'Service Item';
95 $amount = sprintf("%.2f", $ddata['chg'] - $ddata['pmt']);
96 $invoice_total = sprintf("%.2f", $invoice_total +
$amount);
97 writeDetailLine($bgcolor, 'olddetail', $ptname, $invnumber,
98 $code, $ddate, $description, $amount, $invoice_total);
102 // This is called back by parse_era() once per claim.
104 function era_callback(&$out) {
105 global $encount, $debug, $claim_status_codes, $adjustment_reasons, $remark_codes;
106 global $invoice_total;
107 // print_r($out); // debugging
109 // Some heading information.
111 writeMessageLine('#ffffff', 'infdetail',
112 "Payer: " . htmlentities($out['payer_name']));
114 writeMessageLine('#ffffff', 'infdetail',
115 "WITHOUT UPDATE is selected; no changes will be applied.");
119 $invoice_total = 0.00;
120 $bgcolor = (++
$encount & 1) ?
"#ddddff" : "#ffdddd";
121 list($pid, $encounter, $invnumber) = slInvoiceNumber($out);
123 // Get details, if we have them, for the invoice.
126 if ($pid && $encounter) {
127 // Get invoice data into $arrow.
128 $arres = SLQuery("SELECT ar.id, ar.notes, ar.shipvia, customer.name " .
129 "FROM ar, customer WHERE ar.invnumber = '$invnumber' AND " .
130 "customer.id = ar.customer_id");
131 if ($sl_err) die($sl_err);
132 $arrow = SLGetRow($arres, 0);
135 $codes = get_invoice_summary($arrow['id'], true);
136 } else { // oops, no such invoice
137 $pid = $encounter = 0;
138 $invnumber = $out['our_claim_id'];
142 // Show the claim status.
143 $csc = $out['claim_status_code'];
144 writeMessageLine($bgcolor, 'infdetail',
145 "Claim status $csc: " . $claim_status_codes[$csc]);
147 // Show an error message if the claim is missing or already posted.
149 writeMessageLine($bgcolor, 'errdetail',
150 "The following claim is not in our database");
153 $insdone = strtolower($arrow['shipvia']);
154 if (strpos($insdone, 'ins1') !== false) {
156 writeMessageLine($bgcolor, 'errdetail',
157 "Primary insurance EOB was already posted for the following claim");
161 if ($out['warnings']) {
162 writeMessageLine($bgcolor, 'errdetail', nl2br(rtrim($out['warnings'])));
165 // Simplify some claim attributes for cleaner code.
166 $service_date = parse_date($out['dos']);
167 $check_date = parse_date($out['check_date']);
168 $production_date = parse_date($out['production_date']);
169 $patient_name = $arrow['name'] ?
$arrow['name'] :
170 ($out['patient_fname'] . ' ' . $out['patient_lname']);
172 // This loops once for each service item in this claim.
173 foreach ($out['svc'] as $svc) {
175 $prev = $codes[$svc['code']];
177 // This reports detail lines already on file for this service item.
179 writeOldDetail($prev, $patient_name, $invnumber, $service_date, $svc['code'], $bgcolor);
180 // Check for sanity in amount charged.
181 $prevchg = sprintf("%.2f", $prev['chg'] +
$prev['adj']);
182 if ($prevchg != $svc['chg']) {
183 writeMessageLine($bgcolor, 'errdetail',
184 "EOB charge amount " . $svc['chg'] . " for this code does not match our invoice");
187 // Check for duplicate payment. Should not happen.
188 foreach ($prev['dtl'] as $dkey => $ddata) {
189 if (! $ddata['pmt']) continue;
190 $ddate = parse_date($dkey);
191 if ($ddate == $check_date && $ddata['pmt'] == $svc['paid']) {
192 writeMessageLine($bgcolor, 'errdetail',
193 "This payment dated $check_date seems to be already posted!");
197 unset($codes[$svc['code']]);
200 // Or if the service item is not in our database, show it in red for
201 // manual resolution. Probably what happened is that the billing was
202 // "corrected" in OpenEMR after the claim was generated... not good!
204 writeDetailLine($bgcolor, 'errdetail', $patient_name, $invnumber,
205 $svc['code'], $service_date, '*** UNMATCHED SERVICE ITEM ***',
210 $class = $error ?
'errdetail' : 'newdetail';
212 // Report Allowed Amount.
213 if ($svc['allowed']) {
214 // A problem here is that some payers will include an adjustment
215 // reflecting the allowed amount, others not. So here we need to
216 // check if the adjustment exists, and if not then create it. We
217 // assume that any nonzero CO (Contractual Obligation) adjustment
219 $contract_adj = sprintf("%.2f", $svc['chg'] - $svc['allowed']);
220 foreach ($svc['adj'] as $adj) {
221 if ($adj['group_code'] == 'CO' && $adj['amount'] != 0)
224 if ($contract_adj > 0) {
225 $svc['adj'][] = array('group_code' => 'CO', 'reason_code' => 'A2',
226 'amount' => $contract_adj);
228 writeMessageLine($bgcolor, 'infdetail',
229 'Allowed amount is ' . sprintf("%.2f", $svc['allowed']));
232 // Report miscellaneous remarks.
233 if ($svc['remark']) {
234 $rmk = $svc['remark'];
235 writeMessageLine($bgcolor, 'infdetail', "$rmk: " . $remark_codes[$rmk]);
238 // Post and report the payment for this service item from the ERA.
240 if (!$error && !$debug) {
241 slPostPayment($arrow['id'], $svc['paid'], $check_date,
242 'Ins1/' . $out['check_number'], $svc['code'], $prev['ins'], $debug);
243 $invoice_total -= $svc['paid'];
245 writeDetailLine($bgcolor, $class, $patient_name, $invnumber,
246 $svc['code'], $check_date, 'Ins1/' . $out['check_number'] . ' payment',
247 0 - $svc['paid'], ($error ?
'' : $invoice_total));
250 // Post and report adjustments from this ERA. Posted adjustment reasons
251 // must be 25 characters or less in order to fit on patient statements.
252 foreach ($svc['adj'] as $adj) {
253 $description = $adj['reason_code'] . ': ' . $adjustment_reasons[$adj['reason_code']];
254 // Group code PR is Patient Responsibility. Enter these as zero
255 // adjustments to retain the note without crediting the claim.
256 if ($adj['group_code'] == 'PR') {
257 $reason = 'Pt resp: '; // Reasons should be 25 chars or less.
258 if ($adj['reason_code'] == '1') $reason = 'To deductible: ';
259 else if ($adj['reason_code'] == '2') $reason = 'Coinsurance: ';
260 else if ($adj['reason_code'] == '3') $reason = 'Co-pay: ';
261 $reason .= sprintf("%.2f", $adj['amount']);
262 if (!$error && !$debug) {
263 slPostAdjustment($arrow['id'], 0, $production_date,
264 $out['check_number'], $svc['code'], $prev['ins'],
267 writeMessageLine($bgcolor, $class, $description . ' ' .
268 sprintf("%.2f", $adj['amount']));
270 // Other group codes are real adjustments.
272 if (!$error && !$debug) {
273 slPostAdjustment($arrow['id'], $adj['amount'], $production_date,
274 $out['check_number'], $svc['code'], $prev['ins'],
275 'Ins1 adjust code ' . $adj['reason_code'], $debug);
276 $invoice_total -= $adj['amount'];
278 writeDetailLine($bgcolor, $class, $patient_name, $invnumber,
279 $svc['code'], $production_date, $description,
280 0 - $adj['amount'], ($error ?
'' : $invoice_total));
284 } // End of service item
286 // Report any existing service items not mentioned in the ERA.
287 foreach ($codes as $code => $prev) {
288 writeOldDetail($prev, $arrow['name'], $invnumber, $service_date, $code, $bgcolor);
291 // Cleanup: If all is well, mark Ins1 done and check for secondary billing.
292 if (!$error && !$debug) {
294 $query = "UPDATE ar SET shipvia = 'Done: Ins1' WHERE id = " . $arrow['id'];
296 if ($sl_err) die($sl_err);
297 // Check for secondary insurance.
298 $insgot = strtolower($arrow['notes']);
299 if (strpos($insgot, 'ins2') !== false) {
300 slSetupSecondary($arrow['id'], $debug);
301 writeMessageLine($bgcolor, 'infdetail',
302 'This claim is now re-queued for secondary paper billing');
308 /////////////////////////// End Functions ////////////////////////////
312 $eraname = $_GET['eraname'];
313 if (! $eraname) die(xl("You cannot access this page directly."));
315 // Open the output file early so that in case it fails, we do not post a
316 // bunch of stuff without saving the report. Also be sure to retain any old
317 // report files. Do not save the report if this is a no-update situation.
320 $nameprefix = "$webserver_root/era/$eraname";
322 for ($i = 1; is_file("$nameprefix$namesuffix.html"); ++
$i) {
325 $fnreport = "$nameprefix$namesuffix.html";
326 $fhreport = fopen($fnreport, 'w');
327 if (!$fhreport) die(xl("Cannot create") . " '$fnreport'");
334 <link rel
=stylesheet href
="<?echo $css_header;?>" type
="text/css">
335 <style type
="text/css">
336 body
{ font
-family
:sans
-serif
; font
-size
:8pt
; font
-weight
:normal
}
337 .dehead
{ color
:#000000; font-family:sans-serif; font-size:9pt; font-weight:bold }
338 .olddetail
{ color
:#000000; font-family:sans-serif; font-size:9pt; font-weight:normal }
339 .newdetail
{ color
:#00dd00; font-family:sans-serif; font-size:9pt; font-weight:normal }
340 .errdetail
{ color
:#dd0000; font-family:sans-serif; font-size:9pt; font-weight:normal }
341 .infdetail
{ color
:#0000ff; font-family:sans-serif; font-size:9pt; font-weight:normal }
343 <title
><?
xl('EOB Posting - Electronic Remittances','e')?
></title
>
344 <script language
="JavaScript">
347 <body leftmargin
='0' topmargin
='0' marginwidth
='0' marginheight
='0'>
350 <table border
='0' cellpadding
='2' cellspacing
='0' width
='100%'>
352 <tr bgcolor
="#cccccc">
354 <?php
xl('Patient','e') ?
>
357 <?php
xl('Invoice','e') ?
>
360 <?php
xl('Code','e') ?
>
363 <?php
xl('Date','e') ?
>
366 <?php
xl('Description','e') ?
>
368 <td
class="dehead" align
="right">
369 <?php
xl('Amount','e') ?
> 
;
371 <td
class="dehead" align
="right">
372 <?php
xl('Balance','e') ?
> 
;
377 $alertmsg = parse_era("$webserver_root/era/$eraname.edi", 'era_callback');
382 <script language
="JavaScript">
384 if ($alertmsg) echo " alert('" . htmlentities($alertmsg) . "');\n";
390 // Save all of this script's output to a report file.
392 fwrite($fhreport, ob_get_contents());