Highway to PSR2
[openemr.git] / library / FeeSheet.class.php
blob2b6355d72173432f60476e278fe3fc86079f2c06
1 <?php
2 /**
3 * library/FeeSheet.class.php
5 * Base class for implementations of the Fee Sheet.
6 * This should not include UI but may be extended by a class that does.
8 * LICENSE: This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 3
11 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see
18 * http://www.gnu.org/licenses/licenses.html#GPL .
20 * @package OpenEMR
21 * @license http://www.gnu.org/licenses/licenses.html#GPL GNU GPL V3+
22 * @author Rod Roark <rod@sunsetsystems.com>
23 * @link http://www.open-emr.org
30 require_once(dirname(__FILE__) . "/../interface/globals.php");
31 require_once(dirname(__FILE__) . "/acl.inc");
32 require_once(dirname(__FILE__) . "/../custom/code_types.inc.php");
33 require_once(dirname(__FILE__) . "/../interface/drugs/drugs.inc.php");
34 require_once(dirname(__FILE__) . "/options.inc.php");
35 require_once(dirname(__FILE__) . "/appointment_status.inc.php");
36 require_once(dirname(__FILE__) . "/classes/Prescription.class.php");
37 require_once(dirname(__FILE__) . "/forms.inc");
38 require_once(dirname(__FILE__) . "/log.inc");
39 // For logging checksums set this to true.
40 define('CHECKSUM_LOGGING', true);
42 // require_once(dirname(__FILE__) . "/api.inc");
43 // require_once(dirname(__FILE__) . "/forms.inc");
45 class FeeSheet
48 public $pid; // patient id
49 public $encounter; // encounter id
50 public $got_warehouses = false; // if there is more than 1 warehouse
51 public $default_warehouse = ''; // logged-in user's default warehouse
52 public $visit_date = ''; // YYYY-MM-DD date of this visit
53 public $match_services_to_products = false; // For IPPF
54 public $patient_age = 0; // Age in years as of the visit date
55 public $patient_male = 0; // 1 if male
56 public $patient_pricelevel = ''; // From patient_data.pricelevel
57 public $provider_id = 0;
58 public $supervisor_id = 0;
59 public $code_is_in_fee_sheet = false; // Set by genCodeSelectorValue()
61 // Possible units of measure for NDC drug quantities.
62 public $ndc_uom_choices = array(
63 'ML' => 'ML',
64 'GR' => 'Grams',
65 'ME' => 'Milligrams',
66 'F2' => 'I.U.',
67 'UN' => 'Units'
70 // Set by checkRelatedForContraception():
71 public $line_contra_code = '';
72 public $line_contra_cyp = 0;
73 public $line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
75 // Array of line items generated by addServiceLineItem().
76 // Each element is an array of line item attributes.
77 public $serviceitems = array();
79 // Array of line items generated by addProductLineItem().
80 // Each element is an array of line item attributes.
81 public $productitems = array();
83 // Indicates if any line item has a fee.
84 public $hasCharges = false;
86 // Indicates if any clinical services or products are in the fee sheet.
87 public $required_code_count = 0;
89 // These variables are used to compute the initial consult service with highest CYP (IPPF).
90 public $contraception_code = '';
91 public $contraception_cyp = 0;
93 public $ALLOW_COPAYS = false;
95 function __construct($pid = 0, $encounter = 0)
97 if (empty($pid)) {
98 $pid = $GLOBALS['pid'];
101 if (empty($encounter)) {
102 $encounter = $GLOBALS['encounter'];
105 $this->pid = $pid;
106 $this->encounter = $encounter;
108 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
109 $this->ALLOW_COPAYS = !$GLOBALS['ippf_specific'];
111 // Get the user's default warehouse and an indicator if there's a choice of warehouses.
112 $wrow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse' AND activity = 1");
113 $this->got_warehouses = $wrow['count'] > 1;
114 $wrow = sqlQuery(
115 "SELECT default_warehouse FROM users WHERE username = ?",
116 array($_SESSION['authUser'])
118 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
120 // Get some info about this visit.
121 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
122 "opc.pc_catname, fac.extra_validation " .
123 "FROM form_encounter AS fe " .
124 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
125 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
126 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter));
127 $this->visit_date = substr($visit_row['date'], 0, 10);
128 $this->provider_id = $visit_row['provider_id'];
129 if (empty($this->provider_id)) {
130 $this->provider_id = $this->findProvider();
133 $this->supervisor_id = $visit_row['supervisor_id'];
134 // This flag is specific to IPPF validation at form submit time. It indicates
135 // that most contraceptive services and products should match up on the fee sheet.
136 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
137 !empty($visit_row['extra_validation']);
139 // Get some information about the patient.
140 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
141 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
142 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
143 $this->patient_pricelevel = $patientrow['pricelevel'];
146 // Convert numeric code type to the alpha version.
148 public static function alphaCodeType($id)
150 global $code_types;
151 foreach ($code_types as $key => $value) {
152 if ($value['id'] == $id) {
153 return $key;
157 return '';
160 // Compute age in years given a DOB and "as of" date.
162 public static function getAge($dob, $asof = '')
164 if (empty($asof)) {
165 $asof = date('Y-m-d');
168 $a1 = explode('-', substr($dob, 0, 10));
169 $a2 = explode('-', substr($asof, 0, 10));
170 $age = $a2[0] - $a1[0];
171 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) {
172 --$age;
175 return $age;
178 // Gets the provider from the encounter, logged-in user or patient demographics.
179 // Adapted from work by Terry Hill.
181 public function findProvider()
183 $find_provider = sqlQuery(
184 "SELECT provider_id FROM form_encounter " .
185 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
186 array($this->pid, $this->encounter)
188 $providerid = $find_provider['provider_id'];
189 if (!$providerid) {
190 $get_authorized = $_SESSION['userauthorized'];
191 if ($get_authorized == 1) {
192 $providerid = $_SESSION['authUserID'];
196 if (!$providerid) {
197 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
198 "WHERE pid = ?", array($this->pid));
199 $providerid = $find_provider['providerID'];
202 return intval($providerid);
205 // Log a message that is easy for the Re-Opened Visits Report to interpret.
207 public function logFSMessage($action)
209 newEvent(
210 'fee-sheet',
211 $_SESSION['authUser'],
212 $_SESSION['authProvider'],
214 $action,
215 $this->pid,
216 $this->encounter
220 // Compute a current checksum of this encounter's Fee Sheet data from the database.
222 public function visitChecksum($saved = false)
224 $rowb = sqlQuery(
225 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
226 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
227 "))) AS checksum FROM billing WHERE " .
228 "pid = ? AND encounter = ? AND activity = 1",
229 array($this->pid, $this->encounter)
231 $rowp = sqlQuery(
232 "SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
233 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
234 "))) AS checksum FROM drug_sales WHERE " .
235 "pid = ? AND encounter = ?",
236 array($this->pid, $this->encounter)
238 $ret = intval($rowb['checksum']) ^ intval($rowp['checksum']);
239 if (CHECKSUM_LOGGING) {
240 $comment = "Checksum = '$ret'";
241 $comment .= ", Saved = " . ($saved ? "true" : "false");
242 newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid);
245 return $ret;
248 // IPPF-specific; get contraception attributes of the related codes.
250 public function checkRelatedForContraception($related_code, $is_initial_consult = false)
252 $this->line_contra_code = '';
253 $this->line_contra_cyp = 0;
254 $this->line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
255 if (!empty($related_code)) {
256 $relcodes = explode(';', $related_code);
257 foreach ($relcodes as $relstring) {
258 if ($relstring === '') {
259 continue;
262 list($reltype, $relcode) = explode(':', $relstring);
263 if ($reltype !== 'IPPFCM') {
264 continue;
267 $methtype = $is_initial_consult ? 2 : 1;
268 $tmprow = sqlQuery("SELECT cyp_factor FROM codes WHERE " .
269 "code_type = '32' AND code = ? LIMIT 1", array($relcode));
270 $cyp = 0 + $tmprow['cyp_factor'];
271 if ($cyp > $this->line_contra_cyp) {
272 $this->line_contra_cyp = $cyp;
273 // Note this is an IPPFCM code, not an IPPF2 code.
274 $this->line_contra_code = $relcode;
275 $this->line_contra_methtype = $methtype;
281 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
282 // This is only needed for auto-creating Contraception forms.
284 public function insert_lbf_item($form_id, $field_id, $field_value)
286 if ($form_id) {
287 sqlInsert("INSERT INTO lbf_data (form_id, field_id, field_value) " .
288 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
289 } else {
290 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
291 "VALUES (?, ?)", array($field_id, $field_value));
294 return $form_id;
297 // Create an array of data for a particular billing table item that is useful
298 // for building a user interface form row. $args is an array containing:
299 // codetype
300 // code
301 // modifier
302 // ndc_info
303 // auth
304 // del
305 // units
306 // fee
307 // id
308 // billed
309 // code_text
310 // justify
311 // provider_id
312 // notecodes
313 // pricelevel
314 public function addServiceLineItem($args)
316 global $code_types;
318 // echo "<!-- \n"; // debugging
319 // print_r($args); // debugging
320 // echo "--> \n"; // debugging
322 $li = array();
323 $li['hidden'] = array();
325 $codetype = $args['codetype'];
326 $code = $args['code'];
327 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
328 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
329 $units = isset($args['units']) ? $args['units'] : 0;
330 $units = max(1, intval($units));
331 $billed = !empty($args['billed']);
332 $auth = !empty($args['auth']);
333 $id = isset($args['id']) ? intval($args['id']) : 0;
334 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
335 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
336 $justify = isset($args['justify']) ? $args['justify'] : '';
337 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
338 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
339 // Price level should be unset only if adding a new line item.
340 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
341 $del = !empty($args['del']);
343 // If using line item billing and user wishes to default to a selected provider, then do so.
344 if (!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
345 if ($provider_id == 0) {
346 $provider_id = 0 + $this->findProvider();
350 if ($codetype == 'COPAY') {
351 if (!$code_text) {
352 $code_text = 'Cash';
355 if ($fee > 0) {
356 $fee = 0 - $fee;
360 // Get the matching entry from the codes table.
361 $sqlArray = array();
362 $query = "SELECT id, units, code_text FROM codes WHERE " .
363 "code_type = ? AND code = ?";
364 array_push($sqlArray, $code_types[$codetype]['id'], $code);
365 if ($modifier) {
366 $query .= " AND modifier = ?";
367 array_push($sqlArray, $modifier);
368 } else {
369 $query .= " AND (modifier IS NULL OR modifier = '')";
372 $result = sqlQuery($query, $sqlArray);
373 $codes_id = $result['id'];
375 if (!$code_text) {
376 $code_text = $result['code_text'];
377 if (empty($units)) {
378 $units = max(1, intval($result['units']));
381 if (!isset($args['fee'])) {
382 // Fees come from the prices table now.
383 $query = "SELECT pr_price FROM prices WHERE " .
384 "pr_id = ? AND pr_selector = '' AND pr_level = ? " .
385 "LIMIT 1";
386 // echo "\n<!-- $query -->\n"; // debugging
387 $prrow = sqlQuery($query, array($codes_id, $pricelevel));
388 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
392 $fee = sprintf('%01.2f', $fee);
394 $li['hidden']['code_type'] = $codetype;
395 $li['hidden']['code' ] = $code;
396 $li['hidden']['mod' ] = $modifier;
397 $li['hidden']['billed' ] = $billed;
398 $li['hidden']['id' ] = $id;
399 $li['hidden']['codes_id' ] = $codes_id;
401 // This logic is only used for family planning clinics, and then only when
402 // the option is chosen to use or auto-generate Contraception forms.
403 // It adds contraceptive method and effectiveness to relevant lines.
404 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
405 $codesrow = sqlQuery(
406 "SELECT related_code, cyp_factor FROM codes WHERE " .
407 "code_type = ? AND code = ? LIMIT 1",
408 array($code_types[$codetype]['id'], $code)
410 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
411 if ($this->line_contra_code) {
412 $li['hidden']['method' ] = $this->line_contra_code;
413 $li['hidden']['cyp' ] = $this->line_contra_cyp;
414 $li['hidden']['methtype'] = $this->line_contra_methtype;
415 // contraception_code is only concerned with initial consults.
416 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
417 $this->contraception_cyp = $this->line_contra_cyp;
418 $this->contraception_code = $this->line_contra_code;
423 if ($codetype == 'COPAY') {
424 $li['codetype'] = xl($codetype);
425 if ($ndc_info) {
426 $li['codetype'] .= " ($ndc_info)";
429 $ndc_info = '';
430 } else {
431 $li['codetype'] = $codetype;
434 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
435 $li['mod' ] = $modifier;
436 $li['fee' ] = $fee;
437 $li['price' ] = $fee / $units;
438 $li['pricelevel'] = $pricelevel;
439 $li['units' ] = $units;
440 $li['provid' ] = $provider_id;
441 $li['justify' ] = $justify;
442 $li['notecodes'] = $notecodes;
443 $li['del' ] = $id && $del;
444 $li['code_text'] = $code_text;
445 $li['auth' ] = $auth;
447 $li['hidden']['price'] = $li['price'];
449 // If NDC info exists or may be required, add stuff for it.
450 if ($codetype == 'HCPCS' && !$billed) {
451 $ndcnum = '';
452 $ndcuom = '';
453 $ndcqty = '';
454 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
455 $ndcnum = $tmp[1];
456 $ndcuom = $tmp[2];
457 $ndcqty = $tmp[3];
460 $li['ndcnum' ] = $ndcnum;
461 $li['ndcuom' ] = $ndcuom;
462 $li['ndcqty' ] = $ndcqty;
463 } else if ($ndc_info) {
464 $li['ndc_info' ] = $ndc_info;
467 // For Family Planning.
468 if ($codetype == 'MA') {
469 ++$this->required_code_count;
472 if ($fee != 0) {
473 $this->hasCharges = true;
476 $this->serviceitems[] = $li;
479 // Create an array of data for a particular drug_sales table item that is useful
480 // for building a user interface form row. $args is an array containing:
481 // drug_id
482 // selector
483 // sale_id
484 // rx (boolean)
485 // del (boolean)
486 // units
487 // fee
488 // billed
489 // warehouse_id
490 // pricelevel
492 public function addProductLineItem($args)
494 global $code_types;
496 $li = array();
497 $li['hidden'] = array();
499 $drug_id = $args['drug_id'];
500 $selector = isset($args['selector']) ? $args['selector'] : '';
501 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
502 $units = isset($args['units']) ? $args['units'] : 0;
503 $units = max(1, intval($units));
504 $billed = !empty($args['billed']);
505 $rx = !empty($args['rx']);
506 $del = !empty($args['del']);
507 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
508 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
509 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
511 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id));
512 $code_text = $drow['name'];
514 // If no warehouse ID passed, use the logged-in user's default.
515 if ($this->got_warehouses && $warehouse_id === '') {
516 $warehouse_id = $this->default_warehouse;
519 // If fee is not provided, get it from the prices table.
520 // It is assumed in this case that units will match what is in the product template.
521 if (!isset($args['fee'])) {
522 $query = "SELECT pr_price FROM prices WHERE " .
523 "pr_id = ? AND pr_selector = ? AND pr_level = ? " .
524 "LIMIT 1";
525 $prrow = sqlQuery($query, array($drug_id, $selector, $pricelevel));
526 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
529 $fee = sprintf('%01.2f', $fee);
531 $li['fee' ] = $fee;
532 $li['price' ] = $fee / $units;
533 $li['pricelevel'] = $pricelevel;
534 $li['units' ] = $units;
535 $li['del' ] = $sale_id && $del;
536 $li['code_text'] = $code_text;
537 $li['warehouse'] = $warehouse_id;
538 $li['rx' ] = $rx;
540 $li['hidden']['drug_id'] = $drug_id;
541 $li['hidden']['selector'] = $selector;
542 $li['hidden']['sale_id'] = $sale_id;
543 $li['hidden']['billed' ] = $billed;
544 $li['hidden']['price' ] = $li['price'];
546 // This logic is only used for family planning clinics, and then only when
547 // the option is chosen to use or auto-generate Contraception forms.
548 // It adds contraceptive method and effectiveness to relevant lines.
549 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
550 $this->checkRelatedForContraception($drow['related_code']);
551 if ($this->line_contra_code) {
552 $li['hidden']['method' ] = $this->line_contra_code;
553 $li['hidden']['methtype'] = $this->line_contra_methtype;
557 // For Family Planning.
558 ++$this->required_code_count;
559 if ($fee != 0) {
560 $this->hasCharges = true;
563 $this->productitems[] = $li;
566 // Generate rows for items already in the billing table for this encounter.
568 public function loadServiceItems()
570 $billresult = getBillingByEncounter($this->pid, $this->encounter, "*");
571 if ($billresult) {
572 foreach ($billresult as $iter) {
573 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') {
574 continue;
577 $justify = trim($iter['justify']);
578 if ($justify) {
579 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
582 $this->addServiceLineItem(array(
583 'id' => $iter['id'],
584 'codetype' => $iter['code_type'],
585 'code' => trim($iter['code']),
586 'modifier' => trim($iter["modifier"]),
587 'code_text' => trim($iter['code_text']),
588 'units' => $iter['units'],
589 'fee' => $iter['fee'],
590 'pricelevel' => $iter['pricelevel'],
591 'billed' => $iter['billed'],
592 'ndc_info' => $iter['ndc_info'],
593 'provider_id' => $iter['provider_id'],
594 'justify' => $justify,
595 'notecodes' => trim($iter['notecodes']),
600 // echo "<!-- \n"; // debugging
601 // print_r($this->serviceitems); // debugging
602 // echo "--> \n"; // debugging
605 // Generate rows for items already in the drug_sales table for this encounter.
607 public function loadProductItems()
609 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
610 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
611 "ORDER BY ds.sale_id";
612 $sres = sqlStatement($query, array($this->pid, $this->encounter));
613 while ($srow = sqlFetchArray($sres)) {
614 $this->addProductLineItem(array(
615 'drug_id' => $srow['drug_id'],
616 'selector' => $srow['selector'],
617 'sale_id' => $srow['sale_id'],
618 'rx' => !empty($srow['prescription_id']),
619 'units' => $srow['quantity'],
620 'fee' => $srow['fee'],
621 'pricelevel' => $srow['pricelevel'],
622 'billed' => $srow['billed'],
623 'warehouse_id' => $srow['warehouse_id'],
628 // Check for insufficient product inventory levels.
629 // Returns an error message if any product items cannot be filled.
630 // You must call this before save().
632 public function checkInventory(&$prod)
634 $alertmsg = '';
635 $insufficient = 0;
636 $expiredlots = false;
637 if (is_array($prod)) {
638 foreach ($prod as $iter) {
639 if (!empty($iter['billed'])) {
640 continue;
643 $drug_id = $iter['drug_id'];
644 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
645 $units = empty($iter['units']) ? 1 : intval($iter['units']);
646 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
648 // Deleting always works.
649 if (!empty($iter['del'])) {
650 continue;
653 // If the item is already in the database...
654 if ($sale_id) {
655 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
656 "FROM drug_sales AS ds " .
657 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
658 "WHERE ds.sale_id = ?";
659 $dirow = sqlQuery($query, array($sale_id));
660 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
661 if (!empty($dirow['inventory_id'])) {
662 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
663 // Changing warehouse so check inventory in the new warehouse.
664 // Nothing is updated by this call.
665 if (!sellDrug(
666 $drug_id,
667 $units,
669 $this->pid,
670 $this->encounter,
672 $this->visit_date,
674 $warehouse_id,
675 true,
676 $expiredlots
677 )) {
678 $insufficient = $drug_id;
680 } else {
681 if (($dirow['on_hand'] + $dirow['quantity'] - $units) < 0) {
682 $insufficient = $drug_id;
686 } // Otherwise it's a new item...
687 else {
688 // This only checks for sufficient inventory, nothing is updated.
689 if (!sellDrug(
690 $drug_id,
691 $units,
693 $this->pid,
694 $this->encounter,
696 $this->visit_date,
698 $warehouse_id,
699 true,
700 $expiredlots
701 )) {
702 $insufficient = $drug_id;
705 } // end for
708 if ($insufficient) {
709 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
710 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
711 if ($expiredlots) {
712 $alertmsg .= " " . xl('Check expiration dates.');
716 return $alertmsg;
719 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
720 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
722 public function save(
723 &$bill,
724 &$prod,
725 $main_provid = null,
726 $main_supid = null,
727 $default_warehouse = null,
728 $mark_as_closed = false
730 global $code_types;
732 if (isset($main_provid) && $main_supid == $main_provid) {
733 $main_supid = 0;
736 $copay_update = false;
737 $update_session_id = '';
738 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
739 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
740 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
742 if (is_array($bill)) {
743 foreach ($bill as $iter) {
744 // Skip disabled (billed) line items.
745 if (!empty($iter['billed'])) {
746 continue;
749 $id = $iter['id'];
750 $code_type = $iter['code_type'];
751 $code = $iter['code'];
752 $del = !empty($iter['del']);
753 $units = empty($iter['units']) ? 1 : intval($iter['units']);
754 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
755 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
756 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
757 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
758 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
759 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
761 $fee = sprintf('%01.2f', $price * $units);
763 if (!$cod0 && $code_types[$code_type]['fee'] == 1) {
764 $mod0 = $modifier;
765 $cod0 = $code;
766 $ct0 = $code_type;
769 if ($code_type == 'COPAY') {
770 if ($fee < 0) {
771 $fee = $fee * -1;
774 if (!$id) {
775 // adding new copay from fee sheet into ar_session and ar_activity tables
776 $session_id = idSqlStatement(
777 "INSERT INTO ar_session " .
778 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
779 "adjustment_code, post_to_date) " .
780 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
781 array($_SESSION['authId'], $fee, $this->pid)
783 sqlBeginTrans();
784 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
785 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
786 SqlStatement(
787 "INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
788 "payer_type, post_time, post_user, session_id, " .
789 "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
790 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
791 $_SESSION['authId'],
792 $session_id,
793 $fee)
795 sqlCommitTrans();
796 } else {
797 // editing copay saved to ar_session and ar_activity
798 $session_id = $id;
799 $res_amount = sqlQuery(
800 "SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?",
801 array($this->pid, $this->encounter, $session_id)
803 if ($fee != $res_amount['pay_amount']) {
804 sqlStatement(
805 "UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?",
806 array($_SESSION['authId'], $fee, $session_id)
808 sqlStatement(
809 "UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now(),".
810 "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?",
811 array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id)
816 if (!$cod0) {
817 $copay_update = true;
818 $update_session_id = $session_id;
821 continue;
824 # Code to create justification for all codes based on first justification
825 if ($GLOBALS['replicate_justification'] == '1') {
826 if ($justify != '') {
827 $autojustify = $justify;
831 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
832 $justify = $autojustify;
835 if ($justify) {
836 $justify = str_replace(',', ':', $justify) . ':';
839 $auth = "1";
841 $ndc_info = '';
842 if (!empty($iter['ndcnum'])) {
843 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
844 trim($iter['ndcqty']);
847 // If the item is already in the database...
848 if ($id) {
849 if ($del) {
850 $this->logFSMessage(xl('Service deleted'));
851 deleteBilling($id);
852 } else {
853 $tmp = sqlQuery(
854 "SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1",
855 array($id)
857 if (!empty($tmp)) {
858 $tmparr = array('code' => $code, 'authorized' => $auth);
859 if (isset($iter['units' ])) {
860 $tmparr['units' ] = $units;
863 if (isset($iter['price' ])) {
864 $tmparr['fee' ] = $fee;
867 if (isset($iter['pricelevel'])) {
868 $tmparr['pricelevel'] = $pricelevel;
871 if (isset($iter['mod' ])) {
872 $tmparr['modifier' ] = $modifier;
875 if (isset($iter['provid' ])) {
876 $tmparr['provider_id'] = $provid;
879 if (isset($iter['ndcnum' ])) {
880 $tmparr['ndc_info' ] = $ndc_info;
883 if (isset($iter['justify' ])) {
884 $tmparr['justify' ] = $justify;
887 if (isset($iter['notecodes'])) {
888 $tmparr['notecodes' ] = $notecodes;
891 foreach ($tmparr as $key => $value) {
892 if ($tmp[$key] != $value) {
893 if ('fee' == $key) {
894 $this->logFSMessage(xl('Price changed'));
897 if ('units' == $key) {
898 $this->logFSMessage(xl('Quantity changed'));
901 if ('provider_id' == $key) {
902 $this->logFSMessage(xl('Service provider changed'));
905 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
910 } // Otherwise it's a new item...
911 else if (!$del) {
912 $this->logFSMessage(xl('Service added'));
913 $code_text = lookup_code_descriptions($code_type.":".$code);
914 addBilling(
915 $this->encounter,
916 $code_type,
917 $code,
918 $code_text,
919 $this->pid,
920 $auth,
921 $provid,
922 $modifier,
923 $units,
924 $fee,
925 $ndc_info,
926 $justify,
928 $notecodes,
929 $pricelevel
932 } // end for
935 // if modifier is not inserted during loop update the record using the first
936 // non-empty modifier and code
937 if ($copay_update == true && $update_session_id != '' && $mod0 != '') {
938 sqlStatement(
939 "UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?".
940 " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
941 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id)
945 // Doing similarly to the above but for products.
946 if (is_array($prod)) {
947 foreach ($prod as $iter) {
948 // Skip disabled (billed) line items.
949 if (!empty($iter['billed'])) {
950 continue;
953 $drug_id = $iter['drug_id'];
954 $selector = empty($iter['selector']) ? '' : $iter['selector'];
955 $sale_id = $iter['sale_id']; // present only if already saved
956 $units = max(1, intval(trim($iter['units'])));
957 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
958 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
959 $fee = sprintf('%01.2f', $price * $units);
960 $del = !empty($iter['del']);
961 $rxid = 0;
962 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
963 $somechange = false;
965 // If the item is already in the database...
966 if ($sale_id) {
967 $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
968 "ds.sale_date, di.warehouse_id " .
969 "FROM drug_sales AS ds " .
970 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
971 "WHERE ds.sale_id = ?", array($sale_id));
972 $rxid = 0 + $tmprow['prescription_id'];
973 if ($del) {
974 if (!empty($tmprow)) {
975 // Delete this sale and reverse its inventory update.
976 $this->logFSMessage(xl('Product deleted'));
977 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
978 if (!empty($tmprow['inventory_id'])) {
979 sqlStatement(
980 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
981 array($tmprow['quantity'], $tmprow['inventory_id'])
986 if ($rxid) {
987 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
989 } else {
990 // Modify the sale and adjust inventory accordingly.
991 if (!empty($tmprow)) {
992 foreach (array(
993 'quantity' => $units,
994 'fee' => $fee,
995 'pricelevel' => $pricelevel,
996 'selector' => $selector,
997 'sale_date' => $this->visit_date,
998 ) as $key => $value) {
999 if ($tmprow[$key] != $value) {
1000 $somechange = true;
1001 if ('fee' == $key) {
1002 $this->logFSMessage(xl('Price changed'));
1005 if ('pricelevel' == $key) {
1006 $this->logFSMessage(xl('Price level changed'));
1009 if ('selector' == $key) {
1010 $this->logFSMessage(xl('Template selector changed'));
1013 if ('quantity' == $key) {
1014 $this->logFSMessage(xl('Quantity changed'));
1017 sqlStatement(
1018 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1019 array($value, $sale_id)
1021 if ($key == 'quantity' && $tmprow['inventory_id']) {
1022 sqlStatement(
1023 "UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
1024 array($units - $tmprow['quantity'], $tmprow['inventory_id'])
1030 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
1031 // Changing warehouse. Requires deleting and re-adding the sale.
1032 // Not setting $somechange because this alone does not affect a prescription.
1033 $this->logFSMessage(xl('Warehouse changed'));
1034 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1035 sqlStatement(
1036 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1037 array($units, $tmprow['inventory_id'])
1039 $tmpnull = null;
1040 $sale_id = sellDrug(
1041 $drug_id,
1042 $units,
1043 $fee,
1044 $this->pid,
1045 $this->encounter,
1046 (empty($iter['rx']) ? 0 : $rxid),
1047 $this->visit_date,
1049 $warehouse_id,
1050 false,
1051 $tmpnull,
1052 $pricelevel,
1053 $selector
1058 // Delete Rx if $rxid and flag not set.
1059 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
1060 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
1061 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1064 } // Otherwise it's a new item...
1065 else if (! $del) {
1066 $somechange = true;
1067 $this->logFSMessage(xl('Product added'));
1068 $tmpnull = null;
1069 $sale_id = sellDrug(
1070 $drug_id,
1071 $units,
1072 $fee,
1073 $this->pid,
1074 $this->encounter,
1076 $this->visit_date,
1078 $warehouse_id,
1079 false,
1080 $tmpnull,
1081 $pricelevel,
1082 $selector
1084 if (!$sale_id) {
1085 die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
1089 // If a prescription applies, create or update it.
1090 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
1091 // If an active rx already exists for this drug and date we will
1092 // replace it, otherwise we'll make a new one.
1093 if (empty($rxid)) {
1094 $rxid = '';
1097 // Get default drug attributes; prefer the template with the matching selector.
1098 $drow = sqlQuery(
1099 "SELECT dt.*, " .
1100 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
1101 "FROM drugs AS d, drug_templates AS dt WHERE " .
1102 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
1103 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
1104 array($drug_id, $selector)
1106 if (!empty($drow)) {
1107 $rxobj = new Prescription($rxid);
1108 $rxobj->set_patient_id($this->pid);
1109 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
1110 $rxobj->set_drug_id($drug_id);
1111 $rxobj->set_quantity($units);
1112 $rxobj->set_per_refill($units);
1113 $rxobj->set_start_date_y(substr($this->visit_date, 0, 4));
1114 $rxobj->set_start_date_m(substr($this->visit_date, 5, 2));
1115 $rxobj->set_start_date_d(substr($this->visit_date, 8, 2));
1116 $rxobj->set_date_added($this->visit_date);
1117 // Remaining attributes are the drug and template defaults.
1118 $rxobj->set_drug($drow['name']);
1119 $rxobj->set_unit($drow['unit']);
1120 $rxobj->set_dosage($drow['dosage']);
1121 $rxobj->set_form($drow['form']);
1122 $rxobj->set_refills($drow['refills']);
1123 $rxobj->set_size($drow['size']);
1124 $rxobj->set_route($drow['route']);
1125 $rxobj->set_interval($drow['period']);
1126 $rxobj->set_substitute($drow['substitute']);
1128 $rxobj->persist();
1129 // Set drug_sales.prescription_id to $rxobj->get_id().
1130 $oldrxid = $rxid;
1131 $rxid = 0 + $rxobj->get_id();
1132 if ($rxid != $oldrxid) {
1133 sqlStatement(
1134 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1135 array($rxid, $sale_id)
1140 } // end for
1143 // Set default and/or supervising provider for the encounter.
1144 if (isset($main_provid) && $main_provid != $this->provider_id) {
1145 $this->logFSMessage(xl('Default provider changed'));
1146 sqlStatement(
1147 "UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
1148 array($main_provid, $this->pid, $this->encounter)
1150 $this->provider_id = $main_provid;
1153 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
1154 sqlStatement(
1155 "UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
1156 array($main_supid, $this->pid, $this->encounter)
1158 $this->supervisor_id = $main_supid;
1161 // Save-and-Close is currently specific to Family Planning but might be more
1162 // generally useful. It provides the ability to mark an encounter as billed
1163 // directly from the Fee Sheet, if there are no charges.
1164 if ($mark_as_closed) {
1165 $tmp1 = sqlQuery(
1166 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
1167 "pid = ? AND encounter = ? AND billed = 0",
1168 array($this->pid, $this->encounter)
1170 $tmp2 = sqlQuery(
1171 "SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
1172 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1173 array($this->pid, $this->encounter)
1175 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
1176 sqlStatement(
1177 "update drug_sales SET billed = 1 WHERE " .
1178 "pid = ? AND encounter = ? AND billed = 0",
1179 array($this->pid, $this->encounter)
1181 sqlStatement(
1182 "UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
1183 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1184 array($this->pid, $this->encounter)
1186 } else {
1187 // Would be good to display an error message here... they clicked
1188 // Save and Close but the close could not be done. However the
1189 // framework does not provide an easy way to do that.
1194 // Call this after save() for Family Planning implementations.
1195 // It checks the contraception form, or makes a new one if $newmauser is set.
1196 // Returns 0 unless user intervention is required to fix a missing or incorrect form,
1197 // and in that case the return value is an existing form ID, or -1 if none.
1199 // Returns FALSE if user intervention is required to fix a missing or incorrect form.
1201 public function doContraceptionForm($ippfconmeth = null, $newmauser = null, $main_provid = 0)
1203 if (!empty($ippfconmeth)) {
1204 $csrow = sqlQuery(
1205 "SELECT f.form_id, ld.field_value FROM forms AS f " .
1206 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
1207 "WHERE " .
1208 "f.pid = ? AND f.encounter = ? AND " .
1209 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
1210 "ORDER BY f.form_id DESC LIMIT 1",
1211 array($this->pid, $this->encounter)
1213 if (isset($newmauser)) {
1214 // pastmodern is 0 iff new to modern contraception
1215 $pastmodern = $newmauser == '2' ? 0 : 1;
1216 if ($newmauser == '2') {
1217 $newmauser = '1';
1220 // Add contraception form but only if it does not already exist
1221 // (if it does, must be 2 users working on the visit concurrently).
1222 if (empty($csrow)) {
1223 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
1224 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
1225 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
1226 // Do we care about a service-specific provider here?
1227 $this->insert_lbf_item($newid, 'provider', $main_provid);
1228 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
1230 } else if (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
1231 // Contraceptive method does not match what is in an existing Contraception
1232 // form for this visit, or there is no such form. User intervention is needed.
1233 return empty($csrow) ? -1 : intval($csrow['form_id']);
1237 return 0;
1240 // Get price level from patient demographics.
1242 public function getPriceLevel()
1244 return $this->patient_pricelevel;
1247 // Update price level in patient demographics if it's changed.
1249 public function updatePriceLevel($pricelevel)
1251 if (!empty($pricelevel)) {
1252 if ($this->patient_pricelevel != $pricelevel) {
1253 $this->logFSMessage(xl('Price level changed'));
1254 sqlStatement(
1255 "UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1256 array($pricelevel, $this->pid)
1258 $this->patient_pricelevel = $pricelevel;
1263 // Create JSON string representing code type, code and selector.
1264 // This can be a checkbox value for parsing when the checkbox is clicked.
1265 // As a side effect note if the code is already selected in the Fee Sheet.
1267 public function genCodeSelectorValue($codes)
1269 global $code_types;
1270 list($codetype, $code, $selector) = explode(':', $codes);
1271 if ($codetype == 'PROD') {
1272 $crow = sqlQuery(
1273 "SELECT sale_id " .
1274 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1275 "LIMIT 1",
1276 array($this->pid, $this->encounter, $code)
1278 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
1279 $cbarray = array($codetype, $code, $selector);
1280 } else {
1281 $crow = sqlQuery(
1282 "SELECT c.id AS code_id, b.id " .
1283 "FROM codes AS c " .
1284 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1285 "WHERE c.code_type = ? AND c.code = ? LIMIT 1",
1286 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code)
1288 $this->code_is_in_fee_sheet = !empty($crow['id']);
1289 $cbarray = array($codetype, $code);
1292 $cbval = json_encode($cbarray);
1293 return $cbval;