Merge pull request #1346 from bradymiller/update-synd-surv-report_1
[openemr.git] / library / FeeSheet.class.php
blob09ea466cee579801ac186294e68222858e970108
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 $revenue_code = isset($args['revenue_code']) ? $args['revenue_code'] : '';
328 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
329 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
330 $units = isset($args['units']) ? $args['units'] : 0;
331 $units = max(1, intval($units));
332 $billed = !empty($args['billed']);
333 $auth = !empty($args['auth']);
334 $id = isset($args['id']) ? intval($args['id']) : 0;
335 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
336 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
337 $justify = isset($args['justify']) ? $args['justify'] : '';
338 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
339 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
340 // Price level should be unset only if adding a new line item.
341 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
342 $del = !empty($args['del']);
344 // If using line item billing and user wishes to default to a selected provider, then do so.
345 if (!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
346 if ($provider_id == 0) {
347 $provider_id = 0 + $this->findProvider();
351 if ($codetype == 'COPAY') {
352 if (!$code_text) {
353 $code_text = 'Cash';
356 if ($fee > 0) {
357 $fee = 0 - $fee;
361 // Get the matching entry from the codes table.
362 $sqlArray = array();
363 $query = "SELECT id, units, code_text, revenue_code FROM codes WHERE " .
364 "code_type = ? AND code = ?";
365 array_push($sqlArray, $code_types[$codetype]['id'], $code);
366 if ($modifier) {
367 $query .= " AND modifier = ?";
368 array_push($sqlArray, $modifier);
369 } else {
370 $query .= " AND (modifier IS NULL OR modifier = '')";
373 $result = sqlQuery($query, $sqlArray);
374 $codes_id = $result['id'];
375 $revenue_code = $revenue_code ? $revenue_code : $result['revenue_code'];
376 if (!$code_text) {
377 $code_text = $result['code_text'];
378 if (empty($units)) {
379 $units = max(1, intval($result['units']));
382 if (!isset($args['fee'])) {
383 // Fees come from the prices table now.
384 $query = "SELECT pr_price FROM prices WHERE " .
385 "pr_id = ? AND pr_selector = '' AND pr_level = ? " .
386 "LIMIT 1";
387 // echo "\n<!-- $query -->\n"; // debugging
388 $prrow = sqlQuery($query, array($codes_id, $pricelevel));
389 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
393 $fee = sprintf('%01.2f', $fee);
395 $li['hidden']['code_type'] = $codetype;
396 $li['hidden']['code'] = $code;
397 $li['hidden']['revenue_code'] = $revenue_code;
398 $li['hidden']['mod'] = $modifier;
399 $li['hidden']['billed'] = $billed;
400 $li['hidden']['id'] = $id;
401 $li['hidden']['codes_id'] = $codes_id;
403 // This logic is only used for family planning clinics, and then only when
404 // the option is chosen to use or auto-generate Contraception forms.
405 // It adds contraceptive method and effectiveness to relevant lines.
406 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
407 $codesrow = sqlQuery(
408 "SELECT related_code, cyp_factor FROM codes WHERE " .
409 "code_type = ? AND code = ? LIMIT 1",
410 array($code_types[$codetype]['id'], $code)
412 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
413 if ($this->line_contra_code) {
414 $li['hidden']['method' ] = $this->line_contra_code;
415 $li['hidden']['cyp' ] = $this->line_contra_cyp;
416 $li['hidden']['methtype'] = $this->line_contra_methtype;
417 // contraception_code is only concerned with initial consults.
418 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
419 $this->contraception_cyp = $this->line_contra_cyp;
420 $this->contraception_code = $this->line_contra_code;
425 if ($codetype == 'COPAY') {
426 $li['codetype'] = xl($codetype);
427 if ($ndc_info) {
428 $li['codetype'] .= " ($ndc_info)";
431 $ndc_info = '';
432 } else {
433 $li['codetype'] = $codetype;
436 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
437 $li['revenue_code' ] = $revenue_code;
438 $li['mod' ] = $modifier;
439 $li['fee' ] = $fee;
440 $li['price' ] = $fee / $units;
441 $li['pricelevel'] = $pricelevel;
442 $li['units' ] = $units;
443 $li['provid' ] = $provider_id;
444 $li['justify' ] = $justify;
445 $li['notecodes'] = $notecodes;
446 $li['del' ] = $id && $del;
447 $li['code_text'] = $code_text;
448 $li['auth' ] = $auth;
450 $li['hidden']['price'] = $li['price'];
452 // If NDC info exists or may be required, add stuff for it.
453 if ($codetype == 'HCPCS' && !$billed) {
454 $ndcnum = '';
455 $ndcuom = '';
456 $ndcqty = '';
457 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
458 $ndcnum = $tmp[1];
459 $ndcuom = $tmp[2];
460 $ndcqty = $tmp[3];
463 $li['ndcnum' ] = $ndcnum;
464 $li['ndcuom' ] = $ndcuom;
465 $li['ndcqty' ] = $ndcqty;
466 } else if ($ndc_info) {
467 $li['ndc_info' ] = $ndc_info;
470 // For Family Planning.
471 if ($codetype == 'MA') {
472 ++$this->required_code_count;
475 if ($fee != 0) {
476 $this->hasCharges = true;
479 $this->serviceitems[] = $li;
482 // Create an array of data for a particular drug_sales table item that is useful
483 // for building a user interface form row. $args is an array containing:
484 // drug_id
485 // selector
486 // sale_id
487 // rx (boolean)
488 // del (boolean)
489 // units
490 // fee
491 // billed
492 // warehouse_id
493 // pricelevel
495 public function addProductLineItem($args)
497 global $code_types;
499 $li = array();
500 $li['hidden'] = array();
502 $drug_id = $args['drug_id'];
503 $selector = isset($args['selector']) ? $args['selector'] : '';
504 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
505 $units = isset($args['units']) ? $args['units'] : 0;
506 $units = max(1, intval($units));
507 $billed = !empty($args['billed']);
508 $rx = !empty($args['rx']);
509 $del = !empty($args['del']);
510 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
511 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
512 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
514 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id));
515 $code_text = $drow['name'];
517 // If no warehouse ID passed, use the logged-in user's default.
518 if ($this->got_warehouses && $warehouse_id === '') {
519 $warehouse_id = $this->default_warehouse;
522 // If fee is not provided, get it from the prices table.
523 // It is assumed in this case that units will match what is in the product template.
524 if (!isset($args['fee'])) {
525 $query = "SELECT pr_price FROM prices WHERE " .
526 "pr_id = ? AND pr_selector = ? AND pr_level = ? " .
527 "LIMIT 1";
528 $prrow = sqlQuery($query, array($drug_id, $selector, $pricelevel));
529 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
532 $fee = sprintf('%01.2f', $fee);
534 $li['fee' ] = $fee;
535 $li['price' ] = $fee / $units;
536 $li['pricelevel'] = $pricelevel;
537 $li['units' ] = $units;
538 $li['del' ] = $sale_id && $del;
539 $li['code_text'] = $code_text;
540 $li['warehouse'] = $warehouse_id;
541 $li['rx' ] = $rx;
543 $li['hidden']['drug_id'] = $drug_id;
544 $li['hidden']['selector'] = $selector;
545 $li['hidden']['sale_id'] = $sale_id;
546 $li['hidden']['billed' ] = $billed;
547 $li['hidden']['price' ] = $li['price'];
549 // This logic is only used for family planning clinics, and then only when
550 // the option is chosen to use or auto-generate Contraception forms.
551 // It adds contraceptive method and effectiveness to relevant lines.
552 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
553 $this->checkRelatedForContraception($drow['related_code']);
554 if ($this->line_contra_code) {
555 $li['hidden']['method' ] = $this->line_contra_code;
556 $li['hidden']['methtype'] = $this->line_contra_methtype;
560 // For Family Planning.
561 ++$this->required_code_count;
562 if ($fee != 0) {
563 $this->hasCharges = true;
566 $this->productitems[] = $li;
569 // Generate rows for items already in the billing table for this encounter.
571 public function loadServiceItems()
573 $billresult = getBillingByEncounter($this->pid, $this->encounter, "*");
574 if ($billresult) {
575 foreach ($billresult as $iter) {
576 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') {
577 continue;
580 $justify = trim($iter['justify']);
581 if ($justify) {
582 $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
585 $this->addServiceLineItem(array(
586 'id' => $iter['id'],
587 'codetype' => $iter['code_type'],
588 'code' => trim($iter['code']),
589 'revenue_code' => trim($iter["revenue_code"]),
590 'modifier' => trim($iter["modifier"]),
591 'code_text' => trim($iter['code_text']),
592 'units' => $iter['units'],
593 'fee' => $iter['fee'],
594 'pricelevel' => $iter['pricelevel'],
595 'billed' => $iter['billed'],
596 'ndc_info' => $iter['ndc_info'],
597 'provider_id' => $iter['provider_id'],
598 'justify' => $justify,
599 'notecodes' => trim($iter['notecodes']),
604 // echo "<!-- \n"; // debugging
605 // print_r($this->serviceitems); // debugging
606 // echo "--> \n"; // debugging
609 // Generate rows for items already in the drug_sales table for this encounter.
611 public function loadProductItems()
613 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
614 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
615 "ORDER BY ds.sale_id";
616 $sres = sqlStatement($query, array($this->pid, $this->encounter));
617 while ($srow = sqlFetchArray($sres)) {
618 $this->addProductLineItem(array(
619 'drug_id' => $srow['drug_id'],
620 'selector' => $srow['selector'],
621 'sale_id' => $srow['sale_id'],
622 'rx' => !empty($srow['prescription_id']),
623 'units' => $srow['quantity'],
624 'fee' => $srow['fee'],
625 'pricelevel' => $srow['pricelevel'],
626 'billed' => $srow['billed'],
627 'warehouse_id' => $srow['warehouse_id'],
632 // Check for insufficient product inventory levels.
633 // Returns an error message if any product items cannot be filled.
634 // You must call this before save().
636 public function checkInventory(&$prod)
638 $alertmsg = '';
639 $insufficient = 0;
640 $expiredlots = false;
641 if (is_array($prod)) {
642 foreach ($prod as $iter) {
643 if (!empty($iter['billed'])) {
644 continue;
647 $drug_id = $iter['drug_id'];
648 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
649 $units = empty($iter['units']) ? 1 : intval($iter['units']);
650 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
652 // Deleting always works.
653 if (!empty($iter['del'])) {
654 continue;
657 // If the item is already in the database...
658 if ($sale_id) {
659 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
660 "FROM drug_sales AS ds " .
661 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
662 "WHERE ds.sale_id = ?";
663 $dirow = sqlQuery($query, array($sale_id));
664 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
665 if (!empty($dirow['inventory_id'])) {
666 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
667 // Changing warehouse so check inventory in the new warehouse.
668 // Nothing is updated by this call.
669 if (!sellDrug(
670 $drug_id,
671 $units,
673 $this->pid,
674 $this->encounter,
676 $this->visit_date,
678 $warehouse_id,
679 true,
680 $expiredlots
681 )) {
682 $insufficient = $drug_id;
684 } else {
685 if (($dirow['on_hand'] + $dirow['quantity'] - $units) < 0) {
686 $insufficient = $drug_id;
690 } // Otherwise it's a new item...
691 else {
692 // This only checks for sufficient inventory, nothing is updated.
693 if (!sellDrug(
694 $drug_id,
695 $units,
697 $this->pid,
698 $this->encounter,
700 $this->visit_date,
702 $warehouse_id,
703 true,
704 $expiredlots
705 )) {
706 $insufficient = $drug_id;
709 } // end for
712 if ($insufficient) {
713 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
714 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
715 if ($expiredlots) {
716 $alertmsg .= " " . xl('Check expiration dates.');
720 return $alertmsg;
723 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
724 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
726 public function save(
727 &$bill,
728 &$prod,
729 $main_provid = null,
730 $main_supid = null,
731 $default_warehouse = null,
732 $mark_as_closed = false
734 global $code_types;
736 if (isset($main_provid) && $main_supid == $main_provid) {
737 $main_supid = 0;
740 $copay_update = false;
741 $update_session_id = '';
742 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
743 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
744 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
746 if (is_array($bill)) {
747 foreach ($bill as $iter) {
748 // Skip disabled (billed) line items.
749 if (!empty($iter['billed'])) {
750 continue;
753 $id = $iter['id'];
754 $code_type = $iter['code_type'];
755 $code = $iter['code'];
756 $del = !empty($iter['del']);
757 $units = empty($iter['units']) ? 1 : intval($iter['units']);
758 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
759 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
760 $revenue_code = empty($iter['revenue_code']) ? '' : trim($iter['revenue_code']);
761 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
762 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
763 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
764 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
766 $fee = sprintf('%01.2f', $price * $units);
768 if (!$cod0 && $code_types[$code_type]['fee'] == 1) {
769 $mod0 = $modifier;
770 $cod0 = $code;
771 $ct0 = $code_type;
774 if ($code_type == 'COPAY') {
775 if ($fee < 0) {
776 $fee = $fee * -1;
779 if (!$id) {
780 // adding new copay from fee sheet into ar_session and ar_activity tables
781 $session_id = idSqlStatement(
782 "INSERT INTO ar_session " .
783 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
784 "adjustment_code, post_to_date) " .
785 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
786 array($_SESSION['authId'], $fee, $this->pid)
788 sqlBeginTrans();
789 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
790 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
791 SqlStatement(
792 "INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
793 "payer_type, post_time, post_user, session_id, " .
794 "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
795 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
796 $_SESSION['authId'],
797 $session_id,
798 $fee)
800 sqlCommitTrans();
801 } else {
802 // editing copay saved to ar_session and ar_activity
803 $session_id = $id;
804 $res_amount = sqlQuery(
805 "SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?",
806 array($this->pid, $this->encounter, $session_id)
808 if ($fee != $res_amount['pay_amount']) {
809 sqlStatement(
810 "UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?",
811 array($_SESSION['authId'], $fee, $session_id)
813 sqlStatement(
814 "UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now(),".
815 "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?",
816 array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id)
821 if (!$cod0) {
822 $copay_update = true;
823 $update_session_id = $session_id;
826 continue;
829 # Code to create justification for all codes based on first justification
830 if ($GLOBALS['replicate_justification'] == '1') {
831 if ($justify != '') {
832 $autojustify = $justify;
836 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
837 $justify = $autojustify;
840 if ($justify) {
841 $justify = str_replace(',', ':', $justify) . ':';
844 $auth = "1";
846 $ndc_info = '';
847 if (!empty($iter['ndcnum'])) {
848 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
849 trim($iter['ndcqty']);
852 // If the item is already in the database...
853 if ($id) {
854 if ($del) {
855 $this->logFSMessage(xl('Service deleted'));
856 deleteBilling($id);
857 } else {
858 $tmp = sqlQuery(
859 "SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1",
860 array($id)
862 if (!empty($tmp)) {
863 $tmparr = array('code' => $code, 'authorized' => $auth);
864 if (isset($iter['units' ])) {
865 $tmparr['units' ] = $units;
868 if (isset($iter['price' ])) {
869 $tmparr['fee' ] = $fee;
872 if (isset($iter['pricelevel'])) {
873 $tmparr['pricelevel'] = $pricelevel;
876 if (isset($iter['mod' ])) {
877 $tmparr['modifier' ] = $modifier;
880 if (isset($iter['provid' ])) {
881 $tmparr['provider_id'] = $provid;
884 if (isset($iter['ndcnum' ])) {
885 $tmparr['ndc_info' ] = $ndc_info;
888 if (isset($iter['justify' ])) {
889 $tmparr['justify' ] = $justify;
892 if (isset($iter['notecodes'])) {
893 $tmparr['notecodes' ] = $notecodes;
896 if (isset($iter['revenue_code'])) {
897 $tmparr['revenue_code'] = $revenue_code;
900 foreach ($tmparr as $key => $value) {
901 if ($tmp[$key] != $value) {
902 if ('fee' == $key) {
903 $this->logFSMessage(xl('Price changed'));
906 if ('units' == $key) {
907 $this->logFSMessage(xl('Quantity changed'));
910 if ('provider_id' == $key) {
911 $this->logFSMessage(xl('Service provider changed'));
914 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
919 } // Otherwise it's a new item...
920 else if (!$del) {
921 $this->logFSMessage(xl('Service added'));
922 $code_text = lookup_code_descriptions($code_type.":".$code);
923 addBilling(
924 $this->encounter,
925 $code_type,
926 $code,
927 $code_text,
928 $this->pid,
929 $auth,
930 $provid,
931 $modifier,
932 $units,
933 $fee,
934 $ndc_info,
935 $justify,
937 $notecodes,
938 $pricelevel,
939 $revenue_code
942 } // end for
945 // if modifier is not inserted during loop update the record using the first
946 // non-empty modifier and code
947 if ($copay_update == true && $update_session_id != '' && $mod0 != '') {
948 sqlStatement(
949 "UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?".
950 " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
951 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id)
955 // Doing similarly to the above but for products.
956 if (is_array($prod)) {
957 foreach ($prod as $iter) {
958 // Skip disabled (billed) line items.
959 if (!empty($iter['billed'])) {
960 continue;
963 $drug_id = $iter['drug_id'];
964 $selector = empty($iter['selector']) ? '' : $iter['selector'];
965 $sale_id = $iter['sale_id']; // present only if already saved
966 $units = max(1, intval(trim($iter['units'])));
967 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
968 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
969 $fee = sprintf('%01.2f', $price * $units);
970 $del = !empty($iter['del']);
971 $rxid = 0;
972 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
973 $somechange = false;
975 // If the item is already in the database...
976 if ($sale_id) {
977 $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
978 "ds.sale_date, di.warehouse_id " .
979 "FROM drug_sales AS ds " .
980 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
981 "WHERE ds.sale_id = ?", array($sale_id));
982 $rxid = 0 + $tmprow['prescription_id'];
983 if ($del) {
984 if (!empty($tmprow)) {
985 // Delete this sale and reverse its inventory update.
986 $this->logFSMessage(xl('Product deleted'));
987 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
988 if (!empty($tmprow['inventory_id'])) {
989 sqlStatement(
990 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
991 array($tmprow['quantity'], $tmprow['inventory_id'])
996 if ($rxid) {
997 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
999 } else {
1000 // Modify the sale and adjust inventory accordingly.
1001 if (!empty($tmprow)) {
1002 foreach (array(
1003 'quantity' => $units,
1004 'fee' => $fee,
1005 'pricelevel' => $pricelevel,
1006 'selector' => $selector,
1007 'sale_date' => $this->visit_date,
1008 ) as $key => $value) {
1009 if ($tmprow[$key] != $value) {
1010 $somechange = true;
1011 if ('fee' == $key) {
1012 $this->logFSMessage(xl('Price changed'));
1015 if ('pricelevel' == $key) {
1016 $this->logFSMessage(xl('Price level changed'));
1019 if ('selector' == $key) {
1020 $this->logFSMessage(xl('Template selector changed'));
1023 if ('quantity' == $key) {
1024 $this->logFSMessage(xl('Quantity changed'));
1027 sqlStatement(
1028 "UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
1029 array($value, $sale_id)
1031 if ($key == 'quantity' && $tmprow['inventory_id']) {
1032 sqlStatement(
1033 "UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
1034 array($units - $tmprow['quantity'], $tmprow['inventory_id'])
1040 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
1041 // Changing warehouse. Requires deleting and re-adding the sale.
1042 // Not setting $somechange because this alone does not affect a prescription.
1043 $this->logFSMessage(xl('Warehouse changed'));
1044 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
1045 sqlStatement(
1046 "UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
1047 array($units, $tmprow['inventory_id'])
1049 $tmpnull = null;
1050 $sale_id = sellDrug(
1051 $drug_id,
1052 $units,
1053 $fee,
1054 $this->pid,
1055 $this->encounter,
1056 (empty($iter['rx']) ? 0 : $rxid),
1057 $this->visit_date,
1059 $warehouse_id,
1060 false,
1061 $tmpnull,
1062 $pricelevel,
1063 $selector
1068 // Delete Rx if $rxid and flag not set.
1069 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
1070 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
1071 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
1074 } // Otherwise it's a new item...
1075 else if (! $del) {
1076 $somechange = true;
1077 $this->logFSMessage(xl('Product added'));
1078 $tmpnull = null;
1079 $sale_id = sellDrug(
1080 $drug_id,
1081 $units,
1082 $fee,
1083 $this->pid,
1084 $this->encounter,
1086 $this->visit_date,
1088 $warehouse_id,
1089 false,
1090 $tmpnull,
1091 $pricelevel,
1092 $selector
1094 if (!$sale_id) {
1095 die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
1099 // If a prescription applies, create or update it.
1100 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
1101 // If an active rx already exists for this drug and date we will
1102 // replace it, otherwise we'll make a new one.
1103 if (empty($rxid)) {
1104 $rxid = '';
1107 // Get default drug attributes; prefer the template with the matching selector.
1108 $drow = sqlQuery(
1109 "SELECT dt.*, " .
1110 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
1111 "FROM drugs AS d, drug_templates AS dt WHERE " .
1112 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
1113 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
1114 array($drug_id, $selector)
1116 if (!empty($drow)) {
1117 $rxobj = new Prescription($rxid);
1118 $rxobj->set_patient_id($this->pid);
1119 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
1120 $rxobj->set_drug_id($drug_id);
1121 $rxobj->set_quantity($units);
1122 $rxobj->set_per_refill($units);
1123 $rxobj->set_start_date_y(substr($this->visit_date, 0, 4));
1124 $rxobj->set_start_date_m(substr($this->visit_date, 5, 2));
1125 $rxobj->set_start_date_d(substr($this->visit_date, 8, 2));
1126 $rxobj->set_date_added($this->visit_date);
1127 // Remaining attributes are the drug and template defaults.
1128 $rxobj->set_drug($drow['name']);
1129 $rxobj->set_unit($drow['unit']);
1130 $rxobj->set_dosage($drow['dosage']);
1131 $rxobj->set_form($drow['form']);
1132 $rxobj->set_refills($drow['refills']);
1133 $rxobj->set_size($drow['size']);
1134 $rxobj->set_route($drow['route']);
1135 $rxobj->set_interval($drow['period']);
1136 $rxobj->set_substitute($drow['substitute']);
1138 $rxobj->persist();
1139 // Set drug_sales.prescription_id to $rxobj->get_id().
1140 $oldrxid = $rxid;
1141 $rxid = 0 + $rxobj->get_id();
1142 if ($rxid != $oldrxid) {
1143 sqlStatement(
1144 "UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
1145 array($rxid, $sale_id)
1150 } // end for
1153 // Set default and/or supervising provider for the encounter.
1154 if (isset($main_provid) && $main_provid != $this->provider_id) {
1155 $this->logFSMessage(xl('Default provider changed'));
1156 sqlStatement(
1157 "UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
1158 array($main_provid, $this->pid, $this->encounter)
1160 $this->provider_id = $main_provid;
1163 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
1164 sqlStatement(
1165 "UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
1166 array($main_supid, $this->pid, $this->encounter)
1168 $this->supervisor_id = $main_supid;
1171 // Save-and-Close is currently specific to Family Planning but might be more
1172 // generally useful. It provides the ability to mark an encounter as billed
1173 // directly from the Fee Sheet, if there are no charges.
1174 if ($mark_as_closed) {
1175 $tmp1 = sqlQuery(
1176 "SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
1177 "pid = ? AND encounter = ? AND billed = 0",
1178 array($this->pid, $this->encounter)
1180 $tmp2 = sqlQuery(
1181 "SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
1182 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1183 array($this->pid, $this->encounter)
1185 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
1186 sqlStatement(
1187 "update drug_sales SET billed = 1 WHERE " .
1188 "pid = ? AND encounter = ? AND billed = 0",
1189 array($this->pid, $this->encounter)
1191 sqlStatement(
1192 "UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
1193 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
1194 array($this->pid, $this->encounter)
1196 } else {
1197 // Would be good to display an error message here... they clicked
1198 // Save and Close but the close could not be done. However the
1199 // framework does not provide an easy way to do that.
1204 // Call this after save() for Family Planning implementations.
1205 // It checks the contraception form, or makes a new one if $newmauser is set.
1206 // Returns 0 unless user intervention is required to fix a missing or incorrect form,
1207 // and in that case the return value is an existing form ID, or -1 if none.
1209 // Returns FALSE if user intervention is required to fix a missing or incorrect form.
1211 public function doContraceptionForm($ippfconmeth = null, $newmauser = null, $main_provid = 0)
1213 if (!empty($ippfconmeth)) {
1214 $csrow = sqlQuery(
1215 "SELECT f.form_id, ld.field_value FROM forms AS f " .
1216 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
1217 "WHERE " .
1218 "f.pid = ? AND f.encounter = ? AND " .
1219 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
1220 "ORDER BY f.form_id DESC LIMIT 1",
1221 array($this->pid, $this->encounter)
1223 if (isset($newmauser)) {
1224 // pastmodern is 0 iff new to modern contraception
1225 $pastmodern = $newmauser == '2' ? 0 : 1;
1226 if ($newmauser == '2') {
1227 $newmauser = '1';
1230 // Add contraception form but only if it does not already exist
1231 // (if it does, must be 2 users working on the visit concurrently).
1232 if (empty($csrow)) {
1233 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
1234 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
1235 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
1236 // Do we care about a service-specific provider here?
1237 $this->insert_lbf_item($newid, 'provider', $main_provid);
1238 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
1240 } else if (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
1241 // Contraceptive method does not match what is in an existing Contraception
1242 // form for this visit, or there is no such form. User intervention is needed.
1243 return empty($csrow) ? -1 : intval($csrow['form_id']);
1247 return 0;
1250 // Get price level from patient demographics.
1252 public function getPriceLevel()
1254 return $this->patient_pricelevel;
1257 // Update price level in patient demographics if it's changed.
1259 public function updatePriceLevel($pricelevel)
1261 if (!empty($pricelevel)) {
1262 if ($this->patient_pricelevel != $pricelevel) {
1263 $this->logFSMessage(xl('Price level changed'));
1264 sqlStatement(
1265 "UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
1266 array($pricelevel, $this->pid)
1268 $this->patient_pricelevel = $pricelevel;
1273 // Create JSON string representing code type, code and selector.
1274 // This can be a checkbox value for parsing when the checkbox is clicked.
1275 // As a side effect note if the code is already selected in the Fee Sheet.
1277 public function genCodeSelectorValue($codes)
1279 global $code_types;
1280 list($codetype, $code, $selector) = explode(':', $codes);
1281 if ($codetype == 'PROD') {
1282 $crow = sqlQuery(
1283 "SELECT sale_id " .
1284 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
1285 "LIMIT 1",
1286 array($this->pid, $this->encounter, $code)
1288 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
1289 $cbarray = array($codetype, $code, $selector);
1290 } else {
1291 $crow = sqlQuery(
1292 "SELECT c.id AS code_id, b.id " .
1293 "FROM codes AS c " .
1294 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1295 "WHERE c.code_type = ? AND c.code = ? LIMIT 1",
1296 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code)
1298 $this->code_is_in_fee_sheet = !empty($crow['id']);
1299 $cbarray = array($codetype, $code);
1302 $cbval = json_encode($cbarray);
1303 return $cbval;