Fully responsive globals.php with vertical menu (#2460)
[openemr.git] / library / FeeSheet.class.php
blobd6b16d8e8a5e2ceb8fd88a8c03d14d4a70fb5045
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 https://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__) . "/forms.inc");
34 use OpenEMR\Billing\BillingUtilities;
35 use OpenEMR\Common\Logging\EventAuditLogger;
37 // For logging checksums set this to true.
38 define('CHECKSUM_LOGGING', true);
40 // require_once(dirname(__FILE__) . "/api.inc");
41 // require_once(dirname(__FILE__) . "/forms.inc");
43 class FeeSheet
46 public $pid; // patient id
47 public $encounter; // encounter id
48 public $got_warehouses = false; // if there is more than 1 warehouse
49 public $default_warehouse = ''; // logged-in user's default warehouse
50 public $visit_date = ''; // YYYY-MM-DD date of this visit
51 public $match_services_to_products = false; // For IPPF
52 public $patient_age = 0; // Age in years as of the visit date
53 public $patient_male = 0; // 1 if male
54 public $patient_pricelevel = ''; // From patient_data.pricelevel
55 public $provider_id = 0;
56 public $supervisor_id = 0;
57 public $code_is_in_fee_sheet = false; // Set by genCodeSelectorValue()
59 // Possible units of measure for NDC drug quantities.
60 public $ndc_uom_choices = array(
61 'ML' => 'ML',
62 'GR' => 'Grams',
63 'ME' => 'Milligrams',
64 'F2' => 'I.U.',
65 'UN' => 'Units'
68 // Set by checkRelatedForContraception():
69 public $line_contra_code = '';
70 public $line_contra_cyp = 0;
71 public $line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
73 // Array of line items generated by addServiceLineItem().
74 // Each element is an array of line item attributes.
75 public $serviceitems = array();
77 // Array of line items generated by addProductLineItem().
78 // Each element is an array of line item attributes.
79 public $productitems = array();
81 // Indicates if any line item has a fee.
82 public $hasCharges = false;
84 // Indicates if any clinical services or products are in the fee sheet.
85 public $required_code_count = 0;
87 // These variables are used to compute the initial consult service with highest CYP (IPPF).
88 public $contraception_code = '';
89 public $contraception_cyp = 0;
91 public $ALLOW_COPAYS = false;
93 function __construct($pid = 0, $encounter = 0)
95 if (empty($pid)) {
96 $pid = $GLOBALS['pid'];
99 if (empty($encounter)) {
100 $encounter = $GLOBALS['encounter'];
103 $this->pid = $pid;
104 $this->encounter = $encounter;
106 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
107 $this->ALLOW_COPAYS = !$GLOBALS['ippf_specific'];
109 // Get the user's default warehouse and an indicator if there's a choice of warehouses.
110 $wrow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse' AND activity = 1");
111 $this->got_warehouses = $wrow['count'] > 1;
112 $wrow = sqlQuery(
113 "SELECT default_warehouse FROM users WHERE username = ?",
114 array($_SESSION['authUser'])
116 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
118 // Get some info about this visit.
119 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
120 "opc.pc_catname, fac.extra_validation " .
121 "FROM form_encounter AS fe " .
122 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
123 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
124 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter));
125 $this->visit_date = substr($visit_row['date'], 0, 10);
126 $this->provider_id = $visit_row['provider_id'];
127 if (empty($this->provider_id)) {
128 $this->provider_id = $this->findProvider();
131 $this->supervisor_id = $visit_row['supervisor_id'];
132 // This flag is specific to IPPF validation at form submit time. It indicates
133 // that most contraceptive services and products should match up on the fee sheet.
134 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
135 !empty($visit_row['extra_validation']);
137 // Get some information about the patient.
138 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
139 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
140 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
141 $this->patient_pricelevel = $patientrow['pricelevel'];
144 // Convert numeric code type to the alpha version.
146 public static function alphaCodeType($id)
148 global $code_types;
149 foreach ($code_types as $key => $value) {
150 if ($value['id'] == $id) {
151 return $key;
155 return '';
158 // Compute age in years given a DOB and "as of" date.
160 public static function getAge($dob, $asof = '')
162 if (empty($asof)) {
163 $asof = date('Y-m-d');
166 $a1 = explode('-', substr($dob, 0, 10));
167 $a2 = explode('-', substr($asof, 0, 10));
168 $age = $a2[0] - $a1[0];
169 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) {
170 --$age;
173 return $age;
176 // Gets the provider from the encounter, logged-in user or patient demographics.
177 // Adapted from work by Terry Hill.
179 public function findProvider()
181 $find_provider = sqlQuery(
182 "SELECT provider_id FROM form_encounter " .
183 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
184 array($this->pid, $this->encounter)
186 $providerid = $find_provider['provider_id'];
187 if (!$providerid) {
188 $get_authorized = $_SESSION['userauthorized'];
189 if ($get_authorized == 1) {
190 $providerid = $_SESSION['authUserID'];
194 if (!$providerid) {
195 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
196 "WHERE pid = ?", array($this->pid));
197 $providerid = $find_provider['providerID'];
200 return intval($providerid);
203 // Log a message that is easy for the Re-Opened Visits Report to interpret.
205 public function logFSMessage($action)
207 EventAuditLogger::instance()->newEvent(
208 'fee-sheet',
209 $_SESSION['authUser'],
210 $_SESSION['authProvider'],
212 $action,
213 $this->pid,
214 $this->encounter
218 // Compute a current checksum of this encounter's Fee Sheet data from the database.
220 public function visitChecksum($saved = false)
222 $rowb = sqlQuery(
223 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
224 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
225 "))) AS checksum FROM billing WHERE " .
226 "pid = ? AND encounter = ? AND activity = 1",
227 array($this->pid, $this->encounter)
229 $rowp = sqlQuery(
230 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
231 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
232 "))) AS checksum FROM drug_sales WHERE " .
233 "pid = ? AND encounter = ?",
234 array($this->pid, $this->encounter)
236 $ret = intval($rowb['checksum']) ^ intval($rowp['checksum']);
237 if (CHECKSUM_LOGGING) {
238 $comment = "Checksum = '$ret'";
239 $comment .= ", Saved = " . ($saved ? "true" : "false");
240 EventAuditLogger::instance()->newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid);
243 return $ret;
246 // IPPF-specific; get contraception attributes of the related codes.
248 public function checkRelatedForContraception($related_code, $is_initial_consult = false)
250 $this->line_contra_code = '';
251 $this->line_contra_cyp = 0;
252 $this->line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
253 if (!empty($related_code)) {
254 $relcodes = explode(';', $related_code);
255 foreach ($relcodes as $relstring) {
256 if ($relstring === '') {
257 continue;
260 list($reltype, $relcode) = explode(':', $relstring);
261 if ($reltype !== 'IPPFCM') {
262 continue;
265 $methtype = $is_initial_consult ? 2 : 1;
266 $tmprow = sqlQuery("SELECT cyp_factor FROM codes WHERE " .
267 "code_type = '32' AND code = ? LIMIT 1", array($relcode));
268 $cyp = 0 + $tmprow['cyp_factor'];
269 if ($cyp > $this->line_contra_cyp) {
270 $this->line_contra_cyp = $cyp;
271 // Note this is an IPPFCM code, not an IPPF2 code.
272 $this->line_contra_code = $relcode;
273 $this->line_contra_methtype = $methtype;
279 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
280 // This is only needed for auto-creating Contraception forms.
282 public function insert_lbf_item($form_id, $field_id, $field_value)
284 if ($form_id) {
285 sqlStatement("INSERT INTO lbf_data (form_id, field_id, field_value) " .
286 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
287 } else {
288 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
289 "VALUES (?, ?)", array($field_id, $field_value));
292 return $form_id;
295 // Create an array of data for a particular billing table item that is useful
296 // for building a user interface form row. $args is an array containing:
297 // codetype
298 // code
299 // modifier
300 // ndc_info
301 // auth
302 // del
303 // units
304 // fee
305 // id
306 // billed
307 // code_text
308 // justify
309 // provider_id
310 // notecodes
311 // pricelevel
312 public function addServiceLineItem($args)
314 global $code_types;
316 // echo "<!-- \n"; // debugging
317 // print_r($args); // debugging
318 // echo "--> \n"; // debugging
320 $li = array();
321 $li['hidden'] = array();
323 $codetype = $args['codetype'];
324 $code = $args['code'];
325 $revenue_code = isset($args['revenue_code']) ? $args['revenue_code'] : '';
326 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
327 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
328 $units = isset($args['units']) ? $args['units'] : 0;
329 $units = max(1, intval($units));
330 $billed = !empty($args['billed']);
331 $auth = !empty($args['auth']);
332 $id = isset($args['id']) ? intval($args['id']) : 0;
333 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
334 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
335 $justify = isset($args['justify']) ? $args['justify'] : '';
336 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
337 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
338 // Price level should be unset only if adding a new line item.
339 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
340 $del = !empty($args['del']);
342 // If using line item billing and user wishes to default to a selected provider, then do so.
343 if (!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
344 if ($provider_id == 0) {
345 $provider_id = 0 + $this->findProvider();
349 if ($codetype == 'COPAY') {
350 if (!$code_text) {
351 $code_text = 'Cash';
354 if ($fee > 0) {
355 $fee = 0 - $fee;
359 // Get the matching entry from the codes table.
360 $sqlArray = array();
361 $query = "SELECT id, units, code_text, revenue_code FROM codes WHERE " .
362 "code_type = ? AND code = ?";
363 array_push($sqlArray, $code_types[$codetype]['id'], $code);
364 if ($modifier) {
365 $query .= " AND modifier = ?";
366 array_push($sqlArray, $modifier);
367 } else {
368 $query .= " AND (modifier IS NULL OR modifier = '')";
371 $result = sqlQuery($query, $sqlArray);
372 $codes_id = $result['id'];
373 $revenue_code = $revenue_code ? $revenue_code : $result['revenue_code'];
374 if (!$code_text) {
375 $code_text = $result['code_text'];
376 if (empty($units)) {
377 $units = max(1, intval($result['units']));
380 if (!isset($args['fee'])) {
381 // Fees come from the prices table now.
382 $query = "SELECT pr_price FROM prices WHERE " .
383 "pr_id = ? AND pr_selector = '' AND pr_level = ? " .
384 "LIMIT 1";
385 // echo "\n<!-- $query -->\n"; // debugging
386 $prrow = sqlQuery($query, array($codes_id, $pricelevel));
387 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
391 $fee = sprintf('%01.2f', $fee);
393 $li['hidden']['code_type'] = $codetype;
394 $li['hidden']['code'] = $code;
395 $li['hidden']['revenue_code'] = $revenue_code;
396 $li['hidden']['mod'] = $modifier;
397 $li['hidden']['billed'] = $billed;
398 $li['hidden']['id'] = $id;
399 $li['hidden']['codes_id'] = $codes_id;
401 // This logic is only used for family planning clinics, and then only when
402 // the option is chosen to use or auto-generate Contraception forms.
403 // It adds contraceptive method and effectiveness to relevant lines.
404 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
405 $codesrow = sqlQuery(
406 "SELECT related_code, cyp_factor FROM codes WHERE " .
407 "code_type = ? AND code = ? LIMIT 1",
408 array($code_types[$codetype]['id'], $code)
410 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
411 if ($this->line_contra_code) {
412 $li['hidden']['method' ] = $this->line_contra_code;
413 $li['hidden']['cyp' ] = $this->line_contra_cyp;
414 $li['hidden']['methtype'] = $this->line_contra_methtype;
415 // contraception_code is only concerned with initial consults.
416 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
417 $this->contraception_cyp = $this->line_contra_cyp;
418 $this->contraception_code = $this->line_contra_code;
423 if ($codetype == 'COPAY') {
424 $li['codetype'] = xl($codetype);
425 if ($ndc_info) {
426 $li['codetype'] .= " ($ndc_info)";
429 $ndc_info = '';
430 } else {
431 $li['codetype'] = $codetype;
434 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
435 $li['revenue_code' ] = $revenue_code;
436 $li['mod' ] = $modifier;
437 $li['fee' ] = $fee;
438 $li['price' ] = $fee / $units;
439 $li['pricelevel'] = $pricelevel;
440 $li['units' ] = $units;
441 $li['provid' ] = $provider_id;
442 $li['justify' ] = $justify;
443 $li['notecodes'] = $notecodes;
444 $li['del' ] = $id && $del;
445 $li['code_text'] = $code_text;
446 $li['auth' ] = $auth;
448 $li['hidden']['price'] = $li['price'];
450 // If NDC info exists or may be required, add stuff for it.
451 if ($codetype == 'HCPCS' && !$billed) {
452 $ndcnum = '';
453 $ndcuom = '';
454 $ndcqty = '';
455 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
456 $ndcnum = $tmp[1];
457 $ndcuom = $tmp[2];
458 $ndcqty = $tmp[3];
461 $li['ndcnum' ] = $ndcnum;
462 $li['ndcuom' ] = $ndcuom;
463 $li['ndcqty' ] = $ndcqty;
464 } else if ($ndc_info) {
465 $li['ndc_info' ] = $ndc_info;
468 // For Family Planning.
469 if ($codetype == 'MA') {
470 ++$this->required_code_count;
473 if ($fee != 0) {
474 $this->hasCharges = true;
477 $this->serviceitems[] = $li;
480 // Create an array of data for a particular drug_sales table item that is useful
481 // for building a user interface form row. $args is an array containing:
482 // drug_id
483 // selector
484 // sale_id
485 // rx (boolean)
486 // del (boolean)
487 // units
488 // fee
489 // billed
490 // warehouse_id
491 // pricelevel
493 public function addProductLineItem($args)
495 global $code_types;
497 $li = array();
498 $li['hidden'] = array();
500 $drug_id = $args['drug_id'];
501 $selector = isset($args['selector']) ? $args['selector'] : '';
502 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
503 $units = isset($args['units']) ? $args['units'] : 0;
504 $units = max(1, intval($units));
505 $billed = !empty($args['billed']);
506 $rx = !empty($args['rx']);
507 $del = !empty($args['del']);
508 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
509 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
510 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
512 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id));
513 $code_text = $drow['name'];
515 // If no warehouse ID passed, use the logged-in user's default.
516 if ($this->got_warehouses && $warehouse_id === '') {
517 $warehouse_id = $this->default_warehouse;
520 // If fee is not provided, get it from the prices table.
521 // It is assumed in this case that units will match what is in the product template.
522 if (!isset($args['fee'])) {
523 $query = "SELECT pr_price FROM prices WHERE " .
524 "pr_id = ? AND pr_selector = ? AND pr_level = ? " .
525 "LIMIT 1";
526 $prrow = sqlQuery($query, array($drug_id, $selector, $pricelevel));
527 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
530 $fee = sprintf('%01.2f', $fee);
532 $li['fee' ] = $fee;
533 $li['price' ] = $fee / $units;
534 $li['pricelevel'] = $pricelevel;
535 $li['units' ] = $units;
536 $li['del' ] = $sale_id && $del;
537 $li['code_text'] = $code_text;
538 $li['warehouse'] = $warehouse_id;
539 $li['rx' ] = $rx;
541 $li['hidden']['drug_id'] = $drug_id;
542 $li['hidden']['selector'] = $selector;
543 $li['hidden']['sale_id'] = $sale_id;
544 $li['hidden']['billed' ] = $billed;
545 $li['hidden']['price' ] = $li['price'];
547 // This logic is only used for family planning clinics, and then only when
548 // the option is chosen to use or auto-generate Contraception forms.
549 // It adds contraceptive method and effectiveness to relevant lines.
550 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
551 $this->checkRelatedForContraception($drow['related_code']);
552 if ($this->line_contra_code) {
553 $li['hidden']['method' ] = $this->line_contra_code;
554 $li['hidden']['methtype'] = $this->line_contra_methtype;
558 // For Family Planning.
559 ++$this->required_code_count;
560 if ($fee != 0) {
561 $this->hasCharges = true;
564 $this->productitems[] = $li;
567 // Generate rows for items already in the billing table for this encounter.
569 public function loadServiceItems()
571 $billresult = BillingUtilities::getBillingByEncounter($this->pid, $this->encounter, "*");
572 if ($billresult) {
573 foreach ($billresult as $iter) {
574 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') {
575 continue;
578 $justify = trim($iter['justify']);
579 if ($justify) {
580 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
583 $this->addServiceLineItem(array(
584 'id' => $iter['id'],
585 'codetype' => $iter['code_type'],
586 'code' => trim($iter['code']),
587 'revenue_code' => trim($iter["revenue_code"]),
588 'modifier' => trim($iter["modifier"]),
589 'code_text' => trim($iter['code_text']),
590 'units' => $iter['units'],
591 'fee' => $iter['fee'],
592 'pricelevel' => $iter['pricelevel'],
593 'billed' => $iter['billed'],
594 'ndc_info' => $iter['ndc_info'],
595 'provider_id' => $iter['provider_id'],
596 'justify' => $justify,
597 'notecodes' => trim($iter['notecodes']),
602 // echo "<!-- \n"; // debugging
603 // print_r($this->serviceitems); // debugging
604 // echo "--> \n"; // debugging
607 // Generate rows for items already in the drug_sales table for this encounter.
609 public function loadProductItems()
611 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
612 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
613 "ORDER BY ds.sale_id";
614 $sres = sqlStatement($query, array($this->pid, $this->encounter));
615 while ($srow = sqlFetchArray($sres)) {
616 $this->addProductLineItem(array(
617 'drug_id' => $srow['drug_id'],
618 'selector' => $srow['selector'],
619 'sale_id' => $srow['sale_id'],
620 'rx' => !empty($srow['prescription_id']),
621 'units' => $srow['quantity'],
622 'fee' => $srow['fee'],
623 'pricelevel' => $srow['pricelevel'],
624 'billed' => $srow['billed'],
625 'warehouse_id' => $srow['warehouse_id'],
630 // Check for insufficient product inventory levels.
631 // Returns an error message if any product items cannot be filled.
632 // You must call this before save().
634 public function checkInventory(&$prod)
636 $alertmsg = '';
637 $insufficient = 0;
638 $expiredlots = false;
639 if (is_array($prod)) {
640 foreach ($prod as $iter) {
641 if (!empty($iter['billed'])) {
642 continue;
645 $drug_id = $iter['drug_id'];
646 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
647 $units = empty($iter['units']) ? 1 : intval($iter['units']);
648 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
650 // Deleting always works.
651 if (!empty($iter['del'])) {
652 continue;
655 // If the item is already in the database...
656 if ($sale_id) {
657 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
658 "FROM drug_sales AS ds " .
659 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
660 "WHERE ds.sale_id = ?";
661 $dirow = sqlQuery($query, array($sale_id));
662 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
663 if (!empty($dirow['inventory_id'])) {
664 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
665 // Changing warehouse so check inventory in the new warehouse.
666 // Nothing is updated by this call.
667 if (!sellDrug(
668 $drug_id,
669 $units,
671 $this->pid,
672 $this->encounter,
674 $this->visit_date,
676 $warehouse_id,
677 true,
678 $expiredlots
679 )) {
680 $insufficient = $drug_id;
682 } else {
683 if (($dirow['on_hand'] + $dirow['quantity'] - $units) < 0) {
684 $insufficient = $drug_id;
688 } // Otherwise it's a new item...
689 else {
690 // This only checks for sufficient inventory, nothing is updated.
691 if (!sellDrug(
692 $drug_id,
693 $units,
695 $this->pid,
696 $this->encounter,
698 $this->visit_date,
700 $warehouse_id,
701 true,
702 $expiredlots
703 )) {
704 $insufficient = $drug_id;
707 } // end for
710 if ($insufficient) {
711 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
712 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
713 if ($expiredlots) {
714 $alertmsg .= " " . xl('Check expiration dates.');
718 return $alertmsg;
721 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
722 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
724 public function save(
725 &$bill,
726 &$prod,
727 $main_provid = null,
728 $main_supid = null,
729 $default_warehouse = null,
730 $mark_as_closed = false
732 global $code_types;
734 if (isset($main_provid) && $main_supid == $main_provid) {
735 $main_supid = 0;
738 $copay_update = false;
739 $update_session_id = '';
740 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
741 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
742 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
744 if (is_array($bill)) {
745 foreach ($bill as $iter) {
746 // Skip disabled (billed) line items.
747 if (!empty($iter['billed'])) {
748 continue;
751 $id = $iter['id'];
752 $code_type = $iter['code_type'];
753 $code = $iter['code'];
754 $del = !empty($iter['del']);
755 $units = empty($iter['units']) ? 1 : intval($iter['units']);
756 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
757 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
758 $revenue_code = empty($iter['revenue_code']) ? '' : trim($iter['revenue_code']);
759 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
760 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
761 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
762 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
764 $fee = sprintf('%01.2f', $price * $units);
766 if (!$cod0 && $code_types[$code_type]['fee'] == 1) {
767 $mod0 = $modifier;
768 $cod0 = $code;
769 $ct0 = $code_type;
772 if ($code_type == 'COPAY') {
773 if ($fee < 0) {
774 $fee = $fee * -1;
777 if (!$id) {
778 // adding new copay from fee sheet into ar_session and ar_activity tables
779 $session_id = sqlInsert(
780 "INSERT INTO ar_session " .
781 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
782 "adjustment_code, post_to_date) " .
783 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
784 array($_SESSION['authId'], $fee, $this->pid)
786 sqlBeginTrans();
787 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
788 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
789 SqlStatement(
790 "INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
791 "payer_type, post_time, post_user, session_id, " .
792 "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
793 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
794 $_SESSION['authId'],
795 $session_id,
796 $fee)
798 sqlCommitTrans();
799 } else {
800 // editing copay saved to ar_session and ar_activity
801 $session_id = $id;
802 $res_amount = sqlQuery(
803 "SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?",
804 array($this->pid, $this->encounter, $session_id)
806 if ($fee != $res_amount['pay_amount']) {
807 sqlStatement(
808 "UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?",
809 array($_SESSION['authId'], $fee, $session_id)
811 sqlStatement(
812 "UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now(),".
813 "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?",
814 array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id)
819 if (!$cod0) {
820 $copay_update = true;
821 $update_session_id = $session_id;
824 continue;
827 # Code to create justification for all codes based on first justification
828 if ($GLOBALS['replicate_justification'] == '1') {
829 if ($justify != '') {
830 $autojustify = $justify;
834 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
835 $justify = $autojustify;
838 if ($justify) {
839 $justify = str_replace(',', ':', $justify) . ':';
842 $auth = "1";
844 $ndc_info = '';
845 if (!empty($iter['ndcnum'])) {
846 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
847 trim($iter['ndcqty']);
850 // If the item is already in the database...
851 if ($id) {
852 if ($del) {
853 $this->logFSMessage(xl('Service deleted'));
854 BillingUtilities::deleteBilling($id);
855 } else {
856 $tmp = sqlQuery(
857 "SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1",
858 array($id)
860 if (!empty($tmp)) {
861 $tmparr = array('code' => $code, 'authorized' => $auth);
862 if (isset($iter['units' ])) {
863 $tmparr['units' ] = $units;
866 if (isset($iter['price' ])) {
867 $tmparr['fee' ] = $fee;
870 if (isset($iter['pricelevel'])) {
871 $tmparr['pricelevel'] = $pricelevel;
874 if (isset($iter['mod' ])) {
875 $tmparr['modifier' ] = $modifier;
878 if (isset($iter['provid' ])) {
879 $tmparr['provider_id'] = $provid;
882 if (isset($iter['ndcnum' ])) {
883 $tmparr['ndc_info' ] = $ndc_info;
886 if (isset($iter['justify' ])) {
887 $tmparr['justify' ] = $justify;
890 if (isset($iter['notecodes'])) {
891 $tmparr['notecodes' ] = $notecodes;
894 if (isset($iter['revenue_code'])) {
895 $tmparr['revenue_code'] = $revenue_code;
898 foreach ($tmparr as $key => $value) {
899 if ($tmp[$key] != $value) {
900 if ('fee' == $key) {
901 $this->logFSMessage(xl('Price changed'));
904 if ('units' == $key) {
905 $this->logFSMessage(xl('Quantity changed'));
908 if ('provider_id' == $key) {
909 $this->logFSMessage(xl('Service provider changed'));
912 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
917 } // Otherwise it's a new item...
918 else if (!$del) {
919 $this->logFSMessage(xl('Service added'));
920 $code_text = lookup_code_descriptions($code_type.":".$code);
921 BillingUtilities::addBilling(
922 $this->encounter,
923 $code_type,
924 $code,
925 $code_text,
926 $this->pid,
927 $auth,
928 $provid,
929 $modifier,
930 $units,
931 $fee,
932 $ndc_info,
933 $justify,
935 $notecodes,
936 $pricelevel,
937 $revenue_code
940 } // end for
943 // if modifier is not inserted during loop update the record using the first
944 // non-empty modifier and code
945 if ($copay_update == true && $update_session_id != '' && $mod0 != '') {
946 sqlStatement(
947 "UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?".
948 " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
949 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id)
953 // Doing similarly to the above but for products.
954 if (is_array($prod)) {
955 foreach ($prod as $iter) {
956 // Skip disabled (billed) line items.
957 if (!empty($iter['billed'])) {
958 continue;
961 $drug_id = $iter['drug_id'];
962 $selector = empty($iter['selector']) ? '' : $iter['selector'];
963 $sale_id = $iter['sale_id']; // present only if already saved
964 $units = max(1, intval(trim($iter['units'])));
965 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
966 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
967 $fee = sprintf('%01.2f', $price * $units);
968 $del = !empty($iter['del']);
969 $rxid = 0;
970 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
971 $somechange = false;
973 // If the item is already in the database...
974 if ($sale_id) {
975 $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
976 "ds.sale_date, di.warehouse_id " .
977 "FROM drug_sales AS ds " .
978 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
979 "WHERE ds.sale_id = ?", array($sale_id));
980 $rxid = 0 + $tmprow['prescription_id'];
981 if ($del) {
982 if (!empty($tmprow)) {
983 // Delete this sale and reverse its inventory update.
984 $this->logFSMessage(xl('Product deleted'));
985 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
986 if (!empty($tmprow['inventory_id'])) {
987 sqlStatement(
988 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
989 array($tmprow['quantity'], $tmprow['inventory_id'])
994 if ($rxid) {
995 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
997 } else {
998 // Modify the sale and adjust inventory accordingly.
999 if (!empty($tmprow)) {
1000 foreach (array(
1001 'quantity' => $units,
1002 'fee' => $fee,
1003 'pricelevel' => $pricelevel,
1004 'selector' => $selector,
1005 'sale_date' => $this->visit_date,
1006 ) as $key => $value) {
1007 if ($tmprow[$key] != $value) {
1008 $somechange = true;
1009 if ('fee' == $key) {
1010 $this->logFSMessage(xl('Price changed'));
1013 if ('pricelevel' == $key) {
1014 $this->logFSMessage(xl('Price level changed'));
1017 if ('selector' == $key) {
1018 $this->logFSMessage(xl('Template selector changed'));
1021 if ('quantity' == $key) {
1022 $this->logFSMessage(xl('Quantity changed'));
1025 sqlStatement(
1026 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1027 array($value, $sale_id)
1029 if ($key == 'quantity' && $tmprow['inventory_id']) {
1030 sqlStatement(
1031 "UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
1032 array($units - $tmprow['quantity'], $tmprow['inventory_id'])
1038 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
1039 // Changing warehouse. Requires deleting and re-adding the sale.
1040 // Not setting $somechange because this alone does not affect a prescription.
1041 $this->logFSMessage(xl('Warehouse changed'));
1042 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1043 sqlStatement(
1044 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1045 array($units, $tmprow['inventory_id'])
1047 $tmpnull = null;
1048 $sale_id = sellDrug(
1049 $drug_id,
1050 $units,
1051 $fee,
1052 $this->pid,
1053 $this->encounter,
1054 (empty($iter['rx']) ? 0 : $rxid),
1055 $this->visit_date,
1057 $warehouse_id,
1058 false,
1059 $tmpnull,
1060 $pricelevel,
1061 $selector
1066 // Delete Rx if $rxid and flag not set.
1067 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
1068 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
1069 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1072 } // Otherwise it's a new item...
1073 else if (! $del) {
1074 $somechange = true;
1075 $this->logFSMessage(xl('Product added'));
1076 $tmpnull = null;
1077 $sale_id = sellDrug(
1078 $drug_id,
1079 $units,
1080 $fee,
1081 $this->pid,
1082 $this->encounter,
1084 $this->visit_date,
1086 $warehouse_id,
1087 false,
1088 $tmpnull,
1089 $pricelevel,
1090 $selector
1092 if (!$sale_id) {
1093 die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
1097 // If a prescription applies, create or update it.
1098 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
1099 // If an active rx already exists for this drug and date we will
1100 // replace it, otherwise we'll make a new one.
1101 if (empty($rxid)) {
1102 $rxid = '';
1105 // Get default drug attributes; prefer the template with the matching selector.
1106 $drow = sqlQuery(
1107 "SELECT dt.*, " .
1108 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
1109 "FROM drugs AS d, drug_templates AS dt WHERE " .
1110 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
1111 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
1112 array($drug_id, $selector)
1114 if (!empty($drow)) {
1115 $rxobj = new Prescription($rxid);
1116 $rxobj->set_patient_id($this->pid);
1117 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
1118 $rxobj->set_drug_id($drug_id);
1119 $rxobj->set_quantity($units);
1120 $rxobj->set_per_refill($units);
1121 $rxobj->set_start_date_y(substr($this->visit_date, 0, 4));
1122 $rxobj->set_start_date_m(substr($this->visit_date, 5, 2));
1123 $rxobj->set_start_date_d(substr($this->visit_date, 8, 2));
1124 $rxobj->set_date_added($this->visit_date);
1125 // Remaining attributes are the drug and template defaults.
1126 $rxobj->set_drug($drow['name']);
1127 $rxobj->set_unit($drow['unit']);
1128 $rxobj->set_dosage($drow['dosage']);
1129 $rxobj->set_form($drow['form']);
1130 $rxobj->set_refills($drow['refills']);
1131 $rxobj->set_size($drow['size']);
1132 $rxobj->set_route($drow['route']);
1133 $rxobj->set_interval($drow['period']);
1134 $rxobj->set_substitute($drow['substitute']);
1136 $rxobj->persist();
1137 // Set drug_sales.prescription_id to $rxobj->get_id().
1138 $oldrxid = $rxid;
1139 $rxid = 0 + $rxobj->get_id();
1140 if ($rxid != $oldrxid) {
1141 sqlStatement(
1142 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1143 array($rxid, $sale_id)
1148 } // end for
1151 // Set default and/or supervising provider for the encounter.
1152 if (isset($main_provid) && $main_provid != $this->provider_id) {
1153 $this->logFSMessage(xl('Default provider changed'));
1154 sqlStatement(
1155 "UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
1156 array($main_provid, $this->pid, $this->encounter)
1158 $this->provider_id = $main_provid;
1161 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
1162 sqlStatement(
1163 "UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
1164 array($main_supid, $this->pid, $this->encounter)
1166 $this->supervisor_id = $main_supid;
1169 // Save-and-Close is currently specific to Family Planning but might be more
1170 // generally useful. It provides the ability to mark an encounter as billed
1171 // directly from the Fee Sheet, if there are no charges.
1172 if ($mark_as_closed) {
1173 $tmp1 = sqlQuery(
1174 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
1175 "pid = ? AND encounter = ? AND billed = 0",
1176 array($this->pid, $this->encounter)
1178 $tmp2 = sqlQuery(
1179 "SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
1180 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1181 array($this->pid, $this->encounter)
1183 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
1184 sqlStatement(
1185 "update drug_sales SET billed = 1 WHERE " .
1186 "pid = ? AND encounter = ? AND billed = 0",
1187 array($this->pid, $this->encounter)
1189 sqlStatement(
1190 "UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
1191 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1192 array($this->pid, $this->encounter)
1194 } else {
1195 // Would be good to display an error message here... they clicked
1196 // Save and Close but the close could not be done. However the
1197 // framework does not provide an easy way to do that.
1202 // Call this after save() for Family Planning implementations.
1203 // It checks the contraception form, or makes a new one if $newmauser is set.
1204 // Returns 0 unless user intervention is required to fix a missing or incorrect form,
1205 // and in that case the return value is an existing form ID, or -1 if none.
1207 // Returns FALSE if user intervention is required to fix a missing or incorrect form.
1209 public function doContraceptionForm($ippfconmeth = null, $newmauser = null, $main_provid = 0)
1211 if (!empty($ippfconmeth)) {
1212 $csrow = sqlQuery(
1213 "SELECT f.form_id, ld.field_value FROM forms AS f " .
1214 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
1215 "WHERE " .
1216 "f.pid = ? AND f.encounter = ? AND " .
1217 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
1218 "ORDER BY f.form_id DESC LIMIT 1",
1219 array($this->pid, $this->encounter)
1221 if (isset($newmauser)) {
1222 // pastmodern is 0 iff new to modern contraception
1223 $pastmodern = $newmauser == '2' ? 0 : 1;
1224 if ($newmauser == '2') {
1225 $newmauser = '1';
1228 // Add contraception form but only if it does not already exist
1229 // (if it does, must be 2 users working on the visit concurrently).
1230 if (empty($csrow)) {
1231 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
1232 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
1233 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
1234 // Do we care about a service-specific provider here?
1235 $this->insert_lbf_item($newid, 'provider', $main_provid);
1236 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
1238 } else if (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
1239 // Contraceptive method does not match what is in an existing Contraception
1240 // form for this visit, or there is no such form. User intervention is needed.
1241 return empty($csrow) ? -1 : intval($csrow['form_id']);
1245 return 0;
1248 // Get price level from patient demographics.
1250 public function getPriceLevel()
1252 return $this->patient_pricelevel;
1255 // Update price level in patient demographics if it's changed.
1257 public function updatePriceLevel($pricelevel)
1259 if (!empty($pricelevel)) {
1260 if ($this->patient_pricelevel != $pricelevel) {
1261 $this->logFSMessage(xl('Price level changed'));
1262 sqlStatement(
1263 "UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1264 array($pricelevel, $this->pid)
1266 $this->patient_pricelevel = $pricelevel;
1271 // Create JSON string representing code type, code and selector.
1272 // This can be a checkbox value for parsing when the checkbox is clicked.
1273 // As a side effect note if the code is already selected in the Fee Sheet.
1275 public function genCodeSelectorValue($codes)
1277 global $code_types;
1278 list($codetype, $code, $selector) = explode(':', $codes);
1279 if ($codetype == 'PROD') {
1280 $crow = sqlQuery(
1281 "SELECT sale_id " .
1282 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1283 "LIMIT 1",
1284 array($this->pid, $this->encounter, $code)
1286 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
1287 $cbarray = array($codetype, $code, $selector);
1288 } else {
1289 $crow = sqlQuery(
1290 "SELECT c.id AS code_id, b.id " .
1291 "FROM codes AS c " .
1292 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1293 "WHERE c.code_type = ? AND c.code = ? LIMIT 1",
1294 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code)
1296 $this->code_is_in_fee_sheet = !empty($crow['id']);
1297 $cbarray = array($codetype, $code);
1300 $cbval = json_encode($cbarray);
1301 return $cbval;