Removed sql-ledger, take 3.
[openemr.git] / interface / patient_file / pos_checkout.php
blob6c70503f7356a953d5701b5ffffeb41715fb5064
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-2010 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>;.
48 * @package OpenEMR
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/freeb/xmlrpc.inc");
63 require_once("$srcdir/freeb/xmlrpcs.inc");
64 require_once("$srcdir/formatting.inc.php");
65 require_once("$srcdir/formdata.inc.php");
66 require_once("../../custom/code_types.inc.php");
68 $currdecimals = $GLOBALS['currency_decimals'];
70 $details = empty($_GET['details']) ? 0 : 1;
72 $patient_id = empty($_GET['ptid']) ? $pid : 0 + $_GET['ptid'];
74 // Get the patient's name and chart number.
75 $patdata = getPatientData($patient_id, 'fname,mname,lname,pubpid,street,city,state,postal_code');
77 // Get the "next invoice reference number" from this user's pool.
79 function getInvoiceRefNumber() {
80 $trow = sqlQuery("SELECT lo.notes " .
81 "FROM users AS u, list_options AS lo " .
82 "WHERE u.username = ? AND " .
83 "lo.list_id = 'irnpool' AND lo.option_id = u.irnpool LIMIT 1", array($_SESSION['authUser']) );
84 return empty($trow['notes']) ? '' : $trow['notes'];
87 // Increment the "next invoice reference number" of this user's pool.
88 // This identifies the "digits" portion of that number and adds 1 to it.
89 // If it contains more than one string of digits, the last is used.
91 function updateInvoiceRefNumber() {
92 $irnumber = getInvoiceRefNumber();
93 // Here "?" specifies a minimal match, to get the most digits possible:
94 if (preg_match('/^(.*?)(\d+)(\D*)$/', $irnumber, $matches)) {
95 $newdigs = sprintf('%0' . strlen($matches[2]) . 'd', $matches[2] + 1);
96 $newnumber = $matches[1] . $newdigs . $matches[3];
97 sqlStatement("UPDATE users AS u, list_options AS lo " .
98 "SET lo.notes = ? WHERE " .
99 "u.username = ? AND " .
100 "lo.list_id = 'irnpool' AND lo.option_id = u.irnpool", array($newnumber,$_SESSION['authUser']) );
102 return $irnumber;
105 //////////////////////////////////////////////////////////////////////
106 // The following functions are inline here temporarily, and should be
107 // moved to an includable module for common use. In particular
108 // WSClaim.class.php should be rewritten to use them.
109 //////////////////////////////////////////////////////////////////////
111 // Initialize the array of invoice information for posting to the
112 // accounting system.
114 function invoice_initialize(& $invoice_info, $patient_id, $provider_id,
115 $payer_id = 0, $encounter = 0, $dosdate = '')
117 $db = $GLOBALS['adodb']['db'];
119 // Get foreign ID (customer) for patient.
120 $sql = "SELECT foreign_id from integration_mapping as im " .
121 "LEFT JOIN patient_data as pd on im.local_id=pd.id " .
122 "where pd.pid = ? and im.local_table='patient_data' and im.foreign_table='customer'";
123 $result = $db->Execute($sql, array($patient_id) );
124 if($result && !$result->EOF) {
125 $foreign_patient_id = $result->fields['foreign_id'];
127 else {
128 return "Patient '" . $patient_id . "' has not yet been posted to the accounting system.";
131 // Get foreign ID (salesman) for provider.
132 $sql = "SELECT foreign_id from integration_mapping WHERE " .
133 "local_id = ? AND local_table='users' and foreign_table='salesman'";
134 $result = $db->Execute($sql, array($provider_id) );
135 if($result && !$result->EOF) {
136 $foreign_provider_id = $result->fields['foreign_id'];
138 else {
139 return "Provider '" . $provider_id . "' has not yet been posted to the accounting system.";
142 // Get foreign ID (customer) for insurance payer.
143 if ($payer_id && ! $GLOBALS['insurance_companies_are_not_customers']) {
144 $sql = "SELECT foreign_id from integration_mapping WHERE " .
145 "local_id = ? AND local_table = 'insurance_companies' AND foreign_table='customer'";
146 $result = $db->Execute($sql, array($payer_id) );
147 if($result && !$result->EOF) {
148 $foreign_payer_id = $result->fields['foreign_id'];
150 else {
151 return "Payer '" . $payer_id . "' has not yet been posted to the accounting system.";
153 } else {
154 $foreign_payer_id = $payer_id;
157 // Create invoice notes for the new invoice that list the patient's
158 // insurance plans. This is so that when payments are posted, the user
159 // can easily see if a secondary claim needs to be submitted.
161 $insnotes = "";
162 $insno = 0;
163 foreach (array("primary", "secondary", "tertiary") as $instype) {
164 ++$insno;
165 $sql = "SELECT insurance_companies.name " .
166 "FROM insurance_data, insurance_companies WHERE " .
167 "insurance_data.pid = ? AND " .
168 "insurance_data.type = ? AND " .
169 "insurance_companies.id = insurance_data.provider " .
170 "ORDER BY insurance_data.date DESC LIMIT 1";
171 $result = $db->Execute($sql, array($patient_id,$instype) );
172 if ($result && !$result->EOF && $result->fields['name']) {
173 if ($insnotes) $insnotes .= "\n";
174 $insnotes .= "Ins$insno: " . $result->fields['name'];
177 $invoice_info['notes'] = $insnotes;
179 if (preg_match("/(\d\d\d\d)\D*(\d\d)\D*(\d\d)/", $dosdate, $matches)) {
180 $dosdate = $matches[2] . '-' . $matches[3] . '-' . $matches[1];
181 } else {
182 $dosdate = date("m-d-Y");
185 $invoice_info['salesman'] = $foreign_provider_id;
186 $invoice_info['customerid'] = $foreign_patient_id;
187 $invoice_info['payer_id'] = $foreign_payer_id;
188 $invoice_info['invoicenumber'] = $patient_id . "." . $encounter;
189 $invoice_info['dosdate'] = $dosdate;
190 $invoice_info['items'] = array();
191 $invoice_info['total'] = '0.00';
193 return '';
196 function invoice_add_line_item(& $invoice_info, $code_type, $code,
197 $code_text, $amount, $units=1)
199 $units = max(1, intval(trim($units)));
200 $amount = sprintf("%01.2f", $amount);
201 $price = $amount / $units;
202 $tmp = sprintf("%01.2f", $price);
203 if (abs($price - $tmp) < 0.000001) $price = $tmp;
204 $tii = array();
205 $tii['maincode'] = $code;
206 $tii['itemtext'] = "$code_type:$code";
207 if ($code_text) $tii['itemtext'] .= " $code_text";
208 $tii['qty'] = $units;
209 $tii['price'] = $price;
210 $tii['glaccountid'] = $GLOBALS['oer_config']['ws_accounting']['income_acct'];
211 $invoice_info['total'] = sprintf("%01.2f", $invoice_info['total'] + $amount);
212 $invoice_info['items'][] = $tii;
213 return '';
216 function invoice_post(& $invoice_info)
218 $function['ezybiz.add_invoice'] = array(new xmlrpcval($invoice_info, "struct"));
220 list($name, $var) = each($function);
221 $f = new xmlrpcmsg($name, $var);
223 $c = new xmlrpc_client($GLOBALS['oer_config']['ws_accounting']['url'],
224 $GLOBALS['oer_config']['ws_accounting']['server'],
225 $GLOBALS['oer_config']['ws_accounting']['port']);
227 $c->setCredentials($GLOBALS['oer_config']['ws_accounting']['username'],
228 $GLOBALS['oer_config']['ws_accounting']['password']);
230 $r = $c->send($f);
231 if (!$r) return "XMLRPC send failed";
233 // We are not doing anything with the return value yet... should we?
234 $tv = $r->value();
235 if (is_object($tv)) {
236 $value = $tv->getval();
238 else {
239 $value = null;
242 if ($r->faultCode()) {
243 return "Fault: Code: " . $r->faultCode() . " Reason '" . $r->faultString() . "'";
246 return '';
249 ///////////// End of SQL-Ledger invoice posting functions ////////////
251 // Output HTML for an invoice line item.
253 $prevsvcdate = '';
254 function receiptDetailLine($svcdate, $description, $amount, $quantity) {
255 global $prevsvcdate, $details;
256 if (!$details) return;
257 $amount = sprintf('%01.2f', $amount);
258 if (empty($quantity)) $quantity = 1;
259 $price = sprintf('%01.4f', $amount / $quantity);
260 $tmp = sprintf('%01.2f', $price);
261 if ($price == $tmp) $price = $tmp;
262 echo " <tr>\n";
263 echo " <td>" . ($svcdate == $prevsvcdate ? '&nbsp;' : text(oeFormatShortDate($svcdate))) . "</td>\n";
264 echo " <td>" . text($description) . "</td>\n";
265 echo " <td align='right'>" . text(oeFormatMoney($price)) . "</td>\n";
266 echo " <td align='right'>" . text($quantity) . "</td>\n";
267 echo " <td align='right'>" . text(oeFormatMoney($amount)) . "</td>\n";
268 echo " </tr>\n";
269 $prevsvcdate = $svcdate;
272 // Output HTML for an invoice payment.
274 function receiptPaymentLine($paydate, $amount, $description='') {
275 $amount = sprintf('%01.2f', 0 - $amount); // make it negative
276 echo " <tr>\n";
277 echo " <td>" . text(oeFormatShortDate($paydate)) . "</td>\n";
278 echo " <td>" . xlt('Payment') . " " . text($description) . "</td>\n";
279 echo " <td colspan='2'>&nbsp;</td>\n";
280 echo " <td align='right'>" . text(oeFormatMoney($amount)) . "</td>\n";
281 echo " </tr>\n";
284 // Generate a receipt from the last-billed invoice for this patient,
285 // or for the encounter specified as a GET parameter.
287 function generate_receipt($patient_id, $encounter=0) {
288 global $sl_err, $sl_cash_acc, $css_header, $details;
290 // Get details for what we guess is the primary facility.
291 $frow = sqlQuery("SELECT * FROM facility " .
292 "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
294 $patdata = getPatientData($patient_id, 'fname,mname,lname,pubpid,street,city,state,postal_code,providerID');
296 // Get the most recent invoice data or that for the specified encounter.
298 // Adding a provider check so that their info can be displayed on receipts
299 if ($encounter) {
300 $ferow = sqlQuery("SELECT id, date, encounter, provider_id FROM form_encounter " .
301 "WHERE pid = ? AND encounter = ?", array($patient_id,$encounter) );
302 } else {
303 $ferow = sqlQuery("SELECT id, date, encounter, provider_id FROM form_encounter " .
304 "WHERE pid = ? " .
305 "ORDER BY id DESC LIMIT 1", array($patient_id) );
307 if (empty($ferow)) die(xlt("This patient has no activity."));
308 $trans_id = $ferow['id'];
309 $encounter = $ferow['encounter'];
310 $svcdate = substr($ferow['date'], 0, 10);
312 if ($GLOBALS['receipts_by_provider']){
313 if (isset($ferow['provider_id']) ) {
314 $encprovider = $ferow['provider_id'];
315 } else if (isset($patdata['providerID'])){
316 $encprovider = $patdata['providerID'];
317 } else { $encprovider = -1; }
320 if ($encprovider){
321 $providerrow = sqlQuery("SELECT fname, mname, lname, title, street, streetb, " .
322 "city, state, zip, phone, fax FROM users WHERE id = ?", array($encprovider) );
325 // Get invoice reference number.
326 $encrow = sqlQuery("SELECT invoice_refno FROM form_encounter WHERE " .
327 "pid = ? AND encounter = ? LIMIT 1", array($patient_id,$encounter) );
328 $invoice_refno = $encrow['invoice_refno'];
330 <html>
331 <head>
332 <?php html_header_show(); ?>
333 <link rel='stylesheet' href='<?php echo $css_header ?>' type='text/css'>
334 <title><?php echo xlt('Receipt for Payment'); ?></title>
335 <script type="text/javascript" src="../../library/js/jquery-1.2.2.min.js"></script>
336 <script type="text/javascript" src="../../library/dialog.js"></script>
337 <script language="JavaScript">
339 <?php require($GLOBALS['srcdir'] . "/restoreSession.php"); ?>
341 $(document).ready(function() {
342 var win = top.printLogSetup ? top : opener.top;
343 win.printLogSetup(document.getElementById('printbutton'));
346 // Process click on Print button.
347 function printlog_before_print() {
348 var divstyle = document.getElementById('hideonprint').style;
349 divstyle.display = 'none';
352 // Process click on Delete button.
353 function deleteme() {
354 dlgopen('deleter.php?billing=<?php echo attr("$patient_id.$encounter"); ?>', '_blank', 500, 450);
355 return false;
358 // Called by the deleteme.php window on a successful delete.
359 function imdeleted() {
360 window.close();
363 </script>
364 </head>
365 <body class="body_top">
366 <center>
367 <?php
368 if ( $GLOBALS['receipts_by_provider'] && !empty($providerrow) ) { printProviderHeader($providerrow); }
369 else { printFacilityHeader($frow); }
371 <?php
372 echo xlt("Receipt Generated") . ":" . text(date(' F j, Y'));
373 if ($invoice_refno) echo " " . xlt("Invoice Number") . ": " . text($invoice_refno) . " " . xlt("Service Date") . ": " . text($svcdate);
375 <br>&nbsp;
376 </b></p>
377 </center>
379 <?php echo text($patdata['fname']) . ' ' . text($patdata['mname']) . ' ' . text($patdata['lname']) ?>
380 <br><?php echo text($patdata['street']) ?>
381 <br><?php echo text($patdata['city']) . ', ' . text($patdata['state']) . ' ' . text($patdata['postal_code']) ?>
382 <br>&nbsp;
383 </p>
384 <center>
385 <table cellpadding='5'>
386 <tr>
387 <td><b><?php echo xlt('Date'); ?></b></td>
388 <td><b><?php echo xlt('Description'); ?></b></td>
389 <td align='right'><b><?php echo $details ? xlt('Price') : '&nbsp;'; ?></b></td>
390 <td align='right'><b><?php echo $details ? xlt('Qty' ) : '&nbsp;'; ?></b></td>
391 <td align='right'><b><?php echo xlt('Total'); ?></b></td>
392 </tr>
394 <?php
395 $charges = 0.00;
397 // Product sales
398 $inres = sqlStatement("SELECT s.sale_id, s.sale_date, s.fee, " .
399 "s.quantity, s.drug_id, d.name " .
400 "FROM drug_sales AS s LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " .
401 // "WHERE s.pid = '$patient_id' AND s.encounter = '$encounter' AND s.fee != 0 " .
402 "WHERE s.pid = ? AND s.encounter = ? " .
403 "ORDER BY s.sale_id", array($patient_id,$encounter) );
404 while ($inrow = sqlFetchArray($inres)) {
405 $charges += sprintf('%01.2f', $inrow['fee']);
406 receiptDetailLine($inrow['sale_date'], $inrow['name'],
407 $inrow['fee'], $inrow['quantity']);
409 // Service and tax items
410 $inres = sqlStatement("SELECT * FROM billing WHERE " .
411 "pid = ? AND encounter = ? AND " .
412 // "code_type != 'COPAY' AND activity = 1 AND fee != 0 " .
413 "code_type != 'COPAY' AND activity = 1 " .
414 "ORDER BY id", array($patient_id,$encounter) );
415 while ($inrow = sqlFetchArray($inres)) {
416 $charges += sprintf('%01.2f', $inrow['fee']);
417 receiptDetailLine($svcdate, $inrow['code_text'],
418 $inrow['fee'], $inrow['units']);
420 // Adjustments.
421 $inres = sqlStatement("SELECT " .
422 "a.code_type, a.code, a.modifier, a.memo, a.payer_type, a.adj_amount, a.pay_amount, " .
423 "s.payer_id, s.reference, s.check_date, s.deposit_date " .
424 "FROM ar_activity AS a " .
425 "LEFT JOIN ar_session AS s ON s.session_id = a.session_id WHERE " .
426 "a.pid = ? AND a.encounter = ? AND " .
427 "a.adj_amount != 0 " .
428 "ORDER BY s.check_date, a.sequence_no", array($patient_id,$encounter) );
429 while ($inrow = sqlFetchArray($inres)) {
430 $charges -= sprintf('%01.2f', $inrow['adj_amount']);
431 $payer = empty($inrow['payer_type']) ? 'Pt' : ('Ins' . $inrow['payer_type']);
432 receiptDetailLine($svcdate, $payer . ' ' . $inrow['memo'],
433 0 - $inrow['adj_amount'], 1);
437 <tr>
438 <td colspan='5'>&nbsp;</td>
439 </tr>
440 <tr>
441 <td><?php echo text(oeFormatShortDate($svcdispdate)); ?></td>
442 <td><b><?php echo xlt('Total Charges'); ?></b></td>
443 <td align='right'>&nbsp;</td>
444 <td align='right'>&nbsp;</td>
445 <td align='right'><?php echo text(oeFormatMoney($charges, true)) ?></td>
446 </tr>
447 <tr>
448 <td colspan='5'>&nbsp;</td>
449 </tr>
451 <?php
452 // Get co-pays.
453 $inres = sqlStatement("SELECT fee, code_text FROM billing WHERE " .
454 "pid = ? AND encounter = ? AND " .
455 "code_type = 'COPAY' AND activity = 1 AND fee != 0 " .
456 "ORDER BY id", array($patient_id,$encounter) );
457 while ($inrow = sqlFetchArray($inres)) {
458 $charges += sprintf('%01.2f', $inrow['fee']);
459 receiptPaymentLine($svcdate, 0 - $inrow['fee'], $inrow['code_text']);
461 // Get other payments.
462 $inres = sqlStatement("SELECT " .
463 "a.code_type, a.code, a.modifier, a.memo, a.payer_type, a.adj_amount, a.pay_amount, " .
464 "s.payer_id, s.reference, s.check_date, s.deposit_date " .
465 "FROM ar_activity AS a " .
466 "LEFT JOIN ar_session AS s ON s.session_id = a.session_id WHERE " .
467 "a.pid = ? AND a.encounter = ? AND " .
468 "a.pay_amount != 0 " .
469 "ORDER BY s.check_date, a.sequence_no", array($patient_id,$encounter) );
470 while ($inrow = sqlFetchArray($inres)) {
471 $payer = empty($inrow['payer_type']) ? 'Pt' : ('Ins' . $inrow['payer_type']);
472 $charges -= sprintf('%01.2f', $inrow['pay_amount']);
473 receiptPaymentLine($svcdate, $inrow['pay_amount'],
474 $payer . ' ' . $inrow['reference']);
477 <tr>
478 <td colspan='5'>&nbsp;</td>
479 </tr>
480 <tr>
481 <td>&nbsp;</td>
482 <td><b><?php echo xlt('Balance Due'); ?></b></td>
483 <td colspan='2'>&nbsp;</td>
484 <td align='right'><?php echo text(oeFormatMoney($charges, true)) ?></td>
485 </tr>
486 </table>
487 </center>
488 <div id='hideonprint'>
490 &nbsp;
491 <a href='#' id='printbutton'><?php echo xlt('Print'); ?></a>
492 <?php if (acl_check('acct','disc')) { ?>
493 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
494 <a href='#' onclick='return deleteme();'><?php echo xlt('Undo Checkout'); ?></a>
495 <?php } ?>
496 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
497 <?php if ($details) { ?>
498 <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>
499 <?php } else { ?>
500 <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>
501 <?php } ?>
502 </p>
503 </div>
504 </body>
505 </html>
506 <?php
507 } // end function generate_receipt()
509 // Function to output a line item for the input form.
511 $lino = 0;
512 function write_form_line($code_type, $code, $id, $date, $description,
513 $amount, $units, $taxrates) {
514 global $lino;
515 $amount = sprintf("%01.2f", $amount);
516 if (empty($units)) $units = 1;
517 $price = $amount / $units; // should be even cents, but ok here if not
518 if ($code_type == 'COPAY' && !$description) $description = xl('Payment');
519 echo " <tr>\n";
520 echo " <td>" . text(oeFormatShortDate($date));
521 echo "<input type='hidden' name='line[$lino][code_type]' value='" . attr($code_type) . "'>";
522 echo "<input type='hidden' name='line[$lino][code]' value='" . attr($code) . "'>";
523 echo "<input type='hidden' name='line[$lino][id]' value='" . attr($id) . "'>";
524 echo "<input type='hidden' name='line[$lino][description]' value='" . attr($description) . "'>";
525 echo "<input type='hidden' name='line[$lino][taxrates]' value='" . attr($taxrates) . "'>";
526 echo "<input type='hidden' name='line[$lino][price]' value='" . attr($price) . "'>";
527 echo "<input type='hidden' name='line[$lino][units]' value='" . attr($units) . "'>";
528 echo "</td>\n";
529 echo " <td>" . text($description) . "</td>";
530 echo " <td align='right'>" . text($units) . "</td>";
531 echo " <td align='right'><input type='text' name='line[$lino][amount]' " .
532 "value='" . attr($amount) . "' size='6' maxlength='8'";
533 // Modifying prices requires the acct/disc permission.
534 // if ($code_type == 'TAX' || ($code_type != 'COPAY' && !acl_check('acct','disc')))
535 echo " style='text-align:right;background-color:transparent' readonly";
536 // else echo " style='text-align:right' onkeyup='computeTotals()'";
537 echo "></td>\n";
538 echo " </tr>\n";
539 ++$lino;
542 // Create the taxes array. Key is tax id, value is
543 // (description, rate, accumulated total).
544 $taxes = array();
545 $pres = sqlStatement("SELECT option_id, title, option_value " .
546 "FROM list_options WHERE list_id = 'taxrate' ORDER BY seq");
547 while ($prow = sqlFetchArray($pres)) {
548 $taxes[$prow['option_id']] = array($prow['title'], $prow['option_value'], 0);
551 // Print receipt header for facility
552 function printFacilityHeader($frow){
553 echo "<p><b>" . text($frow['name']) .
554 "<br>" . text($frow['street']) .
555 "<br>" . text($frow['city']) . ', ' . text($frow['state']) . ' ' . text($frow['postal_code']) .
556 "<br>" . text($frow['phone']) .
557 "<br>&nbsp" .
558 "<br>";
561 // Pring receipt header for Provider
562 function printProviderHeader($pvdrow){
563 echo "<p><b>" . text($pvdrow['title']) . " " . text($pvdrow['fname']) . " " . text($pvdrow['mname']) . " " . text($pvdrow['lname']) . " " .
564 "<br>" . text($pvdrow['street']) .
565 "<br>" . text($pvdrow['city']) . ', ' . text($pvdrow['state']) . ' ' . text($pvdrow['postal_code']) .
566 "<br>" . text($pvdrow['phone']) .
567 "<br>&nbsp" .
568 "<br>";
571 // Mark the tax rates that are referenced in this invoice.
572 function markTaxes($taxrates) {
573 global $taxes;
574 $arates = explode(':', $taxrates);
575 if (empty($arates)) return;
576 foreach ($arates as $value) {
577 if (!empty($taxes[$value])) $taxes[$value][2] = '1';
581 $payment_methods = array(
582 'Cash',
583 'Check',
584 'MC',
585 'VISA',
586 'AMEX',
587 'DISC',
588 'Other');
590 $alertmsg = ''; // anything here pops up in an alert box
592 // If the Save button was clicked...
594 if ($_POST['form_save']) {
596 // On a save, do the following:
597 // Flag drug_sales and billing items as billed.
598 // Post the corresponding invoice with its payment(s) to sql-ledger
599 // and be careful to use a unique invoice number.
600 // Call the generate-receipt function.
601 // Exit.
603 $form_pid = $_POST['form_pid'];
604 $form_encounter = $_POST['form_encounter'];
606 // Get the posting date from the form as yyyy-mm-dd.
607 $dosdate = date("Y-m-d");
608 if (preg_match("/(\d\d\d\d)\D*(\d\d)\D*(\d\d)/", $_POST['form_date'], $matches)) {
609 $dosdate = $matches[1] . '-' . $matches[2] . '-' . $matches[3];
612 // If there is no associated encounter (i.e. this invoice has only
613 // prescriptions) then assign an encounter number of the service
614 // date, with an optional suffix to ensure that it's unique.
616 if (! $form_encounter) {
617 $form_encounter = substr($dosdate,0,4) . substr($dosdate,5,2) . substr($dosdate,8,2);
618 $tmp = '';
619 while (true) {
620 $ferow = sqlQuery("SELECT id FROM form_encounter WHERE " .
621 "pid = ? AND encounter = ?", array($form_pid, $form_encounter.$tmp) );
622 if (empty($ferow)) break;
623 $tmp = $tmp ? $tmp + 1 : 1;
625 $form_encounter .= $tmp;
628 // Delete any TAX rows from billing because they will be recalculated.
629 sqlStatement("UPDATE billing SET activity = 0 WHERE " .
630 "pid = ? AND encounter = ? AND " .
631 "code_type = 'TAX'", array($form_pid,$form_encounter) );
633 $form_amount = $_POST['form_amount'];
634 $lines = $_POST['line'];
636 for ($lino = 0; $lines[$lino]['code_type']; ++$lino) {
637 $line = $lines[$lino];
638 $code_type = $line['code_type'];
639 $id = $line['id'];
640 $amount = sprintf('%01.2f', trim($line['amount']));
643 if ($code_type == 'PROD') {
644 // Product sales. The fee and encounter ID may have changed.
645 $query = "update drug_sales SET fee = ?, " .
646 "encounter = ?, billed = 1 WHERE " .
647 "sale_id = ?";
648 sqlQuery($query, array($amount,$form_encounter,$id) );
650 else if ($code_type == 'TAX') {
651 // In the SL case taxes show up on the invoice as line items.
652 // Otherwise we gotta save them somewhere, and in the billing
653 // table with a code type of TAX seems easiest.
654 // They will have to be stripped back out when building this
655 // script's input form.
656 addBilling($form_encounter, 'TAX', 'TAX', 'Taxes', $form_pid, 0, 0,
657 '', '', $amount, '', '', 1);
659 else {
660 // Because there is no insurance here, there is no need for a claims
661 // table entry and so we do not call updateClaim(). Note we should not
662 // eliminate billed and bill_date from the billing table!
663 $query = "UPDATE billing SET fee = ?, billed = 1, " .
664 "bill_date = NOW() WHERE id = ?";
665 sqlQuery($query, array($amount,$id) );
669 // Post discount.
670 if ($_POST['form_discount']) {
671 if ($GLOBALS['discount_by_money']) {
672 $amount = sprintf('%01.2f', trim($_POST['form_discount']));
674 else {
675 $amount = sprintf('%01.2f', trim($_POST['form_discount']) * $form_amount / 100);
677 $memo = xl('Discount');
678 $time = date('Y-m-d H:i:s');
679 $query = "INSERT INTO ar_activity ( " .
680 "pid, encounter, code, modifier, payer_type, post_user, post_time, " .
681 "session_id, memo, adj_amount " .
682 ") VALUES ( " .
683 "?, " .
684 "?, " .
685 "'', " .
686 "'', " .
687 "'0', " .
688 "?, " .
689 "?, " .
690 "'0', " .
691 "?, " .
692 "? " .
693 ")";
694 sqlStatement($query, array($form_pid,$form_encounter,$_SESSION['authUserID'],$time,$memo,$amount) );
697 // Post payment.
698 if ($_POST['form_amount']) {
699 $amount = sprintf('%01.2f', trim($_POST['form_amount']));
700 $form_source = trim($_POST['form_source']);
701 $paydesc = trim($_POST['form_method']);
702 //Fetching the existing code and modifier
703 $ResultSearchNew = sqlStatement("SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key ".
704 "WHERE code_types.ct_fee=1 AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier",
705 array($form_pid,$form_encounter));
706 if($RowSearch = sqlFetchArray($ResultSearchNew))
708 $Codetype=$RowSearch['code_type'];
709 $Code=$RowSearch['code'];
710 $Modifier=$RowSearch['modifier'];
711 }else{
712 $Codetype='';
713 $Code='';
714 $Modifier='';
716 $session_id=idSqlStatement("INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total,".
717 " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) ".
718 " VALUES ('0',?,?,now(),?,?,'','patient','COPAY',?,?,'patient_payment',now())",
719 array($_SESSION['authId'],$form_source,$dosdate,$amount,$form_pid,$paydesc));
720 $insrt_id=idSqlStatement("INSERT INTO ar_activity (pid,encounter,code_type,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)".
721 " VALUES (?,?,?,?,?,0,?,?,?,?,'PCP')",
722 array($form_pid,$form_encounter,$Codetype,$Code,$Modifier,$dosdate,$_SESSION['authId'],$session_id,$amount));
725 // If applicable, set the invoice reference number.
726 $invoice_refno = '';
727 if (isset($_POST['form_irnumber'])) {
728 $invoice_refno = trim($_POST['form_irnumber']);
730 else {
731 $invoice_refno = updateInvoiceRefNumber();
733 if ($invoice_refno) {
734 sqlStatement("UPDATE form_encounter " .
735 "SET invoice_refno = ? " .
736 "WHERE pid = ? AND encounter = ?", array($invoice_refno,$form_pid,$form_encounter) );
739 generate_receipt($form_pid, $form_encounter);
740 exit();
743 // If an encounter ID was given, then we must generate a receipt.
745 if (!empty($_GET['enc'])) {
746 generate_receipt($patient_id, $_GET['enc']);
747 exit();
750 // Get the unbilled billing table items for this patient.
751 $query = "SELECT id, date, code_type, code, modifier, code_text, " .
752 "provider_id, payer_id, units, fee, encounter " .
753 "FROM billing WHERE pid = ? AND activity = 1 AND " .
754 "billed = 0 AND code_type != 'TAX' " .
755 "ORDER BY encounter DESC, id ASC";
756 $bres = sqlStatement($query, array($patient_id) );
758 // Get the product sales for this patient.
759 $query = "SELECT s.sale_id, s.sale_date, s.prescription_id, s.fee, " .
760 "s.quantity, s.encounter, s.drug_id, d.name, r.provider_id " .
761 "FROM drug_sales AS s " .
762 "LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " .
763 "LEFT OUTER JOIN prescriptions AS r ON r.id = s.prescription_id " .
764 "WHERE s.pid = ? AND s.billed = 0 " .
765 "ORDER BY s.encounter DESC, s.sale_id ASC";
766 $dres = sqlStatement($query, array($patient_id) );
768 // If there are none, just redisplay the last receipt and exit.
770 if (sqlNumRows($bres) == 0 && sqlNumRows($dres) == 0) {
771 generate_receipt($patient_id);
772 exit();
775 // Get the valid practitioners, including those not active.
776 $arr_users = array();
777 $ures = sqlStatement("SELECT id, username FROM users WHERE " .
778 "( authorized = 1 OR info LIKE '%provider%' ) AND username != ''");
779 while ($urow = sqlFetchArray($ures)) {
780 $arr_users[$urow['id']] = '1';
783 // Now write a data entry form:
784 // List unbilled billing items (cpt, hcpcs, copays) for the patient.
785 // List unbilled product sales for the patient.
786 // Present an editable dollar amount for each line item, a total
787 // which is also the default value of the input payment amount,
788 // and OK and Cancel buttons.
790 <html>
791 <head>
792 <link rel='stylesheet' href='<?php echo $css_header ?>' type='text/css'>
793 <title><?php echo xlt('Patient Checkout'); ?></title>
794 <style>
795 </style>
796 <style type="text/css">@import url(../../library/dynarch_calendar.css);</style>
797 <script type="text/javascript" src="../../library/textformat.js"></script>
798 <script type="text/javascript" src="../../library/dynarch_calendar.js"></script>
799 <?php include_once("{$GLOBALS['srcdir']}/dynarch_calendar_en.inc.php"); ?>
800 <script type="text/javascript" src="../../library/dynarch_calendar_setup.js"></script>
801 <script type="text/javascript" src="../../library/dialog.js"></script>
802 <script type="text/javascript" src="../../library/js/jquery-1.2.2.min.js"></script>
803 <script language="JavaScript">
804 var mypcc = '<?php echo $GLOBALS['phone_country_code'] ?>';
806 <?php require($GLOBALS['srcdir'] . "/restoreSession.php"); ?>
808 // This clears the tax line items in preparation for recomputing taxes.
809 function clearTax(visible) {
810 var f = document.forms[0];
811 for (var lino = 0; true; ++lino) {
812 var pfx = 'line[' + lino + ']';
813 if (! f[pfx + '[code_type]']) break;
814 if (f[pfx + '[code_type]'].value != 'TAX') continue;
815 f[pfx + '[price]'].value = '0.00';
816 if (visible) f[pfx + '[amount]'].value = '0.00';
820 // For a given tax ID and amount, compute the tax on that amount and add it
821 // to the "price" (same as "amount") of the corresponding tax line item.
822 // Note the tax line items include their "taxrate" to make this easy.
823 function addTax(rateid, amount, visible) {
824 if (rateid.length == 0) return 0;
825 var f = document.forms[0];
826 for (var lino = 0; true; ++lino) {
827 var pfx = 'line[' + lino + ']';
828 if (! f[pfx + '[code_type]']) break;
829 if (f[pfx + '[code_type]'].value != 'TAX') continue;
830 if (f[pfx + '[code]'].value != rateid) continue;
831 var tax = amount * parseFloat(f[pfx + '[taxrates]'].value);
832 tax = parseFloat(tax.toFixed(<?php echo $currdecimals ?>));
833 var cumtax = parseFloat(f[pfx + '[price]'].value) + tax;
834 f[pfx + '[price]'].value = cumtax.toFixed(<?php echo $currdecimals ?>); // requires JS 1.5
835 if (visible) f[pfx + '[amount]'].value = cumtax.toFixed(<?php echo $currdecimals ?>); // requires JS 1.5
836 if (isNaN(tax)) alert('Tax rate not numeric at line ' + lino);
837 return tax;
839 return 0;
842 // This mess recomputes the invoice total and optionally applies a discount.
843 function computeDiscountedTotals(discount, visible) {
844 clearTax(visible);
845 var f = document.forms[0];
846 var total = 0.00;
847 for (var lino = 0; f['line[' + lino + '][code_type]']; ++lino) {
848 var code_type = f['line[' + lino + '][code_type]'].value;
849 // price is price per unit when the form was originally generated.
850 // By contrast, amount is the dynamically-generated discounted line total.
851 var price = parseFloat(f['line[' + lino + '][price]'].value);
852 if (isNaN(price)) alert('Price not numeric at line ' + lino);
853 if (code_type == 'COPAY' || code_type == 'TAX') {
854 // This works because the tax lines come last.
855 total += parseFloat(price.toFixed(<?php echo $currdecimals ?>));
856 continue;
858 var units = f['line[' + lino + '][units]'].value;
859 var amount = price * units;
860 amount = parseFloat(amount.toFixed(<?php echo $currdecimals ?>));
861 if (visible) f['line[' + lino + '][amount]'].value = amount.toFixed(<?php echo $currdecimals ?>);
862 total += amount;
863 var taxrates = f['line[' + lino + '][taxrates]'].value;
864 var taxids = taxrates.split(':');
865 for (var j = 0; j < taxids.length; ++j) {
866 addTax(taxids[j], amount, visible);
869 return total - discount;
872 // Recompute displayed amounts with any discount applied.
873 function computeTotals() {
874 var f = document.forms[0];
875 var discount = parseFloat(f.form_discount.value);
876 if (isNaN(discount)) discount = 0;
877 <?php if (!$GLOBALS['discount_by_money']) { ?>
878 // This site discounts by percentage, so convert it to a money amount.
879 if (discount > 100) discount = 100;
880 if (discount < 0 ) discount = 0;
881 discount = 0.01 * discount * computeDiscountedTotals(0, false);
882 <?php } ?>
883 var total = computeDiscountedTotals(discount, true);
884 f.form_amount.value = total.toFixed(<?php echo $currdecimals ?>);
885 return true;
888 </script>
889 </head>
891 <body class="body_top">
893 <form method='post' action='pos_checkout.php'>
894 <input type='hidden' name='form_pid' value='<?php echo attr($patient_id) ?>' />
896 <center>
899 <table cellspacing='5'>
900 <tr>
901 <td colspan='3' align='center'>
902 <b><?php echo xlt('Patient Checkout for '); ?><?php echo text($patdata['fname']) . " " .
903 text($patdata['lname']) . " (" . text($patdata['pubpid']) . ")" ?></b>
904 </td>
905 </tr>
906 <tr>
907 <td><b><?php echo xlt('Date'); ?></b></td>
908 <td><b><?php echo xlt('Description'); ?></b></td>
909 <td align='right'><b><?php echo xlt('Qty'); ?></b></td>
910 <td align='right'><b><?php echo xlt('Amount'); ?></b></td>
911 </tr>
912 <?php
913 $inv_encounter = '';
914 $inv_date = '';
915 $inv_provider = 0;
916 $inv_payer = 0;
917 $gcac_related_visit = false;
918 $gcac_service_provided = false;
920 // Process billing table items.
921 // Items that are not allowed to have a fee are skipped.
923 while ($brow = sqlFetchArray($bres)) {
924 // Skip all but the most recent encounter.
925 if ($inv_encounter && $brow['encounter'] != $inv_encounter) continue;
927 $thisdate = substr($brow['date'], 0, 10);
928 $code_type = $brow['code_type'];
930 // Collect tax rates, related code and provider ID.
931 $taxrates = '';
932 $related_code = '';
933 $sqlBindArray = array();
934 if (!empty($code_types[$code_type]['fee'])) {
935 $query = "SELECT taxrates, related_code FROM codes WHERE code_type = ? " .
936 " AND " .
937 "code = ? AND ";
938 array_push($sqlBindArray,$code_types[$code_type]['id'],$brow['code']);
939 if ($brow['modifier']) {
940 $query .= "modifier = ?";
941 array_push($sqlBindArray,$brow['modifier']);
942 } else {
943 $query .= "(modifier IS NULL OR modifier = '')";
945 $query .= " LIMIT 1";
946 $tmp = sqlQuery($query,$sqlBindArray);
947 $taxrates = $tmp['taxrates'];
948 $related_code = $tmp['related_code'];
949 markTaxes($taxrates);
952 write_form_line($code_type, $brow['code'], $brow['id'], $thisdate,
953 $brow['code_text'], $brow['fee'], $brow['units'],
954 $taxrates);
955 if (!$inv_encounter) $inv_encounter = $brow['encounter'];
956 $inv_payer = $brow['payer_id'];
957 if (!$inv_date || $inv_date < $thisdate) $inv_date = $thisdate;
959 // Custom logic for IPPF to determine if a GCAC issue applies.
960 if ($GLOBALS['ippf_specific'] && $related_code) {
961 $relcodes = explode(';', $related_code);
962 foreach ($relcodes as $codestring) {
963 if ($codestring === '') continue;
964 list($codetype, $code) = explode(':', $codestring);
965 if ($codetype !== 'IPPF') continue;
966 if (preg_match('/^25222/', $code)) {
967 $gcac_related_visit = true;
968 if (preg_match('/^25222[34]/', $code))
969 $gcac_service_provided = true;
975 // Process copays
977 $totalCopay = getPatientCopay($patient_id,$encounter);
978 if ($totalCopay < 0) {
979 write_form_line("COPAY", "", "", "", "", $totalCopay, "", "");
982 // Process drug sales / products.
984 while ($drow = sqlFetchArray($dres)) {
985 if ($inv_encounter && $drow['encounter'] && $drow['encounter'] != $inv_encounter) continue;
987 $thisdate = $drow['sale_date'];
988 if (!$inv_encounter) $inv_encounter = $drow['encounter'];
990 if (!$inv_provider && !empty($arr_users[$drow['provider_id']]))
991 $inv_provider = $drow['provider_id'] + 0;
993 if (!$inv_date || $inv_date < $thisdate) $inv_date = $thisdate;
995 // Accumulate taxes for this product.
996 $tmp = sqlQuery("SELECT taxrates FROM drug_templates WHERE drug_id = ? " .
997 " ORDER BY selector LIMIT 1", array($drow['drug_id']) );
998 // accumTaxes($drow['fee'], $tmp['taxrates']);
999 $taxrates = $tmp['taxrates'];
1000 markTaxes($taxrates);
1002 write_form_line('PROD', $drow['drug_id'], $drow['sale_id'],
1003 $thisdate, $drow['name'], $drow['fee'], $drow['quantity'], $taxrates);
1006 // Write a form line for each tax that has money, adding to $total.
1007 foreach ($taxes as $key => $value) {
1008 if ($value[2]) {
1009 write_form_line('TAX', $key, $key, date('Y-m-d'), $value[0], 0, 1, $value[1]);
1013 // Besides copays, do not collect any other information from ar_activity,
1014 // since this is for appt checkout.
1016 if ($inv_encounter) {
1017 $erow = sqlQuery("SELECT provider_id FROM form_encounter WHERE " .
1018 "pid = ? AND encounter = ? " .
1019 "ORDER BY id DESC LIMIT 1", array($patient_id,$inv_encounter) );
1020 $inv_provider = $erow['provider_id'] + 0;
1023 </table>
1026 <table border='0' cellspacing='4'>
1028 <tr>
1029 <td>
1030 <?php echo $GLOBALS['discount_by_money'] ? xlt('Discount Amount') : xlt('Discount Percentage'); ?>:
1031 </td>
1032 <td>
1033 <input type='text' name='form_discount' size='6' maxlength='8' value=''
1034 style='text-align:right' onkeyup='computeTotals()'>
1035 </td>
1036 </tr>
1038 <tr>
1039 <td>
1040 <?php echo xlt('Payment Method'); ?>:
1041 </td>
1042 <td>
1043 <select name='form_method'>
1044 <?php
1045 $query1112 = "SELECT * FROM list_options where list_id=? ORDER BY seq, title ";
1046 $bres1112 = sqlStatement($query1112,array('payment_method'));
1047 while ($brow1112 = sqlFetchArray($bres1112))
1049 if($brow1112['option_id']=='electronic' || $brow1112['option_id']=='bank_draft')
1050 continue;
1051 echo "<option value='".attr($brow1112['option_id'])."'>".text(xl_list_label($brow1112['title']))."</option>";
1054 </select>
1055 </td>
1056 </tr>
1058 <tr>
1059 <td>
1060 <?php echo xlt('Check/Reference Number'); ?>:
1061 </td>
1062 <td>
1063 <input type='text' name='form_source' size='10' value=''>
1064 </td>
1065 </tr>
1067 <tr>
1068 <td>
1069 <?php echo xlt('Amount Paid'); ?>:
1070 </td>
1071 <td>
1072 <input type='text' name='form_amount' size='10' value='0.00'>
1073 </td>
1074 </tr>
1076 <tr>
1077 <td>
1078 <?php echo xlt('Posting Date'); ?>:
1079 </td>
1080 <td>
1081 <input type='text' size='10' name='form_date' id='form_date'
1082 value='<?php echo attr($inv_date) ?>'
1083 title='yyyy-mm-dd date of service'
1084 onkeyup='datekeyup(this,mypcc)' onblur='dateblur(this,mypcc)' />
1085 <img src='../pic/show_calendar.gif' align='absbottom' width='24' height='22'
1086 id='img_date' border='0' alt='[?]' style='cursor:pointer'
1087 title='<?php echo xla("Click here to choose a date"); ?>'>
1088 </td>
1089 </tr>
1091 <?php
1092 // If this user has a non-empty irnpool assigned, show the pending
1093 // invoice reference number.
1094 $irnumber = getInvoiceRefNumber();
1095 if (!empty($irnumber)) {
1097 <tr>
1098 <td>
1099 <?php echo xlt('Tentative Invoice Ref No'); ?>:
1100 </td>
1101 <td>
1102 <?php echo text($irnumber); ?>
1103 </td>
1104 </tr>
1105 <?php
1107 // Otherwise if there is an invoice reference number mask, ask for the refno.
1108 else if (!empty($GLOBALS['gbl_mask_invoice_number'])) {
1110 <tr>
1111 <td>
1112 <?php echo xlt('Invoice Reference Number'); ?>:
1113 </td>
1114 <td>
1115 <input type='text' name='form_irnumber' size='10' value=''
1116 onkeyup='maskkeyup(this,"<?php echo addslashes($GLOBALS['gbl_mask_invoice_number']); ?>")'
1117 onblur='maskblur(this,"<?php echo addslashes($GLOBALS['gbl_mask_invoice_number']); ?>")'
1119 </td>
1120 </tr>
1121 <?php
1125 <tr>
1126 <td colspan='2' align='center'>
1127 &nbsp;<br>
1128 <input type='submit' name='form_save' value='<?php echo xla('Save'); ?>' /> &nbsp;
1129 <?php if (empty($_GET['framed'])) { ?>
1130 <input type='button' value='<?php echo xla('Cancel'); ?>' onclick='window.close()' />
1131 <?php } ?>
1132 <input type='hidden' name='form_provider' value='<?php echo attr($inv_provider) ?>' />
1133 <input type='hidden' name='form_payer' value='<?php echo attr($inv_payer) ?>' />
1134 <input type='hidden' name='form_encounter' value='<?php echo attr($inv_encounter) ?>' />
1135 </td>
1136 </tr>
1138 </table>
1139 </center>
1141 </form>
1143 <script language='JavaScript'>
1144 Calendar.setup({inputField:"form_date", ifFormat:"%Y-%m-%d", button:"img_date"});
1145 computeTotals();
1146 <?php
1147 // The following is removed, perhaps temporarily, because gcac reporting
1148 // no longer depends on gcac issues. -- Rod 2009-08-11
1149 /*********************************************************************
1150 // Custom code for IPPF. Try to make sure that a GCAC issue is linked to this
1151 // visit if it contains GCAC-related services.
1152 if ($gcac_related_visit) {
1153 $grow = sqlQuery("SELECT l.id, l.title, l.begdate, ie.pid " .
1154 "FROM lists AS l " .
1155 "LEFT JOIN issue_encounter AS ie ON ie.pid = l.pid AND " .
1156 "ie.encounter = '$inv_encounter' AND ie.list_id = l.id " .
1157 "WHERE l.pid = '$pid' AND " .
1158 "l.activity = 1 AND l.type = 'ippf_gcac' " .
1159 "ORDER BY ie.pid DESC, l.begdate DESC LIMIT 1");
1160 // Note that reverse-ordering by ie.pid is a trick for sorting
1161 // issues linked to the encounter (non-null values) first.
1162 if (empty($grow['pid'])) { // if there is no linked GCAC issue
1163 if (!empty($grow)) { // there is one that is not linked
1164 echo " if (confirm('" . xl('OK to link the GCAC issue dated') . " " .
1165 $grow['begdate'] . " " . xl('to this visit?') . "')) {\n";
1166 echo " $.getScript('link_issue_to_encounter.php?issue=" . $grow['id'] .
1167 "&thisenc=$inv_encounter');\n";
1168 echo " } else";
1170 echo " if (confirm('" . xl('Are you prepared to complete a new GCAC issue for this visit?') . "')) {\n";
1171 echo " dlgopen('summary/add_edit_issue.php?thisenc=$inv_encounter" .
1172 "&thistype=ippf_gcac', '_blank', 700, 600);\n";
1173 echo " } else {\n";
1174 echo " $.getScript('link_issue_to_encounter.php?thisenc=$inv_encounter');\n";
1175 echo " }\n";
1177 } // end if ($gcac_related_visit)
1178 *********************************************************************/
1180 if ($gcac_related_visit && !$gcac_service_provided) {
1181 // Skip this warning if the GCAC visit form is not allowed.
1182 $grow = sqlQuery("SELECT COUNT(*) AS count FROM list_options " .
1183 "WHERE list_id = 'lbfnames' AND option_id = 'LBFgcac'");
1184 if (!empty($grow['count'])) { // if gcac is used
1185 // Skip this warning if referral or abortion in TS.
1186 $grow = sqlQuery("SELECT COUNT(*) AS count FROM transactions " .
1187 "WHERE title = 'Referral' AND refer_date IS NOT NULL AND " .
1188 "refer_date = ? AND pid = ?", array($inv_date,$patient_id) );
1189 if (empty($grow['count'])) { // if there is no referral
1190 $grow = sqlQuery("SELECT COUNT(*) AS count FROM forms " .
1191 "WHERE pid = ? AND encounter = ? AND " .
1192 "deleted = 0 AND formdir = 'LBFgcac'", array($patient_id,$inv_encounter) );
1193 if (empty($grow['count'])) { // if there is no gcac form
1194 echo " alert('" . addslashes(xl('This visit will need a GCAC form, referral or procedure service.')) . "');\n";
1198 } // end if ($gcac_related_visit)
1200 </script>
1202 </body>
1203 </html>