improved prior 8.2 fix
[openemr.git] / library / FeeSheet.class.php
blob521822853c4391111b2b47b96c2068296d323289
1 <?php
3 /**
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 .
21 * @package OpenEMR
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");
44 class FeeSheet
47 public $pid; // patient id
48 public $encounter; // encounter id
49 public $got_warehouses = false; // if there is more than 1 warehouse
50 public $default_warehouse = ''; // logged-in user's default warehouse
51 public $visit_date = ''; // YYYY-MM-DD date of this visit
52 public $match_services_to_products = false; // For IPPF
53 public $patient_age = 0; // Age in years as of the visit date
54 public $patient_male = 0; // 1 if male
55 public $patient_pricelevel = ''; // From patient_data.pricelevel
56 public $provider_id = 0;
57 public $supervisor_id = 0;
58 public $code_is_in_fee_sheet = false; // Set by genCodeSelectorValue()
60 // Possible units of measure for NDC drug quantities.
61 public $ndc_uom_choices = array(
62 'ML' => 'ML',
63 'GR' => 'Grams',
64 'ME' => 'Milligrams',
65 'F2' => 'I.U.',
66 'UN' => 'Units'
69 // Set by checkRelatedForContraception():
70 public $line_contra_code = '';
71 public $line_contra_cyp = 0;
72 public $line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
74 // Array of line items generated by addServiceLineItem().
75 // Each element is an array of line item attributes.
76 public $serviceitems = array();
78 // Array of line items generated by addProductLineItem().
79 // Each element is an array of line item attributes.
80 public $productitems = array();
82 // Indicates if any line item has a fee.
83 public $hasCharges = false;
85 // Indicates if any clinical services or products are in the fee sheet.
86 public $required_code_count = 0;
88 // These variables are used to compute the initial consult service with highest CYP (IPPF).
89 public $contraception_code = '';
90 public $contraception_cyp = 0;
92 public $ALLOW_COPAYS = false;
94 function __construct($pid = 0, $encounter = 0)
96 if (empty($pid)) {
97 $pid = $GLOBALS['pid'];
100 if (empty($encounter)) {
101 $encounter = $GLOBALS['encounter'];
104 $this->pid = $pid;
105 $this->encounter = $encounter;
107 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
108 $this->ALLOW_COPAYS = 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;
113 $wrow = sqlQuery(
114 "SELECT default_warehouse FROM users WHERE username = ?",
115 array($_SESSION['authUser'])
117 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
119 // Get some info about this visit.
120 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
121 "opc.pc_catname, fac.extra_validation " .
122 "FROM form_encounter AS fe " .
123 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
124 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
125 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter));
126 $this->visit_date = substr($visit_row['date'], 0, 10);
127 $this->provider_id = $visit_row['provider_id'];
128 if (empty($this->provider_id)) {
129 $this->provider_id = $this->findProvider();
132 $this->supervisor_id = $visit_row['supervisor_id'];
133 // This flag is specific to IPPF validation at form submit time. It indicates
134 // that most contraceptive services and products should match up on the fee sheet.
135 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
136 !empty($visit_row['extra_validation']);
138 // Get some information about the patient.
139 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
140 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
141 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
142 $this->patient_pricelevel = $patientrow['pricelevel'];
145 // Convert numeric code type to the alpha version.
147 public static function alphaCodeType($id)
149 global $code_types;
150 foreach ($code_types as $key => $value) {
151 if ($value['id'] == $id) {
152 return $key;
156 return '';
159 // Compute age in years given a DOB and "as of" date.
161 public static function getAge($dob, $asof = '')
163 if (empty($asof)) {
164 $asof = date('Y-m-d');
167 $a1 = explode('-', substr($dob, 0, 10));
168 $a2 = explode('-', substr($asof, 0, 10));
169 $age = $a2[0] - $a1[0];
170 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) {
171 --$age;
174 return $age;
177 // Gets the provider from the encounter, logged-in user or patient demographics.
178 // Adapted from work by Terry Hill.
180 public function findProvider()
182 $find_provider = sqlQuery(
183 "SELECT provider_id FROM form_encounter " .
184 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
185 array($this->pid, $this->encounter)
187 $providerid = $find_provider['provider_id'];
188 if (!$providerid) {
189 $get_authorized = $_SESSION['userauthorized'];
190 if ($get_authorized == 1) {
191 $providerid = $_SESSION['authUserID'];
195 if (!$providerid) {
196 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
197 "WHERE pid = ?", array($this->pid));
198 $providerid = $find_provider['providerID'];
201 return intval($providerid);
204 // Close the designated visit, making sure it has no charges.
206 public static function closeVisit($pid, $encounter)
208 $tmp1 = sqlQuery(
209 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
210 "pid = ? AND encounter = ? AND billed = 0",
211 array($pid, $encounter)
213 $tmp2 = sqlQuery(
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');
220 sqlStatement(
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.
226 sqlStatement(
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)
231 sqlStatement(
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.
237 $tmprow = sqlQuery(
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
244 sqlStatement(
245 "UPDATE form_encounter SET invoice_refno = ? WHERE pid = ? AND encounter = ?",
246 array($refno, $pid, $encounter)
250 } else {
251 return xl('Cannot close because there are charges. Check out instead.');
253 return '';
256 public static function getBasicUnits($drug_id, $selector)
258 $basic_units = 1;
259 $tmp = sqlQuery(
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'];
265 if (!$basic_units) {
266 $basic_units = 1;
269 return $basic_units;
272 // Log a message that is easy for the Re-Opened Visits Report to interpret.
273 // The optional $logarr contains these line item attributes:
274 // Code Type
275 // Code
276 // Selector (for code type "PROD")
277 // Price Level
278 // Fee
279 // Units
280 // Provider
281 // Warehouse
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(
294 'fee-sheet',
295 $_SESSION['authUser'],
296 $_SESSION['authProvider'],
298 $action,
299 $this->pid,
300 $user_notes
304 // Compute a current checksum of this encounter's Fee Sheet data from the database.
306 public function visitChecksum($saved = false)
308 $rowb = sqlQuery(
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)
315 $rowp = sqlQuery(
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)
322 $rowv = sqlQuery(
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);
335 return $ret;
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 === '') {
349 continue;
352 list($reltype, $relcode) = explode(':', $relstring);
353 if ($reltype !== 'IPPFCM') {
354 continue;
357 $methtype = $is_initial_consult ? 2 : 1;
358 $tmprow = sqlQuery(
359 "SELECT cyp_factor FROM codes WHERE " .
360 "code_type = '32' AND code = ? ORDER BY active DESC, id LIMIT 1",
361 array($relcode)
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)
380 if ($form_id) {
381 sqlStatement("INSERT INTO lbf_data (form_id, field_id, field_value) " .
382 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
383 } else {
384 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
385 "VALUES (?, ?)", array($field_id, $field_value));
388 return $form_id;
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)
397 sqlInsert(
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:
406 // codetype
407 // code
408 // modifier
409 // ndc_info
410 // auth
411 // del
412 // units
413 // fee
414 // id
415 // billed
416 // code_text
417 // justify
418 // provider_id
419 // notecodes
420 // pricelevel
421 public function addServiceLineItem($args)
423 global $code_types;
425 // echo "<!-- \n"; // debugging
426 // print_r($args); // debugging
427 // echo "--> \n"; // debugging
429 $li = array();
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') {
458 if (!$code_text) {
459 $code_text = 'Cash';
462 if ($fee > 0) {
463 $fee = 0 - $fee;
467 // Get the matching entry from the codes table.
468 $sqlArray = array();
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);
472 if ($modifier) {
473 $query .= " AND modifier = ?";
474 array_push($sqlArray, $modifier);
475 } else {
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);
482 if (!$code_text) {
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' " .
493 "ORDER BY seq";
494 // echo "\n<!-- $query -->\n"; // debugging
496 $prdefault = null;
497 $prrow = null;
498 $prrecordset = sqlStatement($query, array($codes_id));
499 while ($row = sqlFetchArray($prrecordset)) {
500 if (empty($prdefault)) {
501 $prdefault = $row;
504 if ($row['pr_level'] === $pricelevel) {
505 $prrow = $row;
509 $fee = 0;
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']));
518 if ($percent > 0) {
519 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
527 if (!$units) {
528 $units = 1;
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);
564 if ($ndc_info) {
565 $li['codetype'] .= " ($ndc_info)";
567 $ndc_info = '';
568 } else {
569 $li['codetype'] = $codetype;
572 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
573 $li['revenue_code' ] = $revenue_code;
574 $li['mod' ] = $modifier;
575 $li['fee' ] = $fee;
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)) {
591 $ndcnum = $tmp[1];
592 $ndcuom = $tmp[2];
593 $ndcqty = $tmp[3];
594 } else {
595 $ndcnum = $ndc_info;
596 $ndcuom = "UN";
597 $ndcqty = "1";
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;
612 if ($fee != 0) {
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:
621 // drug_id
622 // selector
623 // sale_id
624 // rx (boolean)
625 // del (boolean)
626 // units
627 // fee
628 // billed
629 // warehouse_id
630 // pricelevel
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)
637 global $code_types;
639 $li = array();
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);
646 if (!$units) {
647 $units = 1;
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' " .
677 "ORDER BY seq";
679 $prdefault = null;
680 $prrow = null;
681 $prrecordset = sqlStatement($query, array($drug_id, $selector));
682 while ($row = sqlFetchArray($prrecordset)) {
683 if (empty($prdefault)) {
684 $prdefault = $row;
687 if ($row['pr_level'] === $pricelevel) {
688 $prrow = $row;
692 $fee = 0;
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']));
701 if ($percent > 0) {
702 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
709 $fee = sprintf('%01.2f', $fee);
711 $li['fee' ] = $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;
718 $li['rx' ] = $rx;
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;
739 if ($fee != 0) {
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, "*");
751 if ($billresult) {
752 foreach ($billresult as $iter) {
753 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') {
754 continue;
757 $justify = trim($iter['justify']);
758 if ($justify) {
759 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
762 $this->addServiceLineItem(array(
763 'id' => $iter['id'],
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(
796 array(
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'],
807 true
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)
818 $alertmsg = '';
819 $insufficient = 0;
820 $expiredlots = false;
821 if (is_array($prod)) {
822 foreach ($prod as $iter) {
823 if (!empty($iter['billed'])) {
824 continue;
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'])) {
836 continue;
839 // If the item is already in the database...
840 if ($sale_id) {
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.
851 if (
852 !sellDrug(
853 $drug_id,
854 $inv_units,
856 $this->pid,
857 $this->encounter,
859 $this->visit_date,
861 $warehouse_id,
862 true,
863 $expiredlots
866 $insufficient = $drug_id;
868 } else {
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.
876 if (
877 !sellDrug(
878 $drug_id,
879 $inv_units,
881 $this->pid,
882 $this->encounter,
884 $this->visit_date,
886 $warehouse_id,
887 true,
888 $expiredlots
891 $insufficient = $drug_id;
894 } // end for
897 if ($insufficient) {
898 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
899 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
900 if ($expiredlots) {
901 $alertmsg .= " " . xl('Check expiration dates.');
905 return $alertmsg;
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(
912 &$bill,
913 &$prod,
914 $main_provid = null,
915 $main_supid = null,
916 $default_warehouse = null,
917 $mark_as_closed = false
919 global $code_types;
921 if (isset($main_provid) && $main_supid == $main_provid) {
922 $main_supid = 0;
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'])) {
935 continue;
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']);
950 $price = 0;
951 if (!empty($iter['price'])) {
952 if ($code_type == 'COPAY' || $this->pricesAuthorized()) {
953 $price = 0 + trim($iter['price'] ?? 0);
954 } else {
955 $price = $this->getPrice($pricelevel, $code_type, $code);
959 $fee = sprintf('%01.2f', $price * $units);
961 if (!$cod0 && $code_types[$code_type]['fee'] == 1) {
962 $mod0 = $modifier;
963 $cod0 = $code;
964 $ct0 = $code_type;
967 if ($code_type == 'COPAY') {
968 if ($fee < 0) {
969 $fee = $fee * -1;
971 if ($id) {
972 // editing copay in ar_session
973 $session_id = $id;
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']) {
979 sqlStatement(
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
986 sqlStatement(
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)
991 } else {
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
1002 sqlBeginTrans();
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));
1005 SqlStatement(
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)
1012 sqlCommitTrans();
1014 if (!$cod0) {
1015 $copay_update = true;
1016 $update_session_id = $session_id;
1019 continue;
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;
1033 if ($justify) {
1034 $justify = str_replace(',', ':', $justify) . ':';
1037 $auth = "1";
1039 $ndc_info = '';
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...
1046 if ($id) {
1047 // Get existing values from database.
1048 $logarr = null;
1049 $tmp = sqlQuery(
1050 "SELECT * FROM billing WHERE id = ? AND billed = 0 AND activity = 1",
1051 array($id)
1053 if (!empty($tmp)) {
1054 $logarr = array(
1055 $tmp['code_type'],
1056 $tmp['code'],
1058 $tmp['pricelevel'],
1059 $tmp['fee'],
1060 $tmp['units'],
1061 $tmp['provider_id'],
1066 if ($del) {
1067 $this->logFSMessage(xl('Item deleted'), '', $logarr);
1068 BillingUtilities::deleteBilling($id);
1069 } else {
1070 if (!empty($tmp)) {
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(
1132 $this->encounter,
1133 $code_type,
1134 $code,
1135 $code_text,
1136 $this->pid,
1137 $auth,
1138 $provid,
1139 $modifier,
1140 $units,
1141 $fee,
1142 $ndc_info,
1143 $justify,
1145 $notecodes,
1146 $pricelevel,
1147 $revenue_code
1150 } // end for
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 != '') {
1156 sqlStatement(
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'])) {
1168 continue;
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']));
1175 if (!$units) {
1176 $units = 1;
1178 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
1179 $del = !empty($iter['del']);
1180 $rxid = 0;
1181 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
1182 $somechange = false;
1184 $price = 0;
1185 if (!empty($iter['price'])) {
1186 if ($iter['price'] != 'X') {
1187 // The price from the form is good.
1188 $price = 0 + trim($iter['price']);
1189 } else {
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...
1202 if ($sale_id) {
1203 // Get existing values from database.
1204 $tmprow = sqlQuery(
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 = ?",
1210 array($sale_id)
1212 $rxid = 0 + $tmprow['prescription_id'];
1213 $logarr = null;
1214 if (!empty($tmprow)) {
1215 $logarr = array(
1216 'PROD',
1217 $tmprow['drug_id'],
1218 $tmprow['selector'],
1219 $tmprow['pricelevel'],
1220 $tmprow['fee'],
1221 $tmprow['quantity'],
1223 $tmprow['warehouse_id']
1227 if ($del) {
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'])) {
1233 sqlStatement(
1234 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1235 array($tmprow['quantity'], $tmprow['inventory_id'])
1240 if ($rxid) {
1241 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1243 } else {
1244 // Modify the sale and adjust inventory accordingly.
1245 if (!empty($tmprow)) {
1246 foreach (
1247 array(
1248 'quantity' => $inv_units,
1249 'fee' => $fee,
1250 'pricelevel' => $pricelevel,
1251 'selector' => $selector,
1252 'sale_date' => $this->visit_date,
1253 ) as $key => $value
1255 if ($tmprow[$key] != $value) {
1256 $somechange = true;
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);
1273 sqlStatement(
1274 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1275 array($value, $sale_id)
1277 if ($key == 'quantity' && $tmprow['inventory_id']) {
1278 sqlStatement(
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));
1291 sqlStatement(
1292 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1293 array($inv_units, $tmprow['inventory_id'])
1295 $tmpnull = null;
1296 $sale_id = sellDrug(
1297 $drug_id,
1298 $inv_units,
1299 $fee,
1300 $this->pid,
1301 $this->encounter,
1302 (empty($iter['rx']) ? 0 : $rxid),
1303 $this->visit_date,
1305 $warehouse_id,
1306 false,
1307 $tmpnull,
1308 $pricelevel,
1309 $selector
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...
1321 $somechange = true;
1322 $logarr = array('PROD', $drug_id, $selector, $pricelevel, $fee, $units, '', $warehouse_id);
1323 $this->logFSMessage(xl('Item added'), '', $logarr);
1324 $tmpnull = null;
1325 $sale_id = sellDrug(
1326 $drug_id,
1327 $inv_units,
1328 $fee,
1329 $this->pid,
1330 $this->encounter,
1332 $this->visit_date,
1334 $warehouse_id,
1335 false,
1336 $tmpnull,
1337 $pricelevel,
1338 $selector
1340 if (!$sale_id) {
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.
1349 if (empty($rxid)) {
1350 $rxid = '';
1353 // Get default drug attributes; prefer the template with the matching selector.
1354 $drow = sqlQuery(
1355 "SELECT dt.*, " .
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']);
1384 $rxobj->persist();
1385 // Set drug_sales.prescription_id to $rxobj->get_id().
1386 $oldrxid = $rxid;
1387 $rxid = 0 + $rxobj->get_id();
1388 if ($rxid != $oldrxid) {
1389 sqlStatement(
1390 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1391 array($rxid, $sale_id)
1396 } // end for
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'));
1402 sqlStatement(
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) {
1410 sqlStatement(
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 /**********************************************************
1435 $csrow = sqlQuery(
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' " .
1438 "WHERE " .
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 **********************************************************/
1445 $csrow = sqlQuery(
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') {
1460 $newmauser = '1';
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.
1478 $newid = sqlInsert(
1479 "INSERT INTO lbf_data " .
1480 "( field_id, field_value ) VALUES ( '', '' )"
1482 sqlStatement(
1483 "DELETE FROM lbf_data WHERE form_id = ? AND field_id = ''",
1484 array($newid)
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']);
1500 return 0;
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'));
1517 sqlStatement(
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)
1532 global $code_types;
1533 list($codetype, $code, $selector) = explode(':', $codes);
1534 if ($codetype == 'PROD') {
1535 $crow = sqlQuery(
1536 "SELECT sale_id " .
1537 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1538 "LIMIT 1",
1539 array($this->pid, $this->encounter, $code)
1541 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
1542 $cbarray = array($codetype, $code, $selector);
1543 } else {
1544 $crow = sqlQuery(
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);
1556 return $cbval;
1559 // Get price for a charge item and its price level.
1561 public function getPrice($pr_level, $codetype, $code, $selector = '')
1563 global $code_types;
1564 if ($codetype == 'PROD') {
1565 $pr_id = $code;
1566 } else {
1567 $crow = sqlQuery(
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'];
1573 $selector = '';
1575 $prow = sqlQuery(
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');