5 * This module supports a popup window to handle patient checkout
6 * as a point-of-sale transaction. Support for in-house drug sales
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
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,
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
35 * Copyright (C) 2006-2016 Rod Roark <rod@sunsetsystems.com>
37 * LICENSE: This program is free software; you can redistribute it and/or
38 * modify it under the terms of the GNU General Public License
39 * as published by the Free Software Foundation; either version 2
40 * of the License, or (at your option) any later version.
41 * This program is distributed in the hope that it will be useful,
42 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 * GNU General Public License for more details.
45 * You should have received a copy of the GNU General Public License
46 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
49 * @author Rod Roark <rod@sunsetsystems.com>
50 * @author Brady Miller <brady@sparmy.com>
51 * @link http://www.open-emr.org
55 $fake_register_globals=false;
56 $sanitize_all_escapes=true;
58 require_once("../globals.php");
59 require_once("$srcdir/acl.inc");
60 require_once("$srcdir/patient.inc");
61 require_once("$srcdir/billing.inc");
62 require_once("$srcdir/formatting.inc.php");
63 require_once("$srcdir/formdata.inc.php");
64 require_once("../../custom/code_types.inc.php");
66 $currdecimals = $GLOBALS['currency_decimals'];
68 $details = empty($_GET['details']) ?
0 : 1;
70 $patient_id = empty($_GET['ptid']) ?
$pid : 0 +
$_GET['ptid'];
72 // Get the patient's name and chart number.
73 $patdata = getPatientData($patient_id, 'fname,mname,lname,pubpid,street,city,state,postal_code');
75 // Output HTML for an invoice line item.
78 function receiptDetailLine($svcdate, $description, $amount, $quantity) {
79 global $prevsvcdate, $details;
80 if (!$details) return;
81 $amount = sprintf('%01.2f', $amount);
82 if (empty($quantity)) $quantity = 1;
83 $price = sprintf('%01.4f', $amount / $quantity);
84 $tmp = sprintf('%01.2f', $price);
85 if ($price == $tmp) $price = $tmp;
87 echo " <td>" . ($svcdate == $prevsvcdate ?
' ' : text(oeFormatShortDate($svcdate))) . "</td>\n";
88 echo " <td>" . text($description) . "</td>\n";
89 echo " <td align='right'>" . text(oeFormatMoney($price)) . "</td>\n";
90 echo " <td align='right'>" . text($quantity) . "</td>\n";
91 echo " <td align='right'>" . text(oeFormatMoney($amount)) . "</td>\n";
93 $prevsvcdate = $svcdate;
96 // Output HTML for an invoice payment.
98 function receiptPaymentLine($paydate, $amount, $description='') {
99 $amount = sprintf('%01.2f', 0 - $amount); // make it negative
101 echo " <td>" . text(oeFormatShortDate($paydate)) . "</td>\n";
102 echo " <td>" . xlt('Payment') . " " . text($description) . "</td>\n";
103 echo " <td colspan='2'> </td>\n";
104 echo " <td align='right'>" . text(oeFormatMoney($amount)) . "</td>\n";
108 // Generate a receipt from the last-billed invoice for this patient,
109 // or for the encounter specified as a GET parameter.
111 function generate_receipt($patient_id, $encounter=0) {
112 global $sl_err, $sl_cash_acc, $css_header, $details;
114 // Get details for what we guess is the primary facility.
115 $frow = sqlQuery("SELECT * FROM facility " .
116 "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
118 $patdata = getPatientData($patient_id, 'fname,mname,lname,pubpid,street,city,state,postal_code,providerID');
120 // Get the most recent invoice data or that for the specified encounter.
122 // Adding a provider check so that their info can be displayed on receipts
124 $ferow = sqlQuery("SELECT id, date, encounter, provider_id FROM form_encounter " .
125 "WHERE pid = ? AND encounter = ?", array($patient_id,$encounter) );
127 $ferow = sqlQuery("SELECT id, date, encounter, provider_id FROM form_encounter " .
129 "ORDER BY id DESC LIMIT 1", array($patient_id) );
131 if (empty($ferow)) die(xlt("This patient has no activity."));
132 $trans_id = $ferow['id'];
133 $encounter = $ferow['encounter'];
134 $svcdate = substr($ferow['date'], 0, 10);
136 if ($GLOBALS['receipts_by_provider']){
137 if (isset($ferow['provider_id']) ) {
138 $encprovider = $ferow['provider_id'];
139 } else if (isset($patdata['providerID'])){
140 $encprovider = $patdata['providerID'];
141 } else { $encprovider = -1; }
145 $providerrow = sqlQuery("SELECT fname, mname, lname, title, street, streetb, " .
146 "city, state, zip, phone, fax FROM users WHERE id = ?", array($encprovider) );
149 // Get invoice reference number.
150 $encrow = sqlQuery("SELECT invoice_refno FROM form_encounter WHERE " .
151 "pid = ? AND encounter = ? LIMIT 1", array($patient_id,$encounter) );
152 $invoice_refno = $encrow['invoice_refno'];
156 <?php
html_header_show(); ?
>
157 <link rel
='stylesheet' href
='<?php echo $css_header ?>' type
='text/css'>
158 <title
><?php
echo xlt('Receipt for Payment'); ?
></title
>
159 <script type
="text/javascript" src
="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-min-1-2-2/index.js"></script
>
160 <script type
="text/javascript" src
="../../library/dialog.js?v=<?php echo $v_js_includes; ?>"></script
>
161 <script language
="JavaScript">
163 <?php
require($GLOBALS['srcdir'] . "/restoreSession.php"); ?
>
165 $
(document
).ready(function() {
166 var win
= top
.printLogSetup ? top
: opener
.top
;
167 win
.printLogSetup(document
.getElementById('printbutton'));
170 // Process click on Print button.
171 function printlog_before_print() {
172 var divstyle
= document
.getElementById('hideonprint').style
;
173 divstyle
.display
= 'none';
176 // Process click on Delete button.
177 function deleteme() {
178 dlgopen('deleter.php?billing=<?php echo attr("$patient_id.$encounter"); ?>', '_blank', 500, 450);
182 // Called by the deleteme.php window on a successful delete.
183 function imdeleted() {
189 <body
class="body_top">
192 if ( $GLOBALS['receipts_by_provider'] && !empty($providerrow) ) { printProviderHeader($providerrow); }
193 else { printFacilityHeader($frow); }
196 echo xlt("Receipt Generated") . ":" . text(date(' F j, Y'));
197 if ($invoice_refno) echo " " . xlt("Invoice Number") . ": " . text($invoice_refno) . " " . xlt("Service Date") . ": " . text($svcdate);
203 <?php
echo text($patdata['fname']) . ' ' . text($patdata['mname']) . ' ' . text($patdata['lname']) ?
>
204 <br
><?php
echo text($patdata['street']) ?
>
205 <br
><?php
echo text($patdata['city']) . ', ' . text($patdata['state']) . ' ' . text($patdata['postal_code']) ?
>
209 <table cellpadding
='5'>
211 <td
><b
><?php
echo xlt('Date'); ?
></b
></td
>
212 <td
><b
><?php
echo xlt('Description'); ?
></b
></td
>
213 <td align
='right'><b
><?php
echo $details ?
xlt('Price') : ' '; ?
></b
></td
>
214 <td align
='right'><b
><?php
echo $details ?
xlt('Qty' ) : ' '; ?
></b
></td
>
215 <td align
='right'><b
><?php
echo xlt('Total'); ?
></b
></td
>
222 $inres = sqlStatement("SELECT s.sale_id, s.sale_date, s.fee, " .
223 "s.quantity, s.drug_id, d.name " .
224 "FROM drug_sales AS s LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " .
225 // "WHERE s.pid = '$patient_id' AND s.encounter = '$encounter' AND s.fee != 0 " .
226 "WHERE s.pid = ? AND s.encounter = ? " .
227 "ORDER BY s.sale_id", array($patient_id,$encounter) );
228 while ($inrow = sqlFetchArray($inres)) {
229 $charges +
= sprintf('%01.2f', $inrow['fee']);
230 receiptDetailLine($inrow['sale_date'], $inrow['name'],
231 $inrow['fee'], $inrow['quantity']);
233 // Service and tax items
234 $inres = sqlStatement("SELECT * FROM billing WHERE " .
235 "pid = ? AND encounter = ? AND " .
236 // "code_type != 'COPAY' AND activity = 1 AND fee != 0 " .
237 "code_type != 'COPAY' AND activity = 1 " .
238 "ORDER BY id", array($patient_id,$encounter) );
239 while ($inrow = sqlFetchArray($inres)) {
240 $charges +
= sprintf('%01.2f', $inrow['fee']);
241 receiptDetailLine($svcdate, $inrow['code_text'],
242 $inrow['fee'], $inrow['units']);
245 $inres = sqlStatement("SELECT " .
246 "a.code_type, a.code, a.modifier, a.memo, a.payer_type, a.adj_amount, a.pay_amount, " .
247 "s.payer_id, s.reference, s.check_date, s.deposit_date " .
248 "FROM ar_activity AS a " .
249 "LEFT JOIN ar_session AS s ON s.session_id = a.session_id WHERE " .
250 "a.pid = ? AND a.encounter = ? AND " .
251 "a.adj_amount != 0 " .
252 "ORDER BY s.check_date, a.sequence_no", array($patient_id,$encounter) );
253 while ($inrow = sqlFetchArray($inres)) {
254 $charges -= sprintf('%01.2f', $inrow['adj_amount']);
255 $payer = empty($inrow['payer_type']) ?
'Pt' : ('Ins' . $inrow['payer_type']);
256 receiptDetailLine($svcdate, $payer . ' ' . $inrow['memo'],
257 0 - $inrow['adj_amount'], 1);
262 <td colspan
='5'> 
;</td
>
265 <td
><?php
echo text(oeFormatShortDate($svcdispdate)); ?
></td
>
266 <td
><b
><?php
echo xlt('Total Charges'); ?
></b
></td
>
267 <td align
='right'> 
;</td
>
268 <td align
='right'> 
;</td
>
269 <td align
='right'><?php
echo text(oeFormatMoney($charges, true)) ?
></td
>
272 <td colspan
='5'> 
;</td
>
277 $inres = sqlStatement("SELECT fee, code_text FROM billing WHERE " .
278 "pid = ? AND encounter = ? AND " .
279 "code_type = 'COPAY' AND activity = 1 AND fee != 0 " .
280 "ORDER BY id", array($patient_id,$encounter) );
281 while ($inrow = sqlFetchArray($inres)) {
282 $charges +
= sprintf('%01.2f', $inrow['fee']);
283 receiptPaymentLine($svcdate, 0 - $inrow['fee'], $inrow['code_text']);
285 // Get other payments.
286 $inres = sqlStatement("SELECT " .
287 "a.code_type, a.code, a.modifier, a.memo, a.payer_type, a.adj_amount, a.pay_amount, " .
288 "s.payer_id, s.reference, s.check_date, s.deposit_date " .
289 "FROM ar_activity AS a " .
290 "LEFT JOIN ar_session AS s ON s.session_id = a.session_id WHERE " .
291 "a.pid = ? AND a.encounter = ? AND " .
292 "a.pay_amount != 0 " .
293 "ORDER BY s.check_date, a.sequence_no", array($patient_id,$encounter) );
294 while ($inrow = sqlFetchArray($inres)) {
295 $payer = empty($inrow['payer_type']) ?
'Pt' : ('Ins' . $inrow['payer_type']);
296 $charges -= sprintf('%01.2f', $inrow['pay_amount']);
297 receiptPaymentLine($svcdate, $inrow['pay_amount'],
298 $payer . ' ' . $inrow['reference']);
302 <td colspan
='5'> 
;</td
>
306 <td
><b
><?php
echo xlt('Balance Due'); ?
></b
></td
>
307 <td colspan
='2'> 
;</td
>
308 <td align
='right'><?php
echo text(oeFormatMoney($charges, true)) ?
></td
>
312 <div id
='hideonprint'>
315 <a href
='#' id
='printbutton'><?php
echo xlt('Print'); ?
></a
>
316 <?php
if (acl_check('acct','disc')) { ?
>
317  
; 
; 
; 
; 
;
318 <a href
='#' onclick
='return deleteme();'><?php
echo xlt('Undo Checkout'); ?
></a
>
320  
; 
; 
; 
; 
;
321 <?php
if ($details) { ?
>
322 <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
>
324 <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
>
331 } // end function generate_receipt()
333 // Function to output a line item for the input form.
336 function write_form_line($code_type, $code, $id, $date, $description,
337 $amount, $units, $taxrates) {
339 $amount = sprintf("%01.2f", $amount);
340 if (empty($units)) $units = 1;
341 $price = $amount / $units; // should be even cents, but ok here if not
342 if ($code_type == 'COPAY' && !$description) $description = xl('Payment');
344 echo " <td>" . text(oeFormatShortDate($date));
345 echo "<input type='hidden' name='line[$lino][code_type]' value='" . attr($code_type) . "'>";
346 echo "<input type='hidden' name='line[$lino][code]' value='" . attr($code) . "'>";
347 echo "<input type='hidden' name='line[$lino][id]' value='" . attr($id) . "'>";
348 echo "<input type='hidden' name='line[$lino][description]' value='" . attr($description) . "'>";
349 echo "<input type='hidden' name='line[$lino][taxrates]' value='" . attr($taxrates) . "'>";
350 echo "<input type='hidden' name='line[$lino][price]' value='" . attr($price) . "'>";
351 echo "<input type='hidden' name='line[$lino][units]' value='" . attr($units) . "'>";
353 echo " <td>" . text($description) . "</td>";
354 echo " <td align='right'>" . text($units) . "</td>";
355 echo " <td align='right'><input type='text' name='line[$lino][amount]' " .
356 "value='" . attr($amount) . "' size='6' maxlength='8'";
357 // Modifying prices requires the acct/disc permission.
358 // if ($code_type == 'TAX' || ($code_type != 'COPAY' && !acl_check('acct','disc')))
359 echo " style='text-align:right;background-color:transparent' readonly";
360 // else echo " style='text-align:right' onkeyup='computeTotals()'";
366 // Create the taxes array. Key is tax id, value is
367 // (description, rate, accumulated total).
369 $pres = sqlStatement("SELECT option_id, title, option_value " .
370 "FROM list_options WHERE list_id = 'taxrate' AND activity = 1 ORDER BY seq, title, option_id");
371 while ($prow = sqlFetchArray($pres)) {
372 $taxes[$prow['option_id']] = array($prow['title'], $prow['option_value'], 0);
375 // Print receipt header for facility
376 function printFacilityHeader($frow){
377 echo "<p><b>" . text($frow['name']) .
378 "<br>" . text($frow['street']) .
379 "<br>" . text($frow['city']) . ', ' . text($frow['state']) . ' ' . text($frow['postal_code']) .
380 "<br>" . text($frow['phone']) .
385 // Pring receipt header for Provider
386 function printProviderHeader($pvdrow){
387 echo "<p><b>" . text($pvdrow['title']) . " " . text($pvdrow['fname']) . " " . text($pvdrow['mname']) . " " . text($pvdrow['lname']) . " " .
388 "<br>" . text($pvdrow['street']) .
389 "<br>" . text($pvdrow['city']) . ', ' . text($pvdrow['state']) . ' ' . text($pvdrow['postal_code']) .
390 "<br>" . text($pvdrow['phone']) .
395 // Mark the tax rates that are referenced in this invoice.
396 function markTaxes($taxrates) {
398 $arates = explode(':', $taxrates);
399 if (empty($arates)) return;
400 foreach ($arates as $value) {
401 if (!empty($taxes[$value])) $taxes[$value][2] = '1';
405 $payment_methods = array(
414 $alertmsg = ''; // anything here pops up in an alert box
416 // If the Save button was clicked...
418 if ($_POST['form_save']) {
420 // On a save, do the following:
421 // Flag drug_sales and billing items as billed.
422 // Post the corresponding invoice with its payment(s) to sql-ledger
423 // and be careful to use a unique invoice number.
424 // Call the generate-receipt function.
427 $form_pid = $_POST['form_pid'];
428 $form_encounter = $_POST['form_encounter'];
430 // Get the posting date from the form as yyyy-mm-dd.
431 $dosdate = date("Y-m-d");
432 if (preg_match("/(\d\d\d\d)\D*(\d\d)\D*(\d\d)/", $_POST['form_date'], $matches)) {
433 $dosdate = $matches[1] . '-' . $matches[2] . '-' . $matches[3];
436 // If there is no associated encounter (i.e. this invoice has only
437 // prescriptions) then assign an encounter number of the service
438 // date, with an optional suffix to ensure that it's unique.
440 if (! $form_encounter) {
441 $form_encounter = substr($dosdate,0,4) . substr($dosdate,5,2) . substr($dosdate,8,2);
444 $ferow = sqlQuery("SELECT id FROM form_encounter WHERE " .
445 "pid = ? AND encounter = ?", array($form_pid, $form_encounter.$tmp) );
446 if (empty($ferow)) break;
447 $tmp = $tmp ?
$tmp +
1 : 1;
449 $form_encounter .= $tmp;
452 // Delete any TAX rows from billing because they will be recalculated.
453 sqlStatement("UPDATE billing SET activity = 0 WHERE " .
454 "pid = ? AND encounter = ? AND " .
455 "code_type = 'TAX'", array($form_pid,$form_encounter) );
457 $form_amount = $_POST['form_amount'];
458 $lines = $_POST['line'];
460 for ($lino = 0; $lines[$lino]['code_type']; ++
$lino) {
461 $line = $lines[$lino];
462 $code_type = $line['code_type'];
464 $amount = sprintf('%01.2f', trim($line['amount']));
467 if ($code_type == 'PROD') {
468 // Product sales. The fee and encounter ID may have changed.
469 $query = "update drug_sales SET fee = ?, " .
470 "encounter = ?, billed = 1 WHERE " .
472 sqlQuery($query, array($amount,$form_encounter,$id) );
474 else if ($code_type == 'TAX') {
475 // In the SL case taxes show up on the invoice as line items.
476 // Otherwise we gotta save them somewhere, and in the billing
477 // table with a code type of TAX seems easiest.
478 // They will have to be stripped back out when building this
479 // script's input form.
480 addBilling($form_encounter, 'TAX', 'TAX', 'Taxes', $form_pid, 0, 0,
481 '', '', $amount, '', '', 1);
484 // Because there is no insurance here, there is no need for a claims
485 // table entry and so we do not call updateClaim(). Note we should not
486 // eliminate billed and bill_date from the billing table!
487 $query = "UPDATE billing SET fee = ?, billed = 1, " .
488 "bill_date = NOW() WHERE id = ?";
489 sqlQuery($query, array($amount,$id) );
494 if ($_POST['form_discount']) {
495 if ($GLOBALS['discount_by_money']) {
496 $amount = sprintf('%01.2f', trim($_POST['form_discount']));
499 $amount = sprintf('%01.2f', trim($_POST['form_discount']) * $form_amount / 100);
501 $memo = xl('Discount');
502 $time = date('Y-m-d H:i:s');
504 $sequence_no = sqlQuery( "SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $form_encounter));
505 $query = "INSERT INTO ar_activity ( " .
506 "pid, encounter, sequence_no, code, modifier, payer_type, post_user, post_time, " .
507 "session_id, memo, adj_amount " .
521 sqlStatement($query, array($form_pid,$form_encounter,$sequence_no['increment'],$_SESSION['authUserID'],$time,$memo,$amount) );
526 if ($_POST['form_amount']) {
527 $amount = sprintf('%01.2f', trim($_POST['form_amount']));
528 $form_source = trim($_POST['form_source']);
529 $paydesc = trim($_POST['form_method']);
530 //Fetching the existing code and modifier
531 $ResultSearchNew = sqlStatement("SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key ".
532 "WHERE code_types.ct_fee=1 AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier",
533 array($form_pid,$form_encounter));
534 if($RowSearch = sqlFetchArray($ResultSearchNew))
536 $Codetype=$RowSearch['code_type'];
537 $Code=$RowSearch['code'];
538 $Modifier=$RowSearch['modifier'];
544 $session_id=sqlInsert("INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total,".
545 " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) ".
546 " VALUES ('0',?,?,now(),?,?,'','patient','COPAY',?,?,'patient_payment',now())",
547 array($_SESSION['authId'],$form_source,$dosdate,$amount,$form_pid,$paydesc));
550 $sequence_no = sqlQuery( "SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE pid = ? AND encounter = ?", array($form_pid, $form_encounter));
551 $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)".
552 " VALUES (?,?,?,?,?,?,0,?,?,?,?,'PCP')",
553 array($form_pid,$form_encounter,$sequence_no['increment'],$Codetype,$Code,$Modifier,$dosdate,$_SESSION['authId'],$session_id,$amount));
557 // If applicable, set the invoice reference number.
559 if (isset($_POST['form_irnumber'])) {
560 $invoice_refno = trim($_POST['form_irnumber']);
563 $invoice_refno = updateInvoiceRefNumber();
565 if ($invoice_refno) {
566 sqlStatement("UPDATE form_encounter " .
567 "SET invoice_refno = ? " .
568 "WHERE pid = ? AND encounter = ?", array($invoice_refno,$form_pid,$form_encounter) );
571 generate_receipt($form_pid, $form_encounter);
575 // If an encounter ID was given, then we must generate a receipt.
577 if (!empty($_GET['enc'])) {
578 generate_receipt($patient_id, $_GET['enc']);
582 // Get the unbilled billing table items for this patient.
583 $query = "SELECT id, date, code_type, code, modifier, code_text, " .
584 "provider_id, payer_id, units, fee, encounter " .
585 "FROM billing WHERE pid = ? AND activity = 1 AND " .
586 "billed = 0 AND code_type != 'TAX' " .
587 "ORDER BY encounter DESC, id ASC";
588 $bres = sqlStatement($query, array($patient_id) );
590 // Get the product sales for this patient.
591 $query = "SELECT s.sale_id, s.sale_date, s.prescription_id, s.fee, " .
592 "s.quantity, s.encounter, s.drug_id, d.name, r.provider_id " .
593 "FROM drug_sales AS s " .
594 "LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " .
595 "LEFT OUTER JOIN prescriptions AS r ON r.id = s.prescription_id " .
596 "WHERE s.pid = ? AND s.billed = 0 " .
597 "ORDER BY s.encounter DESC, s.sale_id ASC";
598 $dres = sqlStatement($query, array($patient_id) );
600 // If there are none, just redisplay the last receipt and exit.
602 if (sqlNumRows($bres) == 0 && sqlNumRows($dres) == 0) {
603 generate_receipt($patient_id);
607 // Get the valid practitioners, including those not active.
608 $arr_users = array();
609 $ures = sqlStatement("SELECT id, username FROM users WHERE " .
610 "( authorized = 1 OR info LIKE '%provider%' ) AND username != ''");
611 while ($urow = sqlFetchArray($ures)) {
612 $arr_users[$urow['id']] = '1';
615 // Now write a data entry form:
616 // List unbilled billing items (cpt, hcpcs, copays) for the patient.
617 // List unbilled product sales for the patient.
618 // Present an editable dollar amount for each line item, a total
619 // which is also the default value of the input payment amount,
620 // and OK and Cancel buttons.
624 <link rel
='stylesheet' href
='<?php echo $css_header ?>' type
='text/css'>
625 <title
><?php
echo xlt('Patient Checkout'); ?
></title
>
628 <style type
="text/css">@import
url(../../library
/dynarch_calendar
.css
);</style
>
629 <script type
="text/javascript" src
="../../library/textformat.js"></script
>
630 <script type
="text/javascript" src
="../../library/dynarch_calendar.js"></script
>
631 <?php
include_once("{$GLOBALS['srcdir']}/dynarch_calendar_en.inc.php"); ?
>
632 <script type
="text/javascript" src
="../../library/dynarch_calendar_setup.js"></script
>
633 <script type
="text/javascript" src
="../../library/dialog.js?v=<?php echo $v_js_includes; ?>"></script
>
634 <script type
="text/javascript" src
="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-min-1-2-2/index.js"></script
>
635 <script language
="JavaScript">
636 var mypcc
= '<?php echo $GLOBALS['phone_country_code
'] ?>';
638 <?php
require($GLOBALS['srcdir'] . "/restoreSession.php"); ?
>
640 // This clears the tax line items in preparation for recomputing taxes.
641 function clearTax(visible
) {
642 var f
= document
.forms
[0];
643 for (var lino
= 0; true; ++lino
) {
644 var pfx
= 'line[' + lino +
']';
645 if (! f
[pfx +
'[code_type]']) break;
646 if (f
[pfx +
'[code_type]'].value
!= 'TAX') continue;
647 f
[pfx +
'[price]'].value
= '0.00';
648 if (visible
) f
[pfx +
'[amount]'].value
= '0.00';
652 // For a given tax ID and amount, compute the tax on that amount and add it
653 // to the "price" (same as "amount") of the corresponding tax line item.
654 // Note the tax line items include their "taxrate" to make this easy.
655 function addTax(rateid
, amount
, visible
) {
656 if (rateid
.length
== 0) return 0;
657 var f
= document
.forms
[0];
658 for (var lino
= 0; true; ++lino
) {
659 var pfx
= 'line[' + lino +
']';
660 if (! f
[pfx +
'[code_type]']) break;
661 if (f
[pfx +
'[code_type]'].value
!= 'TAX') continue;
662 if (f
[pfx +
'[code]'].value
!= rateid
) continue;
663 var tax
= amount
* parseFloat(f
[pfx +
'[taxrates]'].value
);
664 tax
= parseFloat(tax
.toFixed(<?php
echo $currdecimals ?
>));
665 var cumtax
= parseFloat(f
[pfx +
'[price]'].value
) + tax
;
666 f
[pfx +
'[price]'].value
= cumtax
.toFixed(<?php
echo $currdecimals ?
>); // requires JS 1.5
667 if (visible
) f
[pfx +
'[amount]'].value
= cumtax
.toFixed(<?php
echo $currdecimals ?
>); // requires JS 1.5
668 if (isNaN(tax
)) alert('Tax rate not numeric at line ' + lino
);
674 // This mess recomputes the invoice total and optionally applies a discount.
675 function computeDiscountedTotals(discount
, visible
) {
677 var f
= document
.forms
[0];
679 for (var lino
= 0; f
['line[' + lino +
'][code_type]']; ++lino
) {
680 var code_type
= f
['line[' + lino +
'][code_type]'].value
;
681 // price is price per unit when the form was originally generated.
682 // By contrast, amount is the dynamically-generated discounted line total.
683 var price
= parseFloat(f
['line[' + lino +
'][price]'].value
);
684 if (isNaN(price
)) alert('Price not numeric at line ' + lino
);
685 if (code_type
== 'COPAY' || code_type
== 'TAX') {
686 // This works because the tax lines come last.
687 total +
= parseFloat(price
.toFixed(<?php
echo $currdecimals ?
>));
690 var units
= f
['line[' + lino +
'][units]'].value
;
691 var amount
= price
* units
;
692 amount
= parseFloat(amount
.toFixed(<?php
echo $currdecimals ?
>));
693 if (visible
) f
['line[' + lino +
'][amount]'].value
= amount
.toFixed(<?php
echo $currdecimals ?
>);
695 var taxrates
= f
['line[' + lino +
'][taxrates]'].value
;
696 var taxids
= taxrates
.split(':');
697 for (var j
= 0; j
< taxids
.length
; ++j
) {
698 addTax(taxids
[j
], amount
, visible
);
701 return total
- discount
;
704 // Recompute displayed amounts with any discount applied.
705 function computeTotals() {
706 var f
= document
.forms
[0];
707 var discount
= parseFloat(f
.form_discount
.value
);
708 if (isNaN(discount
)) discount
= 0;
709 <?php
if (!$GLOBALS['discount_by_money']) { ?
>
710 // This site discounts by percentage, so convert it to a money amount.
711 if (discount
> 100) discount
= 100;
712 if (discount
< 0 ) discount
= 0;
713 discount
= 0.01 * discount
* computeDiscountedTotals(0, false);
715 var total
= computeDiscountedTotals(discount
, true);
716 f
.form_amount
.value
= total
.toFixed(<?php
echo $currdecimals ?
>);
723 <body
class="body_top">
725 <form method
='post' action
='pos_checkout.php'>
726 <input type
='hidden' name
='form_pid' value
='<?php echo attr($patient_id) ?>' />
731 <table cellspacing
='5'>
733 <td colspan
='3' align
='center'>
734 <b
><?php
echo xlt('Patient Checkout for '); ?
><?php
echo text($patdata['fname']) . " " .
735 text($patdata['lname']) . " (" . text($patdata['pubpid']) . ")" ?
></b
>
739 <td
><b
><?php
echo xlt('Date'); ?
></b
></td
>
740 <td
><b
><?php
echo xlt('Description'); ?
></b
></td
>
741 <td align
='right'><b
><?php
echo xlt('Qty'); ?
></b
></td
>
742 <td align
='right'><b
><?php
echo xlt('Amount'); ?
></b
></td
>
749 $gcac_related_visit = false;
750 $gcac_service_provided = false;
752 // Process billing table items.
753 // Items that are not allowed to have a fee are skipped.
755 while ($brow = sqlFetchArray($bres)) {
756 // Skip all but the most recent encounter.
757 if ($inv_encounter && $brow['encounter'] != $inv_encounter) continue;
759 $thisdate = substr($brow['date'], 0, 10);
760 $code_type = $brow['code_type'];
762 // Collect tax rates, related code and provider ID.
765 $sqlBindArray = array();
766 if (!empty($code_types[$code_type]['fee'])) {
767 $query = "SELECT taxrates, related_code FROM codes WHERE code_type = ? " .
770 array_push($sqlBindArray,$code_types[$code_type]['id'],$brow['code']);
771 if ($brow['modifier']) {
772 $query .= "modifier = ?";
773 array_push($sqlBindArray,$brow['modifier']);
775 $query .= "(modifier IS NULL OR modifier = '')";
777 $query .= " LIMIT 1";
778 $tmp = sqlQuery($query,$sqlBindArray);
779 $taxrates = $tmp['taxrates'];
780 $related_code = $tmp['related_code'];
781 markTaxes($taxrates);
784 write_form_line($code_type, $brow['code'], $brow['id'], $thisdate,
785 $brow['code_text'], $brow['fee'], $brow['units'],
787 if (!$inv_encounter) $inv_encounter = $brow['encounter'];
788 $inv_payer = $brow['payer_id'];
789 if (!$inv_date ||
$inv_date < $thisdate) $inv_date = $thisdate;
791 // Custom logic for IPPF to determine if a GCAC issue applies.
792 if ($GLOBALS['ippf_specific'] && $related_code) {
793 $relcodes = explode(';', $related_code);
794 foreach ($relcodes as $codestring) {
795 if ($codestring === '') continue;
796 list($codetype, $code) = explode(':', $codestring);
797 if ($codetype !== 'IPPF') continue;
798 if (preg_match('/^25222/', $code)) {
799 $gcac_related_visit = true;
800 if (preg_match('/^25222[34]/', $code))
801 $gcac_service_provided = true;
809 $totalCopay = getPatientCopay($patient_id,$encounter);
810 if ($totalCopay < 0) {
811 write_form_line("COPAY", "", "", "", "", $totalCopay, "", "");
814 // Process drug sales / products.
816 while ($drow = sqlFetchArray($dres)) {
817 if ($inv_encounter && $drow['encounter'] && $drow['encounter'] != $inv_encounter) continue;
819 $thisdate = $drow['sale_date'];
820 if (!$inv_encounter) $inv_encounter = $drow['encounter'];
822 if (!$inv_provider && !empty($arr_users[$drow['provider_id']]))
823 $inv_provider = $drow['provider_id'] +
0;
825 if (!$inv_date ||
$inv_date < $thisdate) $inv_date = $thisdate;
827 // Accumulate taxes for this product.
828 $tmp = sqlQuery("SELECT taxrates FROM drug_templates WHERE drug_id = ? " .
829 " ORDER BY selector LIMIT 1", array($drow['drug_id']) );
830 // accumTaxes($drow['fee'], $tmp['taxrates']);
831 $taxrates = $tmp['taxrates'];
832 markTaxes($taxrates);
834 write_form_line('PROD', $drow['drug_id'], $drow['sale_id'],
835 $thisdate, $drow['name'], $drow['fee'], $drow['quantity'], $taxrates);
838 // Write a form line for each tax that has money, adding to $total.
839 foreach ($taxes as $key => $value) {
841 write_form_line('TAX', $key, $key, date('Y-m-d'), $value[0], 0, 1, $value[1]);
845 // Besides copays, do not collect any other information from ar_activity,
846 // since this is for appt checkout.
848 if ($inv_encounter) {
849 $erow = sqlQuery("SELECT provider_id FROM form_encounter WHERE " .
850 "pid = ? AND encounter = ? " .
851 "ORDER BY id DESC LIMIT 1", array($patient_id,$inv_encounter) );
852 $inv_provider = $erow['provider_id'] +
0;
858 <table border
='0' cellspacing
='4'>
862 <?php
echo $GLOBALS['discount_by_money'] ?
xlt('Discount Amount') : xlt('Discount Percentage'); ?
>:
865 <input type
='text' name
='form_discount' size
='6' maxlength
='8' value
=''
866 style
='text-align:right' onkeyup
='computeTotals()'>
872 <?php
echo xlt('Payment Method'); ?
>:
875 <select name
='form_method'>
877 $query1112 = "SELECT * FROM list_options where list_id=? ORDER BY seq, title ";
878 $bres1112 = sqlStatement($query1112,array('payment_method'));
879 while ($brow1112 = sqlFetchArray($bres1112))
881 if($brow1112['option_id']=='electronic' ||
$brow1112['option_id']=='bank_draft')
883 echo "<option value='".attr($brow1112['option_id'])."'>".text(xl_list_label($brow1112['title']))."</option>";
892 <?php
echo xlt('Check/Reference Number'); ?
>:
895 <input type
='text' name
='form_source' size
='10' value
=''>
901 <?php
echo xlt('Amount Paid'); ?
>:
904 <input type
='text' name
='form_amount' size
='10' value
='0.00'>
910 <?php
echo xlt('Posting Date'); ?
>:
913 <input type
='text' size
='10' name
='form_date' id
='form_date'
914 value
='<?php echo attr($inv_date) ?>'
915 title
='yyyy-mm-dd date of service'
916 onkeyup
='datekeyup(this,mypcc)' onblur
='dateblur(this,mypcc)' />
917 <img src
='../pic/show_calendar.gif' align
='absbottom' width
='24' height
='22'
918 id
='img_date' border
='0' alt
='[?]' style
='cursor:pointer'
919 title
='<?php echo xla("Click here to choose a date"); ?>'>
924 // If this user has a non-empty irnpool assigned, show the pending
925 // invoice reference number.
926 $irnumber = getInvoiceRefNumber();
927 if (!empty($irnumber)) {
931 <?php
echo xlt('Tentative Invoice Ref No'); ?
>:
934 <?php
echo text($irnumber); ?
>
939 // Otherwise if there is an invoice reference number mask, ask for the refno.
940 else if (!empty($GLOBALS['gbl_mask_invoice_number'])) {
944 <?php
echo xlt('Invoice Reference Number'); ?
>:
947 <input type
='text' name
='form_irnumber' size
='10' value
=''
948 onkeyup
='maskkeyup(this,"<?php echo addslashes($GLOBALS['gbl_mask_invoice_number
']); ?>")'
949 onblur
='maskblur(this,"<?php echo addslashes($GLOBALS['gbl_mask_invoice_number
']); ?>")'
958 <td colspan
='2' align
='center'>
960 <input type
='submit' name
='form_save' value
='<?php echo xla('Save
'); ?>' />  
;
961 <?php
if (empty($_GET['framed'])) { ?
>
962 <input type
='button' value
='<?php echo xla('Cancel
'); ?>' onclick
='window.close()' />
964 <input type
='hidden' name
='form_provider' value
='<?php echo attr($inv_provider) ?>' />
965 <input type
='hidden' name
='form_payer' value
='<?php echo attr($inv_payer) ?>' />
966 <input type
='hidden' name
='form_encounter' value
='<?php echo attr($inv_encounter) ?>' />
975 <script language
='JavaScript'>
976 Calendar
.setup({inputField
:"form_date", ifFormat
:"%Y-%m-%d", button
:"img_date"});
980 if ($gcac_related_visit && !$gcac_service_provided) {
981 // Skip this warning if the GCAC visit form is not allowed.
982 $grow = sqlQuery("SELECT COUNT(*) AS count FROM list_options " .
983 "WHERE list_id = 'lbfnames' AND option_id = 'LBFgcac' AND activity = 1");
984 if (!empty($grow['count'])) { // if gcac is used
985 // Skip this warning if referral or abortion in TS.
986 $grow = sqlQuery("SELECT COUNT(*) AS count FROM transactions " .
987 "WHERE title = 'Referral' AND refer_date IS NOT NULL AND " .
988 "refer_date = ? AND pid = ?", array($inv_date,$patient_id) );
989 if (empty($grow['count'])) { // if there is no referral
990 $grow = sqlQuery("SELECT COUNT(*) AS count FROM forms " .
991 "WHERE pid = ? AND encounter = ? AND " .
992 "deleted = 0 AND formdir = 'LBFgcac'", array($patient_id,$inv_encounter) );
993 if (empty($grow['count'])) { // if there is no gcac form
994 echo " alert('" . addslashes(xl('This visit will need a GCAC form, referral or procedure service.')) . "');\n";
998 } // end if ($gcac_related_visit)