Support "Save and Close" button in the Fee Sheet.
[openemr.git] / interface / forms / fee_sheet / new.php
blob328c6d7441cebd7ccd657e3fcf21bea3fe3c84c8
1 <?php
2 // Copyright (C) 2005-2011 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 require_once("../../globals.php");
10 require_once("$srcdir/acl.inc");
11 require_once("$srcdir/api.inc");
12 require_once("codes.php");
13 require_once("../../../custom/code_types.inc.php");
14 require_once("../../drugs/drugs.inc.php");
15 require_once("$srcdir/formatting.inc.php");
16 require_once("$srcdir/options.inc.php");
18 // Some table cells will not be displayed unless insurance billing is used.
19 $usbillstyle = $GLOBALS['ippf_specific'] ? " style='display:none'" : "";
21 function alphaCodeType($id) {
22 global $code_types;
23 foreach ($code_types as $key => $value) {
24 if ($value['id'] == $id) return $key;
26 return '';
29 // Helper function for creating drop-lists.
30 function endFSCategory() {
31 global $i, $last_category, $FEE_SHEET_COLUMNS;
32 if (! $last_category) return;
33 echo " </select>\n";
34 echo " </td>\n";
35 if ($i >= $FEE_SHEET_COLUMNS) {
36 echo " </tr>\n";
37 $i = 0;
41 // Generate JavaScript to build the array of diagnoses.
42 function genDiagJS($code_type, $code) {
43 if ($code_type == 'ICD9') {
44 echo "diags.push('$code');\n";
48 // For IPPF only. Returns 0 = none, 1 = nonsurgical, 2 = surgical.
50 function contraceptionClass($code_type, $code) {
51 global $code_types;
52 if (!$GLOBALS['ippf_specific']) return 0;
53 $contra = 0;
54 // Get the related service codes.
55 $codesrow = sqlQuery("SELECT related_code FROM codes WHERE " .
56 "code_type = '" . $code_types[$code_type]['id'] .
57 "' AND code = '$code' LIMIT 1");
58 if (!empty($codesrow['related_code']) && $code_type == 'MA') {
59 $relcodes = explode(';', $codesrow['related_code']);
60 foreach ($relcodes as $relstring) {
61 if ($relstring === '') continue;
62 list($reltype, $relcode) = explode(':', $relstring);
63 if ($reltype !== 'IPPF') continue;
64 if (preg_match('/^11....110/' , $relcode)) $contra |= 1;
65 else if (preg_match('/^11....999/' , $relcode)) $contra |= 1;
66 else if (preg_match('/^112152010/' , $relcode)) $contra |= 1;
67 else if (preg_match('/^11317[1-2]111/', $relcode)) $contra |= 1;
68 else if (preg_match('/^12118[1-2].13/', $relcode)) $contra |= 2;
69 else if (preg_match('/^12118[1-2]999/', $relcode)) $contra |= 2;
72 return $contra;
75 // This writes a billing line item to the output page.
77 function echoLine($lino, $codetype, $code, $modifier, $ndc_info='',
78 $auth = TRUE, $del = FALSE, $units = NULL, $fee = NULL, $id = NULL,
79 $billed = FALSE, $code_text = NULL, $justify = NULL, $provider_id = 0)
81 global $code_types, $ndc_applies, $ndc_uom_choices, $justinit, $pid;
82 global $contraception, $usbillstyle, $hasCharges;
84 if ($codetype == 'COPAY') {
85 if (!$code_text) $code_text = 'Cash';
86 if ($fee > 0) $fee = 0 - $fee;
88 if (! $code_text) {
89 $query = "select id, units, code_text from codes where code_type = '" .
90 $code_types[$codetype]['id'] . "' and " .
91 "code = '$code' and ";
92 if ($modifier) {
93 $query .= "modifier = '$modifier'";
94 } else {
95 $query .= "(modifier is null or modifier = '')";
97 $result = sqlQuery($query);
98 $code_text = $result['code_text'];
99 if (empty($units)) $units = max(1, intval($result['units']));
100 if (!isset($fee)) {
101 // Fees come from the prices table now.
102 $query = "SELECT prices.pr_price " .
103 "FROM patient_data, prices WHERE " .
104 "patient_data.pid = '$pid' AND " .
105 "prices.pr_id = '" . $result['id'] . "' AND " .
106 "prices.pr_selector = '' AND " .
107 "prices.pr_level = patient_data.pricelevel " .
108 "LIMIT 1";
109 echo "\n<!-- $query -->\n"; // debugging
110 $prrow = sqlQuery($query);
111 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
114 $fee = sprintf('%01.2f', $fee);
115 if (empty($units)) $units = 1;
116 $units = max(1, intval($units));
117 // We put unit price on the screen, not the total line item fee.
118 $price = $fee / $units;
119 $strike1 = ($id && $del) ? "<strike>" : "";
120 $strike2 = ($id && $del) ? "</strike>" : "";
121 echo " <tr>\n";
122 echo " <td class='billcell'>$strike1" .
123 ($codetype == 'COPAY' ? xl($codetype) : $codetype) . $strike2;
124 if ($id) {
125 echo "<input type='hidden' name='bill[$lino][id]' value='$id'>";
127 echo "<input type='hidden' name='bill[$lino][code_type]' value='$codetype'>";
128 echo "<input type='hidden' name='bill[$lino][code]' value='$code'>";
129 echo "<input type='hidden' name='bill[$lino][billed]' value='$billed'>";
130 echo "</td>\n";
131 if ($codetype != 'COPAY') {
132 echo " <td class='billcell'>$strike1$code$strike2</td>\n";
133 } else {
134 echo " <td class='billcell'>&nbsp;</td>\n";
136 if ($billed) {
137 if (modifiers_are_used(true)) {
138 echo " <td class='billcell'>$strike1$modifier$strike2" .
139 "<input type='hidden' name='bill[$lino][mod]' value='$modifier'></td>\n";
141 if (fees_are_used()) {
142 echo " <td class='billcell' align='right'>" . oeFormatMoney($price) . "</td>\n";
143 if ($codetype != 'COPAY') {
144 echo " <td class='billcell' align='center'>$units</td>\n";
145 } else {
146 echo " <td class='billcell'>&nbsp;</td>\n";
148 echo " <td class='billcell' align='center'$usbillstyle>$justify</td>\n";
151 // Show provider for this line.
152 echo " <td class='billcell' align='center'>";
153 genProviderSelect('', '-- Default --', $provider_id, true);
154 echo "</td>\n";
155 echo " <td class='billcell' align='center'$usbillstyle><input type='checkbox'" .
156 ($auth ? " checked" : "") . " disabled /></td>\n";
157 echo " <td class='billcell' align='center'><input type='checkbox'" .
158 " disabled /></td>\n";
160 else { // not billed
161 if (modifiers_are_used(true)) {
162 if ($codetype != 'COPAY' && ($code_types[$codetype]['mod'] || $modifier)) {
163 echo " <td class='billcell'><input type='text' name='bill[$lino][mod]' " .
164 "value='$modifier' size='" . $code_types[$codetype]['mod'] . "'></td>\n";
165 } else {
166 echo " <td class='billcell'>&nbsp;</td>\n";
169 if (fees_are_used()) {
170 if ($codetype == 'COPAY' || $code_types[$codetype]['fee'] || $fee != 0) {
171 echo " <td class='billcell' align='right'>" .
172 "<input type='text' name='bill[$lino][price]' " .
173 "value='$price' size='6'";
174 if (acl_check('acct','disc'))
175 echo " style='text-align:right'";
176 else
177 echo " style='text-align:right;background-color:transparent' readonly";
178 echo "></td>\n";
179 echo " <td class='billcell' align='center'>";
180 if ($codetype != 'COPAY') {
181 echo "<input type='text' name='bill[$lino][units]' " .
182 "value='$units' size='2' style='text-align:right'>";
183 } else {
184 echo "<input type='hidden' name='bill[$lino][units]' value='$units'>";
186 echo "</td>\n";
187 if ($code_types[$codetype]['just'] || $justify) {
188 echo " <td class='billcell' align='center'$usbillstyle>";
189 echo "<select name='bill[$lino][justify]' onchange='setJustify(this)'>";
190 echo "<option value='$justify'>$justify</option></select>";
191 echo "</td>\n";
192 $justinit .= "setJustify(f['bill[$lino][justify]']);\n";
193 } else {
194 echo " <td class='billcell'$usbillstyle>&nbsp;</td>\n";
196 } else {
197 echo " <td class='billcell'>&nbsp;</td>\n";
198 echo " <td class='billcell'>&nbsp;</td>\n";
199 echo " <td class='billcell'$usbillstyle>&nbsp;</td>\n"; // justify
203 // Provider drop-list for this line.
204 echo " <td class='billcell' align='center'>";
205 genProviderSelect("bill[$lino][provid]", '-- Default --', $provider_id);
206 echo "</td>\n";
207 echo " <td class='billcell' align='center'$usbillstyle><input type='checkbox' name='bill[$lino][auth]' " .
208 "value='1'" . ($auth ? " checked" : "") . " /></td>\n";
209 echo " <td class='billcell' align='center'><input type='checkbox' name='bill[$lino][del]' " .
210 "value='1'" . ($del ? " checked" : "") . " /></td>\n";
213 echo " <td class='billcell'>$strike1" . ucfirst(strtolower($code_text)) . "$strike2</td>\n";
214 echo " </tr>\n";
216 // If NDC info exists or may be required, add a line for it.
217 if ($codetype == 'HCPCS' && $ndc_applies && !$billed) {
218 $ndcnum = ''; $ndcuom = ''; $ndcqty = '';
219 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
220 $ndcnum = $tmp[1]; $ndcuom = $tmp[2]; $ndcqty = $tmp[3];
222 echo " <tr>\n";
223 echo " <td class='billcell' colspan='2'>&nbsp;</td>\n";
224 echo " <td class='billcell' colspan='6'>&nbsp;NDC:&nbsp;";
225 echo "<input type='text' name='bill[$lino][ndcnum]' value='$ndcnum' " .
226 "size='11' style='background-color:transparent'>";
227 echo " &nbsp;Qty:&nbsp;";
228 echo "<input type='text' name='bill[$lino][ndcqty]' value='$ndcqty' " .
229 "size='3' style='background-color:transparent;text-align:right'>";
230 echo " ";
231 echo "<select name='bill[$lino][ndcuom]' style='background-color:transparent'>";
232 foreach ($ndc_uom_choices as $key => $value) {
233 echo "<option value='$key'";
234 if ($key == $ndcuom) echo " selected";
235 echo ">$value</option>";
237 echo "</select>";
238 echo "</td>\n";
239 echo " </tr>\n";
241 else if ($ndc_info) {
242 echo " <tr>\n";
243 echo " <td class='billcell' colspan='2'>&nbsp;</td>\n";
244 echo " <td class='billcell' colspan='6'>&nbsp;NDC Data: $ndc_info</td>\n";
245 echo " </tr>\n";
248 // For IPPF. Track contraceptive services.
249 if (!$del) $contraception |= contraceptionClass($codetype, $code);
251 if ($fee != 0) $hasCharges = true;
254 // This writes a product (drug_sales) line item to the output page.
256 function echoProdLine($lino, $drug_id, $del = FALSE, $units = NULL,
257 $fee = NULL, $sale_id = 0, $billed = FALSE)
259 global $code_types, $ndc_applies, $pid, $usbillstyle, $hasCharges;
261 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = '$drug_id'");
262 $code_text = $drow['name'];
264 $fee = sprintf('%01.2f', $fee);
265 if (empty($units)) $units = 1;
266 $units = max(1, intval($units));
267 // We put unit price on the screen, not the total line item fee.
268 $price = $fee / $units;
269 $strike1 = ($sale_id && $del) ? "<strike>" : "";
270 $strike2 = ($sale_id && $del) ? "</strike>" : "";
271 echo " <tr>\n";
272 echo " <td class='billcell'>{$strike1}Product$strike2";
273 echo "<input type='hidden' name='prod[$lino][sale_id]' value='$sale_id'>";
274 echo "<input type='hidden' name='prod[$lino][drug_id]' value='$drug_id'>";
275 echo "<input type='hidden' name='prod[$lino][billed]' value='$billed'>";
276 echo "</td>\n";
277 echo " <td class='billcell'>$strike1$drug_id$strike2</td>\n";
278 if (modifiers_are_used(true)) {
279 echo " <td class='billcell'>&nbsp;</td>\n";
281 if ($billed) {
282 if (fees_are_used()) {
283 echo " <td class='billcell' align='right'>" . oeFormatMoney($price) . "</td>\n";
284 echo " <td class='billcell' align='center'>$units</td>\n";
285 echo " <td class='billcell' align='center'$usbillstyle>&nbsp;</td>\n"; // justify
287 echo " <td class='billcell' align='center'>&nbsp;</td>\n"; // provider
288 echo " <td class='billcell' align='center'$usbillstyle>&nbsp;</td>\n"; // auth
289 echo " <td class='billcell' align='center'><input type='checkbox'" . // del
290 " disabled /></td>\n";
291 } else {
292 if (fees_are_used()) {
293 echo " <td class='billcell' align='right'>" .
294 "<input type='text' name='prod[$lino][price]' " .
295 "value='$price' size='6'";
296 if (acl_check('acct','disc'))
297 echo " style='text-align:right'";
298 else
299 echo " style='text-align:right;background-color:transparent' readonly";
300 echo "></td>\n";
301 echo " <td class='billcell' align='center'>";
302 echo "<input type='text' name='prod[$lino][units]' " .
303 "value='$units' size='2' style='text-align:right'>";
304 echo "</td>\n";
305 echo " <td class='billcell'$usbillstyle>&nbsp;</td>\n"; // justify
307 echo " <td class='billcell' align='center'>&nbsp;</td>\n"; // provider
308 echo " <td class='billcell' align='center'$usbillstyle>&nbsp;</td>\n"; // auth
309 echo " <td class='billcell' align='center'><input type='checkbox' name='prod[$lino][del]' " .
310 "value='1'" . ($del ? " checked" : "") . " /></td>\n";
313 echo " <td class='billcell'>$strike1" . ucfirst(strtolower($code_text)) . "$strike2</td>\n";
314 echo " </tr>\n";
316 if ($fee != 0) $hasCharges = true;
319 // Build a drop-down list of providers. This includes users who
320 // have the word "provider" anywhere in their "additional info"
321 // field, so that we can define providers (for billing purposes)
322 // who do not appear in the calendar.
324 function genProviderSelect($selname, $toptext, $default=0, $disabled=false) {
325 $query = "SELECT id, lname, fname FROM users WHERE " .
326 "( authorized = 1 OR info LIKE '%provider%' ) AND username != '' " .
327 "AND active = 1 AND ( info IS NULL OR info NOT LIKE '%Inactive%' ) " .
328 "ORDER BY lname, fname";
329 $res = sqlStatement($query);
330 echo " <select name='$selname'";
331 if ($disabled) echo " disabled";
332 echo ">\n";
333 echo " <option value=''>$toptext\n";
334 while ($row = sqlFetchArray($res)) {
335 $provid = $row['id'];
336 echo " <option value='$provid'";
337 if ($provid == $default) echo " selected";
338 echo ">" . $row['lname'] . ", " . $row['fname'] . "\n";
340 echo " </select>\n";
343 // This is just for IPPF, to indicate if the visit includes contraceptive services.
344 $contraception = 0;
346 // Possible units of measure for NDC drug quantities.
348 $ndc_uom_choices = array(
349 'ML' => 'ML',
350 'GR' => 'Grams',
351 'ME' => 'Milligrams',
352 'F2' => 'I.U.',
353 'UN' => 'Units'
356 // $FEE_SHEET_COLUMNS should be defined in codes.php.
357 if (empty($FEE_SHEET_COLUMNS)) $FEE_SHEET_COLUMNS = 2;
359 $returnurl = $GLOBALS['concurrent_layout'] ? 'encounter_top.php' : 'patient_encounter.php';
361 // Update price level in patient demographics.
362 if (!empty($_POST['pricelevel'])) {
363 sqlStatement("UPDATE patient_data SET pricelevel = '" .
364 $_POST['pricelevel'] . "' WHERE pid = '$pid'");
367 // Get some info about this visit.
368 $visit_row = sqlQuery("SELECT fe.date, opc.pc_catname " .
369 "FROM form_encounter AS fe " .
370 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
371 "WHERE fe.pid = '$pid' AND fe.encounter = '$encounter' LIMIT 1");
372 $visit_date = substr($visit_row['date'], 0, 10);
374 // If Save or Save-and-Close was clicked, save the new and modified billing
375 // lines; then if no error, redirect to $returnurl.
377 if ($_POST['bn_save'] || $_POST['bn_save_close']) {
378 $main_provid = 0 + $_POST['ProviderID'];
379 $main_supid = 0 + $_POST['SupervisorID'];
380 if ($main_supid == $main_provid) $main_supid = 0;
381 $default_warehouse = $_POST['default_warehouse'];
383 $bill = $_POST['bill'];
384 for ($lino = 1; $bill["$lino"]['code_type']; ++$lino) {
385 $iter = $bill["$lino"];
386 $code_type = $iter['code_type'];
387 $code = $iter['code'];
388 $del = $iter['del'];
390 // Get some information about this service code.
391 $codesrow = sqlQuery("SELECT code_text FROM codes WHERE " .
392 "code_type = '" . $code_types[$code_type]['id'] .
393 "' AND code = '$code' LIMIT 1");
395 // Skip disabled (billed) line items.
396 if ($iter['billed']) continue;
398 $id = $iter['id'];
399 $modifier = trim($iter['mod']);
400 $units = max(1, intval(trim($iter['units'])));
401 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
402 if ($code_type == 'COPAY') {
403 if ($fee > 0) $fee = 0 - $fee;
404 $code = sprintf('%01.2f', 0 - $fee);
406 $justify = trim($iter['justify']);
407 if ($justify) $justify = str_replace(',', ':', $justify) . ':';
408 // $auth = $iter['auth'] ? "1" : "0";
409 $auth = "1";
410 $provid = 0 + $iter['provid'];
412 $ndc_info = '';
413 if ($iter['ndcnum']) {
414 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
415 trim($iter['ndcqty']);
418 // If the item is already in the database...
419 if ($id) {
420 if ($del) {
421 deleteBilling($id);
423 else {
424 // authorizeBilling($id, $auth);
425 sqlQuery("UPDATE billing SET code = '$code', " .
426 "units = '$units', fee = '$fee', modifier = '$modifier', " .
427 "authorized = $auth, provider_id = '$provid', " .
428 "ndc_info = '$ndc_info', justify = '$justify' WHERE " .
429 "id = '$id' AND billed = 0 AND activity = 1");
433 // Otherwise it's a new item...
434 else if (! $del) {
435 $code_text = addslashes($codesrow['code_text']);
436 addBilling($encounter, $code_type, $code, $code_text, $pid, $auth,
437 $provid, $modifier, $units, $fee, $ndc_info, $justify);
439 } // end for
441 // Doing similarly to the above but for products.
442 $prod = $_POST['prod'];
443 for ($lino = 1; $prod["$lino"]['drug_id']; ++$lino) {
444 $iter = $prod["$lino"];
446 if (!empty($iter['billed'])) continue;
448 $drug_id = $iter['drug_id'];
449 $sale_id = $iter['sale_id']; // present only if already saved
450 $units = max(1, intval(trim($iter['units'])));
451 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
452 $del = $iter['del'];
454 // If the item is already in the database...
455 if ($sale_id) {
456 if ($del) {
457 // Zero out this sale and reverse its inventory update. We bring in
458 // drug_sales twice so that the original quantity can be referenced
459 // unambiguously.
460 sqlStatement("UPDATE drug_sales AS dsr, drug_sales AS ds, " .
461 "drug_inventory AS di " .
462 "SET di.on_hand = di.on_hand + dsr.quantity, " .
463 "ds.quantity = 0, ds.fee = 0 WHERE " .
464 "dsr.sale_id = '$sale_id' AND ds.sale_id = dsr.sale_id AND " .
465 "di.inventory_id = ds.inventory_id");
466 // And delete the sale for good measure.
467 sqlStatement("DELETE FROM drug_sales WHERE sale_id = '$sale_id'");
469 else {
470 // Modify the sale and adjust inventory accordingly.
471 $query = "UPDATE drug_sales AS dsr, drug_sales AS ds, " .
472 "drug_inventory AS di " .
473 "SET di.on_hand = di.on_hand + dsr.quantity - $units, " .
474 "ds.quantity = '$units', ds.fee = '$fee', " .
475 "ds.sale_date = '$visit_date' WHERE " .
476 "dsr.sale_id = '$sale_id' AND ds.sale_id = dsr.sale_id AND " .
477 "di.inventory_id = ds.inventory_id";
478 sqlStatement($query);
482 // Otherwise it's a new item...
483 else if (! $del) {
484 $sale_id = sellDrug($drug_id, $units, $fee, $pid, $encounter, 0,
485 $visit_date, '', $default_warehouse);
486 if (!$sale_id) die("Insufficient inventory for product ID \"$drug_id\".");
488 } // end for
490 // Set the main/default service provider in the new-encounter form.
491 /*******************************************************************
492 sqlStatement("UPDATE forms, users SET forms.user = users.username WHERE " .
493 "forms.pid = '$pid' AND forms.encounter = '$encounter' AND " .
494 "forms.formdir = 'newpatient' AND users.id = '$provid'");
495 *******************************************************************/
496 sqlStatement("UPDATE form_encounter SET provider_id = '$main_provid', " .
497 "supervisor_id = '$main_supid' WHERE " .
498 "pid = '$pid' AND encounter = '$encounter'");
500 // Save-and-Close is currently IPPF-specific but might be more generally
501 // useful. It provides the ability to mark an encounter as billed
502 // directly from the Fee Sheet, if there are no charges.
503 if ($_POST['bn_save_close']) {
504 $tmp1 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
505 "pid = '$pid' AND encounter = '$encounter'");
506 $tmp2 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
507 "pid = '$pid' AND encounter = '$encounter' AND billed = 0 AND " .
508 "activity = 1");
509 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
510 sqlStatement("update drug_sales SET billed = 1 WHERE " .
511 "pid = '$pid' AND encounter = '$encounter' AND billed = 0");
512 sqlStatement("UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
513 "pid = '$pid' AND encounter = '$encounter' AND billed = 0 AND " .
514 "activity = 1");
516 else {
517 // Would be good to display an error message here... they clicked
518 // Save and Close but the close could not be done. However the
519 // framework does not provide an easy way to do that.
523 // More IPPF stuff.
524 if (!empty($_POST['contrastart'])) {
525 $contrastart = $_POST['contrastart'];
526 sqlStatement("UPDATE patient_data SET contrastart = '" .
527 $contrastart . "' WHERE pid = '$pid'");
530 // Note: Taxes are computed at checkout time (in pos_checkout.php which
531 // also posts to SL). Currently taxes with insurance claims make no sense,
532 // so for now we'll ignore tax computation in the insurance billing logic.
534 formHeader("Redirecting....");
535 formJump();
536 formFooter();
537 exit;
540 $billresult = getBillingByEncounter($pid, $encounter, "*");
542 <html>
543 <head>
544 <?php html_header_show(); ?>
545 <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css">
546 <style>
547 .billcell { font-family: sans-serif; font-size: 10pt }
548 </style>
549 <script language="JavaScript">
551 var diags = new Array();
553 <?php
554 if ($billresult) {
555 foreach ($billresult as $iter) {
556 genDiagJS($iter["code_type"], trim($iter["code"]));
559 if ($_POST['bill']) {
560 foreach ($_POST['bill'] as $iter) {
561 if ($iter["del"]) continue; // skip if Delete was checked
562 if ($iter["id"]) continue; // skip if it came from the database
563 genDiagJS($iter["code_type"], $iter["code"]);
566 if ($_POST['newcodes']) {
567 $arrcodes = explode('~', $_POST['newcodes']);
568 foreach ($arrcodes as $codestring) {
569 if ($codestring === '') continue;
570 $arrcode = explode('|', $codestring);
571 list($code, $modifier) = explode(":", $arrcode[1]);
572 genDiagJS($arrcode[0], $code);
577 // This is invoked by <select onchange> for the various dropdowns,
578 // including search results.
579 function codeselect(selobj) {
580 var i = selobj.selectedIndex;
581 if (i > 0) {
582 top.restoreSession();
583 var f = document.forms[0];
584 f.newcodes.value = selobj.options[i].value;
585 f.submit();
589 function copayselect() {
590 top.restoreSession();
591 var f = document.forms[0];
592 f.newcodes.value = 'COPAY||';
593 f.submit();
596 function validate(f) {
597 for (var lino = 1; f['bill['+lino+'][code_type]']; ++lino) {
598 var pfx = 'bill['+lino+']';
599 if (f[pfx+'[ndcnum]'] && f[pfx+'[ndcnum]'].value) {
600 // Check NDC number format.
601 var ndcok = true;
602 var ndc = f[pfx+'[ndcnum]'].value;
603 var a = ndc.split('-');
604 if (a.length != 3) {
605 ndcok = false;
607 else if (a[0].length < 1 || a[1].length < 1 || a[2].length < 1 ||
608 a[0].length > 5 || a[1].length > 4 || a[2].length > 2) {
609 ndcok = false;
611 else {
612 for (var i = 0; i < 3; ++i) {
613 for (var j = 0; j < a[i].length; ++j) {
614 var c = a[i].charAt(j);
615 if (c < '0' || c > '9') ndcok = false;
619 if (!ndcok) {
620 alert('<?php xl('Format incorrect for NDC','e') ?> "' + ndc +
621 '", <?php xl('should be like nnnnn-nnnn-nn','e') ?>');
622 if (f[pfx+'[ndcnum]'].focus) f[pfx+'[ndcnum]'].focus();
623 return false;
625 // Check for valid quantity.
626 var qty = f[pfx+'[ndcqty]'].value - 0;
627 if (isNaN(qty) || qty <= 0) {
628 alert('<?php xl('Quantity for NDC','e') ?> "' + ndc +
629 '" <?php xl('is not valid (decimal fractions are OK).','e') ?>');
630 if (f[pfx+'[ndcqty]'].focus) f[pfx+'[ndcqty]'].focus();
631 return false;
635 top.restoreSession();
636 return true;
639 // When a justify selection is made, apply it to the current list for
640 // this procedure and then rebuild its selection list.
642 function setJustify(seljust) {
643 var theopts = seljust.options;
644 var jdisplay = theopts[0].text;
645 // Compute revised justification string. Note this does nothing if
646 // the first entry is still selected, which is handy at startup.
647 if (seljust.selectedIndex > 0) {
648 var newdiag = seljust.value;
649 if (newdiag.length == 0) {
650 jdisplay = '';
652 else {
653 if (jdisplay.length) jdisplay += ',';
654 jdisplay += newdiag;
657 // Rebuild selection list.
658 var jhaystack = ',' + jdisplay + ',';
659 var j = 0;
660 theopts.length = 0;
661 theopts[j++] = new Option(jdisplay,jdisplay,true,true);
662 for (var i = 0; i < diags.length; ++i) {
663 if (jhaystack.indexOf(',' + diags[i] + ',') < 0) {
664 theopts[j++] = new Option(diags[i],diags[i],false,false);
667 theopts[j++] = new Option('Clear','',false,false);
670 </script>
671 </head>
673 <body class="body_top">
674 <form method="post" action="<?php echo $rootdir; ?>/forms/fee_sheet/new.php"
675 onsubmit="return validate(this)">
676 <span class="title"><?php xl('Fee Sheet','e'); ?></span><br>
677 <input type='hidden' name='newcodes' value=''>
679 <center>
681 <?php
682 $isBilled = isEncounterBilled($pid, $encounter);
683 if ($isBilled) {
684 echo "<p><font color='green'>This encounter has been billed. If you " .
685 "need to change it, it must be re-opened.</font></p>\n";
687 else { // the encounter is not yet billed
690 <table width='95%'>
691 <?php
692 $i = 0;
693 $last_category = '';
695 // Create drop-lists based on the fee_sheet_options table.
696 $res = sqlStatement("SELECT * FROM fee_sheet_options " .
697 "ORDER BY fs_category, fs_option");
698 while ($row = sqlFetchArray($res)) {
699 $fs_category = $row['fs_category'];
700 $fs_option = $row['fs_option'];
701 $fs_codes = $row['fs_codes'];
702 if($fs_category !== $last_category) {
703 endFSCategory();
704 $last_category = $fs_category;
705 ++$i;
706 echo ($i <= 1) ? " <tr>\n" : "";
707 echo " <td width='50%' align='center' nowrap>\n";
708 echo " <select style='width:96%' onchange='codeselect(this)'>\n";
709 echo " <option value=''> " . substr($fs_category, 1) . "</option>\n";
711 echo " <option value='$fs_codes'>" . substr($fs_option, 1) . "</option>\n";
713 endFSCategory();
715 // Create drop-lists based on categories defined within the codes.
716 $pres = sqlStatement("SELECT option_id, title FROM list_options " .
717 "WHERE list_id = 'superbill' ORDER BY seq");
718 while ($prow = sqlFetchArray($pres)) {
719 global $code_types;
720 ++$i;
721 echo ($i <= 1) ? " <tr>\n" : "";
722 echo " <td width='50%' align='center' nowrap>\n";
723 echo " <select style='width:96%' onchange='codeselect(this)'>\n";
724 echo " <option value=''> " . $prow['title'] . "\n";
725 $res = sqlStatement("SELECT code_type, code, code_text,modifier FROM codes " .
726 "WHERE superbill = '" . $prow['option_id'] . "' AND active = 1 " .
727 "ORDER BY code_text");
728 while ($row = sqlFetchArray($res)) {
729 $ctkey = alphaCodeType($row['code_type']);
730 if ($code_types[$ctkey]['nofs']) continue;
731 echo " <option value='$ctkey|" .
732 $row['code'] . ':'. $row['modifier']. "|'>" . $row['code_text'] . "</option>\n";
734 echo " </select>\n";
735 echo " </td>\n";
736 if ($i >= $FEE_SHEET_COLUMNS) {
737 echo " </tr>\n";
738 $i = 0;
742 // Create one more drop-list, for Products.
743 if ($GLOBALS['sell_non_drug_products']) {
744 ++$i;
745 echo ($i <= 1) ? " <tr>\n" : "";
746 echo " <td width='50%' align='center' nowrap>\n";
747 echo " <select name='Products' style='width:96%' onchange='codeselect(this)'>\n";
748 echo " <option value=''> " . xl('Products') . "\n";
749 $tres = sqlStatement("SELECT dt.drug_id, dt.selector, d.name " .
750 "FROM drug_templates AS dt, drugs AS d WHERE " .
751 "d.drug_id = dt.drug_id AND d.active = 1 " .
752 "ORDER BY d.name, dt.selector, dt.drug_id");
753 while ($trow = sqlFetchArray($tres)) {
754 echo " <option value='PROD|" . $trow['drug_id'] . '|' . $trow['selector'] . "'>" .
755 $trow['drug_id'] . ':' . $trow['selector'];
756 if ($trow['name'] !== $trow['selector']) echo ' ' . $trow['name'];
757 echo "</option>\n";
759 echo " </select>\n";
760 echo " </td>\n";
761 if ($i >= $FEE_SHEET_COLUMNS) {
762 echo " </tr>\n";
763 $i = 0;
767 $search_type = $default_search_type;
768 if ($_POST['search_type']) $search_type = $_POST['search_type'];
770 $ndc_applies = true; // Assume all payers require NDC info.
772 echo $i ? " <td></td>\n </tr>\n" : "";
773 echo " <tr>\n";
774 echo " <td colspan='$FEE_SHEET_COLUMNS' align='center' nowrap>\n";
776 // If Search was clicked, do it and write the list of results here.
777 // There's no limit on the number of results!
779 $numrows = 0;
780 if ($_POST['bn_search'] && $_POST['search_term']) {
781 $query = "SELECT code, modifier, code_text FROM codes WHERE " .
782 "(code_text LIKE '%" . $_POST['search_term'] . "%' OR " .
783 "code LIKE '%" . $_POST['search_term'] . "%') AND " .
784 "code_type = '" . $code_types[$search_type]['id'] . "' " .
785 "AND active = 1 ORDER BY code";
786 $res = sqlStatement($query);
787 $numrows = mysql_num_rows($res); // FIXME - not portable!
790 echo " <select name='Search Results' style='width:98%' " .
791 "onchange='codeselect(this)'";
792 if (! $numrows) echo ' disabled';
793 echo ">\n";
794 echo " <option value=''> Search Results ($numrows items)\n";
796 if ($numrows) {
797 while ($row = sqlFetchArray($res)) {
798 $code = $row['code'];
799 if ($row['modifier']) $code .= ":" . $row['modifier'];
800 echo " <option value='$search_type|$code|'>$code " .
801 ucfirst(strtolower($row['code_text'])) . "</option>\n";
805 echo " </select>\n";
806 echo " </td>\n";
807 echo " </tr>\n";
810 </table>
812 <p style='margin-top:8px;margin-bottom:8px'>
813 <table>
814 <tr>
815 <td>
816 <input type='button' value='<?php xl('Add Copay','e');?>'
817 onclick="copayselect()" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
818 </td>
819 <td>
820 <?php xl('Search','e'); ?>&nbsp;
821 <?php
822 foreach ($code_types as $key => $value) {
823 if (!empty($value['nofs'])) continue;
824 echo " <input type='radio' name='search_type' value='$key'";
825 if ($key == $default_search_type) echo " checked";
826 echo " />$key&nbsp;\n";
829 <?php xl('for','e'); ?>&nbsp;
830 </td>
831 <td>
832 <input type='text' name='search_term' value=''> &nbsp;
833 </td>
834 <td>
835 <input type='submit' name='bn_search' value='<?php xl('Search','e');?>'>
836 </td>
837 </tr>
838 </table>
839 </p>
840 <p style='margin-top:16px;margin-bottom:8px'>
842 <?php } // end encounter not billed ?>
844 <table cellspacing='5'>
845 <tr>
846 <td class='billcell'><b><?php xl('Type','e');?></b></td>
847 <td class='billcell'><b><?php xl('Code','e');?></b></td>
848 <?php if (modifiers_are_used(true)) { ?>
849 <td class='billcell'><b><?php xl('Mod','e');?></b></td>
850 <?php } ?>
851 <?php if (fees_are_used()) { ?>
852 <td class='billcell' align='right'><b><?php xl('Price','e');?></b>&nbsp;</td>
853 <td class='billcell' align='center'><b><?php xl('Units','e');?></b></td>
854 <td class='billcell' align='center'<?php echo $usbillstyle; ?>><b><?php xl('Justify','e');?></b></td>
855 <?php } ?>
856 <td class='billcell' align='center'><b><?php xl('Provider','e');?></b></td>
857 <td class='billcell' align='center'<?php echo $usbillstyle; ?>><b><?php xl('Auth','e');?></b></td>
858 <td class='billcell' align='center'><b><?php xl('Delete','e');?></b></td>
859 <td class='billcell'><b><?php xl('Description','e');?></b></td>
860 </tr>
862 <?php
863 $justinit = "var f = document.forms[0];\n";
865 // $encounter_provid = -1;
867 $hasCharges = false;
869 // Generate lines for items already in the billing table for this encounter,
870 // and also set the rendering provider if we come across one.
872 $bill_lino = 0;
873 if ($billresult) {
874 foreach ($billresult as $iter) {
875 ++$bill_lino;
876 $bline = $_POST['bill']["$bill_lino"];
877 $del = $bline['del']; // preserve Delete if checked
879 $modifier = trim($iter["modifier"]);
880 $units = $iter["units"];
881 $fee = $iter["fee"];
882 $authorized = $iter["authorized"];
883 $ndc_info = $iter["ndc_info"];
884 $justify = trim($iter['justify']);
885 if ($justify) $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
886 $provider_id = $iter['provider_id'];
888 // Also preserve other items from the form, if present.
889 if ($bline['id'] && !$iter["billed"]) {
890 $modifier = trim($bline['mod']);
891 $units = max(1, intval(trim($bline['units'])));
892 $fee = sprintf('%01.2f',(0 + trim($bline['price'])) * $units);
893 $authorized = $bline['auth'];
894 $ndc_info = '';
895 if ($bline['ndcnum']) {
896 $ndc_info = 'N4' . trim($bline['ndcnum']) . ' ' . $bline['ndcuom'] .
897 trim($bline['ndcqty']);
899 $justify = $bline['justify'];
900 $provider_id = 0 + $bline['provid'];
903 // list($code, $modifier) = explode("-", $iter["code"]);
904 echoLine($bill_lino, $iter["code_type"], trim($iter["code"]),
905 $modifier, $ndc_info, $authorized,
906 $del, $units, $fee, $iter["id"], $iter["billed"],
907 $iter["code_text"], $justify, $provider_id);
911 // Echo new billing items from this form here, but omit any line
912 // whose Delete checkbox is checked.
914 if ($_POST['bill']) {
915 foreach ($_POST['bill'] as $key => $iter) {
916 if ($iter["id"]) continue; // skip if it came from the database
917 if ($iter["del"]) continue; // skip if Delete was checked
918 $ndc_info = '';
919 if ($iter['ndcnum']) {
920 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
921 trim($iter['ndcqty']);
923 // $fee = 0 + trim($iter['fee']);
924 $units = max(1, intval(trim($iter['units'])));
925 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
926 if ($iter['code_type'] == 'COPAY' && $fee > 0) $fee = 0 - $fee;
927 echoLine(++$bill_lino, $iter["code_type"], $iter["code"], trim($iter["mod"]),
928 $ndc_info, $iter["auth"], $iter["del"], $units,
929 $fee, NULL, FALSE, NULL, $iter["justify"], 0 + $iter['provid']);
933 // Generate lines for items already in the drug_sales table for this encounter.
935 $query = "SELECT * FROM drug_sales WHERE " .
936 "pid = '$pid' AND encounter = '$encounter' " .
937 "ORDER BY sale_id";
938 $sres = sqlStatement($query);
939 $prod_lino = 0;
940 while ($srow = sqlFetchArray($sres)) {
941 ++$prod_lino;
942 $pline = $_POST['prod']["$prod_lino"];
943 $del = $pline['del']; // preserve Delete if checked
944 $sale_id = $srow['sale_id'];
945 $drug_id = $srow['drug_id'];
946 $units = $srow['quantity'];
947 $fee = $srow['fee'];
948 $billed = $srow['billed'];
949 // Also preserve other items from the form, if present and unbilled.
950 if ($pline['sale_id'] && !$srow['billed']) {
951 // $units = trim($pline['units']);
952 // $fee = trim($pline['fee']);
953 $units = max(1, intval(trim($pline['units'])));
954 $fee = sprintf('%01.2f',(0 + trim($pline['price'])) * $units);
956 echoProdLine($prod_lino, $drug_id, $del, $units, $fee, $sale_id, $billed);
959 // Echo new product items from this form here, but omit any line
960 // whose Delete checkbox is checked.
962 if ($_POST['prod']) {
963 foreach ($_POST['prod'] as $key => $iter) {
964 if ($iter["sale_id"]) continue; // skip if it came from the database
965 if ($iter["del"]) continue; // skip if Delete was checked
966 // $fee = 0 + trim($iter['fee']);
967 $units = max(1, intval(trim($iter['units'])));
968 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
969 echoProdLine(++$prod_lino, $iter['drug_id'], FALSE, $units, $fee);
973 // If new billing code(s) were <select>ed, add their line(s) here.
975 if ($_POST['newcodes']) {
976 $arrcodes = explode('~', $_POST['newcodes']);
977 foreach ($arrcodes as $codestring) {
978 if ($codestring === '') continue;
979 $arrcode = explode('|', $codestring);
980 $newtype = $arrcode[0];
981 $newcode = $arrcode[1];
982 $newsel = $arrcode[2];
983 if ($newtype == 'COPAY') {
984 $tmp = sqlQuery("SELECT copay FROM insurance_data WHERE pid = '$pid' " .
985 "AND type = 'primary' ORDER BY date DESC LIMIT 1");
986 $code = sprintf('%01.2f', 0 + $tmp['copay']);
987 echoLine(++$bill_lino, $newtype, $code, '', '', '1', '0', '1',
988 sprintf('%01.2f', 0 - $code));
990 else if ($newtype == 'PROD') {
991 $result = sqlQuery("SELECT * FROM drug_templates WHERE " .
992 "drug_id = '$newcode' AND selector = '$newsel'");
993 $units = max(1, intval($result['quantity']));
994 $prrow = sqlQuery("SELECT prices.pr_price " .
995 "FROM patient_data, prices WHERE " .
996 "patient_data.pid = '$pid' AND " .
997 "prices.pr_id = '$newcode' AND " .
998 "prices.pr_selector = '$newsel' AND " .
999 "prices.pr_level = patient_data.pricelevel " .
1000 "LIMIT 1");
1001 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
1002 echoProdLine(++$prod_lino, $newcode, FALSE, $units, $fee);
1004 else {
1005 list($code, $modifier) = explode(":", $newcode);
1006 $ndc_info = '';
1007 // If HCPCS, find last NDC string used for this code.
1008 if ($newtype == 'HCPCS' && $ndc_applies) {
1009 $tmp = sqlQuery("SELECT ndc_info FROM billing WHERE " .
1010 "code_type = '$newtype' AND code = '$code' AND ndc_info LIKE 'N4%' " .
1011 "ORDER BY date DESC LIMIT 1");
1012 if (!empty($tmp)) $ndc_info = $tmp['ndc_info'];
1014 echoLine(++$bill_lino, $newtype, $code, trim($modifier), $ndc_info);
1019 $tmp = sqlQuery("SELECT provider_id, supervisor_id FROM form_encounter " .
1020 "WHERE pid = '$pid' AND encounter = '$encounter' " .
1021 "ORDER BY id DESC LIMIT 1");
1022 $encounter_provid = 0 + $tmp['provider_id'];
1023 $encounter_supid = 0 + $tmp['supervisor_id'];
1025 </table>
1026 </p>
1028 <br />
1029 &nbsp;
1031 <?php
1032 // Choose rendering and supervising providers.
1033 echo "<span class='billcell'><b>\n";
1034 echo xl('Providers') . ": &nbsp;";
1036 echo "&nbsp;&nbsp;" . xl('Rendering') . "\n";
1037 genProviderSelect('ProviderID', '-- Please Select --', $encounter_provid, $isBilled);
1039 if (!$GLOBALS['ippf_specific']) {
1040 echo "&nbsp;&nbsp;" . xl('Supervising') . "\n";
1041 genProviderSelect('SupervisorID', '-- N/A --', $encounter_supid, $isBilled);
1044 echo "</b></span>\n";
1048 &nbsp;
1050 <?php
1051 // If applicable, ask for the contraceptive services start date.
1052 $trow = sqlQuery("SELECT count(*) AS count FROM layout_options WHERE " .
1053 "form_id = 'DEM' AND field_id = 'contrastart' AND uor > 0");
1054 if ($trow['count'] && $contraception && !$isBilled) {
1055 $date1 = substr($visit_row['date'], 0, 10);
1056 // If admission or surgical, then force contrastart.
1057 if ($contraception > 1 ||
1058 strpos(strtolower($visit_row['pc_catname']), 'admission') !== false)
1060 echo " <input type='hidden' name='contrastart' value='$date1' />\n";
1062 else {
1063 // echo "<!-- contraception = $contraception -->\n"; // debugging
1064 $trow = sqlQuery("SELECT contrastart " .
1065 "FROM patient_data WHERE " .
1066 "pid = '$pid' LIMIT 1");
1067 if (empty($trow['contrastart']) || substr($trow['contrastart'], 0, 4) == '0000') {
1068 $date0 = date('Y-m-d', strtotime($date1) - (60 * 60 * 24));
1069 echo " <select name='contrastart'>\n";
1070 echo " <option value='$date1'>" . xl('This visit begins new contraceptive use') . "</option>\n";
1071 echo " <option value='$date0'>" . xl('Contraceptive services previously started') . "</option>\n";
1072 echo " <option value=''>" . xl('None of the above') . "</option>\n";
1073 echo " </select>\n";
1074 echo "&nbsp; &nbsp; &nbsp;\n";
1079 // If there is a choice of warehouses, allow override of user default.
1080 if ($prod_lino > 0) { // if any products are in this form
1081 $trow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse'");
1082 if ($trow['count'] > 1) {
1083 $trow = sqlQuery("SELECT default_warehouse FROM users WHERE username = '" .
1084 $_SESSION['authUser'] . "'");
1085 echo " <span class='billcell'><b>" . xl('Warehouse') . ":</b></span>\n";
1086 echo generate_select_list('default_warehouse', 'warehouse',
1087 $trow['default_warehouse'], '');
1088 echo "&nbsp; &nbsp; &nbsp;\n";
1092 // Allow the patient price level to be fixed here.
1093 $plres = sqlStatement("SELECT option_id, title FROM list_options " .
1094 "WHERE list_id = 'pricelevel' ORDER BY seq");
1095 if (true) {
1096 $trow = sqlQuery("SELECT pricelevel FROM patient_data WHERE " .
1097 "pid = '$pid' LIMIT 1");
1098 $pricelevel = $trow['pricelevel'];
1099 echo " <span class='billcell'><b>" . xl('Price Level') . ":</b></span>\n";
1100 echo " <select name='pricelevel'";
1101 if ($isBilled) echo " disabled";
1102 echo ">\n";
1103 while ($plrow = sqlFetchArray($plres)) {
1104 $key = $plrow['option_id'];
1105 $val = $plrow['title'];
1106 echo " <option value='$key'";
1107 if ($key == $pricelevel) echo ' selected';
1108 echo ">$val</option>\n";
1110 echo " </select>\n";
1114 &nbsp; &nbsp; &nbsp;
1116 <?php if (!$isBilled) { ?>
1117 <input type='submit' name='bn_save' value='<?php xl('Save','e');?>' />
1118 &nbsp;
1119 <?php if (!$hasCharges) { ?>
1120 <input type='submit' name='bn_save_close' value='<?php xl('Save and Close','e');?>' />
1121 &nbsp;
1122 <?php } ?>
1123 <input type='submit' name='bn_refresh' value='<?php xl('Refresh','e');?>'>
1124 &nbsp;
1125 <?php } ?>
1127 <input type='button' value='<?php xl('Cancel','e');?>'
1128 onclick="top.restoreSession();location='<?php echo "$rootdir/patient_file/encounter/$returnurl" ?>'" />
1130 <?php if ($code_types['UCSMC']) { ?>
1131 <p style='font-family:sans-serif;font-size:8pt;color:#666666;'>
1132 &nbsp;<br>
1133 <?php xl('UCSMC codes provided by the University of Calgary Sports Medicine Centre','e');?>
1134 </p>
1135 <?php } ?>
1137 </center>
1139 </form>
1141 <?php
1142 // TBD: If $alertmsg, display it with a JavaScript alert().
1145 <script language='JavaScript'>
1146 <?php echo $justinit; ?>
1147 </script>
1149 </body>
1150 </html>