3 * This the first of two pages to support posting of EOBs.
4 * The second is sl_eob_invoice.php.
7 * @link http://www.open-emr.org
8 * @author Rod Roark <rod@sunsetsystems.com>
9 * @author Bill Cernansky
10 * @author Tony McCormick
11 * @author Roberto Vasquez <robertogagliotta@gmail.com>
12 * @author Jerry Padgett <sjpadgett@gmail.com>
13 * @author Brady Miller <brady.g.miller@gmail.com>
14 * @copyright Copyright (c) 2005-2010 Rod Roark <rod@sunsetsystems.com>
15 * @copyright Copyright (c) 2018 Brady Miller <brady.g.miller@gmail.com>
16 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
19 require_once("../globals.php");
20 require_once("$srcdir/patient.inc");
21 require_once("$srcdir/invoice_summary.inc.php");
22 require_once("$srcdir/appointments.inc.php");
23 require_once($GLOBALS['OE_SITE_DIR'] . "/statement.inc.php");
24 require_once("$srcdir/parse_era.inc.php");
25 require_once("$srcdir/sl_eob.inc.php");
26 require_once("$srcdir/api.inc");
27 require_once("$srcdir/forms.inc");
28 require_once("$srcdir/../controllers/C_Document.class.php");
29 require_once("$srcdir/documents.php");
30 require_once("$srcdir/options.inc.php");
31 require_once("$srcdir/acl.inc");
33 use OpenEMR\Core\Header
;
35 $DEBUG = 0; // set to 0 for production, 1 to test
41 /* Load dependencies only if we need them */
42 if (! empty($GLOBALS['portal_onsite_two_enable'])) {
43 /* Addition of onsite portal patient notify of invoice and reformated invoice - sjpadgett 01/2017 */
44 require_once("../../portal/lib/portal_mail.inc");
45 require_once("../../portal/lib/appsql.class.php");
47 function is_auth_portal($pid = 0)
49 if ($pData = sqlQuery("SELECT * FROM `patient_data` WHERE `pid` = ?", array($pid))) {
50 if ($pData['allow_patient_portal'] != "YES") {
53 $_SESSION['portalUser'] = strtolower($pData['fname']) . $pData['id'];
61 function notify_portal($thispid, array $invoices, $template, $invid)
63 $builddir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates/' . $thispid;
64 if (! is_dir($builddir)) {
65 mkdir($builddir, 0755, true);
68 if (fixup_invoice($template, $builddir . '/invoice' . $invid . '.tpl') != true) {
72 if (SavePatientAudit($thispid, $invoices) != true) {
74 } // this is all the invoice data for portal auditing
75 $note = xl('You have an invoice due for payment in your Patient Documents. There you may pay, download or print the invoice. Thank you.');
76 if (sendMail($_SESSION['authUser'], $note, xlt('Bill/Collect'), '', '0', $_SESSION['authUser'], $_SESSION['authUser'], $_SESSION['portalUser'], $invoices[0]['patient'], "New", '0') == 1) { // remind admin this was sent
77 sendMail($_SESSION['portalUser'], $note, xlt('Bill/Collect'), '', '0', $_SESSION['authUser'], $_SESSION['authUser'], $_SESSION['portalUser'], $invoices[0]['patient'], "New", '0'); // notify patient
85 function fixup_invoice($template, $ifile)
87 $data = file_get_contents($template);
92 if (! file_put_contents($ifile, $data)) {
99 function SavePatientAudit($pid, $invs)
101 $appsql = new ApplicationTable();
104 $audit['patient_id'] = $pid;
105 $audit['activity'] = "invoice";
106 $audit['require_audit'] = "0";
107 $audit['pending_action'] = "payment";
108 $audit['action_taken'] = "";
109 $audit['status'] = "waiting transaction";
110 $audit['narrative'] = "Request patient online payment.";
111 $audit['table_action'] = '';
112 $audit['table_args'] = json_encode($invs);
113 $audit['action_user'] = $pid;
114 $audit['action_taken_time'] = "";
115 $audit['checksum'] = "";
116 $edata = $appsql->getPortalAudit($pid, 'payment', 'invoice', "waiting transaction", 0);
117 if ($edata['id'] > 0) {
118 $appsql->portalAudit('update', $edata['id'], $audit);
120 $appsql->portalAudit('insert', '', $audit);
122 } catch (Exception
$ex) {
130 // This is called back by parse_era() if we are processing X12 835's.
131 function era_callback(&$out)
133 global $where, $eracount, $eraname;
134 // print_r($out); // debugging
136 // $eraname = $out['isa_control_number'];
137 $eraname = $out['gs_date'] . '_' . ltrim($out['isa_control_number'], '0') .
138 '_' . ltrim($out['payer_id'], '0');
139 list($pid, $encounter, $invnumber) = slInvoiceNumber($out);
141 if ($pid && $encounter) {
146 $where .= "( f.pid = '" . add_escape_custom($pid) . "' AND f.encounter = '" . add_escape_custom($encounter) . "' )";
150 function bucks($amount)
153 return oeFormatMoney($amount);
157 function validEmail($email)
159 if (preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email)) {
166 function emailLogin($patient_id, $message)
168 $patientData = sqlQuery("SELECT * FROM `patient_data` WHERE `pid`=?", array($patient_id));
169 if ($patientData['hipaa_allowemail'] != "YES" ||
empty($patientData['email']) ||
empty($GLOBALS['patient_reminder_sender_email'])) {
173 if (!(validEmail($patientData['email']))) {
177 if (!(validEmail($GLOBALS['patient_reminder_sender_email']))) {
181 if ($_SESSION['pc_facility']) {
182 $sql = "select * from facility where id=?";
183 $facility = sqlQuery($sql, array($_SESSION['pc_facility']));
185 $sql = "SELECT * FROM facility ORDER BY billing_location DESC LIMIT 1";
186 $facility = sqlQuery($sql);
189 $mail = new MyMailer();
190 $pt_name=$patientData['fname'].' '.$patientData['lname'];
191 $pt_email=$patientData['email'];
192 $email_subject=($facility['name'] . ' ' . xl('Patient Statement Bill'));
193 $email_sender=$GLOBALS['patient_reminder_sender_email'];
194 $mail->AddReplyTo($email_sender, $email_sender);
195 $mail->SetFrom($email_sender, $email_sender);
196 $mail->AddAddress($pt_email, $pt_name);
197 $mail->Subject
= $email_subject;
198 $mail->MsgHTML("<html><body><div class='wrapper'>".$message."</div></body></html>");
200 $mail->AltBody
= $message;
205 $email_status = $mail->ErrorInfo
;
206 error_log("EMAIL ERROR: ".$email_status, 0);
211 // Upload a file to the client's browser
213 function upload_file_to_client($file_to_send)
215 header("Pragma: public");
216 header("Expires: 0");
217 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
218 header("Content-Type: application/force-download");
219 header("Content-Length: " . filesize($file_to_send));
220 header("Content-Disposition: attachment; filename=" . basename($file_to_send));
221 header("Content-Description: File Transfer");
222 readfile($file_to_send);
223 // flush the content to the browser. If you don't do this, the text from the subsequent
224 // output from this script will be in the file instead of sent to the browser.
226 exit(); //added to exit from process properly in order to stop bad html code -ehrlive
227 // sleep one second to ensure there's no follow-on.
231 function upload_file_to_client_email($ppid, $file_to_send)
234 global $STMT_TEMP_FILE_PDF;
235 $file = fopen($file_to_send, "r");//this file contains the text to be converted to pdf.
236 while (!feof($file)) {
237 $OneLine=fgets($file);//one line is read
239 $message = $message.$OneLine.'<br>';
244 emailLogin($ppid, $message);
247 function upload_file_to_client_pdf($file_to_send, $aPatFirstName = '', $aPatID = null, $flagCFN = false)
249 //modified for statement title name
250 //Function reads a HTML file and converts to pdf.
252 $aPatFName = convert_safe_file_dir_name($aPatFirstName); //modified for statement title name
254 $STMT_TEMP_FILE_PDF = $GLOBALS['temporary_files_dir'] . "/Stmt_{$aPatFName}_{$aPatID}.pdf";
256 global $STMT_TEMP_FILE_PDF;
261 if ($GLOBALS['statement_appearance'] == '1') {
262 require_once("$srcdir/html2pdf/vendor/autoload.php");
263 $pdf2 = new HTML2PDF(
264 $GLOBALS['pdf_layout'],
265 $GLOBALS['pdf_size'],
266 $GLOBALS['pdf_language'],
267 true, // default unicode setting is true
268 'UTF-8', // default encoding setting is UTF-8
269 array($GLOBALS['pdf_left_margin'], $GLOBALS['pdf_top_margin'], $GLOBALS['pdf_right_margin'], $GLOBALS['pdf_bottom_margin']),
270 $_SESSION['language_direction'] == 'rtl' ?
true : false
273 readfile($file_to_send, "r");//this file contains the HTML to be converted to pdf.
275 $content = ob_get_clean();
277 // Fix a nasty html2pdf bug - it ignores document root!
278 global $web_root, $webserver_root;
280 $wrlen = strlen($web_root);
281 $wsrlen = strlen($webserver_root);
283 $i = stripos($content, " src='/", $i +
1);
288 if (substr($content, $i+
6, $wrlen) === $web_root &&
289 substr($content, $i+
6, $wsrlen) !== $webserver_root) {
290 $content = substr($content, 0, $i +
6) . $webserver_root . substr($content, $i +
6 +
$wrlen);
294 $pdf2->WriteHTML($content);
295 $temp_filename = $STMT_TEMP_FILE_PDF;
296 $content_pdf = $pdf2->Output($STMT_TEMP_FILE_PDF, 'F');
298 $pdf = new Cezpdf('LETTER');//pdf creation starts
299 $pdf->ezSetMargins(45, 9, 36, 10);
300 $pdf->selectFont('Courier');
301 $pdf->ezSetY($pdf->ez
['pageHeight'] - $pdf->ez
['topMargin']);
303 $file = fopen($file_to_send, "r");//this file contains the text to be converted to pdf.
304 while (!feof($file)) {
305 $OneLine=fgets($file);//one line is read
306 if (stristr($OneLine, "\014") == true && !feof($file)) {//form feed means we should start a new page.
308 $pdf->ezSetY($pdf->ez
['pageHeight'] - $pdf->ez
['topMargin']);
309 str_replace("\014", "", $OneLine);
312 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.
313 $pdf->ezText('<b>'.$OneLine.'</b>', 12, array('justification' => 'left', 'leading' => 6));
315 $pdf->ezText($OneLine, 12, array('justification' => 'left', 'leading' => 6));
321 $fh = @fopen
($STMT_TEMP_FILE_PDF, 'w');//stored to a pdf file
323 fwrite($fh, $pdf->ezOutput());
328 header("Pragma: public");//this section outputs the pdf file to browser
329 header("Expires: 0");
330 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
331 header("Content-Type: application/force-download");
332 header("Content-Length: " . filesize($STMT_TEMP_FILE_PDF));
333 header("Content-Disposition: attachment; filename=" . basename($STMT_TEMP_FILE_PDF));
334 header("Content-Description: File Transfer");
335 readfile($STMT_TEMP_FILE_PDF);
336 // flush the content to the browser. If you don't do this, the text from the subsequent
337 // output from this script will be in the file instead of sent to the browser.
339 exit(); //added to exit from process properly in order to stop bad html code -ehrlive
340 // sleep one second to ensure there's no follow-on.
345 $today = date("Y-m-d");
346 // Print or download statements if requested.
348 if (($_POST['form_print'] ||
$_POST['form_download'] ||
$_POST['form_email'] ||
$_POST['form_pdf']) ||
$_POST['form_portalnotify'] && $_POST['form_cb']) {
349 if (!verifyCsrfToken($_POST["csrf_token_form"])) {
350 die(xlt('Authentication Error'));
353 $fhprint = fopen($STMT_TEMP_FILE, 'w');
355 $sqlBindArray = array();
357 foreach ($_POST['form_cb'] as $key => $value) {
358 $where .= " OR f.id = ?";
359 array_push($sqlBindArray, $key);
362 if (!empty($where)) {
363 $where = substr($where, 4);
364 $where = '( ' . $where . ' ) AND';
367 $res = sqlStatement("SELECT " .
368 "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, " .
369 "p.fname, p.mname, p.lname, p.street, p.city, p.state, p.postal_code, p.billing_note as pat_billing_note " .
370 "FROM form_encounter AS f, patient_data AS p " .
373 "ORDER BY p.lname, p.fname, f.pid, f.date, f.encounter", $sqlBindArray);
379 $aPatientFirstName = '';
381 $multiplePatients = false;
382 $usePatientNamePdf = false;
384 // get pids for delimits
385 // need to only use summary invoice for multi visits
388 if ($_POST['form_portalnotify']) {
389 foreach ($_POST['form_invpids'] as $key => $v) {
390 if ($_POST['form_cb'][$key]) {
391 array_push($inv_pid, key($v));
396 while ($row = sqlFetchArray($res)) {
398 if (!$inv_pid[$rcnt]) {
399 array_push($inv_pid, $row['pid']);
403 // This loops once for each invoice/encounter.
406 while ($row = $rows[$rcnt++
]) {
407 $svcdate = substr($row['date'], 0, 10);
408 $duedate = $svcdate; // TBD?
409 $duncount = $row['stmt_count'];
410 $enc_note = $row['enc_billing_note'];
414 $aPatientFirstName = $row['fname'];
415 $aPatientID = $row['pid'];
416 $usePatientNamePdf = true;
417 } elseif (!$multiplePatients) {
418 if ($aPatientID != $row['pid']) {
419 $multiplePatients = true;
420 $aPatientFirstName = '';
422 $usePatientNamePdf = false;
426 // If this is a new patient then print the pending statement
427 // and start a new one. This is an associative array:
430 // pid = OpenEMR patient ID
431 // patient = patient name
432 // amount = total amount due
433 // adjust = adjustments (already applied to amount)
434 // duedate = due date of the oldest included invoice
435 // age = number of days from duedate to today
436 // to = array of addressee name/address lines
438 // dos = date of service "yyyy-mm-dd"
439 // desc = description
440 // amount = charge less adjustments
441 // paid = amount paid
442 // notice = 1 for first notice, 2 for second, etc.
443 // detail = array of details, see invoice_summary.inc.php
445 if ($stmt['cid'] != $row['pid']) {
450 $stmt['cid'] = $row['pid'];
451 $stmt['pid'] = $row['pid'];
452 $stmt['dun_count'] = $row['stmt_count'];
453 $stmt['bill_note'] = $row['pat_billing_note'];
454 $stmt['enc_bill_note'] = $row['enc_billing_note'];
455 $stmt['bill_level'] = $row['last_level_billed'];
456 $stmt['level_closed'] = $row['last_level_closed'];
457 $stmt['patient'] = $row['fname'] . ' ' . $row['lname'];
458 $stmt['encounter'] = $row['encounter'];
459 #If you use the field in demographics layout called
460 #guardiansname this will allow you to send statements to the parent
461 #of a child or a guardian etc
462 if (strlen($row['guardiansname']) == 0) {
463 $stmt['to'] = array($row['fname'] . ' ' . $row['lname']);
465 $stmt['to'] = array($row['guardiansname']);
468 if ($row['street']) {
469 $stmt['to'][] = $row['street'];
472 $stmt['to'][] = $row['city'] . ", " . $row['state'] . " " . $row['postal_code'];
473 $stmt['lines'] = array();
474 $stmt['amount'] = '0.00';
475 $stmt['ins_paid'] = 0;
476 $stmt['today'] = $today;
477 $stmt['duedate'] = $duedate;
479 // Report the oldest due date.
480 if ($duedate < $stmt['duedate']) {
481 $stmt['duedate'] = $duedate;
485 // Recompute age at each invoice.
486 $stmt['age'] = round((strtotime($today) - strtotime($stmt['duedate'])) / (24 * 60 * 60));
488 $invlines = ar_get_invoice_summary($row['pid'], $row['encounter'], true);
489 foreach ($invlines as $key => $value) {
491 $line['dos'] = $svcdate;
492 if ($GLOBALS['use_custom_statement']) {
493 $line['desc'] = ($key == 'CO-PAY') ?
"Patient Payment" : $value['code_text'];
495 $line['desc'] = ($key == 'CO-PAY') ?
"Patient Payment" : "Procedure $key";
498 $line['amount'] = sprintf("%.2f", $value['chg']);
499 $line['adjust'] = sprintf("%.2f", $value['adj']);
500 $line['paid'] = sprintf("%.2f", $value['chg'] - $value['bal']);
501 $line['notice'] = $duncount +
1;
502 $line['detail'] = $value['dtl'];
503 $stmt['lines'][] = $line;
504 $stmt['amount'] = sprintf("%.2f", $stmt['amount'] +
$value['bal']);
505 $stmt['ins_paid'] = $stmt['ins_paid'] +
$value['ins'];
508 // Record that this statement was run.
509 if (! $DEBUG && ! $_POST['form_without']) {
510 sqlStatement("UPDATE form_encounter SET " .
511 "last_stmt_date = ?, stmt_count = stmt_count + 1 " .
512 "WHERE id = ?", array($today, $row['id']));
515 if ($_POST['form_portalnotify']) {
516 if (! is_auth_portal($stmt['pid'])) {
517 $alertmsg = xlt('Notification FAILED: Not Portal Authorized');
521 // we don't want to send the portal multiple invoices, thus this. Last invoice for pid is summary.
522 if ($inv_pid[$inv_count] != $inv_pid[$inv_count +
1]) {
523 fwrite($fhprint, make_statement($stmt));
524 if (! notify_portal($stmt['pid'], $pvoice, $STMT_TEMP_FILE, $stmt['pid'] . "-" . $stmt['encounter'])) {
525 $alertmsg = xlt('Notification FAILED');
531 ftruncate($fhprint, 0);
536 if ($inv_pid[$inv_count] != $inv_pid[$inv_count +
1]) {
537 $tmp = make_statement($stmt);
539 $tmp = xlt("This EOB item does not meet minimum print requirements setup in Globals or there is an unknown error.") . " " . xlt("EOB Id") . ":" . text($inv_pid[$inv_count]) . " " . xlt("Encounter") . ":" . text($stmt[encounter
]) . "\n";
540 $tmp .= "<br />\n\014<br /><br />";
542 fwrite($fhprint, $tmp);
553 // Download or print the file, as selected
554 if ($_POST['form_download']) {
555 upload_file_to_client($STMT_TEMP_FILE);
556 } elseif ($_POST['form_pdf']) {
557 upload_file_to_client_pdf($STMT_TEMP_FILE, $aPatientFirstName, $aPatientID, $usePatientNamePdf);
558 } elseif ($_POST['form_email']) {
559 upload_file_to_client_email($stmt['pid'], $STMT_TEMP_FILE);
560 } elseif ($_POST['form_portalnotify']) {
561 if ($alertmsg == "") {
562 $alertmsg = xl('Sending Invoice to Patient Portal Completed');
564 } else { // Must be print!
566 $alertmsg = xl("Printing skipped; see test output in") .' '. $STMT_TEMP_FILE;
568 exec(escapeshellcmd($STMT_PRINT_CMD) . " " . escapeshellarg($STMT_TEMP_FILE));
569 if ($_POST['form_without']) {
570 $alertmsg = xl('Now printing') .' '. $stmt_count .' '. xl('statements; invoices will not be updated.');
572 $alertmsg = xl('Now printing') .' '. $stmt_count .' '. xl('statements and updating invoices.');
575 } // end not form_download
576 } // end statements requested
580 <?php Header
::setupHeader(['datetime-picker']);?
>
581 <title
><?php
echo xlt('EOB Posting - Search'); ?
></title
>
582 <script language
="JavaScript">
585 function checkAll(checked
) {
586 var f
= document
.forms
[0];
587 for (var i
= 0; i
< f
.elements
.length
; ++i
) {
588 var ename
= f
.elements
[i
].name
;
589 if (ename
.indexOf('form_cb[') == 0)
590 f
.elements
[i
].checked
= checked
;
594 function npopup(pid
) {
595 window
.open('sl_eob_patient_note.php?patient_id=' + pid
, '_blank', 'width=500,height=250,resizable=1');
598 $
(document
).ready(function() {
599 $
('.datepicker').datetimepicker({
600 <?php
$datetimepicker_timepicker = false; ?
>
601 <?php
$datetimepicker_showseconds = false; ?
>
602 <?php
$datetimepicker_formatInput = false; ?
>
603 <?php
require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php'); ?
>
604 <?php
// can add any additional javascript settings to datetimepicker here; need to prepend first setting with a comma ?>
610 @media only screen
and (max
-width
: 768px
) {
613 text
-align
:left
!Important
;
616 @media only screen
and (max
-width
: 1004px
) and (min
-width
: 641px
) {
621 display
: inline
-block
;
628 .modal
-body
, .modal
-body
* {
641 if ($GLOBALS['enable_help'] == 1) {
642 $help_icon = '<a class="pull-right oe-help-redirect" data-target="#myModal" data-toggle="modal" href="#" id="help-href" name="help-href" style="color:#676666" title="' . xla("Click to view Help") . '"><i class="fa fa-question-circle" aria-hidden="true"></i></a>';
643 } elseif ($GLOBALS['enable_help'] == 2) {
644 $help_icon = '<a class="pull-right oe-help-redirect" data-target="#myModal" data-toggle="modal" href="#" id="help-href" name="help-href" style="color:#DCD6D0 !Important" title="' . xla("Enable help in Administration > Globals > Features > Enable Help Modal") . '"><i class="fa fa-question-circle" aria-hidden="true"></i></a>';
645 } elseif ($GLOBALS['enable_help'] == 0) {
653 <div
class="container">
655 <div
class="page-header">
656 <h2
class="clearfix"><span id
='header_text'><?php
echo xlt('EOB Posting - Search'); ?
></span
> 
; 
; <a href
='sl_eob_search.php' onclick
='top.restoreSession()' title
="<?php echo xla('Reset'); ?>"><i id
='advanced-tooltip' class='fa fa-undo fa-2x small' aria
-hidden
='true'></i
> </a
><?php
echo $help_icon; ?
></h2
>
660 <form action
='sl_eob_search.php' enctype
='multipart/form-data' method
='post'>
661 <input type
="hidden" name
="csrf_token_form" value
="<?php echo attr(collectCsrfToken()); ?>" />
662 <fieldset id
="payment-allocate" class="oe-show-hide">
664  
;<?php
echo xlt('Post Item');?
><i id
="payment-info-do-not-remove"> </i
>
666 <div
class="col-xs-12 oe-custom-line">
667 <div
class="col-xs-3">
668 <label
class="control-label" for="form_payer_id"> <?php
echo xlt('Payer'); ?
>:</label
>
670 $insurancei = getInsuranceProviders();
671 echo " <select name='form_payer_id'id='form_payer_id' class='form-control'>\n";
672 echo " <option value='0'>-- " . xlt('Patient') . " --</option>\n";
673 foreach ($insurancei as $iid => $iname) {
674 echo "<option value='" . attr($iid) . "'";
675 if ($iid == $_POST['form_payer_id']) {
678 echo ">" . text($iname) . "</option>\n";
683 <div
class="col-xs-2">
684 <label
class="control-label" for="form_source"><?php
echo xlt('Source'); ?
>:</label
>
685 <input type
='text' name
='form_source' id
='form_source' class='form-control' value
='<?php echo attr($_POST['form_source
']); ?>' title
='<?php echo xla("A check number or claim number to identify the payment"); ?>'>
687 <div
class="col-xs-2">
688 <label
class="control-label" for="form_paydate"><?php
echo xlt('Pay Date'); ?
>:</label
>
689 <input type
='text' name
='form_paydate' id
='form_paydate' class='form-control datepicker' value
='<?php echo attr($_POST['form_paydate
']); ?>' onkeyup
='datekeyup(this,mypcc)' onblur
='dateblur(this,mypcc)' title
='<?php echo xla("Date of payment yyyy-mm-dd"); ?>'>
691 <div
class="col-xs-2">
692 <label
class="control-label oe-large" for="form_deposit_date"><?php
echo xlt('Deposit Date'); ?
>:</label
>
693 <label
class="control-label oe-small" for="form_deposit_date"><?php
echo xlt('Dep Date'); ?
>:</label
>
694 <input type
='text' name
='form_deposit_date' id
=='form_deposit_date' class='form-control datepicker' value
='<?php echo attr($_POST['form_deposit_date
']); ?>' onkeyup
='datekeyup(this,mypcc)' onblur
='dateblur(this,mypcc)' title
='<?php echo xla("Date of bank deposit yyyy-mm-dd"); ?>'>
696 <div
class="col-xs-2">
697 <label
class="control-label" for="form_amount"><?php
echo xlt('Amount'); ?
>:</label
>
698 <input type
='text' name
='form_amount' id
='form_amount' class='form-control' value
='<?php echo attr($_POST['form_amount
']); ?>' title
='<?php echo xla("Paid amount that you will allocate"); ?>'>
700 <div
class="col-xs-1">
701 <label
class="control-label oe-large" for="only_with_debt"><?php
echo xlt('Pt Debt');?
>:</label
>
702 <label
class="control-label oe-small" for="only_with_debt"><?php
echo xlt('Debt');?
>:</label
>
703 <div
class="text-center">
704 <input
<?php
echo $_POST['only_with_debt']?
'checked=checked':'';?
> type
="checkbox" name
="only_with_debt" id
="only_with_debt" />
709 <fieldset id
="search-upload">
711  
;<span
><?php
echo xlt('Select Method');?
></span
> 
;<i id
='select-method-tooltip' class="fa fa-info-circle oe-superscript" aria
-hidden
="true"></i
>
712 <div id
="radio-div" class="pull-right oe-legend-radio">
713 <label
class="radio-inline">
714 <input type
="radio" id
="invoice_search" name
="radio-search" onclick
="" value
="inv-search"><?php
echo xlt('Invoice Search'); ?
>
716 <label
class="radio-inline">
717 <input type
="radio" id
="era_upload" name
="radio-search" onclick
="" value
="era-upld"><?php
echo xlt('ERA Upload'); ?
>
721 <input type
="hidden" id
="hid1" value
="<?php echo xla('Invoice Search');?>">
722 <input type
="hidden" id
="hid2" value
="<?php echo xla('ERA Upload');?>">
723 <input type
="hidden" id
="hid3" value
="<?php echo xla('Select Method');?>">
725 <div
class="col-xs-12 .oe-custom-line oe-show-hide" id
= 'inv-search'>
726 <div
class="col-xs-3">
727 <label
class="control-label" for="form_name"><?php
echo xlt('Name'); ?
>:</label
>
728 <input type
='text' name
='form_name' id
='form_name' class='form-control' value
='<?php echo attr($_POST['form_name
']); ?>' title
='<?php echo xla("Any part of the patient name, or \"last,first\", or \"X-Y\""); ?>' placeholder
= '<?php echo xla('Last name
, First name
');?>'>
730 <div
class="col-xs-2">
731 <label
class="control-label" for="form_pid"><?php
echo xlt('Chart ID'); ?
>:</label
>
732 <input type
='text' name
='form_pid' id
='form_pid' class='form-control' value
='<?php echo attr($_POST['form_pid
']); ?>' title
='<?php echo xla("Patient chart ID"); ?>'>
734 <div
class="col-xs-2">
735 <label
class="control-label" for="form_encounter"><?php
echo xlt('Encounter'); ?
>:</label
>
736 <input type
='text' name
='form_encounter' id
='form_encounter' class='form-control' value
='<?php echo attr($_POST['form_encounter
']); ?>' title
='<?php echo xla("Encounter number"); ?>'>
738 <div
class="col-xs-2">
739 <label
class="control-label oe-large" for="form_date"><?php
echo xlt('Service Date From'); ?
>:</label
>
740 <label
class="control-label oe-small" for="form_date"><?php
echo xlt('Svc Date'); ?
>:</label
>
741 <input type
='text' name
='form_date' id
='form_date' class='form-control datepicker' value
='<?php echo attr($_POST['form_date
']); ?>' title
='<?php echo xla("Date of service mm/dd/yyyy"); ?>'>
743 <div
class="col-xs-2">
744 <label
class="control-label" for="form_to_date"><?php
echo xlt('Service Date To'); ?
>:</label
>
745 <input type
='text' name
='form_to_date' id
='form_to_date' class='form-control datepicker' value
='<?php echo attr($_POST['form_to_date
']); ?>' title
='<?php echo xla("Ending DOS mm/dd/yyyy if you wish to enter a range"); ?>'>
747 <div
class="col-xs-1" style
="padding-right:0px">
748 <label
class="control-label" for="type_name"><?php
echo xlt('Type'); ?
>:</label
>
749 <select name
='form_category' id
='form_category' class='form-control'>
751 foreach (array(xl('Open'), xl('All'), xl('Due Pt'), xl('Due Ins')) as $value) {
752 echo " <option value='" . attr($value) . "'";
753 if ($_POST['form_category'] == $value) {
756 echo ">" . text($value) . "</option>\n";
762 <div
class="col-xs-12 .oe-custom-line oe-show-hide" id
= 'era-upld'>
763 <div
class="form-group col-xs9 oe-file-div">
764 <div
class="input-group">
765 <label
class="input-group-btn">
766 <span
class="btn btn-default">
767 Browse
&hellip
;<input type
="file" id
="uploadedfile" name
="form_erafile" style
="display: none;" >
768 <input name
="MAX_FILE_SIZE" type
="hidden" value
="5000000">
771 <input type
="text" class="form-control" placeholder
="<?php echo xla('Click Browse and select one Electronic Remittance Advice (ERA) file...'); ?>" readonly
>
776 <?php
//can change position of buttons by creating a class 'position-override' and adding rule text-alig:center or right as the case may be in individual stylesheets ?>
777 <div
class="form-group clearfix">
778 <div
class="col-sm-12 position-override oe-show-hide" id
="search-btn">
779 <div
class="btn-group" role
="group">
780 <button type
='submit' class="btn btn-default btn-search oe-show-hide" name
='form_search'
781 id
="btn-inv-search" value
='<?php echo xla("Search"); ?>'><?php
echo xlt("Search"); ?
></button
>
782 <button type
='submit' class="btn btn-default btn-save oe-show-hide" name
='form_search'
783 id
="btn-era-upld" value
='<?php echo xla("Upload"); ?>'><?php
echo xlt("Upload"); ?
></button
>
787 <fieldset id
="search-results" class= "oe-show-hide">
788 <legend
><?php
echo xlt('Search Results');?
></legend
>
789 <div
class = "table-responsive">
791 if ($_POST['form_search'] ||
$_POST['form_print']) {
792 if (!verifyCsrfToken($_POST["csrf_token_form"])) {
793 die(xlt('Authentication Error'));
796 $form_name = trim($_POST['form_name']);
797 $form_pid = trim($_POST['form_pid']);
798 $form_encounter = trim($_POST['form_encounter']);
799 $form_date = fixDate($_POST['form_date'], "");
800 $form_to_date = fixDate($_POST['form_to_date'], "");
804 // Handle X12 835 file upload.
806 if ($_FILES['form_erafile']['size']) {
807 $tmp_name = $_FILES['form_erafile']['tmp_name'];
809 // Handle .zip extension if present. Probably won't work on Windows.
810 if (strtolower(substr($_FILES['form_erafile']['name'], -4)) == '.zip') {
811 rename($tmp_name, "$tmp_name.zip");
812 exec("unzip -p " . escapeshellarg($tmp_name.".zip") . " > " . escapeshellarg($tmp_name));
813 unlink("$tmp_name.zip");
816 echo "<!-- Notes from ERA upload processing:\n";
817 $alertmsg .= parse_era($tmp_name, 'era_callback');
819 $erafullname = $GLOBALS['OE_SITE_DIR'] . "/era/$eraname.edi";
821 if (is_file($erafullname)) {
822 $alertmsg .= "Warning: Set $eraname was already uploaded ";
823 if (is_file($GLOBALS['OE_SITE_DIR'] . "/era/$eraname.html")) {
824 $alertmsg .= "and processed. ";
826 $alertmsg .= "but not yet processed. ";
829 rename($tmp_name, $erafullname);
833 // Note that parse_era() modified $eracount and $where.
842 // Allow the last name to be followed by a comma and some part of a first name.
843 if (preg_match('/^(.*\S)\s*,\s*(.*)/', $form_name, $matches)) {
844 $where .= "p.lname LIKE '" . add_escape_custom($matches[1]) . "%' AND p.fname LIKE '" . add_escape_custom($matches[2]) . "%'";
845 // Allow a filter like "A-C" on the first character of the last name.
846 } elseif (preg_match('/^(\S)\s*-\s*(\S)$/', $form_name, $matches)) {
848 while (ord($matches[1]) <= ord($matches[2])) {
849 $tmp .= " OR p.lname LIKE '" . add_escape_custom($matches[1]) . "%'";
850 $matches[1] = chr(ord($matches[1]) +
1);
852 $where .= "( $tmp ) ";
854 $where .= "p.lname LIKE '%" . add_escape_custom($form_name) . "%'";
861 $where .= "f.pid = '" . add_escape_custom($form_pid) . "'";
863 if ($form_encounter) {
867 $where .= "f.encounter = '" . add_escape_custom($form_encounter) . "'";
874 $where .= "f.date >= '" . add_escape_custom($form_date) . "' AND f.date <= '" . add_escape_custom($form_to_date) . "'";
876 $where .= "f.date = '" . add_escape_custom($form_date) . "'";
880 if ($_POST['form_category'] == 'All') {
881 die(xlt("At least one search parameter is required if you select All."));
888 // Notes that as of release 4.1.1 the copays are stored
889 // in the ar_activity table marked with a PCP in the account_code column.
890 $query = "SELECT f.id, f.pid, f.encounter, f.date, " .
891 "f.last_level_billed, f.last_level_closed, f.last_stmt_date, f.stmt_count, " .
892 "p.fname, p.mname, p.lname, p.pubpid, p.billing_note, " .
893 "( SELECT SUM(b.fee) FROM billing AS b WHERE " .
894 "b.pid = f.pid AND b.encounter = f.encounter AND " .
895 "b.activity = 1 AND b.code_type != 'COPAY' ) AS charges, " .
896 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
897 "a.pid = f.pid AND a.encounter = f.encounter AND a.payer_type = 0 AND a.account_code = 'PCP')*-1 AS copays, " .
898 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
899 "a.pid = f.pid AND a.encounter = f.encounter AND a.account_code != 'PCP') AS payments, " .
900 "( SELECT SUM(a.adj_amount) FROM ar_activity AS a WHERE " .
901 "a.pid = f.pid AND a.encounter = f.encounter ) AS adjustments " .
902 "FROM form_encounter AS f " .
903 "JOIN patient_data AS p ON p.pid = f.pid " .
905 "ORDER BY p.lname, p.fname, p.mname, f.pid, f.encounter";
907 // Note that unlike the SQL-Ledger case, this query does not weed
908 // out encounters that are paid up. Also the use of sub-selects
909 // will require MySQL 4.1 or greater.
911 // echo "<!-- $query -->\n"; // debugging
913 $t_res = sqlStatement($query);
915 $num_invoices = sqlNumRows($t_res);
916 if ($eracount && $num_invoices != $eracount) {
917 $alertmsg .= "Of $eracount remittances, there are $num_invoices " .
918 "matching encounters in OpenEMR. ";
921 <table
class="table">
924 <th
class="id dehead"><?php
echo xlt('id');?
></th
>
925 <th
class="dehead"> 
;<?php
echo xlt('Patient'); ?
></th
>
926 <th
class="dehead"> 
;<?php
echo xlt('Invoice'); ?
></th
>
927 <th
class="dehead"> 
;<?php
echo xlt('Svc Date'); ?
></th
>
928 <th
class="dehead"> 
;<?php
echo xlt('Last Stmt'); ?
></th
>
929 <th align
="right" class="dehead"><?php
echo xlt('Charge'); ?
> 
;</th
>
930 <th align
="right" class="dehead"><?php
echo xlt('Adjust'); ?
> 
;</th
>
931 <th align
="right" class="dehead"><?php
echo xlt('Paid'); ?
> 
;</th
>
932 <th align
="right" class="dehead"><?php
echo xlt('Balance'); ?
> 
;</th
>
933 <th align
="center" class="dehead"><?php
echo xlt('Prv'); ?
></th
>
936 <th align
="left" class="dehead"><?php
echo xlt('Sel'); ?
></th
>
937 <th align
="center" class="dehead"><?php
echo xlt('Email'); ?
></th
>
945 while ($row = sqlFetchArray($t_res)) {
946 $balance = sprintf("%.2f", $row['charges'] +
$row['copays'] - $row['payments'] - $row['adjustments']);
947 //new filter only patients with debt.
948 if ($_POST['only_with_debt'] && $balance <= 0) {
953 if ($_POST['form_category'] != 'All' && $eracount == 0 && $balance == 0) {
957 // $duncount was originally supposed to be the number of times that
958 // the patient was sent a statement for this invoice.
960 $duncount = $row['stmt_count'];
962 // But if we have not yet billed the patient, then compute $duncount as a
963 // negative count of the number of insurance plans for which we have not
964 // yet closed out insurance.
967 for ($i = 1; $i <= 3 && arGetPayerID($row['pid'], $row['date'], $i);
970 $duncount = $row['last_level_closed'] +
1 - $i;
973 $isdueany = ($balance > 0);
975 // An invoice is now due from the patient if money is owed and we are
976 // not waiting for insurance to pay.
978 $isduept = ($duncount >= 0 && $isdueany) ?
" checked" : "";
980 // Skip invoices not in the desired "Due..." category.
982 if (substr($_POST['form_category'], 0, 3) == 'Due' && !$isdueany) {
985 if ($_POST['form_category'] == 'Due Ins' && ($duncount >= 0 ||
!$isdueany)) {
988 if ($_POST['form_category'] == 'Due Pt' && ($duncount < 0 ||
!$isdueany)) {
992 $bgcolor = ((++
$orow & 1) ?
"#ffdddd" : "#ddddff");
994 $svcdate = substr($row['date'], 0, 10);
995 $last_stmt_date = empty($row['last_stmt_date']) ?
'' : $row['last_stmt_date'];
997 // Determine if customer is in collections.
999 $billnote = $row['billing_note'];
1000 $in_collections = stristr($billnote, 'IN COLLECTIONS') !== false;
1002 <tr bgcolor
='<?php echo $bgcolor ?>'>
1004 <a href
="" onclick
="return npopup(<?php echo attr(addslashes($row['pid'])) ?>)"><?php
echo text($row['pid']); ?
></a
>
1007  
;<a href
="" onclick
="return npopup(<?php echo attr(addslashes($row['pid'])) ?>)"><?php
echo text($row['lname']) . ', ' . text($row['fname']); ?
></a
>
1010  
;<a href
="sl_eob_invoice.php?id=<?php echo attr(urlencode($row['id'])); ?>" target
="_blank"><?php
echo text($row['pid']) . '.' . text($row['encounter']); ?
></a
>
1012 <td
class="detail"> 
;<?php
echo text(oeFormatShortDate($svcdate)); ?
></td
>
1013 <td
class="detail"> 
;<?php
echo text(oeFormatShortDate($last_stmt_date)); ?
></td
>
1014 <td align
="right" class="detail"><?php
echo text(bucks($row['charges'])); ?
> 
;</td
>
1015 <td align
="right" class="detail"><?php
echo text(bucks($row['adjustments'])); ?
> 
;</td
>
1016 <td align
="right" class="detail"><?php
echo text(bucks($row['payments'] - $row['copays'])); ?
> 
;</td
>
1017 <td align
="right" class="detail"><?php
echo text(bucks($balance)); ?
> 
;</td
>
1018 <td align
="center" class="detail"><?php
echo $duncount ?
text($duncount) : " " ?
></td
>
1019 <?php
if (!$eracount) { ?
>
1020 <td
class="detail" align
="left">
1021 <input type
='checkbox' name
='form_cb[<?php echo attr($row['id
']) ?>]'<?php
echo text($isduept); ?
> />
1023 if ($in_collections) {
1024 echo "<b><font color='red'>IC</font></b>";
1027 if (function_exists('is_auth_portal') ?
is_auth_portal($row['pid']) : false) {
1029 echo("<input type='hidden' name='form_invpids[". attr($row['id']) ."][". attr($row['pid']) ."]' />");
1034 <td align
="left" class="detail">
1036 $patientData = sqlQuery("SELECT * FROM `patient_data` WHERE `pid`=?", array($row['pid']));
1037 if ($patientData['hipaa_allowemail'] == "YES" && $patientData['allow_patient_portal'] == "YES" && $patientData['hipaa_notice'] == "YES" && validEmail($patientData['email'])) {
1047 } // end search/print logic
1050 </div
><!--End of table
-responsive div
-->
1052 <?php
//can change position of buttons by creating a class 'position-override' and adding rule text-alig:center or right as the case may be in individual stylesheets ?>
1053 <div
class="form-group clearfix">
1054 <div
class="col-sm-12 text-left position-override oe-show-hide" id
="statement-download">
1055 <div
class="btn-group" role
="group">
1058 <button type
="button" class="btn btn-default btn-save" name
="Submit"
1059 onclick
='processERA()' value
="<?php echo xla('Process ERA File');?>">
1060 <?php
echo xlt('Process ERA File');?
></button
>
1063 <button type
="button" class="btn btn-default btn-save" name
="Submit1"
1064 onclick
='checkAll(true)'><?php
echo xlt('Select All');?
></button
>
1065 <button type
="button" class="btn btn-default btn-undo" name
="Submit2"
1066 onclick
='checkAll(false)'><?php
echo xlt('Clear All');?
></button
>
1067 <?php
if ($GLOBALS['statement_appearance'] != '1') { ?
>
1068 <button type
="submit" class="btn btn-default btn-print" name
='form_print'
1069 value
="<?php echo xla('Print Selected Statements'); ?>">
1070 <?php
echo xlt('Print Selected Statements');?
></button
>
1071 <button type
="submit" class="btn btn-default btn-download" name
='form_download'
1072 value
="<?php echo xla('Download Selected Statements'); ?>">
1073 <?php
echo xlt('Download Selected Statements');?
></button
>
1075 <button type
="submit" class="btn btn-default btn-download" name
='form_pdf'
1076 value
="<?php echo xla('PDF Download Selected Statements'); ?>">
1077 <?php
echo xlt('PDF Download Selected Statements');?
></button
>
1078 <button type
="submit" class="btn btn-default btn-mail" name
='form_download'
1079 value
="<?php echo xla('Email Selected Statements'); ?>">
1080 <?php
echo xlt('Email Selected Statements');?
></button
>
1083 <button type
="submit" class="btn btn-default btn-save" name
='form_portalnotify'
1084 value
="<?php echo xla('Notify via Patient Portal'); ?>">
1085 <?php
echo xlt('Notify via Patient Portal');?
></button
>
1090 <input type
='checkbox' class="btn-separate-left" name
='form_without' value
='1' /><?php
echo xlt('Without Update');?
>
1096 </div
> <!--End of Container div
-->
1099 //home of the help modal ;)
1100 //$GLOBALS['enable_help'] = 0; // Please comment out line if you want help modal to function on this page
1101 if ($GLOBALS['enable_help'] == 1) {
1102 echo "<script>var helpFile = 'sl_eob_help.php'</script>";
1103 //help_modal.php lives in interface, set path accordingly
1104 require_once "../help_modal.php";
1107 <script language
="JavaScript">
1108 function processERA() {
1109 var f
= document
.forms
[0];
1110 var debug
= f
.form_without
.checked ?
'1' : '0';
1111 var paydate
= f
.form_paydate
.value
;
1112 window
.open('sl_eob_process.php?eraname=<?php echo attr(urlencode($eraname)); ?>&debug=' + debug +
'&paydate=' + paydate +
'&original=original' +
'&csrf_token_form=<?php echo attr(urlencode(collectCsrfToken())); ?>', '_blank');
1116 //https://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3
1117 // We can attach the `fileselect` event to all file inputs on the page
1118 $
(document
).on('change', ':file', function() {
1119 var input
= $
(this
),
1120 numFiles
= input
.get(0).files ? input
.get(0).files
.length
: 1,
1121 label
= input
.val().replace(/\\/g
, '/').replace(/.*\
//, '');
1122 input
.trigger('fileselect', [numFiles
, label
]);
1125 // We can watch for our custom `fileselect` event like this
1126 $
(document
).ready( function() {
1127 $
(':file').on('fileselect', function(event
, numFiles
, label
) {
1128 var input
= $
(this
).parents('.input-group').find(':text'),
1129 log
= numFiles
> 1 ? numFiles +
' files selected' : label
;
1131 if( input
.length
) {
1135 if( log
) alert(log
);
1141 //to dynamically show /hide relevant divs and change Fieldset legends
1142 $
(document
).ready(function() {
1143 $
("input[name=radio-search]").on( "change", function() {
1145 var flip
= $
(this
).val();
1146 $
(".oe-show-hide").hide();
1148 if(flip
== 'inv-search'){
1149 $
("#search-upload").insertAfter("#payment-allocate");
1150 $
('#payment-allocate').show();
1151 $
('#search-btn').show();
1152 $
('#btn-inv-search').show();
1153 var legend_text
= $
('#hid1').val();
1154 $
('#search-upload').find('legend').find('span').text(legend_text
);
1155 $
('#search-upload').find('#form_name').focus();
1156 $
('#select-method-tooltip').hide();
1158 else if (flip
== 'era-upld'){
1159 $
('#payment-allocate').hide();
1160 $
('#search-btn').show();
1161 $
('#btn-era-upld').show();
1162 var legend_text
= $
('#hid2').val();
1163 $
('#search-upload').find('legend').find('span').text(legend_text
);
1164 $
('#select-method-tooltip').hide();
1167 $
('#payment-allocate').hide();
1168 $
('#search-btn').hide();
1169 var legend_text
= $
('#hid3').val();
1170 $
('#search-upload').find('legend').find('span').text(legend_text
);
1171 $
('#select-method-tooltip').show();
1177 echo "alert('" . addslashes($alertmsg) . "');\n";
1181 $
( document
).ready(function() {
1182 //using jquery-ui-1-12-1 tooltip instead of bootstrap tooltip
1183 $
('#select-method-tooltip').attr( "title", "<?php echo xla('Click on either the Invoice Search button on the far right, for manual entry or ERA Upload button for uploading an entire electronic remittance advice ERA file'); ?>").tooltip();
1187 $tr_str = xl('Search');
1188 if ($_POST['form_search'] == "$tr_str") {?
>
1190 $
("#payment-allocate").insertAfter("#search-upload");
1191 $
('#payment-allocate').show();
1192 $
("#search-results").show();
1193 $
("#statement-download").show();
1199 $tr_str = xl('Upload');
1200 if ($_POST['form_search'] == "$tr_str") {?
>
1202 $
('#era-upld').show();
1203 $
('#search-results').show();
1204 $
("#statement-download").show();