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");
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(
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)
97 $pid = $GLOBALS['pid'];
100 if (empty($encounter)) {
101 $encounter = $GLOBALS['encounter'];
105 $this->encounter
= $encounter;
107 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
108 $this->ALLOW_COPAYS
= empty($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;
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)
150 foreach ($code_types as $key => $value) {
151 if ($value['id'] == $id) {
159 // Compute age in years given a DOB and "as of" date.
161 public static function getAge($dob, $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])) {
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'];
189 $get_authorized = $_SESSION['userauthorized'];
190 if ($get_authorized == 1) {
191 $providerid = $_SESSION['authUserID'];
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 // Close the designated visit, making sure it has no charges.
206 public static function closeVisit($pid, $encounter)
209 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
210 "pid = ? AND encounter = ? AND billed = 0",
211 array($pid, $encounter)
214 "SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
215 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1 AND code_type != 'TAX'",
216 array($pid, $encounter)
218 if ($tmp1['sum'] +
$tmp2['sum'] == 0) {
219 $this_bill_date = date('Y-m-d H:i:s');
221 "update drug_sales SET billed = 1, bill_date = ? WHERE " .
222 "pid = ? AND encounter = ? AND billed = 0",
223 array($this_bill_date, $pid, $encounter)
225 // Unbilled tax would have been recomputed at checkout and is invalid here.
227 "UPDATE billing SET activity = 0 WHERE " .
228 "pid = ? AND encounter = ? AND code_type = 'TAX' AND activity = 1 AND billed = 0",
229 array($pid, $encounter)
232 "UPDATE billing SET billed = 1, bill_date = ? WHERE " .
233 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
234 array($this_bill_date, $pid, $encounter)
236 // Generate and set invoice reference number if appropriate.
238 "SELECT invoice_refno FROM form_encounter WHERE pid = ? AND encounter = ?",
239 array($pid, $encounter)
241 if (empty($tmprow['invoice_refno'])) { // not empty means there was a previous checkout
242 $refno = updateInvoiceRefNumber();
243 if ($refno) { // means user has an invoice refno pool
245 "UPDATE form_encounter SET invoice_refno = ? WHERE pid = ? AND encounter = ?",
246 array($refno, $pid, $encounter)
251 return xl('Cannot close because there are charges. Check out instead.');
256 public static function getBasicUnits($drug_id, $selector)
260 "SELECT quantity FROM drug_templates WHERE drug_id = ? AND selector = ?",
261 array($drug_id, $selector)
263 if (!empty($tmp['quantity'])) {
264 $basic_units = 0 +
$tmp['quantity'];
272 // Log a message that is easy for the Re-Opened Visits Report to interpret.
273 // The optional $logarr contains these line item attributes:
276 // Selector (for code type "PROD")
283 public function logFSMessage($action, $newvalue = '', $logarr = null)
285 $user_notes = $this->encounter
;
286 if (is_array($logarr)) {
287 array_unshift($logarr, $newvalue);
288 foreach ($logarr as $tmp) {
289 $user_notes .= '|' . str_replace('|', '', $tmp);
293 EventAuditLogger
::instance()->newEvent(
295 $_SESSION['authUser'],
296 $_SESSION['authProvider'],
304 // Compute a current checksum of this encounter's Fee Sheet data from the database.
306 public function visitChecksum($saved = false)
309 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
310 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
311 "))) AS checksum FROM billing WHERE " .
312 "pid = ? AND encounter = ? AND activity = 1",
313 array($this->pid
, $this->encounter
)
316 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
317 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
318 "))) AS checksum FROM drug_sales WHERE " .
319 "pid = ? AND encounter = ?",
320 array($this->pid
, $this->encounter
)
323 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
324 "id, date, provider_id, supervisor_id, last_level_billed, last_level_closed" .
325 "))) AS checksum FROM form_encounter WHERE " .
326 "pid = ? AND encounter = ?",
327 array($this->pid
, $this->encounter
)
329 $ret = intval($rowb['checksum']) ^
intval($rowp['checksum']) ^
intval($rowv['checksum']);
330 if (CHECKSUM_LOGGING
) {
331 $comment = "Checksum = '$ret'";
332 $comment .= ", Saved = " . ($saved ?
"true" : "false");
333 EventAuditLogger
::instance()->newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid
);
338 // IPPF-specific; get contraception attributes of the related codes.
340 public function checkRelatedForContraception($related_code, $is_initial_consult = false)
342 $this->line_contra_code
= '';
343 $this->line_contra_cyp
= 0;
344 $this->line_contra_methtype
= 0; // 0 = None, 1 = Not initial, 2 = Initial consult
345 if (!empty($related_code)) {
346 $relcodes = explode(';', $related_code);
347 foreach ($relcodes as $relstring) {
348 if ($relstring === '') {
352 list($reltype, $relcode) = explode(':', $relstring);
353 if ($reltype !== 'IPPFCM') {
357 $methtype = $is_initial_consult ?
2 : 1;
359 "SELECT cyp_factor FROM codes WHERE " .
360 "code_type = '32' AND code = ? ORDER BY active DESC, id LIMIT 1",
363 $cyp = 0 +
$tmprow['cyp_factor'];
364 if ($cyp > $this->line_contra_cyp
) {
365 $this->line_contra_cyp
= $cyp;
366 // Note this is an IPPFCM code, not an IPPF2 code.
367 $this->line_contra_code
= $relcode;
368 $this->line_contra_methtype
= $methtype;
374 /******************************************************************
375 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
376 // This is only needed for auto-creating Contraception forms.
378 public function insert_lbf_item($form_id, $field_id, $field_value)
381 sqlStatement("INSERT INTO lbf_data (form_id, field_id, field_value) " .
382 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
384 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
385 "VALUES (?, ?)", array($field_id, $field_value));
390 ******************************************************************/
392 // Insert a row into the shared_attributes table.
393 // This is only needed for auto-creating Contraception forms.
395 public function insert_lbf_item($field_id, $field_value)
398 "INSERT INTO shared_attributes (pid, encounter, last_update, user_id, field_id, field_value) " .
399 "VALUES (?, ?, 'NOW()', ?, ?, ?)",
400 array($this->pid
, $this->encounter
, $_SESSION['authId'], $field_id, $field_value)
404 // Create an array of data for a particular billing table item that is useful
405 // for building a user interface form row. $args is an array containing:
421 public function addServiceLineItem($args)
425 // echo "<!-- \n"; // debugging
426 // print_r($args); // debugging
427 // echo "--> \n"; // debugging
430 $li['hidden'] = array();
432 $codetype = $args['codetype'];
433 $code = $args['code'];
434 $revenue_code = isset($args['revenue_code']) ?
$args['revenue_code'] : '';
435 $modifier = isset($args['modifier']) ?
$args['modifier'] : '';
436 $code_text = isset($args['code_text']) ?
$args['code_text'] : '';
437 $units = intval(isset($args['units']) ?
$args['units'] : 0);
438 $billed = !empty($args['billed']);
439 $auth = !empty($args['auth']);
440 $id = isset($args['id']) ?
intval($args['id']) : 0;
441 $ndc_info = isset($args['ndc_info']) ?
$args['ndc_info'] : '';
442 $provider_id = isset($args['provider_id']) ?
intval($args['provider_id']) : 0;
443 $justify = isset($args['justify']) ?
$args['justify'] : '';
444 $notecodes = isset($args['notecodes']) ?
$args['notecodes'] : '';
445 $fee = isset($args['fee']) ?
(0 +
$args['fee']) : 0;
446 // Price level should be unset only if adding a new line item.
447 $pricelevel = isset($args['pricelevel']) ?
$args['pricelevel'] : $this->patient_pricelevel
;
448 $del = !empty($args['del']);
450 // If using line item billing and user wishes to default to a selected provider, then do so.
451 if (!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
452 if ($provider_id == 0) {
453 $provider_id = 0 +
$this->findProvider();
457 if ($codetype == 'COPAY') {
467 // Get the matching entry from the codes table.
469 $query = "SELECT id, units, code_text, revenue_code FROM codes WHERE " .
470 "code_type = ? AND code = ?";
471 array_push($sqlArray, ($code_types[$codetype]['id'] ??
''), $code);
473 $query .= " AND modifier = ?";
474 array_push($sqlArray, $modifier);
476 $query .= " AND (modifier IS NULL OR modifier = '')";
478 $query .= " ORDER BY active DESC, id LIMIT 1";
479 $result = sqlQuery($query, $sqlArray);
480 $codes_id = $result['id'] ??
null;
481 $revenue_code = $revenue_code ?
$revenue_code : ($result['revenue_code'] ??
null);
483 $code_text = $result['code_text'] ??
null;
484 if (empty($units) && !empty($result)) {
485 $units = intval($result['units']);
488 if (!isset($args['fee'])) {
489 // Fees come from the prices table now.
490 $query = "SELECT pr_price, lo.option_id AS pr_level, lo.notes FROM list_options lo " .
491 " LEFT OUTER JOIN prices p ON lo.option_id=p.pr_level AND pr_id = ? AND pr_selector = '' " .
492 " WHERE lo.list_id='pricelevel' " .
494 // echo "\n<!-- $query -->\n"; // debugging
498 $prrecordset = sqlStatement($query, array($codes_id));
499 while ($row = sqlFetchArray($prrecordset)) {
500 if (empty($prdefault)) {
504 if ($row['pr_level'] === $pricelevel) {
510 if (!empty($prrow)) {
511 $fee = $prrow['pr_price'];
513 // if percent-based pricing is enabled...
514 if ($GLOBALS['enable_percent_pricing']) {
515 // if this price level is a percentage, calculate price from default price
516 if (!empty($prrow['notes']) && strpos($prrow['notes'], '%') > -1 && !empty($prdefault)) {
517 $percent = intval(str_replace('%', '', $prrow['notes']));
519 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
530 $fee = sprintf('%01.2f', $fee);
532 $li['hidden']['code_type'] = $codetype;
533 $li['hidden']['code'] = $code;
534 $li['hidden']['revenue_code'] = $revenue_code;
535 $li['hidden']['mod'] = $modifier;
536 $li['hidden']['billed'] = $billed;
537 $li['hidden']['id'] = $id;
538 $li['hidden']['codes_id'] = $codes_id;
540 // This logic is only used for family planning clinics, and then only when
541 // the option is chosen to use or auto-generate Contraception forms.
542 // It adds contraceptive method and effectiveness to relevant lines.
543 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
544 $codesrow = sqlQuery(
545 "SELECT related_code, cyp_factor FROM codes WHERE " .
546 "code_type = ? AND code = ? ORDER BY active DESC, id LIMIT 1",
547 array($code_types[$codetype]['id'], $code)
549 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
550 if ($this->line_contra_code
) {
551 $li['hidden']['method' ] = $this->line_contra_code
;
552 $li['hidden']['cyp' ] = $this->line_contra_cyp
;
553 $li['hidden']['methtype'] = $this->line_contra_methtype
;
554 // contraception_code is only concerned with initial consults.
555 if ($this->line_contra_cyp
> $this->contraception_cyp
&& $this->line_contra_methtype
== 2) {
556 $this->contraception_cyp
= $this->line_contra_cyp
;
557 $this->contraception_code
= $this->line_contra_code
;
562 if ($codetype == 'COPAY') {
563 $li['codetype'] = xl($codetype);
565 $li['codetype'] .= " ($ndc_info)";
569 $li['codetype'] = $codetype;
572 $li['code' ] = $codetype == 'COPAY' ?
'' : $code;
573 $li['revenue_code' ] = $revenue_code;
574 $li['mod' ] = $modifier;
576 $li['price' ] = $fee / $units;
577 $li['pricelevel'] = $pricelevel;
578 $li['units' ] = $units;
579 $li['provid' ] = $provider_id;
580 $li['justify' ] = $justify;
581 $li['notecodes'] = $notecodes;
582 $li['del' ] = $id && $del;
583 $li['code_text'] = $code_text;
584 $li['auth' ] = $auth;
586 $li['hidden']['price'] = $li['price'];
588 // If NDC info exists or may be required, add stuff for it.
589 if ($codetype == 'HCPCS' && !$billed) {
590 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
600 $li['ndcnum' ] = $ndcnum;
601 $li['ndcuom' ] = $ndcuom;
602 $li['ndcqty' ] = $ndcqty;
603 } elseif ($ndc_info) {
604 $li['ndc_info' ] = $ndc_info;
607 // For Family Planning.
608 if ($codetype == 'MA') {
609 ++
$this->required_code_count
;
613 $this->hasCharges
= true;
616 $this->serviceitems
[] = $li;
619 // Create an array of data for a particular drug_sales table item that is useful
620 // for building a user interface form row. $args is an array containing:
632 // Pass true for the 2nd argument if the data is coming from the database;
633 // if from user input, make it false.
635 public function addProductLineItem($args, $convert_units = true)
640 $li['hidden'] = array();
642 $drug_id = $args['drug_id'];
643 $selector = isset($args['selector']) ?
$args['selector'] : '';
644 $sale_id = isset($args['sale_id']) ?
intval($args['sale_id']) : 0;
645 $units = intval(isset($args['units']) ?
$args['units'] : 0);
649 $billed = !empty($args['billed']);
650 $rx = !empty($args['rx']);
651 $del = !empty($args['del']);
652 $fee = isset($args['fee']) ?
(0 +
$args['fee']) : 0;
653 $pricelevel = isset($args['pricelevel']) ?
$args['pricelevel'] : $this->patient_pricelevel
;
654 $warehouse_id = isset($args['warehouse_id']) ?
$args['warehouse_id'] : '';
656 if ($convert_units) {
657 // "Basic Units" is the quantity from the product template and is the number of
658 // inventory items in the package that the template represents.
659 // Units seen by the user should be inventory units divided by template quantity.
660 $units = $units / $this->getBasicUnits($drug_id, $selector);
663 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id));
664 $code_text = $drow['name'];
666 // If no warehouse ID passed, use the logged-in user's default.
667 if ($this->got_warehouses
&& $warehouse_id === '') {
668 $warehouse_id = $this->default_warehouse
;
671 // If fee is not provided, get it from the prices table.
672 // It is assumed in this case that units will match what is in the product template.
673 if (!isset($args['fee'])) {
674 $query = "SELECT pr_price, lo.option_id AS pr_level, lo.notes FROM list_options lo " .
675 " LEFT OUTER JOIN prices p ON lo.option_id=p.pr_level AND pr_id = ? AND pr_selector = ? " .
676 " WHERE lo.list_id='pricelevel' " .
681 $prrecordset = sqlStatement($query, array($drug_id, $selector));
682 while ($row = sqlFetchArray($prrecordset)) {
683 if (empty($prdefault)) {
687 if ($row['pr_level'] === $pricelevel) {
693 if (!empty($prrow)) {
694 $fee = $prrow['pr_price'];
696 // if percent-based pricing is enabled...
697 if ($GLOBALS['enable_percent_pricing']) {
698 // if this price level is a percentage, calculate price from default price
699 if (!empty($prrow['notes']) && strpos($prrow['notes'], '%') > -1 && !empty($prdefault)) {
700 $percent = intval(str_replace('%', '', $prrow['notes']));
702 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
709 $fee = sprintf('%01.2f', $fee);
712 $li['price' ] = $fee / $units;
713 $li['pricelevel'] = $pricelevel;
714 $li['units' ] = $units;
715 $li['del' ] = $sale_id && $del;
716 $li['code_text'] = $code_text;
717 $li['warehouse'] = $warehouse_id;
720 $li['hidden']['drug_id'] = $drug_id;
721 $li['hidden']['selector'] = $selector;
722 $li['hidden']['sale_id'] = $sale_id;
723 $li['hidden']['billed' ] = $billed;
724 $li['hidden']['price' ] = $li['price'];
726 // This logic is only used for family planning clinics, and then only when
727 // the option is chosen to use or auto-generate Contraception forms.
728 // It adds contraceptive method and effectiveness to relevant lines.
729 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
730 $this->checkRelatedForContraception($drow['related_code']);
731 if ($this->line_contra_code
) {
732 $li['hidden']['method' ] = $this->line_contra_code
;
733 $li['hidden']['methtype'] = $this->line_contra_methtype
;
737 // For Family Planning.
738 ++
$this->required_code_count
;
740 $this->hasCharges
= true;
743 $this->productitems
[] = $li;
746 // Generate rows for items already in the billing table for this encounter.
748 public function loadServiceItems()
750 $billresult = BillingUtilities
::getBillingByEncounter($this->pid
, $this->encounter
, "*");
752 foreach ($billresult as $iter) {
753 if (!$this->ALLOW_COPAYS
&& $iter["code_type"] == 'COPAY') {
757 $justify = trim($iter['justify']);
759 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
762 $this->addServiceLineItem(array(
764 'codetype' => $iter['code_type'],
765 'code' => trim($iter['code']),
766 'revenue_code' => trim($iter["revenue_code"]),
767 'modifier' => trim($iter["modifier"]),
768 'code_text' => trim($iter['code_text']),
769 'units' => $iter['units'],
770 'fee' => $iter['fee'],
771 'pricelevel' => $iter['pricelevel'],
772 'billed' => $iter['billed'],
773 'ndc_info' => $iter['ndc_info'],
774 'provider_id' => $iter['provider_id'],
775 'justify' => $justify,
776 'notecodes' => trim($iter['notecodes']),
781 // echo "<!-- \n"; // debugging
782 // print_r($this->serviceitems); // debugging
783 // echo "--> \n"; // debugging
786 // Generate rows for items already in the drug_sales table for this encounter.
788 public function loadProductItems()
790 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
791 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
792 "ORDER BY ds.sale_id";
793 $sres = sqlStatement($query, array($this->pid
, $this->encounter
));
794 while ($srow = sqlFetchArray($sres)) {
795 $this->addProductLineItem(
797 'drug_id' => $srow['drug_id'],
798 'selector' => $srow['selector'],
799 'sale_id' => $srow['sale_id'],
800 'rx' => !empty($srow['prescription_id']),
801 'units' => $srow['quantity'],
802 'fee' => $srow['fee'],
803 'pricelevel' => $srow['pricelevel'],
804 'billed' => $srow['billed'],
805 'warehouse_id' => $srow['warehouse_id'],
812 // Check for insufficient product inventory levels.
813 // Returns an error message if any product items cannot be filled.
814 // You must call this before save().
816 public function checkInventory(&$prod)
820 $expiredlots = false;
821 if (is_array($prod)) {
822 foreach ($prod as $iter) {
823 if (!empty($iter['billed'])) {
827 $drug_id = $iter['drug_id'];
828 $sale_id = empty($iter['sale_id']) ?
0 : intval($iter['sale_id']); // present only if already saved
829 $units = empty($iter['units']) ?
1 : intval($iter['units']);
830 $selector = empty($iter['selector']) ?
'' : $iter['selector'];
831 $inv_units = $units * $this->getBasicUnits($drug_id, $selector);
832 $warehouse_id = empty($iter['warehouse']) ?
'' : $iter['warehouse'];
834 // Deleting always works.
835 if (!empty($iter['del'])) {
839 // If the item is already in the database...
841 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
842 "FROM drug_sales AS ds " .
843 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
844 "WHERE ds.sale_id = ?";
845 $dirow = sqlQuery($query, array($sale_id));
846 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
847 if (!empty($dirow['inventory_id'])) {
848 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
849 // Changing warehouse so check inventory in the new warehouse.
850 // Nothing is updated by this call.
866 $insufficient = $drug_id;
869 if (($dirow['on_hand'] +
$dirow['quantity'] - $inv_units) < 0) {
870 $insufficient = $drug_id;
874 } else { // Otherwise it's a new item...
875 // This only checks for sufficient inventory, nothing is updated.
891 $insufficient = $drug_id;
898 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
899 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
901 $alertmsg .= " " . xl('Check expiration dates.');
908 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
909 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
911 public function save(
916 $default_warehouse = null,
917 $mark_as_closed = false
921 if (isset($main_provid) && $main_supid == $main_provid) {
925 $copay_update = false;
926 $update_session_id = '';
927 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
928 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
929 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
931 if (is_array($bill)) {
932 foreach ($bill as $iter) {
933 // Skip disabled (billed) line items.
934 if (!empty($iter['billed'])) {
938 $id = $iter['id'] ??
null;
939 $code_type = $iter['code_type'];
940 $code = $iter['code'];
941 $del = !empty($iter['del']);
942 $units = empty($iter['units']) ?
1 : intval($iter['units']);
943 $pricelevel = empty($iter['pricelevel']) ?
'' : $iter['pricelevel'];
944 $revenue_code = empty($iter['revenue_code']) ?
'' : trim($iter['revenue_code']);
945 $modifier = empty($iter['mod']) ?
'' : trim($iter['mod']);
946 $justify = empty($iter['justify' ]) ?
'' : trim($iter['justify']);
947 $notecodes = empty($iter['notecodes']) ?
'' : trim($iter['notecodes']);
948 $provid = empty($iter['provid' ]) ?
0 : intval($iter['provid']);
951 if (!empty($iter['price'])) {
952 if ($code_type == 'COPAY' ||
$this->pricesAuthorized()) {
953 $price = 0 +
trim($iter['price'] ??
0);
955 $price = $this->getPrice($pricelevel, $code_type, $code);
959 $fee = sprintf('%01.2f', $price * $units);
961 if (!$cod0 && $code_types[$code_type]['fee'] == 1) {
967 if ($code_type == 'COPAY') {
972 // editing copay in ar_session
974 $res_amount = sqlQuery(
975 "SELECT pay_amount FROM ar_activity WHERE pid = ? AND encounter = ? AND session_id = ?",
976 array($this->pid
, $this->encounter
, $session_id)
978 if ($fee != $res_amount['pay_amount']) {
980 "UPDATE ar_session SET user_id = ?, pay_total = ?, modified_time = now(), " .
981 "post_to_date = now() WHERE session_id = ?",
982 array($_SESSION['authUserID'], $fee, $session_id)
985 // deleting old copay
987 "UPDATE ar_activity SET deleted = NOW() WHERE " .
988 "deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
989 array($this->pid
, $this->encounter
, $id)
992 // adding new copay from fee sheet into ar_session
993 $session_id = sqlInsert(
994 "INSERT INTO ar_session " .
995 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
996 "adjustment_code, post_to_date) " .
997 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
998 array($_SESSION['authUserID'], $fee, $this->pid
)
1001 // adding new or changed copay from fee sheet into ar_activity
1003 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
1004 "pid = ? AND encounter = ?", array($this->pid
, $this->encounter
));
1006 "INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
1007 "payer_type, post_time, post_user, session_id, pay_amount, account_code) " .
1008 "VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
1009 array($this->pid
, $this->encounter
, $sequence_no['increment'], $ct0, $cod0, $mod0,
1010 $_SESSION['authUserID'], $session_id, $fee)
1015 $copay_update = true;
1016 $update_session_id = $session_id;
1022 # Code to create justification for all codes based on first justification
1023 if ($GLOBALS['replicate_justification'] == '1') {
1024 if ($justify != '') {
1025 $autojustify = $justify;
1029 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
1030 $justify = $autojustify;
1034 $justify = str_replace(',', ':', $justify) . ':';
1040 if (!empty($iter['ndcnum'])) {
1041 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
1042 trim($iter['ndcqty']);
1045 // If the item is already in the database...
1047 // Get existing values from database.
1050 "SELECT * FROM billing WHERE id = ? AND billed = 0 AND activity = 1",
1061 $tmp['provider_id'],
1067 $this->logFSMessage(xl('Item deleted'), '', $logarr);
1068 BillingUtilities
::deleteBilling($id);
1071 $tmparr = array('code' => $code, 'authorized' => $auth);
1072 if (isset($iter['units' ])) {
1073 $tmparr['units' ] = $units;
1076 if (isset($iter['price' ])) {
1077 $tmparr['fee' ] = $fee;
1080 if (isset($iter['pricelevel'])) {
1081 $tmparr['pricelevel'] = $pricelevel;
1084 if (isset($iter['mod' ])) {
1085 $tmparr['modifier' ] = $modifier;
1088 if (isset($iter['provid' ])) {
1089 $tmparr['provider_id'] = $provid;
1092 if (isset($iter['ndcnum' ])) {
1093 $tmparr['ndc_info' ] = $ndc_info;
1096 if (isset($iter['justify' ])) {
1097 $tmparr['justify' ] = $justify;
1100 if (isset($iter['notecodes'])) {
1101 $tmparr['notecodes' ] = $notecodes;
1104 if (isset($iter['revenue_code'])) {
1105 $tmparr['revenue_code'] = $revenue_code;
1108 foreach ($tmparr as $key => $value) {
1109 if ($tmp[$key] != $value) {
1110 if ('fee' == $key) {
1111 $this->logFSMessage(xl('Price changed'), $value, $logarr);
1114 if ('units' == $key) {
1115 $this->logFSMessage(xl('Quantity changed'), $value, $logarr);
1118 if ('provider_id' == $key) {
1119 $this->logFSMessage(xl('Service provider changed'), $value, $logarr);
1122 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
1127 } elseif (!$del) { // Otherwise it's a new item...
1128 $logarr = array($code_type, $code, '', $pricelevel, $fee, $units, $provid, '');
1129 $this->logFSMessage(xl('Item added'), '', $logarr);
1130 $code_text = lookup_code_descriptions($code_type . ":" . $code . ":" . $modifier);
1131 BillingUtilities
::addBilling(
1153 // if modifier is not inserted during loop update the record using the first
1154 // non-empty modifier and code
1155 if ($copay_update == true && $update_session_id != '' && $mod0 != '') {
1157 "UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?" .
1158 " WHERE deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
1159 array($ct0, $cod0, $mod0, $this->pid
, $this->encounter
, $update_session_id)
1163 // Doing similarly to the above but for products.
1164 if (is_array($prod)) {
1165 foreach ($prod as $iter) {
1166 // Skip disabled (billed) line items.
1167 if (!empty($iter['billed'])) {
1171 $drug_id = $iter['drug_id'];
1172 $selector = empty($iter['selector']) ?
'' : $iter['selector'];
1173 $sale_id = $iter['sale_id']; // present only if already saved
1174 $units = intval(trim($iter['units']));
1178 $pricelevel = empty($iter['pricelevel']) ?
'' : $iter['pricelevel'];
1179 $del = !empty($iter['del']);
1181 $warehouse_id = empty($iter['warehouse']) ?
'' : $iter['warehouse'];
1182 $somechange = false;
1185 if (!empty($iter['price'])) {
1186 if ($iter['price'] != 'X') {
1187 // The price from the form is good.
1188 $price = 0 +
trim($iter['price']);
1190 // Otherwise get its price for the given price level and product.
1191 $price = $this->getPrice($pricelevel, 'PROD', $drug_id, $selector);
1195 $fee = sprintf('%01.2f', $price * $units);
1197 // $units is the user view, multipliers of Basic Units.
1198 // Need to compute inventory units for the save logic below.
1199 $inv_units = $units * $this->getBasicUnits($drug_id, $selector);
1201 // If the item is already in the database...
1203 // Get existing values from database.
1205 "SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
1206 "ds.sale_date, ds.drug_id, ds.selector, ds.pricelevel, di.warehouse_id " .
1207 "FROM drug_sales AS ds " .
1208 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
1209 "WHERE ds.sale_id = ?",
1212 $rxid = 0 +
$tmprow['prescription_id'];
1214 if (!empty($tmprow)) {
1218 $tmprow['selector'],
1219 $tmprow['pricelevel'],
1221 $tmprow['quantity'],
1223 $tmprow['warehouse_id']
1228 if (!empty($tmprow)) {
1229 // Delete this sale and reverse its inventory update.
1230 $this->logFSMessage(xl('Item deleted'), '', $logarr);
1231 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1232 if (!empty($tmprow['inventory_id'])) {
1234 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1235 array($tmprow['quantity'], $tmprow['inventory_id'])
1241 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1244 // Modify the sale and adjust inventory accordingly.
1245 if (!empty($tmprow)) {
1248 'quantity' => $inv_units,
1250 'pricelevel' => $pricelevel,
1251 'selector' => $selector,
1252 'sale_date' => $this->visit_date
,
1255 if ($tmprow[$key] != $value) {
1257 if ('fee' == $key) {
1258 $this->logFSMessage(xl('Price changed'), $value, $logarr);
1261 if ('pricelevel' == $key) {
1262 $this->logFSMessage(xl('Price level changed'), $value, $logarr);
1265 if ('selector' == $key) {
1266 $this->logFSMessage(xl('Template selector changed'), $value, $logarr);
1269 if ('quantity' == $key) {
1270 $this->logFSMessage(xl('Quantity changed'), $value, $logarr);
1274 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1275 array($value, $sale_id)
1277 if ($key == 'quantity' && $tmprow['inventory_id']) {
1279 "UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
1280 array($inv_units - $tmprow['quantity'], $tmprow['inventory_id'])
1286 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
1287 // Changing warehouse. Requires deleting and re-adding the sale.
1288 // Not setting $somechange because this alone does not affect a prescription.
1289 $this->logFSMessage(xl('Warehouse changed'), $warehouse_id, $logarr);
1290 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1292 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1293 array($inv_units, $tmprow['inventory_id'])
1296 $sale_id = sellDrug(
1302 (empty($iter['rx']) ?
0 : $rxid),
1314 // Delete Rx if $rxid and flag not set.
1315 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
1316 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
1317 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1320 } elseif (! $del) { // Otherwise it's a new item...
1322 $logarr = array('PROD', $drug_id, $selector, $pricelevel, $fee, $units, '', $warehouse_id);
1323 $this->logFSMessage(xl('Item added'), '', $logarr);
1325 $sale_id = sellDrug(
1341 die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
1345 // If a prescription applies, create or update it.
1346 if (!empty($iter['rx']) && !$del && ($somechange ||
empty($rxid))) {
1347 // If an active rx already exists for this drug and date we will
1348 // replace it, otherwise we'll make a new one.
1353 // Get default drug attributes; prefer the template with the matching selector.
1356 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
1357 "FROM drugs AS d, drug_templates AS dt WHERE " .
1358 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
1359 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
1360 array($drug_id, $selector)
1362 if (!empty($drow)) {
1363 $rxobj = new Prescription($rxid);
1364 $rxobj->set_patient_id($this->pid
);
1365 $rxobj->set_provider_id(isset($main_provid) ?
$main_provid : $this->provider_id
);
1366 $rxobj->set_drug_id($drug_id);
1367 $rxobj->set_quantity($inv_units);
1368 $rxobj->set_per_refill($inv_units);
1369 $rxobj->set_start_date_y(substr($this->visit_date
, 0, 4));
1370 $rxobj->set_start_date_m(substr($this->visit_date
, 5, 2));
1371 $rxobj->set_start_date_d(substr($this->visit_date
, 8, 2));
1372 $rxobj->set_date_added($this->visit_date
);
1373 // Remaining attributes are the drug and template defaults.
1374 $rxobj->set_drug($drow['name']);
1375 $rxobj->set_unit($drow['unit']);
1376 $rxobj->set_dosage($drow['dosage']);
1377 $rxobj->set_form($drow['form']);
1378 $rxobj->set_refills($drow['refills']);
1379 $rxobj->set_size($drow['size']);
1380 $rxobj->set_route($drow['route']);
1381 $rxobj->set_interval($drow['period']);
1382 $rxobj->set_substitute($drow['substitute']);
1385 // Set drug_sales.prescription_id to $rxobj->get_id().
1387 $rxid = 0 +
$rxobj->get_id();
1388 if ($rxid != $oldrxid) {
1390 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1391 array($rxid, $sale_id)
1399 // Set default and/or supervising provider for the encounter.
1400 if (isset($main_provid) && $main_provid != $this->provider_id
) {
1401 $this->logFSMessage(xl('Default provider changed'));
1403 "UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
1404 array($main_provid, $this->pid
, $this->encounter
)
1406 $this->provider_id
= $main_provid;
1409 if (isset($main_supid) && $main_supid != $this->supervisor_id
) {
1411 "UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
1412 array($main_supid, $this->pid
, $this->encounter
)
1414 $this->supervisor_id
= $main_supid;
1417 // Save-and-Close is currently specific to Family Planning but might be more
1418 // generally useful. It provides the ability to mark an encounter as billed
1419 // directly from the Fee Sheet, if there are no charges.
1420 if ($mark_as_closed) {
1421 $this->closeVisit($this->pid
, $this->encounter
);
1425 // Call this after save() for Family Planning implementations.
1426 // It checks the contraception data, or auto-creates it if $newmauser is set.
1427 // Returns 0 unless user intervention is required to fix missing or incorrect data,
1428 // and in that case the return value is a LBFcontra form_id or -1 if none.
1429 // -1 could be returned if a non-LBFcontra form type recorded data that needs fixing.
1431 public function doContraceptionForm($ippfconmeth = null, $newmauser = null, $main_provid = 0)
1433 if (!empty($ippfconmeth)) {
1434 /**********************************************************
1436 "SELECT f.form_id, ld.field_value FROM forms AS f " .
1437 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
1439 "f.pid = ? AND f.encounter = ? AND " .
1440 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
1441 "ORDER BY f.form_id DESC LIMIT 1",
1442 array($this->pid, $this->encounter)
1444 **********************************************************/
1446 "SELECT f.form_id, d3.field_value " .
1447 "FROM form_encounter AS fe " .
1448 " JOIN shared_attributes AS d1 ON d1.pid = fe.pid AND d1.encounter = fe.encounter AND d1.field_id = 'cgen_newmauser' " .
1449 "LEFT JOIN shared_attributes AS d3 ON d3.pid = fe.pid AND d3.encounter = fe.encounter AND d3.field_id = 'cgen_MethAdopt' " .
1450 "LEFT JOIN forms AS f ON f.pid = fe.pid AND f.encounter = fe.encounter AND f.formdir = 'LBFcontra' AND f.deleted = 0 " .
1451 "WHERE fe.pid = ? AND fe.encounter = ? " .
1452 "ORDER BY fe.date DESC, fe.encounter DESC LIMIT 1",
1453 array($this->pid
, $this->encounter
)
1456 if (isset($newmauser)) {
1457 // pastmodern is 0 iff new to modern contraception
1458 $pastmodern = $newmauser == '2' ?
0 : 1;
1459 if ($newmauser == '2') {
1462 /******************************************************
1463 // Add contraception form but only if it does not already exist
1464 // (if it does, must be 2 users working on the visit concurrently).
1465 if (empty($csrow)) {
1466 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
1467 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
1468 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
1469 // Do we care about a service-specific provider here?
1470 $this->insert_lbf_item($newid, 'provider', $main_provid);
1471 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
1473 ******************************************************/
1474 // Auto-add contraception visit data if it does not already exist.
1475 if (empty($csrow)) {
1476 // Creating a new form. Get the new form_id by inserting and deleting a dummy row.
1477 // The form is required so there is a proper way to delete the data.
1479 "INSERT INTO lbf_data " .
1480 "( field_id, field_value ) VALUES ( '', '' )"
1483 "DELETE FROM lbf_data WHERE form_id = ? AND field_id = ''",
1486 addForm($this->encounter
, 'Contraception Summary', $newid, 'LBFcontra', $this->pid
, $GLOBALS['userauthorized']);
1487 // Now add the needed visit fields.
1488 $this->insert_lbf_item('cgen_newmauser', $newmauser);
1489 $this->insert_lbf_item('cgen_MethAdopt', "IPPFCM:$ippfconmeth");
1490 $this->insert_lbf_item('cgen_PastModern', $pastmodern);
1491 $this->insert_lbf_item('cgen_provider', $main_provid);
1493 } elseif (empty($csrow) ||
$csrow['field_value'] != "IPPFCM:$ippfconmeth") {
1494 // Contraceptive method does not match what is in an existing Contraception
1495 // form for this visit, or there is no such form. User intervention is needed.
1496 return empty($csrow['form_id']) ?
-1 : intval($csrow['form_id']);
1503 // Get price level from patient demographics.
1505 public function getPriceLevel()
1507 return $this->patient_pricelevel
;
1510 // Update price level in patient demographics if it's changed.
1512 public function updatePriceLevel($pricelevel)
1514 if (!empty($pricelevel)) {
1515 if ($this->patient_pricelevel
!= $pricelevel) {
1516 $this->logFSMessage(xl('Price level changed'));
1518 "UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1519 array($pricelevel, $this->pid
)
1521 $this->patient_pricelevel
= $pricelevel;
1526 // Create JSON string representing code type, code and selector.
1527 // This can be a checkbox value for parsing when the checkbox is clicked.
1528 // As a side effect note if the code is already selected in the Fee Sheet.
1530 public function genCodeSelectorValue($codes)
1533 list($codetype, $code, $selector) = explode(':', $codes);
1534 if ($codetype == 'PROD') {
1537 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1539 array($this->pid
, $this->encounter
, $code)
1541 $this->code_is_in_fee_sheet
= !empty($crow['sale_id']);
1542 $cbarray = array($codetype, $code, $selector);
1545 "SELECT c.id AS code_id, b.id " .
1546 "FROM codes AS c " .
1547 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1548 "WHERE c.code_type = ? AND c.code = ? ORDER BY c.active DESC, c.id LIMIT 1",
1549 array($this->pid
, $this->encounter
, $codetype, $code_types[$codetype]['id'], $code)
1551 $this->code_is_in_fee_sheet
= !empty($crow['id']);
1552 $cbarray = array($codetype, $code);
1555 $cbval = json_encode($cbarray);
1559 // Get price for a charge item and its price level.
1561 public function getPrice($pr_level, $codetype, $code, $selector = '')
1564 if ($codetype == 'PROD') {
1568 "SELECT id FROM codes WHERE code_type = ? AND code = ? " .
1569 "ORDER BY active DESC, modifier, id LIMIT 1",
1570 array($code_types[$codetype]['id'], $code)
1572 $pr_id = $crow['id'];
1576 "SELECT pr_price FROM prices WHERE " .
1577 "pr_id = ? AND pr_selector = ? AND pr_level = ?",
1578 array($pr_id, $selector, $pr_level)
1580 return empty($prow['pr_price']) ?
0 : $prow['pr_price'];
1583 // Determine if the current user is allowed to see prices.
1585 public function pricesAuthorized()
1587 return AclMain
::aclCheckCore('acct', 'disc') ||
acl_check('acct', 'bill');