4 * library/FeeSheet.class.php
6 * Base class for implementations of the Fee Sheet.
7 * This should not include UI but may be extended by a class that does.
9 * LICENSE: This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 3
12 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see
19 * http://www.gnu.org/licenses/licenses.html#GPL .
22 * @license https://www.gnu.org/licenses/licenses.html#GPL GNU GPL V3+
23 * @author Rod Roark <rod@sunsetsystems.com>
24 * @link http://www.open-emr.org
27 require_once(dirname(__FILE__
) . "/../interface/globals.php");
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\Acl\AclMain
;
36 use OpenEMR\Common\Logging\EventAuditLogger
;
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");
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(
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)
96 $pid = $GLOBALS['pid'];
99 if (empty($encounter)) {
100 $encounter = $GLOBALS['encounter'];
104 $this->encounter
= $encounter;
106 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
107 $this->ALLOW_COPAYS
= empty($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;
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)
149 foreach ($code_types as $key => $value) {
150 if ($value['id'] == $id) {
158 // Compute age in years given a DOB and "as of" date.
160 public static function getAge($dob, $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])) {
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'];
188 $get_authorized = $_SESSION['userauthorized'];
189 if ($get_authorized == 1) {
190 $providerid = $_SESSION['authUserID'];
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 // Close the designated visit, making sure it has no charges.
205 public static function closeVisit($pid, $encounter)
208 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
209 "pid = ? AND encounter = ? AND billed = 0",
210 array($pid, $encounter)
213 "SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
214 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1 AND code_type != 'TAX'",
215 array($pid, $encounter)
217 if ($tmp1['sum'] +
$tmp2['sum'] == 0) {
218 $this_bill_date = date('Y-m-d H:i:s');
220 "update drug_sales SET billed = 1, bill_date = ? WHERE " .
221 "pid = ? AND encounter = ? AND billed = 0",
222 array($this_bill_date, $pid, $encounter)
224 // Unbilled tax would have been recomputed at checkout and is invalid here.
226 "UPDATE billing SET activity = 0 WHERE " .
227 "pid = ? AND encounter = ? AND code_type = 'TAX' AND activity = 1 AND billed = 0",
228 array($pid, $encounter)
231 "UPDATE billing SET billed = 1, bill_date = ? WHERE " .
232 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
233 array($this_bill_date, $pid, $encounter)
235 // Generate and set invoice reference number if appropriate.
237 "SELECT invoice_refno FROM form_encounter WHERE pid = ? AND encounter = ?",
238 array($pid, $encounter)
240 if (empty($tmprow['invoice_refno'])) { // not empty means there was a previous checkout
241 $refno = updateInvoiceRefNumber();
242 if ($refno) { // means user has an invoice refno pool
244 "UPDATE form_encounter SET invoice_refno = ? WHERE pid = ? AND encounter = ?",
245 array($refno, $pid, $encounter)
250 return xl('Cannot close because there are charges. Check out instead.');
255 public static function getBasicUnits($drug_id, $selector)
259 "SELECT quantity FROM drug_templates WHERE drug_id = ? AND selector = ?",
260 array($drug_id, $selector)
262 if (!empty($tmp['quantity'])) {
263 $basic_units = 0 +
$tmp['quantity'];
271 // Log a message that is easy for the Re-Opened Visits Report to interpret.
272 // The optional $logarr contains these line item attributes:
275 // Selector (for code type "PROD")
282 public function logFSMessage($action, $newvalue = '', $logarr = null)
284 $user_notes = $this->encounter
;
285 if (is_array($logarr)) {
286 array_unshift($logarr, $newvalue);
287 foreach ($logarr as $tmp) {
288 $user_notes .= '|' . str_replace('|', '', $tmp);
292 EventAuditLogger
::instance()->newEvent(
294 $_SESSION['authUser'],
295 $_SESSION['authProvider'],
303 // Compute a current checksum of this encounter's Fee Sheet data from the database.
305 public function visitChecksum($saved = false)
308 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
309 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
310 "))) AS checksum FROM billing WHERE " .
311 "pid = ? AND encounter = ? AND activity = 1",
312 array($this->pid
, $this->encounter
)
315 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
316 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
317 "))) AS checksum FROM drug_sales WHERE " .
318 "pid = ? AND encounter = ?",
319 array($this->pid
, $this->encounter
)
322 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
323 "id, date, provider_id, supervisor_id, last_level_billed, last_level_closed" .
324 "))) AS checksum FROM form_encounter WHERE " .
325 "pid = ? AND encounter = ?",
326 array($this->pid
, $this->encounter
)
328 $ret = intval($rowb['checksum']) ^
intval($rowp['checksum']) ^
intval($rowv['checksum']);
329 if (CHECKSUM_LOGGING
) {
330 $comment = "Checksum = '$ret'";
331 $comment .= ", Saved = " . ($saved ?
"true" : "false");
332 EventAuditLogger
::instance()->newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid
);
337 // IPPF-specific; get contraception attributes of the related codes.
339 public function checkRelatedForContraception($related_code, $is_initial_consult = false)
341 $this->line_contra_code
= '';
342 $this->line_contra_cyp
= 0;
343 $this->line_contra_methtype
= 0; // 0 = None, 1 = Not initial, 2 = Initial consult
344 if (!empty($related_code)) {
345 $relcodes = explode(';', $related_code);
346 foreach ($relcodes as $relstring) {
347 if ($relstring === '') {
351 list($reltype, $relcode) = explode(':', $relstring);
352 if ($reltype !== 'IPPFCM') {
356 $methtype = $is_initial_consult ?
2 : 1;
358 "SELECT cyp_factor FROM codes WHERE " .
359 "code_type = '32' AND code = ? ORDER BY active DESC, id LIMIT 1",
362 $cyp = 0 +
$tmprow['cyp_factor'];
363 if ($cyp > $this->line_contra_cyp
) {
364 $this->line_contra_cyp
= $cyp;
365 // Note this is an IPPFCM code, not an IPPF2 code.
366 $this->line_contra_code
= $relcode;
367 $this->line_contra_methtype
= $methtype;
373 /******************************************************************
374 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
375 // This is only needed for auto-creating Contraception forms.
377 public function insert_lbf_item($form_id, $field_id, $field_value)
380 sqlStatement("INSERT INTO lbf_data (form_id, field_id, field_value) " .
381 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
383 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
384 "VALUES (?, ?)", array($field_id, $field_value));
389 ******************************************************************/
391 // Insert a row into the shared_attributes table.
392 // This is only needed for auto-creating Contraception forms.
394 public function insert_lbf_item($field_id, $field_value)
397 "INSERT INTO shared_attributes (pid, encounter, last_update, user_id, field_id, field_value) " .
398 "VALUES (?, ?, 'NOW()', ?, ?, ?)",
399 array($this->pid
, $this->encounter
, $_SESSION['authId'], $field_id, $field_value)
403 // Create an array of data for a particular billing table item that is useful
404 // for building a user interface form row. $args is an array containing:
420 public function addServiceLineItem($args)
424 // echo "<!-- \n"; // debugging
425 // print_r($args); // debugging
426 // echo "--> \n"; // debugging
429 $li['hidden'] = array();
431 $codetype = $args['codetype'];
432 $code = $args['code'];
433 $revenue_code = isset($args['revenue_code']) ?
$args['revenue_code'] : '';
434 $modifier = isset($args['modifier']) ?
$args['modifier'] : '';
435 $code_text = isset($args['code_text']) ?
$args['code_text'] : '';
436 $units = intval(isset($args['units']) ?
$args['units'] : 0);
437 $billed = !empty($args['billed']);
438 $auth = !empty($args['auth']);
439 $id = isset($args['id']) ?
intval($args['id']) : 0;
440 $ndc_info = isset($args['ndc_info']) ?
$args['ndc_info'] : '';
441 $provider_id = isset($args['provider_id']) ?
intval($args['provider_id']) : 0;
442 $justify = isset($args['justify']) ?
$args['justify'] : '';
443 $notecodes = isset($args['notecodes']) ?
$args['notecodes'] : '';
444 $fee = isset($args['fee']) ?
(0 +
$args['fee']) : 0;
445 // Price level should be unset only if adding a new line item.
446 $pricelevel = isset($args['pricelevel']) ?
$args['pricelevel'] : $this->patient_pricelevel
;
447 $del = !empty($args['del']);
449 // If using line item billing and user wishes to default to a selected provider, then do so.
450 if (!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
451 if ($provider_id == 0) {
452 $provider_id = 0 +
$this->findProvider();
456 if ($codetype == 'COPAY') {
466 // Get the matching entry from the codes table.
468 $query = "SELECT id, units, code_text, revenue_code FROM codes WHERE " .
469 "code_type = ? AND code = ?";
470 array_push($sqlArray, ($code_types[$codetype]['id'] ??
''), $code);
472 $query .= " AND modifier = ?";
473 array_push($sqlArray, $modifier);
475 $query .= " AND (modifier IS NULL OR modifier = '')";
477 $query .= " ORDER BY active DESC, id LIMIT 1";
478 $result = sqlQuery($query, $sqlArray);
479 $codes_id = $result['id'] ??
null;
480 $revenue_code = $revenue_code ?
$revenue_code : ($result['revenue_code'] ??
null);
482 $code_text = $result['code_text'] ??
null;
483 if (empty($units) && !empty($result)) {
484 $units = intval($result['units']);
487 if (!isset($args['fee'])) {
488 // Fees come from the prices table now.
489 $query = "SELECT pr_price, lo.option_id AS pr_level, lo.notes FROM list_options lo " .
490 " LEFT OUTER JOIN prices p ON lo.option_id=p.pr_level AND pr_id = ? AND pr_selector = '' " .
491 " WHERE lo.list_id='pricelevel' " .
493 // echo "\n<!-- $query -->\n"; // debugging
497 $prrecordset = sqlStatement($query, array($codes_id));
498 while ($row = sqlFetchArray($prrecordset)) {
499 if (empty($prdefault)) {
503 if ($row['pr_level'] === $pricelevel) {
509 if (!empty($prrow)) {
510 $fee = $prrow['pr_price'];
512 // if percent-based pricing is enabled...
513 if ($GLOBALS['enable_percent_pricing']) {
514 // if this price level is a percentage, calculate price from default price
515 if (!empty($prrow['notes']) && strpos($prrow['notes'], '%') > -1 && !empty($prdefault)) {
516 $percent = intval(str_replace('%', '', $prrow['notes']));
518 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
529 $fee = sprintf('%01.2f', $fee);
531 $li['hidden']['code_type'] = $codetype;
532 $li['hidden']['code'] = $code;
533 $li['hidden']['revenue_code'] = $revenue_code;
534 $li['hidden']['mod'] = $modifier;
535 $li['hidden']['billed'] = $billed;
536 $li['hidden']['id'] = $id;
537 $li['hidden']['codes_id'] = $codes_id;
539 // This logic is only used for family planning clinics, and then only when
540 // the option is chosen to use or auto-generate Contraception forms.
541 // It adds contraceptive method and effectiveness to relevant lines.
542 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
543 $codesrow = sqlQuery(
544 "SELECT related_code, cyp_factor FROM codes WHERE " .
545 "code_type = ? AND code = ? ORDER BY active DESC, id LIMIT 1",
546 array($code_types[$codetype]['id'], $code)
548 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
549 if ($this->line_contra_code
) {
550 $li['hidden']['method' ] = $this->line_contra_code
;
551 $li['hidden']['cyp' ] = $this->line_contra_cyp
;
552 $li['hidden']['methtype'] = $this->line_contra_methtype
;
553 // contraception_code is only concerned with initial consults.
554 if ($this->line_contra_cyp
> $this->contraception_cyp
&& $this->line_contra_methtype
== 2) {
555 $this->contraception_cyp
= $this->line_contra_cyp
;
556 $this->contraception_code
= $this->line_contra_code
;
561 if ($codetype == 'COPAY') {
562 $li['codetype'] = xl($codetype);
564 $li['codetype'] .= " ($ndc_info)";
568 $li['codetype'] = $codetype;
571 $li['code' ] = $codetype == 'COPAY' ?
'' : $code;
572 $li['revenue_code' ] = $revenue_code;
573 $li['mod' ] = $modifier;
575 $li['price' ] = $fee / $units;
576 $li['pricelevel'] = $pricelevel;
577 $li['units' ] = $units;
578 $li['provid' ] = $provider_id;
579 $li['justify' ] = $justify;
580 $li['notecodes'] = $notecodes;
581 $li['del' ] = $id && $del;
582 $li['code_text'] = $code_text;
583 $li['auth' ] = $auth;
585 $li['hidden']['price'] = $li['price'];
587 // If NDC info exists or may be required, add stuff for it.
588 if ($codetype == 'HCPCS' && !$billed) {
589 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
599 $li['ndcnum' ] = $ndcnum;
600 $li['ndcuom' ] = $ndcuom;
601 $li['ndcqty' ] = $ndcqty;
602 } elseif ($ndc_info) {
603 $li['ndc_info' ] = $ndc_info;
606 // For Family Planning.
607 if ($codetype == 'MA') {
608 ++
$this->required_code_count
;
612 $this->hasCharges
= true;
615 $this->serviceitems
[] = $li;
618 // Create an array of data for a particular drug_sales table item that is useful
619 // for building a user interface form row. $args is an array containing:
631 // Pass true for the 2nd argument if the data is coming from the database;
632 // if from user input, make it false.
634 public function addProductLineItem($args, $convert_units = true)
639 $li['hidden'] = array();
641 $drug_id = $args['drug_id'];
642 $selector = isset($args['selector']) ?
$args['selector'] : '';
643 $sale_id = isset($args['sale_id']) ?
intval($args['sale_id']) : 0;
644 $units = intval(isset($args['units']) ?
$args['units'] : 0);
648 $billed = !empty($args['billed']);
649 $rx = !empty($args['rx']);
650 $del = !empty($args['del']);
651 $fee = isset($args['fee']) ?
(0 +
$args['fee']) : 0;
652 $pricelevel = isset($args['pricelevel']) ?
$args['pricelevel'] : $this->patient_pricelevel
;
653 $warehouse_id = isset($args['warehouse_id']) ?
$args['warehouse_id'] : '';
655 if ($convert_units) {
656 // "Basic Units" is the quantity from the product template and is the number of
657 // inventory items in the package that the template represents.
658 // Units seen by the user should be inventory units divided by template quantity.
659 $units = $units / $this->getBasicUnits($drug_id, $selector);
662 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id));
663 $code_text = $drow['name'];
665 // If no warehouse ID passed, use the logged-in user's default.
666 if ($this->got_warehouses
&& $warehouse_id === '') {
667 $warehouse_id = $this->default_warehouse
;
670 // If fee is not provided, get it from the prices table.
671 // It is assumed in this case that units will match what is in the product template.
672 if (!isset($args['fee'])) {
673 $query = "SELECT pr_price, lo.option_id AS pr_level, lo.notes FROM list_options lo " .
674 " LEFT OUTER JOIN prices p ON lo.option_id=p.pr_level AND pr_id = ? AND pr_selector = ? " .
675 " WHERE lo.list_id='pricelevel' " .
680 $prrecordset = sqlStatement($query, array($drug_id, $selector));
681 while ($row = sqlFetchArray($prrecordset)) {
682 if (empty($prdefault)) {
686 if ($row['pr_level'] === $pricelevel) {
692 if (!empty($prrow)) {
693 $fee = $prrow['pr_price'];
695 // if percent-based pricing is enabled...
696 if ($GLOBALS['enable_percent_pricing']) {
697 // if this price level is a percentage, calculate price from default price
698 if (!empty($prrow['notes']) && strpos($prrow['notes'], '%') > -1 && !empty($prdefault)) {
699 $percent = intval(str_replace('%', '', $prrow['notes']));
701 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
708 $fee = sprintf('%01.2f', $fee);
711 $li['price' ] = $fee / $units;
712 $li['pricelevel'] = $pricelevel;
713 $li['units' ] = $units;
714 $li['del' ] = $sale_id && $del;
715 $li['code_text'] = $code_text;
716 $li['warehouse'] = $warehouse_id;
719 $li['hidden']['drug_id'] = $drug_id;
720 $li['hidden']['selector'] = $selector;
721 $li['hidden']['sale_id'] = $sale_id;
722 $li['hidden']['billed' ] = $billed;
723 $li['hidden']['price' ] = $li['price'];
725 // This logic is only used for family planning clinics, and then only when
726 // the option is chosen to use or auto-generate Contraception forms.
727 // It adds contraceptive method and effectiveness to relevant lines.
728 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
729 $this->checkRelatedForContraception($drow['related_code']);
730 if ($this->line_contra_code
) {
731 $li['hidden']['method' ] = $this->line_contra_code
;
732 $li['hidden']['methtype'] = $this->line_contra_methtype
;
736 // For Family Planning.
737 ++
$this->required_code_count
;
739 $this->hasCharges
= true;
742 $this->productitems
[] = $li;
745 // Generate rows for items already in the billing table for this encounter.
747 public function loadServiceItems()
749 $billresult = BillingUtilities
::getBillingByEncounter($this->pid
, $this->encounter
, "*");
751 foreach ($billresult as $iter) {
752 if (!$this->ALLOW_COPAYS
&& $iter["code_type"] == 'COPAY') {
756 $justify = trim($iter['justify']);
758 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
761 $this->addServiceLineItem(array(
763 'codetype' => $iter['code_type'],
764 'code' => trim($iter['code']),
765 'revenue_code' => trim($iter["revenue_code"]),
766 'modifier' => trim($iter["modifier"]),
767 'code_text' => trim($iter['code_text']),
768 'units' => $iter['units'],
769 'fee' => $iter['fee'],
770 'pricelevel' => $iter['pricelevel'],
771 'billed' => $iter['billed'],
772 'ndc_info' => $iter['ndc_info'],
773 'provider_id' => $iter['provider_id'],
774 'justify' => $justify,
775 'notecodes' => trim($iter['notecodes']),
780 // echo "<!-- \n"; // debugging
781 // print_r($this->serviceitems); // debugging
782 // echo "--> \n"; // debugging
785 // Generate rows for items already in the drug_sales table for this encounter.
787 public function loadProductItems()
789 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
790 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
791 "ORDER BY ds.sale_id";
792 $sres = sqlStatement($query, array($this->pid
, $this->encounter
));
793 while ($srow = sqlFetchArray($sres)) {
794 $this->addProductLineItem(
796 'drug_id' => $srow['drug_id'],
797 'selector' => $srow['selector'],
798 'sale_id' => $srow['sale_id'],
799 'rx' => !empty($srow['prescription_id']),
800 'units' => $srow['quantity'],
801 'fee' => $srow['fee'],
802 'pricelevel' => $srow['pricelevel'],
803 'billed' => $srow['billed'],
804 'warehouse_id' => $srow['warehouse_id'],
811 // Check for insufficient product inventory levels.
812 // Returns an error message if any product items cannot be filled.
813 // You must call this before save().
815 public function checkInventory(&$prod)
819 $expiredlots = false;
820 if (is_array($prod)) {
821 foreach ($prod as $iter) {
822 if (!empty($iter['billed'])) {
826 $drug_id = $iter['drug_id'];
827 $sale_id = empty($iter['sale_id']) ?
0 : intval($iter['sale_id']); // present only if already saved
828 $units = empty($iter['units']) ?
1 : intval($iter['units']);
829 $selector = empty($iter['selector']) ?
'' : $iter['selector'];
830 $inv_units = $units * $this->getBasicUnits($drug_id, $selector);
831 $warehouse_id = empty($iter['warehouse']) ?
'' : $iter['warehouse'];
833 // Deleting always works.
834 if (!empty($iter['del'])) {
838 // If the item is already in the database...
840 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
841 "FROM drug_sales AS ds " .
842 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
843 "WHERE ds.sale_id = ?";
844 $dirow = sqlQuery($query, array($sale_id));
845 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
846 if (!empty($dirow['inventory_id'])) {
847 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
848 // Changing warehouse so check inventory in the new warehouse.
849 // Nothing is updated by this call.
865 $insufficient = $drug_id;
868 if (($dirow['on_hand'] +
$dirow['quantity'] - $inv_units) < 0) {
869 $insufficient = $drug_id;
873 } else { // Otherwise it's a new item...
874 // This only checks for sufficient inventory, nothing is updated.
890 $insufficient = $drug_id;
897 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
898 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
900 $alertmsg .= " " . xl('Check expiration dates.');
907 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
908 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
910 public function save(
915 $default_warehouse = null,
916 $mark_as_closed = false
920 if (isset($main_provid) && $main_supid == $main_provid) {
924 $copay_update = false;
925 $update_session_id = '';
926 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
927 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
928 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
930 if (is_array($bill)) {
931 foreach ($bill as $iter) {
932 // Skip disabled (billed) line items.
933 if (!empty($iter['billed'])) {
937 $id = $iter['id'] ??
null;
938 $code_type = $iter['code_type'];
939 $code = $iter['code'];
940 $del = !empty($iter['del']);
941 $units = empty($iter['units']) ?
1 : intval($iter['units']);
942 $pricelevel = empty($iter['pricelevel']) ?
'' : $iter['pricelevel'];
943 $revenue_code = empty($iter['revenue_code']) ?
'' : trim($iter['revenue_code']);
944 $modifier = empty($iter['mod']) ?
'' : trim($iter['mod']);
945 $justify = empty($iter['justify' ]) ?
'' : trim($iter['justify']);
946 $notecodes = empty($iter['notecodes']) ?
'' : trim($iter['notecodes']);
947 $provid = empty($iter['provid' ]) ?
0 : intval($iter['provid']);
950 if (!empty($iter['price'])) {
951 if ($code_type == 'COPAY' ||
$this->pricesAuthorized()) {
952 $price = 0 +
trim($iter['price'] ??
0);
954 $price = $this->getPrice($pricelevel, $code_type, $code);
958 $fee = sprintf('%01.2f', $price * $units);
960 if (!$cod0 && $code_types[$code_type]['fee'] == 1) {
966 if ($code_type == 'COPAY') {
971 // editing copay in ar_session
973 $res_amount = sqlQuery(
974 "SELECT pay_amount FROM ar_activity WHERE pid = ? AND encounter = ? AND session_id = ?",
975 array($this->pid
, $this->encounter
, $session_id)
977 if ($fee != $res_amount['pay_amount']) {
979 "UPDATE ar_session SET user_id = ?, pay_total = ?, modified_time = now(), " .
980 "post_to_date = now() WHERE session_id = ?",
981 array($_SESSION['authUserID'], $fee, $session_id)
984 // deleting old copay
986 "UPDATE ar_activity SET deleted = NOW() WHERE " .
987 "deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
988 array($this->pid
, $this->encounter
, $id)
991 // adding new copay from fee sheet into ar_session
992 $session_id = sqlInsert(
993 "INSERT INTO ar_session " .
994 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
995 "adjustment_code, post_to_date) " .
996 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
997 array($_SESSION['authUserID'], $fee, $this->pid
)
1000 // adding new or changed copay from fee sheet into ar_activity
1002 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
1003 "pid = ? AND encounter = ?", array($this->pid
, $this->encounter
));
1005 "INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
1006 "payer_type, post_time, post_user, session_id, pay_amount, account_code) " .
1007 "VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
1008 array($this->pid
, $this->encounter
, $sequence_no['increment'], $ct0, $cod0, $mod0,
1009 $_SESSION['authUserID'], $session_id, $fee)
1014 $copay_update = true;
1015 $update_session_id = $session_id;
1021 # Code to create justification for all codes based on first justification
1022 if ($GLOBALS['replicate_justification'] == '1') {
1023 if ($justify != '') {
1024 $autojustify = $justify;
1028 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
1029 $justify = $autojustify;
1033 $justify = str_replace(',', ':', $justify) . ':';
1039 if (!empty($iter['ndcnum'])) {
1040 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
1041 trim($iter['ndcqty']);
1044 // If the item is already in the database...
1046 // Get existing values from database.
1049 "SELECT * FROM billing WHERE id = ? AND billed = 0 AND activity = 1",
1060 $tmp['provider_id'],
1066 $this->logFSMessage(xl('Item deleted'), '', $logarr);
1067 BillingUtilities
::deleteBilling($id);
1070 $tmparr = array('code' => $code, 'authorized' => $auth);
1071 if (isset($iter['units' ])) {
1072 $tmparr['units' ] = $units;
1075 if (isset($iter['price' ])) {
1076 $tmparr['fee' ] = $fee;
1079 if (isset($iter['pricelevel'])) {
1080 $tmparr['pricelevel'] = $pricelevel;
1083 if (isset($iter['mod' ])) {
1084 $tmparr['modifier' ] = $modifier;
1087 if (isset($iter['provid' ])) {
1088 $tmparr['provider_id'] = $provid;
1091 if (isset($iter['ndcnum' ])) {
1092 $tmparr['ndc_info' ] = $ndc_info;
1095 if (isset($iter['justify' ])) {
1096 $tmparr['justify' ] = $justify;
1099 if (isset($iter['notecodes'])) {
1100 $tmparr['notecodes' ] = $notecodes;
1103 if (isset($iter['revenue_code'])) {
1104 $tmparr['revenue_code'] = $revenue_code;
1107 foreach ($tmparr as $key => $value) {
1108 if ($tmp[$key] != $value) {
1109 if ('fee' == $key) {
1110 $this->logFSMessage(xl('Price changed'), $value, $logarr);
1113 if ('units' == $key) {
1114 $this->logFSMessage(xl('Quantity changed'), $value, $logarr);
1117 if ('provider_id' == $key) {
1118 $this->logFSMessage(xl('Service provider changed'), $value, $logarr);
1121 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
1126 } elseif (!$del) { // Otherwise it's a new item...
1127 $logarr = array($code_type, $code, '', $pricelevel, $fee, $units, $provid, '');
1128 $this->logFSMessage(xl('Item added'), '', $logarr);
1129 $code_text = lookup_code_descriptions($code_type . ":" . $code . ":" . $modifier);
1130 BillingUtilities
::addBilling(
1152 // if modifier is not inserted during loop update the record using the first
1153 // non-empty modifier and code
1154 if ($copay_update == true && $update_session_id != '' && $mod0 != '') {
1156 "UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?" .
1157 " WHERE deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
1158 array($ct0, $cod0, $mod0, $this->pid
, $this->encounter
, $update_session_id)
1162 // Doing similarly to the above but for products.
1163 if (is_array($prod)) {
1164 foreach ($prod as $iter) {
1165 // Skip disabled (billed) line items.
1166 if (!empty($iter['billed'])) {
1170 $drug_id = $iter['drug_id'];
1171 $selector = empty($iter['selector']) ?
'' : $iter['selector'];
1172 $sale_id = $iter['sale_id']; // present only if already saved
1173 $units = intval(trim($iter['units']));
1177 $pricelevel = empty($iter['pricelevel']) ?
'' : $iter['pricelevel'];
1178 $del = !empty($iter['del']);
1180 $warehouse_id = empty($iter['warehouse']) ?
'' : $iter['warehouse'];
1181 $somechange = false;
1184 if (!empty($iter['price'])) {
1185 if ($iter['price'] != 'X') {
1186 // The price from the form is good.
1187 $price = 0 +
trim($iter['price']);
1189 // Otherwise get its price for the given price level and product.
1190 $price = $this->getPrice($pricelevel, 'PROD', $drug_id, $selector);
1194 $fee = sprintf('%01.2f', $price * $units);
1196 // $units is the user view, multipliers of Basic Units.
1197 // Need to compute inventory units for the save logic below.
1198 $inv_units = $units * $this->getBasicUnits($drug_id, $selector);
1200 // If the item is already in the database...
1202 // Get existing values from database.
1204 "SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
1205 "ds.sale_date, ds.drug_id, ds.selector, ds.pricelevel, di.warehouse_id " .
1206 "FROM drug_sales AS ds " .
1207 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
1208 "WHERE ds.sale_id = ?",
1211 $rxid = 0 +
$tmprow['prescription_id'];
1213 if (!empty($tmprow)) {
1217 $tmprow['selector'],
1218 $tmprow['pricelevel'],
1220 $tmprow['quantity'],
1222 $tmprow['warehouse_id']
1227 if (!empty($tmprow)) {
1228 // Delete this sale and reverse its inventory update.
1229 $this->logFSMessage(xl('Item deleted'), '', $logarr);
1230 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1231 if (!empty($tmprow['inventory_id'])) {
1233 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1234 array($tmprow['quantity'], $tmprow['inventory_id'])
1240 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1243 // Modify the sale and adjust inventory accordingly.
1244 if (!empty($tmprow)) {
1247 'quantity' => $inv_units,
1249 'pricelevel' => $pricelevel,
1250 'selector' => $selector,
1251 'sale_date' => $this->visit_date
,
1254 if ($tmprow[$key] != $value) {
1256 if ('fee' == $key) {
1257 $this->logFSMessage(xl('Price changed'), $value, $logarr);
1260 if ('pricelevel' == $key) {
1261 $this->logFSMessage(xl('Price level changed'), $value, $logarr);
1264 if ('selector' == $key) {
1265 $this->logFSMessage(xl('Template selector changed'), $value, $logarr);
1268 if ('quantity' == $key) {
1269 $this->logFSMessage(xl('Quantity changed'), $value, $logarr);
1273 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1274 array($value, $sale_id)
1276 if ($key == 'quantity' && $tmprow['inventory_id']) {
1278 "UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
1279 array($inv_units - $tmprow['quantity'], $tmprow['inventory_id'])
1285 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
1286 // Changing warehouse. Requires deleting and re-adding the sale.
1287 // Not setting $somechange because this alone does not affect a prescription.
1288 $this->logFSMessage(xl('Warehouse changed'), $warehouse_id, $logarr);
1289 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1291 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1292 array($inv_units, $tmprow['inventory_id'])
1295 $sale_id = sellDrug(
1301 (empty($iter['rx']) ?
0 : $rxid),
1313 // Delete Rx if $rxid and flag not set.
1314 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
1315 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
1316 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1319 } elseif (! $del) { // Otherwise it's a new item...
1321 $logarr = array('PROD', $drug_id, $selector, $pricelevel, $fee, $units, '', $warehouse_id);
1322 $this->logFSMessage(xl('Item added'), '', $logarr);
1324 $sale_id = sellDrug(
1340 die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
1344 // If a prescription applies, create or update it.
1345 if (!empty($iter['rx']) && !$del && ($somechange ||
empty($rxid))) {
1346 // If an active rx already exists for this drug and date we will
1347 // replace it, otherwise we'll make a new one.
1352 // Get default drug attributes; prefer the template with the matching selector.
1355 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
1356 "FROM drugs AS d, drug_templates AS dt WHERE " .
1357 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
1358 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
1359 array($drug_id, $selector)
1361 if (!empty($drow)) {
1362 $rxobj = new Prescription($rxid);
1363 $rxobj->set_patient_id($this->pid
);
1364 $rxobj->set_provider_id(isset($main_provid) ?
$main_provid : $this->provider_id
);
1365 $rxobj->set_drug_id($drug_id);
1366 $rxobj->set_quantity($inv_units);
1367 $rxobj->set_per_refill($inv_units);
1368 $rxobj->set_start_date_y(substr($this->visit_date
, 0, 4));
1369 $rxobj->set_start_date_m(substr($this->visit_date
, 5, 2));
1370 $rxobj->set_start_date_d(substr($this->visit_date
, 8, 2));
1371 $rxobj->set_date_added($this->visit_date
);
1372 // Remaining attributes are the drug and template defaults.
1373 $rxobj->set_drug($drow['name']);
1374 $rxobj->set_unit($drow['unit']);
1375 $rxobj->set_dosage($drow['dosage']);
1376 $rxobj->set_form($drow['form']);
1377 $rxobj->set_refills($drow['refills']);
1378 $rxobj->set_size($drow['size']);
1379 $rxobj->set_route($drow['route']);
1380 $rxobj->set_interval($drow['period']);
1381 $rxobj->set_substitute($drow['substitute']);
1384 // Set drug_sales.prescription_id to $rxobj->get_id().
1386 $rxid = 0 +
$rxobj->get_id();
1387 if ($rxid != $oldrxid) {
1389 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1390 array($rxid, $sale_id)
1398 // Set default and/or supervising provider for the encounter.
1399 if (isset($main_provid) && $main_provid != $this->provider_id
) {
1400 $this->logFSMessage(xl('Default provider changed'));
1402 "UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
1403 array($main_provid, $this->pid
, $this->encounter
)
1405 $this->provider_id
= $main_provid;
1408 if (isset($main_supid) && $main_supid != $this->supervisor_id
) {
1410 "UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
1411 array($main_supid, $this->pid
, $this->encounter
)
1413 $this->supervisor_id
= $main_supid;
1416 // Save-and-Close is currently specific to Family Planning but might be more
1417 // generally useful. It provides the ability to mark an encounter as billed
1418 // directly from the Fee Sheet, if there are no charges.
1419 if ($mark_as_closed) {
1420 $this->closeVisit($this->pid
, $this->encounter
);
1424 // Call this after save() for Family Planning implementations.
1425 // It checks the contraception data, or auto-creates it if $newmauser is set.
1426 // Returns 0 unless user intervention is required to fix missing or incorrect data,
1427 // and in that case the return value is a LBFcontra form_id or -1 if none.
1428 // -1 could be returned if a non-LBFcontra form type recorded data that needs fixing.
1430 public function doContraceptionForm($ippfconmeth = null, $newmauser = null, $main_provid = 0)
1432 if (!empty($ippfconmeth)) {
1433 /**********************************************************
1435 "SELECT f.form_id, ld.field_value FROM forms AS f " .
1436 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
1438 "f.pid = ? AND f.encounter = ? AND " .
1439 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
1440 "ORDER BY f.form_id DESC LIMIT 1",
1441 array($this->pid, $this->encounter)
1443 **********************************************************/
1445 "SELECT f.form_id, d3.field_value " .
1446 "FROM form_encounter AS fe " .
1447 " JOIN shared_attributes AS d1 ON d1.pid = fe.pid AND d1.encounter = fe.encounter AND d1.field_id = 'cgen_newmauser' " .
1448 "LEFT JOIN shared_attributes AS d3 ON d3.pid = fe.pid AND d3.encounter = fe.encounter AND d3.field_id = 'cgen_MethAdopt' " .
1449 "LEFT JOIN forms AS f ON f.pid = fe.pid AND f.encounter = fe.encounter AND f.formdir = 'LBFcontra' AND f.deleted = 0 " .
1450 "WHERE fe.pid = ? AND fe.encounter = ? " .
1451 "ORDER BY fe.date DESC, fe.encounter DESC LIMIT 1",
1452 array($this->pid
, $this->encounter
)
1455 if (isset($newmauser)) {
1456 // pastmodern is 0 iff new to modern contraception
1457 $pastmodern = $newmauser == '2' ?
0 : 1;
1458 if ($newmauser == '2') {
1461 /******************************************************
1462 // Add contraception form but only if it does not already exist
1463 // (if it does, must be 2 users working on the visit concurrently).
1464 if (empty($csrow)) {
1465 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
1466 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
1467 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
1468 // Do we care about a service-specific provider here?
1469 $this->insert_lbf_item($newid, 'provider', $main_provid);
1470 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
1472 ******************************************************/
1473 // Auto-add contraception visit data if it does not already exist.
1474 if (empty($csrow)) {
1475 // Creating a new form. Get the new form_id by inserting and deleting a dummy row.
1476 // The form is required so there is a proper way to delete the data.
1478 "INSERT INTO lbf_data " .
1479 "( field_id, field_value ) VALUES ( '', '' )"
1482 "DELETE FROM lbf_data WHERE form_id = ? AND field_id = ''",
1485 addForm($this->encounter
, 'Contraception Summary', $newid, 'LBFcontra', $this->pid
, $GLOBALS['userauthorized']);
1486 // Now add the needed visit fields.
1487 $this->insert_lbf_item('cgen_newmauser', $newmauser);
1488 $this->insert_lbf_item('cgen_MethAdopt', "IPPFCM:$ippfconmeth");
1489 $this->insert_lbf_item('cgen_PastModern', $pastmodern);
1490 $this->insert_lbf_item('cgen_provider', $main_provid);
1492 } elseif (empty($csrow) ||
$csrow['field_value'] != "IPPFCM:$ippfconmeth") {
1493 // Contraceptive method does not match what is in an existing Contraception
1494 // form for this visit, or there is no such form. User intervention is needed.
1495 return empty($csrow['form_id']) ?
-1 : intval($csrow['form_id']);
1502 // Get price level from patient demographics.
1504 public function getPriceLevel()
1506 return $this->patient_pricelevel
;
1509 // Update price level in patient demographics if it's changed.
1511 public function updatePriceLevel($pricelevel)
1513 if (!empty($pricelevel)) {
1514 if ($this->patient_pricelevel
!= $pricelevel) {
1515 $this->logFSMessage(xl('Price level changed'));
1517 "UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1518 array($pricelevel, $this->pid
)
1520 $this->patient_pricelevel
= $pricelevel;
1525 // Create JSON string representing code type, code and selector.
1526 // This can be a checkbox value for parsing when the checkbox is clicked.
1527 // As a side effect note if the code is already selected in the Fee Sheet.
1529 public function genCodeSelectorValue($codes)
1532 list($codetype, $code, $selector) = explode(':', $codes);
1533 if ($codetype == 'PROD') {
1536 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1538 array($this->pid
, $this->encounter
, $code)
1540 $this->code_is_in_fee_sheet
= !empty($crow['sale_id']);
1541 $cbarray = array($codetype, $code, $selector);
1544 "SELECT c.id AS code_id, b.id " .
1545 "FROM codes AS c " .
1546 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1547 "WHERE c.code_type = ? AND c.code = ? ORDER BY c.active DESC, c.id LIMIT 1",
1548 array($this->pid
, $this->encounter
, $codetype, $code_types[$codetype]['id'], $code)
1550 $this->code_is_in_fee_sheet
= !empty($crow['id']);
1551 $cbarray = array($codetype, $code);
1554 $cbval = json_encode($cbarray);
1558 // Get price for a charge item and its price level.
1560 public function getPrice($pr_level, $codetype, $code, $selector = '')
1563 if ($codetype == 'PROD') {
1567 "SELECT id FROM codes WHERE code_type = ? AND code = ? " .
1568 "ORDER BY active DESC, modifier, id LIMIT 1",
1569 array($code_types[$codetype]['id'], $code)
1571 $pr_id = $crow['id'];
1575 "SELECT pr_price FROM prices WHERE " .
1576 "pr_id = ? AND pr_selector = ? AND pr_level = ?",
1577 array($pr_id, $selector, $pr_level)
1579 return empty($prow['pr_price']) ?
0 : $prow['pr_price'];
1582 // Determine if the current user is allowed to see prices.
1584 public function pricesAuthorized()
1586 return AclMain
::aclCheckCore('acct', 'disc') ||
acl_check('acct', 'bill');