minor mod to previous fee sheet commit to not rely on register globals work around
[openemr.git] / interface / forms / fee_sheet / new.php
blob6551e519e4aec35143c9447a44df0dc85d478eeb
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 global $code_types;
44 if ($code_types[$code_type]['diag']) {
45 echo "diags.push('$code');\n";
49 // For IPPF only. Returns 0 = none, 1 = nonsurgical, 2 = surgical.
51 function contraceptionClass($code_type, $code) {
52 global $code_types;
53 if (!$GLOBALS['ippf_specific']) return 0;
54 $contra = 0;
55 // Get the related service codes.
56 $codesrow = sqlQuery("SELECT related_code FROM codes WHERE " .
57 "code_type = '" . $code_types[$code_type]['id'] .
58 "' AND code = '$code' LIMIT 1");
59 if (!empty($codesrow['related_code']) && $code_type == 'MA') {
60 $relcodes = explode(';', $codesrow['related_code']);
61 foreach ($relcodes as $relstring) {
62 if ($relstring === '') continue;
63 list($reltype, $relcode) = explode(':', $relstring);
64 if ($reltype !== 'IPPF') continue;
65 if (preg_match('/^11....110/' , $relcode)) $contra |= 1;
66 else if (preg_match('/^11....999/' , $relcode)) $contra |= 1;
67 else if (preg_match('/^112152010/' , $relcode)) $contra |= 1;
68 else if (preg_match('/^11317[1-2]111/', $relcode)) $contra |= 1;
69 else if (preg_match('/^12118[1-2].13/', $relcode)) $contra |= 2;
70 else if (preg_match('/^12118[1-2]999/', $relcode)) $contra |= 2;
73 return $contra;
76 // This writes a billing line item to the output page.
78 function echoLine($lino, $codetype, $code, $modifier, $ndc_info='',
79 $auth = TRUE, $del = FALSE, $units = NULL, $fee = NULL, $id = NULL,
80 $billed = FALSE, $code_text = NULL, $justify = NULL, $provider_id = 0)
82 global $code_types, $ndc_applies, $ndc_uom_choices, $justinit, $pid;
83 global $contraception, $usbillstyle;
85 if ($codetype == 'COPAY') {
86 if (!$code_text) $code_text = 'Cash';
87 if ($fee > 0) $fee = 0 - $fee;
89 if (! $code_text) {
90 $query = "select id, units, code_text from codes where code_type = '" .
91 $code_types[$codetype]['id'] . "' and " .
92 "code = '$code' and ";
93 if ($modifier) {
94 $query .= "modifier = '$modifier'";
95 } else {
96 $query .= "(modifier is null or modifier = '')";
98 $result = sqlQuery($query);
99 $code_text = $result['code_text'];
100 if (empty($units)) $units = max(1, intval($result['units']));
101 if (!isset($fee)) {
102 // Fees come from the prices table now.
103 $query = "SELECT prices.pr_price " .
104 "FROM patient_data, prices WHERE " .
105 "patient_data.pid = '$pid' AND " .
106 "prices.pr_id = '" . $result['id'] . "' AND " .
107 "prices.pr_selector = '' AND " .
108 "prices.pr_level = patient_data.pricelevel " .
109 "LIMIT 1";
110 echo "\n<!-- $query -->\n"; // debugging
111 $prrow = sqlQuery($query);
112 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
115 $fee = sprintf('%01.2f', $fee);
116 if (empty($units)) $units = 1;
117 $units = max(1, intval($units));
118 // We put unit price on the screen, not the total line item fee.
119 $price = $fee / $units;
120 $strike1 = ($id && $del) ? "<strike>" : "";
121 $strike2 = ($id && $del) ? "</strike>" : "";
122 echo " <tr>\n";
123 echo " <td class='billcell'>$strike1" .
124 ($codetype == 'COPAY' ? xl($codetype) : $codetype) . $strike2;
125 if ($id) {
126 echo "<input type='hidden' name='bill[$lino][id]' value='$id'>";
128 echo "<input type='hidden' name='bill[$lino][code_type]' value='$codetype'>";
129 echo "<input type='hidden' name='bill[$lino][code]' value='$code'>";
130 echo "<input type='hidden' name='bill[$lino][billed]' value='$billed'>";
131 echo "</td>\n";
132 if ($codetype != 'COPAY') {
133 echo " <td class='billcell'>$strike1$code$strike2</td>\n";
134 } else {
135 echo " <td class='billcell'>&nbsp;</td>\n";
137 if ($billed) {
138 if (modifiers_are_used(true)) {
139 echo " <td class='billcell'>$strike1$modifier$strike2" .
140 "<input type='hidden' name='bill[$lino][mod]' value='$modifier'></td>\n";
142 if (fees_are_used()) {
143 echo " <td class='billcell' align='right'>" . oeFormatMoney($price) . "</td>\n";
144 if ($codetype != 'COPAY') {
145 echo " <td class='billcell' align='center'>$units</td>\n";
146 } else {
147 echo " <td class='billcell'>&nbsp;</td>\n";
149 echo " <td class='billcell' align='center'$usbillstyle>$justify</td>\n";
152 // Show provider for this line.
153 echo " <td class='billcell' align='center'>";
154 genProviderSelect('', '-- Default --', $provider_id, true);
155 echo "</td>\n";
156 echo " <td class='billcell' align='center'$usbillstyle><input type='checkbox'" .
157 ($auth ? " checked" : "") . " disabled /></td>\n";
158 echo " <td class='billcell' align='center'><input type='checkbox'" .
159 " disabled /></td>\n";
161 else { // not billed
162 if (modifiers_are_used(true)) {
163 if ($codetype != 'COPAY' && ($code_types[$codetype]['mod'] || $modifier)) {
164 echo " <td class='billcell'><input type='text' name='bill[$lino][mod]' " .
165 "value='$modifier' size='" . $code_types[$codetype]['mod'] . "'></td>\n";
166 } else {
167 echo " <td class='billcell'>&nbsp;</td>\n";
170 if (fees_are_used()) {
171 if ($codetype == 'COPAY' || $code_types[$codetype]['fee'] || $fee != 0) {
172 echo " <td class='billcell' align='right'>" .
173 "<input type='text' name='bill[$lino][price]' " .
174 "value='$price' size='6'";
175 if (acl_check('acct','disc'))
176 echo " style='text-align:right'";
177 else
178 echo " style='text-align:right;background-color:transparent' readonly";
179 echo "></td>\n";
180 echo " <td class='billcell' align='center'>";
181 if ($codetype != 'COPAY') {
182 echo "<input type='text' name='bill[$lino][units]' " .
183 "value='$units' size='2' style='text-align:right'>";
184 } else {
185 echo "<input type='hidden' name='bill[$lino][units]' value='$units'>";
187 echo "</td>\n";
188 if ($code_types[$codetype]['just'] || $justify) {
189 echo " <td class='billcell' align='center'$usbillstyle>";
190 echo "<select name='bill[$lino][justify]' onchange='setJustify(this)'>";
191 echo "<option value='$justify'>$justify</option></select>";
192 echo "</td>\n";
193 $justinit .= "setJustify(f['bill[$lino][justify]']);\n";
194 } else {
195 echo " <td class='billcell'$usbillstyle>&nbsp;</td>\n";
197 } else {
198 echo " <td class='billcell'>&nbsp;</td>\n";
199 echo " <td class='billcell'>&nbsp;</td>\n";
200 echo " <td class='billcell'$usbillstyle>&nbsp;</td>\n"; // justify
204 // Provider drop-list for this line.
205 echo " <td class='billcell' align='center'>";
206 genProviderSelect("bill[$lino][provid]", '-- Default --', $provider_id);
207 echo "</td>\n";
208 echo " <td class='billcell' align='center'$usbillstyle><input type='checkbox' name='bill[$lino][auth]' " .
209 "value='1'" . ($auth ? " checked" : "") . " /></td>\n";
210 echo " <td class='billcell' align='center'><input type='checkbox' name='bill[$lino][del]' " .
211 "value='1'" . ($del ? " checked" : "") . " /></td>\n";
214 echo " <td class='billcell'>$strike1" . ucfirst(strtolower($code_text)) . "$strike2</td>\n";
215 echo " </tr>\n";
217 // If NDC info exists or may be required, add a line for it.
218 if ($codetype == 'HCPCS' && $ndc_applies && !$billed) {
219 $ndcnum = ''; $ndcuom = ''; $ndcqty = '';
220 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
221 $ndcnum = $tmp[1]; $ndcuom = $tmp[2]; $ndcqty = $tmp[3];
223 echo " <tr>\n";
224 echo " <td class='billcell' colspan='2'>&nbsp;</td>\n";
225 echo " <td class='billcell' colspan='6'>&nbsp;NDC:&nbsp;";
226 echo "<input type='text' name='bill[$lino][ndcnum]' value='$ndcnum' " .
227 "size='11' style='background-color:transparent'>";
228 echo " &nbsp;Qty:&nbsp;";
229 echo "<input type='text' name='bill[$lino][ndcqty]' value='$ndcqty' " .
230 "size='3' style='background-color:transparent;text-align:right'>";
231 echo " ";
232 echo "<select name='bill[$lino][ndcuom]' style='background-color:transparent'>";
233 foreach ($ndc_uom_choices as $key => $value) {
234 echo "<option value='$key'";
235 if ($key == $ndcuom) echo " selected";
236 echo ">$value</option>";
238 echo "</select>";
239 echo "</td>\n";
240 echo " </tr>\n";
242 else if ($ndc_info) {
243 echo " <tr>\n";
244 echo " <td class='billcell' colspan='2'>&nbsp;</td>\n";
245 echo " <td class='billcell' colspan='6'>&nbsp;NDC Data: $ndc_info</td>\n";
246 echo " </tr>\n";
249 // For IPPF. Track contraceptive services.
250 if (!$del) $contraception |= contraceptionClass($codetype, $code);
253 // This writes a product (drug_sales) line item to the output page.
255 function echoProdLine($lino, $drug_id, $del = FALSE, $units = NULL,
256 $fee = NULL, $sale_id = 0, $billed = FALSE)
258 global $code_types, $ndc_applies, $pid, $usbillstyle;
260 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = '$drug_id'");
261 $code_text = $drow['name'];
263 $fee = sprintf('%01.2f', $fee);
264 if (empty($units)) $units = 1;
265 $units = max(1, intval($units));
266 // We put unit price on the screen, not the total line item fee.
267 $price = $fee / $units;
268 $strike1 = ($sale_id && $del) ? "<strike>" : "";
269 $strike2 = ($sale_id && $del) ? "</strike>" : "";
270 echo " <tr>\n";
271 echo " <td class='billcell'>{$strike1}Product$strike2";
272 echo "<input type='hidden' name='prod[$lino][sale_id]' value='$sale_id'>";
273 echo "<input type='hidden' name='prod[$lino][drug_id]' value='$drug_id'>";
274 echo "<input type='hidden' name='prod[$lino][billed]' value='$billed'>";
275 echo "</td>\n";
276 echo " <td class='billcell'>$strike1$drug_id$strike2</td>\n";
277 if (modifiers_are_used(true)) {
278 echo " <td class='billcell'>&nbsp;</td>\n";
280 if ($billed) {
281 if (fees_are_used()) {
282 echo " <td class='billcell' align='right'>" . oeFormatMoney($price) . "</td>\n";
283 echo " <td class='billcell' align='center'>$units</td>\n";
284 echo " <td class='billcell' align='center'$usbillstyle>&nbsp;</td>\n"; // justify
286 echo " <td class='billcell' align='center'>&nbsp;</td>\n"; // provider
287 echo " <td class='billcell' align='center'$usbillstyle>&nbsp;</td>\n"; // auth
288 echo " <td class='billcell' align='center'><input type='checkbox'" . // del
289 " disabled /></td>\n";
290 } else {
291 if (fees_are_used()) {
292 echo " <td class='billcell' align='right'>" .
293 "<input type='text' name='prod[$lino][price]' " .
294 "value='$price' size='6'";
295 if (acl_check('acct','disc'))
296 echo " style='text-align:right'";
297 else
298 echo " style='text-align:right;background-color:transparent' readonly";
299 echo "></td>\n";
300 echo " <td class='billcell' align='center'>";
301 echo "<input type='text' name='prod[$lino][units]' " .
302 "value='$units' size='2' style='text-align:right'>";
303 echo "</td>\n";
304 echo " <td class='billcell'$usbillstyle>&nbsp;</td>\n"; // justify
306 echo " <td class='billcell' align='center'>&nbsp;</td>\n"; // provider
307 echo " <td class='billcell' align='center'$usbillstyle>&nbsp;</td>\n"; // auth
308 echo " <td class='billcell' align='center'><input type='checkbox' name='prod[$lino][del]' " .
309 "value='1'" . ($del ? " checked" : "") . " /></td>\n";
312 echo " <td class='billcell'>$strike1" . ucfirst(strtolower($code_text)) . "$strike2</td>\n";
313 echo " </tr>\n";
316 // Build a drop-down list of providers. This includes users who
317 // have the word "provider" anywhere in their "additional info"
318 // field, so that we can define providers (for billing purposes)
319 // who do not appear in the calendar.
321 function genProviderSelect($selname, $toptext, $default=0, $disabled=false) {
322 $query = "SELECT id, lname, fname FROM users WHERE " .
323 "( authorized = 1 OR info LIKE '%provider%' ) AND username != '' " .
324 "AND active = 1 AND ( info IS NULL OR info NOT LIKE '%Inactive%' ) " .
325 "ORDER BY lname, fname";
326 $res = sqlStatement($query);
327 echo " <select name='$selname'";
328 if ($disabled) echo " disabled";
329 echo ">\n";
330 echo " <option value=''>$toptext\n";
331 while ($row = sqlFetchArray($res)) {
332 $provid = $row['id'];
333 echo " <option value='$provid'";
334 if ($provid == $default) echo " selected";
335 echo ">" . $row['lname'] . ", " . $row['fname'] . "\n";
337 echo " </select>\n";
340 // This is just for IPPF, to indicate if the visit includes contraceptive services.
341 $contraception = 0;
343 // Possible units of measure for NDC drug quantities.
345 $ndc_uom_choices = array(
346 'ML' => 'ML',
347 'GR' => 'Grams',
348 'ME' => 'Milligrams',
349 'F2' => 'I.U.',
350 'UN' => 'Units'
353 // $FEE_SHEET_COLUMNS should be defined in codes.php.
354 if (empty($FEE_SHEET_COLUMNS)) $FEE_SHEET_COLUMNS = 2;
356 $returnurl = $GLOBALS['concurrent_layout'] ? 'encounter_top.php' : 'patient_encounter.php';
358 // Update price level in patient demographics.
359 if (!empty($_POST['pricelevel'])) {
360 sqlStatement("UPDATE patient_data SET pricelevel = '" .
361 $_POST['pricelevel'] . "' WHERE pid = '$pid'");
364 // Get some info about this visit.
365 $visit_row = sqlQuery("SELECT fe.date, opc.pc_catname " .
366 "FROM form_encounter AS fe " .
367 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
368 "WHERE fe.pid = '$pid' AND fe.encounter = '$encounter' LIMIT 1");
369 $visit_date = substr($visit_row['date'], 0, 10);
371 // If Save was clicked, save the new and modified billing lines;
372 // then if no error, redirect to $returnurl.
374 if ($_POST['bn_save']) {
375 $main_provid = 0 + $_POST['ProviderID'];
376 $main_supid = 0 + $_POST['SupervisorID'];
377 if ($main_supid == $main_provid) $main_supid = 0;
378 $default_warehouse = $_POST['default_warehouse'];
380 $bill = $_POST['bill'];
381 for ($lino = 1; $bill["$lino"]['code_type']; ++$lino) {
382 $iter = $bill["$lino"];
383 $code_type = $iter['code_type'];
384 $code = $iter['code'];
385 $del = $iter['del'];
387 // Get some information about this service code.
388 $codesrow = sqlQuery("SELECT code_text FROM codes WHERE " .
389 "code_type = '" . $code_types[$code_type]['id'] .
390 "' AND code = '$code' LIMIT 1");
392 // Skip disabled (billed) line items.
393 if ($iter['billed']) continue;
395 $id = $iter['id'];
396 $modifier = trim($iter['mod']);
397 $units = max(1, intval(trim($iter['units'])));
398 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
399 if ($code_type == 'COPAY') {
400 if ($fee > 0) $fee = 0 - $fee;
401 $code = sprintf('%01.2f', 0 - $fee);
403 $justify = trim($iter['justify']);
404 if ($justify) $justify = str_replace(',', ':', $justify) . ':';
405 // $auth = $iter['auth'] ? "1" : "0";
406 $auth = "1";
407 $provid = 0 + $iter['provid'];
409 $ndc_info = '';
410 if ($iter['ndcnum']) {
411 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
412 trim($iter['ndcqty']);
415 // If the item is already in the database...
416 if ($id) {
417 if ($del) {
418 deleteBilling($id);
420 else {
421 // authorizeBilling($id, $auth);
422 sqlQuery("UPDATE billing SET code = '$code', " .
423 "units = '$units', fee = '$fee', modifier = '$modifier', " .
424 "authorized = $auth, provider_id = '$provid', " .
425 "ndc_info = '$ndc_info', justify = '$justify' WHERE " .
426 "id = '$id' AND billed = 0 AND activity = 1");
430 // Otherwise it's a new item...
431 else if (! $del) {
432 $code_text = addslashes($codesrow['code_text']);
433 addBilling($encounter, $code_type, $code, $code_text, $pid, $auth,
434 $provid, $modifier, $units, $fee, $ndc_info, $justify);
436 } // end for
438 // Doing similarly to the above but for products.
439 $prod = $_POST['prod'];
440 for ($lino = 1; $prod["$lino"]['drug_id']; ++$lino) {
441 $iter = $prod["$lino"];
443 if (!empty($iter['billed'])) continue;
445 $drug_id = $iter['drug_id'];
446 $sale_id = $iter['sale_id']; // present only if already saved
447 $units = max(1, intval(trim($iter['units'])));
448 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
449 $del = $iter['del'];
451 // If the item is already in the database...
452 if ($sale_id) {
453 if ($del) {
454 // Zero out this sale and reverse its inventory update. We bring in
455 // drug_sales twice so that the original quantity can be referenced
456 // unambiguously.
457 sqlStatement("UPDATE drug_sales AS dsr, drug_sales AS ds, " .
458 "drug_inventory AS di " .
459 "SET di.on_hand = di.on_hand + dsr.quantity, " .
460 "ds.quantity = 0, ds.fee = 0 WHERE " .
461 "dsr.sale_id = '$sale_id' AND ds.sale_id = dsr.sale_id AND " .
462 "di.inventory_id = ds.inventory_id");
463 // And delete the sale for good measure.
464 sqlStatement("DELETE FROM drug_sales WHERE sale_id = '$sale_id'");
466 else {
467 // Modify the sale and adjust inventory accordingly.
468 $query = "UPDATE drug_sales AS dsr, drug_sales AS ds, " .
469 "drug_inventory AS di " .
470 "SET di.on_hand = di.on_hand + dsr.quantity - $units, " .
471 "ds.quantity = '$units', ds.fee = '$fee', " .
472 "ds.sale_date = '$visit_date' WHERE " .
473 "dsr.sale_id = '$sale_id' AND ds.sale_id = dsr.sale_id AND " .
474 "di.inventory_id = ds.inventory_id";
475 sqlStatement($query);
479 // Otherwise it's a new item...
480 else if (! $del) {
481 $sale_id = sellDrug($drug_id, $units, $fee, $pid, $encounter, 0,
482 $visit_date, '', $default_warehouse);
483 if (!$sale_id) die("Insufficient inventory for product ID \"$drug_id\".");
485 } // end for
487 // Set the main/default service provider in the new-encounter form.
488 /*******************************************************************
489 sqlStatement("UPDATE forms, users SET forms.user = users.username WHERE " .
490 "forms.pid = '$pid' AND forms.encounter = '$encounter' AND " .
491 "forms.formdir = 'newpatient' AND users.id = '$provid'");
492 *******************************************************************/
493 sqlStatement("UPDATE form_encounter SET provider_id = '$main_provid', " .
494 "supervisor_id = '$main_supid' WHERE " .
495 "pid = '$pid' AND encounter = '$encounter'");
497 // More IPPF stuff.
498 if (!empty($_POST['contrastart'])) {
499 $contrastart = $_POST['contrastart'];
500 sqlStatement("UPDATE patient_data SET contrastart = '" .
501 $contrastart . "' WHERE pid = '$pid'");
504 // Note: Taxes are computed at checkout time (in pos_checkout.php which
505 // also posts to SL). Currently taxes with insurance claims make no sense,
506 // so for now we'll ignore tax computation in the insurance billing logic.
508 formHeader("Redirecting....");
509 formJump();
510 formFooter();
511 exit;
514 $billresult = getBillingByEncounter($pid, $encounter, "*");
516 <html>
517 <head>
518 <?php html_header_show(); ?>
519 <link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css">
520 <style>
521 .billcell { font-family: sans-serif; font-size: 10pt }
522 </style>
523 <script language="JavaScript">
525 var diags = new Array();
527 <?php
528 if ($billresult) {
529 foreach ($billresult as $iter) {
530 genDiagJS($iter["code_type"], trim($iter["code"]));
533 if ($_POST['bill']) {
534 foreach ($_POST['bill'] as $iter) {
535 if ($iter["del"]) continue; // skip if Delete was checked
536 if ($iter["id"]) continue; // skip if it came from the database
537 genDiagJS($iter["code_type"], $iter["code"]);
540 if ($_POST['newcodes']) {
541 $arrcodes = explode('~', $_POST['newcodes']);
542 foreach ($arrcodes as $codestring) {
543 if ($codestring === '') continue;
544 $arrcode = explode('|', $codestring);
545 list($code, $modifier) = explode(":", $arrcode[1]);
546 genDiagJS($arrcode[0], $code);
551 // This is invoked by <select onchange> for the various dropdowns,
552 // including search results.
553 function codeselect(selobj) {
554 var i = selobj.selectedIndex;
555 if (i > 0) {
556 top.restoreSession();
557 var f = document.forms[0];
558 f.newcodes.value = selobj.options[i].value;
559 f.submit();
563 function copayselect() {
564 top.restoreSession();
565 var f = document.forms[0];
566 f.newcodes.value = 'COPAY||';
567 f.submit();
570 function validate(f) {
571 for (var lino = 1; f['bill['+lino+'][code_type]']; ++lino) {
572 var pfx = 'bill['+lino+']';
573 if (f[pfx+'[ndcnum]'] && f[pfx+'[ndcnum]'].value) {
574 // Check NDC number format.
575 var ndcok = true;
576 var ndc = f[pfx+'[ndcnum]'].value;
577 var a = ndc.split('-');
578 if (a.length != 3) {
579 ndcok = false;
581 else if (a[0].length < 1 || a[1].length < 1 || a[2].length < 1 ||
582 a[0].length > 5 || a[1].length > 4 || a[2].length > 2) {
583 ndcok = false;
585 else {
586 for (var i = 0; i < 3; ++i) {
587 for (var j = 0; j < a[i].length; ++j) {
588 var c = a[i].charAt(j);
589 if (c < '0' || c > '9') ndcok = false;
593 if (!ndcok) {
594 alert('<?php xl('Format incorrect for NDC','e') ?> "' + ndc +
595 '", <?php xl('should be like nnnnn-nnnn-nn','e') ?>');
596 if (f[pfx+'[ndcnum]'].focus) f[pfx+'[ndcnum]'].focus();
597 return false;
599 // Check for valid quantity.
600 var qty = f[pfx+'[ndcqty]'].value - 0;
601 if (isNaN(qty) || qty <= 0) {
602 alert('<?php xl('Quantity for NDC','e') ?> "' + ndc +
603 '" <?php xl('is not valid (decimal fractions are OK).','e') ?>');
604 if (f[pfx+'[ndcqty]'].focus) f[pfx+'[ndcqty]'].focus();
605 return false;
609 top.restoreSession();
610 return true;
613 // When a justify selection is made, apply it to the current list for
614 // this procedure and then rebuild its selection list.
616 function setJustify(seljust) {
617 var theopts = seljust.options;
618 var jdisplay = theopts[0].text;
619 // Compute revised justification string. Note this does nothing if
620 // the first entry is still selected, which is handy at startup.
621 if (seljust.selectedIndex > 0) {
622 var newdiag = seljust.value;
623 if (newdiag.length == 0) {
624 jdisplay = '';
626 else {
627 if (jdisplay.length) jdisplay += ',';
628 jdisplay += newdiag;
631 // Rebuild selection list.
632 var jhaystack = ',' + jdisplay + ',';
633 var j = 0;
634 theopts.length = 0;
635 theopts[j++] = new Option(jdisplay,jdisplay,true,true);
636 for (var i = 0; i < diags.length; ++i) {
637 if (jhaystack.indexOf(',' + diags[i] + ',') < 0) {
638 theopts[j++] = new Option(diags[i],diags[i],false,false);
641 theopts[j++] = new Option('Clear','',false,false);
644 </script>
645 </head>
647 <body class="body_top">
648 <form method="post" action="<?php echo $rootdir; ?>/forms/fee_sheet/new.php"
649 onsubmit="return validate(this)">
650 <span class="title"><?php xl('Fee Sheet','e'); ?></span><br>
651 <input type='hidden' name='newcodes' value=''>
653 <center>
655 <?php
656 $isBilled = isEncounterBilled($pid, $encounter);
657 if ($isBilled) {
658 echo "<p><font color='green'>This encounter has been billed. If you " .
659 "need to change it, it must be re-opened.</font></p>\n";
661 else { // the encounter is not yet billed
664 <table width='95%'>
665 <?php
666 $i = 0;
667 $last_category = '';
669 // Create drop-lists based on the fee_sheet_options table.
670 $res = sqlStatement("SELECT * FROM fee_sheet_options " .
671 "ORDER BY fs_category, fs_option");
672 while ($row = sqlFetchArray($res)) {
673 $fs_category = $row['fs_category'];
674 $fs_option = $row['fs_option'];
675 $fs_codes = $row['fs_codes'];
676 if($fs_category !== $last_category) {
677 endFSCategory();
678 $last_category = $fs_category;
679 ++$i;
680 echo ($i <= 1) ? " <tr>\n" : "";
681 echo " <td width='50%' align='center' nowrap>\n";
682 echo " <select style='width:96%' onchange='codeselect(this)'>\n";
683 echo " <option value=''> " . substr($fs_category, 1) . "</option>\n";
685 echo " <option value='$fs_codes'>" . substr($fs_option, 1) . "</option>\n";
687 endFSCategory();
689 // Create drop-lists based on categories defined within the codes.
690 $pres = sqlStatement("SELECT option_id, title FROM list_options " .
691 "WHERE list_id = 'superbill' ORDER BY seq");
692 while ($prow = sqlFetchArray($pres)) {
693 global $code_types;
694 ++$i;
695 echo ($i <= 1) ? " <tr>\n" : "";
696 echo " <td width='50%' align='center' nowrap>\n";
697 echo " <select style='width:96%' onchange='codeselect(this)'>\n";
698 echo " <option value=''> " . $prow['title'] . "\n";
699 $res = sqlStatement("SELECT code_type, code, code_text,modifier FROM codes " .
700 "WHERE superbill = '" . $prow['option_id'] . "' AND active = 1 " .
701 "ORDER BY code_text");
702 while ($row = sqlFetchArray($res)) {
703 $ctkey = alphaCodeType($row['code_type']);
704 if ($code_types[$ctkey]['nofs']) continue;
705 echo " <option value='$ctkey|" .
706 $row['code'] . ':'. $row['modifier']. "|'>" . $row['code_text'] . "</option>\n";
708 echo " </select>\n";
709 echo " </td>\n";
710 if ($i >= $FEE_SHEET_COLUMNS) {
711 echo " </tr>\n";
712 $i = 0;
716 // Create one more drop-list, for Products.
717 if ($GLOBALS['sell_non_drug_products']) {
718 ++$i;
719 echo ($i <= 1) ? " <tr>\n" : "";
720 echo " <td width='50%' align='center' nowrap>\n";
721 echo " <select name='Products' style='width:96%' onchange='codeselect(this)'>\n";
722 echo " <option value=''> " . xl('Products') . "\n";
723 $tres = sqlStatement("SELECT dt.drug_id, dt.selector, d.name " .
724 "FROM drug_templates AS dt, drugs AS d WHERE " .
725 "d.drug_id = dt.drug_id AND d.active = 1 " .
726 "ORDER BY d.name, dt.selector, dt.drug_id");
727 while ($trow = sqlFetchArray($tres)) {
728 echo " <option value='PROD|" . $trow['drug_id'] . '|' . $trow['selector'] . "'>" .
729 $trow['drug_id'] . ':' . $trow['selector'];
730 if ($trow['name'] !== $trow['selector']) echo ' ' . $trow['name'];
731 echo "</option>\n";
733 echo " </select>\n";
734 echo " </td>\n";
735 if ($i >= $FEE_SHEET_COLUMNS) {
736 echo " </tr>\n";
737 $i = 0;
741 $search_type = $default_search_type;
742 if ($_POST['search_type']) $search_type = $_POST['search_type'];
744 $ndc_applies = true; // Assume all payers require NDC info.
746 echo $i ? " <td></td>\n </tr>\n" : "";
747 echo " <tr>\n";
748 echo " <td colspan='$FEE_SHEET_COLUMNS' align='center' nowrap>\n";
750 // If Search was clicked, do it and write the list of results here.
751 // There's no limit on the number of results!
753 $numrows = 0;
754 if ($_POST['bn_search'] && $_POST['search_term']) {
755 $query = "SELECT code, modifier, code_text FROM codes WHERE " .
756 "(code_text LIKE '%" . $_POST['search_term'] . "%' OR " .
757 "code LIKE '%" . $_POST['search_term'] . "%') AND " .
758 "code_type = '" . $code_types[$search_type]['id'] . "' " .
759 "AND active = 1 ORDER BY code";
760 $res = sqlStatement($query);
761 $numrows = mysql_num_rows($res); // FIXME - not portable!
764 echo " <select name='Search Results' style='width:98%' " .
765 "onchange='codeselect(this)'";
766 if (! $numrows) echo ' disabled';
767 echo ">\n";
768 echo " <option value=''> Search Results ($numrows items)\n";
770 if ($numrows) {
771 while ($row = sqlFetchArray($res)) {
772 $code = $row['code'];
773 if ($row['modifier']) $code .= ":" . $row['modifier'];
774 echo " <option value='$search_type|$code|'>$code " .
775 ucfirst(strtolower($row['code_text'])) . "</option>\n";
779 echo " </select>\n";
780 echo " </td>\n";
781 echo " </tr>\n";
784 </table>
786 <p style='margin-top:8px;margin-bottom:8px'>
787 <table>
788 <tr>
789 <td>
790 <input type='button' value='<?php xl('Add Copay','e');?>'
791 onclick="copayselect()" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
792 </td>
793 <td>
794 <?php xl('Search','e'); ?>&nbsp;
795 <?php
796 foreach ($code_types as $key => $value) {
797 if (!empty($value['nofs'])) continue;
798 echo " <input type='radio' name='search_type' value='$key'";
799 if ($key == $default_search_type) echo " checked";
800 echo " />$key&nbsp;\n";
803 <?php xl('for','e'); ?>&nbsp;
804 </td>
805 <td>
806 <input type='text' name='search_term' value=''> &nbsp;
807 </td>
808 <td>
809 <input type='submit' name='bn_search' value='<?php xl('Search','e');?>'>
810 </td>
811 </tr>
812 </table>
813 </p>
814 <p style='margin-top:16px;margin-bottom:8px'>
816 <?php } // end encounter not billed ?>
818 <table cellspacing='5'>
819 <tr>
820 <td class='billcell'><b><?php xl('Type','e');?></b></td>
821 <td class='billcell'><b><?php xl('Code','e');?></b></td>
822 <?php if (modifiers_are_used(true)) { ?>
823 <td class='billcell'><b><?php xl('Mod','e');?></b></td>
824 <?php } ?>
825 <?php if (fees_are_used()) { ?>
826 <td class='billcell' align='right'><b><?php xl('Price','e');?></b>&nbsp;</td>
827 <td class='billcell' align='center'><b><?php xl('Units','e');?></b></td>
828 <td class='billcell' align='center'<?php echo $usbillstyle; ?>><b><?php xl('Justify','e');?></b></td>
829 <?php } ?>
830 <td class='billcell' align='center'><b><?php xl('Provider','e');?></b></td>
831 <td class='billcell' align='center'<?php echo $usbillstyle; ?>><b><?php xl('Auth','e');?></b></td>
832 <td class='billcell' align='center'><b><?php xl('Delete','e');?></b></td>
833 <td class='billcell'><b><?php xl('Description','e');?></b></td>
834 </tr>
836 <?php
837 $justinit = "var f = document.forms[0];\n";
839 // $encounter_provid = -1;
841 // Generate lines for items already in the billing table for this encounter,
842 // and also set the rendering provider if we come across one.
844 $bill_lino = 0;
845 if ($billresult) {
846 foreach ($billresult as $iter) {
847 ++$bill_lino;
848 $bline = $_POST['bill']["$bill_lino"];
849 $del = $bline['del']; // preserve Delete if checked
851 $modifier = trim($iter["modifier"]);
852 $units = $iter["units"];
853 $fee = $iter["fee"];
854 $authorized = $iter["authorized"];
855 $ndc_info = $iter["ndc_info"];
856 $justify = trim($iter['justify']);
857 if ($justify) $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
858 $provider_id = $iter['provider_id'];
860 // Also preserve other items from the form, if present.
861 if ($bline['id'] && !$iter["billed"]) {
862 $modifier = trim($bline['mod']);
863 $units = max(1, intval(trim($bline['units'])));
864 $fee = sprintf('%01.2f',(0 + trim($bline['price'])) * $units);
865 $authorized = $bline['auth'];
866 $ndc_info = '';
867 if ($bline['ndcnum']) {
868 $ndc_info = 'N4' . trim($bline['ndcnum']) . ' ' . $bline['ndcuom'] .
869 trim($bline['ndcqty']);
871 $justify = $bline['justify'];
872 $provider_id = 0 + $bline['provid'];
875 // list($code, $modifier) = explode("-", $iter["code"]);
876 echoLine($bill_lino, $iter["code_type"], trim($iter["code"]),
877 $modifier, $ndc_info, $authorized,
878 $del, $units, $fee, $iter["id"], $iter["billed"],
879 $iter["code_text"], $justify, $provider_id);
883 // Echo new billing items from this form here, but omit any line
884 // whose Delete checkbox is checked.
886 if ($_POST['bill']) {
887 foreach ($_POST['bill'] as $key => $iter) {
888 if ($iter["id"]) continue; // skip if it came from the database
889 if ($iter["del"]) continue; // skip if Delete was checked
890 $ndc_info = '';
891 if ($iter['ndcnum']) {
892 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
893 trim($iter['ndcqty']);
895 // $fee = 0 + trim($iter['fee']);
896 $units = max(1, intval(trim($iter['units'])));
897 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
898 if ($iter['code_type'] == 'COPAY' && $fee > 0) $fee = 0 - $fee;
899 echoLine(++$bill_lino, $iter["code_type"], $iter["code"], trim($iter["mod"]),
900 $ndc_info, $iter["auth"], $iter["del"], $units,
901 $fee, NULL, FALSE, NULL, $iter["justify"], 0 + $iter['provid']);
905 // Generate lines for items already in the drug_sales table for this encounter.
907 $query = "SELECT * FROM drug_sales WHERE " .
908 "pid = '$pid' AND encounter = '$encounter' " .
909 "ORDER BY sale_id";
910 $sres = sqlStatement($query);
911 $prod_lino = 0;
912 while ($srow = sqlFetchArray($sres)) {
913 ++$prod_lino;
914 $pline = $_POST['prod']["$prod_lino"];
915 $del = $pline['del']; // preserve Delete if checked
916 $sale_id = $srow['sale_id'];
917 $drug_id = $srow['drug_id'];
918 $units = $srow['quantity'];
919 $fee = $srow['fee'];
920 $billed = $srow['billed'];
921 // Also preserve other items from the form, if present and unbilled.
922 if ($pline['sale_id'] && !$srow['billed']) {
923 // $units = trim($pline['units']);
924 // $fee = trim($pline['fee']);
925 $units = max(1, intval(trim($pline['units'])));
926 $fee = sprintf('%01.2f',(0 + trim($pline['price'])) * $units);
928 echoProdLine($prod_lino, $drug_id, $del, $units, $fee, $sale_id, $billed);
931 // Echo new product items from this form here, but omit any line
932 // whose Delete checkbox is checked.
934 if ($_POST['prod']) {
935 foreach ($_POST['prod'] as $key => $iter) {
936 if ($iter["sale_id"]) continue; // skip if it came from the database
937 if ($iter["del"]) continue; // skip if Delete was checked
938 // $fee = 0 + trim($iter['fee']);
939 $units = max(1, intval(trim($iter['units'])));
940 $fee = sprintf('%01.2f',(0 + trim($iter['price'])) * $units);
941 echoProdLine(++$prod_lino, $iter['drug_id'], FALSE, $units, $fee);
945 // If new billing code(s) were <select>ed, add their line(s) here.
947 if ($_POST['newcodes']) {
948 $arrcodes = explode('~', $_POST['newcodes']);
949 foreach ($arrcodes as $codestring) {
950 if ($codestring === '') continue;
951 $arrcode = explode('|', $codestring);
952 $newtype = $arrcode[0];
953 $newcode = $arrcode[1];
954 $newsel = $arrcode[2];
955 if ($newtype == 'COPAY') {
956 $tmp = sqlQuery("SELECT copay FROM insurance_data WHERE pid = '$pid' " .
957 "AND type = 'primary' ORDER BY date DESC LIMIT 1");
958 $code = sprintf('%01.2f', 0 + $tmp['copay']);
959 echoLine(++$bill_lino, $newtype, $code, '', '', '1', '0', '1',
960 sprintf('%01.2f', 0 - $code));
962 else if ($newtype == 'PROD') {
963 $result = sqlQuery("SELECT * FROM drug_templates WHERE " .
964 "drug_id = '$newcode' AND selector = '$newsel'");
965 $units = max(1, intval($result['quantity']));
966 $prrow = sqlQuery("SELECT prices.pr_price " .
967 "FROM patient_data, prices WHERE " .
968 "patient_data.pid = '$pid' AND " .
969 "prices.pr_id = '$newcode' AND " .
970 "prices.pr_selector = '$newsel' AND " .
971 "prices.pr_level = patient_data.pricelevel " .
972 "LIMIT 1");
973 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
974 echoProdLine(++$prod_lino, $newcode, FALSE, $units, $fee);
976 else {
977 list($code, $modifier) = explode(":", $newcode);
978 $ndc_info = '';
979 // If HCPCS, find last NDC string used for this code.
980 if ($newtype == 'HCPCS' && $ndc_applies) {
981 $tmp = sqlQuery("SELECT ndc_info FROM billing WHERE " .
982 "code_type = '$newtype' AND code = '$code' AND ndc_info LIKE 'N4%' " .
983 "ORDER BY date DESC LIMIT 1");
984 if (!empty($tmp)) $ndc_info = $tmp['ndc_info'];
986 echoLine(++$bill_lino, $newtype, $code, trim($modifier), $ndc_info);
991 $tmp = sqlQuery("SELECT provider_id, supervisor_id FROM form_encounter " .
992 "WHERE pid = '$pid' AND encounter = '$encounter' " .
993 "ORDER BY id DESC LIMIT 1");
994 $encounter_provid = 0 + $tmp['provider_id'];
995 $encounter_supid = 0 + $tmp['supervisor_id'];
997 </table>
998 </p>
1000 <br />
1001 &nbsp;
1003 <?php
1004 // Choose rendering and supervising providers.
1005 echo "<span class='billcell'><b>\n";
1006 echo xl('Providers') . ": &nbsp;";
1008 echo "&nbsp;&nbsp;" . xl('Rendering') . "\n";
1009 genProviderSelect('ProviderID', '-- Please Select --', $encounter_provid, $isBilled);
1011 if (!$GLOBALS['ippf_specific']) {
1012 echo "&nbsp;&nbsp;" . xl('Supervising') . "\n";
1013 genProviderSelect('SupervisorID', '-- N/A --', $encounter_supid, $isBilled);
1016 echo "</b></span>\n";
1020 &nbsp;
1022 <?php
1023 // If applicable, ask for the contraceptive services start date.
1024 $trow = sqlQuery("SELECT count(*) AS count FROM layout_options WHERE " .
1025 "form_id = 'DEM' AND field_id = 'contrastart' AND uor > 0");
1026 if ($trow['count'] && $contraception && !$isBilled) {
1027 $date1 = substr($visit_row['date'], 0, 10);
1028 // If admission or surgical, then force contrastart.
1029 if ($contraception > 1 ||
1030 strpos(strtolower($visit_row['pc_catname']), 'admission') !== false)
1032 echo " <input type='hidden' name='contrastart' value='$date1' />\n";
1034 else {
1035 // echo "<!-- contraception = $contraception -->\n"; // debugging
1036 $trow = sqlQuery("SELECT contrastart " .
1037 "FROM patient_data WHERE " .
1038 "pid = '$pid' LIMIT 1");
1039 if (empty($trow['contrastart']) || substr($trow['contrastart'], 0, 4) == '0000') {
1040 $date0 = date('Y-m-d', strtotime($date1) - (60 * 60 * 24));
1041 echo " <select name='contrastart'>\n";
1042 echo " <option value='$date1'>" . xl('This visit begins new contraceptive use') . "</option>\n";
1043 echo " <option value='$date0'>" . xl('Contraceptive services previously started') . "</option>\n";
1044 echo " <option value=''>" . xl('None of the above') . "</option>\n";
1045 echo " </select>\n";
1046 echo "&nbsp; &nbsp; &nbsp;\n";
1051 // If there is a choice of warehouses, allow override of user default.
1052 if ($prod_lino > 0) { // if any products are in this form
1053 $trow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse'");
1054 if ($trow['count'] > 1) {
1055 $trow = sqlQuery("SELECT default_warehouse FROM users WHERE username = '" .
1056 $_SESSION['authUser'] . "'");
1057 echo " <span class='billcell'><b>" . xl('Warehouse') . ":</b></span>\n";
1058 echo generate_select_list('default_warehouse', 'warehouse',
1059 $trow['default_warehouse'], '');
1060 echo "&nbsp; &nbsp; &nbsp;\n";
1064 // Allow the patient price level to be fixed here.
1065 $plres = sqlStatement("SELECT option_id, title FROM list_options " .
1066 "WHERE list_id = 'pricelevel' ORDER BY seq");
1067 if (true) {
1068 $trow = sqlQuery("SELECT pricelevel FROM patient_data WHERE " .
1069 "pid = '$pid' LIMIT 1");
1070 $pricelevel = $trow['pricelevel'];
1071 echo " <span class='billcell'><b>" . xl('Price Level') . ":</b></span>\n";
1072 echo " <select name='pricelevel'";
1073 if ($isBilled) echo " disabled";
1074 echo ">\n";
1075 while ($plrow = sqlFetchArray($plres)) {
1076 $key = $plrow['option_id'];
1077 $val = $plrow['title'];
1078 echo " <option value='$key'";
1079 if ($key == $pricelevel) echo ' selected';
1080 echo ">$val</option>\n";
1082 echo " </select>\n";
1086 &nbsp; &nbsp; &nbsp;
1088 <?php if (!$isBilled) { ?>
1089 <input type='submit' name='bn_save' value='<?php xl('Save','e');?>' />
1090 &nbsp;
1091 <input type='submit' name='bn_refresh' value='<?php xl('Refresh','e');?>'>
1092 &nbsp;
1093 <?php } ?>
1095 <input type='button' value='<?php xl('Cancel','e');?>'
1096 onclick="top.restoreSession();location='<?php echo "$rootdir/patient_file/encounter/$returnurl" ?>'" />
1098 <?php if ($code_types['UCSMC']) { ?>
1099 <p style='font-family:sans-serif;font-size:8pt;color:#666666;'>
1100 &nbsp;<br>
1101 <?php xl('UCSMC codes provided by the University of Calgary Sports Medicine Centre','e');?>
1102 </p>
1103 <?php } ?>
1105 </center>
1107 </form>
1109 <?php
1110 // TBD: If $alertmsg, display it with a JavaScript alert().
1113 <script language='JavaScript'>
1114 <?php echo $justinit; ?>
1115 </script>
1117 </body>
1118 </html>