Fixes #5182 set correct patient language system (#5189)
[openemr.git] / portal / portal_payment.php
blobe0a43b594a5d2e0c9bf5b96824b7a103866a28e9
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");
41 require_once("$srcdir/payment.inc.php");
42 require_once("$srcdir/forms.inc");
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\PaymentProcessing\Sphere\SpherePayment;
51 $cryptoGen = new CryptoGen();
53 $appsql = new ApplicationTable();
54 $pid = isset($_REQUEST['pid']) ? $_REQUEST['pid'] : $pid;
55 $pid = $_REQUEST['hidden_patient_code'] > 0 ? $_REQUEST['hidden_patient_code'] : $pid;
56 $recid = isset($_REQUEST['recid']) ? (int) $_REQUEST['recid'] : 0;
57 $adminUser = '';
58 $portalPatient = '';
60 $query = "SELECT pao.portal_username as recip_id, Concat_Ws(' ', patient_data.fname, patient_data.lname) as username FROM patient_data " .
61 "LEFT JOIN patient_access_onsite pao ON pao.pid = patient_data.pid " .
62 "WHERE patient_data.pid = ? AND pao.portal_pwd_status = 1";
63 $portalPatient = sqlQueryNoLog($query, $pid);
64 if ($_SESSION['authUserID']) {
65 $query = "SELECT users.username as recip_id, users.authorized as dash, CONCAT(users.fname,' ',users.lname) as username " .
66 "FROM users WHERE id = ?";
67 $adminUser = sqlQueryNoLog($query, $_SESSION['authUserID']);
70 if ($recid) {
71 $edata = $appsql->getPortalAuditRec($recid);
72 } else {
73 $edata = $appsql->getPortalAudit($pid, 'review', 'payment');
75 $ccdata = array();
76 $invdata = array();
77 if ($edata) {
78 $ccdata = json_decode($cryptoGen->decryptStandard($edata['checksum']), true);
79 $invdata = json_decode($edata['table_args'], true);
80 echo "<script>var jsondata='" . $edata['table_args'] . "';var ccdata='" . $edata['checksum'] . "'</script>";
83 function bucks($amount)
85 if ($amount) {
86 $amount = oeFormatMoney($amount);
87 return $amount;
90 return '';
93 function rawbucks($amount)
95 if ($amount) {
96 $amount = sprintf("%.2f", $amount);
97 return $amount;
100 return '';
103 // Display a row of data for an encounter.
105 $var_index = 0;
106 $sum_charges = $sum_ptpaid = $sum_inspaid = $sum_duept = $sum_copay = $sum_patcopay = $sum_balance = 0;
107 function echoLine($iname, $date, $charges, $ptpaid, $inspaid, $duept, $encounter = 0, $copay = 0, $patcopay = 0)
109 global $sum_charges, $sum_ptpaid, $sum_inspaid, $sum_duept, $sum_copay, $sum_patcopay, $sum_balance;
110 global $var_index;
111 $var_index++;
112 $balance = bucks($charges - $ptpaid - $inspaid);
113 $balance = (round($duept, 2) != 0) ? 0 : $balance; // if balance is due from patient, then insurance balance is displayed as zero
114 $encounter = $encounter ? $encounter : '';
115 echo " <tr id='tr_" . attr($var_index) . "' >\n";
116 echo " <td class='detail'>" . text(oeFormatShortDate($date)) . "</td>\n";
117 echo " <td class='detail' id='" . attr($date) . "' align='left'>" . text($encounter) . "</td>\n";
118 echo " <td class='detail' align='center' id='td_charges_$var_index' >" . text(bucks($charges)) . "</td>\n";
119 echo " <td class='detail' align='center' id='td_inspaid_$var_index' >" . text(bucks($inspaid * -1)) . "</td>\n";
120 echo " <td class='detail' align='center' id='td_ptpaid_$var_index' >" . text(bucks($ptpaid * -1)) . "</td>\n";
121 echo " <td class='detail' align='center' id='td_patient_copay_$var_index' >" . text(bucks($patcopay)) . "</td>\n";
122 echo " <td class='detail' align='center' id='td_copay_$var_index' >" . text(bucks($copay)) . "</td>\n";
123 echo " <td class='detail' align='center' id='balance_$var_index'>" . text(bucks($balance)) . "</td>\n";
124 echo " <td class='detail' align='center' id='duept_$var_index'>" . text(bucks(round($duept, 2) * 1)) . "</td>\n";
125 echo " <td class='detail' align='center'><input class='form-control' name='" . attr($iname) . "' id='paying_" . attr($var_index) .
126 "' " . " value='" . '' . "' onchange='coloring();calctotal()' autocomplete='off' " . "onkeyup='calctotal()'/></td>\n";
127 echo " </tr>\n";
129 $sum_charges += (float)$charges * 1;
130 $sum_ptpaid += (float)$ptpaid * -1;
131 $sum_inspaid += (float)$inspaid * -1;
132 $sum_duept += (float)$duept * 1;
133 $sum_patcopay += (float)$patcopay * 1;
134 $sum_copay += (float)$copay * 1;
135 $sum_balance += (float)$balance * 1;
138 // We use this to put dashes, colons, etc. back into a timestamp.
140 function decorateString($fmt, $str)
142 $res = '';
143 while ($fmt) {
144 $fc = substr($fmt, 0, 1);
145 $fmt = substr($fmt, 1);
146 if ($fc == '.') {
147 $res .= substr($str, 0, 1);
148 $str = substr($str, 1);
149 } else {
150 $res .= $fc;
154 return $res;
157 // Compute taxes from a tax rate string and a possibly taxable amount.
159 function calcTaxes($row, $amount)
161 $total = 0;
162 if (empty($row['taxrates'])) {
163 return $total;
166 $arates = explode(':', $row['taxrates']);
167 if (empty($arates)) {
168 return $total;
171 foreach ($arates as $value) {
172 if (empty($value)) {
173 continue;
176 $trow = sqlQuery("SELECT option_value FROM list_options WHERE " . "list_id = 'taxrate' AND option_id = ? LIMIT 1", array($value
178 if (empty($trow['option_value'])) {
179 echo "<!-- Missing tax rate '" . text($value) . "'! -->\n";
180 continue;
183 $tax = sprintf("%01.2f", $amount * $trow['option_value']);
184 // echo "<!-- Rate = '$value', amount = '$amount', tax = '$tax' -->\n";
185 $total += $tax;
188 return $total;
191 $now = time();
192 $today = date('Y-m-d', $now);
193 $timestamp = date('Y-m-d H:i:s', $now);
195 $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
198 $alertmsg = ''; // anything here pops up in an alert box
200 // If the Save button was clicked...
201 if ($_POST['form_save']) {
202 $form_pid = $_POST['form_pid'];
203 $form_method = trim($_POST['form_method']);
204 $form_source = trim($_POST['form_source']);
205 $patdata = getPatientData($form_pid, 'fname,mname,lname,pubpid');
206 $NameNew = $patdata['fname'] . " " . $patdata['lname'] . " " . $patdata['mname'];
208 if ($_REQUEST['radio_type_of_payment'] == 'pre_payment') {
209 $payment_id = sqlInsert(
210 "insert into ar_session set " .
211 "payer_id = ?" .
212 ", patient_id = ?" .
213 ", user_id = ?" .
214 ", closed = ?" .
215 ", reference = ?" .
216 ", check_date = now() , deposit_date = now() " .
217 ", pay_total = ?" .
218 ", payment_type = 'patient'" .
219 ", description = ?" .
220 ", adjustment_code = 'pre_payment'" .
221 ", post_to_date = now() " .
222 ", payment_method = ?",
223 array(0, $form_pid, $_SESSION['authUserID'], 0, $form_source, $_REQUEST['form_prepayment'], $NameNew, $form_method)
226 frontPayment($form_pid, 0, $form_method, $form_source, $_REQUEST['form_prepayment'], 0, $timestamp);//insertion to 'payments' table.
229 if ($_POST['form_upay'] && $_REQUEST['radio_type_of_payment'] != 'pre_payment') {
230 foreach ($_POST['form_upay'] as $enc => $payment) {
231 if ($amount = (float)$payment) {
232 $zero_enc = $enc;
234 //----------------------------------------------------------------------------------------------------
235 //Fetching the existing code and modifier
236 $ResultSearchNew = sqlStatement(
237 "SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key " .
238 "WHERE code_types.ct_fee=1 AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier",
239 array($form_pid, $enc)
241 if ($RowSearch = sqlFetchArray($ResultSearchNew)) {
242 $Codetype = $RowSearch['code_type'];
243 $Code = $RowSearch['code'];
244 $Modifier = $RowSearch['modifier'];
245 } else {
246 $Codetype = '';
247 $Code = '';
248 $Modifier = '';
251 //----------------------------------------------------------------------------------------------------
252 if ($_REQUEST['radio_type_of_payment'] == 'copay') {//copay saving to ar_session and ar_activity tables
253 $session_id = sqlInsert(
254 "INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total," .
255 " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) " .
256 " VALUES ('0',?,?,now(),now(),?,'','patient','COPAY',?,?,'patient_payment',now())",
257 array($_SESSION['authUserID'], $form_source, $amount, $form_pid, $form_method)
260 sqlBeginTrans();
261 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $enc));
262 $insrt_id = sqlInsert(
263 "INSERT INTO ar_activity (pid,encounter,sequence_no,code_type,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)" .
264 " VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
265 array($form_pid, $enc, $sequence_no['increment'], $Codetype, $Code, $Modifier, $_SESSION['authUserID'], $session_id, $amount)
267 sqlCommitTrans();
269 frontPayment($form_pid, $enc, $form_method, $form_source, $amount, 0, $timestamp);//insertion to 'payments' table.
272 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.
273 if ($_REQUEST['radio_type_of_payment'] == 'cash') {
274 sqlStatement(
275 "update form_encounter set last_level_closed=? where encounter=? and pid=? ",
276 array(4, $enc, $form_pid)
278 sqlStatement(
279 "update billing set billed=? where encounter=? and pid=?",
280 array(1, $enc, $form_pid)
284 $adjustment_code = 'patient_payment';
285 $payment_id = sqlInsert(
286 "insert into ar_session set " .
287 "payer_id = ?" .
288 ", patient_id = ?" .
289 ", user_id = ?" .
290 ", closed = ?" .
291 ", reference = ?" .
292 ", check_date = now() , deposit_date = now() " .
293 ", pay_total = ?" .
294 ", payment_type = 'patient'" .
295 ", description = ?" .
296 ", adjustment_code = ?" .
297 ", post_to_date = now() " .
298 ", payment_method = ?",
299 array(0, $form_pid, $_SESSION['authUserID'], 0, $form_source, $amount, $NameNew, $adjustment_code, $form_method)
302 //--------------------------------------------------------------------------------------------------------------------
304 frontPayment($form_pid, $enc, $form_method, $form_source, 0, $amount, $timestamp);//insertion to 'payments' table.
306 //--------------------------------------------------------------------------------------------------------------------
308 $resMoneyGot = sqlStatement(
309 "SELECT sum(pay_amount) as PatientPay FROM ar_activity where deleted IS NULL AND pid =? and " .
310 "encounter =? and payer_type=0 and account_code='PCP'",
311 array($form_pid, $enc)
312 );//new fees screen copay gives account_code='PCP'
313 $rowMoneyGot = sqlFetchArray($resMoneyGot);
314 $Copay = $rowMoneyGot['PatientPay'];
316 //--------------------------------------------------------------------------------------------------------------------
318 //Looping the existing code and modifier
319 $ResultSearchNew = sqlStatement(
320 "SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key WHERE code_types.ct_fee=1 " .
321 "AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier",
322 array($form_pid, $enc)
324 while ($RowSearch = sqlFetchArray($ResultSearchNew)) {
325 $Codetype = $RowSearch['code_type'];
326 $Code = $RowSearch['code'];
327 $Modifier = $RowSearch['modifier'];
328 $Fee = $RowSearch['fee'];
330 $resMoneyGot = sqlStatement(
331 "SELECT sum(pay_amount) as MoneyGot FROM ar_activity where deleted IS NULL AND pid = ? " .
332 "and code_type=? and code=? and modifier=? and encounter =? and !(payer_type=0 and account_code='PCP')",
333 array($form_pid, $Codetype, $Code, $Modifier, $enc)
335 //new fees screen copay gives account_code='PCP'
336 $rowMoneyGot = sqlFetchArray($resMoneyGot);
337 $MoneyGot = $rowMoneyGot['MoneyGot'];
339 $resMoneyAdjusted = sqlStatement(
340 "SELECT sum(adj_amount) as MoneyAdjusted FROM ar_activity where deleted IS NULL AND " .
341 "pid =? and code_type=? and code=? and modifier=? and encounter =?",
342 array($form_pid, $Codetype, $Code, $Modifier, $enc)
344 $rowMoneyAdjusted = sqlFetchArray($resMoneyAdjusted);
345 $MoneyAdjusted = $rowMoneyAdjusted['MoneyAdjusted'];
347 $Remainder = $Fee - $Copay - $MoneyGot - $MoneyAdjusted;
348 $Copay = 0;
349 if (round($Remainder, 2) != 0 && $amount != 0) {
350 if ($amount - $Remainder >= 0) {
351 $insert_value = $Remainder;
352 $amount = $amount - $Remainder;
353 } else {
354 $insert_value = $amount;
355 $amount = 0;
358 sqlBeginTrans();
359 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $enc));
360 sqlStatement(
361 "insert into ar_activity set " .
362 "pid = ?" .
363 ", encounter = ?" .
364 ", sequence_no = ?" .
365 ", code_type = ?" .
366 ", code = ?" .
367 ", modifier = ?" .
368 ", payer_type = ?" .
369 ", post_time = now() " .
370 ", post_user = ?" .
371 ", session_id = ?" .
372 ", pay_amount = ?" .
373 ", adj_amount = ?" .
374 ", account_code = 'PP'",
375 array($form_pid, $enc, $sequence_no['increment'], $Codetype, $Code, $Modifier, 0, $_SESSION['authUserID'], $payment_id, $insert_value, 0)
377 sqlCommitTrans();
378 }//if
379 }//while
380 if ($amount != 0) {//if any excess is there.
381 sqlBeginTrans();
382 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $enc));
383 sqlStatement(
384 "insert into ar_activity set " .
385 "pid = ?" .
386 ", encounter = ?" .
387 ", sequence_no = ?" .
388 ", code_type = ?" .
389 ", code = ?" .
390 ", modifier = ?" .
391 ", payer_type = ?" .
392 ", post_time = now() " .
393 ", post_user = ?" .
394 ", session_id = ?" .
395 ", pay_amount = ?" .
396 ", adj_amount = ?" .
397 ", account_code = 'PP'",
398 array($form_pid, $enc, $sequence_no['increment'], $Codetype, $Code, $Modifier, 0, $_SESSION['authUserID'], $payment_id, $amount, 0)
400 sqlCommitTrans();
403 //--------------------------------------------------------------------------------------------------------------------
404 }//invoice_balance
405 }//if ($amount = 0 + $payment)
406 }//foreach
407 }//if ($_POST['form_upay'])
408 }//if ($_POST['form_save'])
410 if ($_POST['form_save'] || $_REQUEST['receipt']) {
411 if ($_REQUEST['receipt']) {
412 $form_pid = $_GET['patient'];
413 $timestamp = decorateString('....-..-.. ..:..:..', $_GET['time']);
416 // Get details for what we guess is the primary facility.
417 $frow = sqlQuery("SELECT * FROM facility " . "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
419 // Get the patient's name and chart number.
420 $patdata = getPatientData($form_pid, 'fname,mname,lname,pubpid');
422 // Re-fetch payment info.
423 $payrow = sqlQuery("SELECT " . "SUM(amount1) AS amount1, " . "SUM(amount2) AS amount2, " . "MAX(method) AS method, " . "MAX(source) AS source, " . "MAX(dtime) AS dtime, " .
424 // "MAX(user) AS user " .
425 "MAX(user) AS user, " . "MAX(encounter) as encounter " . "FROM payments WHERE " . "pid = ? AND dtime = ?", array($form_pid, $timestamp
428 // Create key for deleting, just in case.
429 $ref_id = ($_REQUEST['radio_type_of_payment'] == 'copay') ? $session_id : $payment_id;
430 $payment_key = $form_pid . '.' . preg_replace('/[^0-9]/', '', $timestamp) . '.' . $ref_id;
432 // get facility from encounter
433 $tmprow = sqlQuery("SELECT facility_id FROM form_encounter WHERE encounter = ?", array($payrow['encounter']));
434 $frow = sqlQuery("SELECT * FROM facility " . " WHERE id = ?", array($tmprow['facility_id']
437 // Now proceed with printing the receipt.
440 <title><?php echo xlt('Receipt for Payment'); ?></title>
441 <script src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery/dist/jquery.min.js"></script>
442 <script>
444 function goHome() {
445 window.location.replace("./patient/onsiteactivityviews");
448 function notifyPatient() {
449 let pid = <?php echo js_escape($pid); ?>;
450 let note = $('#pop_receipt').html();
451 let formURL = './messaging/handle_note.php';
452 let owner = <?php echo js_escape($adminUser['recip_id']); ?>;
453 let sn = <?php echo js_escape($adminUser['username']); ?>;
454 let rid = <?php echo js_escape($portalPatient['recip_id']); ?>;
455 let rn = <?php echo js_escape($portalPatient['username']); ?>;
456 $.ajax({
457 url: formURL,
458 type: "POST",
459 data: {
460 'task': 'add',
461 'owner': owner,
462 'pid': pid,
463 'inputBody': note,
464 'title': 'Bill/Collect',
465 'recipient_name': rn,
466 'recipient_id': rid,
467 'sender_id': owner,
468 'sender_name': sn
470 success: function (data, textStatus, jqXHR) {
471 alert('Receipt sent to patient via Messages.')
473 error: function (jqXHR, status, error) {
474 console.log(status + ": " + error);
478 </script>
479 <?php
480 ob_start();
481 echo '<htlm><head></head><body style="text-align: center; margin: auto;">';
483 <div id='pop_receipt' style='display: block'>
485 <h2><?php echo xlt('Receipt for Payment'); ?></h2>
486 <p><?php echo text($frow['name']) ?>
487 <br /><?php echo text($frow['street']) ?>
488 <br /><?php echo text($frow['city'] . ', ' . $frow['state']) . ' ' . text($frow['postal_code']) ?>
489 <br /><?php echo text($frow['phone']) ?>
491 <div class="text-center" style="margin: auto;">
492 <table border='0' cellspacing='8' class="text-center" style="margin: auto;">
493 <tr>
494 <td><?php echo xlt('Date'); ?>:</td>
495 <td><?php echo text(oeFormatSDFT(strtotime($payrow['dtime']))) ?></td>
496 </tr>
497 <tr>
498 <td><?php echo xlt('Patient'); ?>:</td>
499 <td><?php echo text($patdata['fname']) . " " . text($patdata['mname']) . " " . text($patdata['lname']) . " (" . text($patdata['pubpid']) . ")" ?></td>
500 </tr>
501 <tr>
502 <td><?php echo xlt('Paid Via'); ?>:</td>
503 <td><?php echo generate_display_field(array('data_type' => '1', 'list_id' => 'payment_method'), $payrow['method']); ?></td>
504 </tr>
505 <tr>
506 <td><?php echo xlt('Authorized Id'); ?>:</td>
507 <td><?php echo text($payrow['source']) ?></td>
508 </tr>
509 <tr>
510 <td><?php echo xlt('Amount for This Visit'); ?>:</td>
511 <td><?php echo text(oeFormatMoney($payrow['amount1'])) ?></td>
512 </tr>
513 <tr>
514 <td><?php echo xlt('Amount for Past Balance'); ?>:</td>
515 <td><?php echo text(oeFormatMoney($payrow['amount2'])) ?></td>
516 </tr>
517 <tr>
518 <td><?php echo xlt('Received By'); ?>:</td>
519 <td><?php echo text($payrow['user']) ?></td>
520 </tr>
521 </table>
522 </div>
523 </div>
524 <button class='btn btn-sm' type='button' onclick='goHome()' id='returnhome'><?php echo xla('Return Home'); ?></button>
525 <button class='btn btn-sm' type='button' onclick="notifyPatient()"><?php echo xla('Notify Patient'); ?></button>
526 </body></html>
527 <?php
528 ob_end_flush();
529 } else {
531 // Here we display the form for data entry.
534 <title><?php echo xlt('Record Payment'); ?></title>
535 <style>
536 .dehead {
537 color: #000000;
538 font-weight: bold
540 .detail {
541 padding: 1px 1px;
542 color: #000000;
543 font-weight: normal
545 </style>
546 <script src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-creditcardvalidator/jquery.creditCardValidator.js"></script>
547 <script src="<?php echo $GLOBALS['webroot'] ?>/library/textformat.js?v=<?php echo $v_js_includes; ?>"></script>
548 <script>
549 var chargeMsg = <?php $amsg = xl('Payment was successfully authorized and your card is charged.') . "\n" .
550 xl("You will be notified when your payment is applied for this invoice.") . "\n" .
551 xl('Until then you will continue to see payment details here.') . "\n" . xl('Thank You.');
552 echo json_encode($amsg);
554 var publicKey = <?php echo json_encode($cryptoGen->decryptStandard($GLOBALS['gateway_public_key'])); ?>;
555 var apiKey = <?php echo json_encode($cryptoGen->decryptStandard($GLOBALS['gateway_api_key'])); ?>;
557 function calctotal() {
558 var flag = 0;
559 var f = document.forms["invoiceForm"];
560 var total = 0;
561 for (var i = 0; i < f.elements.length; ++i) {
562 var elem = f.elements[i];
563 var ename = elem.name;
564 if (ename.indexOf('form_upay[') == 0 || ename.indexOf('form_bpay[') == 0) {
565 if (elem.value.length > 0) {
566 total += Number(elem.value);
567 if (total < 0) flag = 1;
571 f.form_paytotal.value = Number(total).toFixed(2);
572 if (flag) {
573 $('#invoiceForm')[0].reset();
574 alert(<?php echo xlj('Negative payments not accepted'); ?>)
576 return true;
579 function coloring() {
580 for (var i = 1; ; ++i) {
581 if (document.getElementById('paying_' + i)) {
582 paying = document.getElementById('paying_' + i).value * 1;
583 patient_balance = document.getElementById('duept_' + i).innerHTML * 1;
584 if (patient_balance > 0 && paying > 0) {
585 if (paying > patient_balance) {
586 document.getElementById('paying_' + i).style.background = '#FF0000';
588 else if (paying < patient_balance) {
589 document.getElementById('paying_' + i).style.background = '#99CC00';
591 else if (paying == patient_balance) {
592 document.getElementById('paying_' + i).style.background = '#ffffff';
595 else {
596 document.getElementById('paying_' + i).style.background = '#ffffff';
599 else {
600 break;
605 function CheckVisible(MakeBlank) {//Displays and hides the check number text box.
606 if (document.getElementById('form_method').options[document.getElementById('form_method').selectedIndex].value == 'check_payment' ||
607 document.getElementById('form_method').options[document.getElementById('form_method').selectedIndex].value == 'bank_draft') {
608 document.getElementById('check_number').disabled = false;
610 else {
611 document.getElementById('check_number').disabled = true;
615 function validate() {
616 var f = document.forms["invoiceForm"];
617 ok = -1;
618 //no checks taken here....
619 issue = 'no';
620 if (document.getElementById('radio_type_of_payment_self1').checked == false &&
621 document.getElementById('radio_type_of_payment1').checked == false
622 && document.getElementById('radio_type_of_payment2').checked == false
623 && document.getElementById('radio_type_of_payment4').checked == false) {
624 alert("<?php //echo addslashes( xl('Please Select Type Of Payment.')) ?>");
625 return false;
627 if (document.getElementById('radio_type_of_payment_self1').checked == true || document.getElementById('radio_type_of_payment1').checked == true) {
628 for (var i = 0; i < f.elements.length; ++i) {
629 var elem = f.elements[i];
630 var ename = elem.name;
631 if (ename.indexOf('form_upay[0') == 0) //Today is this text box.
633 if (elem.value * 1 > 0) {//A warning message, if the amount is posted with out encounter.
634 if (confirm(<?php echo xlj('Are you sure to post for today?'); ?>)) {
635 ok = 1;
637 else {
638 elem.focus();
639 return false;
642 break;
646 else if (document.getElementsByName('form_paytotal')[0].value <= 0)//total 0
648 alert(<?php echo xlj('Invalid Total!'); ?>)
649 return false;
651 if (ok == -1) {
652 if (confirm(<?php echo xlj('Payment Validated: Save?'); ?>)) {
653 return true;
655 else {
656 return false;
661 function cursor_pointer() {//Point the cursor to the latest encounter(Today)
662 var f = document.forms["invoiceForm"];
663 var total = 0;
664 for (var i = 0; i < f.elements.length; ++i) {
665 var elem = f.elements[i];
666 var ename = elem.name;
667 if (ename.indexOf('form_upay[') == 0) {
668 elem.focus();
669 break;
674 function make_it_hide_enc_pay() {
675 document.getElementById('td_head_insurance_payment').style.display = "none";
676 document.getElementById('td_head_patient_co_pay').style.display = "none";
677 document.getElementById('td_head_co_pay').style.display = "none";
678 document.getElementById('td_head_insurance_balance').style.display = "none";
679 for (var i = 1; ; ++i) {
680 var td_inspaid_elem = document.getElementById('td_inspaid_' + i)
681 var td_patient_copay_elem = document.getElementById('td_patient_copay_' + i)
682 var td_copay_elem = document.getElementById('td_copay_' + i)
683 var balance_elem = document.getElementById('balance_' + i)
684 if (td_inspaid_elem) {
685 td_inspaid_elem.style.display = "none";
686 td_patient_copay_elem.style.display = "none";
687 td_copay_elem.style.display = "none";
688 balance_elem.style.display = "none";
690 else {
691 break;
694 document.getElementById('td_total_4').style.display = "none";
695 document.getElementById('td_total_7').style.display = "none";
696 document.getElementById('td_total_8').style.display = "none";
697 document.getElementById('td_total_6').style.display = "none";
699 document.getElementById('table_display').width = "420px";
702 function make_visible() {
703 document.getElementById('td_head_rep_doc').style.display = "";
704 document.getElementById('td_head_description').style.display = "";
705 document.getElementById('td_head_total_charge').style.display = "none";
706 document.getElementById('td_head_insurance_payment').style.display = "none";
707 document.getElementById('td_head_patient_payment').style.display = "none";
708 document.getElementById('td_head_patient_co_pay').style.display = "none";
709 document.getElementById('td_head_co_pay').style.display = "none";
710 document.getElementById('td_head_insurance_balance').style.display = "none";
711 document.getElementById('td_head_patient_balance').style.display = "none";
712 for (var i = 1; ; ++i) {
713 var td_charges_elem = document.getElementById('td_charges_' + i)
714 var td_inspaid_elem = document.getElementById('td_inspaid_' + i)
715 var td_ptpaid_elem = document.getElementById('td_ptpaid_' + i)
716 var td_patient_copay_elem = document.getElementById('td_patient_copay_' + i)
717 var td_copay_elem = document.getElementById('td_copay_' + i)
718 var balance_elem = document.getElementById('balance_' + i)
719 var duept_elem = document.getElementById('duept_' + i)
720 if (td_charges_elem) {
721 td_charges_elem.style.display = "none";
722 td_inspaid_elem.style.display = "none";
723 td_ptpaid_elem.style.display = "none";
724 td_patient_copay_elem.style.display = "none";
725 td_copay_elem.style.display = "none";
726 balance_elem.style.display = "none";
727 duept_elem.style.display = "none";
729 else {
730 break;
733 document.getElementById('td_total_7').style.display = "";
734 document.getElementById('td_total_8').style.display = "";
735 document.getElementById('td_total_1').style.display = "none";
736 document.getElementById('td_total_2').style.display = "none";
737 document.getElementById('td_total_3').style.display = "none";
738 document.getElementById('td_total_4').style.display = "none";
739 document.getElementById('td_total_5').style.display = "none";
740 document.getElementById('td_total_6').style.display = "none";
742 document.getElementById('table_display').width = "505px";
745 function make_it_hide() {
746 document.getElementById('td_head_rep_doc').style.display = "none";
747 document.getElementById('td_head_description').style.display = "none";
748 document.getElementById('td_head_total_charge').style.display = "";
749 document.getElementById('td_head_insurance_payment').style.display = "";
750 document.getElementById('td_head_patient_payment').style.display = "";
751 document.getElementById('td_head_patient_co_pay').style.display = "";
752 document.getElementById('td_head_co_pay').style.display = "";
753 document.getElementById('td_head_insurance_balance').style.display = "";
754 document.getElementById('td_head_patient_balance').style.display = "";
755 for (var i = 1; ; ++i) {
756 var td_charges_elem = document.getElementById('td_charges_' + i)
757 var td_inspaid_elem = document.getElementById('td_inspaid_' + i)
758 var td_ptpaid_elem = document.getElementById('td_ptpaid_' + i)
759 var td_patient_copay_elem = document.getElementById('td_patient_copay_' + i)
760 var td_copay_elem = document.getElementById('td_copay_' + i)
761 var balance_elem = document.getElementById('balance_' + i)
762 var duept_elem = document.getElementById('duept_' + i)
763 if (td_charges_elem) {
764 td_charges_elem.style.display = "";
765 td_inspaid_elem.style.display = "";
766 td_ptpaid_elem.style.display = "";
767 td_patient_copay_elem.style.display = "";
768 td_copay_elem.style.display = "";
769 balance_elem.style.display = "";
770 duept_elem.style.display = "";
772 else {
773 break;
776 document.getElementById('td_total_1').style.display = "";
777 document.getElementById('td_total_2').style.display = "";
778 document.getElementById('td_total_3').style.display = "";
779 document.getElementById('td_total_4').style.display = "";
780 document.getElementById('td_total_5').style.display = "";
781 document.getElementById('td_total_6').style.display = "";
782 document.getElementById('td_total_7').style.display = "";
783 document.getElementById('td_total_8').style.display = "";
785 document.getElementById('table_display').width = "100%";
788 function make_visible_radio() {
789 document.getElementById('tr_radio1').style.display = "";
790 document.getElementById('tr_radio2').style.display = "none";
793 function make_hide_radio() {
794 document.getElementById('tr_radio1').style.display = "none";
795 document.getElementById('tr_radio2').style.display = "";
798 function make_visible_row() {
799 document.getElementById('table_display').style.display = "";
800 document.getElementById('table_display_prepayment').style.display = "none";
803 function make_hide_row() {
804 document.getElementById('table_display').style.display = "none";
805 document.getElementById('table_display_prepayment').style.display = "";
808 function make_self() {
809 make_visible_row();
810 make_it_hide();
811 make_it_hide_enc_pay();
812 document.getElementById('radio_type_of_payment_self1').checked = true;
813 cursor_pointer();
816 function make_insurance() {
817 make_visible_row();
818 make_it_hide();
819 cursor_pointer();
820 document.getElementById('radio_type_of_payment1').checked = true;
823 $('#paySubmit').click(function (e) {
824 e.preventDefault();e.stopPropagation();
825 $("#mode").val("portal-save");
826 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
827 let extra_values = JSON.stringify(getFormObj('paymentForm'));
828 let extra = "&inv_values=" + encodeURIComponent(inv_values) + "&extra_values=" + encodeURIComponent(extra_values);
829 let flag = 0
830 let liburl = './lib/paylib.php';
831 $.ajax({
832 type: "POST",
833 url: liburl,
834 data: $("#invoiceForm").serialize() + extra,
835 beforeSend: function (xhr) {
836 if (validateCC() !== true) return false;
837 if ($('#cardCode').val() == "" || $('#cardHolderName').val() == "" || $('#expYear').val() == "" || $('#expMonth').val() == "") {
838 alert(<?php echo xlj('Invalid Credit Card Values: Please correct'); ?>)
839 return false;
841 if (validate() != true) {
842 flag = 1;
843 alert(<?php echo xlj('Validation error: Fix and resubmit. This popup info is preserved!'); ?>)
844 return false;
846 $("#openPayModal .close").click()
848 error: function (qXHR, textStatus, errorThrow) {
849 console.log("There was an error:" + errorThrow);
851 success: function (templateHtml, textStatus, jqXHR) {
852 let msg = <?php $amsg = xl('Payment successfully sent for review and posting to your account.') . "\n" .
853 xl("You will be notified when the payment transaction is confirmed.") . "\n" .
854 xl('Until then you will continue to see payment details here.') . "\n" . xl('Thank You.');
855 echo json_encode($amsg); // backward compatable 5.0.1
857 alert(msg);
858 window.location.reload(false);
861 if (flag) {
862 $("#openPayModal .close").click();
866 $('#openPayModal').on('show.bs.modal', function () {
867 let total = $("#form_paytotal").val();
868 if(Number(total) < 1) {
869 let error = <?php echo json_encode("Please enter a payment amount"); ?>;
870 alert(error);
871 return false;
873 $("#payTotal").text(total);
874 $("#paymentAmount").val(total);
877 $("#invoiceForm").on('submit', function (e) {
878 e.preventDefault();
879 let thisform = this;
880 $("#mode").val("review-save");
881 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
882 let extra_values = JSON.stringify(getFormObj('paymentForm'));
883 let extra = "&inv_values=" + inv_values + "&extra_values=" + extra_values;
885 let flag = 0
886 let liburl = '<?php echo $GLOBALS["webroot"] ?>/portal/lib/paylib.php';
887 $.ajax({
888 type: "POST",
889 url: liburl,
890 data: $("#invoiceForm").serialize() + extra,
891 beforeSend: function (xhr) {
892 if (validate() != true) {
893 flag = 1;
894 alert(<?php echo xlj('Validation error: Fix and resubmit.'); ?>)
895 return false;
898 error: function (xhr, textStatus, error) {
899 alert(<?php echo xlj('There is a Post error'); ?>)
900 console.log("There was an error:" + textStatus);
901 return false;
903 success: function (templateHtml, textStatus, jqXHR) {
904 thisform.submit();
909 function getFormObj(formId) {
910 let formObj = {};
911 let inputs = $('#' + formId).serializeArray();
912 $.each(inputs, function (i, input) {
913 formObj[input.name] = input.value;
915 return formObj;
918 function formRepopulate(jsondata) {
919 let data = $.parseJSON(jsondata);
920 $.each(data, function (name, val) {
921 let $el = $('[name="' + name + '"]'),
922 type = $el.attr('type');
923 switch (type) {
924 case 'checkbox':
925 $el.prop('checked', true);
926 break;
927 case 'radio':
928 $el.filter('[value="' + val + '"]').prop('checked', true);
929 break;
930 default:
931 $el.val(val);
936 function getAuth() {
937 let authnum = document.getElementById("check_number").value;
938 authnum = prompt(<?php echo xlj('Please enter card comfirmation authorization'); ?>, authnum);
939 if (authnum != null) {
940 document.getElementById("check_number").value = authnum;
943 </script>
945 <body class="skin-blue" onunload='imclosing()' onLoad="cursor_pointer();"
946 style="text-align: center; margin: auto;">
948 <form id="invoiceForm" method='post' action='<?php echo $GLOBALS["webroot"] ?>/portal/portal_payment.php'>
949 <input type='hidden' name='form_pid' value='<?php echo attr($pid) ?>'/>
950 <input type='hidden' name='form_save' value='<?php echo xla('Invoice'); ?>'/>
951 <table>
952 <tr height="10">
953 <td colspan="3">&nbsp;</td>
954 </tr>
955 <tr>
956 <td colspan='3' align='center' class='text'>
957 <b><?php echo xlt('Accept Payment for'); ?>&nbsp;:&nbsp;&nbsp;<?php
958 echo text($patdata['fname']) . " " .
959 text($patdata['lname']) . " " .
960 text($patdata['mname']) . " (" .
961 text($patdata['pid']) . ")" ?></b>
962 <?php $NameNew = $patdata['fname'] . " " . $patdata['lname'] . " " . $patdata['mname']; ?>
963 </td>
964 </tr>
965 <tr height="15">
966 <td colspan='3'></td>
967 </tr>
968 <tr>
969 <td class='text'>
970 <?php echo xlt('Payment Method'); ?>:
971 </td>
972 <td colspan='2'><select name="form_method" id="form_method" class="form-control" onChange='CheckVisible("yes")'>
973 <?php
974 $query1112 = "SELECT * FROM list_options where list_id=? ORDER BY seq, title ";
975 $bres1112 = sqlStatement($query1112, array('payment_method'));
976 while ($brow1112 = sqlFetchArray($bres1112)) {
977 if ($brow1112['option_id'] != 'credit_card' || $brow1112['option_id'] == 'debit' || $brow1112['option_id'] == 'bank_draft') {
978 continue;
980 echo "<option value='" . attr($brow1112['option_id']) . "'>" .
981 text(xl_list_label($brow1112['title'])) . "</option>";
984 </select></td>
985 </tr>
986 <?php if (isset($_SESSION['authUserID'])) { ?>
987 <tr height="5">
988 <td colspan='3'></td>
989 </tr>
990 <tr>
991 <td class='text'>
992 <?php echo xlt('Authorized'); ?>:
993 </td>
994 <td colspan='2'>
995 <?php if ($ccdata['authCode'] && empty($payrow['source'])) {
996 $payrow['source'] = $ccdata['authCode'] . " : " . $ccdata['transId'];
999 <input class="form-control form-control-sm" id='check_number' name='form_source' style='' value='<?php echo attr($payrow['source']) ?>' />
1000 </td>
1001 </tr>
1002 <?php } ?>
1003 <?php if (isset($_SESSION['authUserID'])) {
1004 $hide = '';
1005 echo '<tr height="5"><td colspan="3"></td></tr><tr">';
1006 } else {
1007 $hide = 'hidden';
1008 echo '<tr class="hidden">';
1011 <td class='text' valign="middle">
1012 <?php echo xlt('Patient Coverage'); ?>:
1013 </td>
1014 <td class='text' colspan="2">
1015 <input type="radio" name="radio_type_of_coverage" id="radio_type_of_coverage1"
1016 value="self" onClick="make_visible_radio();make_self();"/>
1017 <?php echo xlt('Self'); ?>
1018 <input type="radio" name="radio_type_of_coverage" id="radio_type_of_coverag2" value="insurance"
1019 checked="checked"
1020 onClick="make_hide_radio();make_insurance();"/>
1021 <?php echo xlt('Insurance'); ?>
1022 </td>
1023 </tr>
1024 <tr height="5">
1025 <td colspan='3'></td>
1026 </tr>
1027 <tr id="tr_radio1" style="display: none">
1028 <!-- For radio Insurance -->
1029 <td class='text' valign="top">
1030 <?php echo xlt('Payment against'); ?>:
1031 </td>
1032 <td class='text' colspan="2">
1033 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment_self1"
1034 value="cash" onClick="make_visible_row();make_it_hide_enc_pay();cursor_pointer();"/>
1035 <?php echo xlt('Encounter Payment'); ?>
1036 </td>
1037 </tr>
1038 <tr id="tr_radio2">
1039 <!-- For radio self -->
1040 <td class='text' valign="top"><?php echo xlt('Payment against'); ?>:</td>
1041 <td class='text' colspan="2">
1042 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment1" class="<?php echo $hide ? $hide : ''; ?>"
1043 value="copay" onClick="make_visible_row();cursor_pointer();"/><?php echo !$hide ? xlt('Co Pay') : ''; ?>
1044 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment2" checked="checked"
1045 value="invoice_balance" onClick="make_visible_row();"/><?php echo xlt('Invoice Balance'); ?>
1046 <input type="radio" name="radio_type_of_payment" id="radio_type_of_payment4" value="pre_payment"
1047 onClick="make_hide_row();"/><?php echo xlt('Pre Pay'); ?>
1048 </td>
1049 </tr>
1050 <tr height="15">
1051 <td colspan='3'></td>
1052 </tr>
1053 </table>
1054 <table width="20%" border="0" cellspacing="0" cellpadding="0" id="table_display_prepayment" style="margin-bottom: 10px; display: none">
1055 <tr>
1056 <td class='detail'><?php echo xlt('Pre Payment'); ?></td>
1057 <td><input class="form-control" type='text' id= 'form_prepayment' name='form_prepayment' style=''/></td>
1058 </tr>
1059 </table>
1060 <table id="table_display" style="background: #eee;" class="table table-sm table-striped table-bordered w-100">
1061 <thead>
1062 </thead>
1063 <tbody>
1064 <tr bgcolor="#cccccc" id="tr_head">
1065 <td class="dehead" width="60">
1066 <?php echo xlt('DOS') ?>
1067 </td>
1068 <td class="dehead" width="120">
1069 <?php echo xlt('Visit Reason') ?>
1070 </td>
1071 <td class="dehead" align="center" width="70" id="td_head_total_charge">
1072 <?php echo xlt('Total Charge') ?>
1073 </td>
1074 <td class="dehead" align="center" width="70" id="td_head_rep_doc" style='display: none'>
1075 <?php echo xlt('Report/ Form') ?>
1076 </td>
1077 <td class="dehead" align="center" width="200" id="td_head_description" style='display: none'>
1078 <?php echo xlt('Description') ?>
1079 </td>
1080 <td class="dehead" align="center" width="70" id="td_head_insurance_payment">
1081 <?php echo xlt('Insurance Payment') ?>
1082 </td>
1083 <td class="dehead" align="center" width="70" id="td_head_patient_payment">
1084 <?php echo xlt('Patient Payment') ?>
1085 </td>
1086 <td class="dehead" align="center" width="55" id="td_head_patient_co_pay">
1087 <?php echo xlt('Co Pay Paid') ?>
1088 </td>
1089 <td class="dehead" align="center" width="55" id="td_head_co_pay">
1090 <?php echo xlt('Required Co Pay') ?>
1091 </td>
1092 <td class="dehead" align="center" width="70" id="td_head_insurance_balance">
1093 <?php echo xlt('Insurance Balance') ?>
1094 </td>
1095 <td class="dehead" align="center" width="70" id="td_head_patient_balance">
1096 <?php echo xlt('Patient Balance') ?>
1097 </td>
1098 <td class="dehead" align="center" width="50">
1099 <?php echo xlt('Paying') ?>
1100 </td>
1101 </tr>
1102 <?php
1103 $encs = array();
1104 // Get the unbilled service charges and payments by encounter for this patient.
1106 $query = "SELECT fe.encounter, fe.reason, b.code_type, b.code, b.modifier, b.fee, " .
1107 "LEFT(fe.date, 10) AS encdate ,fe.last_level_closed " . "FROM form_encounter AS fe left join billing AS b on " .
1108 "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 " .
1109 "where fe.pid = ? " . "ORDER BY b.encounter";
1110 $bres = sqlStatement($query, array($pid, $pid));
1112 while ($brow = sqlFetchArray($bres)) {
1113 $key = (int)$brow['encounter'];
1114 if (empty($encs[$key])) {
1115 $encs[$key] = array('encounter' => $brow['encounter'], 'date' => $brow['encdate'], 'last_level_closed' => $brow['last_level_closed'], 'charges' => 0, 'payments' => 0, 'reason' => $brow['reason']
1119 if ($brow['code_type'] === 'COPAY') {
1120 // $encs[$key]['payments'] -= $brow['fee'];
1121 } else {
1122 $encs[$key]['charges'] += $brow['fee'];
1123 // Add taxes.
1124 $sql_array = array();
1125 $query = "SELECT taxrates FROM codes WHERE " . "code_type = ? AND " . "code = ? AND ";
1126 array_push($sql_array, $code_types[$brow['code_type']]['id'], $brow['code']);
1127 if ($brow['modifier']) {
1128 $query .= "modifier = ?";
1129 array_push($sql_array, $brow['modifier']);
1130 } else {
1131 $query .= "(modifier IS NULL OR modifier = '')";
1134 $query .= " LIMIT 1";
1135 $trow = sqlQuery($query, $sql_array);
1136 $encs[$key]['charges'] += calcTaxes($trow, $brow['fee']);
1140 // Do the same for unbilled product sales.
1142 $query = "SELECT fe.encounter, fe.reason, s.drug_id, s.fee, " .
1143 "LEFT(fe.date, 10) AS encdate,fe.last_level_closed " .
1144 "FROM form_encounter AS fe left join drug_sales AS s " .
1145 "on s.pid = ? AND s.fee != 0 " .
1146 "AND fe.pid = s.pid AND fe.encounter = s.encounter " .
1147 "where fe.pid = ? " . "ORDER BY s.encounter";
1149 $dres = sqlStatement($query, array($pid, $pid));
1151 while ($drow = sqlFetchArray($dres)) {
1152 $key = (int)$drow['encounter'];
1153 if (empty($encs[$key])) {
1154 $encs[$key] = array(
1155 'encounter' => $drow['encounter'], 'date' => $drow['encdate'],
1156 'last_level_closed' => $drow['last_level_closed'],
1157 'charges' => 0, 'payments' => 0
1161 $encs[$key]['charges'] += $drow['fee'];
1162 // Add taxes.
1163 $trow = sqlQuery(
1164 "SELECT taxrates FROM drug_templates WHERE drug_id = ? " .
1165 "ORDER BY selector LIMIT 1",
1166 array($drow['drug_id'])
1168 $encs[$key]['charges'] += calcTaxes($trow, $drow['fee']);
1171 ksort($encs, SORT_NUMERIC);
1173 foreach ($encs as $key => $value) {
1174 $enc = $value['encounter'];
1175 $reason = $value['reason'];
1176 $dispdate = $value['date'];
1178 $inscopay = BillingUtilities::getCopay($pid, $dispdate);
1179 $patcopay = BillingUtilities::getPatientCopay($pid, $enc);
1180 // Insurance Payment
1182 $drow = sqlQuery(
1183 "SELECT SUM(pay_amount) AS payments, " .
1184 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1185 "deleted IS NULL AND pid = ? and encounter = ? AND " .
1186 "payer_type != 0 AND account_code != 'PCP'",
1187 array($pid, $enc)
1189 $dpayment = $drow['payments'];
1190 $dadjustment = $drow['adjustments'];
1191 // Patient Payment
1193 $drow = sqlQuery(
1194 "SELECT SUM(pay_amount) AS payments, SUM(adj_amount) AS adjustments " .
1195 "FROM ar_activity WHERE deleted IS NULL AND pid = ? and encounter = ? and " .
1196 "payer_type = 0 and account_code != 'PCP'",
1197 array($pid, $enc)
1199 $dpayment_pat = $drow['payments'];
1201 // NumberOfInsurance
1203 $ResultNumberOfInsurance = sqlStatement(
1204 "SELECT COUNT( DISTINCT TYPE ) NumberOfInsurance FROM insurance_data where pid = ? and provider>0 ",
1205 array($pid)
1207 $RowNumberOfInsurance = sqlFetchArray($ResultNumberOfInsurance);
1208 $NumberOfInsurance = $RowNumberOfInsurance['NumberOfInsurance'] * 1;
1209 $duept = 0;
1210 if ((($NumberOfInsurance == 0 || $value['last_level_closed'] == 4 || $NumberOfInsurance == $value['last_level_closed']))) { // Patient balance
1211 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " . "pid = ? and encounter = ? AND activity = 1", array($pid, $enc
1213 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " . "pid = ? and encounter = ? ", array($pid, $enc
1215 $drow = sqlQuery(
1216 "SELECT SUM(pay_amount) AS payments, SUM(adj_amount) AS adjustments " .
1217 "FROM ar_activity WHERE deleted IS NULL AND pid = ? and encounter = ? ",
1218 array($pid, $enc)
1220 $duept = $brow['amount'] + $srow['amount'] - $drow['payments'] - $drow['adjustments'];
1223 echoLine("form_upay[$enc]", $dispdate, $value['charges'], $dpayment_pat, ($dpayment + $dadjustment), $duept, ($enc . ': ' . $reason), $inscopay, $patcopay);
1226 // Continue with display of the data entry form.
1228 <tr>
1229 <td class="dehead" align="center"><?php echo xlt('Total'); ?></td>
1230 <td class="dehead" id='td_total_1' align="center"></td>
1231 <td class="dehead" id='td_total_2' align="center"><?php echo text(bucks($sum_charges)) ?></td>
1232 <td class="dehead" id='td_total_3' align="center"><?php echo text(bucks($sum_inspaid)) ?></td>
1233 <td class="dehead" id='td_total_4' align="center"><?php echo text(bucks($sum_ptpaid)) ?></td>
1234 <td class="dehead" id='td_total_5' align="center"><?php echo text(bucks($sum_patcopay)) ?></td>
1235 <td class="dehead" id='td_total_6' align="center"><?php echo text(bucks($sum_copay)) ?></td>
1236 <td class="dehead" id='td_total_7' align="center"><?php echo text(bucks($sum_balance)) ?></td>
1237 <td class="dehead" id='td_total_8' align="center"><?php echo text(bucks($sum_duept)) ?></td>
1238 <td class="dehead" align="center">
1239 <input class="form-control" name='form_paytotal' id='form_paytotal' value='' style='color: #3b9204;' readonly />
1240 </td>
1241 </tr>
1242 </table>
1243 <?php
1244 if (isset($ccdata["cardHolderName"])) {
1245 echo '<div class="col-5"><div class="card panel-default height">';
1246 if (!isset($_SESSION['authUserID'])) {
1247 echo '<div class="card-heading">' . xlt("Payment Information") .
1248 '<span style="color: #cc0000"><em> ' . xlt("Pending Auth since") . ': </em>' . text($edata["date"]) . '</span></div>';
1249 } else {
1250 echo '<div class="card-heading">' . xlt("Audit Payment") .
1251 '<span style="color: #cc0000"><em> ' . xlt("Pending since") . ': </em>' . text($edata["date"]) . '</span>' .
1252 ' <button type="button" class="btn btn-warning btn-sm" onclick="getAuth()">' . xlt("Authorize") . '</button></div>';
1254 } else {
1255 echo '<div style="display:none" class="col-6"><div class="card panel-default height">' .
1256 '<div class="card-heading">' . xlt("Payment Information") . ' </div>';
1259 <div class="card-body">
1260 <span class="font-weight-bold"><?php echo xlt('Card Name'); ?>: </span><span id="cn"><?php echo text($ccdata["cc_type"]) ?></span><br />
1261 <span class="font-weight-bold"><?php echo xlt('Name on Card'); ?>: </span><span id="nc"><?php echo text($ccdata["cardHolderName"]) ?></span>
1262 <span class="font-weight-bold"><?php echo xlt('Card Holder Zip'); ?>: </span><span id="czip"><?php echo text($ccdata["zip"]) ?></span><br />
1263 <span class="font-weight-bold"><?php echo xlt('Card Number'); ?>: </span><span id="ccn">
1264 <?php
1265 if (isset($_SESSION['authUserID']) || isset($ccdata["transId"])) {
1266 echo text($ccdata["cardNumber"]) . "</span><br />";
1267 } else {
1268 echo "********** " . text(substr($ccdata["cardNumber"], -4)) . "</span><br />";
1271 <?php
1272 if (!isset($ccdata["transId"])) { ?>
1273 <span class="font-weight-bold"><?php echo xlt('Exp Date'); ?>: </span><span id="ed"><?php echo text($ccdata["month"]) . "/" . text($ccdata["year"]) ?></span>
1274 <span class="font-weight-bold"><?php echo xlt('CVV'); ?>: </span><span id="cvvpin"><?php echo text($ccdata["cardCode"]) ?></span><br />
1275 <?php } else { ?>
1276 <span class="font-weight-bold"><?php echo xlt('Transaction Id'); ?>: </span><span id="ed"><?php echo text($ccdata["transId"]) . "/" . text($ccdata["year"]) ?></span>
1277 <span class="font-weight-bold"><?php echo xlt('Authorization'); ?>: </span><span id="cvvpin"><?php echo text($ccdata["authCode"]) ?></span><br />
1278 <?php } ?>
1279 <span class="font-weight-bold"><?php echo xlt('Charge Total'); ?>: </span><span id="ct"><?php echo text($invdata["form_paytotal"]) ?></span><br />
1280 </div>
1281 </div>
1282 </div>
1283 <div>
1284 <?php
1285 if (!isset($_SESSION['authUserID'])) {
1286 if (!isset($ccdata["cardHolderName"])) {
1287 if ($GLOBALS['payment_gateway'] == 'Sphere') {
1288 echo SpherePayment::renderSphereHtml('patient');
1289 } else {
1290 echo '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#openPayModal">' . xlt("Pay Invoice") . '</button>';
1292 } else {
1293 echo '<h4><span class="bg-danger">' . xlt("Locked Payment Pending") . '</span></h4>';
1295 } else {
1296 echo "<button type='submit' class='btn btn-success' form='invoiceForm'>" . xlt('Post Payment') . "</button>";
1299 </div>
1300 <input type="hidden" name="hidden_patient_code" id="hidden_patient_code" value="<?php echo attr($pid); ?>"/>
1301 <input type='hidden' name='mode' id='mode' value=''/>
1302 </form>
1304 <script>
1305 if (typeof jsondata !== 'undefined') {
1306 formRepopulate(jsondata);
1308 calctotal();
1309 </script>
1310 <!-- credit payment modal -->
1311 <div id="openPayModal" class="modal fade" role="dialog">
1312 <div class="modal-dialog">
1313 <div class="modal-content">
1314 <div class="modal-header">
1315 <h4><?php echo xlt('Submit Payment for Authorization'); ?></h4>
1316 <!--<button type="button" class="close" data-dismiss="modal">&times;</button>-->
1317 </div>
1318 <div class="modal-body">
1319 <?php if ($GLOBALS['payment_gateway'] != 'Stripe' && $GLOBALS['payment_gateway'] != 'Sphere') { ?>
1320 <form id='paymentForm' method='post' action='<?php echo $GLOBALS["webroot"] ?>/portal/lib/paylib.php'>
1321 <fieldset>
1322 <div class="form-group">
1323 <label label-default="label-default"
1324 class="control-label"><?php echo xlt('Name on Card'); ?></label>
1325 <div class="controls">
1326 <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']) ?>" />
1327 </div>
1328 </div>
1329 <div class="form-group">
1330 <label class="control-label"><?php echo xlt('Card Number'); ?></label>
1331 <div class="controls">
1332 <div class="row">
1333 <div class="col-sm-12">
1334 <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;
1335 <h4 name="cardtype" id="cardtype" style="display: inline-block; color:#cc0000;"><?php echo xlt('Validating') ?></h4>
1336 </div>
1337 </div>
1338 </div>
1339 </div>
1340 <div class="form-group">
1341 <label label-default="label-default"><?php echo xlt('Card Expiry Date and Card Holders Zip'); ?></label>
1342 <div class="controls">
1343 <div class="row">
1344 <div class="col-md-4">
1345 <select name="month" id="expMonth" class="form-control">
1346 <option value=""><?php echo xlt('Select Month'); ?></option>
1347 <option value="01"><?php echo xlt('January'); ?></option>
1348 <option value="02"><?php echo xlt('February'); ?></option>
1349 <option value="03"><?php echo xlt('March'); ?></option>
1350 <option value="04"><?php echo xlt('April'); ?></option>
1351 <option value="05"><?php echo xlt('May'); ?></option>
1352 <option value="06"><?php echo xlt('June'); ?></option>
1353 <option value="07"><?php echo xlt('July'); ?></option>
1354 <option value="08"><?php echo xlt('August'); ?></option>
1355 <option value="09"><?php echo xlt('September'); ?></option>
1356 <option value="10"><?php echo xlt('October'); ?></option>
1357 <option value="11"><?php echo xlt('November'); ?></option>
1358 <option value="12"><?php echo xlt('December'); ?></option>
1359 </select>
1360 </div>
1361 <div class="col-md-4">
1362 <select name="year" id="expYear" class="form-control">
1363 <option value=""><?php echo xlt('Select Year'); ?></option>
1364 <option value="2019">2019</option>
1365 <option value="2020">2020</option>
1366 <option value="2021">2021</option>
1367 <option value="2022">2022</option>
1368 <option value="2023">2023</option>
1369 <option value="2024">2024</option>
1370 <option value="2025">2025</option>
1371 <option value="2026">2026</option>
1372 <option value="2027">2027</option>
1373 <option value="2028">2028</option>
1374 </select>
1375 </div>
1376 <div class="col-md-4">
1377 <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']) ?>"/>
1378 </div>
1379 </div>
1380 </div>
1381 </div>
1382 <div class="form-group">
1383 <label label-default="label-default" class="control-label"><?php echo xlt('Card CVV'); ?></label>
1384 <div class="controls">
1385 <div class="row">
1386 <div class="col-md-3">
1387 <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="" />
1388 </div>
1389 <div class="col-md-3">
1390 <img src='./images/img_cvc.png' style='height: 40px; width: auto' />
1391 </div>
1392 <div class="col-md-6">
1393 <h4 style="display: inline-block;"><?php echo xlt('Payment Amount'); ?>:&nbsp;
1394 <span class="font-weight-bold"><span id="payTotal"></span></span></h4>
1395 </div>
1396 </div>
1397 </div>
1398 </div>
1399 <input type='hidden' name='pid' id='pid' value='<?php echo attr($pid) ?>'/>
1400 <input type='hidden' name='mode' id='mode' value=''/>
1401 <input type='hidden' name='cc_type' id='cc_type' value=''/>
1402 <input type='hidden' name='payment' id='paymentAmount' value=''/>
1403 <input type='hidden' name='invValues' id='invValues' value=''/>
1404 <input type="hidden" name="dataValue" id="dataValue" />
1405 <input type="hidden" name="dataDescriptor" id="dataDescriptor" />
1406 </fieldset>
1407 </form>
1408 <?php } else { ?>
1409 <form method="post" name="payment-form" id="payment-form">
1410 <fieldset>
1411 <div class="form-group">
1412 <label label-default="label-default"><?php echo xlt('Name on Card'); ?></label>
1413 <div class="controls">
1414 <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']) ?>" />
1415 </div>
1416 </div>
1417 <div class="form-group">
1418 <label for="card-element"><?php echo xlt('Credit or Debit Card') ?></label>
1419 <div class="form-group" id="card-element"></div>
1420 <div id="card-errors" role="alert"></div>
1421 </div>
1422 <div class="col-md-6">
1423 <h4 style="display: inline-block;"><?php echo xlt('Payment Amount'); ?>:&nbsp;
1424 <strong><span id="payTotal"></span></strong></h4>
1425 </div>
1426 <input type='hidden' name='mode' id='mode' value=''/>
1427 <input type='hidden' name='cc_type' id='cc_type' value=''/>
1428 <input type='hidden' name='payment' id='paymentAmount' value=''/>
1429 <input type='hidden' name='invValues' id='invValues' value=''/>
1430 </fieldset>
1431 </form>
1432 <?php } ?>
1433 </div>
1434 <!-- Body -->
1435 <div class="modal-footer">
1436 <div class="button-group">
1437 <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo xlt('Cancel'); ?></button>
1438 <?php
1439 if ($GLOBALS['payment_gateway'] == 'InHouse') { ?>
1440 <button id="paySubmit" class="btn btn-primary"><?php echo xlt('Send Payment'); ?></button>
1441 <?php } elseif ($GLOBALS['payment_gateway'] == 'AuthorizeNet') { ?>
1442 <button id="payAurhorizeNet" class="btn btn-primary"
1443 onclick="sendPaymentDataToAnet(event)"><?php echo xlt('Pay Now'); ?></button>
1444 <?php }
1445 if ($GLOBALS['payment_gateway'] == 'Stripe') { ?>
1446 <button id="stripeSubmit" class="btn btn-primary"><?php echo xlt('Pay Now'); ?></button>
1447 <?php } ?>
1448 </div>
1449 </div>
1450 </div>
1451 </div>
1452 </div>
1453 <script>
1454 var ccerr = <?php echo xlj('Invalid Credit Card Number'); ?>
1456 // In House CC number Validation
1457 /*$('#cardNumber').validateCreditCard(function (result) {
1458 var r = (result.card_type === null ? '' : result.card_type.name.toUpperCase())
1459 var v = (result.valid === true ? ' Valid Number' : ' Validating')
1460 if (result.valid === true) {
1461 document.getElementById("cardtype").style.color = "#00aa00";
1462 } else {
1463 document.getElementById("cardtype").style.color = "#aa0000";
1465 $('#cardtype').text(r + v);
1466 });*/
1468 // In House CC Validation
1469 function validateCC() {
1470 var result = $('#cardNumber').validateCreditCard();
1471 var r = (result.card_type == null ? '' : result.card_type.name.toUpperCase())
1472 var v = (result.valid == true ? ' Valid Card Number' : ' Invalid Card Number')
1473 if (result.valid === true) {
1474 document.getElementById("cardtype").style.color = "#00aa00";
1475 } else {
1476 document.getElementById("cardtype").style.color = "#aa0000";
1478 $('#cardtype').text(r + v);
1479 $('#cc_type').val(r);
1480 if (!result.valid) {
1481 alert(ccerr);
1482 return false;
1484 else {
1485 return true;
1488 </script>
1490 <?php if ($GLOBALS['payment_gateway'] == 'AuthorizeNet' && isset($_SESSION['patient_portal_onsite_two'])) {
1491 // Include Authorize.Net dependency to tokenize card.
1492 // Will return a token to use for payment request keeping
1493 // credit info off the server.
1495 <script>
1496 function sendPaymentDataToAnet(e) {
1497 e.preventDefault();
1498 const authData = {};
1499 authData.clientKey = publicKey;
1500 authData.apiLoginID = apiKey;
1502 const cardData = {};
1503 cardData.cardNumber = document.getElementById("cardNumber").value;
1504 cardData.month = document.getElementById("expMonth").value;
1505 cardData.year = document.getElementById("expYear").value;
1506 cardData.cardCode = document.getElementById("cardCode").value;
1507 cardData.fullName = document.getElementById("cardHolderName").value;
1508 cardData.zip = document.getElementById("cczip").value;
1510 const secureData = {};
1511 secureData.authData = authData;
1512 secureData.cardData = cardData;
1514 Accept.dispatchData(secureData, acceptResponseHandler);
1516 function acceptResponseHandler(response) {
1517 if (response.messages.resultCode === "Error") {
1518 let i = 0;
1519 let errorMsg = '';
1520 while (i < response.messages.message.length) {
1521 errorMsg = errorMsg + response.messages.message[i].code + ": " +response.messages.message[i].text;
1522 console.log(errorMsg);
1523 i = i + 1;
1525 alert(errorMsg);
1526 } else {
1527 paymentFormUpdate(response.opaqueData);
1532 function paymentFormUpdate(opaqueData) {
1533 // this is card tokenized
1534 document.getElementById("dataDescriptor").value = opaqueData.dataDescriptor;
1535 document.getElementById("dataValue").value = opaqueData.dataValue;
1536 let oForm = document.forms['paymentForm'];
1537 oForm.elements['mode'].value = "AuthorizeNet";
1538 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
1539 document.getElementById("invValues").value = inv_values;
1541 // empty out the fields before submitting to server.
1542 document.getElementById("cardNumber").value = "";
1543 document.getElementById("expMonth").value = "";
1544 document.getElementById("expYear").value = "";
1545 document.getElementById("cardCode").value = "";
1547 // Submit payment to server
1548 fetch('./lib/paylib.php', {
1549 method: 'POST',
1550 body: new FormData(oForm)
1551 }).then(function(response) {
1552 if (!response.ok) {
1553 throw Error(response.statusText);
1555 return response.text();
1556 }).then(function(data) {
1557 if(data !== 'ok') {
1558 alert(data);
1559 return;
1561 alert(chargeMsg);
1562 window.location.reload(false);
1563 }).catch(function(error) {
1564 alert(error)
1567 </script>
1568 <?php } // end authorize.net ?>
1570 <?php if ($GLOBALS['payment_gateway'] == 'Stripe' && isset($_SESSION['patient_portal_onsite_two'])) { // Begin Include Stripe ?>
1571 <script>
1572 const stripe = Stripe(publicKey);
1573 const elements = stripe.elements();// Custom styling can be passed to options when creating an Element.
1574 const style = {
1575 base: {
1576 color: '#32325d',
1577 lineHeight: '1.2rem',
1578 fontSmoothing: 'antialiased',
1579 fontSize: '16px',
1580 '::placeholder': {
1581 color: '#8e8e8e'
1584 invalid: {
1585 color: '#fa755a',
1586 iconColor: '#fa755a'
1590 // Create an instance of the card Element.
1591 const card = elements.create('card', {style: style});
1592 // Add an instance of the card Element into the `card-element` <div>.
1593 card.mount('#card-element');
1594 // Handle real-time validation errors from the card Element.
1595 card.addEventListener('change', function (event) {
1596 let displayError = document.getElementById('card-errors');
1597 if (event.error) {
1598 displayError.textContent = event.error.message;
1599 } else {
1600 displayError.textContent = '';
1603 // Handle form submission.
1604 let form = document.getElementById('stripeSubmit');
1605 form.addEventListener('click', function (event) {
1606 event.preventDefault();
1607 stripe.createToken(card).then(function (result) {
1608 if (result.error) {
1609 // Inform the user if there was an error.
1610 let errorElement = document.getElementById('card-errors');
1611 errorElement.textContent = result.error.message;
1612 } else {
1613 // Send the token to server.
1614 stripeTokenHandler(result.token);
1618 // Submit the form with the token ID.
1619 function stripeTokenHandler(token) {
1620 // Insert the token ID into the form so it gets submitted to the server
1621 let oForm = document.forms['payment-form'];
1622 oForm.elements['mode'].value = "Stripe";
1624 let inv_values = JSON.stringify(getFormObj('invoiceForm'));
1625 document.getElementById("invValues").value = inv_values;
1627 let hiddenInput = document.createElement('input');
1628 hiddenInput.setAttribute('type', 'hidden');
1629 hiddenInput.setAttribute('name', 'stripeToken');
1630 hiddenInput.setAttribute('value', token.id);
1631 oForm.appendChild(hiddenInput);
1633 // Submit payment to server
1634 fetch('./lib/paylib.php', {
1635 method: 'POST',
1636 body: new FormData(oForm)
1637 }).then(function(response) {
1638 if (!response.ok) {
1639 throw Error(response.statusText);
1641 return response.text();
1642 }).then(function(data) {
1643 if(data !== 'ok') {
1644 alert(data);
1645 return;
1647 alert(chargeMsg);
1648 window.location.reload(false);
1649 }).catch(function(error) {
1650 alert(error)
1653 </script>
1654 <?php } ?>
1656 <?php
1657 if ($GLOBALS['payment_gateway'] == 'Sphere' && isset($_SESSION['patient_portal_onsite_two'])) {
1658 echo (new SpherePayment('patient', $pid))->renderSphereJs();
1662 </body>
1663 <?php } // end else display ?>