2 // Copyright (C) 2005-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 is the first of two pages to support posting of EOBs.
10 // The second is sl_eob_invoice.php.
12 include_once("../globals.php");
13 include_once("../../library/patient.inc");
14 include_once("../../library/sql-ledger.inc");
15 include_once("../../library/invoice_summary.inc.php");
16 include_once("../../custom/statement.inc.php");
17 include_once("../../library/parse_era.inc.php");
18 include_once("../../library/sl_eob.inc.php");
20 $DEBUG = 0; // set to 0 for production, 1 to test
27 // This is called back by parse_era() if we are processing X12 835's.
29 function era_callback(&$out) {
30 global $where, $eracount, $eraname;
31 // print_r($out); // debugging
33 // $eraname = $out['isa_control_number'];
34 $eraname = $out['gs_date'] . '_' . ltrim($out['isa_control_number'], '0') .
35 '_' . ltrim($out['payer_id'], '0');
36 list($pid, $encounter, $invnumber) = slInvoiceNumber($out);
38 if ($pid && $encounter) {
39 if ($where) $where .= ' OR ';
40 $where .= "invnumber = '$invnumber'";
44 function bucks($amount) {
46 printf("%.2f", $amount);
49 $today = date("Y-m-d");
53 // Print statements if requested.
55 if ($_POST['form_print'] && $_POST['form_cb']) {
57 $fhprint = fopen($STMT_TEMP_FILE, 'w');
60 foreach ($_POST['form_cb'] as $key => $value) $where .= " OR ar.id = $key";
61 $where = substr($where, 4);
63 // Sort by patient so that multiple invoices can be
64 // represented on a single statement.
65 $res = SLQuery("SELECT ar.*, customer.name, " .
66 "customer.address1, customer.address2, " .
67 "customer.city, customer.state, customer.zipcode, " .
68 "substring(trim(both from customer.name) from '% #\"%#\"' for '#') AS lname, " .
69 "substring(trim(both from customer.name) from '#\"%#\" %' for '#') AS fname " .
70 "FROM ar, customer WHERE ( $where ) AND " .
71 "customer.id = ar.customer_id " .
72 "ORDER BY lname, fname, ar.customer_id, ar.transdate");
73 if ($sl_err) die($sl_err);
78 for ($irow = 0; $irow < SLRowCount($res); ++
$irow) {
79 $row = SLGetRow($res, $irow);
81 // Determine the date of service. An 8-digit encounter number is
82 // presumed to be a date of service imported during conversion.
83 // Otherwise look it up in the form_encounter table.
86 list($pid, $encounter) = explode(".", $row['invnumber']);
87 if (strlen($encounter) == 8) {
88 $svcdate = substr($encounter, 0, 4) . "-" . substr($encounter, 4, 2) .
89 "-" . substr($encounter, 6, 2);
90 } else if ($encounter) {
91 $tmp = sqlQuery("SELECT date FROM form_encounter WHERE " .
92 "encounter = $encounter");
93 $svcdate = substr($tmp['date'], 0, 10);
96 // How many times have we dunned them for this invoice?
97 $intnotes = trim($row['intnotes']);
98 $duncount = substr_count(strtolower($intnotes), "statement sent");
100 // If this is a new patient then print the pending statement
101 // and start a new one. This is an associative array:
103 // cid = SQL-Ledger customer ID
104 // pid = OpenEMR patient ID
105 // patient = patient name
106 // amount = total amount due
107 // adjust = adjustments (already applied to amount)
108 // duedate = due date of the oldest included invoice
109 // age = number of days from duedate to today
110 // to = array of addressee name/address lines
112 // dos = date of service "yyyy-mm-dd"
113 // desc = description
114 // amount = charge less adjustments
115 // paid = amount paid
116 // notice = 1 for first notice, 2 for second, etc.
117 // detail = array of details, see invoice_summary.inc.php
119 if ($stmt['cid'] != $row['customer_id']) {
120 if (!empty($stmt)) ++
$stmt_count;
121 fwrite($fhprint, create_statement($stmt));
122 $stmt['cid'] = $row['customer_id'];
124 $stmt['patient'] = $row['name'];
125 $stmt['to'] = array($row['name']);
126 if ($row['address1']) $stmt['to'][] = $row['address1'];
127 if ($row['address2']) $stmt['to'][] = $row['address2'];
128 $stmt['to'][] = $row['city'] . ", " . $row['state'] . " " . $row['zipcode'];
129 $stmt['lines'] = array();
130 $stmt['amount'] = '0.00';
131 $stmt['today'] = $today;
132 $stmt['duedate'] = $row['duedate'];
134 // Report the oldest due date.
135 if ($row['duedate'] < $stmt['duedate']) {
136 $stmt['duedate'] = $row['duedate'];
140 $stmt['age'] = round((strtotime($today) - strtotime($stmt['duedate'])) /
143 $invlines = get_invoice_summary($row['id'], true); // true added by Rod 2006-06-09
144 foreach ($invlines as $key => $value) {
146 $line['dos'] = $svcdate;
147 $line['desc'] = ($key == 'CO-PAY') ?
"Patient Payment" : "Procedure $key";
148 $line['amount'] = sprintf("%.2f", $value['chg']);
149 $line['adjust'] = sprintf("%.2f", $value['adj']);
150 $line['paid'] = sprintf("%.2f", $value['chg'] - $value['bal']);
151 $line['notice'] = $duncount +
1;
152 $line['detail'] = $value['dtl']; // Added by Rod 2006-06-09
153 $stmt['lines'][] = $line;
154 $stmt['amount'] = sprintf("%.2f", $stmt['amount'] +
$value['bal']);
157 // Record something in ar.intnotes about this statement run.
158 if ($intnotes) $intnotes .= "\n";
159 $intnotes = addslashes($intnotes . "Statement sent $today");
160 if (! $DEBUG && ! $_POST['form_without']) {
161 SLQuery("UPDATE ar SET intnotes = '$intnotes' WHERE id = " . $row['id']);
162 if ($sl_err) die($sl_err);
166 if (!empty($stmt)) ++
$stmt_count;
167 fwrite($fhprint, create_statement($stmt));
170 $alertmsg = xl("Printing skipped; see test output in ").$STMT_TEMP_FILE;
172 exec("$STMT_PRINT_CMD $STMT_TEMP_FILE");
173 if ($_POST['form_without']) {
174 $alertmsg = xl("Now printing $stmt_count statements; invoices will not be updated.");
176 $alertmsg = xl("Now printing $stmt_count statements and updating invoices.");
183 <link rel
=stylesheet href
="<?echo $css_header;?>" type
="text/css">
184 <title
><?
xl('EOB Posting - Search','e')?
></title
>
185 <script type
="text/javascript" src
="../../library/textformat.js"></script
>
187 <script language
="JavaScript">
191 function checkAll(checked
) {
192 var f
= document
.forms
[0];
193 for (var i
= 0; i
< f
.elements
.length
; ++i
) {
194 var ename
= f
.elements
[i
].name
;
195 if (ename
.indexOf('form_cb[') == 0)
196 f
.elements
[i
].checked
= checked
;
200 function npopup(pid
) {
201 window
.open('sl_eob_patient_note.php?patient_id=' + pid
, '_blank', 'width=500,height=250,resizable=1');
209 <body leftmargin
='0' topmargin
='0' marginwidth
='0' marginheight
='0'>
212 <form method
='post' action
='sl_eob_search.php' enctype
='multipart/form-data'>
214 <table border
='0' cellpadding
='5' cellspacing
='0'>
217 <td height
="1" colspan
="10">
226 <?
xl('Source:','e')?
>
229 <input type
='text' name
='form_source' size
='10' value
='<?php echo $_POST['form_source
']; ?>'
230 title
='<?xl("A check number or claim number to identify the payment","e")?>'>
233 <?
xl('Pay Date:','e')?
>
236 <input type
='text' name
='form_paydate' size
='10' value
='<?php echo $_POST['form_paydate
']; ?>'
237 onkeyup
='datekeyup(this,mypcc)' onblur
='dateblur(this,mypcc)'
238 title
='<?xl("Date of payment yyyy-mm-dd","e")?>'>
241 <?
xl('Amount:','e')?
>
244 <input type
='text' name
='form_amount' size
='10' value
='<?php echo $_POST['form_amount
']; ?>'
245 title
='<?xl("Paid amount that you will allocate","e")?>'>
247 <td colspan
='2' align
='right'>
248 <a href
='sl_eob_help.php' target
='_blank'><?
xl('Help','e')?
></a
>
253 <td height
="1" colspan
="10">
257 <tr bgcolor
='#ddddff'>
262 <input type
='text' name
='form_name' size
='10' value
='<?php echo $_POST['form_name
']; ?>'
263 title
='<?xl("Any part of the patient name, or \"last,first\", or \"X-Y\"","e")?>'>
266 <?
xl('Chart ID:','e')?
>
269 <input type
='text' name
='form_pid' size
='10' value
='<?php echo $_POST['form_pid
']; ?>'
270 title
='<?xl("Patient chart ID","e")?>'>
273 <?
xl('Encounter:','e')?
>
276 <input type
='text' name
='form_encounter' size
='10' value
='<?php echo $_POST['form_encounter
']; ?>'
277 title
='<?xl("Encounter number","e")?>'>
280 <?
xl('Svc Date:','e')?
>
283 <input type
='text' name
='form_date' size
='10' value
='<?php echo $_POST['form_date
']; ?>'
284 title
='<?xl("Date of service mm/dd/yyyy","e")?>'>
290 <input type
='text' name
='form_to_date' size
='10' value
='<?php echo $_POST['form_to_date
']; ?>'
291 title
='<?xl("Ending DOS mm/dd/yyyy if you wish to enter a range","e")?>'>
294 <select name
='form_category'>
296 foreach (array(xl('Open'), xl('All'), xl('Due Pt'), xl('Due Ins')) as $value) {
297 echo " <option value='$value'";
298 if ($_POST['form_category'] == $value) echo " selected";
299 echo ">$value</option>\n";
305 <input type
='submit' name
='form_search' value
='<?xl("Search","e")?>'>
309 <!-- Support
for X12
835 upload
-->
310 <tr bgcolor
='#ddddff'>
312 <?
xl('Or upload ERA file:','e')?
>
313 <input type
="hidden" name
="MAX_FILE_SIZE" value
="5000000" />
314 <input name
="form_erafile" type
="file" />
319 <td height
="1" colspan
="10">
326 if ($_POST['form_search'] ||
$_POST['form_print']) {
327 $form_name = trim($_POST['form_name']);
328 $form_pid = trim($_POST['form_pid']);
329 $form_encounter = trim($_POST['form_encounter']);
330 $form_date = fixDate($_POST['form_date'], "");
331 $form_to_date = fixDate($_POST['form_to_date'], "");
335 // Handle X12 835 file upload.
337 if ($_FILES['form_erafile']['size']) {
338 $tmp_name = $_FILES['form_erafile']['tmp_name'];
340 // Handle .zip extension if present. Probably won't work on Windows.
341 if (strtolower(substr($_FILES['form_erafile']['name'], -4)) == '.zip') {
342 rename($tmp_name, "$tmp_name.zip");
343 exec("unzip -p $tmp_name.zip > $tmp_name");
344 unlink("$tmp_name.zip");
347 echo "<!-- Notes from ERA upload processing:\n";
348 $alertmsg .= parse_era($tmp_name, 'era_callback');
350 $erafullname = "$webserver_root/era/$eraname.edi";
352 if (is_file($erafullname)) {
353 $alertmsg .= "Warning: Set $eraname was already uploaded ";
354 if (is_file("$webserver_root/era/$eraname.html"))
355 $alertmsg .= "and processed. ";
357 $alertmsg .= "but not yet processed. ";
359 // if (!move_uploaded_file($_FILES['form_erafile']['tmp_name'], $erafullname)) {
360 // die("Upload failed! $alertmsg");
362 rename($tmp_name, $erafullname);
366 if (! $where) $where = '1 = 2';
370 if ($where) $where .= " AND ";
371 // Allow the last name to be followed by a comma and some part of a first name.
372 if (preg_match('/^(.*\S)\s*,\s*(.*)/', $form_name, $matches)) {
373 $where .= "customer.name ILIKE '" . $matches[2] . '% ' . $matches[1] . "%'";
374 // Allow a filter like "A-C" on the first character of the last name.
375 } else if (preg_match('/^(\S)\s*-\s*(\S)$/', $form_name, $matches)) {
377 while (ord($matches[1]) <= ord($matches[2])) {
378 // $tmp .= " OR customer.name ILIKE '% " . $matches[1] . "%'";
379 // Fixing the above which was also matching on middle names:
380 $tmp .= " OR customer.name ~* ' " . $matches[1] . "[A-Z]*$'";
381 $matches[1] = chr(ord($matches[1]) +
1);
383 $where .= "( $tmp ) ";
385 $where .= "customer.name ILIKE '%$form_name%'";
388 if ($form_pid && $form_encounter) {
389 if ($where) $where .= " AND ";
390 $where .= "ar.invnumber = '$form_pid.$form_encounter'";
392 else if ($form_pid) {
393 if ($where) $where .= " AND ";
394 $where .= "ar.invnumber LIKE '$form_pid.%'";
396 else if ($form_encounter) {
397 if ($where) $where .= " AND ";
398 $where .= "ar.invnumber like '%.$form_encounter'";
402 if ($where) $where .= " AND ";
403 $date1 = substr($form_date, 0, 4) . substr($form_date, 5, 2) .
404 substr($form_date, 8, 2);
406 $date2 = substr($form_to_date, 0, 4) . substr($form_to_date, 5, 2) .
407 substr($form_to_date, 8, 2);
408 $where .= "((CAST (substring(ar.invnumber from position('.' in ar.invnumber) + 1 for 8) AS integer) " .
409 "BETWEEN '$date1' AND '$date2')";
410 $tmp = "date >= '$form_date' AND date <= '$form_to_date'";
413 // This catches old converted invoices where we have no encounters:
414 $where .= "(ar.invnumber LIKE '%.$date1'";
415 $tmp = "date = '$form_date'";
417 // Pick out the encounters from MySQL with the desired DOS:
418 $rez = sqlStatement("SELECT pid, encounter FROM form_encounter WHERE $tmp");
419 while ($row = sqlFetchArray($rez)) {
420 $where .= " OR ar.invnumber = '" . $row['pid'] . "." . $row['encounter'] . "'";
426 if ($_POST['form_category'] == 'All') {
427 die("At least one search parameter is required if you select All.");
434 $query = "SELECT ar.id, ar.invnumber, ar.duedate, ar.amount, ar.paid, " .
435 "ar.intnotes, ar.notes, ar.shipvia, customer.name, customer.id AS custid, " .
436 "substring(trim(both from customer.name) from '% #\"%#\"' for '#') AS lname, " .
437 "substring(trim(both from customer.name) from '#\"%#\" %' for '#') AS fname, " .
438 "(SELECT SUM(invoice.fxsellprice) FROM invoice WHERE " .
439 "invoice.trans_id = ar.id AND invoice.fxsellprice > 0) AS charges, " .
440 "(SELECT SUM(invoice.fxsellprice) FROM invoice WHERE " .
441 "invoice.trans_id = ar.id AND invoice.fxsellprice < 0) AS adjustments " .
442 "FROM ar, customer WHERE ( $where ) AND customer.id = ar.customer_id ";
443 if ($_POST['form_category'] != 'All' && !$eracount) {
444 $query .= "AND ar.amount != ar.paid ";
445 // if ($_POST['form_category'] == 'Due') {
446 // $query .= "AND ar.duedate <= CURRENT_DATE ";
449 $query .= "ORDER BY lname, fname, ar.invnumber";
451 echo "<!-- $query -->\n"; // debugging
453 $t_res = SLQuery($query);
454 if ($sl_err) die($sl_err);
456 $num_invoices = SLRowCount($t_res);
457 if ($eracount && $num_invoices != $eracount) {
458 $alertmsg .= "Of $eracount remittances, there are $num_invoices " .
459 "matching claims in OpenEMR. ";
463 <table border
='0' cellpadding
='1' cellspacing
='2' width
='98%'>
465 <tr bgcolor
="#dddddd">
467  
;<?
xl('Patient','e')?
>
470  
;<?
xl('Invoice','e')?
>
473  
;<?
xl('Svc Date','e')?
>
476  
;<?
xl('Due Date','e')?
>
478 <td
class="dehead" align
="right">
479 <?
xl('Charge','e')?
> 
;
481 <td
class="dehead" align
="right">
482 <?
xl('Adjust','e')?
> 
;
484 <td
class="dehead" align
="right">
485 <?
xl('Paid','e')?
> 
;
487 <td
class="dehead" align
="right">
488 <?
xl('Balance','e')?
> 
;
490 <td
class="dehead" align
="center">
493 <?php
if (!$eracount) { ?
>
494 <td
class="dehead" align
="left">
502 for ($irow = 0; $irow < $num_invoices; ++
$irow) {
503 $row = SLGetRow($t_res, $irow);
505 // $duncount was originally supposed to be the number of times that
506 // the patient was sent a statement for this invoice.
508 $duncount = substr_count(strtolower($row['intnotes']), "statement sent");
510 // But if we have not yet billed the patient, then compute $duncount as a
511 // negative count of the number of insurance plans for which we have not
512 // yet closed out insurance.
515 $insgot = strtolower($row['notes']);
516 $inseobs = strtolower($row['shipvia']);
517 foreach (array('ins1', 'ins2', 'ins3') as $value) {
518 if (strpos($insgot, $value) !== false &&
519 strpos($inseobs, $value) === false)
524 // $isdue = ($row['duedate'] <= $today && $row['amount'] > $row['paid']) ? " checked" : "";
526 $isdueany = sprintf("%.2f",$row['amount']) > sprintf("%.2f",$row['paid']);
528 // An invoice is now due from the patient if money is owed and we are
529 // not waiting for insurance to pay. We no longer look at the due date
532 $isduept = ($duncount >= 0 && $isdueany) ?
" checked" : "";
534 // Skip invoices not in the desired "Due..." category.
536 if (substr($_POST['form_category'], 0, 3) == 'Due' && !$isdueany) continue;
537 if ($_POST['form_category'] == 'Due Ins' && ($duncount >= 0 ||
!$isdueany)) continue;
538 if ($_POST['form_category'] == 'Due Pt' && ($duncount < 0 ||
!$isdueany)) continue;
540 $bgcolor = ((++
$orow & 1) ?
"#ffdddd" : "#ddddff");
542 // Determine the date of service. If this was a search parameter
543 // then we already know it. Or an 8-digit encounter number is
544 // presumed to be a date of service imported during conversion.
545 // Otherwise look it up in the form_encounter table.
548 list($pid, $encounter) = explode(".", $row['invnumber']);
550 // $svcdate = $form_date;
552 if (strlen($encounter) == 8) {
553 $svcdate = substr($encounter, 0, 4) . "-" . substr($encounter, 4, 2) .
554 "-" . substr($encounter, 6, 2);
556 else if ($encounter) {
557 $tmp = sqlQuery("SELECT date FROM form_encounter WHERE " .
558 "encounter = $encounter");
559 $svcdate = substr($tmp['date'], 0, 10);
562 // Get billing note to determine if customer is in collections.
564 $pdrow = sqlQuery("SELECT pd.genericname2, pd.genericval2 FROM " .
565 "integration_mapping AS im, patient_data AS pd WHERE " .
566 "im.foreign_id = " . $row['custid'] . " AND " .
567 "im.foreign_table = 'customer' AND " .
568 "pd.id = im.local_id");
569 $row['billnote'] = ($pdrow['genericname2'] == 'Billing') ?
$pdrow['genericval2'] : '';
570 $in_collections = stristr($row['billnote'], 'IN COLLECTIONS') !== false;
572 <tr bgcolor
='<?php echo $bgcolor ?>'>
574  
;<a href
="" onclick
="return npopup(<?php echo $pid ?>)"
575 ><?php
echo $row['lname'] . ', ' . $row['fname']; ?
></a
>
578  
;<a href
="sl_eob_invoice.php?id=<?php echo $row['id'] ?>"
579 target
="_blank"><?php
echo $row['invnumber'] ?
></a
>
582  
;<?php
echo $svcdate ?
>
585  
;<?php
echo $row['duedate'] ?
>
587 <td
class="detail" align
="right">
588 <?php
bucks($row['charges']) ?
> 
;
590 <td
class="detail" align
="right">
591 <?php
bucks($row['adjustments']) ?
> 
;
593 <td
class="detail" align
="right">
594 <?php
bucks($row['paid']) ?
> 
;
596 <td
class="detail" align
="right">
597 <?php
bucks($row['charges'] +
$row['adjustments'] - $row['paid']) ?
> 
;
599 <td
class="detail" align
="center">
600 <?php
echo $duncount ?
$duncount : " " ?
>
602 <?php
if (!$eracount) { ?
>
603 <td
class="detail" align
="left">
604 <input type
='checkbox' name
='form_cb[<?php echo($row['id
']) ?>]'<?php
echo $isduept ?
> />
605 <?php
if ($in_collections) echo "<b><font color='red'>IC</font></b>"; ?
>
618 <?php
if ($eracount) { ?
>
619 <input type
='button' value
='Process ERA File' onclick
='processERA()' />  
;
621 <input type
='button' value
='Select All' onclick
='checkAll(true)' />  
;
622 <input type
='button' value
='Clear All' onclick
='checkAll(false)' />  
;
623 <input type
='submit' name
='form_print' value
='Print Selected Statements' />  
;
625 <input type
='checkbox' name
='form_without' value
='1' /> <?
xl('Without Update','e')?
>
630 <script language
="JavaScript">
631 function processERA() {
632 var f
= document
.forms
[0];
633 var debug
= f
.form_without
.checked ?
'1' : '0';
634 var paydate
= f
.form_paydate
.value
;
635 window
.open('sl_eob_process.php?eraname=<?php echo $eraname ?>&debug=' + debug +
'&paydate=' + paydate
, '_blank');
640 echo "alert('" . htmlentities($alertmsg) . "');\n";