tentative completion of in-house drugs and POS checkout
[openemr.git] / interface / patient_file / pos_checkout.php
blobd283f920a8d00a50bfc7ed6ac5a320fbe58464d0
1 <?php
2 // Copyright (C) 2006 Rod Roark <rod@sunsetsystems.com>
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License
6 // as published by the Free Software Foundation; either version 2
7 // of the License, or (at your option) any later version.
9 // This module supports a popup window to handle patient checkout
10 // as a point-of-sale transaction. Support for in-house drug sales
11 // is included.
13 // Important notes about system design:
15 // (1) Drug sales may or may not be associated with an encounter;
16 // they are if they are paid for concurrently with an encounter.
17 // (2) Drug sales without an encounter will have 20YYMMDD, possibly
18 // with a suffix, as the encounter-number portion of their invoice
19 // number.
20 // (3) Payments are saved in SL only, don't mess with the billing table.
21 // See library/classes/WSClaim.class.php for posting code.
22 // (4) On checkout, the billing table entries are marked as billed and
23 // so become unavailable for further billing.
24 // (5) On checkout, drug_sales entries are marked as billed by having
25 // an invoice number assigned.
26 // (6) Receipt printing must be a separate operation from payment,
27 // and repeatable, therefore driven from the SL database and
28 // mirroring the contents of the invoice.
30 require_once("../globals.php");
31 require_once("$srcdir/patient.inc");
32 require_once("$srcdir/sql-ledger.inc");
33 require_once("$srcdir/freeb/xmlrpc.inc");
34 require_once("$srcdir/freeb/xmlrpcs.inc");
36 // Get the patient's name and chart number.
37 $patdata = getPatientData($pid, 'fname,mname,lname,pubpid,street,city,state,postal_code');
39 //////////////////////////////////////////////////////////////////////
40 // The following functions are inline here temporarily, and should be
41 // moved to an includable module for common use. In particular
42 // WSClaim.class.php should be rewritten to use them.
43 //////////////////////////////////////////////////////////////////////
45 // Initialize the array of invoice information for posting to the
46 // accounting system.
48 function invoice_initialize(& $invoice_info, $patient_id, $provider_id,
49 $payer_id = 0, $encounter = 0)
51 $db = $GLOBALS['adodb']['db'];
53 // Get foreign ID (customer) for patient.
54 $sql = "SELECT foreign_id from integration_mapping as im " .
55 "LEFT JOIN patient_data as pd on im.local_id=pd.id " .
56 "where pd.pid = '" .
57 $patient_id .
58 "' and im.local_table='patient_data' and im.foreign_table='customer'";
59 $result = $db->Execute($sql);
60 if($result && !$result->EOF) {
61 $foreign_patient_id = $result->fields['foreign_id'];
63 else {
64 return "Patient '" . $patient_id . "' has not yet been posted to the accounting system.";
67 // Get foreign ID (salesman) for provider.
68 $sql = "SELECT foreign_id from integration_mapping WHERE " .
69 "local_id = $provider_id AND local_table='users' and foreign_table='salesman'";
70 $result = $db->Execute($sql);
71 if($result && !$result->EOF) {
72 $foreign_provider_id = $result->fields['foreign_id'];
74 else {
75 return "Provider '" . $provider_id . "' has not yet been posted to the accounting system.";
78 // Get foreign ID (customer) for insurance payer.
79 if ($payer_id && ! $GLOBALS['insurance_companies_are_not_customers']) {
80 $sql = "SELECT foreign_id from integration_mapping WHERE " .
81 "local_id = $payer_id AND local_table = 'insurance_companies' AND foreign_table='customer'";
82 $result = $db->Execute($sql);
83 if($result && !$result->EOF) {
84 $foreign_payer_id = $result->fields['foreign_id'];
86 else {
87 return "Payer '" . $payer_id . "' has not yet been posted to the accounting system.";
89 } else {
90 $foreign_payer_id = $payer_id;
93 // Create invoice notes for the new invoice that list the patient's
94 // insurance plans. This is so that when payments are posted, the user
95 // can easily see if a secondary claim needs to be submitted.
97 $insnotes = "";
98 $insno = 0;
99 foreach (array("primary", "secondary", "tertiary") as $instype) {
100 ++$insno;
101 $sql = "SELECT insurance_companies.name " .
102 "FROM insurance_data, insurance_companies WHERE " .
103 "insurance_data.pid = $patient_id AND " .
104 "insurance_data.type = '$instype' AND " .
105 "insurance_companies.id = insurance_data.provider " .
106 "LIMIT 1";
107 $result = $db->Execute($sql);
108 if ($result && !$result->EOF && $result->fields['name']) {
109 if ($insnotes) $insnotes .= "\n";
110 $insnotes .= "Ins$insno: " . $result->fields['name'];
113 $invoice_info['notes'] = $insnotes;
115 $invoice_info['salesman'] = $foreign_provider_id;
116 $invoice_info['customerid'] = $foreign_patient_id;
117 $invoice_info['payer_id'] = $foreign_payer_id;
118 $invoice_info['invoicenumber'] = $patient_id . "." . $encounter;
119 $invoice_info['dosdate'] = date("m-d-Y");
120 $invoice_info['items'] = array();
121 $invoice_info['total'] = '0.00';
123 return '';
126 function invoice_add_line_item(& $invoice_info, $code_type, $code,
127 $code_text, $amount)
129 $tii = array();
130 $tii['maincode'] = $code;
131 $tii['itemtext'] = "$code_type:$code $code_text";
132 $tii['qty'] = 1;
133 $tii['price'] = sprintf("%01.2f", $amount);
134 $tii['glaccountid'] = $GLOBALS['oer_config']['ws_accounting']['income_acct'];
135 $invoice_info['total'] = sprintf("%01.2f", $invoice_info['total'] + $tii['price']);
136 $invoice_info['items'][] = $tii;
137 return '';
140 function invoice_post(& $invoice_info)
142 $function['ezybiz.add_invoice'] = array(new xmlrpcval($invoice_info, "struct"));
144 list($name, $var) = each($function);
145 $f = new xmlrpcmsg($name, $var);
147 $c = new xmlrpc_client($GLOBALS['oer_config']['ws_accounting']['url'],
148 $GLOBALS['oer_config']['ws_accounting']['server'],
149 $GLOBALS['oer_config']['ws_accounting']['port']);
151 $c->setCredentials($GLOBALS['oer_config']['ws_accounting']['username'],
152 $GLOBALS['oer_config']['ws_accounting']['password']);
154 $r = $c->send($f);
155 if (!$r) return "XMLRPC send failed";
157 // We are not doing anything with the return value yet... should we?
158 $tv = $r->value();
159 if (is_object($tv)) {
160 $value = $tv->getval();
162 else {
163 $value = null;
166 if ($r->faultCode()) {
167 return "Fault: Code: " . $r->faultCode() . " Reason '" . $r->faultString() . "'";
170 return '';
173 /////////////////// End of invoice posting functions /////////////////
175 // Generate a receipt from the last-billed invoice for this patient.
177 function generate_receipt($patient_id) {
178 global $sl_err, $sl_cash_acc, $css_header;
180 // Get details for what we guess is the primary facility.
181 $frow = sqlQuery("SELECT * FROM facility " .
182 "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
184 $patdata = getPatientData($patient_id, 'fname,mname,lname,pubpid,street,city,state,postal_code');
186 SLConnect();
188 // Get the most recent invoice data into $arrow.
190 $arres = SLQuery("SELECT * FROM ar WHERE " .
191 "invnumber LIKE '$patient_id.%' " .
192 "ORDER BY id DESC LIMIT 1");
193 if ($sl_err) die($sl_err);
194 $arrow = SLGetRow($arres, 0);
195 if (! $arrow) die(xl("This patient has no activity."));
197 $trans_id = $arrow['id'];
199 // Determine the date of service. An 8-digit encounter number is
200 // presumed to be a date of service imported during conversion or
201 // associated with prescriptions only. Otherwise look it up in the
202 // form_encounter table.
204 $svcdate = "";
205 list($trash, $encounter) = explode(".", $arrow['invnumber']);
206 if (strlen($encounter) >= 8) {
207 $svcdate = substr($encounter, 0, 4) . "-" . substr($encounter, 4, 2) .
208 "-" . substr($encounter, 6, 2);
210 else if ($encounter) {
211 $tmp = sqlQuery("SELECT date FROM form_encounter WHERE " .
212 "encounter = $encounter");
213 $svcdate = substr($tmp['date'], 0, 10);
216 <html>
217 <head>
218 <link rel='stylesheet' href='<?php echo $css_header ?>' type='text/css'>
219 <title><? xl('Receipt for Payment','e'); ?></title>
220 </head>
221 <body <?echo $top_bg_line;?> leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>
222 <center>
223 <p><b><?php echo $frow['name'] ?>
224 <br><?php echo $frow['street'] ?>
225 <br><?php echo $frow['city'] . ', ' . $frow['state'] . ' ' . $frow['postal_code'] ?>
226 <br><?php echo $frow['phone'] ?>
227 <br>&nbsp;
228 <br><?php echo date('F j, Y') ?>
229 <br>&nbsp;
230 </b></p>
231 </center>
233 <?php echo $patdata['fname'] . ' ' . $patdata['mname'] . ' ' . $patdata['lname'] ?>
234 <br><?php echo $patdata['street'] ?>
235 <br><?php echo $patdata['city'] . ', ' . $patdata['state'] . ' ' . $patdata['postal_code'] ?>
236 <br>&nbsp;
237 </p>
238 <center>
239 <table>
240 <tr>
241 <td><b>Date</b></td>
242 <td><b>Description</b></td>
243 <td align='right'><b>Amount</b></td>
244 </tr>
245 <?php
246 $charges = 0.00;
248 // Request all line items with money belonging to the invoice.
249 $inres = SLQuery("select * from invoice where trans_id = $trans_id and sellprice != 0");
250 if ($sl_err) die($sl_err);
252 for ($irow = 0; $irow < SLRowCount($inres); ++$irow) {
253 $row = SLGetRow($inres, $irow);
254 $amount = sprintf('%01.2f', $row['sellprice']);
255 $charges += $amount;
256 echo " <tr>\n";
257 echo " <td>$svcdate</td>\n";
258 echo " <td>" . $row['description'] . "</td>\n";
259 echo " <td align='right'>$amount</td>\n";
260 echo " </tr>\n";
263 $chart_id_cash = SLQueryValue("select id from chart where accno = '$sl_cash_acc'");
264 if ($sl_err) die($sl_err);
265 if (! $chart_id_cash) die("There is no COA entry for cash account '$sl_cash_acc'");
267 // Request all cash entries belonging to the invoice.
268 $atres = SLQuery("select * from acc_trans where trans_id = $trans_id and chart_id = $chart_id_cash");
269 if ($sl_err) die($sl_err);
271 for ($irow = 0; $irow < SLRowCount($atres); ++$irow) {
272 $row = SLGetRow($atres, $irow);
273 $amount = sprintf('%01.2f', $row['amount']); // negative
274 $charges += $amount;
275 echo " <tr>\n";
276 echo " <td>" . $row['transdate'] . "</td>\n";
277 echo " <td>Payment " . $row['source'] . "</td>\n";
278 echo " <td align='right'>$amount</td>\n";
279 echo " </tr>\n";
282 <tr>
283 <td colspan='3'>&nbsp;</td>
284 </tr>
285 <tr>
286 <td>&nbsp;</td>
287 <td><b>Balance Due</b></td>
288 <td align='right'><?php echo sprintf('%01.2f', $charges) ?></td>
289 </tr>
290 </table>
291 </center>
292 <p>&nbsp;<a href='' onclick='window.print(); return false;'>Print</a></p>
293 </body>
294 </html>
295 <?php
296 SLClose();
297 } // end function
299 // Function to output a line item for the input form.
301 $lino = 0;
302 function write_form_line($code_type, $code, $id, $date, $description, $amount) {
303 global $lino;
304 $amount = sprintf("%01.2f", $amount);
305 echo " <tr>\n";
306 echo " <td>$date";
307 echo "<input type='hidden' name='line[$lino][code_type]' value='$code_type'>";
308 echo "<input type='hidden' name='line[$lino][code]' value='$code'>";
309 echo "<input type='hidden' name='line[$lino][id]' value='$id'>";
310 echo "<input type='hidden' name='line[$lino][description]' value='$description'>";
311 echo "</td>\n";
312 echo " <td>$description</td>";
313 echo " <td align='right'><input type='text' name='line[$lino][amount]' " .
314 "value='$amount' size='6' maxlength='8' style='text-align:right'></td>\n";
315 echo " </tr>\n";
316 ++$lino;
319 $payment_methods = array(
320 'Cash',
321 'Check',
322 'MC',
323 'VISA',
324 'AMEX',
325 'DISC',
326 'Other');
328 $alertmsg = ''; // anything here pops up in an alert box
330 // If the Save button was clicked...
332 if ($_POST['form_save']) {
334 // On a save, do the following:
335 // Flag drug_sales and billing items as billed.
336 // Post the corresponding invoice with its payment(s) to sql-ledger
337 // and be careful to use a unique invoice number.
338 // Call the generate-receipt function.
339 // Exit.
341 $form_pid = $_POST['form_pid'];
342 $form_encounter = $_POST['form_encounter'];
344 // If there is no associated encounter (i.e. this invoice has only
345 // prescriptions) then assign an encounter number of the current
346 // date, with an optional suffix to ensure that it's unique.
348 if (! $form_encounter) {
349 SLConnect();
350 $form_encounter = date('Ymd');
351 $tmp = '';
352 while (SLQueryValue("select id from ar where " .
353 "invnumber = '$form_pid.$form_encounter$tmp'")) {
354 $tmp = $tmp ? $tmp + 1 : 1;
356 $form_encounter .= $tmp;
357 SLClose();
360 // Initialize an array of invoice information for posting.
362 $invoice_info = array();
363 $msg = invoice_initialize($invoice_info, $_POST['form_pid'],
364 $_POST['form_provider'], $_POST['form_payer'], $form_encounter);
365 if ($msg) die($msg);
367 $form_amount = $_POST['form_amount'];
368 $lines = $_POST['line'];
370 for ($lino = 0; $lines[$lino]['code_type']; ++$lino) {
371 $line = $lines[$lino];
373 $code_type = $line['code_type'];
374 $id = $line['id'];
375 $amount = sprintf('%01.2f', trim($line['amount']));
377 $msg = invoice_add_line_item($invoice_info, $code_type,
378 $line['code'], $line['description'], $amount);
379 if ($msg) die($msg);
381 if ($code_type == 'MED') {
382 $query = "update drug_sales SET fee = '$amount', " .
383 "encounter = '$form_encounter' WHERE " .
384 "sale_id = '$id'";
386 else {
387 $query = "UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
388 "id = '$id'";
390 sqlQuery($query);
391 // echo $query . "<br>\n"; // debugging
394 if ($_POST['form_amount']) {
395 $paydesc = 'Received at time of visit';
396 if ($_POST['form_source']) $paydesc .= ' (' . $_POST['form_source'] . ')';
397 $msg = invoice_add_line_item($invoice_info, 'COPAY',
398 $_POST['form_method'],
399 $paydesc,
400 $_POST['form_amount']);
401 if ($msg) die($msg);
404 $msg = invoice_post($invoice_info);
405 if ($msg) die($msg);
407 generate_receipt($_POST['form_pid']);
408 exit();
411 // Get the unbilled billing table items and prescription sales for
412 // this patient.
414 $query = "SELECT id, date, code_type, code, code_text, " .
415 "provider_id, payer_id, fee, encounter " .
416 "FROM billing " .
417 "WHERE pid = '$pid' AND activity = 1 AND billed = 0 " .
418 "ORDER BY encounter";
419 $bres = sqlStatement($query);
421 $query = "SELECT s.sale_id, s.sale_date, s.prescription_id, s.fee, " .
422 "d.name, r.provider_id " .
423 "FROM drug_sales AS s " .
424 "LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " .
425 "LEFT JOIN prescriptions AS r ON r.id = s.prescription_id " .
426 "WHERE s.pid = '$pid' AND s.encounter = 0 " .
427 "ORDER BY s.sale_id";
428 $dres = sqlStatement($query);
430 // If there are none, just redisplay the last receipt and exit.
432 if (mysql_num_rows($bres) == 0 && mysql_num_rows($dres) == 0) {
433 generate_receipt($pid);
434 exit();
437 // Now write a data entry form:
438 // List unbilled billing items (cpt, hcpcs, copays) for the patient.
439 // List unbilled prescription sales for the patient.
440 // Present an editable dollar amount for each line item, a total
441 // which is also the default value of the input payment amount,
442 // and OK and Cancel buttons.
444 <html>
445 <head>
446 <link rel='stylesheet' href='<?php echo $css_header ?>' type='text/css'>
447 <title><? xl('Patient Checkout','e'); ?></title>
448 <style>
449 </style>
450 <script language="JavaScript">
451 </script>
452 </head>
454 <body <?echo $top_bg_line;?> leftmargin='0' topmargin='0' marginwidth='0'
455 marginheight='0'>
457 <form method='post' action='pos_checkout.php'>
458 <input type='hidden' name='form_pid' value='<?php echo $pid ?>' />
460 <center>
463 <table cellspacing='5'>
464 <tr>
465 <td colspan='3' align='center'>
466 <b><? xl('Patient Checkout for ','e'); ?><?php echo $patdata['fname'] . " " .
467 $patdata['lname'] . " (" . $patdata['pubpid'] . ")" ?></b>
468 </td>
469 </tr>
470 <tr>
471 <td><b>Date</b></td>
472 <td><b>Description</b></td>
473 <td align='right'><b>Amount</b>&nbsp;</td>
474 </tr>
475 <?php
476 $inv_encounter = '';
477 $inv_provider = 0;
478 $inv_payer = 0;
479 $total = 0.00;
480 while ($brow = sqlFetchArray($bres)) {
481 write_form_line($brow['code_type'], $brow['code'], $brow['id'],
482 substr($brow['date'], 0, 10), $brow['code_text'], $brow['fee']);
483 $inv_encounter = $brow['encounter'];
484 $inv_provider = $brow['provider_id'];
485 $inv_payer = $brow['payer_id'];
486 $total += $brow['fee'];
488 while ($drow = sqlFetchArray($dres)) {
489 write_form_line('MED', $drow['prescription_id'], $drow['sale_id'],
490 $drow['sale_date'], $drow['name'], $drow['fee']);
491 $inv_provider = $drow['provider_id'];
492 $total += $drow['fee'];
495 </table>
498 <table border='0' cellspacing='8'>
500 <tr>
501 <td>
502 <? xl('Payment Method','e'); ?>:
503 </td>
504 <td>
505 <select name='form_method'>
507 foreach ($payment_methods as $value) {
508 echo " <option value='$value'";
509 echo ">$value</option>\n";
512 </select>
513 </td>
514 </tr>
516 <tr>
517 <td>
518 <? xl('Check/Reference Number','e'); ?>:
519 </td>
520 <td>
521 <input type='text' name='form_source' size='10' value=''>
522 </td>
523 </tr>
525 <tr>
526 <td>
527 <? xl('Amount Paid','e'); ?>:
528 </td>
529 <td>
530 <input type='text' name='form_amount' size='10' value='<?php echo sprintf("%01.2f", $total) ?>'>
531 </td>
532 </tr>
534 <tr>
535 <td colspan='2' align='center'>
536 &nbsp;<br>
537 <input type='submit' name='form_save' value='Save' /> &nbsp;
538 <input type='button' value='Cancel' onclick='window.close()' />
539 <input type='hidden' name='form_provider' value='<?php echo $inv_provider ?>' />
540 <input type='hidden' name='form_payer' value='<?php echo $inv_payer ?>' />
541 <input type='hidden' name='form_encounter' value='<?php echo $inv_encounter ?>' />
542 </td>
543 </tr>
545 </table>
546 </center>
548 </form>
550 </body>
551 </html>