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