Highway to PSR2
[openemr.git] / interface / billing / sl_eob_search.php
blobfc786a9390f82a57e40dffc2d9ef3d53b7213a14
1 <?php
2 /**
3 * This the first of two pages to support posting of EOBs.
4 * The second is sl_eob_invoice.php.
5 * Windows compatibility and statement downloading:
6 * 2009 Bill Cernansky and Tony McCormick [mi-squared.com]
8 * Copyright (C) 2005-2010 Rod Roark <rod@sunsetsystems.com>
10 * LICENSE: This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
21 * @package OpenEMR
22 * @author Rod Roark <rod@sunsetsystems.com>
23 * @author Roberto Vasquez <robertogagliotta@gmail.com>
24 * @author Jerry Padgett <sjpadgett@gmail.com>
25 * @link http://www.open-emr.org
27 require_once("../globals.php");
28 require_once("$srcdir/patient.inc");
29 require_once("$srcdir/invoice_summary.inc.php");
30 require_once("$srcdir/appointments.inc.php");
31 require_once($GLOBALS['OE_SITE_DIR'] . "/statement.inc.php");
32 require_once("$srcdir/parse_era.inc.php");
33 require_once("$srcdir/sl_eob.inc.php");
34 require_once("$srcdir/api.inc");
35 require_once("$srcdir/forms.inc");
36 require_once("$srcdir/../controllers/C_Document.class.php");
37 require_once("$srcdir/documents.php");
38 require_once("$srcdir/options.inc.php");
39 require_once("$srcdir/acl.inc");
41 $DEBUG = 0; // set to 0 for production, 1 to test
43 $alertmsg = '';
44 $where = '';
45 $eraname = '';
46 $eracount = 0;
47 /* Load dependencies only if we need them */
48 if (! empty($GLOBALS['portal_onsite_two_enable'])) {
49 /* Addition of onsite portal patient notify of invoice and reformated invoice - sjpadgett 01/2017 */
50 require_once("../../portal/lib/portal_mail.inc");
51 require_once("../../portal/lib/appsql.class.php");
53 function is_auth_portal($pid = 0)
55 if ($pData = sqlQuery("SELECT * FROM `patient_data` WHERE `pid` = ?", array(
56 $pid
57 ))) {
58 if ($pData['allow_patient_portal'] != "YES") {
59 return false;
60 } else {
61 $_SESSION['portalUser'] = strtolower($pData['fname']) . $pData['id'];
62 return true;
64 } else {
65 return false;
69 function notify_portal($thispid, array $invoices, $template, $invid)
71 $builddir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates/' . $thispid;
72 if (! is_dir($builddir)) {
73 mkdir($builddir, 0755, true);
76 if (fixup_invoice($template, $builddir . '/invoice' . $invid . '.tpl') != true) {
77 return false;
80 if (SavePatientAudit($thispid, $invoices) != true) {
81 return false;
82 } // this is all the invoice data for portal auditing
83 $note = xl('You have an invoice due for payment in your Patient Documents. There you may pay, download or print the invoice. Thank you.');
84 if (sendMail($_SESSION['authUser'], $note, xlt('Bill/Collect'), '', '0', $_SESSION['authUser'], $_SESSION['authUser'], $_SESSION['portalUser'], $invoices[0]['patient']) == 1) { // remind admin this was sent
85 sendMail($_SESSION['portalUser'], $note, xlt('Bill/Collect'), '', '0', $_SESSION['authUser'], $_SESSION['authUser'], $_SESSION['portalUser'], $invoices[0]['patient']); // notify patient
86 } else {
87 return false;
90 return true;
93 function fixup_invoice($template, $ifile)
95 $data = file_get_contents($template);
96 if ($data == "") {
97 return false;
100 if (! file_put_contents($ifile, $data)) {
101 return false;
104 return true;
107 function SavePatientAudit($pid, $invs)
109 $appsql = new ApplicationTable();
110 try {
111 $audit = array();
112 $audit['patient_id'] = $pid;
113 $audit['activity'] = "invoice";
114 $audit['require_audit'] = "0";
115 $audit['pending_action'] = "payment";
116 $audit['action_taken'] = "";
117 $audit['status'] = "waiting transaction";
118 $audit['narrative'] = "Request patient online payment.";
119 $audit['table_action'] = '';
120 $audit['table_args'] = json_encode($invs);
121 $audit['action_user'] = $pid;
122 $audit['action_taken_time'] = "";
123 $audit['checksum'] = "";
124 $edata = $appsql->getPortalAudit($pid, 'payment', 'invoice', "waiting transaction", 0);
125 if ($edata['id'] > 0) {
126 $appsql->portalAudit('update', $edata['id'], $audit);
127 } else {
128 $appsql->portalAudit('insert', '', $audit);
130 } catch (Exception $ex) {
131 return $ex;
134 return true;
138 // This is called back by parse_era() if we are processing X12 835's.
139 function era_callback(&$out)
141 global $where, $eracount, $eraname;
142 // print_r($out); // debugging
143 ++$eracount;
144 // $eraname = $out['isa_control_number'];
145 $eraname = $out['gs_date'] . '_' . ltrim($out['isa_control_number'], '0') .
146 '_' . ltrim($out['payer_id'], '0');
147 list($pid, $encounter, $invnumber) = slInvoiceNumber($out);
149 if ($pid && $encounter) {
150 if ($where) {
151 $where .= ' OR ';
154 $where .= "( f.pid = '$pid' AND f.encounter = '$encounter' )";
158 function bucks($amount)
160 if ($amount) {
161 echo oeFormatMoney($amount);
165 function validEmail($email)
167 if (preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email)) {
168 return true;
171 return false;
174 function emailLogin($patient_id, $message)
176 $patientData = sqlQuery("SELECT * FROM `patient_data` WHERE `pid`=?", array($patient_id));
177 if ($patientData['hipaa_allowemail'] != "YES" || empty($patientData['email']) || empty($GLOBALS['patient_reminder_sender_email'])) {
178 return false;
181 if (!(validEmail($patientData['email']))) {
182 return false;
185 if (!(validEmail($GLOBALS['patient_reminder_sender_email']))) {
186 return false;
189 if ($_SESSION['pc_facility']) {
190 $sql = "select * from facility where id=?";
191 $facility = sqlQuery($sql, array($_SESSION['pc_facility']));
192 } else {
193 $sql = "SELECT * FROM facility ORDER BY billing_location DESC LIMIT 1";
194 $facility = sqlQuery($sql);
197 $mail = new MyMailer();
198 $pt_name=$patientData['fname'].' '.$patientData['lname'];
199 $pt_email=$patientData['email'];
200 $email_subject=($facility['name'] . ' ' . xl('Patient Statement Bill'));
201 $email_sender=$GLOBALS['patient_reminder_sender_email'];
202 $mail->AddReplyTo($email_sender, $email_sender);
203 $mail->SetFrom($email_sender, $email_sender);
204 $mail->AddAddress($pt_email, $pt_name);
205 $mail->Subject = $email_subject;
206 $mail->MsgHTML("<html><body><div class='wrapper'>".$message."</div></body></html>");
207 $mail->IsHTML(true);
208 $mail->AltBody = $message;
210 if ($mail->Send()) {
211 return true;
212 } else {
213 $email_status = $mail->ErrorInfo;
214 error_log("EMAIL ERROR: ".$email_status, 0);
215 return false;
219 // Upload a file to the client's browser
221 function upload_file_to_client($file_to_send)
223 header("Pragma: public");
224 header("Expires: 0");
225 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
226 header("Content-Type: application/force-download");
227 header("Content-Length: " . filesize($file_to_send));
228 header("Content-Disposition: attachment; filename=" . basename($file_to_send));
229 header("Content-Description: File Transfer");
230 readfile($file_to_send);
231 // flush the content to the browser. If you don't do this, the text from the subsequent
232 // output from this script will be in the file instead of sent to the browser.
233 flush();
234 exit(); //added to exit from process properly in order to stop bad html code -ehrlive
235 // sleep one second to ensure there's no follow-on.
236 sleep(1);
239 function upload_file_to_client_email($ppid, $file_to_send)
241 $message = "";
242 global $STMT_TEMP_FILE_PDF;
243 $file = fopen($file_to_send, "r");//this file contains the text to be converted to pdf.
244 while (!feof($file)) {
245 $OneLine=fgets($file);//one line is read
247 $message = $message.$OneLine.'<br>';
249 $countline++;
252 emailLogin($ppid, $message);
255 function upload_file_to_client_pdf($file_to_send, $aPatFirstName = '', $aPatID = null, $flagCFN = false)
257 //modified for statement title name
258 //Function reads a HTML file and converts to pdf.
260 $aPatFName = convert_safe_file_dir_name($aPatFirstName); //modified for statement title name
261 if ($flagCFN) {
262 $STMT_TEMP_FILE_PDF = $GLOBALS['temporary_files_dir'] . "/Stmt_{$aPatFName}_{$aPatID}.pdf";
263 } else {
264 global $STMT_TEMP_FILE_PDF;
267 global $srcdir;
269 if ($GLOBALS['statement_appearance'] == '1') {
270 require_once("$srcdir/html2pdf/vendor/autoload.php");
271 $pdf2 = new HTML2PDF(
272 $GLOBALS['pdf_layout'],
273 $GLOBALS['pdf_size'],
274 $GLOBALS['pdf_language'],
275 true, // default unicode setting is true
276 'UTF-8', // default encoding setting is UTF-8
277 array($GLOBALS['pdf_left_margin'],$GLOBALS['pdf_top_margin'],$GLOBALS['pdf_right_margin'],$GLOBALS['pdf_bottom_margin']),
278 $_SESSION['language_direction'] == 'rtl' ? true : false
280 ob_start();
281 echo readfile($file_to_send, "r");//this file contains the HTML to be converted to pdf.
282 //echo $file;
283 $content = ob_get_clean();
285 // Fix a nasty html2pdf bug - it ignores document root!
286 global $web_root, $webserver_root;
287 $i = 0;
288 $wrlen = strlen($web_root);
289 $wsrlen = strlen($webserver_root);
290 while (true) {
291 $i = stripos($content, " src='/", $i + 1);
292 if ($i === false) {
293 break;
296 if (substr($content, $i+6, $wrlen) === $web_root &&
297 substr($content, $i+6, $wsrlen) !== $webserver_root) {
298 $content = substr($content, 0, $i + 6) . $webserver_root . substr($content, $i + 6 + $wrlen);
302 $pdf2->WriteHTML($content);
303 $temp_filename = $STMT_TEMP_FILE_PDF;
304 $content_pdf = $pdf2->Output($STMT_TEMP_FILE_PDF, 'F');
305 } else {
306 $pdf = new Cezpdf('LETTER');//pdf creation starts
307 $pdf->ezSetMargins(45, 9, 36, 10);
308 $pdf->selectFont('Courier');
309 $pdf->ezSetY($pdf->ez['pageHeight'] - $pdf->ez['topMargin']);
310 $countline=1;
311 $file = fopen($file_to_send, "r");//this file contains the text to be converted to pdf.
312 while (!feof($file)) {
313 $OneLine=fgets($file);//one line is read
314 if (stristr($OneLine, "\014") == true && !feof($file)) {//form feed means we should start a new page.
315 $pdf->ezNewPage();
316 $pdf->ezSetY($pdf->ez['pageHeight'] - $pdf->ez['topMargin']);
317 str_replace("\014", "", $OneLine);
320 if (stristr($OneLine, 'REMIT TO') == true || stristr($OneLine, 'Visit Date') == true || stristr($OneLine, 'Future Appointments') == true || stristr($OneLine, 'Current') == true) { //lines are made bold when 'REMIT TO' or 'Visit Date' is there.
321 $pdf->ezText('<b>'.$OneLine.'</b>', 12, array('justification' => 'left', 'leading' => 6));
322 } else {
323 $pdf->ezText($OneLine, 12, array('justification' => 'left', 'leading' => 6));
326 $countline++;
329 $fh = @fopen($STMT_TEMP_FILE_PDF, 'w');//stored to a pdf file
330 if ($fh) {
331 fwrite($fh, $pdf->ezOutput());
332 fclose($fh);
336 header("Pragma: public");//this section outputs the pdf file to browser
337 header("Expires: 0");
338 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
339 header("Content-Type: application/force-download");
340 header("Content-Length: " . filesize($STMT_TEMP_FILE_PDF));
341 header("Content-Disposition: attachment; filename=" . basename($STMT_TEMP_FILE_PDF));
342 header("Content-Description: File Transfer");
343 readfile($STMT_TEMP_FILE_PDF);
344 // flush the content to the browser. If you don't do this, the text from the subsequent
345 // output from this script will be in the file instead of sent to the browser.
346 flush();
347 exit(); //added to exit from process properly in order to stop bad html code -ehrlive
348 // sleep one second to ensure there's no follow-on.
349 sleep(1);
353 $today = date("Y-m-d");
354 // Print or download statements if requested.
356 if (($_POST['form_print'] || $_POST['form_download'] || $_POST['form_email'] || $_POST['form_pdf']) || $_POST['form_portalnotify'] && $_POST['form_cb']) {
357 $fhprint = fopen($STMT_TEMP_FILE, 'w');
359 $sqlBindArray = array();
360 $where = "";
361 foreach ($_POST['form_cb'] as $key => $value) {
362 $where .= " OR f.id = ?";
363 array_push($sqlBindArray, $key);
366 if (!empty($where)) {
367 $where = substr($where, 4);
368 $where = '( ' . $where . ' ) AND';
371 // need to only use summary invoice for multi visits
372 $inv_pid = array();
373 $inv_count = -1;
374 foreach ($_POST['form_invpids'] as $key => $v) {
375 if ($_POST['form_cb'][$key]) {
376 array_push($inv_pid, key($v));
380 $res = sqlStatement("SELECT " .
381 "f.id, f.date, f.pid, f.encounter, f.stmt_count, f.last_stmt_date, f.last_level_closed, f.last_level_billed, f.billing_note as enc_billing_note, " .
382 "p.fname, p.mname, p.lname, p.street, p.city, p.state, p.postal_code, p.billing_note as pat_billing_note " .
383 "FROM form_encounter AS f, patient_data AS p " .
384 "WHERE $where " .
385 "p.pid = f.pid " .
386 "ORDER BY p.lname, p.fname, f.pid, f.date, f.encounter", $sqlBindArray);
388 $stmt = array();
389 $stmt_count = 0;
391 $flagT = true;
392 $aPatientFirstName = '';
393 $aPatientID = null;
394 $multiplePatients = false;
395 $usePatientNamePdf = false;
397 // This loops once for each invoice/encounter.
399 while ($row = sqlFetchArray($res)) {
400 $svcdate = substr($row['date'], 0, 10);
401 $duedate = $svcdate; // TBD?
402 $duncount = $row['stmt_count'];
403 $enc_note = $row['enc_billing_note'];
405 if ($flagT) {
406 $flagT = false;
407 $aPatientFirstName = $row['fname'];
408 $aPatientID = $row['pid'];
409 $usePatientNamePdf = true;
410 } elseif (!$multiplePatients) {
411 if ($aPatientID != $row['pid']) {
412 $multiplePatients = true;
413 $aPatientFirstName = '';
414 $aPatientID = null;
415 $usePatientNamePdf = false;
419 // If this is a new patient then print the pending statement
420 // and start a new one. This is an associative array:
422 // cid = same as pid
423 // pid = OpenEMR patient ID
424 // patient = patient name
425 // amount = total amount due
426 // adjust = adjustments (already applied to amount)
427 // duedate = due date of the oldest included invoice
428 // age = number of days from duedate to today
429 // to = array of addressee name/address lines
430 // lines = array of:
431 // dos = date of service "yyyy-mm-dd"
432 // desc = description
433 // amount = charge less adjustments
434 // paid = amount paid
435 // notice = 1 for first notice, 2 for second, etc.
436 // detail = array of details, see invoice_summary.inc.php
438 if ($stmt['cid'] != $row['pid']) {
439 if (!empty($stmt)) {
440 ++$stmt_count;
443 $stmt['cid'] = $row['pid'];
444 $stmt['pid'] = $row['pid'];
445 $stmt['dun_count'] = $row['stmt_count'];
446 $stmt['bill_note'] = $row['pat_billing_note'];
447 $stmt['enc_bill_note'] = $row['enc_billing_note'];
448 $stmt['bill_level'] = $row['last_level_billed'];
449 $stmt['level_closed'] = $row['last_level_closed'];
450 $stmt['patient'] = $row['fname'] . ' ' . $row['lname'];
451 $stmt['encounter'] = $row['encounter'];
452 #If you use the field in demographics layout called
453 #guardiansname this will allow you to send statements to the parent
454 #of a child or a guardian etc
455 if (strlen($row['guardiansname']) == 0) {
456 $stmt['to'] = array($row['fname'] . ' ' . $row['lname']);
457 } else {
458 $stmt['to'] = array($row['guardiansname']);
461 if ($row['street']) {
462 $stmt['to'][] = $row['street'];
465 $stmt['to'][] = $row['city'] . ", " . $row['state'] . " " . $row['postal_code'];
466 $stmt['lines'] = array();
467 $stmt['amount'] = '0.00';
468 $stmt['ins_paid'] = 0;
469 $stmt['today'] = $today;
470 $stmt['duedate'] = $duedate;
471 } else {
472 // Report the oldest due date.
473 if ($duedate < $stmt['duedate']) {
474 $stmt['duedate'] = $duedate;
478 // Recompute age at each invoice.
479 $stmt['age'] = round((strtotime($today) - strtotime($stmt['duedate'])) / (24 * 60 * 60));
481 $invlines = ar_get_invoice_summary($row['pid'], $row['encounter'], true);
482 foreach ($invlines as $key => $value) {
483 $line = array();
484 $line['dos'] = $svcdate;
485 if ($GLOBALS['use_custom_statement']) {
486 $line['desc'] = ($key == 'CO-PAY') ? "Patient Payment" : $value['code_text'];
487 } else {
488 $line['desc'] = ($key == 'CO-PAY') ? "Patient Payment" : "Procedure $key";
491 $line['amount'] = sprintf("%.2f", $value['chg']);
492 $line['adjust'] = sprintf("%.2f", $value['adj']);
493 $line['paid'] = sprintf("%.2f", $value['chg'] - $value['bal']);
494 $line['notice'] = $duncount + 1;
495 $line['detail'] = $value['dtl'];
496 $stmt['lines'][] = $line;
497 $stmt['amount'] = sprintf("%.2f", $stmt['amount'] + $value['bal']);
498 $stmt['ins_paid'] = $stmt['ins_paid'] + $value['ins'];
501 // Record that this statement was run.
502 if (! $DEBUG && ! $_POST['form_without']) {
503 sqlStatement("UPDATE form_encounter SET " .
504 "last_stmt_date = '$today', stmt_count = stmt_count + 1 " .
505 "WHERE id = " . $row['id']);
508 if ($_POST['form_portalnotify']) {
509 if (! is_auth_portal($stmt['pid'])) {
510 $alertmsg = xlt('Notification FAILED: Not Portal Authorized');
511 break;
514 $inv_count += 1;
515 $pvoice[] = $stmt;
516 // we don't want to send the portal multiple invoices, thus this. Last invoice for pid is summary.
517 if ($inv_pid[$inv_count] != $inv_pid[$inv_count+1]) {
518 fwrite($fhprint, make_statement($stmt));
519 if (!notify_portal($stmt['pid'], $pvoice, $STMT_TEMP_FILE, $stmt['pid'] . "-" . $stmt['encounter'])) {
520 $alertmsg = xlt('Notification FAILED');
521 break;
524 $pvoice = array();
525 flush();
526 ftruncate($fhprint, 0);
527 } else {
528 continue;
530 } else {
531 fwrite($fhprint, make_statement($stmt));
533 } // end while
535 if (!empty($stmt)) {
536 ++$stmt_count;
539 fclose($fhprint);
540 sleep(1);
541 // Download or print the file, as selected
542 if ($_POST['form_download']) {
543 upload_file_to_client($STMT_TEMP_FILE);
544 } elseif ($_POST['form_pdf']) {
545 upload_file_to_client_pdf($STMT_TEMP_FILE, $aPatientFirstName, $aPatientID, $usePatientNamePdf);
546 } elseif ($_POST['form_email']) {
547 upload_file_to_client_email($stmt['pid'], $STMT_TEMP_FILE);
548 } elseif ($_POST['form_portalnotify']) {
549 if ($alertmsg == "") {
550 $alertmsg = xl('Sending Invoice to Patient Portal Completed');
552 } else { // Must be print!
553 if ($DEBUG) {
554 $alertmsg = xl("Printing skipped; see test output in") .' '. $STMT_TEMP_FILE;
555 } else {
556 exec("$STMT_PRINT_CMD $STMT_TEMP_FILE");
557 if ($_POST['form_without']) {
558 $alertmsg = xl('Now printing') .' '. $stmt_count .' '. xl('statements; invoices will not be updated.');
559 } else {
560 $alertmsg = xl('Now printing') .' '. $stmt_count .' '. xl('statements and updating invoices.');
562 } // end not debug
563 } // end not form_download
564 } // end statements requested
566 <html>
567 <head>
568 <?php html_header_show(); ?>
569 <link rel=stylesheet href="<?php echo $css_header;?>" type="text/css">
570 <title><?php xl('EOB Posting - Search', 'e'); ?></title>
571 <script type="text/javascript" src="../../library/textformat.js"></script>
573 <script language="JavaScript">
575 var mypcc = '1';
577 function checkAll(checked) {
578 var f = document.forms[0];
579 for (var i = 0; i < f.elements.length; ++i) {
580 var ename = f.elements[i].name;
581 if (ename.indexOf('form_cb[') == 0)
582 f.elements[i].checked = checked;
586 function npopup(pid) {
587 window.open('sl_eob_patient_note.php?patient_id=' + pid, '_blank', 'width=500,height=250,resizable=1');
588 return false;
591 </script>
593 </head>
595 <body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>
596 <center>
598 <form method='post' action='sl_eob_search.php' enctype='multipart/form-data'>
600 <table border='0' cellpadding='5' cellspacing='0'>
601 <tr>
603 <?php
604 // Identify the payer to support resumable posting sessions.
605 echo " <td>\n";
606 echo " " . xl('Payer') . ":\n";
607 echo " </td>\n";
608 echo " <td>\n";
609 $insurancei = getInsuranceProviders();
610 echo " <select name='form_payer_id'>\n";
611 echo " <option value='0'>-- " . xl('Patient') . " --</option>\n";
612 foreach ($insurancei as $iid => $iname) {
613 echo "<option value='$iid'";
614 if ($iid == $_POST['form_payer_id']) {
615 echo " selected";
618 echo ">" . $iname . "</option>\n";
621 echo " </select>\n";
622 echo " </td>\n";
625 <td>
626 <?php xl('Source:', 'e'); ?>
627 </td>
628 <td>
629 <input type='text' name='form_source' size='10' value='<?php echo $_POST['form_source']; ?>'
630 title='<?php xl("A check number or claim number to identify the payment", "e"); ?>'>
631 </td>
632 <td>
633 <?php xl('Pay Date:', 'e'); ?>
634 </td>
635 <td>
636 <input type='text' name='form_paydate' size='10' value='<?php echo $_POST['form_paydate']; ?>'
637 onkeyup='datekeyup(this,mypcc)' onblur='dateblur(this,mypcc)'
638 title='<?php xl("Date of payment yyyy-mm-dd", "e"); ?>'>
639 </td>
641 <td>
642 <?php xl('Deposit Date:', 'e'); ?>
643 </td>
644 <td>
645 <input type='text' name='form_deposit_date' size='10' value='<?php echo $_POST['form_deposit_date']; ?>'
646 onkeyup='datekeyup(this,mypcc)' onblur='dateblur(this,mypcc)'
647 title='<?php xl("Date of bank deposit yyyy-mm-dd", "e"); ?>'>
648 </td>
650 <td>
651 <?php xl('Amount:', 'e'); ?>
652 </td>
653 <td>
654 <input type='text' name='form_amount' size='10' value='<?php echo $_POST['form_amount']; ?>'
655 title='<?php xl("Paid amount that you will allocate", "e"); ?>'>
656 </td>
657 <td align='right'>
658 <a href='sl_eob_help.php' target='_blank'><?php xl('Help', 'e'); ?></a>
659 </td>
661 </tr>
662 </table>
664 <table border='0' cellpadding='5' cellspacing='0'>
666 <tr bgcolor='#ddddff'>
667 <td>
668 <?php xl('Name:', 'e'); ?>
669 </td>
670 <td>
671 <input type='text' name='form_name' size='10' value='<?php echo $_POST['form_name']; ?>'
672 title='<?php xl("Any part of the patient name, or \"last,first\", or \"X-Y\"", "e"); ?>'>
673 </td>
674 <td>
675 <?php xl('Chart ID:', 'e'); ?>
676 </td>
677 <td>
678 <input type='text' name='form_pid' size='10' value='<?php echo $_POST['form_pid']; ?>'
679 title='<?php xl("Patient chart ID", "e"); ?>'>
680 </td>
681 <td>
682 <?php xl('Encounter:', 'e'); ?>
683 </td>
684 <td>
685 <input type='text' name='form_encounter' size='10' value='<?php echo $_POST['form_encounter']; ?>'
686 title='<?php xl("Encounter number", "e"); ?>'>
687 </td>
688 <td>
689 <?php xl('Svc Date:', 'e'); ?>
690 </td>
691 <td>
692 <input type='text' name='form_date' size='10' value='<?php echo $_POST['form_date']; ?>'
693 title='<?php xl("Date of service mm/dd/yyyy", "e"); ?>'>
694 </td>
695 <td>
696 <?php xl('To:', 'e'); ?>
697 </td>
698 <td>
699 <input type='text' name='form_to_date' size='10' value='<?php echo $_POST['form_to_date']; ?>'
700 title='<?php xl("Ending DOS mm/dd/yyyy if you wish to enter a range", "e"); ?>'>
701 </td>
702 <td>
703 <select name='form_category'>
704 <?php
705 foreach (array(xl('Open'), xl('All'), xl('Due Pt'), xl('Due Ins')) as $value) {
706 echo " <option value='$value'";
707 if ($_POST['form_category'] == $value) {
708 echo " selected";
711 echo ">$value</option>\n";
714 </select>
715 </td>
716 <td>
717 <input type='submit' name='form_search' value='<?php xl("Search", "e"); ?>'>
718 </td>
719 </tr>
720 <!-- Filter - only show those who have debt -->
721 <tr bgcolor='#ddddff'>
722 <td colspan='12'>
724 <span><?php echo xlt('Patients with debt');?>
725 <input <?php echo $_POST['only_with_debt']?'checked=checked':'';?> type="checkbox" name="only_with_debt" />
726 </span>
728 </td>
729 </tr>
730 <!-- Support for X12 835 upload -->
731 <tr bgcolor='#ddddff'>
732 <td colspan='12'>
733 <?php xl('Or upload ERA file:', 'e'); ?>
734 <input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
735 <input name="form_erafile" type="file" />
736 </td>
737 </tr>
739 <tr>
740 <td height="1" colspan="10">
741 </td>
742 </tr>
744 </table>
746 <?php
747 if ($_POST['form_search'] || $_POST['form_print']) {
748 $form_name = trim($_POST['form_name']);
749 $form_pid = trim($_POST['form_pid']);
750 $form_encounter = trim($_POST['form_encounter']);
751 $form_date = fixDate($_POST['form_date'], "");
752 $form_to_date = fixDate($_POST['form_to_date'], "");
754 $where = "";
756 // Handle X12 835 file upload.
758 if ($_FILES['form_erafile']['size']) {
759 $tmp_name = $_FILES['form_erafile']['tmp_name'];
761 // Handle .zip extension if present. Probably won't work on Windows.
762 if (strtolower(substr($_FILES['form_erafile']['name'], -4)) == '.zip') {
763 rename($tmp_name, "$tmp_name.zip");
764 exec("unzip -p $tmp_name.zip > $tmp_name");
765 unlink("$tmp_name.zip");
768 echo "<!-- Notes from ERA upload processing:\n";
769 $alertmsg .= parse_era($tmp_name, 'era_callback');
770 echo "-->\n";
771 $erafullname = $GLOBALS['OE_SITE_DIR'] . "/era/$eraname.edi";
773 if (is_file($erafullname)) {
774 $alertmsg .= "Warning: Set $eraname was already uploaded ";
775 if (is_file($GLOBALS['OE_SITE_DIR'] . "/era/$eraname.html")) {
776 $alertmsg .= "and processed. ";
777 } else {
778 $alertmsg .= "but not yet processed. ";
782 rename($tmp_name, $erafullname);
783 } // End 835 upload
785 if ($eracount) {
786 // Note that parse_era() modified $eracount and $where.
787 if (! $where) {
788 $where = '1 = 2';
790 } else {
791 if ($form_name) {
792 if ($where) {
793 $where .= " AND ";
796 // Allow the last name to be followed by a comma and some part of a first name.
797 if (preg_match('/^(.*\S)\s*,\s*(.*)/', $form_name, $matches)) {
798 $where .= "p.lname LIKE '" . $matches[1] . "%' AND p.fname LIKE '" . $matches[2] . "%'";
799 // Allow a filter like "A-C" on the first character of the last name.
800 } else if (preg_match('/^(\S)\s*-\s*(\S)$/', $form_name, $matches)) {
801 $tmp = '1 = 2';
802 while (ord($matches[1]) <= ord($matches[2])) {
803 $tmp .= " OR p.lname LIKE '" . $matches[1] . "%'";
804 $matches[1] = chr(ord($matches[1]) + 1);
807 $where .= "( $tmp ) ";
808 } else {
809 $where .= "p.lname LIKE '%$form_name%'";
813 if ($form_pid) {
814 if ($where) {
815 $where .= " AND ";
818 $where .= "f.pid = '$form_pid'";
821 if ($form_encounter) {
822 if ($where) {
823 $where .= " AND ";
826 $where .= "f.encounter = '$form_encounter'";
829 if ($form_date) {
830 if ($where) {
831 $where .= " AND ";
834 if ($form_to_date) {
835 $where .= "f.date >= '$form_date' AND f.date <= '$form_to_date'";
836 } else {
837 $where .= "f.date = '$form_date'";
841 if (! $where) {
842 if ($_POST['form_category'] == 'All') {
843 die(xl("At least one search parameter is required if you select All."));
844 } else {
845 $where = "1 = 1";
850 // Notes that as of release 4.1.1 the copays are stored
851 // in the ar_activity table marked with a PCP in the account_code column.
852 $query = "SELECT f.id, f.pid, f.encounter, f.date, " .
853 "f.last_level_billed, f.last_level_closed, f.last_stmt_date, f.stmt_count, " .
854 "p.fname, p.mname, p.lname, p.pubpid, p.billing_note, " .
855 "( SELECT SUM(b.fee) FROM billing AS b WHERE " .
856 "b.pid = f.pid AND b.encounter = f.encounter AND " .
857 "b.activity = 1 AND b.code_type != 'COPAY' ) AS charges, " .
858 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
859 "a.pid = f.pid AND a.encounter = f.encounter AND a.payer_type = 0 AND a.account_code = 'PCP')*-1 AS copays, " .
860 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
861 "a.pid = f.pid AND a.encounter = f.encounter AND a.account_code != 'PCP') AS payments, " .
862 "( SELECT SUM(a.adj_amount) FROM ar_activity AS a WHERE " .
863 "a.pid = f.pid AND a.encounter = f.encounter ) AS adjustments " .
864 "FROM form_encounter AS f " .
865 "JOIN patient_data AS p ON p.pid = f.pid " .
866 "WHERE $where " .
867 "ORDER BY p.lname, p.fname, p.mname, f.pid, f.encounter";
869 // Note that unlike the SQL-Ledger case, this query does not weed
870 // out encounters that are paid up. Also the use of sub-selects
871 // will require MySQL 4.1 or greater.
873 // echo "<!-- $query -->\n"; // debugging
875 $t_res = sqlStatement($query);
877 $num_invoices = sqlNumRows($t_res);
878 if ($eracount && $num_invoices != $eracount) {
879 $alertmsg .= "Of $eracount remittances, there are $num_invoices " .
880 "matching encounters in OpenEMR. ";
884 <table border='0' cellpadding='1' cellspacing='2' width='98%'>
886 <tr bgcolor="#dddddd">
887 <td class="id">
888 <?php xl('id', 'e');?>
889 </td>
890 <td class="dehead">
891 &nbsp;<?php xl('Patient', 'e'); ?>
892 </td>
893 <td class="dehead">
894 &nbsp;<?php xl('Invoice', 'e'); ?>
895 </td>
896 <td class="dehead">
897 &nbsp;<?php xl('Svc Date', 'e'); ?>
898 </td>
899 <td class="dehead">
900 &nbsp;<?php xl('Last Stmt', 'e'); ?>
901 </td>
902 <td class="dehead" align="right">
903 <?php xl('Charge', 'e'); ?>&nbsp;
904 </td>
905 <td class="dehead" align="right">
906 <?php xl('Adjust', 'e'); ?>&nbsp;
907 </td>
908 <td class="dehead" align="right">
909 <?php xl('Paid', 'e'); ?>&nbsp;
910 </td>
911 <td class="dehead" align="right">
912 <?php xl('Balance', 'e'); ?>&nbsp;
913 </td>
914 <td class="dehead" align="center">
915 <?php xl('Prv', 'e'); ?>
916 </td>
917 <?php if (!$eracount) { ?>
918 <td class="dehead" align="left">
919 <?php xl('Sel', 'e'); ?>
920 </td>
921 <td class="dehead" align="center">
922 <?php xl('Email', 'e'); ?>
923 </td>
925 <?php } ?>
926 </tr>
928 <?php
929 $orow = -1;
931 while ($row = sqlFetchArray($t_res)) {
932 $balance = sprintf("%.2f", $row['charges'] + $row['copays'] - $row['payments'] - $row['adjustments']);
933 //new filter only patients with debt.
934 if ($_POST['only_with_debt'] && $balance <= 0) {
935 continue;
939 if ($_POST['form_category'] != 'All' && $eracount == 0 && $balance == 0) {
940 continue;
943 // $duncount was originally supposed to be the number of times that
944 // the patient was sent a statement for this invoice.
946 $duncount = $row['stmt_count'];
948 // But if we have not yet billed the patient, then compute $duncount as a
949 // negative count of the number of insurance plans for which we have not
950 // yet closed out insurance.
952 if (! $duncount) {
953 for ($i = 1; $i <= 3 && arGetPayerID($row['pid'], $row['date'], $i);
954 ++$i) {
957 $duncount = $row['last_level_closed'] + 1 - $i;
960 $isdueany = ($balance > 0);
962 // An invoice is now due from the patient if money is owed and we are
963 // not waiting for insurance to pay.
965 $isduept = ($duncount >= 0 && $isdueany) ? " checked" : "";
967 // Skip invoices not in the desired "Due..." category.
969 if (substr($_POST['form_category'], 0, 3) == 'Due' && !$isdueany) {
970 continue;
973 if ($_POST['form_category'] == 'Due Ins' && ($duncount >= 0 || !$isdueany)) {
974 continue;
977 if ($_POST['form_category'] == 'Due Pt' && ($duncount < 0 || !$isdueany)) {
978 continue;
981 $bgcolor = ((++$orow & 1) ? "#ffdddd" : "#ddddff");
983 $svcdate = substr($row['date'], 0, 10);
984 $last_stmt_date = empty($row['last_stmt_date']) ? '' : $row['last_stmt_date'];
986 // Determine if customer is in collections.
988 $billnote = $row['billing_note'];
989 $in_collections = stristr($billnote, 'IN COLLECTIONS') !== false;
991 <tr bgcolor='<?php echo $bgcolor ?>'>
992 <td class="detail">
993 <a href="" onclick="return npopup(<?php echo $row['pid'] ?>)"><?php echo $row['pid'];?></a>
994 </td>
995 <td class="detail">
996 &nbsp;<a href="" onclick="return npopup(<?php echo $row['pid'] ?>)"
997 ><?php echo $row['lname'] . ', ' . $row['fname']; ?></a>
998 </td>
999 <td class="detail">
1000 &nbsp;<a href="sl_eob_invoice.php?id=<?php echo $row['id'] ?>"
1001 target="_blank"><?php echo $row['pid'] . '.' . $row['encounter']; ?></a>
1002 </td>
1003 <td class="detail">
1004 &nbsp;<?php echo oeFormatShortDate($svcdate) ?>
1005 </td>
1006 <td class="detail">
1007 &nbsp;<?php echo oeFormatShortDate($last_stmt_date) ?>
1008 </td>
1009 <td class="detail" align="right">
1010 <?php bucks($row['charges']) ?>&nbsp;
1011 </td>
1012 <td class="detail" align="right">
1013 <?php bucks($row['adjustments']) ?>&nbsp;
1014 </td>
1015 <td class="detail" align="right">
1016 <?php bucks($row['payments'] - $row['copays']); ?>&nbsp;
1017 </td>
1018 <td class="detail" align="right">
1019 <?php bucks($balance); ?>&nbsp;
1020 </td>
1021 <td class="detail" align="center">
1022 <?php echo $duncount ? $duncount : "&nbsp;" ?>
1023 </td>
1024 <?php if (!$eracount) { ?>
1025 <td class="detail" align="left">
1026 <input type='checkbox' name='form_cb[<?php echo($row['id']) ?>]'<?php echo $isduept ?> />
1027 <?php if ($in_collections) {
1028 echo "<b><font color='red'>IC</font></b>";
1029 } ?>
1030 <?php if (function_exists('is_auth_portal') ? is_auth_portal($row['pid']) : false) {
1031 echo(' PPt');
1032 echo("<input type='hidden' name='form_invpids[". $row['id'] ."][". $row['pid'] ."]' />");
1033 $is_portal = true;
1035 </td>
1036 <?php } ?>
1037 <td class="detail" align="left">
1038 <?php
1039 $patientData = sqlQuery("SELECT * FROM `patient_data` WHERE `pid`=?", array($row['pid']));
1040 if ($patientData['hipaa_allowemail'] == "YES" && $patientData['allow_patient_portal'] == "YES" && $patientData['hipaa_notice'] == "YES" && validEmail($patientData['email'])) {
1041 echo xlt("YES");
1042 } else {
1043 echo xlt("NO");
1046 </td>
1048 </tr>
1049 <?php
1050 } // end while
1051 } // end search/print logic
1055 </table>
1058 <?php if ($eracount) { ?>
1059 <input type='button' value='<?php xl('Process ERA File', 'e')?>' onclick='processERA()' /> &nbsp;
1060 <?php } else { ?>
1061 <input type='button' value='<?php xl('Select All', 'e')?>' onclick='checkAll(true)' /> &nbsp;
1062 <input type='button' value='<?php xl('Clear All', 'e')?>' onclick='checkAll(false)' /> &nbsp;
1063 <?php if ($GLOBALS['statement_appearance'] != '1') { ?>
1064 <input type='submit' name='form_print' value='<?php xl('Print Selected Statements', 'e'); ?>' /> &nbsp;
1065 <input type='submit' name='form_download' value='<?php xl('Download Selected Statements', 'e'); ?>' /> &nbsp;
1066 <?php } ?>
1067 <input type='submit' name='form_pdf' value='<?php xl('PDF Download Selected Statements', 'e'); ?>' /> &nbsp;
1068 <input type='submit' name='form_email' value='<?php xl('Email Selected Statements', 'e'); ?>' /> &nbsp;
1069 <?php if ($is_portal) {?>
1070 <input type='submit' name='form_portalnotify' value='<?php xl('Notify via Patient Portal', 'e'); ?>' /> &nbsp;
1071 <?php }
1073 <input type='checkbox' name='form_without' value='1' /> <?php xl('Without Update', 'e'); ?>
1074 </p>
1076 </form>
1077 </center>
1078 <script language="JavaScript">
1079 function processERA() {
1080 var f = document.forms[0];
1081 var debug = f.form_without.checked ? '1' : '0';
1082 var paydate = f.form_paydate.value;
1083 window.open('sl_eob_process.php?eraname=<?php echo $eraname ?>&debug=' + debug + '&paydate=' + paydate + '&original=original', '_blank');
1084 return false;
1086 <?php
1087 if ($alertmsg) {
1088 echo "alert('" . htmlentities($alertmsg) . "');\n";
1092 </script>
1093 </body>
1094 </html>