fix: quick fix to enforce support of x509 database connection on install (#6157)
[openemr.git] / portal / portal_payment.php
blob736b6b54226c3d500a3010b0fbed66c3a543dfef
1 <?php
3 /**
5 * namespace OnsitePortal
7 * @package OpenEMR
8 * @link http://www.open-emr.org
9 * @author Rod Roark <rod@sunsetsystems.com>
10 * @author Jerry Padgett <sjpadgett@gmail.com>
11 * @author Brady Miller <brady.g.miller@gmail.com>
12 * @copyright Copyright (c) 2006-2020 Rod Roark <rod@sunsetsystems.com>
13 * @copyright Copyright (c) 2016-2019 Jerry Padgett <sjpadgett@gmail.com>
14 * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>
15 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
18 // Will start the (patient) portal OpenEMR session/cookie.
19 require_once(__DIR__ . "/../src/Common/Session/SessionUtil.php");
20 OpenEMR\Common\Session\SessionUtil::portalSessionStart();
22 $isPortal = false;
23 if (isset($_SESSION['pid']) && isset($_SESSION['patient_portal_onsite_two'])) {
24 $pid = $_SESSION['pid'];
25 $ignoreAuth_onsite_portal = true;
26 $isPortal = true;
27 require_once(__DIR__ . "/../interface/globals.php");
28 } else {
29 OpenEMR\Common\Session\SessionUtil::portalSessionCookieDestroy();
30 $ignoreAuth = false;
31 require_once(__DIR__ . "/../interface/globals.php");
32 if (!isset($_SESSION['authUserID'])) {
33 $landingpage = "index.php";
34 header('Location: ' . $landingpage);
35 exit();
39 require_once(__DIR__ . "/lib/appsql.class.php");
40 require_once("$srcdir/patient.inc.php");
41 require_once("$srcdir/payment.inc.php");
42 require_once("$srcdir/forms.inc.php");
43 require_once("../custom/code_types.inc.php");
44 require_once("$srcdir/options.inc.php");
45 require_once("$srcdir/encounter_events.inc.php");
47 use OpenEMR\Billing\BillingUtilities;
48 use OpenEMR\Common\Crypto\CryptoGen;
49 use OpenEMR\Common\Csrf\CsrfUtils;
50 use OpenEMR\PaymentProcessing\Sphere\SpherePayment;
52 $cryptoGen = new CryptoGen();
54 $appsql = new ApplicationTable();
55 $pid = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : $pid;
56 $pid = $_REQUEST['hidden_patient_code'] > 0 ? $_REQUEST['hidden_patient_code'] : $pid;
57 $recid = isset($_REQUEST['recid']) ? (int) $_REQUEST['recid'] : 0;
58 $adminUser = '';
59 $portalPatient = '';
61 $query = "SELECT pao.portal_username as recip_id, Concat_Ws(' ', patient_data.fname, patient_data.lname) as username FROM patient_data " .
62 "LEFT JOIN patient_access_onsite pao ON pao.pid = patient_data.pid " .
63 "WHERE patient_data.pid = ? AND pao.portal_pwd_status = 1";
64 $portalPatient = sqlQueryNoLog($query, $pid);
65 if ($_SESSION['authUserID']) {
66 $query = "SELECT users.username as recip_id, users.authorized as dash, CONCAT(users.fname,' ',users.lname) as username " .
67 "FROM users WHERE id = ?";
68 $adminUser = sqlQueryNoLog($query, $_SESSION['authUserID']);
71 if ($recid) {
72 $edata = $appsql->getPortalAuditRec($recid);
73 } else {
74 $edata = $appsql->getPortalAudit($pid, 'review', 'payment');
76 $ccdata = array();
77 $invdata = array();
78 if ($edata) {
79 $ccdata = json_decode($cryptoGen->decryptStandard($edata['checksum']), true);
80 $invdata = json_decode($edata['table_args'], true);
81 echo "<script>var jsondata='" . $edata['table_args'] . "';var ccdata='" . $edata['checksum'] . "'</script>";
84 function bucks($amount)
86 if ($amount) {
87 $amount = oeFormatMoney($amount);
88 return $amount;
91 return '';
94 function rawbucks($amount)
96 if ($amount) {
97 $amount = sprintf("%.2f", $amount);
98 return $amount;
101 return '';
104 // Display a row of data for an encounter.
106 $var_index = 0;
107 $sum_charges = $sum_ptpaid = $sum_inspaid = $sum_duept = $sum_copay = $sum_patcopay = $sum_balance = 0;
108 function echoLine($iname, $date, $charges, $ptpaid, $inspaid, $duept, $encounter = 0, $copay = 0, $patcopay = 0)
110 global $sum_charges, $sum_ptpaid, $sum_inspaid, $sum_duept, $sum_copay, $sum_patcopay, $sum_balance;
111 global $var_index;
112 $var_index++;
113 $balance = bucks($charges - $ptpaid - $inspaid);
114 $balance = (round($duept, 2) != 0) ? 0 : $balance; // if balance is due from patient, then insurance balance is displayed as zero
115 $encounter = $encounter ? $encounter : '';
116 echo " <tr id='tr_" . attr($var_index) . "' >\n";
117 echo " <td class='detail'>" . text(oeFormatShortDate($date)) . "</td>\n";
118 echo " <td class='detail' id='" . attr($date) . "' align='left'>" . text($encounter) . "</td>\n";
119 echo " <td class='detail' align='center' id='td_charges_$var_index' >" . text(bucks($charges)) . "</td>\n";
120 echo " <td class='detail' align='center' id='td_inspaid_$var_index' >" . text(bucks($inspaid * -1)) . "</td>\n";
121 echo " <td class='detail' align='center' id='td_ptpaid_$var_index' >" . text(bucks($ptpaid * -1)) . "</td>\n";
122 echo " <td class='detail' align='center' id='td_patient_copay_$var_index' >" . text(bucks($patcopay)) . "</td>\n";
123 echo " <td class='detail' align='center' id='td_copay_$var_index' >" . text(bucks($copay)) . "</td>\n";
124 echo " <td class='detail' align='center' id='balance_$var_index'>" . text(bucks($balance)) . "</td>\n";
125 echo " <td class='detail' align='center' id='duept_$var_index'>" . text(bucks(round($duept, 2) * 1)) . "</td>\n";
126 echo " <td class='detail' align='center'><input class='form-control' name='" . attr($iname) . "' id='paying_" . attr($var_index) .
127 "' " . " value='" . '' . "' onchange='coloring();calctotal()' autocomplete='off' " . "onkeyup='calctotal()'/></td>\n";
128 echo " </tr>\n";
130 $sum_charges += (float)$charges * 1;
131 $sum_ptpaid += (float)$ptpaid * -1;
132 $sum_inspaid += (float)$inspaid * -1;
133 $sum_duept += (float)$duept * 1;
134 $sum_patcopay += (float)$patcopay * 1;
135 $sum_copay += (float)$copay * 1;
136 $sum_balance += (float)$balance * 1;
139 // We use this to put dashes, colons, etc. back into a timestamp.
141 function decorateString($fmt, $str)
143 $res = '';
144 while ($fmt) {
145 $fc = substr($fmt, 0, 1);
146 $fmt = substr($fmt, 1);
147 if ($fc == '.') {
148 $res .= substr($str, 0, 1);
149 $str = substr($str, 1);
150 } else {
151 $res .= $fc;
155 return $res;
158 // Compute taxes from a tax rate string and a possibly taxable amount.
160 function calcTaxes($row, $amount)
162 $total = 0;
163 if (empty($row['taxrates'])) {
164 return $total;
167 $arates = explode(':', $row['taxrates']);
168 if (empty($arates)) {
169 return $total;
172 foreach ($arates as $value) {
173 if (empty($value)) {
174 continue;
177 $trow = sqlQuery("SELECT option_value FROM list_options WHERE " . "list_id = 'taxrate' AND option_id = ? LIMIT 1", array($value
179 if (empty($trow['option_value'])) {
180 echo "<!-- Missing tax rate '" . text($value) . "'! -->\n";
181 continue;
184 $tax = sprintf("%01.2f", $amount * $trow['option_value']);
185 // echo "<!-- Rate = '$value', amount = '$amount', tax = '$tax' -->\n";
186 $total += $tax;
189 return $total;
192 $now = time();
193 $today = date('Y-m-d', $now);
194 $timestamp = date('Y-m-d H:i:s', $now);
196 $patdata = sqlQuery("SELECT " . "p.fname, p.mname, p.lname, p.postal_code, p.pubpid,p.pid, i.copay " . "FROM patient_data AS p " . "LEFT OUTER JOIN insurance_data AS i ON " . "i.pid = p.pid AND i.type = 'primary' " . "WHERE p.pid = ? ORDER BY i.date DESC LIMIT 1", array($pid
199 $alertmsg = ''; // anything here pops up in an alert box
201 // If the Save button was clicked...
202 if ($_POST['form_save']) {
203 $form_pid = $_POST['form_pid'];
204 $form_method = trim($_POST['form_method']);
205 $form_source = trim($_POST['form_source']);
206 $patdata = getPatientData($form_pid, 'fname,mname,lname,pubpid');
207 $NameNew = $patdata['fname'] . " " . $patdata['lname'] . " " . $patdata['mname'];
209 if ($_REQUEST['radio_type_of_payment'] == 'pre_payment') {
210 $payment_id = sqlInsert(
211 "insert into ar_session set " .
212 "payer_id = ?" .
213 ", patient_id = ?" .
214 ", user_id = ?" .
215 ", closed = ?" .
216 ", reference = ?" .
217 ", check_date = now() , deposit_date = now() " .
218 ", pay_total = ?" .
219 ", payment_type = 'patient'" .
220 ", description = ?" .
221 ", adjustment_code = 'pre_payment'" .
222 ", post_to_date = now() " .
223 ", payment_method = ?",
224 array(0, $form_pid, $_SESSION['authUserID'], 0, $form_source, $_REQUEST['form_prepayment'], $NameNew, $form_method)
227 frontPayment($form_pid, 0, $form_method, $form_source, $_REQUEST['form_prepayment'], 0, $timestamp);//insertion to 'payments' table.
230 if ($_POST['form_upay'] && $_REQUEST['radio_type_of_payment'] != 'pre_payment') {
231 foreach ($_POST['form_upay'] as $enc => $payment) {
232 if ($amount = (float)$payment) {
233 $zero_enc = $enc;
235 //----------------------------------------------------------------------------------------------------
236 //Fetching the existing code and modifier
237 $ResultSearchNew = sqlStatement(
238 "SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key " .
239 "WHERE code_types.ct_fee=1 AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier",
240 array($form_pid, $enc)
242 if ($RowSearch = sqlFetchArray($ResultSearchNew)) {
243 $Codetype = $RowSearch['code_type'];
244 $Code = $RowSearch['code'];
245 $Modifier = $RowSearch['modifier'];
246 } else {
247 $Codetype = '';
248 $Code = '';
249 $Modifier = '';
252 //----------------------------------------------------------------------------------------------------
253 if ($_REQUEST['radio_type_of_payment'] == 'copay') {//copay saving to ar_session and ar_activity tables
254 $session_id = sqlInsert(
255 "INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total," .
256 " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) " .
257 " VALUES ('0',?,?,now(),now(),?,'','patient','COPAY',?,?,'patient_payment',now())",
258 array($_SESSION['authUserID'], $form_source, $amount, $form_pid, $form_method)
261 sqlBeginTrans();
262 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $enc));
263 $insrt_id = sqlInsert(
264 "INSERT INTO ar_activity (pid,encounter,sequence_no,code_type,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)" .
265 " VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
266 array($form_pid, $enc, $sequence_no['increment'], $Codetype, $Code, $Modifier, $_SESSION['authUserID'], $session_id, $amount)
268 sqlCommitTrans();
270 frontPayment($form_pid, $enc, $form_method, $form_source, $amount, 0, $timestamp);//insertion to 'payments' table.
273 if ($_REQUEST['radio_type_of_payment'] == 'invoice_balance' || $_REQUEST['radio_type_of_payment'] == 'cash') { //Payment by patient after insurance paid, cash patients similar to do not bill insurance in feesheet.
274 if ($_REQUEST['radio_type_of_payment'] == 'cash') {
275 sqlStatement(
276 "update form_encounter set last_level_closed=? where encounter=? and pid=? ",
277 array(4, $enc, $form_pid)
279 sqlStatement(
280 "update billing set billed=? where encounter=? and pid=?",
281 array(1, $enc, $form_pid)
285 $adjustment_code = 'patient_payment';
286 $payment_id = sqlInsert(
287 "insert into ar_session set " .
288 "payer_id = ?" .
289 ", patient_id = ?" .
290 ", user_id = ?" .
291 ", closed = ?" .
292 ", reference = ?" .
293 ", check_date = now() , deposit_date = now() " .
294 ", pay_total = ?" .
295 ", payment_type = 'patient'" .
296 ", description = ?" .
297 ", adjustment_code = ?" .
298 ", post_to_date = now() " .
299 ", payment_method = ?",
300 array(0, $form_pid, $_SESSION['authUserID'], 0, $form_source, $amount, $NameNew, $adjustment_code, $form_method)
303 //--------------------------------------------------------------------------------------------------------------------
305 frontPayment($form_pid, $enc, $form_method, $form_source, 0, $amount, $timestamp);//insertion to 'payments' table.
307 //--------------------------------------------------------------------------------------------------------------------
309 $resMoneyGot = sqlStatement(
310 "SELECT sum(pay_amount) as PatientPay FROM ar_activity where deleted IS NULL AND pid =? and " .
311 "encounter =? and payer_type=0 and account_code='PCP'",
312 array($form_pid, $enc)
313 );//new fees screen copay gives account_code='PCP'
314 $rowMoneyGot = sqlFetchArray($resMoneyGot);
315 $Copay = $rowMoneyGot['PatientPay'];
317 //--------------------------------------------------------------------------------------------------------------------
319 //Looping the existing code and modifier
320 $ResultSearchNew = sqlStatement(
321 "SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key WHERE code_types.ct_fee=1 " .
322 "AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier",
323 array($form_pid, $enc)
325 while ($RowSearch = sqlFetchArray($ResultSearchNew)) {
326 $Codetype = $RowSearch['code_type'];
327 $Code = $RowSearch['code'];
328 $Modifier = $RowSearch['modifier'];
329 $Fee = $RowSearch['fee'];
331 $resMoneyGot = sqlStatement(
332 "SELECT sum(pay_amount) as MoneyGot FROM ar_activity where deleted IS NULL AND pid = ? " .
333 "and code_type=? and code=? and modifier=? and encounter =? and !(payer_type=0 and account_code='PCP')",
334 array($form_pid, $Codetype, $Code, $Modifier, $enc)
336 //new fees screen copay gives account_code='PCP'
337 $rowMoneyGot = sqlFetchArray($resMoneyGot);
338 $MoneyGot = $rowMoneyGot['MoneyGot'];
340 $resMoneyAdjusted = sqlStatement(
341 "SELECT sum(adj_amount) as MoneyAdjusted FROM ar_activity where deleted IS NULL AND " .
342 "pid =? and code_type=? and code=? and modifier=? and encounter =?",
343 array($form_pid, $Codetype, $Code, $Modifier, $enc)
345 $rowMoneyAdjusted = sqlFetchArray($resMoneyAdjusted);
346 $MoneyAdjusted = $rowMoneyAdjusted['MoneyAdjusted'];
348 $Remainder = $Fee - $Copay - $MoneyGot - $MoneyAdjusted;
349 $Copay = 0;
350 if (round($Remainder, 2) != 0 && $amount != 0) {
351 if ($amount - $Remainder >= 0) {
352 $insert_value = $Remainder;
353 $amount = $amount - $Remainder;
354 } else {
355 $insert_value = $amount;
356 $amount = 0;
359 sqlBeginTrans();
360 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $enc));
361 sqlStatement(
362 "insert into ar_activity set " .
363 "pid = ?" .
364 ", encounter = ?" .
365 ", sequence_no = ?" .
366 ", code_type = ?" .
367 ", code = ?" .
368 ", modifier = ?" .
369 ", payer_type = ?" .
370 ", post_time = now() " .
371 ", post_user = ?" .
372 ", session_id = ?" .
373 ", pay_amount = ?" .
374 ", adj_amount = ?" .
375 ", account_code = 'PP'",
376 array($form_pid, $enc, $sequence_no['increment'], $Codetype, $Code, $Modifier, 0, $_SESSION['authUserID'], $payment_id, $insert_value, 0)
378 sqlCommitTrans();
379 }//if
380 }//while
381 if ($amount != 0) {//if any excess is there.
382 sqlBeginTrans();
383 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $enc));
384 sqlStatement(
385 "insert into ar_activity set " .
386 "pid = ?" .
387 ", encounter = ?" .
388 ", sequence_no = ?" .
389 ", code_type = ?" .
390 ", code = ?" .
391 ", modifier = ?" .
392 ", payer_type = ?" .
393 ", post_time = now() " .
394 ", post_user = ?" .
395 ", session_id = ?" .
396 ", pay_amount = ?" .
397 ", adj_amount = ?" .
398 ", account_code = 'PP'",
399 array($form_pid, $enc, $sequence_no['increment'], $Codetype, $Code, $Modifier, 0, $_SESSION['authUserID'], $payment_id, $amount, 0)
401 sqlCommitTrans();
404 //--------------------------------------------------------------------------------------------------------------------
405 }//invoice_balance
406 }//if ($amount = 0 + $payment)
407 }//foreach
408 }//if ($_POST['form_upay'])
409 }//if ($_POST['form_save'])
411 if ($_POST['form_save'] || $_REQUEST['receipt']) {
412 if ($_REQUEST['receipt']) {
413 $form_pid = $_GET['patient'];
414 $timestamp = decorateString('....-..-.. ..:..:..', $_GET['time']);
417 // Get details for what we guess is the primary facility.
418 $frow = sqlQuery("SELECT * FROM facility " . "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
420 // Get the patient's name and chart number.
421 $patdata = getPatientData($form_pid, 'fname,mname,lname,pubpid');
423 // Re-fetch payment info.
424 $payrow = sqlQuery("SELECT " . "SUM(amount1) AS amount1, " . "SUM(amount2) AS amount2, " . "MAX(method) AS method, " . "MAX(source) AS source, " . "MAX(dtime) AS dtime, " .
425 // "MAX(user) AS user " .
426 "MAX(user) AS user, " . "MAX(encounter) as encounter " . "FROM payments WHERE " . "pid = ? AND dtime = ?", array($form_pid, $timestamp
429 // Create key for deleting, just in case.
430 $ref_id = ($_REQUEST['radio_type_of_payment'] == 'copay') ? $session_id : $payment_id;
431 $payment_key = $form_pid . '.' . preg_replace('/[^0-9]/', '', $timestamp) . '.' . $ref_id;
433 // get facility from encounter
434 $tmprow = sqlQuery("SELECT facility_id FROM form_encounter WHERE encounter = ?", array($payrow['encounter']));
435 $frow = sqlQuery("SELECT * FROM facility " . " WHERE id = ?", array($tmprow['facility_id']
438 // Now proceed with printing the receipt.
441 <title><?php echo xlt('Receipt for Payment'); ?></title>
442 <script src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery/dist/jquery.min.js"></script>
443 <script>
445 function goHome() {
446 window.location.replace("./patient/onsiteactivityviews");
449 function notifyPatient() {
450 let pid = <?php echo js_escape($pid); ?>;
451 let note = $('#pop_receipt').html();
452 let formURL = './messaging/handle_note.php';
453 let owner = <?php echo js_escape($adminUser['recip_id']); ?>;
454 let sn = <?php echo js_escape($adminUser['username']); ?>;
455 let rid = <?php echo js_escape($portalPatient['recip_id']); ?>;
456 let rn = <?php echo js_escape($portalPatient['username']); ?>;
457 $.ajax({
458 url: formURL,
459 type: "POST",
460 data: {
461 'csrf_token_form': <?php echo js_escape(CsrfUtils::collectCsrfToken('messages-portal')); ?>,
462 'task': 'add',
463 'pid': pid,
464 'inputBody': note,
465 'title': 'Bill/Collect',
466 'recipient_name': rn,
467 'recipient_id': rid,
468 'sender_id': owner,
469 'sender_name': sn
471 success: function (data, textStatus, jqXHR) {
472 alert('Receipt sent to patient via Messages.')
474 error: function (jqXHR, status, error) {
475 console.log(status + ": " + error);
479 </script>
480 <?php
481 ob_start();
482 echo '<htlm><head></head><body style="text-align: center; margin: auto;">';
484 <div id='pop_receipt' style='display: block'>
486 <h2><?php echo xlt('Receipt for Payment'); ?></h2>
487 <p><?php echo text($frow['name']) ?>
488 <br /><?php echo text($frow['street']) ?>
489 <br /><?php echo text($frow['city'] . ', ' . $frow['state']) . ' ' . text($frow['postal_code']) ?>
490 <br /><?php echo text($frow['phone']) ?>
492 <div class="text-center" style="margin: auto;">
493 <table border='0' cellspacing='8' class="text-center" style="margin: auto;">
494 <tr>
495 <td><?php echo xlt('Date'); ?>:</td>
496 <td><?php echo text(oeFormatSDFT(strtotime($payrow['dtime']))) ?></td>
497 </tr>
498 <tr>
499 <td><?php echo xlt('Patient'); ?>:</td>
500 <td><?php echo text($patdata['fname']) . " " . text($patdata['mname']) . " " . text($patdata['lname']) . " (" . text($patdata['pubpid']) . ")" ?></td>
501 </tr>
502 <tr>
503 <td><?php echo xlt('Paid Via'); ?>:</td>
504 <td><?php echo generate_display_field(array('data_type' => '1', 'list_id' => 'payment_method'), $payrow['method']); ?></td>
505 </tr>
506 <tr>
507 <td><?php echo xlt('Authorized Id'); ?>:</td>
508 <td><?php echo text($payrow['source']) ?></td>
509 </tr>
510 <tr>
511 <td><?php echo xlt('Amount for This Visit'); ?>:</td>
512 <td><?php echo text(oeFormatMoney($payrow['amount1'])) ?></td>
513 </tr>
514 <tr>
515 <td><?php echo xlt('Amount for Past Balance'); ?>:</td>
516 <td><?php echo text(oeFormatMoney($payrow['amount2'])) ?></td>
517 </tr>
518 <tr>
519 <td><?php echo xlt('Received By'); ?>:</td>
520 <td><?php echo text($payrow['user']) ?></td>
521 </tr>
522 </table>
523 </div>
524 </div>
525 <button class='btn btn-sm' type='button' onclick='goHome()' id='returnhome'><?php echo xla('Return Home'); ?></button>
526 <button class='btn btn-sm' type='button' onclick="notifyPatient()"><?php echo xla('Notify Patient'); ?></button>
527 </body></html>
528 <?php
529 ob_end_flush();
530 } else {
532 // Here we display the form for data entry.
535 <title><?php echo xlt('Record Payment'); ?></title>
536 <style>
537 .dehead {
538 color: #000000;
539 font-weight: bold
541 .detail {
542 padding: 1px 1px;
543 color: #000000;
544 font-weight: normal
546 </style>
547 <script src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-creditcardvalidator/jquery.creditCardValidator.js"></script>
548 <script src="<?php echo $GLOBALS['webroot'] ?>/library/textformat.js?v=<?php echo $v_js_includes; ?>"></script>
549 <script>
550 var chargeMsg = <?php $amsg = xl('Payment was successfully authorized and your card is charged.') . "\n" .
551 xl("You will be notified when your payment is applied for this invoice.") . "\n" .
552 xl('Until then you will continue to see payment details here.') . "\n" . xl('Thank You.');
553 echo json_encode($amsg);
555 var publicKey = <?php echo json_encode($cryptoGen->decryptStandard($GLOBALS['gateway_public_key'])); ?>;
556 var apiKey = <?php echo json_encode($cryptoGen->decryptStandard($GLOBALS['gateway_api_key'])); ?>;
558 function calctotal() {
559 var flag = 0;
560 var f = document.forms["invoiceForm"];
561 var total = 0;
562 for (var i = 0; i < f.elements.length; ++i) {
563 var elem = f.elements[i];
564 var ename = elem.name;
565 if (ename.indexOf('form_upay[') == 0 || ename.indexOf('form_bpay[') == 0) {
566 if (elem.value.length > 0) {
567 total += Number(elem.value);
568 if (total < 0) flag = 1;
572 f.form_paytotal.value = Number(total).toFixed(2);
573 if (flag) {
574 $('#invoiceForm')[0].reset();
575 alert(<?php echo xlj('Negative payments not accepted'); ?>)
577 return true;
580 function coloring() {
581 for (var i = 1; ; ++i) {
582 if (document.getElementById('paying_' + i)) {
583 paying = document.getElementById('paying_' + i).value * 1;
584 patient_balance = document.getElementById('duept_' + i).innerHTML * 1;
585 if (patient_balance > 0 && paying > 0) {
586 if (paying > patient_balance) {
587 document.getElementById('paying_' + i).style.background = '#FF0000';
589 else if (paying < patient_balance) {
590 document.getElementById('paying_' + i).style.background = '#99CC00';
592 else if (paying == patient_balance) {
593 document.getElementById('paying_' + i).style.background = '#ffffff';
596 else {
597 document.getElementById('paying_' + i).style.background = '#ffffff';
600 else {
601 break;
606 function CheckVisible(MakeBlank) {//Displays and hides the check number text box.
607 if (document.getElementById('form_method').options[document.getElementById('form_method').selectedIndex].value == 'check_payment' ||
608 document.getElementById('form_method').options[document.getElementById('form_method').selectedIndex].value == 'bank_draft') {
609 document.getElementById('check_number').disabled = false;
611 else {
612 document.getElementById('check_number').disabled = true;
616 function validate() {
617 var f = document.forms["invoiceForm"];
618 ok = -1;
619 //no checks taken here....
620 issue = 'no';
621 if (document.getElementById('radio_type_of_payment_self1').checked == false &&
622 document.getElementById('radio_type_of_payment1').checked == false
623 && document.getElementById('radio_type_of_payment2').checked == false
624 && document.getElementById('radio_type_of_payment4').checked == false) {
625 alert("<?php //echo addslashes( xl('Please Select Type Of Payment.')) ?>");
626 return false;
628 if (document.getElementById('radio_type_of_payment_self1').checked == true || document.getElementById('radio_type_of_payment1').checked == true) {
629 for (var i = 0; i < f.elements.length; ++i) {
630 var elem = f.elements[i];
631 var ename = elem.name;
632 if (ename.indexOf('form_upay[0') == 0) //Today is this text box.
634 if (elem.value * 1 > 0) {//A warning message, if the amount is posted with out encounter.
635 if (confirm(<?php echo xlj('Are you sure to post for today?'); ?>)) {
636 ok = 1;
638 else {
639 elem.focus();
640 return false;
643 break;
647 else if (document.getElementsByName('form_paytotal')[0].value <= 0)//total 0
649 alert(<?php echo xlj('Invalid Total!'); ?>)
650 return false;
652 if (ok == -1) {
653 if (confirm(<?php echo xlj('Payment Validated: Save?'); ?>)) {
654 return true;
656 else {
657 return false;
662 function cursor_pointer() {//Point the cursor to the latest encounter(Today)
663 var f = document.forms["invoiceForm"];
664 var total = 0;
665 for (var i = 0; i < f.elements.length; ++i) {
666 var elem = f.elements[i];
667 var ename = elem.name;
668 if (ename.indexOf('form_upay[') == 0) {
669 elem.focus();
670 break;
675 function make_it_hide_enc_pay() {
676 document.getElementById('td_head_insurance_payment').style.display = "none";
677 document.getElementById('td_head_patient_co_pay').style.display = "none";
678 document.getElementById('td_head_co_pay').style.display = "none";
679 document.getElementById('td_head_insurance_balance').style.display = "none";
680 for (var i = 1; ; ++i) {
681 var td_inspaid_elem = document.getElementById('td_inspaid_' + i)
682 var td_patient_copay_elem = document.getElementById('td_patient_copay_' + i)
683 var td_copay_elem = document.getElementById('td_copay_' + i)
684 var balance_elem = document.getElementById('balance_' + i)
685 if (td_inspaid_elem) {
686 td_inspaid_elem.style.display = "none";
687 td_patient_copay_elem.style.display = "none";
688 td_copay_elem.style.display = "none";
689 balance_elem.style.display = "none";
691 else {
692 break;
695 document.getElementById('td_total_4').style.display = "none";
696 document.getElementById('td_total_7').style.display = "none";
697 document.getElementById('td_total_8').style.display = "none";
698 document.getElementById('td_total_6').style.display = "none";
700 document.getElementById('table_display').width = "420px";
703 function make_visible() {
704 document.getElementById('td_head_rep_doc').style.display = "";
705 document.getElementById('td_head_description').style.display = "";
706 document.getElementById('td_head_total_charge').style.display = "none";
707 document.getElementById('td_head_insurance_payment').style.display = "none";
708 document.getElementById('td_head_patient_payment').style.display = "none";
709 document.getElementById('td_head_patient_co_pay').style.display = "none";
710 document.getElementById('td_head_co_pay').style.display = "none";
711 document.getElementById('td_head_insurance_balance').style.display = "none";
712 document.getElementById('td_head_patient_balance').style.display = "none";
713 for (var i = 1; ; ++i) {
714 var td_charges_elem = document.getElementById('td_charges_' + i)
715 var td_inspaid_elem = document.getElementById('td_inspaid_' + i)
716 var td_ptpaid_elem = document.getElementById('td_ptpaid_' + i)
717 var td_patient_copay_elem = document.getElementById('td_patient_copay_' + i)
718 var td_copay_elem = document.getElementById('td_copay_' + i)
719 var balance_elem = document.getElementById('balance_' + i)
720 var duept_elem = document.getElementById('duept_' + i)
721 if (td_charges_elem) {
722 td_charges_elem.style.display = "none";
723 td_inspaid_elem.style.display = "none";
724 td_ptpaid_elem.style.display = "none";
725 td_patient_copay_elem.style.display = "none";
726 td_copay_elem.style.display = "none";
727 balance_elem.style.display = "none";
728 duept_elem.style.display = "none";
730 else {
731 break;
734 document.getElementById('td_total_7').style.display = "";
735 document.getElementById('td_total_8').style.display = "";
736 document.getElementById('td_total_1').style.display = "none";
737 document.getElementById('td_total_2').style.display = "none";
738 document.getElementById('td_total_3').style.display = "none";
739 document.getElementById('td_total_4').style.display = "none";
740 document.getElementById('td_total_5').style.display = "none";
741 document.getElementById('td_total_6').style.display = "none";
743 document.getElementById('table_display').width = "505px";
746 function make_it_hide() {
747 document.getElementById('td_head_rep_doc').style.display = "none";
748 document.getElementById('td_head_description').style.display = "none";
749 document.getElementById('td_head_total_charge').style.display = "";
750 document.getElementById('td_head_insurance_payment').style.display = "";
751 document.getElementById('td_head_patient_payment').style.display = "";
752 document.getElementById('td_head_patient_co_pay').style.display = "";
753 document.getElementById('td_head_co_pay').style.display = "";
754 document.getElementById('td_head_insurance_balance').style.display = "";
755 document.getElementById('td_head_patient_balance').style.display = "";
756 for (var i = 1; ; ++i) {
757 var td_charges_elem = document.getElementById('td_charges_' + i)
758 var td_inspaid_elem = document.getElementById('td_inspaid_' + i)
759 var td_ptpaid_elem = document.getElementById('td_ptpaid_' + i)
760 var td_patient_copay_elem = document.getElementById('td_patient_copay_' + i)
761 var td_copay_elem = document.getElementById('td_copay_' + i)
762 var balance_elem = document.getElementById('balance_' + i)
763 var duept_elem = document.getElementById('duept_' + i)
764 if (td_charges_elem) {
765 td_charges_elem.style.display = "";
766 td_inspaid_elem.style.display = "";
767 td_ptpaid_elem.style.display = "";
768 td_patient_copay_elem.style.display = "";
769 td_copay_elem.style.display = "";
770 balance_elem.style.display = "";
771 duept_elem.style.display = "";
773 else {
774 break;
777 document.getElementById('td_total_1').style.display = "";
778 document.getElementById('td_total_2').style.display = "";
779 document.getElementById('td_total_3').style.display = "";
780 document.getElementById('td_total_4').style.display = "";
781 document.getElementById('td_total_5').style.display = "";
782 document.getElementById('td_total_6').style.display = "";
783 document.getElementById('td_total_7').style.display = "";
784 document.getElementById('td_total_8').style.display = "";
786 document.getElementById('table_display').width = "100%";
789 function make_visible_radio() {
790 document.getElementById('tr_radio1').style.display = "";
791 document.getElementById('tr_radio2').style.display = "none";
794 function make_hide_radio() {
795 document.getElementById('tr_radio1').style.display = "none";
796 document.getElementById('tr_radio2').style.display = "";
799 function make_visible_row() {
800 document.getElementById('table_display').style.display = "";
801 document.getElementById('table_display_prepayment').style.display = "none";
804 function make_hide_row() {
805 document.getElementById('table_display').style.display = "none";
806 document.getElementById('table_display_prepayment').style.display = "";
809 function make_self() {
810 make_visible_row();
811 make_it_hide();
812 make_it_hide_enc_pay();
813 document.getElementById('radio_type_of_payment_self1').checked = true;
814 cursor_pointer();
817 function make_insurance() {
818 make_visible_row();
819 make_it_hide();
820 cursor_pointer();
821 document.getElementById('radio_type_of_payment1').checked = true;
824 $('#paySubmit').click(function (e) {
825 e.preventDefault();e.stopPropagation();
826 $("#mode").val("portal-save");
827 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
828 let extra_values = JSON.stringify(getFormObj('paymentForm'));
829 let extra = "&inv_values=" + encodeURIComponent(inv_values) + "&extra_values=" + encodeURIComponent(extra_values);
830 let flag = 0
831 let liburl = './lib/paylib.php';
832 $.ajax({
833 type: "POST",
834 url: liburl,
835 data: $("#invoiceForm").serialize() + extra,
836 beforeSend: function (xhr) {
837 if (validateCC() !== true) return false;
838 if ($('#cardCode').val() == "" || $('#cardHolderName').val() == "" || $('#expYear').val() == "" || $('#expMonth').val() == "") {
839 alert(<?php echo xlj('Invalid Credit Card Values: Please correct'); ?>)
840 return false;
842 if (validate() != true) {
843 flag = 1;
844 alert(<?php echo xlj('Validation error: Fix and resubmit. This popup info is preserved!'); ?>)
845 return false;
847 $("#openPayModal .close").click()
849 error: function (qXHR, textStatus, errorThrow) {
850 console.log("There was an error:" + errorThrow);
852 success: function (templateHtml, textStatus, jqXHR) {
853 let msg = <?php $amsg = xl('Payment successfully sent for review and posting to your account.') . "\n" .
854 xl("You will be notified when the payment transaction is confirmed.") . "\n" .
855 xl('Until then you will continue to see payment details here.') . "\n" . xl('Thank You.');
856 echo json_encode($amsg); // backward compatable 5.0.1
858 alert(msg);
859 window.location.reload(false);
862 if (flag) {
863 $("#openPayModal .close").click();
867 $('#openPayModal').on('show.bs.modal', function () {
868 let total = $("#form_paytotal").val();
869 if(Number(total) < 1) {
870 let error = <?php echo json_encode("Please enter a payment amount"); ?>;
871 alert(error);
872 return false;
874 $("#payTotal").text(total);
875 $("#paymentAmount").val(total);
878 $("#invoiceForm").on('submit', function (e) {
879 e.preventDefault();
880 let thisform = this;
881 $("#mode").val("review-save");
882 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
883 let extra_values = JSON.stringify(getFormObj('paymentForm'));
884 let extra = "&inv_values=" + inv_values + "&extra_values=" + extra_values;
886 let flag = 0
887 let liburl = '<?php echo $GLOBALS["webroot"] ?>/portal/lib/paylib.php';
888 $.ajax({
889 type: "POST",
890 url: liburl,
891 data: $("#invoiceForm").serialize() + extra,
892 beforeSend: function (xhr) {
893 if (validate() != true) {
894 flag = 1;
895 alert(<?php echo xlj('Validation error: Fix and resubmit.'); ?>)
896 return false;
899 error: function (xhr, textStatus, error) {
900 alert(<?php echo xlj('There is a Post error'); ?>)
901 console.log("There was an error:" + textStatus);
902 return false;
904 success: function (templateHtml, textStatus, jqXHR) {
905 thisform.submit();
910 function getFormObj(formId) {
911 let formObj = {};
912 let inputs = $('#' + formId).serializeArray();
913 $.each(inputs, function (i, input) {
914 formObj[input.name] = input.value;
916 return formObj;
919 function formRepopulate(jsondata) {
920 let data = $.parseJSON(jsondata);
921 $.each(data, function (name, val) {
922 let $el = $('[name="' + name + '"]'),
923 type = $el.attr('type');
924 switch (type) {
925 case 'checkbox':
926 $el.prop('checked', true);
927 break;
928 case 'radio':
929 $el.filter('[value="' + val + '"]').prop('checked', true);
930 break;
931 default:
932 $el.val(val);
937 function getAuth() {
938 let authnum = document.getElementById("check_number").value;
939 authnum = prompt(<?php echo xlj('Please enter card comfirmation authorization'); ?>, authnum);
940 if (authnum != null) {
941 document.getElementById("check_number").value = authnum;
944 </script>
946 <body class="skin-blue" onunload='imclosing()' onLoad="cursor_pointer();"
947 style="text-align: center; margin: auto;">
949 <form id="invoiceForm" method='post' action='<?php echo $GLOBALS["webroot"] ?>/portal/portal_payment.php'>
950 <input type='hidden' name='form_pid' value='<?php echo attr($pid) ?>'/>
951 <input type='hidden' name='form_save' value='<?php echo xla('Invoice'); ?>'/>
952 <table>
953 <tr height="10">
954 <td colspan="3">&nbsp;</td>
955 </tr>
956 <tr>
957 <td colspan='3' align='center' class='text'>
958 <b><?php echo xlt('Accept Payment for'); ?>&nbsp;:&nbsp;&nbsp;<?php
959 echo text($patdata['fname']) . " " .
960 text($patdata['lname']) . " " .
961 text($patdata['mname']) . " (" .
962 text($patdata['pid']) . ")" ?></b>
963 <?php $NameNew = $patdata['fname'] . " " . $patdata['lname'] . " " . $patdata['mname']; ?>
964 </td>
965 </tr>
966 <tr height="15">
967 <td colspan='3'></td>
968 </tr>
969 <tr>
970 <td class='text'>
971 <?php echo xlt('Payment Method'); ?>:
972 </td>
973 <td colspan='2'><select name="form_method" id="form_method" class="form-control" onChange='CheckVisible("yes")'>
974 <?php
975 $query1112 = "SELECT * FROM list_options where list_id=? ORDER BY seq, title ";
976 $bres1112 = sqlStatement($query1112, array('payment_method'));
977 while ($brow1112 = sqlFetchArray($bres1112)) {
978 if ($brow1112['option_id'] != 'credit_card' || $brow1112['option_id'] == 'debit' || $brow1112['option_id'] == 'bank_draft') {
979 continue;
981 echo "<option value='" . attr($brow1112['option_id']) . "'>" .
982 text(xl_list_label($brow1112['title'])) . "</option>";
985 </select></td>
986 </tr>
987 <?php if (isset($_SESSION['authUserID'])) { ?>
988 <tr height="5">
989 <td colspan='3'></td>
990 </tr>
991 <tr>
992 <td class='text'>
993 <?php echo xlt('Authorized'); ?>:
994 </td>
995 <td colspan='2'>
996 <?php if ($ccdata['authCode'] && empty($payrow['source'])) {
997 $payrow['source'] = $ccdata['authCode'] . " : " . $ccdata['transId'];
1000 <input class="form-control form-control-sm" id='check_number' name='form_source' style='' value='<?php echo attr($payrow['source']) ?>' />
1001 </td>
1002 </tr>
1003 <?php } ?>
1004 <?php if (isset($_SESSION['authUserID'])) {
1005 $hide = '';
1006 echo '<tr height="5"><td colspan="3"></td></tr><tr">';
1007 } else {
1008 $hide = 'hidden';
1009 echo '<tr class="hidden">';
1012 <td class='text' valign="middle">
1013 <?php echo xlt('Patient Coverage'); ?>:
1014 </td>
1015 <td class='text' colspan="2">
1016 <input type="radio" name="radio_type_of_coverage" id="radio_type_of_coverage1"
1017 value="self" onClick="make_visible_radio();make_self();"/>
1018 <?php echo xlt('Self'); ?>
1019 <input type="radio" name="radio_type_of_coverage" id="radio_type_of_coverag2" value="insurance"
1020 checked="checked"
1021 onClick="make_hide_radio();make_insurance();"/>
1022 <?php echo xlt('Insurance'); ?>
1023 </td>
1024 </tr>
1025 <tr height="5">
1026 <td colspan='3'></td>
1027 </tr>
1028 <tr id="tr_radio1" style="display: none">
1029 <!-- For radio Insurance -->
1030 <td class='text' valign="top">
1031 <?php echo xlt('Payment against'); ?>:
1032 </td>
1033 <td class='text' colspan="2">
1034 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment_self1"
1035 value="cash" onClick="make_visible_row();make_it_hide_enc_pay();cursor_pointer();"/>
1036 <?php echo xlt('Encounter Payment'); ?>
1037 </td>
1038 </tr>
1039 <tr id="tr_radio2">
1040 <!-- For radio self -->
1041 <td class='text' valign="top"><?php echo xlt('Payment against'); ?>:</td>
1042 <td class='text' colspan="2">
1043 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment1" class="<?php echo $hide ? $hide : ''; ?>"
1044 value="copay" onClick="make_visible_row();cursor_pointer();"/><?php echo !$hide ? xlt('Co Pay') : ''; ?>
1045 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment2" checked="checked"
1046 value="invoice_balance" onClick="make_visible_row();"/><?php echo xlt('Invoice Balance'); ?>
1047 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment4" value="pre_payment"
1048 onClick="make_hide_row();"/><?php echo xlt('Pre Pay'); ?>
1049 </td>
1050 </tr>
1051 <tr height="15">
1052 <td colspan='3'></td>
1053 </tr>
1054 </table>
1055 <table width="20%" border="0" cellspacing="0" cellpadding="0" id="table_display_prepayment" style="margin-bottom: 10px; display: none">
1056 <tr>
1057 <td class='detail'><?php echo xlt('Pre Payment'); ?></td>
1058 <td><input class="form-control" type='text' id= 'form_prepayment' name='form_prepayment' style=''/></td>
1059 </tr>
1060 </table>
1061 <table id="table_display" style="background: #eee;" class="table table-sm table-striped table-bordered w-100">
1062 <thead>
1063 </thead>
1064 <tbody>
1065 <tr bgcolor="#cccccc" id="tr_head">
1066 <td class="dehead" width="60">
1067 <?php echo xlt('DOS') ?>
1068 </td>
1069 <td class="dehead" width="120">
1070 <?php echo xlt('Visit Reason') ?>
1071 </td>
1072 <td class="dehead" align="center" width="70" id="td_head_total_charge">
1073 <?php echo xlt('Total Charge') ?>
1074 </td>
1075 <td class="dehead" align="center" width="70" id="td_head_rep_doc" style='display: none'>
1076 <?php echo xlt('Report/ Form') ?>
1077 </td>
1078 <td class="dehead" align="center" width="200" id="td_head_description" style='display: none'>
1079 <?php echo xlt('Description') ?>
1080 </td>
1081 <td class="dehead" align="center" width="70" id="td_head_insurance_payment">
1082 <?php echo xlt('Insurance Payment') ?>
1083 </td>
1084 <td class="dehead" align="center" width="70" id="td_head_patient_payment">
1085 <?php echo xlt('Patient Payment') ?>
1086 </td>
1087 <td class="dehead" align="center" width="55" id="td_head_patient_co_pay">
1088 <?php echo xlt('Co Pay Paid') ?>
1089 </td>
1090 <td class="dehead" align="center" width="55" id="td_head_co_pay">
1091 <?php echo xlt('Required Co Pay') ?>
1092 </td>
1093 <td class="dehead" align="center" width="70" id="td_head_insurance_balance">
1094 <?php echo xlt('Insurance Balance') ?>
1095 </td>
1096 <td class="dehead" align="center" width="70" id="td_head_patient_balance">
1097 <?php echo xlt('Patient Balance') ?>
1098 </td>
1099 <td class="dehead" align="center" width="50">
1100 <?php echo xlt('Paying') ?>
1101 </td>
1102 </tr>
1103 <?php
1104 $encs = array();
1105 // Get the unbilled service charges and payments by encounter for this patient.
1107 $query = "SELECT fe.encounter, fe.reason, b.code_type, b.code, b.modifier, b.fee, " .
1108 "LEFT(fe.date, 10) AS encdate ,fe.last_level_closed " . "FROM form_encounter AS fe left join billing AS b on " .
1109 "b.pid = ? AND b.activity = 1 AND " . "b.code_type != 'TAX' AND b.fee != 0 " . "AND fe.pid = b.pid AND fe.encounter = b.encounter " .
1110 "where fe.pid = ? " . "ORDER BY b.encounter";
1111 $bres = sqlStatement($query, array($pid, $pid));
1113 while ($brow = sqlFetchArray($bres)) {
1114 $key = (int)$brow['encounter'];
1115 if (empty($encs[$key])) {
1116 $encs[$key] = array('encounter' => $brow['encounter'], 'date' => $brow['encdate'], 'last_level_closed' => $brow['last_level_closed'], 'charges' => 0, 'payments' => 0, 'reason' => $brow['reason']
1120 if ($brow['code_type'] === 'COPAY') {
1121 // $encs[$key]['payments'] -= $brow['fee'];
1122 } else {
1123 $encs[$key]['charges'] += $brow['fee'];
1124 // Add taxes.
1125 $sql_array = array();
1126 $query = "SELECT taxrates FROM codes WHERE " . "code_type = ? AND " . "code = ? AND ";
1127 array_push($sql_array, $code_types[$brow['code_type']]['id'], $brow['code']);
1128 if ($brow['modifier']) {
1129 $query .= "modifier = ?";
1130 array_push($sql_array, $brow['modifier']);
1131 } else {
1132 $query .= "(modifier IS NULL OR modifier = '')";
1135 $query .= " LIMIT 1";
1136 $trow = sqlQuery($query, $sql_array);
1137 $encs[$key]['charges'] += calcTaxes($trow, $brow['fee']);
1141 // Do the same for unbilled product sales.
1143 $query = "SELECT fe.encounter, fe.reason, s.drug_id, s.fee, " .
1144 "LEFT(fe.date, 10) AS encdate,fe.last_level_closed " .
1145 "FROM form_encounter AS fe left join drug_sales AS s " .
1146 "on s.pid = ? AND s.fee != 0 " .
1147 "AND fe.pid = s.pid AND fe.encounter = s.encounter " .
1148 "where fe.pid = ? " . "ORDER BY s.encounter";
1150 $dres = sqlStatement($query, array($pid, $pid));
1152 while ($drow = sqlFetchArray($dres)) {
1153 $key = (int)$drow['encounter'];
1154 if (empty($encs[$key])) {
1155 $encs[$key] = array(
1156 'encounter' => $drow['encounter'], 'date' => $drow['encdate'],
1157 'last_level_closed' => $drow['last_level_closed'],
1158 'charges' => 0, 'payments' => 0
1162 $encs[$key]['charges'] += $drow['fee'];
1163 // Add taxes.
1164 $trow = sqlQuery(
1165 "SELECT taxrates FROM drug_templates WHERE drug_id = ? " .
1166 "ORDER BY selector LIMIT 1",
1167 array($drow['drug_id'])
1169 $encs[$key]['charges'] += calcTaxes($trow, $drow['fee']);
1172 ksort($encs, SORT_NUMERIC);
1174 foreach ($encs as $key => $value) {
1175 $enc = $value['encounter'];
1176 $reason = $value['reason'];
1177 $dispdate = $value['date'];
1179 $inscopay = BillingUtilities::getCopay($pid, $dispdate);
1180 $patcopay = BillingUtilities::getPatientCopay($pid, $enc);
1181 // Insurance Payment
1183 $drow = sqlQuery(
1184 "SELECT SUM(pay_amount) AS payments, " .
1185 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1186 "deleted IS NULL AND pid = ? and encounter = ? AND " .
1187 "payer_type != 0 AND account_code != 'PCP'",
1188 array($pid, $enc)
1190 $dpayment = $drow['payments'];
1191 $dadjustment = $drow['adjustments'];
1192 // Patient Payment
1194 $drow = sqlQuery(
1195 "SELECT SUM(pay_amount) AS payments, SUM(adj_amount) AS adjustments " .
1196 "FROM ar_activity WHERE deleted IS NULL AND pid = ? and encounter = ? and " .
1197 "payer_type = 0 and account_code != 'PCP'",
1198 array($pid, $enc)
1200 $dpayment_pat = $drow['payments'];
1202 // NumberOfInsurance
1204 $ResultNumberOfInsurance = sqlStatement(
1205 "SELECT COUNT( DISTINCT TYPE ) NumberOfInsurance FROM insurance_data where pid = ? and provider>0 ",
1206 array($pid)
1208 $RowNumberOfInsurance = sqlFetchArray($ResultNumberOfInsurance);
1209 $NumberOfInsurance = $RowNumberOfInsurance['NumberOfInsurance'] * 1;
1210 $duept = 0;
1211 if ((($NumberOfInsurance == 0 || $value['last_level_closed'] == 4 || $NumberOfInsurance == $value['last_level_closed']))) { // Patient balance
1212 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " . "pid = ? and encounter = ? AND activity = 1", array($pid, $enc
1214 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " . "pid = ? and encounter = ? ", array($pid, $enc
1216 $drow = sqlQuery(
1217 "SELECT SUM(pay_amount) AS payments, SUM(adj_amount) AS adjustments " .
1218 "FROM ar_activity WHERE deleted IS NULL AND pid = ? and encounter = ? ",
1219 array($pid, $enc)
1221 $duept = $brow['amount'] + $srow['amount'] - $drow['payments'] - $drow['adjustments'];
1224 echoLine("form_upay[$enc]", $dispdate, $value['charges'], $dpayment_pat, ($dpayment + $dadjustment), $duept, ($enc . ': ' . $reason), $inscopay, $patcopay);
1227 // Continue with display of the data entry form.
1229 <tr>
1230 <td class="dehead" align="center"><?php echo xlt('Total'); ?></td>
1231 <td class="dehead" id='td_total_1' align="center"></td>
1232 <td class="dehead" id='td_total_2' align="center"><?php echo text(bucks($sum_charges)) ?></td>
1233 <td class="dehead" id='td_total_3' align="center"><?php echo text(bucks($sum_inspaid)) ?></td>
1234 <td class="dehead" id='td_total_4' align="center"><?php echo text(bucks($sum_ptpaid)) ?></td>
1235 <td class="dehead" id='td_total_5' align="center"><?php echo text(bucks($sum_patcopay)) ?></td>
1236 <td class="dehead" id='td_total_6' align="center"><?php echo text(bucks($sum_copay)) ?></td>
1237 <td class="dehead" id='td_total_7' align="center"><?php echo text(bucks($sum_balance)) ?></td>
1238 <td class="dehead" id='td_total_8' align="center"><?php echo text(bucks($sum_duept)) ?></td>
1239 <td class="dehead" align="center">
1240 <input class="form-control" name='form_paytotal' id='form_paytotal' value='' style='color: #3b9204;' readonly />
1241 </td>
1242 </tr>
1243 </table>
1244 <?php
1245 if (isset($ccdata["cardHolderName"])) {
1246 echo '<div class="col-5"><div class="card panel-default height">';
1247 if (!isset($_SESSION['authUserID'])) {
1248 echo '<div class="card-heading">' . xlt("Payment Information") .
1249 '<span style="color: #cc0000"><em> ' . xlt("Pending Auth since") . ': </em>' . text($edata["date"]) . '</span></div>';
1250 } else {
1251 echo '<div class="card-heading">' . xlt("Audit Payment") .
1252 '<span style="color: #cc0000"><em> ' . xlt("Pending since") . ': </em>' . text($edata["date"]) . '</span>' .
1253 ' <button type="button" class="btn btn-warning btn-sm" onclick="getAuth()">' . xlt("Authorize") . '</button></div>';
1255 } else {
1256 echo '<div style="display:none" class="col-6"><div class="card panel-default height">' .
1257 '<div class="card-heading">' . xlt("Payment Information") . ' </div>';
1260 <div class="card-body">
1261 <span class="font-weight-bold"><?php echo xlt('Card Name'); ?>: </span><span id="cn"><?php echo text($ccdata["cc_type"]) ?></span><br />
1262 <span class="font-weight-bold"><?php echo xlt('Name on Card'); ?>: </span><span id="nc"><?php echo text($ccdata["cardHolderName"]) ?></span>
1263 <span class="font-weight-bold"><?php echo xlt('Card Holder Zip'); ?>: </span><span id="czip"><?php echo text($ccdata["zip"]) ?></span><br />
1264 <span class="font-weight-bold"><?php echo xlt('Card Number'); ?>: </span><span id="ccn">
1265 <?php
1266 if (isset($_SESSION['authUserID']) || isset($ccdata["transId"])) {
1267 echo text($ccdata["cardNumber"]) . "</span><br />";
1268 } else {
1269 echo "********** " . text(substr($ccdata["cardNumber"], -4)) . "</span><br />";
1272 <?php
1273 if (!isset($ccdata["transId"])) { ?>
1274 <span class="font-weight-bold"><?php echo xlt('Exp Date'); ?>: </span><span id="ed"><?php echo text($ccdata["month"]) . "/" . text($ccdata["year"]) ?></span>
1275 <span class="font-weight-bold"><?php echo xlt('CVV'); ?>: </span><span id="cvvpin"><?php echo text($ccdata["cardCode"]) ?></span><br />
1276 <?php } else { ?>
1277 <span class="font-weight-bold"><?php echo xlt('Transaction Id'); ?>: </span><span id="ed"><?php echo text($ccdata["transId"]) . "/" . text($ccdata["year"]) ?></span>
1278 <span class="font-weight-bold"><?php echo xlt('Authorization'); ?>: </span><span id="cvvpin"><?php echo text($ccdata["authCode"]) ?></span><br />
1279 <?php } ?>
1280 <span class="font-weight-bold"><?php echo xlt('Charge Total'); ?>: </span><span id="ct"><?php echo text($invdata["form_paytotal"]) ?></span><br />
1281 </div>
1282 </div>
1283 </div>
1284 <div>
1285 <?php
1286 if (!isset($_SESSION['authUserID'])) {
1287 if (!isset($ccdata["cardHolderName"])) {
1288 if ($GLOBALS['payment_gateway'] == 'Sphere') {
1289 echo SpherePayment::renderSphereHtml('patient');
1290 } else {
1291 echo '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#openPayModal">' . xlt("Pay Invoice") . '</button>';
1293 } else {
1294 echo '<h4><span class="bg-danger">' . xlt("Locked Payment Pending") . '</span></h4>';
1296 } else {
1297 echo "<button type='submit' class='btn btn-success' form='invoiceForm'>" . xlt('Post Payment') . "</button>";
1300 </div>
1301 <input type="hidden" name="hidden_patient_code" id="hidden_patient_code" value="<?php echo attr($pid); ?>"/>
1302 <input type='hidden' name='mode' id='mode' value=''/>
1303 </form>
1305 <script>
1306 if (typeof jsondata !== 'undefined') {
1307 formRepopulate(jsondata);
1309 calctotal();
1310 </script>
1311 <!-- credit payment modal -->
1312 <div id="openPayModal" class="modal fade" role="dialog">
1313 <div class="modal-dialog">
1314 <div class="modal-content">
1315 <div class="modal-header">
1316 <h4><?php echo xlt('Submit Payment for Authorization'); ?></h4>
1317 <!--<button type="button" class="close" data-dismiss="modal">&times;</button>-->
1318 </div>
1319 <div class="modal-body">
1320 <?php if ($GLOBALS['payment_gateway'] != 'Stripe' && $GLOBALS['payment_gateway'] != 'Sphere') { ?>
1321 <form id='paymentForm' method='post' action='<?php echo $GLOBALS["webroot"] ?>/portal/lib/paylib.php'>
1322 <fieldset>
1323 <div class="form-group">
1324 <label label-default="label-default"
1325 class="control-label"><?php echo xlt('Name on Card'); ?></label>
1326 <div class="controls">
1327 <input name="cardHolderName" id="cardHolderName" type="text" class="form-control" pattern="\w+ \w+.*" title="<?php echo xla('Fill your first and last name'); ?>" value="<?php echo attr($patdata['fname']) . ' ' . attr($patdata['lname']) ?>" />
1328 </div>
1329 </div>
1330 <div class="form-group">
1331 <label class="control-label"><?php echo xlt('Card Number'); ?></label>
1332 <div class="controls">
1333 <div class="row">
1334 <div class="col-sm-12">
1335 <input name="cardNumber" id="cardNumber" type="text" class="form-control inline col-sm-4" autocomplete="off" maxlength="19" pattern="\d" onchange="validateCC()" title="<?php echo xla('Card Number'); ?>" value="" />&nbsp;&nbsp;
1336 <h4 name="cardtype" id="cardtype" style="display: inline-block; color:#cc0000;"><?php echo xlt('Validating') ?></h4>
1337 </div>
1338 </div>
1339 </div>
1340 </div>
1341 <div class="form-group">
1342 <label label-default="label-default"><?php echo xlt('Card Expiry Date and Card Holders Zip'); ?></label>
1343 <div class="controls">
1344 <div class="row">
1345 <div class="col-md-4">
1346 <select name="month" id="expMonth" class="form-control">
1347 <option value=""><?php echo xlt('Select Month'); ?></option>
1348 <option value="01"><?php echo xlt('January'); ?></option>
1349 <option value="02"><?php echo xlt('February'); ?></option>
1350 <option value="03"><?php echo xlt('March'); ?></option>
1351 <option value="04"><?php echo xlt('April'); ?></option>
1352 <option value="05"><?php echo xlt('May'); ?></option>
1353 <option value="06"><?php echo xlt('June'); ?></option>
1354 <option value="07"><?php echo xlt('July'); ?></option>
1355 <option value="08"><?php echo xlt('August'); ?></option>
1356 <option value="09"><?php echo xlt('September'); ?></option>
1357 <option value="10"><?php echo xlt('October'); ?></option>
1358 <option value="11"><?php echo xlt('November'); ?></option>
1359 <option value="12"><?php echo xlt('December'); ?></option>
1360 </select>
1361 </div>
1362 <div class="col-md-4">
1363 <select name="year" id="expYear" class="form-control">
1364 <option value=""><?php echo xlt('Select Year'); ?></option>
1365 <option value="2019">2019</option>
1366 <option value="2020">2020</option>
1367 <option value="2021">2021</option>
1368 <option value="2022">2022</option>
1369 <option value="2023">2023</option>
1370 <option value="2024">2024</option>
1371 <option value="2025">2025</option>
1372 <option value="2026">2026</option>
1373 <option value="2027">2027</option>
1374 <option value="2028">2028</option>
1375 </select>
1376 </div>
1377 <div class="col-md-4">
1378 <input name="zip" id="cczip" type="text" class="form-control" pattern="\d" title="<?php echo xla('Enter Your Zip'); ?>" placeholder="<?php echo xla('Card Holder Zip'); ?>" value="<?php echo attr($patdata['postal_code']) ?>"/>
1379 </div>
1380 </div>
1381 </div>
1382 </div>
1383 <div class="form-group">
1384 <label label-default="label-default" class="control-label"><?php echo xlt('Card CVV'); ?></label>
1385 <div class="controls">
1386 <div class="row">
1387 <div class="col-md-3">
1388 <input name="cardCode" id="cardCode" type="text" class="form-control" autocomplete="off" maxlength="4" onfocus="validateCC()" title="<?php echo xla('Three or four digits at back of your card'); ?>" value="" />
1389 </div>
1390 <div class="col-md-3">
1391 <img src='./images/img_cvc.png' style='height: 40px; width: auto' />
1392 </div>
1393 <div class="col-md-6">
1394 <h4 style="display: inline-block;"><?php echo xlt('Payment Amount'); ?>:&nbsp;
1395 <span class="font-weight-bold"><span id="payTotal"></span></span></h4>
1396 </div>
1397 </div>
1398 </div>
1399 </div>
1400 <input type='hidden' name='pid' id='pid' value='<?php echo attr($pid) ?>'/>
1401 <input type='hidden' name='mode' id='mode' value=''/>
1402 <input type='hidden' name='cc_type' id='cc_type' value=''/>
1403 <input type='hidden' name='payment' id='paymentAmount' value=''/>
1404 <input type='hidden' name='invValues' id='invValues' value=''/>
1405 <input type="hidden" name="dataValue" id="dataValue" />
1406 <input type="hidden" name="dataDescriptor" id="dataDescriptor" />
1407 </fieldset>
1408 </form>
1409 <?php } else { ?>
1410 <form method="post" name="payment-form" id="payment-form">
1411 <fieldset>
1412 <div class="form-group">
1413 <label label-default="label-default"><?php echo xlt('Name on Card'); ?></label>
1414 <div class="controls">
1415 <input name="cardHolderName" id="cardHolderName" type="text" class="form-control" pattern="\w+ \w+.*" title="<?php echo xla('Fill your first and last name'); ?>" value="<?php echo attr($patdata['fname']) . ' ' . attr($patdata['lname']) ?>" />
1416 </div>
1417 </div>
1418 <div class="form-group">
1419 <label for="card-element"><?php echo xlt('Credit or Debit Card') ?></label>
1420 <div class="form-group" id="card-element"></div>
1421 <div id="card-errors" role="alert"></div>
1422 </div>
1423 <div class="col-md-6">
1424 <h4 style="display: inline-block;"><?php echo xlt('Payment Amount'); ?>:&nbsp;
1425 <strong><span id="payTotal"></span></strong></h4>
1426 </div>
1427 <input type='hidden' name='mode' id='mode' value=''/>
1428 <input type='hidden' name='cc_type' id='cc_type' value=''/>
1429 <input type='hidden' name='payment' id='paymentAmount' value=''/>
1430 <input type='hidden' name='invValues' id='invValues' value=''/>
1431 </fieldset>
1432 </form>
1433 <?php } ?>
1434 </div>
1435 <!-- Body -->
1436 <div class="modal-footer">
1437 <div class="button-group">
1438 <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo xlt('Cancel'); ?></button>
1439 <?php
1440 if ($GLOBALS['payment_gateway'] == 'InHouse') { ?>
1441 <button id="paySubmit" class="btn btn-primary"><?php echo xlt('Send Payment'); ?></button>
1442 <?php } elseif ($GLOBALS['payment_gateway'] == 'AuthorizeNet') { ?>
1443 <button id="payAurhorizeNet" class="btn btn-primary"
1444 onclick="sendPaymentDataToAnet(event)"><?php echo xlt('Pay Now'); ?></button>
1445 <?php }
1446 if ($GLOBALS['payment_gateway'] == 'Stripe') { ?>
1447 <button id="stripeSubmit" class="btn btn-primary"><?php echo xlt('Pay Now'); ?></button>
1448 <?php } ?>
1449 </div>
1450 </div>
1451 </div>
1452 </div>
1453 </div>
1454 <script>
1455 var ccerr = <?php echo xlj('Invalid Credit Card Number'); ?>
1457 // In House CC number Validation
1458 /*$('#cardNumber').validateCreditCard(function (result) {
1459 var r = (result.card_type === null ? '' : result.card_type.name.toUpperCase())
1460 var v = (result.valid === true ? ' Valid Number' : ' Validating')
1461 if (result.valid === true) {
1462 document.getElementById("cardtype").style.color = "#00aa00";
1463 } else {
1464 document.getElementById("cardtype").style.color = "#aa0000";
1466 $('#cardtype').text(r + v);
1467 });*/
1469 // In House CC Validation
1470 function validateCC() {
1471 var result = $('#cardNumber').validateCreditCard();
1472 var r = (result.card_type == null ? '' : result.card_type.name.toUpperCase())
1473 var v = (result.valid == true ? ' Valid Card Number' : ' Invalid Card Number')
1474 if (result.valid === true) {
1475 document.getElementById("cardtype").style.color = "#00aa00";
1476 } else {
1477 document.getElementById("cardtype").style.color = "#aa0000";
1479 $('#cardtype').text(r + v);
1480 $('#cc_type').val(r);
1481 if (!result.valid) {
1482 alert(ccerr);
1483 return false;
1485 else {
1486 return true;
1489 </script>
1491 <?php if ($GLOBALS['payment_gateway'] == 'AuthorizeNet' && isset($_SESSION['patient_portal_onsite_two'])) {
1492 // Include Authorize.Net dependency to tokenize card.
1493 // Will return a token to use for payment request keeping
1494 // credit info off the server.
1496 <script>
1497 function sendPaymentDataToAnet(e) {
1498 e.preventDefault();
1499 const authData = {};
1500 authData.clientKey = publicKey;
1501 authData.apiLoginID = apiKey;
1503 const cardData = {};
1504 cardData.cardNumber = document.getElementById("cardNumber").value;
1505 cardData.month = document.getElementById("expMonth").value;
1506 cardData.year = document.getElementById("expYear").value;
1507 cardData.cardCode = document.getElementById("cardCode").value;
1508 cardData.fullName = document.getElementById("cardHolderName").value;
1509 cardData.zip = document.getElementById("cczip").value;
1511 const secureData = {};
1512 secureData.authData = authData;
1513 secureData.cardData = cardData;
1515 Accept.dispatchData(secureData, acceptResponseHandler);
1517 function acceptResponseHandler(response) {
1518 if (response.messages.resultCode === "Error") {
1519 let i = 0;
1520 let errorMsg = '';
1521 while (i < response.messages.message.length) {
1522 errorMsg = errorMsg + response.messages.message[i].code + ": " +response.messages.message[i].text;
1523 console.log(errorMsg);
1524 i = i + 1;
1526 alert(errorMsg);
1527 } else {
1528 paymentFormUpdate(response.opaqueData);
1533 function paymentFormUpdate(opaqueData) {
1534 // this is card tokenized
1535 document.getElementById("dataDescriptor").value = opaqueData.dataDescriptor;
1536 document.getElementById("dataValue").value = opaqueData.dataValue;
1537 let oForm = document.forms['paymentForm'];
1538 oForm.elements['mode'].value = "AuthorizeNet";
1539 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
1540 document.getElementById("invValues").value = inv_values;
1542 // empty out the fields before submitting to server.
1543 document.getElementById("cardNumber").value = "";
1544 document.getElementById("expMonth").value = "";
1545 document.getElementById("expYear").value = "";
1546 document.getElementById("cardCode").value = "";
1548 // Submit payment to server
1549 fetch('./lib/paylib.php', {
1550 method: 'POST',
1551 body: new FormData(oForm)
1552 }).then(function(response) {
1553 if (!response.ok) {
1554 throw Error(response.statusText);
1556 return response.text();
1557 }).then(function(data) {
1558 if(data !== 'ok') {
1559 alert(data);
1560 return;
1562 alert(chargeMsg);
1563 window.location.reload(false);
1564 }).catch(function(error) {
1565 alert(error)
1568 </script>
1569 <?php } // end authorize.net ?>
1571 <?php if ($GLOBALS['payment_gateway'] == 'Stripe' && isset($_SESSION['patient_portal_onsite_two'])) { // Begin Include Stripe ?>
1572 <script>
1573 const stripe = Stripe(publicKey);
1574 const elements = stripe.elements();// Custom styling can be passed to options when creating an Element.
1575 const style = {
1576 base: {
1577 color: '#32325d',
1578 lineHeight: '1.2rem',
1579 fontSmoothing: 'antialiased',
1580 fontSize: '16px',
1581 '::placeholder': {
1582 color: '#8e8e8e'
1585 invalid: {
1586 color: '#fa755a',
1587 iconColor: '#fa755a'
1591 // Create an instance of the card Element.
1592 const card = elements.create('card', {style: style});
1593 // Add an instance of the card Element into the `card-element` <div>.
1594 card.mount('#card-element');
1595 // Handle real-time validation errors from the card Element.
1596 card.addEventListener('change', function (event) {
1597 let displayError = document.getElementById('card-errors');
1598 if (event.error) {
1599 displayError.textContent = event.error.message;
1600 } else {
1601 displayError.textContent = '';
1604 // Handle form submission.
1605 let form = document.getElementById('stripeSubmit');
1606 form.addEventListener('click', function (event) {
1607 event.preventDefault();
1608 stripe.createToken(card).then(function (result) {
1609 if (result.error) {
1610 // Inform the user if there was an error.
1611 let errorElement = document.getElementById('card-errors');
1612 errorElement.textContent = result.error.message;
1613 } else {
1614 // Send the token to server.
1615 stripeTokenHandler(result.token);
1619 // Submit the form with the token ID.
1620 function stripeTokenHandler(token) {
1621 // Insert the token ID into the form so it gets submitted to the server
1622 let oForm = document.forms['payment-form'];
1623 oForm.elements['mode'].value = "Stripe";
1625 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
1626 document.getElementById("invValues").value = inv_values;
1628 let hiddenInput = document.createElement('input');
1629 hiddenInput.setAttribute('type', 'hidden');
1630 hiddenInput.setAttribute('name', 'stripeToken');
1631 hiddenInput.setAttribute('value', token.id);
1632 oForm.appendChild(hiddenInput);
1634 // Submit payment to server
1635 fetch('./lib/paylib.php', {
1636 method: 'POST',
1637 body: new FormData(oForm)
1638 }).then(function(response) {
1639 if (!response.ok) {
1640 throw Error(response.statusText);
1642 return response.text();
1643 }).then(function(data) {
1644 if(data !== 'ok') {
1645 alert(data);
1646 return;
1648 alert(chargeMsg);
1649 window.location.reload(false);
1650 }).catch(function(error) {
1651 alert(error)
1654 </script>
1655 <?php } ?>
1657 <?php
1658 if ($GLOBALS['payment_gateway'] == 'Sphere' && isset($_SESSION['patient_portal_onsite_two'])) {
1659 echo (new SpherePayment('patient', $pid))->renderSphereJs();
1663 </body>
1664 <?php } // end else display ?>