Setup script bootstrapped with new theme selector - Take 2 (#2139)
[openemr.git] / library / FeeSheet.class.php
blob15814985d1168d1cf5ce26d97d9d550f3a3b3b12
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
26 require_once(dirname(__FILE__) . "/../interface/globals.php");
27 require_once(dirname(__FILE__) . "/acl.inc");
28 require_once(dirname(__FILE__) . "/../custom/code_types.inc.php");
29 require_once(dirname(__FILE__) . "/../interface/drugs/drugs.inc.php");
30 require_once(dirname(__FILE__) . "/options.inc.php");
31 require_once(dirname(__FILE__) . "/appointment_status.inc.php");
32 require_once(dirname(__FILE__) . "/classes/Prescription.class.php");
33 require_once(dirname(__FILE__) . "/forms.inc");
34 require_once(dirname(__FILE__) . "/log.inc");
36 use OpenEMR\Billing\BillingUtilities;
38 // For logging checksums set this to true.
39 define('CHECKSUM_LOGGING', true);
41 // require_once(dirname(__FILE__) . "/api.inc");
42 // require_once(dirname(__FILE__) . "/forms.inc");
44 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)) {
97 $pid = $GLOBALS['pid'];
100 if (empty($encounter)) {
101 $encounter = $GLOBALS['encounter'];
104 $this->pid = $pid;
105 $this->encounter = $encounter;
107 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
108 $this->ALLOW_COPAYS = !$GLOBALS['ippf_specific'];
110 // Get the user's default warehouse and an indicator if there's a choice of warehouses.
111 $wrow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse' AND activity = 1");
112 $this->got_warehouses = $wrow['count'] > 1;
113 $wrow = sqlQuery(
114 "SELECT default_warehouse FROM users WHERE username = ?",
115 array($_SESSION['authUser'])
117 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
119 // Get some info about this visit.
120 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
121 "opc.pc_catname, fac.extra_validation " .
122 "FROM form_encounter AS fe " .
123 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
124 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
125 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter));
126 $this->visit_date = substr($visit_row['date'], 0, 10);
127 $this->provider_id = $visit_row['provider_id'];
128 if (empty($this->provider_id)) {
129 $this->provider_id = $this->findProvider();
132 $this->supervisor_id = $visit_row['supervisor_id'];
133 // This flag is specific to IPPF validation at form submit time. It indicates
134 // that most contraceptive services and products should match up on the fee sheet.
135 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
136 !empty($visit_row['extra_validation']);
138 // Get some information about the patient.
139 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
140 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
141 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
142 $this->patient_pricelevel = $patientrow['pricelevel'];
145 // Convert numeric code type to the alpha version.
147 public static function alphaCodeType($id)
149 global $code_types;
150 foreach ($code_types as $key => $value) {
151 if ($value['id'] == $id) {
152 return $key;
156 return '';
159 // Compute age in years given a DOB and "as of" date.
161 public static function getAge($dob, $asof = '')
163 if (empty($asof)) {
164 $asof = date('Y-m-d');
167 $a1 = explode('-', substr($dob, 0, 10));
168 $a2 = explode('-', substr($asof, 0, 10));
169 $age = $a2[0] - $a1[0];
170 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) {
171 --$age;
174 return $age;
177 // Gets the provider from the encounter, logged-in user or patient demographics.
178 // Adapted from work by Terry Hill.
180 public function findProvider()
182 $find_provider = sqlQuery(
183 "SELECT provider_id FROM form_encounter " .
184 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
185 array($this->pid, $this->encounter)
187 $providerid = $find_provider['provider_id'];
188 if (!$providerid) {
189 $get_authorized = $_SESSION['userauthorized'];
190 if ($get_authorized == 1) {
191 $providerid = $_SESSION['authUserID'];
195 if (!$providerid) {
196 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
197 "WHERE pid = ?", array($this->pid));
198 $providerid = $find_provider['providerID'];
201 return intval($providerid);
204 // Log a message that is easy for the Re-Opened Visits Report to interpret.
206 public function logFSMessage($action)
208 newEvent(
209 'fee-sheet',
210 $_SESSION['authUser'],
211 $_SESSION['authProvider'],
213 $action,
214 $this->pid,
215 $this->encounter
219 // Compute a current checksum of this encounter's Fee Sheet data from the database.
221 public function visitChecksum($saved = false)
223 $rowb = sqlQuery(
224 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
225 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
226 "))) AS checksum FROM billing WHERE " .
227 "pid = ? AND encounter = ? AND activity = 1",
228 array($this->pid, $this->encounter)
230 $rowp = sqlQuery(
231 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
232 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
233 "))) AS checksum FROM drug_sales WHERE " .
234 "pid = ? AND encounter = ?",
235 array($this->pid, $this->encounter)
237 $ret = intval($rowb['checksum']) ^ intval($rowp['checksum']);
238 if (CHECKSUM_LOGGING) {
239 $comment = "Checksum = '$ret'";
240 $comment .= ", Saved = " . ($saved ? "true" : "false");
241 newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid);
244 return $ret;
247 // IPPF-specific; get contraception attributes of the related codes.
249 public function checkRelatedForContraception($related_code, $is_initial_consult = false)
251 $this->line_contra_code = '';
252 $this->line_contra_cyp = 0;
253 $this->line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
254 if (!empty($related_code)) {
255 $relcodes = explode(';', $related_code);
256 foreach ($relcodes as $relstring) {
257 if ($relstring === '') {
258 continue;
261 list($reltype, $relcode) = explode(':', $relstring);
262 if ($reltype !== 'IPPFCM') {
263 continue;
266 $methtype = $is_initial_consult ? 2 : 1;
267 $tmprow = sqlQuery("SELECT cyp_factor FROM codes WHERE " .
268 "code_type = '32' AND code = ? LIMIT 1", array($relcode));
269 $cyp = 0 + $tmprow['cyp_factor'];
270 if ($cyp > $this->line_contra_cyp) {
271 $this->line_contra_cyp = $cyp;
272 // Note this is an IPPFCM code, not an IPPF2 code.
273 $this->line_contra_code = $relcode;
274 $this->line_contra_methtype = $methtype;
280 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
281 // This is only needed for auto-creating Contraception forms.
283 public function insert_lbf_item($form_id, $field_id, $field_value)
285 if ($form_id) {
286 sqlInsert("INSERT INTO lbf_data (form_id, field_id, field_value) " .
287 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
288 } else {
289 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
290 "VALUES (?, ?)", array($field_id, $field_value));
293 return $form_id;
296 // Create an array of data for a particular billing table item that is useful
297 // for building a user interface form row. $args is an array containing:
298 // codetype
299 // code
300 // modifier
301 // ndc_info
302 // auth
303 // del
304 // units
305 // fee
306 // id
307 // billed
308 // code_text
309 // justify
310 // provider_id
311 // notecodes
312 // pricelevel
313 public function addServiceLineItem($args)
315 global $code_types;
317 // echo "<!-- \n"; // debugging
318 // print_r($args); // debugging
319 // echo "--> \n"; // debugging
321 $li = array();
322 $li['hidden'] = array();
324 $codetype = $args['codetype'];
325 $code = $args['code'];
326 $revenue_code = isset($args['revenue_code']) ? $args['revenue_code'] : '';
327 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
328 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
329 $units = isset($args['units']) ? $args['units'] : 0;
330 $units = max(1, intval($units));
331 $billed = !empty($args['billed']);
332 $auth = !empty($args['auth']);
333 $id = isset($args['id']) ? intval($args['id']) : 0;
334 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
335 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
336 $justify = isset($args['justify']) ? $args['justify'] : '';
337 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
338 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
339 // Price level should be unset only if adding a new line item.
340 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
341 $del = !empty($args['del']);
343 // If using line item billing and user wishes to default to a selected provider, then do so.
344 if (!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
345 if ($provider_id == 0) {
346 $provider_id = 0 + $this->findProvider();
350 if ($codetype == 'COPAY') {
351 if (!$code_text) {
352 $code_text = 'Cash';
355 if ($fee > 0) {
356 $fee = 0 - $fee;
360 // Get the matching entry from the codes table.
361 $sqlArray = array();
362 $query = "SELECT id, units, code_text, revenue_code FROM codes WHERE " .
363 "code_type = ? AND code = ?";
364 array_push($sqlArray, $code_types[$codetype]['id'], $code);
365 if ($modifier) {
366 $query .= " AND modifier = ?";
367 array_push($sqlArray, $modifier);
368 } else {
369 $query .= " AND (modifier IS NULL OR modifier = '')";
372 $result = sqlQuery($query, $sqlArray);
373 $codes_id = $result['id'];
374 $revenue_code = $revenue_code ? $revenue_code : $result['revenue_code'];
375 if (!$code_text) {
376 $code_text = $result['code_text'];
377 if (empty($units)) {
378 $units = max(1, intval($result['units']));
381 if (!isset($args['fee'])) {
382 // Fees come from the prices table now.
383 $query = "SELECT pr_price FROM prices WHERE " .
384 "pr_id = ? AND pr_selector = '' AND pr_level = ? " .
385 "LIMIT 1";
386 // echo "\n<!-- $query -->\n"; // debugging
387 $prrow = sqlQuery($query, array($codes_id, $pricelevel));
388 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
392 $fee = sprintf('%01.2f', $fee);
394 $li['hidden']['code_type'] = $codetype;
395 $li['hidden']['code'] = $code;
396 $li['hidden']['revenue_code'] = $revenue_code;
397 $li['hidden']['mod'] = $modifier;
398 $li['hidden']['billed'] = $billed;
399 $li['hidden']['id'] = $id;
400 $li['hidden']['codes_id'] = $codes_id;
402 // This logic is only used for family planning clinics, and then only when
403 // the option is chosen to use or auto-generate Contraception forms.
404 // It adds contraceptive method and effectiveness to relevant lines.
405 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
406 $codesrow = sqlQuery(
407 "SELECT related_code, cyp_factor FROM codes WHERE " .
408 "code_type = ? AND code = ? LIMIT 1",
409 array($code_types[$codetype]['id'], $code)
411 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
412 if ($this->line_contra_code) {
413 $li['hidden']['method' ] = $this->line_contra_code;
414 $li['hidden']['cyp' ] = $this->line_contra_cyp;
415 $li['hidden']['methtype'] = $this->line_contra_methtype;
416 // contraception_code is only concerned with initial consults.
417 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
418 $this->contraception_cyp = $this->line_contra_cyp;
419 $this->contraception_code = $this->line_contra_code;
424 if ($codetype == 'COPAY') {
425 $li['codetype'] = xl($codetype);
426 if ($ndc_info) {
427 $li['codetype'] .= " ($ndc_info)";
430 $ndc_info = '';
431 } else {
432 $li['codetype'] = $codetype;
435 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
436 $li['revenue_code' ] = $revenue_code;
437 $li['mod' ] = $modifier;
438 $li['fee' ] = $fee;
439 $li['price' ] = $fee / $units;
440 $li['pricelevel'] = $pricelevel;
441 $li['units' ] = $units;
442 $li['provid' ] = $provider_id;
443 $li['justify' ] = $justify;
444 $li['notecodes'] = $notecodes;
445 $li['del' ] = $id && $del;
446 $li['code_text'] = $code_text;
447 $li['auth' ] = $auth;
449 $li['hidden']['price'] = $li['price'];
451 // If NDC info exists or may be required, add stuff for it.
452 if ($codetype == 'HCPCS' && !$billed) {
453 $ndcnum = '';
454 $ndcuom = '';
455 $ndcqty = '';
456 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
457 $ndcnum = $tmp[1];
458 $ndcuom = $tmp[2];
459 $ndcqty = $tmp[3];
462 $li['ndcnum' ] = $ndcnum;
463 $li['ndcuom' ] = $ndcuom;
464 $li['ndcqty' ] = $ndcqty;
465 } else if ($ndc_info) {
466 $li['ndc_info' ] = $ndc_info;
469 // For Family Planning.
470 if ($codetype == 'MA') {
471 ++$this->required_code_count;
474 if ($fee != 0) {
475 $this->hasCharges = true;
478 $this->serviceitems[] = $li;
481 // Create an array of data for a particular drug_sales table item that is useful
482 // for building a user interface form row. $args is an array containing:
483 // drug_id
484 // selector
485 // sale_id
486 // rx (boolean)
487 // del (boolean)
488 // units
489 // fee
490 // billed
491 // warehouse_id
492 // pricelevel
494 public function addProductLineItem($args)
496 global $code_types;
498 $li = array();
499 $li['hidden'] = array();
501 $drug_id = $args['drug_id'];
502 $selector = isset($args['selector']) ? $args['selector'] : '';
503 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
504 $units = isset($args['units']) ? $args['units'] : 0;
505 $units = max(1, intval($units));
506 $billed = !empty($args['billed']);
507 $rx = !empty($args['rx']);
508 $del = !empty($args['del']);
509 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
510 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
511 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
513 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id));
514 $code_text = $drow['name'];
516 // If no warehouse ID passed, use the logged-in user's default.
517 if ($this->got_warehouses && $warehouse_id === '') {
518 $warehouse_id = $this->default_warehouse;
521 // If fee is not provided, get it from the prices table.
522 // It is assumed in this case that units will match what is in the product template.
523 if (!isset($args['fee'])) {
524 $query = "SELECT pr_price FROM prices WHERE " .
525 "pr_id = ? AND pr_selector = ? AND pr_level = ? " .
526 "LIMIT 1";
527 $prrow = sqlQuery($query, array($drug_id, $selector, $pricelevel));
528 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
531 $fee = sprintf('%01.2f', $fee);
533 $li['fee' ] = $fee;
534 $li['price' ] = $fee / $units;
535 $li['pricelevel'] = $pricelevel;
536 $li['units' ] = $units;
537 $li['del' ] = $sale_id && $del;
538 $li['code_text'] = $code_text;
539 $li['warehouse'] = $warehouse_id;
540 $li['rx' ] = $rx;
542 $li['hidden']['drug_id'] = $drug_id;
543 $li['hidden']['selector'] = $selector;
544 $li['hidden']['sale_id'] = $sale_id;
545 $li['hidden']['billed' ] = $billed;
546 $li['hidden']['price' ] = $li['price'];
548 // This logic is only used for family planning clinics, and then only when
549 // the option is chosen to use or auto-generate Contraception forms.
550 // It adds contraceptive method and effectiveness to relevant lines.
551 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
552 $this->checkRelatedForContraception($drow['related_code']);
553 if ($this->line_contra_code) {
554 $li['hidden']['method' ] = $this->line_contra_code;
555 $li['hidden']['methtype'] = $this->line_contra_methtype;
559 // For Family Planning.
560 ++$this->required_code_count;
561 if ($fee != 0) {
562 $this->hasCharges = true;
565 $this->productitems[] = $li;
568 // Generate rows for items already in the billing table for this encounter.
570 public function loadServiceItems()
572 $billresult = BillingUtilities::getBillingByEncounter($this->pid, $this->encounter, "*");
573 if ($billresult) {
574 foreach ($billresult as $iter) {
575 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') {
576 continue;
579 $justify = trim($iter['justify']);
580 if ($justify) {
581 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
584 $this->addServiceLineItem(array(
585 'id' => $iter['id'],
586 'codetype' => $iter['code_type'],
587 'code' => trim($iter['code']),
588 'revenue_code' => trim($iter["revenue_code"]),
589 'modifier' => trim($iter["modifier"]),
590 'code_text' => trim($iter['code_text']),
591 'units' => $iter['units'],
592 'fee' => $iter['fee'],
593 'pricelevel' => $iter['pricelevel'],
594 'billed' => $iter['billed'],
595 'ndc_info' => $iter['ndc_info'],
596 'provider_id' => $iter['provider_id'],
597 'justify' => $justify,
598 'notecodes' => trim($iter['notecodes']),
603 // echo "<!-- \n"; // debugging
604 // print_r($this->serviceitems); // debugging
605 // echo "--> \n"; // debugging
608 // Generate rows for items already in the drug_sales table for this encounter.
610 public function loadProductItems()
612 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
613 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
614 "ORDER BY ds.sale_id";
615 $sres = sqlStatement($query, array($this->pid, $this->encounter));
616 while ($srow = sqlFetchArray($sres)) {
617 $this->addProductLineItem(array(
618 'drug_id' => $srow['drug_id'],
619 'selector' => $srow['selector'],
620 'sale_id' => $srow['sale_id'],
621 'rx' => !empty($srow['prescription_id']),
622 'units' => $srow['quantity'],
623 'fee' => $srow['fee'],
624 'pricelevel' => $srow['pricelevel'],
625 'billed' => $srow['billed'],
626 'warehouse_id' => $srow['warehouse_id'],
631 // Check for insufficient product inventory levels.
632 // Returns an error message if any product items cannot be filled.
633 // You must call this before save().
635 public function checkInventory(&$prod)
637 $alertmsg = '';
638 $insufficient = 0;
639 $expiredlots = false;
640 if (is_array($prod)) {
641 foreach ($prod as $iter) {
642 if (!empty($iter['billed'])) {
643 continue;
646 $drug_id = $iter['drug_id'];
647 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
648 $units = empty($iter['units']) ? 1 : intval($iter['units']);
649 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
651 // Deleting always works.
652 if (!empty($iter['del'])) {
653 continue;
656 // If the item is already in the database...
657 if ($sale_id) {
658 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
659 "FROM drug_sales AS ds " .
660 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
661 "WHERE ds.sale_id = ?";
662 $dirow = sqlQuery($query, array($sale_id));
663 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
664 if (!empty($dirow['inventory_id'])) {
665 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
666 // Changing warehouse so check inventory in the new warehouse.
667 // Nothing is updated by this call.
668 if (!sellDrug(
669 $drug_id,
670 $units,
672 $this->pid,
673 $this->encounter,
675 $this->visit_date,
677 $warehouse_id,
678 true,
679 $expiredlots
680 )) {
681 $insufficient = $drug_id;
683 } else {
684 if (($dirow['on_hand'] + $dirow['quantity'] - $units) < 0) {
685 $insufficient = $drug_id;
689 } // Otherwise it's a new item...
690 else {
691 // This only checks for sufficient inventory, nothing is updated.
692 if (!sellDrug(
693 $drug_id,
694 $units,
696 $this->pid,
697 $this->encounter,
699 $this->visit_date,
701 $warehouse_id,
702 true,
703 $expiredlots
704 )) {
705 $insufficient = $drug_id;
708 } // end for
711 if ($insufficient) {
712 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
713 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
714 if ($expiredlots) {
715 $alertmsg .= " " . xl('Check expiration dates.');
719 return $alertmsg;
722 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
723 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
725 public function save(
726 &$bill,
727 &$prod,
728 $main_provid = null,
729 $main_supid = null,
730 $default_warehouse = null,
731 $mark_as_closed = false
733 global $code_types;
735 if (isset($main_provid) && $main_supid == $main_provid) {
736 $main_supid = 0;
739 $copay_update = false;
740 $update_session_id = '';
741 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
742 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
743 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
745 if (is_array($bill)) {
746 foreach ($bill as $iter) {
747 // Skip disabled (billed) line items.
748 if (!empty($iter['billed'])) {
749 continue;
752 $id = $iter['id'];
753 $code_type = $iter['code_type'];
754 $code = $iter['code'];
755 $del = !empty($iter['del']);
756 $units = empty($iter['units']) ? 1 : intval($iter['units']);
757 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
758 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
759 $revenue_code = empty($iter['revenue_code']) ? '' : trim($iter['revenue_code']);
760 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
761 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
762 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
763 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
765 $fee = sprintf('%01.2f', $price * $units);
767 if (!$cod0 && $code_types[$code_type]['fee'] == 1) {
768 $mod0 = $modifier;
769 $cod0 = $code;
770 $ct0 = $code_type;
773 if ($code_type == 'COPAY') {
774 if ($fee < 0) {
775 $fee = $fee * -1;
778 if (!$id) {
779 // adding new copay from fee sheet into ar_session and ar_activity tables
780 $session_id = idSqlStatement(
781 "INSERT INTO ar_session " .
782 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
783 "adjustment_code, post_to_date) " .
784 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
785 array($_SESSION['authId'], $fee, $this->pid)
787 sqlBeginTrans();
788 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
789 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
790 SqlStatement(
791 "INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
792 "payer_type, post_time, post_user, session_id, " .
793 "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
794 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
795 $_SESSION['authId'],
796 $session_id,
797 $fee)
799 sqlCommitTrans();
800 } else {
801 // editing copay saved to ar_session and ar_activity
802 $session_id = $id;
803 $res_amount = sqlQuery(
804 "SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?",
805 array($this->pid, $this->encounter, $session_id)
807 if ($fee != $res_amount['pay_amount']) {
808 sqlStatement(
809 "UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?",
810 array($_SESSION['authId'], $fee, $session_id)
812 sqlStatement(
813 "UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now(),".
814 "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?",
815 array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id)
820 if (!$cod0) {
821 $copay_update = true;
822 $update_session_id = $session_id;
825 continue;
828 # Code to create justification for all codes based on first justification
829 if ($GLOBALS['replicate_justification'] == '1') {
830 if ($justify != '') {
831 $autojustify = $justify;
835 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
836 $justify = $autojustify;
839 if ($justify) {
840 $justify = str_replace(',', ':', $justify) . ':';
843 $auth = "1";
845 $ndc_info = '';
846 if (!empty($iter['ndcnum'])) {
847 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
848 trim($iter['ndcqty']);
851 // If the item is already in the database...
852 if ($id) {
853 if ($del) {
854 $this->logFSMessage(xl('Service deleted'));
855 BillingUtilities::deleteBilling($id);
856 } else {
857 $tmp = sqlQuery(
858 "SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1",
859 array($id)
861 if (!empty($tmp)) {
862 $tmparr = array('code' => $code, 'authorized' => $auth);
863 if (isset($iter['units' ])) {
864 $tmparr['units' ] = $units;
867 if (isset($iter['price' ])) {
868 $tmparr['fee' ] = $fee;
871 if (isset($iter['pricelevel'])) {
872 $tmparr['pricelevel'] = $pricelevel;
875 if (isset($iter['mod' ])) {
876 $tmparr['modifier' ] = $modifier;
879 if (isset($iter['provid' ])) {
880 $tmparr['provider_id'] = $provid;
883 if (isset($iter['ndcnum' ])) {
884 $tmparr['ndc_info' ] = $ndc_info;
887 if (isset($iter['justify' ])) {
888 $tmparr['justify' ] = $justify;
891 if (isset($iter['notecodes'])) {
892 $tmparr['notecodes' ] = $notecodes;
895 if (isset($iter['revenue_code'])) {
896 $tmparr['revenue_code'] = $revenue_code;
899 foreach ($tmparr as $key => $value) {
900 if ($tmp[$key] != $value) {
901 if ('fee' == $key) {
902 $this->logFSMessage(xl('Price changed'));
905 if ('units' == $key) {
906 $this->logFSMessage(xl('Quantity changed'));
909 if ('provider_id' == $key) {
910 $this->logFSMessage(xl('Service provider changed'));
913 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
918 } // Otherwise it's a new item...
919 else if (!$del) {
920 $this->logFSMessage(xl('Service added'));
921 $code_text = lookup_code_descriptions($code_type.":".$code);
922 BillingUtilities::addBilling(
923 $this->encounter,
924 $code_type,
925 $code,
926 $code_text,
927 $this->pid,
928 $auth,
929 $provid,
930 $modifier,
931 $units,
932 $fee,
933 $ndc_info,
934 $justify,
936 $notecodes,
937 $pricelevel,
938 $revenue_code
941 } // end for
944 // if modifier is not inserted during loop update the record using the first
945 // non-empty modifier and code
946 if ($copay_update == true && $update_session_id != '' && $mod0 != '') {
947 sqlStatement(
948 "UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?".
949 " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
950 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id)
954 // Doing similarly to the above but for products.
955 if (is_array($prod)) {
956 foreach ($prod as $iter) {
957 // Skip disabled (billed) line items.
958 if (!empty($iter['billed'])) {
959 continue;
962 $drug_id = $iter['drug_id'];
963 $selector = empty($iter['selector']) ? '' : $iter['selector'];
964 $sale_id = $iter['sale_id']; // present only if already saved
965 $units = max(1, intval(trim($iter['units'])));
966 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
967 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
968 $fee = sprintf('%01.2f', $price * $units);
969 $del = !empty($iter['del']);
970 $rxid = 0;
971 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
972 $somechange = false;
974 // If the item is already in the database...
975 if ($sale_id) {
976 $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
977 "ds.sale_date, di.warehouse_id " .
978 "FROM drug_sales AS ds " .
979 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
980 "WHERE ds.sale_id = ?", array($sale_id));
981 $rxid = 0 + $tmprow['prescription_id'];
982 if ($del) {
983 if (!empty($tmprow)) {
984 // Delete this sale and reverse its inventory update.
985 $this->logFSMessage(xl('Product deleted'));
986 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
987 if (!empty($tmprow['inventory_id'])) {
988 sqlStatement(
989 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
990 array($tmprow['quantity'], $tmprow['inventory_id'])
995 if ($rxid) {
996 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
998 } else {
999 // Modify the sale and adjust inventory accordingly.
1000 if (!empty($tmprow)) {
1001 foreach (array(
1002 'quantity' => $units,
1003 'fee' => $fee,
1004 'pricelevel' => $pricelevel,
1005 'selector' => $selector,
1006 'sale_date' => $this->visit_date,
1007 ) as $key => $value) {
1008 if ($tmprow[$key] != $value) {
1009 $somechange = true;
1010 if ('fee' == $key) {
1011 $this->logFSMessage(xl('Price changed'));
1014 if ('pricelevel' == $key) {
1015 $this->logFSMessage(xl('Price level changed'));
1018 if ('selector' == $key) {
1019 $this->logFSMessage(xl('Template selector changed'));
1022 if ('quantity' == $key) {
1023 $this->logFSMessage(xl('Quantity changed'));
1026 sqlStatement(
1027 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1028 array($value, $sale_id)
1030 if ($key == 'quantity' && $tmprow['inventory_id']) {
1031 sqlStatement(
1032 "UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
1033 array($units - $tmprow['quantity'], $tmprow['inventory_id'])
1039 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
1040 // Changing warehouse. Requires deleting and re-adding the sale.
1041 // Not setting $somechange because this alone does not affect a prescription.
1042 $this->logFSMessage(xl('Warehouse changed'));
1043 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1044 sqlStatement(
1045 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1046 array($units, $tmprow['inventory_id'])
1048 $tmpnull = null;
1049 $sale_id = sellDrug(
1050 $drug_id,
1051 $units,
1052 $fee,
1053 $this->pid,
1054 $this->encounter,
1055 (empty($iter['rx']) ? 0 : $rxid),
1056 $this->visit_date,
1058 $warehouse_id,
1059 false,
1060 $tmpnull,
1061 $pricelevel,
1062 $selector
1067 // Delete Rx if $rxid and flag not set.
1068 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
1069 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
1070 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1073 } // Otherwise it's a new item...
1074 else if (! $del) {
1075 $somechange = true;
1076 $this->logFSMessage(xl('Product added'));
1077 $tmpnull = null;
1078 $sale_id = sellDrug(
1079 $drug_id,
1080 $units,
1081 $fee,
1082 $this->pid,
1083 $this->encounter,
1085 $this->visit_date,
1087 $warehouse_id,
1088 false,
1089 $tmpnull,
1090 $pricelevel,
1091 $selector
1093 if (!$sale_id) {
1094 die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
1098 // If a prescription applies, create or update it.
1099 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
1100 // If an active rx already exists for this drug and date we will
1101 // replace it, otherwise we'll make a new one.
1102 if (empty($rxid)) {
1103 $rxid = '';
1106 // Get default drug attributes; prefer the template with the matching selector.
1107 $drow = sqlQuery(
1108 "SELECT dt.*, " .
1109 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
1110 "FROM drugs AS d, drug_templates AS dt WHERE " .
1111 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
1112 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
1113 array($drug_id, $selector)
1115 if (!empty($drow)) {
1116 $rxobj = new Prescription($rxid);
1117 $rxobj->set_patient_id($this->pid);
1118 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
1119 $rxobj->set_drug_id($drug_id);
1120 $rxobj->set_quantity($units);
1121 $rxobj->set_per_refill($units);
1122 $rxobj->set_start_date_y(substr($this->visit_date, 0, 4));
1123 $rxobj->set_start_date_m(substr($this->visit_date, 5, 2));
1124 $rxobj->set_start_date_d(substr($this->visit_date, 8, 2));
1125 $rxobj->set_date_added($this->visit_date);
1126 // Remaining attributes are the drug and template defaults.
1127 $rxobj->set_drug($drow['name']);
1128 $rxobj->set_unit($drow['unit']);
1129 $rxobj->set_dosage($drow['dosage']);
1130 $rxobj->set_form($drow['form']);
1131 $rxobj->set_refills($drow['refills']);
1132 $rxobj->set_size($drow['size']);
1133 $rxobj->set_route($drow['route']);
1134 $rxobj->set_interval($drow['period']);
1135 $rxobj->set_substitute($drow['substitute']);
1137 $rxobj->persist();
1138 // Set drug_sales.prescription_id to $rxobj->get_id().
1139 $oldrxid = $rxid;
1140 $rxid = 0 + $rxobj->get_id();
1141 if ($rxid != $oldrxid) {
1142 sqlStatement(
1143 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1144 array($rxid, $sale_id)
1149 } // end for
1152 // Set default and/or supervising provider for the encounter.
1153 if (isset($main_provid) && $main_provid != $this->provider_id) {
1154 $this->logFSMessage(xl('Default provider changed'));
1155 sqlStatement(
1156 "UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
1157 array($main_provid, $this->pid, $this->encounter)
1159 $this->provider_id = $main_provid;
1162 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
1163 sqlStatement(
1164 "UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
1165 array($main_supid, $this->pid, $this->encounter)
1167 $this->supervisor_id = $main_supid;
1170 // Save-and-Close is currently specific to Family Planning but might be more
1171 // generally useful. It provides the ability to mark an encounter as billed
1172 // directly from the Fee Sheet, if there are no charges.
1173 if ($mark_as_closed) {
1174 $tmp1 = sqlQuery(
1175 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
1176 "pid = ? AND encounter = ? AND billed = 0",
1177 array($this->pid, $this->encounter)
1179 $tmp2 = sqlQuery(
1180 "SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
1181 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1182 array($this->pid, $this->encounter)
1184 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
1185 sqlStatement(
1186 "update drug_sales SET billed = 1 WHERE " .
1187 "pid = ? AND encounter = ? AND billed = 0",
1188 array($this->pid, $this->encounter)
1190 sqlStatement(
1191 "UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
1192 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1193 array($this->pid, $this->encounter)
1195 } else {
1196 // Would be good to display an error message here... they clicked
1197 // Save and Close but the close could not be done. However the
1198 // framework does not provide an easy way to do that.
1203 // Call this after save() for Family Planning implementations.
1204 // It checks the contraception form, or makes a new one if $newmauser is set.
1205 // Returns 0 unless user intervention is required to fix a missing or incorrect form,
1206 // and in that case the return value is an existing form ID, or -1 if none.
1208 // Returns FALSE if user intervention is required to fix a missing or incorrect form.
1210 public function doContraceptionForm($ippfconmeth = null, $newmauser = null, $main_provid = 0)
1212 if (!empty($ippfconmeth)) {
1213 $csrow = sqlQuery(
1214 "SELECT f.form_id, ld.field_value FROM forms AS f " .
1215 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
1216 "WHERE " .
1217 "f.pid = ? AND f.encounter = ? AND " .
1218 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
1219 "ORDER BY f.form_id DESC LIMIT 1",
1220 array($this->pid, $this->encounter)
1222 if (isset($newmauser)) {
1223 // pastmodern is 0 iff new to modern contraception
1224 $pastmodern = $newmauser == '2' ? 0 : 1;
1225 if ($newmauser == '2') {
1226 $newmauser = '1';
1229 // Add contraception form but only if it does not already exist
1230 // (if it does, must be 2 users working on the visit concurrently).
1231 if (empty($csrow)) {
1232 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
1233 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
1234 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
1235 // Do we care about a service-specific provider here?
1236 $this->insert_lbf_item($newid, 'provider', $main_provid);
1237 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
1239 } else if (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
1240 // Contraceptive method does not match what is in an existing Contraception
1241 // form for this visit, or there is no such form. User intervention is needed.
1242 return empty($csrow) ? -1 : intval($csrow['form_id']);
1246 return 0;
1249 // Get price level from patient demographics.
1251 public function getPriceLevel()
1253 return $this->patient_pricelevel;
1256 // Update price level in patient demographics if it's changed.
1258 public function updatePriceLevel($pricelevel)
1260 if (!empty($pricelevel)) {
1261 if ($this->patient_pricelevel != $pricelevel) {
1262 $this->logFSMessage(xl('Price level changed'));
1263 sqlStatement(
1264 "UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1265 array($pricelevel, $this->pid)
1267 $this->patient_pricelevel = $pricelevel;
1272 // Create JSON string representing code type, code and selector.
1273 // This can be a checkbox value for parsing when the checkbox is clicked.
1274 // As a side effect note if the code is already selected in the Fee Sheet.
1276 public function genCodeSelectorValue($codes)
1278 global $code_types;
1279 list($codetype, $code, $selector) = explode(':', $codes);
1280 if ($codetype == 'PROD') {
1281 $crow = sqlQuery(
1282 "SELECT sale_id " .
1283 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1284 "LIMIT 1",
1285 array($this->pid, $this->encounter, $code)
1287 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
1288 $cbarray = array($codetype, $code, $selector);
1289 } else {
1290 $crow = sqlQuery(
1291 "SELECT c.id AS code_id, b.id " .
1292 "FROM codes AS c " .
1293 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1294 "WHERE c.code_type = ? AND c.code = ? LIMIT 1",
1295 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code)
1297 $this->code_is_in_fee_sheet = !empty($crow['id']);
1298 $cbarray = array($codetype, $code);
1301 $cbval = json_encode($cbarray);
1302 return $cbval;