updated datepicker in checkout gui
[openemr.git] / interface / patient_file / pos_checkout.php
blobb0438cff0e8c663e8aef2e2e8f21fb917fdc0eaf
1 <?php
2 /**
3 * Checkout Module.
5 * This module supports a popup window to handle patient checkout
6 * as a point-of-sale transaction. Support for in-house drug sales
7 * is included.
9 * <pre>
10 * Important notes about system design:
11 * (1) Drug sales may or may not be associated with an encounter;
12 * they are if they are paid for concurrently with an encounter, or
13 * if they are "product" (non-prescription) sales via the Fee Sheet.
14 * (2) Drug sales without an encounter will have 20YYMMDD, possibly
15 * with a suffix, as the encounter-number portion of their invoice
16 * number.
17 * (3) Payments are saved as AR only, don't mess with the billing table.
18 * See library/classes/WSClaim.class.php for posting code.
19 * (4) On checkout, the billing and drug_sales table entries are marked
20 * as billed and so become unavailable for further billing.
21 * (5) Receipt printing must be a separate operation from payment,
22 * and repeatable.
24 * TBD:
25 * If this user has 'irnpool' set
26 * on display of checkout form
27 * show pending next invoice number
28 * on applying checkout
29 * save next invoice number to form_encounter
30 * compute new next invoice number
31 * on receipt display
32 * show invoice number
33 * </pre>
35 * Copyright (C) 2006-2016 Rod Roark <rod@sunsetsystems.com>
36 * Copyright (C) 2017 Brady Miller <brady.g.miller@gmail.com>
38 * LICENSE: This program is free software; you can redistribute it and/or
39 * modify it under the terms of the GNU General Public License
40 * as published by the Free Software Foundation; either version 2
41 * of the License, or (at your option) any later version.
42 * This program is distributed in the hope that it will be useful,
43 * but WITHOUT ANY WARRANTY; without even the implied warranty of
44 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
45 * GNU General Public License for more details.
46 * You should have received a copy of the GNU General Public License
47 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
49 * @package OpenEMR
50 * @author Rod Roark <rod@sunsetsystems.com>
51 * @author Brady Miller <brady.g.miller@gmail.com>
52 * @link http://www.open-emr.org
56 $fake_register_globals=false;
57 $sanitize_all_escapes=true;
59 require_once("../globals.php");
60 require_once("$srcdir/acl.inc");
61 require_once("$srcdir/patient.inc");
62 require_once("$srcdir/billing.inc");
63 require_once("../../custom/code_types.inc.php");
65 $currdecimals = $GLOBALS['currency_decimals'];
67 $details = empty($_GET['details']) ? 0 : 1;
69 $patient_id = empty($_GET['ptid']) ? $pid : 0 + $_GET['ptid'];
71 // Get the patient's name and chart number.
72 $patdata = getPatientData($patient_id, 'fname,mname,lname,pubpid,street,city,state,postal_code');
74 // Output HTML for an invoice line item.
76 $prevsvcdate = '';
77 function receiptDetailLine($svcdate, $description, $amount, $quantity) {
78 global $prevsvcdate, $details;
79 if (!$details) return;
80 $amount = sprintf('%01.2f', $amount);
81 if (empty($quantity)) $quantity = 1;
82 $price = sprintf('%01.4f', $amount / $quantity);
83 $tmp = sprintf('%01.2f', $price);
84 if ($price == $tmp) $price = $tmp;
85 echo " <tr>\n";
86 echo " <td>" . ($svcdate == $prevsvcdate ? '&nbsp;' : text(oeFormatShortDate($svcdate))) . "</td>\n";
87 echo " <td>" . text($description) . "</td>\n";
88 echo " <td align='right'>" . text(oeFormatMoney($price)) . "</td>\n";
89 echo " <td align='right'>" . text($quantity) . "</td>\n";
90 echo " <td align='right'>" . text(oeFormatMoney($amount)) . "</td>\n";
91 echo " </tr>\n";
92 $prevsvcdate = $svcdate;
95 // Output HTML for an invoice payment.
97 function receiptPaymentLine($paydate, $amount, $description='') {
98 $amount = sprintf('%01.2f', 0 - $amount); // make it negative
99 echo " <tr>\n";
100 echo " <td>" . text(oeFormatShortDate($paydate)) . "</td>\n";
101 echo " <td>" . xlt('Payment') . " " . text($description) . "</td>\n";
102 echo " <td colspan='2'>&nbsp;</td>\n";
103 echo " <td align='right'>" . text(oeFormatMoney($amount)) . "</td>\n";
104 echo " </tr>\n";
107 // Generate a receipt from the last-billed invoice for this patient,
108 // or for the encounter specified as a GET parameter.
110 function generate_receipt($patient_id, $encounter=0) {
111 global $sl_err, $sl_cash_acc, $css_header, $details;
113 // Get details for what we guess is the primary facility.
114 $frow = sqlQuery("SELECT * FROM facility " .
115 "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
117 $patdata = getPatientData($patient_id, 'fname,mname,lname,pubpid,street,city,state,postal_code,providerID');
119 // Get the most recent invoice data or that for the specified encounter.
121 // Adding a provider check so that their info can be displayed on receipts
122 if ($encounter) {
123 $ferow = sqlQuery("SELECT id, date, encounter, provider_id FROM form_encounter " .
124 "WHERE pid = ? AND encounter = ?", array($patient_id,$encounter) );
125 } else {
126 $ferow = sqlQuery("SELECT id, date, encounter, provider_id FROM form_encounter " .
127 "WHERE pid = ? " .
128 "ORDER BY id DESC LIMIT 1", array($patient_id) );
130 if (empty($ferow)) die(xlt("This patient has no activity."));
131 $trans_id = $ferow['id'];
132 $encounter = $ferow['encounter'];
133 $svcdate = substr($ferow['date'], 0, 10);
135 if ($GLOBALS['receipts_by_provider']){
136 if (isset($ferow['provider_id']) ) {
137 $encprovider = $ferow['provider_id'];
138 } else if (isset($patdata['providerID'])){
139 $encprovider = $patdata['providerID'];
140 } else { $encprovider = -1; }
143 if ($encprovider){
144 $providerrow = sqlQuery("SELECT fname, mname, lname, title, street, streetb, " .
145 "city, state, zip, phone, fax FROM users WHERE id = ?", array($encprovider) );
148 // Get invoice reference number.
149 $encrow = sqlQuery("SELECT invoice_refno FROM form_encounter WHERE " .
150 "pid = ? AND encounter = ? LIMIT 1", array($patient_id,$encounter) );
151 $invoice_refno = $encrow['invoice_refno'];
153 <html>
154 <head>
155 <?php html_header_show(); ?>
156 <link rel='stylesheet' href='<?php echo $css_header ?>' type='text/css'>
158 <title><?php echo xlt('Receipt for Payment'); ?></title>
160 <script type="text/javascript" src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-min-3-1-1/index.js"></script>
161 <script type="text/javascript" src="../../library/dialog.js?v=<?php echo $v_js_includes; ?>"></script>
163 <script language="JavaScript">
165 <?php require($GLOBALS['srcdir'] . "/restoreSession.php"); ?>
167 $(document).ready(function() {
168 var win = top.printLogSetup ? top : opener.top;
169 win.printLogSetup(document.getElementById('printbutton'));
172 // Process click on Print button.
173 function printlog_before_print() {
174 var divstyle = document.getElementById('hideonprint').style;
175 divstyle.display = 'none';
178 // Process click on Delete button.
179 function deleteme() {
180 dlgopen('deleter.php?billing=<?php echo attr("$patient_id.$encounter"); ?>', '_blank', 500, 450);
181 return false;
184 // Called by the deleteme.php window on a successful delete.
185 function imdeleted() {
186 window.close();
189 </script>
190 </head>
191 <body class="body_top">
192 <center>
193 <?php
194 if ( $GLOBALS['receipts_by_provider'] && !empty($providerrow) ) { printProviderHeader($providerrow); }
195 else { printFacilityHeader($frow); }
197 <?php
198 echo xlt("Receipt Generated") . ":" . text(date(' F j, Y'));
199 if ($invoice_refno) echo " " . xlt("Invoice Number") . ": " . text($invoice_refno) . " " . xlt("Service Date") . ": " . text($svcdate);
201 <br>&nbsp;
202 </b></p>
203 </center>
205 <?php echo text($patdata['fname']) . ' ' . text($patdata['mname']) . ' ' . text($patdata['lname']) ?>
206 <br><?php echo text($patdata['street']) ?>
207 <br><?php echo text($patdata['city']) . ', ' . text($patdata['state']) . ' ' . text($patdata['postal_code']) ?>
208 <br>&nbsp;
209 </p>
210 <center>
211 <table cellpadding='5'>
212 <tr>
213 <td><b><?php echo xlt('Date'); ?></b></td>
214 <td><b><?php echo xlt('Description'); ?></b></td>
215 <td align='right'><b><?php echo $details ? xlt('Price') : '&nbsp;'; ?></b></td>
216 <td align='right'><b><?php echo $details ? xlt('Qty' ) : '&nbsp;'; ?></b></td>
217 <td align='right'><b><?php echo xlt('Total'); ?></b></td>
218 </tr>
220 <?php
221 $charges = 0.00;
223 // Product sales
224 $inres = sqlStatement("SELECT s.sale_id, s.sale_date, s.fee, " .
225 "s.quantity, s.drug_id, d.name " .
226 "FROM drug_sales AS s LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " .
227 // "WHERE s.pid = '$patient_id' AND s.encounter = '$encounter' AND s.fee != 0 " .
228 "WHERE s.pid = ? AND s.encounter = ? " .
229 "ORDER BY s.sale_id", array($patient_id,$encounter) );
230 while ($inrow = sqlFetchArray($inres)) {
231 $charges += sprintf('%01.2f', $inrow['fee']);
232 receiptDetailLine($inrow['sale_date'], $inrow['name'],
233 $inrow['fee'], $inrow['quantity']);
235 // Service and tax items
236 $inres = sqlStatement("SELECT * FROM billing WHERE " .
237 "pid = ? AND encounter = ? AND " .
238 // "code_type != 'COPAY' AND activity = 1 AND fee != 0 " .
239 "code_type != 'COPAY' AND activity = 1 " .
240 "ORDER BY id", array($patient_id,$encounter) );
241 while ($inrow = sqlFetchArray($inres)) {
242 $charges += sprintf('%01.2f', $inrow['fee']);
243 receiptDetailLine($svcdate, $inrow['code_text'],
244 $inrow['fee'], $inrow['units']);
246 // Adjustments.
247 $inres = sqlStatement("SELECT " .
248 "a.code_type, a.code, a.modifier, a.memo, a.payer_type, a.adj_amount, a.pay_amount, " .
249 "s.payer_id, s.reference, s.check_date, s.deposit_date " .
250 "FROM ar_activity AS a " .
251 "LEFT JOIN ar_session AS s ON s.session_id = a.session_id WHERE " .
252 "a.pid = ? AND a.encounter = ? AND " .
253 "a.adj_amount != 0 " .
254 "ORDER BY s.check_date, a.sequence_no", array($patient_id,$encounter) );
255 while ($inrow = sqlFetchArray($inres)) {
256 $charges -= sprintf('%01.2f', $inrow['adj_amount']);
257 $payer = empty($inrow['payer_type']) ? 'Pt' : ('Ins' . $inrow['payer_type']);
258 receiptDetailLine($svcdate, $payer . ' ' . $inrow['memo'],
259 0 - $inrow['adj_amount'], 1);
263 <tr>
264 <td colspan='5'>&nbsp;</td>
265 </tr>
266 <tr>
267 <td><?php echo text(oeFormatShortDate($svcdispdate)); ?></td>
268 <td><b><?php echo xlt('Total Charges'); ?></b></td>
269 <td align='right'>&nbsp;</td>
270 <td align='right'>&nbsp;</td>
271 <td align='right'><?php echo text(oeFormatMoney($charges, true)) ?></td>
272 </tr>
273 <tr>
274 <td colspan='5'>&nbsp;</td>
275 </tr>
277 <?php
278 // Get co-pays.
279 $inres = sqlStatement("SELECT fee, code_text FROM billing WHERE " .
280 "pid = ? AND encounter = ? AND " .
281 "code_type = 'COPAY' AND activity = 1 AND fee != 0 " .
282 "ORDER BY id", array($patient_id,$encounter) );
283 while ($inrow = sqlFetchArray($inres)) {
284 $charges += sprintf('%01.2f', $inrow['fee']);
285 receiptPaymentLine($svcdate, 0 - $inrow['fee'], $inrow['code_text']);
287 // Get other payments.
288 $inres = sqlStatement("SELECT " .
289 "a.code_type, a.code, a.modifier, a.memo, a.payer_type, a.adj_amount, a.pay_amount, " .
290 "s.payer_id, s.reference, s.check_date, s.deposit_date " .
291 "FROM ar_activity AS a " .
292 "LEFT JOIN ar_session AS s ON s.session_id = a.session_id WHERE " .
293 "a.pid = ? AND a.encounter = ? AND " .
294 "a.pay_amount != 0 " .
295 "ORDER BY s.check_date, a.sequence_no", array($patient_id,$encounter) );
296 while ($inrow = sqlFetchArray($inres)) {
297 $payer = empty($inrow['payer_type']) ? 'Pt' : ('Ins' . $inrow['payer_type']);
298 $charges -= sprintf('%01.2f', $inrow['pay_amount']);
299 receiptPaymentLine($svcdate, $inrow['pay_amount'],
300 $payer . ' ' . $inrow['reference']);
303 <tr>
304 <td colspan='5'>&nbsp;</td>
305 </tr>
306 <tr>
307 <td>&nbsp;</td>
308 <td><b><?php echo xlt('Balance Due'); ?></b></td>
309 <td colspan='2'>&nbsp;</td>
310 <td align='right'><?php echo text(oeFormatMoney($charges, true)) ?></td>
311 </tr>
312 </table>
313 </center>
314 <div id='hideonprint'>
316 &nbsp;
317 <a href='#' id='printbutton'><?php echo xlt('Print'); ?></a>
318 <?php if (acl_check('acct','disc')) { ?>
319 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
320 <a href='#' onclick='return deleteme();'><?php echo xlt('Undo Checkout'); ?></a>
321 <?php } ?>
322 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
323 <?php if ($details) { ?>
324 <a href='pos_checkout.php?details=0&ptid=<?php echo attr($patient_id); ?>&enc=<?php echo attr($encounter); ?>' onclick='top.restoreSession()'><?php echo xlt('Hide Details'); ?></a>
325 <?php } else { ?>
326 <a href='pos_checkout.php?details=1&ptid=<?php echo attr($patient_id); ?>&enc=<?php echo attr($encounter); ?>' onclick='top.restoreSession()'><?php echo xlt('Show Details'); ?></a>
327 <?php } ?>
328 </p>
329 </div>
330 </body>
331 </html>
332 <?php
333 } // end function generate_receipt()
335 // Function to output a line item for the input form.
337 $lino = 0;
338 function write_form_line($code_type, $code, $id, $date, $description,
339 $amount, $units, $taxrates) {
340 global $lino;
341 $amount = sprintf("%01.2f", $amount);
342 if (empty($units)) $units = 1;
343 $price = $amount / $units; // should be even cents, but ok here if not
344 if ($code_type == 'COPAY' && !$description) $description = xl('Payment');
345 echo " <tr>\n";
346 echo " <td>" . text(oeFormatShortDate($date));
347 echo "<input type='hidden' name='line[$lino][code_type]' value='" . attr($code_type) . "'>";
348 echo "<input type='hidden' name='line[$lino][code]' value='" . attr($code) . "'>";
349 echo "<input type='hidden' name='line[$lino][id]' value='" . attr($id) . "'>";
350 echo "<input type='hidden' name='line[$lino][description]' value='" . attr($description) . "'>";
351 echo "<input type='hidden' name='line[$lino][taxrates]' value='" . attr($taxrates) . "'>";
352 echo "<input type='hidden' name='line[$lino][price]' value='" . attr($price) . "'>";
353 echo "<input type='hidden' name='line[$lino][units]' value='" . attr($units) . "'>";
354 echo "</td>\n";
355 echo " <td>" . text($description) . "</td>";
356 echo " <td align='right'>" . text($units) . "</td>";
357 echo " <td align='right'><input type='text' name='line[$lino][amount]' " .
358 "value='" . attr($amount) . "' size='6' maxlength='8'";
359 // Modifying prices requires the acct/disc permission.
360 // if ($code_type == 'TAX' || ($code_type != 'COPAY' && !acl_check('acct','disc')))
361 echo " style='text-align:right;background-color:transparent' readonly";
362 // else echo " style='text-align:right' onkeyup='computeTotals()'";
363 echo "></td>\n";
364 echo " </tr>\n";
365 ++$lino;
368 // Create the taxes array. Key is tax id, value is
369 // (description, rate, accumulated total).
370 $taxes = array();
371 $pres = sqlStatement("SELECT option_id, title, option_value " .
372 "FROM list_options WHERE list_id = 'taxrate' AND activity = 1 ORDER BY seq, title, option_id");
373 while ($prow = sqlFetchArray($pres)) {
374 $taxes[$prow['option_id']] = array($prow['title'], $prow['option_value'], 0);
377 // Print receipt header for facility
378 function printFacilityHeader($frow){
379 echo "<p><b>" . text($frow['name']) .
380 "<br>" . text($frow['street']) .
381 "<br>" . text($frow['city']) . ', ' . text($frow['state']) . ' ' . text($frow['postal_code']) .
382 "<br>" . text($frow['phone']) .
383 "<br>&nbsp" .
384 "<br>";
387 // Pring receipt header for Provider
388 function printProviderHeader($pvdrow){
389 echo "<p><b>" . text($pvdrow['title']) . " " . text($pvdrow['fname']) . " " . text($pvdrow['mname']) . " " . text($pvdrow['lname']) . " " .
390 "<br>" . text($pvdrow['street']) .
391 "<br>" . text($pvdrow['city']) . ', ' . text($pvdrow['state']) . ' ' . text($pvdrow['postal_code']) .
392 "<br>" . text($pvdrow['phone']) .
393 "<br>&nbsp" .
394 "<br>";
397 // Mark the tax rates that are referenced in this invoice.
398 function markTaxes($taxrates) {
399 global $taxes;
400 $arates = explode(':', $taxrates);
401 if (empty($arates)) return;
402 foreach ($arates as $value) {
403 if (!empty($taxes[$value])) $taxes[$value][2] = '1';
407 $payment_methods = array(
408 'Cash',
409 'Check',
410 'MC',
411 'VISA',
412 'AMEX',
413 'DISC',
414 'Other');
416 $alertmsg = ''; // anything here pops up in an alert box
418 // If the Save button was clicked...
420 if ($_POST['form_save']) {
422 // On a save, do the following:
423 // Flag drug_sales and billing items as billed.
424 // Post the corresponding invoice with its payment(s) to sql-ledger
425 // and be careful to use a unique invoice number.
426 // Call the generate-receipt function.
427 // Exit.
429 $form_pid = $_POST['form_pid'];
430 $form_encounter = $_POST['form_encounter'];
432 // Get the posting date from the form as yyyy-mm-dd.
433 $dosdate = date("Y-m-d");
434 if (preg_match("/(\d\d\d\d)\D*(\d\d)\D*(\d\d)/", $_POST['form_date'], $matches)) {
435 $dosdate = $matches[1] . '-' . $matches[2] . '-' . $matches[3];
438 // If there is no associated encounter (i.e. this invoice has only
439 // prescriptions) then assign an encounter number of the service
440 // date, with an optional suffix to ensure that it's unique.
442 if (! $form_encounter) {
443 $form_encounter = substr($dosdate,0,4) . substr($dosdate,5,2) . substr($dosdate,8,2);
444 $tmp = '';
445 while (true) {
446 $ferow = sqlQuery("SELECT id FROM form_encounter WHERE " .
447 "pid = ? AND encounter = ?", array($form_pid, $form_encounter.$tmp) );
448 if (empty($ferow)) break;
449 $tmp = $tmp ? $tmp + 1 : 1;
451 $form_encounter .= $tmp;
454 // Delete any TAX rows from billing because they will be recalculated.
455 sqlStatement("UPDATE billing SET activity = 0 WHERE " .
456 "pid = ? AND encounter = ? AND " .
457 "code_type = 'TAX'", array($form_pid,$form_encounter) );
459 $form_amount = $_POST['form_amount'];
460 $lines = $_POST['line'];
462 for ($lino = 0; $lines[$lino]['code_type']; ++$lino) {
463 $line = $lines[$lino];
464 $code_type = $line['code_type'];
465 $id = $line['id'];
466 $amount = sprintf('%01.2f', trim($line['amount']));
469 if ($code_type == 'PROD') {
470 // Product sales. The fee and encounter ID may have changed.
471 $query = "update drug_sales SET fee = ?, " .
472 "encounter = ?, billed = 1 WHERE " .
473 "sale_id = ?";
474 sqlQuery($query, array($amount,$form_encounter,$id) );
476 else if ($code_type == 'TAX') {
477 // In the SL case taxes show up on the invoice as line items.
478 // Otherwise we gotta save them somewhere, and in the billing
479 // table with a code type of TAX seems easiest.
480 // They will have to be stripped back out when building this
481 // script's input form.
482 addBilling($form_encounter, 'TAX', 'TAX', 'Taxes', $form_pid, 0, 0,
483 '', '', $amount, '', '', 1);
485 else {
486 // Because there is no insurance here, there is no need for a claims
487 // table entry and so we do not call updateClaim(). Note we should not
488 // eliminate billed and bill_date from the billing table!
489 $query = "UPDATE billing SET fee = ?, billed = 1, " .
490 "bill_date = NOW() WHERE id = ?";
491 sqlQuery($query, array($amount,$id) );
495 // Post discount.
496 if ($_POST['form_discount']) {
497 if ($GLOBALS['discount_by_money']) {
498 $amount = sprintf('%01.2f', trim($_POST['form_discount']));
500 else {
501 $amount = sprintf('%01.2f', trim($_POST['form_discount']) * $form_amount / 100);
503 $memo = xl('Discount');
504 $time = date('Y-m-d H:i:s');
505 sqlBeginTrans();
506 $sequence_no = sqlQuery( "SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $form_encounter));
507 $query = "INSERT INTO ar_activity ( " .
508 "pid, encounter, sequence_no, code, modifier, payer_type, post_user, post_time, " .
509 "session_id, memo, adj_amount " .
510 ") VALUES ( " .
511 "?, " .
512 "?, " .
513 "?, " .
514 "'', " .
515 "'', " .
516 "'0', " .
517 "?, " .
518 "?, " .
519 "'0', " .
520 "?, " .
521 "? " .
522 ")";
523 sqlStatement($query, array($form_pid,$form_encounter,$sequence_no['increment'],$_SESSION['authUserID'],$time,$memo,$amount) );
524 sqlCommitTrans();
527 // Post payment.
528 if ($_POST['form_amount']) {
529 $amount = sprintf('%01.2f', trim($_POST['form_amount']));
530 $form_source = trim($_POST['form_source']);
531 $paydesc = trim($_POST['form_method']);
532 //Fetching the existing code and modifier
533 $ResultSearchNew = sqlStatement("SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key ".
534 "WHERE code_types.ct_fee=1 AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier",
535 array($form_pid,$form_encounter));
536 if($RowSearch = sqlFetchArray($ResultSearchNew))
538 $Codetype=$RowSearch['code_type'];
539 $Code=$RowSearch['code'];
540 $Modifier=$RowSearch['modifier'];
541 }else{
542 $Codetype='';
543 $Code='';
544 $Modifier='';
546 $session_id=sqlInsert("INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total,".
547 " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) ".
548 " VALUES ('0',?,?,now(),?,?,'','patient','COPAY',?,?,'patient_payment',now())",
549 array($_SESSION['authId'],$form_source,$dosdate,$amount,$form_pid,$paydesc));
551 sqlBeginTrans();
552 $sequence_no = sqlQuery( "SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $form_encounter));
553 $insrt_id=sqlInsert("INSERT INTO ar_activity (pid,encounter,sequence_no,code_type,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)".
554 " VALUES (?,?,?,?,?,?,0,?,?,?,?,'PCP')",
555 array($form_pid,$form_encounter,$sequence_no['increment'],$Codetype,$Code,$Modifier,$dosdate,$_SESSION['authId'],$session_id,$amount));
556 sqlCommitTrans();
559 // If applicable, set the invoice reference number.
560 $invoice_refno = '';
561 if (isset($_POST['form_irnumber'])) {
562 $invoice_refno = trim($_POST['form_irnumber']);
564 else {
565 $invoice_refno = updateInvoiceRefNumber();
567 if ($invoice_refno) {
568 sqlStatement("UPDATE form_encounter " .
569 "SET invoice_refno = ? " .
570 "WHERE pid = ? AND encounter = ?", array($invoice_refno,$form_pid,$form_encounter) );
573 generate_receipt($form_pid, $form_encounter);
574 exit();
577 // If an encounter ID was given, then we must generate a receipt.
579 if (!empty($_GET['enc'])) {
580 generate_receipt($patient_id, $_GET['enc']);
581 exit();
584 // Get the unbilled billing table items for this patient.
585 $query = "SELECT id, date, code_type, code, modifier, code_text, " .
586 "provider_id, payer_id, units, fee, encounter " .
587 "FROM billing WHERE pid = ? AND activity = 1 AND " .
588 "billed = 0 AND code_type != 'TAX' " .
589 "ORDER BY encounter DESC, id ASC";
590 $bres = sqlStatement($query, array($patient_id) );
592 // Get the product sales for this patient.
593 $query = "SELECT s.sale_id, s.sale_date, s.prescription_id, s.fee, " .
594 "s.quantity, s.encounter, s.drug_id, d.name, r.provider_id " .
595 "FROM drug_sales AS s " .
596 "LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " .
597 "LEFT OUTER JOIN prescriptions AS r ON r.id = s.prescription_id " .
598 "WHERE s.pid = ? AND s.billed = 0 " .
599 "ORDER BY s.encounter DESC, s.sale_id ASC";
600 $dres = sqlStatement($query, array($patient_id) );
602 // If there are none, just redisplay the last receipt and exit.
604 if (sqlNumRows($bres) == 0 && sqlNumRows($dres) == 0) {
605 generate_receipt($patient_id);
606 exit();
609 // Get the valid practitioners, including those not active.
610 $arr_users = array();
611 $ures = sqlStatement("SELECT id, username FROM users WHERE " .
612 "( authorized = 1 OR info LIKE '%provider%' ) AND username != ''");
613 while ($urow = sqlFetchArray($ures)) {
614 $arr_users[$urow['id']] = '1';
617 // Now write a data entry form:
618 // List unbilled billing items (cpt, hcpcs, copays) for the patient.
619 // List unbilled product sales for the patient.
620 // Present an editable dollar amount for each line item, a total
621 // which is also the default value of the input payment amount,
622 // and OK and Cancel buttons.
624 <html>
625 <head>
626 <link rel='stylesheet' href='<?php echo $css_header ?>' type='text/css'>
627 <link rel="stylesheet" href="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-datetimepicker-2-5-4/build/jquery.datetimepicker.min.css">
629 <title><?php echo xlt('Patient Checkout'); ?></title>
630 <style>
631 </style>
633 <script type="text/javascript" src="../../library/textformat.js?v=<?php echo $v_js_includes; ?>"></script>
634 <script type="text/javascript" src="../../library/dialog.js?v=<?php echo $v_js_includes; ?>"></script>
635 <script type="text/javascript" src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-min-3-1-1/index.js"></script>
636 <script type="text/javascript" src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-datetimepicker-2-5-4/build/jquery.datetimepicker.full.min.js"></script>
638 <script language="JavaScript">
639 var mypcc = '<?php echo $GLOBALS['phone_country_code'] ?>';
641 <?php require($GLOBALS['srcdir'] . "/restoreSession.php"); ?>
643 // This clears the tax line items in preparation for recomputing taxes.
644 function clearTax(visible) {
645 var f = document.forms[0];
646 for (var lino = 0; true; ++lino) {
647 var pfx = 'line[' + lino + ']';
648 if (! f[pfx + '[code_type]']) break;
649 if (f[pfx + '[code_type]'].value != 'TAX') continue;
650 f[pfx + '[price]'].value = '0.00';
651 if (visible) f[pfx + '[amount]'].value = '0.00';
655 // For a given tax ID and amount, compute the tax on that amount and add it
656 // to the "price" (same as "amount") of the corresponding tax line item.
657 // Note the tax line items include their "taxrate" to make this easy.
658 function addTax(rateid, amount, visible) {
659 if (rateid.length == 0) return 0;
660 var f = document.forms[0];
661 for (var lino = 0; true; ++lino) {
662 var pfx = 'line[' + lino + ']';
663 if (! f[pfx + '[code_type]']) break;
664 if (f[pfx + '[code_type]'].value != 'TAX') continue;
665 if (f[pfx + '[code]'].value != rateid) continue;
666 var tax = amount * parseFloat(f[pfx + '[taxrates]'].value);
667 tax = parseFloat(tax.toFixed(<?php echo $currdecimals ?>));
668 var cumtax = parseFloat(f[pfx + '[price]'].value) + tax;
669 f[pfx + '[price]'].value = cumtax.toFixed(<?php echo $currdecimals ?>); // requires JS 1.5
670 if (visible) f[pfx + '[amount]'].value = cumtax.toFixed(<?php echo $currdecimals ?>); // requires JS 1.5
671 if (isNaN(tax)) alert('Tax rate not numeric at line ' + lino);
672 return tax;
674 return 0;
677 // This mess recomputes the invoice total and optionally applies a discount.
678 function computeDiscountedTotals(discount, visible) {
679 clearTax(visible);
680 var f = document.forms[0];
681 var total = 0.00;
682 for (var lino = 0; f['line[' + lino + '][code_type]']; ++lino) {
683 var code_type = f['line[' + lino + '][code_type]'].value;
684 // price is price per unit when the form was originally generated.
685 // By contrast, amount is the dynamically-generated discounted line total.
686 var price = parseFloat(f['line[' + lino + '][price]'].value);
687 if (isNaN(price)) alert('Price not numeric at line ' + lino);
688 if (code_type == 'COPAY' || code_type == 'TAX') {
689 // This works because the tax lines come last.
690 total += parseFloat(price.toFixed(<?php echo $currdecimals ?>));
691 continue;
693 var units = f['line[' + lino + '][units]'].value;
694 var amount = price * units;
695 amount = parseFloat(amount.toFixed(<?php echo $currdecimals ?>));
696 if (visible) f['line[' + lino + '][amount]'].value = amount.toFixed(<?php echo $currdecimals ?>);
697 total += amount;
698 var taxrates = f['line[' + lino + '][taxrates]'].value;
699 var taxids = taxrates.split(':');
700 for (var j = 0; j < taxids.length; ++j) {
701 addTax(taxids[j], amount, visible);
704 return total - discount;
707 // Recompute displayed amounts with any discount applied.
708 function computeTotals() {
709 var f = document.forms[0];
710 var discount = parseFloat(f.form_discount.value);
711 if (isNaN(discount)) discount = 0;
712 <?php if (!$GLOBALS['discount_by_money']) { ?>
713 // This site discounts by percentage, so convert it to a money amount.
714 if (discount > 100) discount = 100;
715 if (discount < 0 ) discount = 0;
716 discount = 0.01 * discount * computeDiscountedTotals(0, false);
717 <?php } ?>
718 var total = computeDiscountedTotals(discount, true);
719 f.form_amount.value = total.toFixed(<?php echo $currdecimals ?>);
720 return true;
723 $(document).ready(function() {
724 $('.datepicker').datetimepicker({
725 <?php $datetimepicker_timepicker = false; ?>
726 <?php $datetimepicker_formatInput = false; ?>
727 <?php require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php'); ?>
728 <?php // can add any additional javascript settings to datetimepicker here; need to prepend first setting with a comma ?>
732 </script>
733 </head>
735 <body class="body_top">
737 <form method='post' action='pos_checkout.php'>
738 <input type='hidden' name='form_pid' value='<?php echo attr($patient_id) ?>' />
740 <center>
743 <table cellspacing='5'>
744 <tr>
745 <td colspan='3' align='center'>
746 <b><?php echo xlt('Patient Checkout for '); ?><?php echo text($patdata['fname']) . " " .
747 text($patdata['lname']) . " (" . text($patdata['pubpid']) . ")" ?></b>
748 </td>
749 </tr>
750 <tr>
751 <td><b><?php echo xlt('Date'); ?></b></td>
752 <td><b><?php echo xlt('Description'); ?></b></td>
753 <td align='right'><b><?php echo xlt('Qty'); ?></b></td>
754 <td align='right'><b><?php echo xlt('Amount'); ?></b></td>
755 </tr>
756 <?php
757 $inv_encounter = '';
758 $inv_date = '';
759 $inv_provider = 0;
760 $inv_payer = 0;
761 $gcac_related_visit = false;
762 $gcac_service_provided = false;
764 // Process billing table items.
765 // Items that are not allowed to have a fee are skipped.
767 while ($brow = sqlFetchArray($bres)) {
768 // Skip all but the most recent encounter.
769 if ($inv_encounter && $brow['encounter'] != $inv_encounter) continue;
771 $thisdate = substr($brow['date'], 0, 10);
772 $code_type = $brow['code_type'];
774 // Collect tax rates, related code and provider ID.
775 $taxrates = '';
776 $related_code = '';
777 $sqlBindArray = array();
778 if (!empty($code_types[$code_type]['fee'])) {
779 $query = "SELECT taxrates, related_code FROM codes WHERE code_type = ? " .
780 " AND " .
781 "code = ? AND ";
782 array_push($sqlBindArray,$code_types[$code_type]['id'],$brow['code']);
783 if ($brow['modifier']) {
784 $query .= "modifier = ?";
785 array_push($sqlBindArray,$brow['modifier']);
786 } else {
787 $query .= "(modifier IS NULL OR modifier = '')";
789 $query .= " LIMIT 1";
790 $tmp = sqlQuery($query,$sqlBindArray);
791 $taxrates = $tmp['taxrates'];
792 $related_code = $tmp['related_code'];
793 markTaxes($taxrates);
796 write_form_line($code_type, $brow['code'], $brow['id'], $thisdate,
797 $brow['code_text'], $brow['fee'], $brow['units'],
798 $taxrates);
799 if (!$inv_encounter) $inv_encounter = $brow['encounter'];
800 $inv_payer = $brow['payer_id'];
801 if (!$inv_date || $inv_date < $thisdate) $inv_date = $thisdate;
803 // Custom logic for IPPF to determine if a GCAC issue applies.
804 if ($GLOBALS['ippf_specific'] && $related_code) {
805 $relcodes = explode(';', $related_code);
806 foreach ($relcodes as $codestring) {
807 if ($codestring === '') continue;
808 list($codetype, $code) = explode(':', $codestring);
809 if ($codetype !== 'IPPF') continue;
810 if (preg_match('/^25222/', $code)) {
811 $gcac_related_visit = true;
812 if (preg_match('/^25222[34]/', $code))
813 $gcac_service_provided = true;
819 // Process copays
821 $totalCopay = getPatientCopay($patient_id,$encounter);
822 if ($totalCopay < 0) {
823 write_form_line("COPAY", "", "", "", "", $totalCopay, "", "");
826 // Process drug sales / products.
828 while ($drow = sqlFetchArray($dres)) {
829 if ($inv_encounter && $drow['encounter'] && $drow['encounter'] != $inv_encounter) continue;
831 $thisdate = $drow['sale_date'];
832 if (!$inv_encounter) $inv_encounter = $drow['encounter'];
834 if (!$inv_provider && !empty($arr_users[$drow['provider_id']]))
835 $inv_provider = $drow['provider_id'] + 0;
837 if (!$inv_date || $inv_date < $thisdate) $inv_date = $thisdate;
839 // Accumulate taxes for this product.
840 $tmp = sqlQuery("SELECT taxrates FROM drug_templates WHERE drug_id = ? " .
841 " ORDER BY selector LIMIT 1", array($drow['drug_id']) );
842 // accumTaxes($drow['fee'], $tmp['taxrates']);
843 $taxrates = $tmp['taxrates'];
844 markTaxes($taxrates);
846 write_form_line('PROD', $drow['drug_id'], $drow['sale_id'],
847 $thisdate, $drow['name'], $drow['fee'], $drow['quantity'], $taxrates);
850 // Write a form line for each tax that has money, adding to $total.
851 foreach ($taxes as $key => $value) {
852 if ($value[2]) {
853 write_form_line('TAX', $key, $key, date('Y-m-d'), $value[0], 0, 1, $value[1]);
857 // Besides copays, do not collect any other information from ar_activity,
858 // since this is for appt checkout.
860 if ($inv_encounter) {
861 $erow = sqlQuery("SELECT provider_id FROM form_encounter WHERE " .
862 "pid = ? AND encounter = ? " .
863 "ORDER BY id DESC LIMIT 1", array($patient_id,$inv_encounter) );
864 $inv_provider = $erow['provider_id'] + 0;
867 </table>
870 <table border='0' cellspacing='4'>
872 <tr>
873 <td>
874 <?php echo $GLOBALS['discount_by_money'] ? xlt('Discount Amount') : xlt('Discount Percentage'); ?>:
875 </td>
876 <td>
877 <input type='text' name='form_discount' size='6' maxlength='8' value=''
878 style='text-align:right' onkeyup='computeTotals()'>
879 </td>
880 </tr>
882 <tr>
883 <td>
884 <?php echo xlt('Payment Method'); ?>:
885 </td>
886 <td>
887 <select name='form_method'>
888 <?php
889 $query1112 = "SELECT * FROM list_options where list_id=? ORDER BY seq, title ";
890 $bres1112 = sqlStatement($query1112,array('payment_method'));
891 while ($brow1112 = sqlFetchArray($bres1112))
893 if($brow1112['option_id']=='electronic' || $brow1112['option_id']=='bank_draft')
894 continue;
895 echo "<option value='".attr($brow1112['option_id'])."'>".text(xl_list_label($brow1112['title']))."</option>";
898 </select>
899 </td>
900 </tr>
902 <tr>
903 <td>
904 <?php echo xlt('Check/Reference Number'); ?>:
905 </td>
906 <td>
907 <input type='text' name='form_source' size='10' value=''>
908 </td>
909 </tr>
911 <tr>
912 <td>
913 <?php echo xlt('Amount Paid'); ?>:
914 </td>
915 <td>
916 <input type='text' name='form_amount' size='10' value='0.00'>
917 </td>
918 </tr>
920 <tr>
921 <td>
922 <?php echo xlt('Posting Date'); ?>:
923 </td>
924 <td>
925 <input type='text' size='10' class='datepicker' name='form_date' id='form_date'
926 value='<?php echo attr($inv_date) ?>'
927 title='yyyy-mm-dd date of service' />
928 </td>
929 </tr>
931 <?php
932 // If this user has a non-empty irnpool assigned, show the pending
933 // invoice reference number.
934 $irnumber = getInvoiceRefNumber();
935 if (!empty($irnumber)) {
937 <tr>
938 <td>
939 <?php echo xlt('Tentative Invoice Ref No'); ?>:
940 </td>
941 <td>
942 <?php echo text($irnumber); ?>
943 </td>
944 </tr>
945 <?php
947 // Otherwise if there is an invoice reference number mask, ask for the refno.
948 else if (!empty($GLOBALS['gbl_mask_invoice_number'])) {
950 <tr>
951 <td>
952 <?php echo xlt('Invoice Reference Number'); ?>:
953 </td>
954 <td>
955 <input type='text' name='form_irnumber' size='10' value=''
956 onkeyup='maskkeyup(this,"<?php echo addslashes($GLOBALS['gbl_mask_invoice_number']); ?>")'
957 onblur='maskblur(this,"<?php echo addslashes($GLOBALS['gbl_mask_invoice_number']); ?>")'
959 </td>
960 </tr>
961 <?php
965 <tr>
966 <td colspan='2' align='center'>
967 &nbsp;<br>
968 <input type='submit' name='form_save' value='<?php echo xla('Save'); ?>' /> &nbsp;
969 <?php if (empty($_GET['framed'])) { ?>
970 <input type='button' value='<?php echo xla('Cancel'); ?>' onclick='window.close()' />
971 <?php } ?>
972 <input type='hidden' name='form_provider' value='<?php echo attr($inv_provider) ?>' />
973 <input type='hidden' name='form_payer' value='<?php echo attr($inv_payer) ?>' />
974 <input type='hidden' name='form_encounter' value='<?php echo attr($inv_encounter) ?>' />
975 </td>
976 </tr>
978 </table>
979 </center>
981 </form>
983 <script language='JavaScript'>
984 computeTotals();
986 <?php
987 if ($gcac_related_visit && !$gcac_service_provided) {
988 // Skip this warning if the GCAC visit form is not allowed.
989 $grow = sqlQuery("SELECT COUNT(*) AS count FROM list_options " .
990 "WHERE list_id = 'lbfnames' AND option_id = 'LBFgcac' AND activity = 1");
991 if (!empty($grow['count'])) { // if gcac is used
992 // Skip this warning if referral or abortion in TS.
993 $grow = sqlQuery("SELECT COUNT(*) AS count FROM transactions " .
994 "WHERE title = 'Referral' AND refer_date IS NOT NULL AND " .
995 "refer_date = ? AND pid = ?", array($inv_date,$patient_id) );
996 if (empty($grow['count'])) { // if there is no referral
997 $grow = sqlQuery("SELECT COUNT(*) AS count FROM forms " .
998 "WHERE pid = ? AND encounter = ? AND " .
999 "deleted = 0 AND formdir = 'LBFgcac'", array($patient_id,$inv_encounter) );
1000 if (empty($grow['count'])) { // if there is no gcac form
1001 echo " alert('" . addslashes(xl('This visit will need a GCAC form, referral or procedure service.')) . "');\n";
1005 } // end if ($gcac_related_visit)
1007 </script>
1009 </body>
1010 </html>