Added access controls for encounter categories
[openemr.git] / library / FeeSheet.class.php
blobe6b7ed3158795ac1a61312724ef5363a827a98d3
1 <?php
2 /**
3 * library/FeeSheet.class.php
5 * Base class for implementations of the Fee Sheet.
6 * This should not include UI but may be extended by a class that does.
8 * LICENSE: This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 3
11 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see
18 * http://www.gnu.org/licenses/licenses.html#GPL .
20 * @package OpenEMR
21 * @license http://www.gnu.org/licenses/licenses.html#GPL GNU GPL V3+
22 * @author Rod Roark <rod@sunsetsystems.com>
23 * @link http://www.open-emr.org
30 require_once(dirname(__FILE__) . "/../interface/globals.php");
31 require_once(dirname(__FILE__) . "/acl.inc");
32 require_once(dirname(__FILE__) . "/../custom/code_types.inc.php");
33 require_once(dirname(__FILE__) . "/../interface/drugs/drugs.inc.php");
34 require_once(dirname(__FILE__) . "/options.inc.php");
35 require_once(dirname(__FILE__) . "/appointment_status.inc.php");
36 require_once(dirname(__FILE__) . "/classes/Prescription.class.php");
37 require_once(dirname(__FILE__) . "/forms.inc");
38 require_once(dirname(__FILE__) . "/log.inc");
39 // For logging checksums set this to true.
40 define('CHECKSUM_LOGGING', true);
42 // require_once(dirname(__FILE__) . "/api.inc");
43 // require_once(dirname(__FILE__) . "/forms.inc");
45 class FeeSheet {
47 public $pid; // patient id
48 public $encounter; // encounter id
49 public $got_warehouses = false; // if there is more than 1 warehouse
50 public $default_warehouse = ''; // logged-in user's default warehouse
51 public $visit_date = ''; // YYYY-MM-DD date of this visit
52 public $match_services_to_products = false; // For IPPF
53 public $patient_age = 0; // Age in years as of the visit date
54 public $patient_male = 0; // 1 if male
55 public $patient_pricelevel = ''; // From patient_data.pricelevel
56 public $provider_id = 0;
57 public $supervisor_id = 0;
58 public $code_is_in_fee_sheet = false; // Set by genCodeSelectorValue()
60 // Possible units of measure for NDC drug quantities.
61 public $ndc_uom_choices = array(
62 'ML' => 'ML',
63 'GR' => 'Grams',
64 'ME' => 'Milligrams',
65 'F2' => 'I.U.',
66 'UN' => 'Units'
69 // Set by checkRelatedForContraception():
70 public $line_contra_code = '';
71 public $line_contra_cyp = 0;
72 public $line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
74 // Array of line items generated by addServiceLineItem().
75 // Each element is an array of line item attributes.
76 public $serviceitems = array();
78 // Array of line items generated by addProductLineItem().
79 // Each element is an array of line item attributes.
80 public $productitems = array();
82 // Indicates if any line item has a fee.
83 public $hasCharges = false;
85 // Indicates if any clinical services or products are in the fee sheet.
86 public $required_code_count = 0;
88 // These variables are used to compute the initial consult service with highest CYP (IPPF).
89 public $contraception_code = '';
90 public $contraception_cyp = 0;
92 public $ALLOW_COPAYS = false;
94 function __construct($pid=0, $encounter=0)
96 if (empty($pid)) $pid = $GLOBALS['pid'];
97 if (empty($encounter)) $encounter = $GLOBALS['encounter'];
98 $this->pid = $pid;
99 $this->encounter = $encounter;
101 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
102 $this->ALLOW_COPAYS = !$GLOBALS['ippf_specific'];
104 // Get the user's default warehouse and an indicator if there's a choice of warehouses.
105 $wrow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse' AND activity = 1");
106 $this->got_warehouses = $wrow['count'] > 1;
107 $wrow = sqlQuery("SELECT default_warehouse FROM users WHERE username = ?",
108 array($_SESSION['authUser']));
109 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
111 // Get some info about this visit.
112 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
113 "opc.pc_catname, fac.extra_validation " .
114 "FROM form_encounter AS fe " .
115 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
116 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
117 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter) );
118 $this->visit_date = substr($visit_row['date'], 0, 10);
119 $this->provider_id = $visit_row['provider_id'];
120 if (empty($this->provider_id)) $this->provider_id = $this->findProvider();
121 $this->supervisor_id = $visit_row['supervisor_id'];
122 // This flag is specific to IPPF validation at form submit time. It indicates
123 // that most contraceptive services and products should match up on the fee sheet.
124 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
125 !empty($visit_row['extra_validation']);
127 // Get some information about the patient.
128 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
129 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
130 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
131 $this->patient_pricelevel = $patientrow['pricelevel'];
134 // Convert numeric code type to the alpha version.
136 public static function alphaCodeType($id)
138 global $code_types;
139 foreach ($code_types as $key => $value) {
140 if ($value['id'] == $id) return $key;
142 return '';
145 // Compute age in years given a DOB and "as of" date.
147 public static function getAge($dob, $asof='')
149 if (empty($asof)) $asof = date('Y-m-d');
150 $a1 = explode('-', substr($dob , 0, 10));
151 $a2 = explode('-', substr($asof, 0, 10));
152 $age = $a2[0] - $a1[0];
153 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) --$age;
154 return $age;
157 // Gets the provider from the encounter, logged-in user or patient demographics.
158 // Adapted from work by Terry Hill.
160 public function findProvider()
162 $find_provider = sqlQuery("SELECT provider_id FROM form_encounter " .
163 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
164 array($this->pid, $this->encounter));
165 $providerid = $find_provider['provider_id'];
166 if (!$providerid) {
167 $get_authorized = $_SESSION['userauthorized'];
168 if ($get_authorized == 1) {
169 $providerid = $_SESSION['authUserID'];
172 if (!$providerid) {
173 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
174 "WHERE pid = ?", array($this->pid) );
175 $providerid = $find_provider['providerID'];
177 return intval($providerid);
180 // Log a message that is easy for the Re-Opened Visits Report to interpret.
182 public function logFSMessage($action)
184 newEvent('fee-sheet', $_SESSION['authUser'], $_SESSION['authProvider'], 1,
185 $action, $this->pid, $this->encounter);
188 // Compute a current checksum of this encounter's Fee Sheet data from the database.
190 public function visitChecksum($saved=false)
192 $rowb = sqlQuery("SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
193 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
194 "))) AS checksum FROM billing WHERE " .
195 "pid = ? AND encounter = ? AND activity = 1",
196 array($this->pid, $this->encounter));
197 $rowp = sqlQuery("SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
198 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
199 "))) AS checksum FROM drug_sales WHERE " .
200 "pid = ? AND encounter = ?",
201 array($this->pid, $this->encounter));
202 $ret = intval($rowb['checksum']) ^ intval($rowp['checksum']);
203 if (CHECKSUM_LOGGING) {
204 $comment = "Checksum = '$ret'";
205 $comment .= ", Saved = " . ($saved ? "true" : "false");
206 newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid);
208 return $ret;
211 // IPPF-specific; get contraception attributes of the related codes.
213 public function checkRelatedForContraception($related_code, $is_initial_consult=false)
215 $this->line_contra_code = '';
216 $this->line_contra_cyp = 0;
217 $this->line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
218 if (!empty($related_code)) {
219 $relcodes = explode(';', $related_code);
220 foreach ($relcodes as $relstring) {
221 if ($relstring === '') continue;
222 list($reltype, $relcode) = explode(':', $relstring);
223 if ($reltype !== 'IPPFCM') continue;
224 $methtype = $is_initial_consult ? 2 : 1;
225 $tmprow = sqlQuery("SELECT cyp_factor FROM codes WHERE " .
226 "code_type = '32' AND code = ? LIMIT 1", array($relcode));
227 $cyp = 0 + $tmprow['cyp_factor'];
228 if ($cyp > $this->line_contra_cyp) {
229 $this->line_contra_cyp = $cyp;
230 // Note this is an IPPFCM code, not an IPPF2 code.
231 $this->line_contra_code = $relcode;
232 $this->line_contra_methtype = $methtype;
238 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
239 // This is only needed for auto-creating Contraception forms.
241 public function insert_lbf_item($form_id, $field_id, $field_value)
243 if ($form_id) {
244 sqlInsert("INSERT INTO lbf_data (form_id, field_id, field_value) " .
245 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
247 else {
248 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
249 "VALUES (?, ?)", array($field_id, $field_value));
251 return $form_id;
254 // Create an array of data for a particular billing table item that is useful
255 // for building a user interface form row. $args is an array containing:
256 // codetype
257 // code
258 // modifier
259 // ndc_info
260 // auth
261 // del
262 // units
263 // fee
264 // id
265 // billed
266 // code_text
267 // justify
268 // provider_id
269 // notecodes
270 // pricelevel
271 public function addServiceLineItem($args)
273 global $code_types;
275 // echo "<!-- \n"; // debugging
276 // print_r($args); // debugging
277 // echo "--> \n"; // debugging
279 $li = array();
280 $li['hidden'] = array();
282 $codetype = $args['codetype'];
283 $code = $args['code'];
284 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
285 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
286 $units = isset($args['units']) ? $args['units'] : 0;
287 $units = max(1, intval($units));
288 $billed = !empty($args['billed']);
289 $auth = !empty($args['auth']);
290 $id = isset($args['id']) ? intval($args['id']) : 0;
291 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
292 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
293 $justify = isset($args['justify']) ? $args['justify'] : '';
294 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
295 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
296 // Price level should be unset only if adding a new line item.
297 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
298 $del = !empty($args['del']);
300 // If using line item billing and user wishes to default to a selected provider, then do so.
301 if(!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
302 if ($provider_id == 0) {
303 $provider_id = 0 + $this->findProvider();
307 if ($codetype == 'COPAY') {
308 if (!$code_text) $code_text = 'Cash';
309 if ($fee > 0) $fee = 0 - $fee;
312 // Get the matching entry from the codes table.
313 $sqlArray = array();
314 $query = "SELECT id, units, code_text FROM codes WHERE " .
315 "code_type = ? AND code = ?";
316 array_push($sqlArray, $code_types[$codetype]['id'], $code);
317 if ($modifier) {
318 $query .= " AND modifier = ?";
319 array_push($sqlArray, $modifier);
321 else {
322 $query .= " AND (modifier IS NULL OR modifier = '')";
324 $result = sqlQuery($query, $sqlArray);
325 $codes_id = $result['id'];
327 if (!$code_text) {
328 $code_text = $result['code_text'];
329 if (empty($units)) $units = max(1, intval($result['units']));
330 if (!isset($args['fee'])) {
331 // Fees come from the prices table now.
332 $query = "SELECT pr_price FROM prices WHERE " .
333 "pr_id = ? AND pr_selector = '' AND pr_level = ? " .
334 "LIMIT 1";
335 // echo "\n<!-- $query -->\n"; // debugging
336 $prrow = sqlQuery($query, array($codes_id, $pricelevel));
337 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
340 $fee = sprintf('%01.2f', $fee);
342 $li['hidden']['code_type'] = $codetype;
343 $li['hidden']['code' ] = $code;
344 $li['hidden']['mod' ] = $modifier;
345 $li['hidden']['billed' ] = $billed;
346 $li['hidden']['id' ] = $id;
347 $li['hidden']['codes_id' ] = $codes_id;
349 // This logic is only used for family planning clinics, and then only when
350 // the option is chosen to use or auto-generate Contraception forms.
351 // It adds contraceptive method and effectiveness to relevant lines.
352 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
353 $codesrow = sqlQuery("SELECT related_code, cyp_factor FROM codes WHERE " .
354 "code_type = ? AND code = ? LIMIT 1",
355 array($code_types[$codetype]['id'], $code));
356 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
357 if ($this->line_contra_code) {
358 $li['hidden']['method' ] = $this->line_contra_code;
359 $li['hidden']['cyp' ] = $this->line_contra_cyp;
360 $li['hidden']['methtype'] = $this->line_contra_methtype;
361 // contraception_code is only concerned with initial consults.
362 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
363 $this->contraception_cyp = $this->line_contra_cyp;
364 $this->contraception_code = $this->line_contra_code;
369 if($codetype == 'COPAY') {
370 $li['codetype'] = xl($codetype);
371 if ($ndc_info) $li['codetype'] .= " ($ndc_info)";
372 $ndc_info = '';
374 else {
375 $li['codetype'] = $codetype;
378 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
379 $li['mod' ] = $modifier;
380 $li['fee' ] = $fee;
381 $li['price' ] = $fee / $units;
382 $li['pricelevel'] = $pricelevel;
383 $li['units' ] = $units;
384 $li['provid' ] = $provider_id;
385 $li['justify' ] = $justify;
386 $li['notecodes'] = $notecodes;
387 $li['del' ] = $id && $del;
388 $li['code_text'] = $code_text;
389 $li['auth' ] = $auth;
391 $li['hidden']['price'] = $li['price'];
393 // If NDC info exists or may be required, add stuff for it.
394 if ($codetype == 'HCPCS' && !$billed) {
395 $ndcnum = '';
396 $ndcuom = '';
397 $ndcqty = '';
398 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
399 $ndcnum = $tmp[1];
400 $ndcuom = $tmp[2];
401 $ndcqty = $tmp[3];
403 $li['ndcnum' ] = $ndcnum;
404 $li['ndcuom' ] = $ndcuom;
405 $li['ndcqty' ] = $ndcqty;
407 else if ($ndc_info) {
408 $li['ndc_info' ] = $ndc_info;
411 // For Family Planning.
412 if ($codetype == 'MA') ++$this->required_code_count;
413 if ($fee != 0) $this->hasCharges = true;
415 $this->serviceitems[] = $li;
418 // Create an array of data for a particular drug_sales table item that is useful
419 // for building a user interface form row. $args is an array containing:
420 // drug_id
421 // selector
422 // sale_id
423 // rx (boolean)
424 // del (boolean)
425 // units
426 // fee
427 // billed
428 // warehouse_id
429 // pricelevel
431 public function addProductLineItem($args)
433 global $code_types;
435 $li = array();
436 $li['hidden'] = array();
438 $drug_id = $args['drug_id'];
439 $selector = isset($args['selector']) ? $args['selector'] : '';
440 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
441 $units = isset($args['units']) ? $args['units'] : 0;
442 $units = max(1, intval($units));
443 $billed = !empty($args['billed']);
444 $rx = !empty($args['rx']);
445 $del = !empty($args['del']);
446 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
447 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
448 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
450 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id) );
451 $code_text = $drow['name'];
453 // If no warehouse ID passed, use the logged-in user's default.
454 if ($this->got_warehouses && $warehouse_id === '') $warehouse_id = $this->default_warehouse;
456 // If fee is not provided, get it from the prices table.
457 // It is assumed in this case that units will match what is in the product template.
458 if (!isset($args['fee'])) {
459 $query = "SELECT pr_price FROM prices WHERE " .
460 "pr_id = ? AND pr_selector = ? AND pr_level = ? " .
461 "LIMIT 1";
462 $prrow = sqlQuery($query, array($drug_id, $selector, $pricelevel));
463 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
466 $fee = sprintf('%01.2f', $fee);
468 $li['fee' ] = $fee;
469 $li['price' ] = $fee / $units;
470 $li['pricelevel'] = $pricelevel;
471 $li['units' ] = $units;
472 $li['del' ] = $sale_id && $del;
473 $li['code_text'] = $code_text;
474 $li['warehouse'] = $warehouse_id;
475 $li['rx' ] = $rx;
477 $li['hidden']['drug_id'] = $drug_id;
478 $li['hidden']['selector'] = $selector;
479 $li['hidden']['sale_id'] = $sale_id;
480 $li['hidden']['billed' ] = $billed;
481 $li['hidden']['price' ] = $li['price'];
483 // This logic is only used for family planning clinics, and then only when
484 // the option is chosen to use or auto-generate Contraception forms.
485 // It adds contraceptive method and effectiveness to relevant lines.
486 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
487 $this->checkRelatedForContraception($drow['related_code']);
488 if ($this->line_contra_code) {
489 $li['hidden']['method' ] = $this->line_contra_code;
490 $li['hidden']['methtype'] = $this->line_contra_methtype;
494 // For Family Planning.
495 ++$this->required_code_count;
496 if ($fee != 0) $this->hasCharges = true;
498 $this->productitems[] = $li;
501 // Generate rows for items already in the billing table for this encounter.
503 public function loadServiceItems()
505 $billresult = getBillingByEncounter($this->pid, $this->encounter, "*");
506 if ($billresult) {
507 foreach ($billresult as $iter) {
508 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') continue;
509 $justify = trim($iter['justify']);
510 if ($justify) $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
511 $this->addServiceLineItem(array(
512 'id' => $iter['id'],
513 'codetype' => $iter['code_type'],
514 'code' => trim($iter['code']),
515 'modifier' => trim($iter["modifier"]),
516 'code_text' => trim($iter['code_text']),
517 'units' => $iter['units'],
518 'fee' => $iter['fee'],
519 'pricelevel' => $iter['pricelevel'],
520 'billed' => $iter['billed'],
521 'ndc_info' => $iter['ndc_info'],
522 'provider_id' => $iter['provider_id'],
523 'justify' => $justify,
524 'notecodes' => trim($iter['notecodes']),
528 // echo "<!-- \n"; // debugging
529 // print_r($this->serviceitems); // debugging
530 // echo "--> \n"; // debugging
533 // Generate rows for items already in the drug_sales table for this encounter.
535 public function loadProductItems()
537 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
538 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
539 "ORDER BY ds.sale_id";
540 $sres = sqlStatement($query, array($this->pid, $this->encounter));
541 while ($srow = sqlFetchArray($sres)) {
542 $this->addProductLineItem(array(
543 'drug_id' => $srow['drug_id'],
544 'selector' => $srow['selector'],
545 'sale_id' => $srow['sale_id'],
546 'rx' => !empty($srow['prescription_id']),
547 'units' => $srow['quantity'],
548 'fee' => $srow['fee'],
549 'pricelevel' => $srow['pricelevel'],
550 'billed' => $srow['billed'],
551 'warehouse_id' => $srow['warehouse_id'],
556 // Check for insufficient product inventory levels.
557 // Returns an error message if any product items cannot be filled.
558 // You must call this before save().
560 public function checkInventory(&$prod)
562 $alertmsg = '';
563 $insufficient = 0;
564 $expiredlots = false;
565 if (is_array($prod)) foreach ($prod as $iter) {
566 if (!empty($iter['billed'])) continue;
567 $drug_id = $iter['drug_id'];
568 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
569 $units = empty($iter['units']) ? 1 : intval($iter['units']);
570 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
572 // Deleting always works.
573 if (!empty($iter['del'])) continue;
575 // If the item is already in the database...
576 if ($sale_id) {
577 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
578 "FROM drug_sales AS ds " .
579 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
580 "WHERE ds.sale_id = ?";
581 $dirow = sqlQuery($query, array($sale_id));
582 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
583 if (!empty($dirow['inventory_id'])) {
584 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
585 // Changing warehouse so check inventory in the new warehouse.
586 // Nothing is updated by this call.
587 if (!sellDrug($drug_id, $units, 0, $this->pid, $this->encounter, 0,
588 $this->visit_date, '', $warehouse_id, true, $expiredlots)) {
589 $insufficient = $drug_id;
592 else {
593 if (($dirow['on_hand'] + $dirow['quantity'] - $units) < 0) {
594 $insufficient = $drug_id;
599 // Otherwise it's a new item...
600 else {
601 // This only checks for sufficient inventory, nothing is updated.
602 if (!sellDrug($drug_id, $units, 0, $this->pid, $this->encounter, 0,
603 $this->visit_date, '', $warehouse_id, true, $expiredlots)) {
604 $insufficient = $drug_id;
607 } // end for
608 if ($insufficient) {
609 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
610 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
611 if ($expiredlots) $alertmsg .= " " . xl('Check expiration dates.');
613 return $alertmsg;
616 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
617 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
619 public function save(
620 &$bill,
621 &$prod,
622 $main_provid=null,
623 $main_supid=null,
624 $default_warehouse=null,
625 $mark_as_closed=false
627 global $code_types;
629 if (isset($main_provid) && $main_supid == $main_provid) $main_supid = 0;
631 $copay_update = false;
632 $update_session_id = '';
633 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
634 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
635 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
637 if (is_array($bill)) foreach ($bill as $iter) {
638 // Skip disabled (billed) line items.
639 if (!empty($iter['billed'])) continue;
641 $id = $iter['id'];
642 $code_type = $iter['code_type'];
643 $code = $iter['code'];
644 $del = !empty($iter['del']);
645 $units = empty($iter['units']) ? 1 : intval($iter['units']);
646 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
647 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
648 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
649 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
650 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
651 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
653 $fee = sprintf('%01.2f', $price * $units);
655 if(!$cod0 && $code_types[$code_type]['fee'] == 1) {
656 $mod0 = $modifier;
657 $cod0 = $code;
658 $ct0 = $code_type;
661 if ($code_type == 'COPAY') {
662 if ($fee < 0) {
663 $fee = $fee * -1;
665 if (!$id) {
666 // adding new copay from fee sheet into ar_session and ar_activity tables
667 $session_id = idSqlStatement("INSERT INTO ar_session " .
668 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
669 "adjustment_code, post_to_date) " .
670 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
671 array($_SESSION['authId'], $fee, $this->pid));
672 sqlBeginTrans();
673 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
674 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
675 SqlStatement("INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
676 "payer_type, post_time, post_user, session_id, " .
677 "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
678 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
679 $_SESSION['authId'], $session_id, $fee));
680 sqlCommitTrans();
682 else {
683 // editing copay saved to ar_session and ar_activity
684 $session_id = $id;
685 $res_amount = sqlQuery("SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?",
686 array($this->pid, $this->encounter, $session_id));
687 if ($fee != $res_amount['pay_amount']) {
688 sqlStatement("UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?",
689 array($_SESSION['authId'], $fee, $session_id));
690 sqlStatement("UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now(),".
691 "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?",
692 array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id));
695 if (!$cod0){
696 $copay_update = true;
697 $update_session_id = $session_id;
699 continue;
702 # Code to create justification for all codes based on first justification
703 if ($GLOBALS['replicate_justification'] == '1') {
704 if ($justify != '') {
705 $autojustify = $justify;
708 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
709 $justify = $autojustify;
712 if ($justify) $justify = str_replace(',', ':', $justify) . ':';
713 $auth = "1";
715 $ndc_info = '';
716 if (!empty($iter['ndcnum'])) {
717 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
718 trim($iter['ndcqty']);
721 // If the item is already in the database...
722 if ($id) {
723 if ($del) {
724 $this->logFSMessage(xl('Service deleted'));
725 deleteBilling($id);
727 else {
728 $tmp = sqlQuery("SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1",
729 array($id));
730 if (!empty($tmp)) {
731 $tmparr = array('code' => $code, 'authorized' => $auth);
732 if (isset($iter['units' ])) $tmparr['units' ] = $units;
733 if (isset($iter['price' ])) $tmparr['fee' ] = $fee;
734 if (isset($iter['pricelevel'])) $tmparr['pricelevel'] = $pricelevel;
735 if (isset($iter['mod' ])) $tmparr['modifier' ] = $modifier;
736 if (isset($iter['provid' ])) $tmparr['provider_id'] = $provid;
737 if (isset($iter['ndcnum' ])) $tmparr['ndc_info' ] = $ndc_info;
738 if (isset($iter['justify' ])) $tmparr['justify' ] = $justify;
739 if (isset($iter['notecodes'])) $tmparr['notecodes' ] = $notecodes;
740 foreach ($tmparr as $key => $value) {
741 if ($tmp[$key] != $value) {
742 if ('fee' == $key) $this->logFSMessage(xl('Price changed'));
743 if ('units' == $key) $this->logFSMessage(xl('Quantity changed'));
744 if ('provider_id' == $key) $this->logFSMessage(xl('Service provider changed'));
745 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
751 // Otherwise it's a new item...
752 else if (!$del) {
753 $this->logFSMessage(xl('Service added'));
754 $code_text = lookup_code_descriptions($code_type.":".$code);
755 addBilling($this->encounter, $code_type, $code, $code_text, $this->pid, $auth,
756 $provid, $modifier, $units, $fee, $ndc_info, $justify, 0, $notecodes, $pricelevel);
758 } // end for
760 // if modifier is not inserted during loop update the record using the first
761 // non-empty modifier and code
762 if($copay_update == true && $update_session_id != '' && $mod0 != '') {
763 sqlStatement("UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?".
764 " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
765 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id));
768 // Doing similarly to the above but for products.
769 if (is_array($prod)) foreach ($prod as $iter) {
770 // Skip disabled (billed) line items.
771 if (!empty($iter['billed'])) continue;
773 $drug_id = $iter['drug_id'];
774 $selector = empty($iter['selector']) ? '' : $iter['selector'];
775 $sale_id = $iter['sale_id']; // present only if already saved
776 $units = max(1, intval(trim($iter['units'])));
777 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
778 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
779 $fee = sprintf('%01.2f', $price * $units);
780 $del = !empty($iter['del']);
781 $rxid = 0;
782 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
783 $somechange = false;
785 // If the item is already in the database...
786 if ($sale_id) {
787 $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
788 "ds.sale_date, di.warehouse_id " .
789 "FROM drug_sales AS ds " .
790 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
791 "WHERE ds.sale_id = ?", array($sale_id));
792 $rxid = 0 + $tmprow['prescription_id'];
793 if ($del) {
794 if (!empty($tmprow)) {
795 // Delete this sale and reverse its inventory update.
796 $this->logFSMessage(xl('Product deleted'));
797 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
798 if (!empty($tmprow['inventory_id'])) {
799 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
800 array($tmprow['quantity'], $tmprow['inventory_id']));
803 if ($rxid) {
804 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
807 else {
808 // Modify the sale and adjust inventory accordingly.
809 if (!empty($tmprow)) {
810 foreach (array(
811 'quantity' => $units,
812 'fee' => $fee,
813 'pricelevel' => $pricelevel,
814 'selector' => $selector,
815 'sale_date' => $this->visit_date,
816 ) as $key => $value) {
817 if ($tmprow[$key] != $value) {
818 $somechange = true;
819 if ('fee' == $key) $this->logFSMessage(xl('Price changed'));
820 if ('pricelevel' == $key) $this->logFSMessage(xl('Price level changed'));
821 if ('selector' == $key) $this->logFSMessage(xl('Template selector changed'));
822 if ('quantity' == $key) $this->logFSMessage(xl('Quantity changed'));
823 sqlStatement("UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
824 array($value, $sale_id));
825 if ($key == 'quantity' && $tmprow['inventory_id']) {
826 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
827 array($units - $tmprow['quantity'], $tmprow['inventory_id']));
831 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
832 // Changing warehouse. Requires deleting and re-adding the sale.
833 // Not setting $somechange because this alone does not affect a prescription.
834 $this->logFSMessage(xl('Warehouse changed'));
835 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
836 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
837 array($units, $tmprow['inventory_id']));
838 $tmpnull = null;
839 $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter,
840 (empty($iter['rx']) ? 0 : $rxid), $this->visit_date, '', $warehouse_id,
841 false, $tmpnull, $pricelevel, $selector);
844 // Delete Rx if $rxid and flag not set.
845 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
846 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
847 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
852 // Otherwise it's a new item...
853 else if (! $del) {
854 $somechange = true;
855 $this->logFSMessage(xl('Product added'));
856 $tmpnull = null;
857 $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter, 0,
858 $this->visit_date, '', $warehouse_id, false, $tmpnull, $pricelevel, $selector);
859 if (!$sale_id) die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
862 // If a prescription applies, create or update it.
863 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
864 // If an active rx already exists for this drug and date we will
865 // replace it, otherwise we'll make a new one.
866 if (empty($rxid)) $rxid = '';
867 // Get default drug attributes; prefer the template with the matching selector.
868 $drow = sqlQuery("SELECT dt.*, " .
869 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
870 "FROM drugs AS d, drug_templates AS dt WHERE " .
871 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
872 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
873 array($drug_id, $selector));
874 if (!empty($drow)) {
875 $rxobj = new Prescription($rxid);
876 $rxobj->set_patient_id($this->pid);
877 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
878 $rxobj->set_drug_id($drug_id);
879 $rxobj->set_quantity($units);
880 $rxobj->set_per_refill($units);
881 $rxobj->set_start_date_y(substr($this->visit_date,0,4));
882 $rxobj->set_start_date_m(substr($this->visit_date,5,2));
883 $rxobj->set_start_date_d(substr($this->visit_date,8,2));
884 $rxobj->set_date_added($this->visit_date);
885 // Remaining attributes are the drug and template defaults.
886 $rxobj->set_drug($drow['name']);
887 $rxobj->set_unit($drow['unit']);
888 $rxobj->set_dosage($drow['dosage']);
889 $rxobj->set_form($drow['form']);
890 $rxobj->set_refills($drow['refills']);
891 $rxobj->set_size($drow['size']);
892 $rxobj->set_route($drow['route']);
893 $rxobj->set_interval($drow['period']);
894 $rxobj->set_substitute($drow['substitute']);
896 $rxobj->persist();
897 // Set drug_sales.prescription_id to $rxobj->get_id().
898 $oldrxid = $rxid;
899 $rxid = 0 + $rxobj->get_id();
900 if ($rxid != $oldrxid) {
901 sqlStatement("UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
902 array($rxid, $sale_id));
906 } // end for
908 // Set default and/or supervising provider for the encounter.
909 if (isset($main_provid) && $main_provid != $this->provider_id) {
910 $this->logFSMessage(xl('Default provider changed'));
911 sqlStatement("UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
912 array($main_provid, $this->pid, $this->encounter));
913 $this->provider_id = $main_provid;
915 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
916 sqlStatement("UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
917 array($main_supid, $this->pid, $this->encounter));
918 $this->supervisor_id = $main_supid;
921 // Save-and-Close is currently specific to Family Planning but might be more
922 // generally useful. It provides the ability to mark an encounter as billed
923 // directly from the Fee Sheet, if there are no charges.
924 if ($mark_as_closed) {
925 $tmp1 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
926 "pid = ? AND encounter = ? AND billed = 0",
927 array($this->pid, $this->encounter));
928 $tmp2 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
929 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
930 array($this->pid, $this->encounter));
931 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
932 sqlStatement("update drug_sales SET billed = 1 WHERE " .
933 "pid = ? AND encounter = ? AND billed = 0",
934 array($this->pid, $this->encounter));
935 sqlStatement("UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
936 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
937 array($this->pid, $this->encounter));
939 else {
940 // Would be good to display an error message here... they clicked
941 // Save and Close but the close could not be done. However the
942 // framework does not provide an easy way to do that.
947 // Call this after save() for Family Planning implementations.
948 // It checks the contraception form, or makes a new one if $newmauser is set.
949 // Returns 0 unless user intervention is required to fix a missing or incorrect form,
950 // and in that case the return value is an existing form ID, or -1 if none.
952 // Returns FALSE if user intervention is required to fix a missing or incorrect form.
954 public function doContraceptionForm($ippfconmeth=null, $newmauser=null, $main_provid=0)
956 if (!empty($ippfconmeth)) {
957 $csrow = sqlQuery("SELECT f.form_id, ld.field_value FROM forms AS f " .
958 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
959 "WHERE " .
960 "f.pid = ? AND f.encounter = ? AND " .
961 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
962 "ORDER BY f.form_id DESC LIMIT 1",
963 array($this->pid, $this->encounter));
964 if (isset($newmauser)) {
965 // pastmodern is 0 iff new to modern contraception
966 $pastmodern = $newmauser == '2' ? 0 : 1;
967 if ($newmauser == '2') $newmauser = '1';
968 // Add contraception form but only if it does not already exist
969 // (if it does, must be 2 users working on the visit concurrently).
970 if (empty($csrow)) {
971 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
972 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
973 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
974 // Do we care about a service-specific provider here?
975 $this->insert_lbf_item($newid, 'provider', $main_provid);
976 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
979 else if (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
980 // Contraceptive method does not match what is in an existing Contraception
981 // form for this visit, or there is no such form. User intervention is needed.
982 return empty($csrow) ? -1 : intval($csrow['form_id']);
985 return 0;
988 // Get price level from patient demographics.
990 public function getPriceLevel()
992 return $this->patient_pricelevel;
995 // Update price level in patient demographics if it's changed.
997 public function updatePriceLevel($pricelevel)
999 if (!empty($pricelevel)) {
1000 if ($this->patient_pricelevel != $pricelevel) {
1001 $this->logFSMessage(xl('Price level changed'));
1002 sqlStatement("UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1003 array($pricelevel, $this->pid));
1004 $this->patient_pricelevel = $pricelevel;
1009 // Create JSON string representing code type, code and selector.
1010 // This can be a checkbox value for parsing when the checkbox is clicked.
1011 // As a side effect note if the code is already selected in the Fee Sheet.
1013 public function genCodeSelectorValue($codes)
1015 global $code_types;
1016 list($codetype, $code, $selector) = explode(':', $codes);
1017 if ($codetype == 'PROD') {
1018 $crow = sqlQuery("SELECT sale_id " .
1019 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1020 "LIMIT 1",
1021 array($this->pid, $this->encounter, $code));
1022 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
1023 $cbarray = array($codetype, $code, $selector);
1025 else {
1026 $crow = sqlQuery("SELECT c.id AS code_id, b.id " .
1027 "FROM codes AS c " .
1028 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1029 "WHERE c.code_type = ? AND c.code = ? LIMIT 1",
1030 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code));
1031 $this->code_is_in_fee_sheet = !empty($crow['id']);
1032 $cbarray = array($codetype, $code);
1034 $cbval = json_encode($cbarray);
1035 return $cbval;