Fix for exporting a large number of lists.
[openemr.git] / library / FeeSheet.class.php
blob36b406b553de6d02f39db914f346a107f71892ae
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
46 public $pid; // patient id
47 public $encounter; // encounter id
48 public $got_warehouses = false; // if there is more than 1 warehouse
49 public $default_warehouse = ''; // logged-in user's default warehouse
50 public $visit_date = ''; // YYYY-MM-DD date of this visit
51 public $match_services_to_products = false; // For IPPF
52 public $patient_age = 0; // Age in years as of the visit date
53 public $patient_male = 0; // 1 if male
54 public $patient_pricelevel = ''; // From patient_data.pricelevel
55 public $provider_id = 0;
56 public $supervisor_id = 0;
57 public $code_is_in_fee_sheet = false; // Set by genCodeSelectorValue()
59 // Possible units of measure for NDC drug quantities.
60 public $ndc_uom_choices = array(
61 'ML' => 'ML',
62 'GR' => 'Grams',
63 'ME' => 'Milligrams',
64 'F2' => 'I.U.',
65 'UN' => 'Units'
68 // Set by checkRelatedForContraception():
69 public $line_contra_code = '';
70 public $line_contra_cyp = 0;
71 public $line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
73 // Array of line items generated by addServiceLineItem().
74 // Each element is an array of line item attributes.
75 public $serviceitems = array();
77 // Array of line items generated by addProductLineItem().
78 // Each element is an array of line item attributes.
79 public $productitems = array();
81 // Indicates if any line item has a fee.
82 public $hasCharges = false;
84 // Indicates if any clinical services or products are in the fee sheet.
85 public $required_code_count = 0;
87 // These variables are used to compute the initial consult service with highest CYP (IPPF).
88 public $contraception_code = '';
89 public $contraception_cyp = 0;
91 public $ALLOW_COPAYS = false;
93 function __construct($pid = 0, $encounter = 0)
95 if (empty($pid)) {
96 $pid = $GLOBALS['pid'];
99 if (empty($encounter)) {
100 $encounter = $GLOBALS['encounter'];
103 $this->pid = $pid;
104 $this->encounter = $encounter;
105 // get provider field for pid's primary insurance from insurance_data to be added to billing row table as payer_id
106 $primary_insurance = getInsuranceData($this->pid);
107 $this->payer_id = $primary_insurance['provider'];
109 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
110 $this->ALLOW_COPAYS = empty($GLOBALS['ippf_specific']);
112 // Get the user's default warehouse and an indicator if there's a choice of warehouses.
113 $wrow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse' AND activity = 1");
114 $this->got_warehouses = $wrow['count'] > 1;
115 $wrow = sqlQuery(
116 "SELECT default_warehouse FROM users WHERE username = ?",
117 array($_SESSION['authUser'])
119 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
121 // Get some info about this visit.
122 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
123 "opc.pc_catname, fac.extra_validation " .
124 "FROM form_encounter AS fe " .
125 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
126 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
127 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter));
128 $this->visit_date = substr($visit_row['date'], 0, 10);
129 $this->provider_id = $visit_row['provider_id'];
130 if (empty($this->provider_id)) {
131 $this->provider_id = $this->findProvider();
134 $this->supervisor_id = $visit_row['supervisor_id'];
135 // This flag is specific to IPPF validation at form submit time. It indicates
136 // that most contraceptive services and products should match up on the fee sheet.
137 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
138 !empty($visit_row['extra_validation']);
140 // Get some information about the patient.
141 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
142 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
143 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
144 $this->patient_pricelevel = $patientrow['pricelevel'];
147 // Convert numeric code type to the alpha version.
149 public static function alphaCodeType($id)
151 global $code_types;
152 foreach ($code_types as $key => $value) {
153 if ($value['id'] == $id) {
154 return $key;
158 return '';
161 // Compute age in years given a DOB and "as of" date.
163 public static function getAge($dob, $asof = '')
165 if (empty($asof)) {
166 $asof = date('Y-m-d');
169 $a1 = explode('-', substr($dob, 0, 10));
170 $a2 = explode('-', substr($asof, 0, 10));
171 $age = $a2[0] - $a1[0];
172 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) {
173 --$age;
176 return $age;
179 // Gets the provider from the encounter, logged-in user or patient demographics.
180 // Adapted from work by Terry Hill.
182 public function findProvider()
184 $find_provider = sqlQuery(
185 "SELECT provider_id FROM form_encounter " .
186 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
187 array($this->pid, $this->encounter)
189 $providerid = $find_provider['provider_id'];
190 if (!$providerid) {
191 $get_authorized = $_SESSION['userauthorized'];
192 if ($get_authorized == 1) {
193 $providerid = $_SESSION['authUserID'];
197 if (!$providerid) {
198 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
199 "WHERE pid = ?", array($this->pid));
200 $providerid = $find_provider['providerID'];
203 return intval($providerid);
206 // Close the designated visit, making sure it has no charges.
208 public static function closeVisit($pid, $encounter)
210 $tmp1 = sqlQuery(
211 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
212 "pid = ? AND encounter = ? AND billed = 0",
213 array($pid, $encounter)
215 $tmp2 = sqlQuery(
216 "SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
217 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1 AND code_type != 'TAX'",
218 array($pid, $encounter)
220 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
221 $this_bill_date = date('Y-m-d H:i:s');
222 sqlStatement(
223 "update drug_sales SET billed = 1, bill_date = ? WHERE " .
224 "pid = ? AND encounter = ? AND billed = 0",
225 array($this_bill_date, $pid, $encounter)
227 // Unbilled tax would have been recomputed at checkout and is invalid here.
228 sqlStatement(
229 "UPDATE billing SET activity = 0 WHERE " .
230 "pid = ? AND encounter = ? AND code_type = 'TAX' AND activity = 1 AND billed = 0",
231 array($pid, $encounter)
233 sqlStatement(
234 "UPDATE billing SET billed = 1, bill_date = ? WHERE " .
235 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
236 array($this_bill_date, $pid, $encounter)
238 // Generate and set invoice reference number if appropriate.
239 $tmprow = sqlQuery(
240 "SELECT invoice_refno FROM form_encounter WHERE pid = ? AND encounter = ?",
241 array($pid, $encounter)
243 if (empty($tmprow['invoice_refno'])) { // not empty means there was a previous checkout
244 $refno = updateInvoiceRefNumber();
245 if ($refno) { // means user has an invoice refno pool
246 sqlStatement(
247 "UPDATE form_encounter SET invoice_refno = ? WHERE pid = ? AND encounter = ?",
248 array($refno, $pid, $encounter)
252 } else {
253 return xl('Cannot close because there are charges. Check out instead.');
255 return '';
258 public static function getBasicUnits($drug_id, $selector)
260 $basic_units = 1;
261 $tmp = sqlQuery(
262 "SELECT quantity FROM drug_templates WHERE drug_id = ? AND selector = ?",
263 array($drug_id, $selector)
265 if (!empty($tmp['quantity'])) {
266 $basic_units = 0 + $tmp['quantity'];
267 if (!$basic_units) {
268 $basic_units = 1;
271 return $basic_units;
274 // Log a message that is easy for the Re-Opened Visits Report to interpret.
275 // The optional $logarr contains these line item attributes:
276 // Code Type
277 // Code
278 // Selector (for code type "PROD")
279 // Price Level
280 // Fee
281 // Units
282 // Provider
283 // Warehouse
285 public function logFSMessage($action, $newvalue = '', $logarr = null)
287 $user_notes = $this->encounter;
288 if (is_array($logarr)) {
289 array_unshift($logarr, $newvalue);
290 foreach ($logarr as $tmp) {
291 $user_notes .= '|' . str_replace('|', '', $tmp);
295 EventAuditLogger::instance()->newEvent(
296 'fee-sheet',
297 $_SESSION['authUser'],
298 $_SESSION['authProvider'],
300 $action,
301 $this->pid,
302 $user_notes
306 // Compute a current checksum of this encounter's Fee Sheet data from the database.
308 public function visitChecksum($saved = false)
310 $rowb = sqlQuery(
311 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
312 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
313 "))) AS checksum FROM billing WHERE " .
314 "pid = ? AND encounter = ? AND activity = 1",
315 array($this->pid, $this->encounter)
317 $rowp = sqlQuery(
318 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
319 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
320 "))) AS checksum FROM drug_sales WHERE " .
321 "pid = ? AND encounter = ?",
322 array($this->pid, $this->encounter)
324 $rowv = sqlQuery(
325 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
326 "id, date, provider_id, supervisor_id, last_level_billed, last_level_closed" .
327 "))) AS checksum FROM form_encounter WHERE " .
328 "pid = ? AND encounter = ?",
329 array($this->pid, $this->encounter)
331 $ret = intval($rowb['checksum']) ^ intval($rowp['checksum']) ^ intval($rowv['checksum']);
332 if (CHECKSUM_LOGGING) {
333 $comment = "Checksum = '$ret'";
334 $comment .= ", Saved = " . ($saved ? "true" : "false");
335 EventAuditLogger::instance()->newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid);
337 return $ret;
340 // IPPF-specific; get contraception attributes of the related codes.
342 public function checkRelatedForContraception($related_code, $is_initial_consult = false)
344 $this->line_contra_code = '';
345 $this->line_contra_cyp = 0;
346 $this->line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
347 if (!empty($related_code)) {
348 $relcodes = explode(';', $related_code);
349 foreach ($relcodes as $relstring) {
350 if ($relstring === '') {
351 continue;
354 list($reltype, $relcode) = explode(':', $relstring);
355 if ($reltype !== 'IPPFCM') {
356 continue;
359 $methtype = $is_initial_consult ? 2 : 1;
360 $tmprow = sqlQuery(
361 "SELECT cyp_factor FROM codes WHERE " .
362 "code_type = '32' AND code = ? ORDER BY active DESC, id LIMIT 1",
363 array($relcode)
365 $cyp = 0 + $tmprow['cyp_factor'];
366 if ($cyp > $this->line_contra_cyp) {
367 $this->line_contra_cyp = $cyp;
368 // Note this is an IPPFCM code, not an IPPF2 code.
369 $this->line_contra_code = $relcode;
370 $this->line_contra_methtype = $methtype;
376 /******************************************************************
377 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
378 // This is only needed for auto-creating Contraception forms.
380 public function insert_lbf_item($form_id, $field_id, $field_value)
382 if ($form_id) {
383 sqlStatement("INSERT INTO lbf_data (form_id, field_id, field_value) " .
384 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
385 } else {
386 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
387 "VALUES (?, ?)", array($field_id, $field_value));
390 return $form_id;
392 ******************************************************************/
394 // Insert a row into the shared_attributes table.
395 // This is only needed for auto-creating Contraception forms.
397 public function insert_lbf_item($field_id, $field_value)
399 sqlInsert(
400 "INSERT INTO shared_attributes (pid, encounter, last_update, user_id, field_id, field_value) " .
401 "VALUES (?, ?, 'NOW()', ?, ?, ?)",
402 array($this->pid, $this->encounter, $_SESSION['authId'], $field_id, $field_value)
406 // Create an array of data for a particular billing table item that is useful
407 // for building a user interface form row. $args is an array containing:
408 // codetype
409 // code
410 // modifier
411 // ndc_info
412 // auth
413 // del
414 // units
415 // fee
416 // id
417 // billed
418 // code_text
419 // justify
420 // provider_id
421 // notecodes
422 // pricelevel
423 public function addServiceLineItem($args)
425 global $code_types;
427 // echo "<!-- \n"; // debugging
428 // print_r($args); // debugging
429 // echo "--> \n"; // debugging
431 $li = array();
432 $li['hidden'] = array();
434 $codetype = $args['codetype'];
435 $code = $args['code'];
436 $revenue_code = isset($args['revenue_code']) ? $args['revenue_code'] : '';
437 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
438 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
439 $units = intval(isset($args['units']) ? $args['units'] : 0);
440 $billed = !empty($args['billed']);
441 $auth = !empty($args['auth']);
442 $id = isset($args['id']) ? intval($args['id']) : 0;
443 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
444 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
445 $justify = isset($args['justify']) ? $args['justify'] : '';
446 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
447 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
448 // Price level should be unset only if adding a new line item.
449 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
450 $del = !empty($args['del']);
452 // If using line item billing and user wishes to default to a selected provider, then do so.
453 if (!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
454 if ($provider_id == 0) {
455 $provider_id = (int) $this->findProvider();
459 if ($codetype == 'COPAY') {
460 if (!$code_text) {
461 $code_text = 'Cash';
464 if ($fee > 0) {
465 $fee = 0 - $fee;
469 // Get the matching entry from the codes table.
470 $sqlArray = array();
471 $query = "SELECT id, units, code_text, revenue_code FROM codes WHERE " .
472 "code_type = ? AND code = ?";
473 array_push($sqlArray, ($code_types[$codetype]['id'] ?? ''), $code);
474 if ($modifier) {
475 $query .= " AND modifier = ?";
476 array_push($sqlArray, $modifier);
477 } else {
478 $query .= " AND (modifier IS NULL OR modifier = '')";
480 $query .= " ORDER BY active DESC, id LIMIT 1";
481 $result = sqlQuery($query, $sqlArray);
482 $codes_id = $result['id'] ?? null;
483 $revenue_code = $revenue_code ? $revenue_code : ($result['revenue_code'] ?? null);
484 if (!$code_text) {
485 $code_text = $result['code_text'] ?? null;
486 if (empty($units) && !empty($result)) {
487 $units = intval($result['units']);
490 if (!isset($args['fee'])) {
491 // Fees come from the prices table now.
492 $query = "SELECT pr_price, lo.option_id AS pr_level, lo.notes FROM list_options lo " .
493 " LEFT OUTER JOIN prices p ON lo.option_id=p.pr_level AND pr_id = ? AND pr_selector = '' " .
494 " WHERE lo.list_id='pricelevel' " .
495 "ORDER BY seq";
496 // echo "\n<!-- $query -->\n"; // debugging
498 $prdefault = null;
499 $prrow = null;
500 $prrecordset = sqlStatement($query, array($codes_id));
501 while ($row = sqlFetchArray($prrecordset)) {
502 if (empty($prdefault)) {
503 $prdefault = $row;
506 if ($row['pr_level'] === $pricelevel) {
507 $prrow = $row;
511 $fee = 0;
512 if (!empty($prrow)) {
513 $fee = $prrow['pr_price'];
515 // if percent-based pricing is enabled...
516 if ($GLOBALS['enable_percent_pricing']) {
517 // if this price level is a percentage, calculate price from default price
518 if (!empty($prrow['notes']) && strpos($prrow['notes'], '%') > -1 && !empty($prdefault)) {
519 $percent = intval(str_replace('%', '', $prrow['notes']));
520 if ($percent > 0) {
521 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
529 if (!$units) {
530 $units = 1;
532 $fee = sprintf('%01.2f', $fee);
534 $li['hidden']['code_type'] = $codetype;
535 $li['hidden']['code'] = $code;
536 $li['hidden']['revenue_code'] = $revenue_code;
537 $li['hidden']['mod'] = $modifier;
538 $li['hidden']['billed'] = $billed;
539 $li['hidden']['id'] = $id;
540 $li['hidden']['codes_id'] = $codes_id;
542 // This logic is only used for family planning clinics, and then only when
543 // the option is chosen to use or auto-generate Contraception forms.
544 // It adds contraceptive method and effectiveness to relevant lines.
545 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
546 $codesrow = sqlQuery(
547 "SELECT related_code, cyp_factor FROM codes WHERE " .
548 "code_type = ? AND code = ? ORDER BY active DESC, id LIMIT 1",
549 array($code_types[$codetype]['id'], $code)
551 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
552 if ($this->line_contra_code) {
553 $li['hidden']['method' ] = $this->line_contra_code;
554 $li['hidden']['cyp' ] = $this->line_contra_cyp;
555 $li['hidden']['methtype'] = $this->line_contra_methtype;
556 // contraception_code is only concerned with initial consults.
557 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
558 $this->contraception_cyp = $this->line_contra_cyp;
559 $this->contraception_code = $this->line_contra_code;
564 if ($codetype == 'COPAY') {
565 $li['codetype'] = xl($codetype);
566 if ($ndc_info) {
567 $li['codetype'] .= " ($ndc_info)";
569 $ndc_info = '';
570 } else {
571 $li['codetype'] = $codetype;
574 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
575 $li['revenue_code' ] = $revenue_code;
576 $li['mod' ] = $modifier;
577 $li['fee' ] = $fee;
578 $li['price' ] = $fee / $units;
579 $li['pricelevel'] = $pricelevel;
580 $li['units' ] = $units;
581 $li['provid' ] = $provider_id;
582 $li['justify' ] = $justify;
583 $li['notecodes'] = $notecodes;
584 $li['del' ] = $id && $del;
585 $li['code_text'] = $code_text;
586 $li['auth' ] = $auth;
588 $li['hidden']['price'] = $li['price'];
590 // If NDC info exists or may be required, add stuff for it.
591 if ($codetype == 'HCPCS' && !$billed) {
592 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
593 $ndcnum = $tmp[1];
594 $ndcuom = $tmp[2];
595 $ndcqty = $tmp[3];
596 } else {
597 $ndcnum = $ndc_info;
598 $ndcuom = "UN";
599 $ndcqty = "1";
602 $li['ndcnum' ] = $ndcnum;
603 $li['ndcuom' ] = $ndcuom;
604 $li['ndcqty' ] = $ndcqty;
605 } elseif ($ndc_info) {
606 $li['ndc_info' ] = $ndc_info;
609 // For Family Planning.
610 if ($codetype == 'MA') {
611 ++$this->required_code_count;
614 if ($fee != 0) {
615 $this->hasCharges = true;
618 $this->serviceitems[] = $li;
621 // Create an array of data for a particular drug_sales table item that is useful
622 // for building a user interface form row. $args is an array containing:
623 // drug_id
624 // selector
625 // sale_id
626 // rx (boolean)
627 // del (boolean)
628 // units
629 // fee
630 // billed
631 // warehouse_id
632 // pricelevel
634 // Pass true for the 2nd argument if the data is coming from the database;
635 // if from user input, make it false.
637 public function addProductLineItem($args, $convert_units = true)
639 global $code_types;
641 $li = array();
642 $li['hidden'] = array();
644 $drug_id = $args['drug_id'];
645 $selector = isset($args['selector']) ? $args['selector'] : '';
646 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
647 $units = intval(isset($args['units']) ? $args['units'] : 0);
648 if (!$units) {
649 $units = 1;
651 $billed = !empty($args['billed']);
652 $rx = !empty($args['rx']);
653 $del = !empty($args['del']);
654 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
655 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
656 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
658 if ($convert_units) {
659 // "Basic Units" is the quantity from the product template and is the number of
660 // inventory items in the package that the template represents.
661 // Units seen by the user should be inventory units divided by template quantity.
662 $units = $units / $this->getBasicUnits($drug_id, $selector);
665 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id));
666 $code_text = $drow['name'];
668 // If no warehouse ID passed, use the logged-in user's default.
669 if ($this->got_warehouses && $warehouse_id === '') {
670 $warehouse_id = $this->default_warehouse;
673 // If fee is not provided, get it from the prices table.
674 // It is assumed in this case that units will match what is in the product template.
675 if (!isset($args['fee'])) {
676 $query = "SELECT pr_price, lo.option_id AS pr_level, lo.notes FROM list_options lo " .
677 " LEFT OUTER JOIN prices p ON lo.option_id=p.pr_level AND pr_id = ? AND pr_selector = ? " .
678 " WHERE lo.list_id='pricelevel' " .
679 "ORDER BY seq";
681 $prdefault = null;
682 $prrow = null;
683 $prrecordset = sqlStatement($query, array($drug_id, $selector));
684 while ($row = sqlFetchArray($prrecordset)) {
685 if (empty($prdefault)) {
686 $prdefault = $row;
689 if ($row['pr_level'] === $pricelevel) {
690 $prrow = $row;
694 $fee = 0;
695 if (!empty($prrow)) {
696 $fee = $prrow['pr_price'];
698 // if percent-based pricing is enabled...
699 if ($GLOBALS['enable_percent_pricing']) {
700 // if this price level is a percentage, calculate price from default price
701 if (!empty($prrow['notes']) && strpos($prrow['notes'], '%') > -1 && !empty($prdefault)) {
702 $percent = intval(str_replace('%', '', $prrow['notes']));
703 if ($percent > 0) {
704 $fee = $prdefault['pr_price'] * ((100 - $percent) / 100);
711 $fee = sprintf('%01.2f', $fee);
713 $li['fee' ] = $fee;
714 $li['price' ] = $fee / $units;
715 $li['pricelevel'] = $pricelevel;
716 $li['units' ] = $units;
717 $li['del' ] = $sale_id && $del;
718 $li['code_text'] = $code_text;
719 $li['warehouse'] = $warehouse_id;
720 $li['rx' ] = $rx;
722 $li['hidden']['drug_id'] = $drug_id;
723 $li['hidden']['selector'] = $selector;
724 $li['hidden']['sale_id'] = $sale_id;
725 $li['hidden']['billed' ] = $billed;
726 $li['hidden']['price' ] = $li['price'];
728 // This logic is only used for family planning clinics, and then only when
729 // the option is chosen to use or auto-generate Contraception forms.
730 // It adds contraceptive method and effectiveness to relevant lines.
731 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
732 $this->checkRelatedForContraception($drow['related_code']);
733 if ($this->line_contra_code) {
734 $li['hidden']['method' ] = $this->line_contra_code;
735 $li['hidden']['methtype'] = $this->line_contra_methtype;
739 // For Family Planning.
740 ++$this->required_code_count;
741 if ($fee != 0) {
742 $this->hasCharges = true;
745 $this->productitems[] = $li;
748 // Generate rows for items already in the billing table for this encounter.
750 public function loadServiceItems()
752 $billresult = BillingUtilities::getBillingByEncounter($this->pid, $this->encounter, "*");
753 if ($billresult) {
754 foreach ($billresult as $iter) {
755 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') {
756 continue;
759 $justify = trim($iter['justify']);
760 if ($justify) {
761 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
764 $this->addServiceLineItem(array(
765 'id' => $iter['id'],
766 'codetype' => $iter['code_type'],
767 'code' => trim($iter['code']),
768 'revenue_code' => trim($iter["revenue_code"]),
769 'modifier' => trim($iter["modifier"]),
770 'code_text' => trim($iter['code_text']),
771 'units' => $iter['units'],
772 'fee' => $iter['fee'],
773 'pricelevel' => $iter['pricelevel'],
774 'billed' => $iter['billed'],
775 'ndc_info' => $iter['ndc_info'],
776 'provider_id' => $iter['provider_id'],
777 'justify' => $justify,
778 'notecodes' => trim($iter['notecodes']),
783 // echo "<!-- \n"; // debugging
784 // print_r($this->serviceitems); // debugging
785 // echo "--> \n"; // debugging
788 // Generate rows for items already in the drug_sales table for this encounter.
790 public function loadProductItems()
792 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
793 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
794 "ORDER BY ds.sale_id";
795 $sres = sqlStatement($query, array($this->pid, $this->encounter));
796 while ($srow = sqlFetchArray($sres)) {
797 $this->addProductLineItem(
798 array(
799 'drug_id' => $srow['drug_id'],
800 'selector' => $srow['selector'],
801 'sale_id' => $srow['sale_id'],
802 'rx' => !empty($srow['prescription_id']),
803 'units' => $srow['quantity'],
804 'fee' => $srow['fee'],
805 'pricelevel' => $srow['pricelevel'],
806 'billed' => $srow['billed'],
807 'warehouse_id' => $srow['warehouse_id'],
809 true
814 // Check for insufficient product inventory levels.
815 // Returns an error message if any product items cannot be filled.
816 // You must call this before save().
818 public function checkInventory(&$prod)
820 $alertmsg = '';
821 $insufficient = 0;
822 $expiredlots = false;
823 if (is_array($prod)) {
824 foreach ($prod as $iter) {
825 if (!empty($iter['billed'])) {
826 continue;
829 $drug_id = $iter['drug_id'];
830 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
831 $units = empty($iter['units']) ? 1 : intval($iter['units']);
832 $selector = empty($iter['selector']) ? '' : $iter['selector'];
833 $inv_units = $units * $this->getBasicUnits($drug_id, $selector);
834 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
836 // Deleting always works.
837 if (!empty($iter['del'])) {
838 continue;
841 // If the item is already in the database...
842 if ($sale_id) {
843 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
844 "FROM drug_sales AS ds " .
845 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
846 "WHERE ds.sale_id = ?";
847 $dirow = sqlQuery($query, array($sale_id));
848 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
849 if (!empty($dirow['inventory_id'])) {
850 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
851 // Changing warehouse so check inventory in the new warehouse.
852 // Nothing is updated by this call.
853 if (
854 !sellDrug(
855 $drug_id,
856 $inv_units,
858 $this->pid,
859 $this->encounter,
861 $this->visit_date,
863 $warehouse_id,
864 true,
865 $expiredlots
868 $insufficient = $drug_id;
870 } else {
871 if (($dirow['on_hand'] + $dirow['quantity'] - $inv_units) < 0) {
872 $insufficient = $drug_id;
876 } else { // Otherwise it's a new item...
877 // This only checks for sufficient inventory, nothing is updated.
878 if (
879 !sellDrug(
880 $drug_id,
881 $inv_units,
883 $this->pid,
884 $this->encounter,
886 $this->visit_date,
888 $warehouse_id,
889 true,
890 $expiredlots
893 $insufficient = $drug_id;
896 } // end for
899 if ($insufficient) {
900 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
901 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
902 if ($expiredlots) {
903 $alertmsg .= " " . xl('Check expiration dates.');
907 return $alertmsg;
910 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
911 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
913 public function save(
914 &$bill,
915 &$prod,
916 $main_provid = null,
917 $main_supid = null,
918 $default_warehouse = null,
919 $mark_as_closed = false
921 global $code_types;
923 if (isset($main_provid) && $main_supid == $main_provid) {
924 $main_supid = 0;
927 $copay_update = false;
928 $update_session_id = '';
929 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
930 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
931 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
933 if (is_array($bill)) {
934 foreach ($bill as $iter) {
935 // Skip disabled (billed) line items.
936 if (!empty($iter['billed'])) {
937 continue;
940 $id = $iter['id'] ?? null;
941 $code_type = $iter['code_type'];
942 $code = $iter['code'];
943 $del = !empty($iter['del']);
944 $units = empty($iter['units']) ? 1 : intval($iter['units']);
945 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
946 $revenue_code = empty($iter['revenue_code']) ? '' : trim($iter['revenue_code']);
947 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
948 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
949 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
950 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
952 $price = 0;
953 if (!empty($iter['price'])) {
954 if ($code_type == 'COPAY' || $this->pricesAuthorized()) {
955 $price = 0 + trim($iter['price'] ?? 0);
956 } else {
957 $price = $this->getPrice($pricelevel, $code_type, $code);
961 $fee = sprintf('%01.2f', $price * $units);
963 if (!$cod0 && ($code_types[$code_type]['fee'] ?? null) == 1) {
964 $mod0 = $modifier;
965 $cod0 = $code;
966 $ct0 = $code_type;
969 if ($code_type == 'COPAY') {
970 if ($fee < 0) {
971 $fee = $fee * -1;
973 if ($id) {
974 // editing copay in ar_session
975 $session_id = $id;
976 $res_amount = sqlQuery(
977 "SELECT pay_amount FROM ar_activity WHERE pid = ? AND encounter = ? AND session_id = ?",
978 array($this->pid, $this->encounter, $session_id)
980 if ($fee != $res_amount['pay_amount']) {
981 sqlStatement(
982 "UPDATE ar_session SET user_id = ?, pay_total = ?, modified_time = now(), " .
983 "post_to_date = now() WHERE session_id = ?",
984 array($_SESSION['authUserID'], $fee, $session_id)
987 // deleting old copay
988 sqlStatement(
989 "UPDATE ar_activity SET deleted = NOW() WHERE " .
990 "deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
991 array($this->pid, $this->encounter, $id)
993 } else {
994 // adding new copay from fee sheet into ar_session
995 $session_id = sqlInsert(
996 "INSERT INTO ar_session " .
997 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
998 "adjustment_code, post_to_date) " .
999 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
1000 array($_SESSION['authUserID'], $fee, $this->pid)
1003 // adding new or changed copay from fee sheet into ar_activity
1004 sqlBeginTrans();
1005 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
1006 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
1007 SqlStatement(
1008 "INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
1009 "payer_type, post_time, post_user, session_id, pay_amount, account_code) " .
1010 "VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
1011 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
1012 $_SESSION['authUserID'], $session_id, $fee)
1014 sqlCommitTrans();
1016 if (!$cod0) {
1017 $copay_update = true;
1018 $update_session_id = $session_id;
1021 continue;
1024 # Code to create justification for all codes based on first justification
1025 if ($GLOBALS['replicate_justification'] == '1') {
1026 if ($justify != '') {
1027 $autojustify = $justify;
1031 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
1032 $justify = $autojustify;
1035 if ($justify) {
1036 $justify = str_replace(',', ':', $justify) . ':';
1039 $auth = "1";
1041 $ndc_info = '';
1042 if (!empty($iter['ndcnum'])) {
1043 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
1044 trim($iter['ndcqty']);
1047 // If the item is already in the database...
1048 if ($id) {
1049 // Get existing values from database.
1050 $logarr = null;
1051 $tmp = sqlQuery(
1052 "SELECT * FROM billing WHERE id = ? AND billed = 0 AND activity = 1",
1053 array($id)
1055 if (!empty($tmp)) {
1056 $logarr = array(
1057 $tmp['code_type'],
1058 $tmp['code'],
1060 $tmp['pricelevel'],
1061 $tmp['fee'],
1062 $tmp['units'],
1063 $tmp['provider_id'],
1068 if ($del) {
1069 $this->logFSMessage(xl('Item deleted'), '', $logarr);
1070 BillingUtilities::deleteBilling($id);
1071 } else {
1072 if (!empty($tmp)) {
1073 $tmparr = array('code' => $code, 'authorized' => $auth);
1074 if (isset($iter['units' ])) {
1075 $tmparr['units' ] = $units;
1078 if (isset($iter['price' ])) {
1079 $tmparr['fee' ] = $fee;
1082 if (isset($iter['pricelevel'])) {
1083 $tmparr['pricelevel'] = $pricelevel;
1086 if (isset($iter['mod' ])) {
1087 $tmparr['modifier' ] = $modifier;
1090 if (isset($iter['provid' ])) {
1091 $tmparr['provider_id'] = $provid;
1094 if (isset($iter['ndcnum' ])) {
1095 $tmparr['ndc_info' ] = $ndc_info;
1098 if (isset($iter['justify' ])) {
1099 $tmparr['justify' ] = $justify;
1102 if (isset($iter['notecodes'])) {
1103 $tmparr['notecodes' ] = $notecodes;
1106 if (isset($iter['revenue_code'])) {
1107 $tmparr['revenue_code'] = $revenue_code;
1110 foreach ($tmparr as $key => $value) {
1111 if ($tmp[$key] != $value) {
1112 if ('fee' == $key) {
1113 $this->logFSMessage(xl('Price changed'), $value, $logarr);
1116 if ('units' == $key) {
1117 $this->logFSMessage(xl('Quantity changed'), $value, $logarr);
1120 if ('provider_id' == $key) {
1121 $this->logFSMessage(xl('Service provider changed'), $value, $logarr);
1124 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
1129 } elseif (!$del) { // Otherwise it's a new item...
1130 $logarr = array($code_type, $code, '', $pricelevel, $fee, $units, $provid, '');
1131 $this->logFSMessage(xl('Item added'), '', $logarr);
1132 $code_text = lookup_code_descriptions($code_type . ":" . $code . ":" . $modifier);
1133 BillingUtilities::addBilling(
1134 $this->encounter,
1135 $code_type,
1136 $code,
1137 $code_text,
1138 $this->pid,
1139 $auth,
1140 $provid,
1141 $modifier,
1142 $units,
1143 $fee,
1144 $ndc_info,
1145 $justify,
1147 $notecodes,
1148 $pricelevel,
1149 $revenue_code,
1150 $this->payer_id
1153 } // end for
1156 // if modifier is not inserted during loop update the record using the first
1157 // non-empty modifier and code
1158 if ($copay_update == true && $update_session_id != '' && $mod0 != '') {
1159 sqlStatement(
1160 "UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?" .
1161 " WHERE deleted IS NULL AND pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
1162 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id)
1166 // Doing similarly to the above but for products.
1167 if (is_array($prod)) {
1168 foreach ($prod as $iter) {
1169 // Skip disabled (billed) line items.
1170 if (!empty($iter['billed'])) {
1171 continue;
1174 $drug_id = $iter['drug_id'];
1175 $selector = empty($iter['selector']) ? '' : $iter['selector'];
1176 $sale_id = $iter['sale_id']; // present only if already saved
1177 $units = intval(trim($iter['units']));
1178 if (!$units) {
1179 $units = 1;
1181 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
1182 $del = !empty($iter['del']);
1183 $rxid = 0;
1184 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
1185 $somechange = false;
1187 $price = 0;
1188 if (!empty($iter['price'])) {
1189 if ($iter['price'] != 'X') {
1190 // The price from the form is good.
1191 $price = 0 + trim($iter['price']);
1192 } else {
1193 // Otherwise get its price for the given price level and product.
1194 $price = $this->getPrice($pricelevel, 'PROD', $drug_id, $selector);
1198 $fee = sprintf('%01.2f', $price * $units);
1200 // $units is the user view, multipliers of Basic Units.
1201 // Need to compute inventory units for the save logic below.
1202 $inv_units = $units * $this->getBasicUnits($drug_id, $selector);
1204 // If the item is already in the database...
1205 if ($sale_id) {
1206 // Get existing values from database.
1207 $tmprow = sqlQuery(
1208 "SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
1209 "ds.sale_date, ds.drug_id, ds.selector, ds.pricelevel, di.warehouse_id " .
1210 "FROM drug_sales AS ds " .
1211 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
1212 "WHERE ds.sale_id = ?",
1213 array($sale_id)
1215 $rxid = (int) $tmprow['prescription_id'];
1216 $logarr = null;
1217 if (!empty($tmprow)) {
1218 $logarr = array(
1219 'PROD',
1220 $tmprow['drug_id'],
1221 $tmprow['selector'],
1222 $tmprow['pricelevel'],
1223 $tmprow['fee'],
1224 $tmprow['quantity'],
1226 $tmprow['warehouse_id']
1230 if ($del) {
1231 if (!empty($tmprow)) {
1232 // Delete this sale and reverse its inventory update.
1233 $this->logFSMessage(xl('Item deleted'), '', $logarr);
1234 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1235 if (!empty($tmprow['inventory_id'])) {
1236 sqlStatement(
1237 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1238 array($tmprow['quantity'], $tmprow['inventory_id'])
1243 if ($rxid) {
1244 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1246 } else {
1247 // Modify the sale and adjust inventory accordingly.
1248 if (!empty($tmprow)) {
1249 foreach (
1250 array(
1251 'quantity' => $inv_units,
1252 'fee' => $fee,
1253 'pricelevel' => $pricelevel,
1254 'selector' => $selector,
1255 'sale_date' => $this->visit_date,
1256 ) as $key => $value
1258 if ($tmprow[$key] != $value) {
1259 $somechange = true;
1260 if ('fee' == $key) {
1261 $this->logFSMessage(xl('Price changed'), $value, $logarr);
1264 if ('pricelevel' == $key) {
1265 $this->logFSMessage(xl('Price level changed'), $value, $logarr);
1268 if ('selector' == $key) {
1269 $this->logFSMessage(xl('Template selector changed'), $value, $logarr);
1272 if ('quantity' == $key) {
1273 $this->logFSMessage(xl('Quantity changed'), $value, $logarr);
1276 sqlStatement(
1277 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1278 array($value, $sale_id)
1280 if ($key == 'quantity' && $tmprow['inventory_id']) {
1281 sqlStatement(
1282 "UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
1283 array($inv_units - $tmprow['quantity'], $tmprow['inventory_id'])
1289 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
1290 // Changing warehouse. Requires deleting and re-adding the sale.
1291 // Not setting $somechange because this alone does not affect a prescription.
1292 $this->logFSMessage(xl('Warehouse changed'), $warehouse_id, $logarr);
1293 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1294 sqlStatement(
1295 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1296 array($inv_units, $tmprow['inventory_id'])
1298 $tmpnull = null;
1299 $sale_id = sellDrug(
1300 $drug_id,
1301 $inv_units,
1302 $fee,
1303 $this->pid,
1304 $this->encounter,
1305 (empty($iter['rx']) ? 0 : $rxid),
1306 $this->visit_date,
1308 $warehouse_id,
1309 false,
1310 $tmpnull,
1311 $pricelevel,
1312 $selector
1317 // Delete Rx if $rxid and flag not set.
1318 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
1319 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
1320 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1323 } elseif (! $del) { // Otherwise it's a new item...
1324 $somechange = true;
1325 $logarr = array('PROD', $drug_id, $selector, $pricelevel, $fee, $units, '', $warehouse_id);
1326 $this->logFSMessage(xl('Item added'), '', $logarr);
1327 $tmpnull = null;
1328 $sale_id = sellDrug(
1329 $drug_id,
1330 $inv_units,
1331 $fee,
1332 $this->pid,
1333 $this->encounter,
1335 $this->visit_date,
1337 $warehouse_id,
1338 false,
1339 $tmpnull,
1340 $pricelevel,
1341 $selector
1343 if (!$sale_id) {
1344 die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
1348 // If a prescription applies, create or update it.
1349 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
1350 // If an active rx already exists for this drug and date we will
1351 // replace it, otherwise we'll make a new one.
1352 if (empty($rxid)) {
1353 $rxid = '';
1356 // Get default drug attributes; prefer the template with the matching selector.
1357 $drow = sqlQuery(
1358 "SELECT dt.*, " .
1359 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
1360 "FROM drugs AS d, drug_templates AS dt WHERE " .
1361 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
1362 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
1363 array($drug_id, $selector)
1365 if (!empty($drow)) {
1366 $rxobj = new Prescription($rxid);
1367 $rxobj->set_patient_id($this->pid);
1368 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
1369 $rxobj->set_drug_id($drug_id);
1370 $rxobj->set_quantity($inv_units);
1371 $rxobj->set_per_refill($inv_units);
1372 $rxobj->set_start_date_y(substr($this->visit_date, 0, 4));
1373 $rxobj->set_start_date_m(substr($this->visit_date, 5, 2));
1374 $rxobj->set_start_date_d(substr($this->visit_date, 8, 2));
1375 $rxobj->set_date_added($this->visit_date);
1376 // Remaining attributes are the drug and template defaults.
1377 $rxobj->set_drug($drow['name']);
1378 $rxobj->set_unit($drow['unit']);
1379 $rxobj->set_dosage($drow['dosage']);
1380 $rxobj->set_form($drow['form']);
1381 $rxobj->set_refills($drow['refills']);
1382 $rxobj->set_size($drow['size']);
1383 $rxobj->set_route($drow['route']);
1384 $rxobj->set_interval($drow['period']);
1385 $rxobj->set_substitute($drow['substitute']);
1387 $rxobj->persist();
1388 // Set drug_sales.prescription_id to $rxobj->get_id().
1389 $oldrxid = $rxid;
1390 $rxid = (int) $rxobj->get_id();
1391 if ($rxid != $oldrxid) {
1392 sqlStatement(
1393 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1394 array($rxid, $sale_id)
1399 } // end for
1402 // Set default and/or supervising provider for the encounter.
1403 if (isset($main_provid) && $main_provid != $this->provider_id) {
1404 $this->logFSMessage(xl('Default provider changed'));
1405 sqlStatement(
1406 "UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
1407 array($main_provid, $this->pid, $this->encounter)
1409 $this->provider_id = $main_provid;
1412 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
1413 sqlStatement(
1414 "UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
1415 array($main_supid, $this->pid, $this->encounter)
1417 $this->supervisor_id = $main_supid;
1420 // Save-and-Close is currently specific to Family Planning but might be more
1421 // generally useful. It provides the ability to mark an encounter as billed
1422 // directly from the Fee Sheet, if there are no charges.
1423 if ($mark_as_closed) {
1424 $this->closeVisit($this->pid, $this->encounter);
1428 // Call this after save() for Family Planning implementations.
1429 // It checks the contraception data, or auto-creates it if $newmauser is set.
1430 // Returns 0 unless user intervention is required to fix missing or incorrect data,
1431 // and in that case the return value is a LBFcontra form_id or -1 if none.
1432 // -1 could be returned if a non-LBFcontra form type recorded data that needs fixing.
1434 public function doContraceptionForm($ippfconmeth = null, $newmauser = null, $main_provid = 0)
1436 if (!empty($ippfconmeth)) {
1437 /**********************************************************
1438 $csrow = sqlQuery(
1439 "SELECT f.form_id, ld.field_value FROM forms AS f " .
1440 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
1441 "WHERE " .
1442 "f.pid = ? AND f.encounter = ? AND " .
1443 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
1444 "ORDER BY f.form_id DESC LIMIT 1",
1445 array($this->pid, $this->encounter)
1447 **********************************************************/
1448 $csrow = sqlQuery(
1449 "SELECT f.form_id, d3.field_value " .
1450 "FROM form_encounter AS fe " .
1451 " JOIN shared_attributes AS d1 ON d1.pid = fe.pid AND d1.encounter = fe.encounter AND d1.field_id = 'cgen_newmauser' " .
1452 "LEFT JOIN shared_attributes AS d3 ON d3.pid = fe.pid AND d3.encounter = fe.encounter AND d3.field_id = 'cgen_MethAdopt' " .
1453 "LEFT JOIN forms AS f ON f.pid = fe.pid AND f.encounter = fe.encounter AND f.formdir = 'LBFcontra' AND f.deleted = 0 " .
1454 "WHERE fe.pid = ? AND fe.encounter = ? " .
1455 "ORDER BY fe.date DESC, fe.encounter DESC LIMIT 1",
1456 array($this->pid, $this->encounter)
1459 if (isset($newmauser)) {
1460 // pastmodern is 0 iff new to modern contraception
1461 $pastmodern = $newmauser == '2' ? 0 : 1;
1462 if ($newmauser == '2') {
1463 $newmauser = '1';
1465 /******************************************************
1466 // Add contraception form but only if it does not already exist
1467 // (if it does, must be 2 users working on the visit concurrently).
1468 if (empty($csrow)) {
1469 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
1470 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
1471 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
1472 // Do we care about a service-specific provider here?
1473 $this->insert_lbf_item($newid, 'provider', $main_provid);
1474 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
1476 ******************************************************/
1477 // Auto-add contraception visit data if it does not already exist.
1478 if (empty($csrow)) {
1479 // Creating a new form. Get the new form_id by inserting and deleting a dummy row.
1480 // The form is required so there is a proper way to delete the data.
1481 $newid = sqlInsert(
1482 "INSERT INTO lbf_data " .
1483 "( field_id, field_value ) VALUES ( '', '' )"
1485 sqlStatement(
1486 "DELETE FROM lbf_data WHERE form_id = ? AND field_id = ''",
1487 array($newid)
1489 addForm($this->encounter, 'Contraception Summary', $newid, 'LBFcontra', $this->pid, $GLOBALS['userauthorized']);
1490 // Now add the needed visit fields.
1491 $this->insert_lbf_item('cgen_newmauser', $newmauser);
1492 $this->insert_lbf_item('cgen_MethAdopt', "IPPFCM:$ippfconmeth");
1493 $this->insert_lbf_item('cgen_PastModern', $pastmodern);
1494 $this->insert_lbf_item('cgen_provider', $main_provid);
1496 } elseif (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
1497 // Contraceptive method does not match what is in an existing Contraception
1498 // form for this visit, or there is no such form. User intervention is needed.
1499 return empty($csrow['form_id']) ? -1 : intval($csrow['form_id']);
1503 return 0;
1506 // Get price level from patient demographics.
1508 public function getPriceLevel()
1510 return $this->patient_pricelevel;
1513 // Update price level in patient demographics if it's changed.
1515 public function updatePriceLevel($pricelevel)
1517 if (!empty($pricelevel)) {
1518 if ($this->patient_pricelevel != $pricelevel) {
1519 $this->logFSMessage(xl('Price level changed'));
1520 sqlStatement(
1521 "UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1522 array($pricelevel, $this->pid)
1524 $this->patient_pricelevel = $pricelevel;
1529 // Create JSON string representing code type, code and selector.
1530 // This can be a checkbox value for parsing when the checkbox is clicked.
1531 // As a side effect note if the code is already selected in the Fee Sheet.
1533 public function genCodeSelectorValue($codes)
1535 global $code_types;
1536 list($codetype, $code, $selector) = explode(':', $codes);
1537 if ($codetype == 'PROD') {
1538 $crow = sqlQuery(
1539 "SELECT sale_id " .
1540 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1541 "LIMIT 1",
1542 array($this->pid, $this->encounter, $code)
1544 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
1545 $cbarray = array($codetype, $code, $selector);
1546 } else {
1547 $crow = sqlQuery(
1548 "SELECT c.id AS code_id, b.id " .
1549 "FROM codes AS c " .
1550 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1551 "WHERE c.code_type = ? AND c.code = ? ORDER BY c.active DESC, c.id LIMIT 1",
1552 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code)
1554 $this->code_is_in_fee_sheet = !empty($crow['id']);
1555 $cbarray = array($codetype, $code);
1558 $cbval = json_encode($cbarray);
1559 return $cbval;
1562 // Get price for a charge item and its price level.
1564 public function getPrice($pr_level, $codetype, $code, $selector = '')
1566 global $code_types;
1567 if ($codetype == 'PROD') {
1568 $pr_id = $code;
1569 } else {
1570 $crow = sqlQuery(
1571 "SELECT id FROM codes WHERE code_type = ? AND code = ? " .
1572 "ORDER BY active DESC, modifier, id LIMIT 1",
1573 array($code_types[$codetype]['id'], $code)
1575 $pr_id = $crow['id'];
1576 $selector = '';
1578 $prow = sqlQuery(
1579 "SELECT pr_price FROM prices WHERE " .
1580 "pr_id = ? AND pr_selector = ? AND pr_level = ?",
1581 array($pr_id, $selector, $pr_level)
1583 return empty($prow['pr_price']) ? 0 : $prow['pr_price'];
1586 // Determine if the current user is allowed to see prices.
1588 public function pricesAuthorized()
1590 return AclMain::aclCheckCore('acct', 'disc') || acl_check('acct', 'bill');