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>;.
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
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(
58 if ($pData['allow_patient_portal'] != "YES") {
61 $_SESSION['portalUser'] = strtolower($pData['fname']) . $pData['id'];
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) {
80 if (SavePatientAudit($thispid, $invoices) != true) {
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
93 function fixup_invoice($template, $ifile)
95 $data = file_get_contents($template);
100 if (! file_put_contents($ifile, $data)) {
107 function SavePatientAudit($pid, $invs)
109 $appsql = new ApplicationTable();
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);
128 $appsql->portalAudit('insert', '', $audit);
130 } catch (Exception
$ex) {
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
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) {
154 $where .= "( f.pid = '$pid' AND f.encounter = '$encounter' )";
158 function bucks($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)) {
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'])) {
181 if (!(validEmail($patientData['email']))) {
185 if (!(validEmail($GLOBALS['patient_reminder_sender_email']))) {
189 if ($_SESSION['pc_facility']) {
190 $sql = "select * from facility where id=?";
191 $facility = sqlQuery($sql, array($_SESSION['pc_facility']));
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>");
208 $mail->AltBody
= $message;
213 $email_status = $mail->ErrorInfo
;
214 error_log("EMAIL ERROR: ".$email_status, 0);
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.
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.
239 function upload_file_to_client_email($ppid, $file_to_send)
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>';
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
262 $STMT_TEMP_FILE_PDF = $GLOBALS['temporary_files_dir'] . "/Stmt_{$aPatFName}_{$aPatID}.pdf";
264 global $STMT_TEMP_FILE_PDF;
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
281 echo readfile($file_to_send, "r");//this file contains the HTML to be converted to pdf.
283 $content = ob_get_clean();
285 // Fix a nasty html2pdf bug - it ignores document root!
286 global $web_root, $webserver_root;
288 $wrlen = strlen($web_root);
289 $wsrlen = strlen($webserver_root);
291 $i = stripos($content, " src='/", $i +
1);
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');
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']);
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.
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));
323 $pdf->ezText($OneLine, 12, array('justification' => 'left', 'leading' => 6));
329 $fh = @fopen
($STMT_TEMP_FILE_PDF, 'w');//stored to a pdf file
331 fwrite($fh, $pdf->ezOutput());
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.
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.
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();
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
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 " .
386 "ORDER BY p.lname, p.fname, f.pid, f.date, f.encounter", $sqlBindArray);
392 $aPatientFirstName = '';
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'];
407 $aPatientFirstName = $row['fname'];
408 $aPatientID = $row['pid'];
409 $usePatientNamePdf = true;
410 } elseif (!$multiplePatients) {
411 if ($aPatientID != $row['pid']) {
412 $multiplePatients = true;
413 $aPatientFirstName = '';
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:
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
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']) {
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']);
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;
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) {
484 $line['dos'] = $svcdate;
485 if ($GLOBALS['use_custom_statement']) {
486 $line['desc'] = ($key == 'CO-PAY') ?
"Patient Payment" : $value['code_text'];
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');
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');
526 ftruncate($fhprint, 0);
531 fwrite($fhprint, make_statement($stmt));
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!
554 $alertmsg = xl("Printing skipped; see test output in") .' '. $STMT_TEMP_FILE;
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.');
560 $alertmsg = xl('Now printing') .' '. $stmt_count .' '. xl('statements and updating invoices.');
563 } // end not form_download
564 } // end statements requested
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">
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');
595 <body leftmargin
='0' topmargin
='0' marginwidth
='0' marginheight
='0'>
598 <form method
='post' action
='sl_eob_search.php' enctype
='multipart/form-data'>
600 <table border
='0' cellpadding
='5' cellspacing
='0'>
604 // Identify the payer to support resumable posting sessions.
606 echo " " . xl('Payer') . ":\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']) {
618 echo ">" . $iname . "</option>\n";
626 <?php
xl('Source:', 'e'); ?
>
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"); ?>'>
633 <?php
xl('Pay Date:', 'e'); ?
>
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"); ?>'>
642 <?php
xl('Deposit Date:', 'e'); ?
>
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"); ?>'>
651 <?php
xl('Amount:', 'e'); ?
>
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"); ?>'>
658 <a href
='sl_eob_help.php' target
='_blank'><?php
xl('Help', 'e'); ?
></a
>
664 <table border
='0' cellpadding
='5' cellspacing
='0'>
666 <tr bgcolor
='#ddddff'>
668 <?php
xl('Name:', 'e'); ?
>
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"); ?>'>
675 <?php
xl('Chart ID:', 'e'); ?
>
678 <input type
='text' name
='form_pid' size
='10' value
='<?php echo $_POST['form_pid
']; ?>'
679 title
='<?php xl("Patient chart ID", "e"); ?>'>
682 <?php
xl('Encounter:', 'e'); ?
>
685 <input type
='text' name
='form_encounter' size
='10' value
='<?php echo $_POST['form_encounter
']; ?>'
686 title
='<?php xl("Encounter number", "e"); ?>'>
689 <?php
xl('Svc Date:', 'e'); ?
>
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"); ?>'>
696 <?php
xl('To:', 'e'); ?
>
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"); ?>'>
703 <select name
='form_category'>
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) {
711 echo ">$value</option>\n";
717 <input type
='submit' name
='form_search' value
='<?php xl("Search", "e"); ?>'>
720 <!-- Filter
- only show those who have debt
-->
721 <tr bgcolor
='#ddddff'>
724 <span
><?php
echo xlt('Patients with debt');?
>
725 <input
<?php
echo $_POST['only_with_debt']?
'checked=checked':'';?
> type
="checkbox" name
="only_with_debt" />
730 <!-- Support
for X12
835 upload
-->
731 <tr bgcolor
='#ddddff'>
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" />
740 <td height
="1" colspan
="10">
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'], "");
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');
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. ";
778 $alertmsg .= "but not yet processed. ";
782 rename($tmp_name, $erafullname);
786 // Note that parse_era() modified $eracount and $where.
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)) {
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 ) ";
809 $where .= "p.lname LIKE '%$form_name%'";
818 $where .= "f.pid = '$form_pid'";
821 if ($form_encounter) {
826 $where .= "f.encounter = '$form_encounter'";
835 $where .= "f.date >= '$form_date' AND f.date <= '$form_to_date'";
837 $where .= "f.date = '$form_date'";
842 if ($_POST['form_category'] == 'All') {
843 die(xl("At least one search parameter is required if you select All."));
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 " .
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">
888 <?php
xl('id', 'e');?
>
891  
;<?php
xl('Patient', 'e'); ?
>
894  
;<?php
xl('Invoice', 'e'); ?
>
897  
;<?php
xl('Svc Date', 'e'); ?
>
900  
;<?php
xl('Last Stmt', 'e'); ?
>
902 <td
class="dehead" align
="right">
903 <?php
xl('Charge', 'e'); ?
> 
;
905 <td
class="dehead" align
="right">
906 <?php
xl('Adjust', 'e'); ?
> 
;
908 <td
class="dehead" align
="right">
909 <?php
xl('Paid', 'e'); ?
> 
;
911 <td
class="dehead" align
="right">
912 <?php
xl('Balance', 'e'); ?
> 
;
914 <td
class="dehead" align
="center">
915 <?php
xl('Prv', 'e'); ?
>
917 <?php
if (!$eracount) { ?
>
918 <td
class="dehead" align
="left">
919 <?php
xl('Sel', 'e'); ?
>
921 <td
class="dehead" align
="center">
922 <?php
xl('Email', 'e'); ?
>
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) {
939 if ($_POST['form_category'] != 'All' && $eracount == 0 && $balance == 0) {
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.
953 for ($i = 1; $i <= 3 && arGetPayerID($row['pid'], $row['date'], $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) {
973 if ($_POST['form_category'] == 'Due Ins' && ($duncount >= 0 ||
!$isdueany)) {
977 if ($_POST['form_category'] == 'Due Pt' && ($duncount < 0 ||
!$isdueany)) {
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 ?>'>
993 <a href
="" onclick
="return npopup(<?php echo $row['pid'] ?>)"><?php
echo $row['pid'];?
></a
>
996  
;<a href
="" onclick
="return npopup(<?php echo $row['pid'] ?>)"
997 ><?php
echo $row['lname'] . ', ' . $row['fname']; ?
></a
>
1000  
;<a href
="sl_eob_invoice.php?id=<?php echo $row['id'] ?>"
1001 target
="_blank"><?php
echo $row['pid'] . '.' . $row['encounter']; ?
></a
>
1004  
;<?php
echo oeFormatShortDate($svcdate) ?
>
1007  
;<?php
echo oeFormatShortDate($last_stmt_date) ?
>
1009 <td
class="detail" align
="right">
1010 <?php
bucks($row['charges']) ?
> 
;
1012 <td
class="detail" align
="right">
1013 <?php
bucks($row['adjustments']) ?
> 
;
1015 <td
class="detail" align
="right">
1016 <?php
bucks($row['payments'] - $row['copays']); ?
> 
;
1018 <td
class="detail" align
="right">
1019 <?php
bucks($balance); ?
> 
;
1021 <td
class="detail" align
="center">
1022 <?php
echo $duncount ?
$duncount : " " ?
>
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>";
1030 <?php
if (function_exists('is_auth_portal') ?
is_auth_portal($row['pid']) : false) {
1032 echo("<input type='hidden' name='form_invpids[". $row['id'] ."][". $row['pid'] ."]' />");
1037 <td
class="detail" align
="left">
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'])) {
1051 } // end search/print logic
1058 <?php
if ($eracount) { ?
>
1059 <input type
='button' value
='<?php xl('Process ERA File
', 'e
')?>' onclick
='processERA()' />  
;
1061 <input type
='button' value
='<?php xl('Select All
', 'e
')?>' onclick
='checkAll(true)' />  
;
1062 <input type
='button' value
='<?php xl('Clear All
', 'e
')?>' onclick
='checkAll(false)' />  
;
1063 <?php
if ($GLOBALS['statement_appearance'] != '1') { ?
>
1064 <input type
='submit' name
='form_print' value
='<?php xl('Print Selected Statements
', 'e
'); ?>' />  
;
1065 <input type
='submit' name
='form_download' value
='<?php xl('Download Selected Statements
', 'e
'); ?>' />  
;
1067 <input type
='submit' name
='form_pdf' value
='<?php xl('PDF Download Selected Statements
', 'e
'); ?>' />  
;
1068 <input type
='submit' name
='form_email' value
='<?php xl('Email Selected Statements
', 'e
'); ?>' />  
;
1069 <?php
if ($is_portal) {?
>
1070 <input type
='submit' name
='form_portalnotify' value
='<?php xl('Notify via Patient Portal
', 'e
'); ?>' />  
;
1073 <input type
='checkbox' name
='form_without' value
='1' /> <?php
xl('Without Update', 'e'); ?
>
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');
1088 echo "alert('" . htmlentities($alertmsg) . "');\n";