migrated ubiquitous libraries to composer autoloader (#421)
[openemr.git] / library / FeeSheet.class.php
blobf6dbda5341774f74c34cbb83c7cdc9fe2fa15ee2
1 <?php
2 /**
3 * library/FeeSheet.class.php
4 *
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
26 $fake_register_globals = false;
27 $sanitize_all_escapes = true;
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__) . "/formatting.inc.php");
35 require_once(dirname(__FILE__) . "/options.inc.php");
36 require_once(dirname(__FILE__) . "/appointment_status.inc.php");
37 require_once(dirname(__FILE__) . "/classes/Prescription.class.php");
38 require_once(dirname(__FILE__) . "/forms.inc");
39 require_once(dirname(__FILE__) . "/log.inc");
40 // For logging checksums set this to true.
41 define('CHECKSUM_LOGGING', true);
43 // require_once(dirname(__FILE__) . "/api.inc");
44 // require_once(dirname(__FILE__) . "/forms.inc");
46 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) {
96 if (empty($pid)) $pid = $GLOBALS['pid'];
97 if (empty($encounter)) $encounter = $GLOBALS['encounter'];
98 $this->pid = $pid;
99 $this->encounter = $encounter;
101 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
102 $this->ALLOW_COPAYS = !$GLOBALS['ippf_specific'];
104 // Get the user's default warehouse and an indicator if there's a choice of warehouses.
105 $wrow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse' AND activity = 1");
106 $this->got_warehouses = $wrow['count'] > 1;
107 $wrow = sqlQuery("SELECT default_warehouse FROM users WHERE username = ?",
108 array($_SESSION['authUser']));
109 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
111 // Get some info about this visit.
112 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
113 "opc.pc_catname, fac.extra_validation " .
114 "FROM form_encounter AS fe " .
115 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
116 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
117 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter) );
118 $this->visit_date = substr($visit_row['date'], 0, 10);
119 $this->provider_id = $visit_row['provider_id'];
120 if (empty($this->provider_id)) $this->provider_id = findProvider();
121 $this->supervisor_id = $visit_row['supervisor_id'];
122 // This flag is specific to IPPF validation at form submit time. It indicates
123 // that most contraceptive services and products should match up on the fee sheet.
124 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
125 !empty($visit_row['extra_validation']);
127 // Get some information about the patient.
128 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
129 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
130 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
131 $this->patient_pricelevel = $patientrow['pricelevel'];
134 // Convert numeric code type to the alpha version.
136 public static function alphaCodeType($id) {
137 global $code_types;
138 foreach ($code_types as $key => $value) {
139 if ($value['id'] == $id) return $key;
141 return '';
144 // Compute age in years given a DOB and "as of" date.
146 public static function getAge($dob, $asof='') {
147 if (empty($asof)) $asof = date('Y-m-d');
148 $a1 = explode('-', substr($dob , 0, 10));
149 $a2 = explode('-', substr($asof, 0, 10));
150 $age = $a2[0] - $a1[0];
151 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) --$age;
152 return $age;
155 // Gets the provider from the encounter, logged-in user or patient demographics.
156 // Adapted from work by Terry Hill.
158 public function findProvider() {
159 $find_provider = sqlQuery("SELECT provider_id FROM form_encounter " .
160 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
161 array($this->pid, $this->encounter));
162 $providerid = $find_provider['provider_id'];
163 if (!$providerid) {
164 $get_authorized = $_SESSION['userauthorized'];
165 if ($get_authorized == 1) {
166 $providerid = $_SESSION['authUserID'];
169 if (!$providerid) {
170 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
171 "WHERE pid = ?", array($this->pid) );
172 $providerid = $find_provider['providerID'];
174 return intval($providerid);
177 // Log a message that is easy for the Re-Opened Visits Report to interpret.
179 public function logFSMessage($action) {
180 newEvent('fee-sheet', $_SESSION['authUser'], $_SESSION['authProvider'], 1,
181 $action, $this->pid, $this->encounter);
184 // Compute a current checksum of this encounter's Fee Sheet data from the database.
186 public function visitChecksum($saved=false) {
187 $rowb = sqlQuery("SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
188 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
189 "))) AS checksum FROM billing WHERE " .
190 "pid = ? AND encounter = ? AND activity = 1",
191 array($this->pid, $this->encounter));
192 $rowp = sqlQuery("SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
193 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
194 "))) AS checksum FROM drug_sales WHERE " .
195 "pid = ? AND encounter = ?",
196 array($this->pid, $this->encounter));
197 $ret = intval($rowb['checksum']) ^ intval($rowp['checksum']);
198 if (CHECKSUM_LOGGING) {
199 $comment = "Checksum = '$ret'";
200 $comment .= ", Saved = " . ($saved ? "true" : "false");
201 newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid);
203 return $ret;
206 // IPPF-specific; get contraception attributes of the related codes.
208 public function checkRelatedForContraception($related_code, $is_initial_consult=false) {
209 $this->line_contra_code = '';
210 $this->line_contra_cyp = 0;
211 $this->line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
212 if (!empty($related_code)) {
213 $relcodes = explode(';', $related_code);
214 foreach ($relcodes as $relstring) {
215 if ($relstring === '') continue;
216 list($reltype, $relcode) = explode(':', $relstring);
217 if ($reltype !== 'IPPFCM') continue;
218 $methtype = $is_initial_consult ? 2 : 1;
219 $tmprow = sqlQuery("SELECT cyp_factor FROM codes WHERE " .
220 "code_type = '32' AND code = ? LIMIT 1", array($relcode));
221 $cyp = 0 + $tmprow['cyp_factor'];
222 if ($cyp > $this->line_contra_cyp) {
223 $this->line_contra_cyp = $cyp;
224 // Note this is an IPPFCM code, not an IPPF2 code.
225 $this->line_contra_code = $relcode;
226 $this->line_contra_methtype = $methtype;
232 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
233 // This is only needed for auto-creating Contraception forms.
235 public function insert_lbf_item($form_id, $field_id, $field_value) {
236 if ($form_id) {
237 sqlInsert("INSERT INTO lbf_data (form_id, field_id, field_value) " .
238 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
240 else {
241 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
242 "VALUES (?, ?)", array($field_id, $field_value));
244 return $form_id;
247 // Create an array of data for a particular billing table item that is useful
248 // for building a user interface form row. $args is an array containing:
249 // codetype
250 // code
251 // modifier
252 // ndc_info
253 // auth
254 // del
255 // units
256 // fee
257 // id
258 // billed
259 // code_text
260 // justify
261 // provider_id
262 // notecodes
263 // pricelevel
264 public function addServiceLineItem($args) {
265 global $code_types;
267 // echo "<!-- \n"; // debugging
268 // print_r($args); // debugging
269 // echo "--> \n"; // debugging
271 $li = array();
272 $li['hidden'] = array();
274 $codetype = $args['codetype'];
275 $code = $args['code'];
276 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
277 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
278 $units = isset($args['units']) ? $args['units'] : 0;
279 $units = max(1, intval($units));
280 $billed = !empty($args['billed']);
281 $auth = !empty($args['auth']);
282 $id = isset($args['id']) ? intval($args['id']) : 0;
283 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
284 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
285 $justify = isset($args['justify']) ? $args['justify'] : '';
286 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
287 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
288 // Price level should be unset only if adding a new line item.
289 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
290 $del = !empty($args['del']);
292 // If using line item billing and user wishes to default to a selected provider, then do so.
293 if(!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
294 if ($provider_id == 0) {
295 $provider_id = 0 + $this->findProvider();
299 if ($codetype == 'COPAY') {
300 if (!$code_text) $code_text = 'Cash';
301 if ($fee > 0) $fee = 0 - $fee;
304 // Get the matching entry from the codes table.
305 $sqlArray = array();
306 $query = "SELECT id, units, code_text FROM codes WHERE " .
307 "code_type = ? AND code = ?";
308 array_push($sqlArray, $code_types[$codetype]['id'], $code);
309 if ($modifier) {
310 $query .= " AND modifier = ?";
311 array_push($sqlArray, $modifier);
313 else {
314 $query .= " AND (modifier IS NULL OR modifier = '')";
316 $result = sqlQuery($query, $sqlArray);
317 $codes_id = $result['id'];
319 if (!$code_text) {
320 $code_text = $result['code_text'];
321 if (empty($units)) $units = max(1, intval($result['units']));
322 if (!isset($args['fee'])) {
323 // Fees come from the prices table now.
324 $query = "SELECT pr_price FROM prices WHERE " .
325 "pr_id = ? AND pr_selector = '' AND pr_level = ? " .
326 "LIMIT 1";
327 // echo "\n<!-- $query -->\n"; // debugging
328 $prrow = sqlQuery($query, array($codes_id, $pricelevel));
329 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
332 $fee = sprintf('%01.2f', $fee);
334 $li['hidden']['code_type'] = $codetype;
335 $li['hidden']['code' ] = $code;
336 $li['hidden']['mod' ] = $modifier;
337 $li['hidden']['billed' ] = $billed;
338 $li['hidden']['id' ] = $id;
339 $li['hidden']['codes_id' ] = $codes_id;
341 // This logic is only used for family planning clinics, and then only when
342 // the option is chosen to use or auto-generate Contraception forms.
343 // It adds contraceptive method and effectiveness to relevant lines.
344 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
345 $codesrow = sqlQuery("SELECT related_code, cyp_factor FROM codes WHERE " .
346 "code_type = ? AND code = ? LIMIT 1",
347 array($code_types[$codetype]['id'], $code));
348 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
349 if ($this->line_contra_code) {
350 $li['hidden']['method' ] = $this->line_contra_code;
351 $li['hidden']['cyp' ] = $this->line_contra_cyp;
352 $li['hidden']['methtype'] = $this->line_contra_methtype;
353 // contraception_code is only concerned with initial consults.
354 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
355 $this->contraception_cyp = $this->line_contra_cyp;
356 $this->contraception_code = $this->line_contra_code;
361 if($codetype == 'COPAY') {
362 $li['codetype'] = xl($codetype);
363 if ($ndc_info) $li['codetype'] .= " ($ndc_info)";
364 $ndc_info = '';
366 else {
367 $li['codetype'] = $codetype;
370 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
371 $li['mod' ] = $modifier;
372 $li['fee' ] = $fee;
373 $li['price' ] = $fee / $units;
374 $li['pricelevel'] = $pricelevel;
375 $li['units' ] = $units;
376 $li['provid' ] = $provider_id;
377 $li['justify' ] = $justify;
378 $li['notecodes'] = $notecodes;
379 $li['del' ] = $id && $del;
380 $li['code_text'] = $code_text;
381 $li['auth' ] = $auth;
383 $li['hidden']['price'] = $li['price'];
385 // If NDC info exists or may be required, add stuff for it.
386 if ($codetype == 'HCPCS' && !$billed) {
387 $ndcnum = ''; $ndcuom = ''; $ndcqty = '';
388 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
389 $ndcnum = $tmp[1]; $ndcuom = $tmp[2]; $ndcqty = $tmp[3];
391 $li['ndcnum' ] = $ndcnum;
392 $li['ndcuom' ] = $ndcuom;
393 $li['ndcqty' ] = $ndcqty;
395 else if ($ndc_info) {
396 $li['ndc_info' ] = $ndc_info;
399 // For Family Planning.
400 if ($codetype == 'MA') ++$this->required_code_count;
401 if ($fee != 0) $this->hasCharges = true;
403 $this->serviceitems[] = $li;
406 // Create an array of data for a particular drug_sales table item that is useful
407 // for building a user interface form row. $args is an array containing:
408 // drug_id
409 // selector
410 // sale_id
411 // rx (boolean)
412 // del (boolean)
413 // units
414 // fee
415 // billed
416 // warehouse_id
417 // pricelevel
419 public function addProductLineItem($args) {
420 global $code_types;
422 $li = array();
423 $li['hidden'] = array();
425 $drug_id = $args['drug_id'];
426 $selector = isset($args['selector']) ? $args['selector'] : '';
427 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
428 $units = isset($args['units']) ? $args['units'] : 0;
429 $units = max(1, intval($units));
430 $billed = !empty($args['billed']);
431 $rx = !empty($args['rx']);
432 $del = !empty($args['del']);
433 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
434 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
435 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
437 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id) );
438 $code_text = $drow['name'];
440 // If no warehouse ID passed, use the logged-in user's default.
441 if ($this->got_warehouses && $warehouse_id === '') $warehouse_id = $this->default_warehouse;
443 // If fee is not provided, get it from the prices table.
444 // It is assumed in this case that units will match what is in the product template.
445 if (!isset($args['fee'])) {
446 $query = "SELECT pr_price FROM prices WHERE " .
447 "pr_id = ? AND pr_selector = ? AND pr_level = ? " .
448 "LIMIT 1";
449 $prrow = sqlQuery($query, array($drug_id, $selector, $pricelevel));
450 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
453 $fee = sprintf('%01.2f', $fee);
455 $li['fee' ] = $fee;
456 $li['price' ] = $fee / $units;
457 $li['pricelevel'] = $pricelevel;
458 $li['units' ] = $units;
459 $li['del' ] = $sale_id && $del;
460 $li['code_text'] = $code_text;
461 $li['warehouse'] = $warehouse_id;
462 $li['rx' ] = $rx;
464 $li['hidden']['drug_id'] = $drug_id;
465 $li['hidden']['selector'] = $selector;
466 $li['hidden']['sale_id'] = $sale_id;
467 $li['hidden']['billed' ] = $billed;
468 $li['hidden']['price' ] = $li['price'];
470 // This logic is only used for family planning clinics, and then only when
471 // the option is chosen to use or auto-generate Contraception forms.
472 // It adds contraceptive method and effectiveness to relevant lines.
473 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
474 $this->checkRelatedForContraception($drow['related_code']);
475 if ($this->line_contra_code) {
476 $li['hidden']['method' ] = $this->line_contra_code;
477 $li['hidden']['methtype'] = $this->line_contra_methtype;
481 // For Family Planning.
482 ++$this->required_code_count;
483 if ($fee != 0) $this->hasCharges = true;
485 $this->productitems[] = $li;
488 // Generate rows for items already in the billing table for this encounter.
490 public function loadServiceItems() {
491 $billresult = getBillingByEncounter($this->pid, $this->encounter, "*");
492 if ($billresult) {
493 foreach ($billresult as $iter) {
494 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') continue;
495 $justify = trim($iter['justify']);
496 if ($justify) $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
497 $this->addServiceLineItem(array(
498 'id' => $iter['id'],
499 'codetype' => $iter['code_type'],
500 'code' => trim($iter['code']),
501 'modifier' => trim($iter["modifier"]),
502 'code_text' => trim($iter['code_text']),
503 'units' => $iter['units'],
504 'fee' => $iter['fee'],
505 'pricelevel' => $iter['pricelevel'],
506 'billed' => $iter['billed'],
507 'ndc_info' => $iter['ndc_info'],
508 'provider_id' => $iter['provider_id'],
509 'justify' => $justify,
510 'notecodes' => trim($iter['notecodes']),
514 // echo "<!-- \n"; // debugging
515 // print_r($this->serviceitems); // debugging
516 // echo "--> \n"; // debugging
519 // Generate rows for items already in the drug_sales table for this encounter.
521 public function loadProductItems() {
522 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
523 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
524 "ORDER BY ds.sale_id";
525 $sres = sqlStatement($query, array($this->pid, $this->encounter));
526 while ($srow = sqlFetchArray($sres)) {
527 $this->addProductLineItem(array(
528 'drug_id' => $srow['drug_id'],
529 'selector' => $srow['selector'],
530 'sale_id' => $srow['sale_id'],
531 'rx' => !empty($srow['prescription_id']),
532 'units' => $srow['quantity'],
533 'fee' => $srow['fee'],
534 'pricelevel' => $srow['pricelevel'],
535 'billed' => $srow['billed'],
536 'warehouse_id' => $srow['warehouse_id'],
541 // Check for insufficient product inventory levels.
542 // Returns an error message if any product items cannot be filled.
543 // You must call this before save().
545 public function checkInventory(&$prod) {
546 $alertmsg = '';
547 $insufficient = 0;
548 $expiredlots = false;
549 if (is_array($prod)) foreach ($prod as $iter) {
550 if (!empty($iter['billed'])) continue;
551 $drug_id = $iter['drug_id'];
552 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
553 $units = empty($iter['units']) ? 1 : intval($iter['units']);
554 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
556 // Deleting always works.
557 if (!empty($iter['del'])) continue;
559 // If the item is already in the database...
560 if ($sale_id) {
561 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
562 "FROM drug_sales AS ds " .
563 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
564 "WHERE ds.sale_id = ?";
565 $dirow = sqlQuery($query, array($sale_id));
566 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
567 if (!empty($dirow['inventory_id'])) {
568 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
569 // Changing warehouse so check inventory in the new warehouse.
570 // Nothing is updated by this call.
571 if (!sellDrug($drug_id, $units, 0, $this->pid, $this->encounter, 0,
572 $this->visit_date, '', $warehouse_id, true, $expiredlots)) {
573 $insufficient = $drug_id;
576 else {
577 if (($dirow['on_hand'] + $dirow['quantity'] - $units) < 0) {
578 $insufficient = $drug_id;
583 // Otherwise it's a new item...
584 else {
585 // This only checks for sufficient inventory, nothing is updated.
586 if (!sellDrug($drug_id, $units, 0, $this->pid, $this->encounter, 0,
587 $this->visit_date, '', $warehouse_id, true, $expiredlots)) {
588 $insufficient = $drug_id;
591 } // end for
592 if ($insufficient) {
593 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
594 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
595 if ($expiredlots) $alertmsg .= " " . xl('Check expiration dates.');
597 return $alertmsg;
600 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
601 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
603 public function save(&$bill, &$prod, $main_provid=NULL, $main_supid=NULL, $default_warehouse=NULL,
604 $mark_as_closed=false) {
605 global $code_types;
607 if (isset($main_provid) && $main_supid == $main_provid) $main_supid = 0;
609 $copay_update = FALSE;
610 $update_session_id = '';
611 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
612 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
613 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
615 if (is_array($bill)) foreach ($bill as $iter) {
616 // Skip disabled (billed) line items.
617 if (!empty($iter['billed'])) continue;
619 $id = $iter['id'];
620 $code_type = $iter['code_type'];
621 $code = $iter['code'];
622 $del = !empty($iter['del']);
623 $units = empty($iter['units']) ? 1 : intval($iter['units']);
624 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
625 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
626 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
627 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
628 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
629 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
631 $fee = sprintf('%01.2f', $price * $units);
633 if(!$cod0 && $code_types[$code_type]['fee'] == 1) {
634 $mod0 = $modifier;
635 $cod0 = $code;
636 $ct0 = $code_type;
639 if ($code_type == 'COPAY') {
640 if ($fee < 0) {
641 $fee = $fee * -1;
643 if (!$id) {
644 // adding new copay from fee sheet into ar_session and ar_activity tables
645 $session_id = idSqlStatement("INSERT INTO ar_session " .
646 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
647 "adjustment_code, post_to_date) " .
648 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
649 array($_SESSION['authId'], $fee, $this->pid));
650 sqlBeginTrans();
651 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
652 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
653 SqlStatement("INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
654 "payer_type, post_time, post_user, session_id, " .
655 "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
656 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
657 $_SESSION['authId'], $session_id, $fee));
658 sqlCommitTrans();
660 else {
661 // editing copay saved to ar_session and ar_activity
662 $session_id = $id;
663 $res_amount = sqlQuery("SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?",
664 array($this->pid, $this->encounter, $session_id));
665 if ($fee != $res_amount['pay_amount']) {
666 sqlStatement("UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?",
667 array($_SESSION['authId'], $fee, $session_id));
668 sqlStatement("UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now(),".
669 "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?",
670 array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id));
673 if (!$cod0){
674 $copay_update = TRUE;
675 $update_session_id = $session_id;
677 continue;
680 # Code to create justification for all codes based on first justification
681 if ($GLOBALS['replicate_justification'] == '1') {
682 if ($justify != '') {
683 $autojustify = $justify;
686 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
687 $justify = $autojustify;
690 if ($justify) $justify = str_replace(',', ':', $justify) . ':';
691 $auth = "1";
693 $ndc_info = '';
694 if (!empty($iter['ndcnum'])) {
695 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
696 trim($iter['ndcqty']);
699 // If the item is already in the database...
700 if ($id) {
701 if ($del) {
702 $this->logFSMessage(xl('Service deleted'));
703 deleteBilling($id);
705 else {
706 $tmp = sqlQuery("SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1",
707 array($id));
708 if (!empty($tmp)) {
709 $tmparr = array('code' => $code, 'authorized' => $auth);
710 if (isset($iter['units' ])) $tmparr['units' ] = $units;
711 if (isset($iter['price' ])) $tmparr['fee' ] = $fee;
712 if (isset($iter['pricelevel'])) $tmparr['pricelevel'] = $pricelevel;
713 if (isset($iter['mod' ])) $tmparr['modifier' ] = $modifier;
714 if (isset($iter['provid' ])) $tmparr['provider_id'] = $provid;
715 if (isset($iter['ndcnum' ])) $tmparr['ndc_info' ] = $ndc_info;
716 if (isset($iter['justify' ])) $tmparr['justify' ] = $justify;
717 if (isset($iter['notecodes'])) $tmparr['notecodes' ] = $notecodes;
718 foreach ($tmparr AS $key => $value) {
719 if ($tmp[$key] != $value) {
720 if ('fee' == $key) $this->logFSMessage(xl('Price changed'));
721 if ('units' == $key) $this->logFSMessage(xl('Quantity changed'));
722 if ('provider_id' == $key) $this->logFSMessage(xl('Service provider changed'));
723 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
729 // Otherwise it's a new item...
730 else if (!$del) {
731 $this->logFSMessage(xl('Service added'));
732 $code_text = lookup_code_descriptions($code_type.":".$code);
733 addBilling($this->encounter, $code_type, $code, $code_text, $this->pid, $auth,
734 $provid, $modifier, $units, $fee, $ndc_info, $justify, 0, $notecodes, $pricelevel);
736 } // end for
738 // if modifier is not inserted during loop update the record using the first
739 // non-empty modifier and code
740 if($copay_update == TRUE && $update_session_id != '' && $mod0 != '') {
741 sqlStatement("UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?".
742 " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
743 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id));
746 // Doing similarly to the above but for products.
747 if (is_array($prod)) foreach ($prod as $iter) {
748 // Skip disabled (billed) line items.
749 if (!empty($iter['billed'])) continue;
751 $drug_id = $iter['drug_id'];
752 $selector = empty($iter['selector']) ? '' : $iter['selector'];
753 $sale_id = $iter['sale_id']; // present only if already saved
754 $units = max(1, intval(trim($iter['units'])));
755 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
756 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
757 $fee = sprintf('%01.2f', $price * $units);
758 $del = !empty($iter['del']);
759 $rxid = 0;
760 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
761 $somechange = false;
763 // If the item is already in the database...
764 if ($sale_id) {
765 $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
766 "ds.sale_date, di.warehouse_id " .
767 "FROM drug_sales AS ds " .
768 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
769 "WHERE ds.sale_id = ?", array($sale_id));
770 $rxid = 0 + $tmprow['prescription_id'];
771 if ($del) {
772 if (!empty($tmprow)) {
773 // Delete this sale and reverse its inventory update.
774 $this->logFSMessage(xl('Product deleted'));
775 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
776 if (!empty($tmprow['inventory_id'])) {
777 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
778 array($tmprow['quantity'], $tmprow['inventory_id']));
781 if ($rxid) {
782 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
785 else {
786 // Modify the sale and adjust inventory accordingly.
787 if (!empty($tmprow)) {
788 foreach (array(
789 'quantity' => $units,
790 'fee' => $fee,
791 'pricelevel' => $pricelevel,
792 'selector' => $selector,
793 'sale_date' => $this->visit_date,
794 ) AS $key => $value) {
795 if ($tmprow[$key] != $value) {
796 $somechange = true;
797 if ('fee' == $key) $this->logFSMessage(xl('Price changed'));
798 if ('pricelevel' == $key) $this->logFSMessage(xl('Price level changed'));
799 if ('selector' == $key) $this->logFSMessage(xl('Template selector changed'));
800 if ('quantity' == $key) $this->logFSMessage(xl('Quantity changed'));
801 sqlStatement("UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
802 array($value, $sale_id));
803 if ($key == 'quantity' && $tmprow['inventory_id']) {
804 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
805 array($units - $tmprow['quantity'], $tmprow['inventory_id']));
809 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
810 // Changing warehouse. Requires deleting and re-adding the sale.
811 // Not setting $somechange because this alone does not affect a prescription.
812 $this->logFSMessage(xl('Warehouse changed'));
813 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
814 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
815 array($units, $tmprow['inventory_id']));
816 $tmpnull = null;
817 $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter,
818 (empty($iter['rx']) ? 0 : $rxid), $this->visit_date, '', $warehouse_id,
819 false, $tmpnull, $pricelevel, $selector);
822 // Delete Rx if $rxid and flag not set.
823 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
824 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
825 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
830 // Otherwise it's a new item...
831 else if (! $del) {
832 $somechange = true;
833 $this->logFSMessage(xl('Product added'));
834 $tmpnull = null;
835 $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter, 0,
836 $this->visit_date, '', $warehouse_id, false, $tmpnull, $pricelevel, $selector);
837 if (!$sale_id) die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
840 // If a prescription applies, create or update it.
841 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
842 // If an active rx already exists for this drug and date we will
843 // replace it, otherwise we'll make a new one.
844 if (empty($rxid)) $rxid = '';
845 // Get default drug attributes; prefer the template with the matching selector.
846 $drow = sqlQuery("SELECT dt.*, " .
847 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
848 "FROM drugs AS d, drug_templates AS dt WHERE " .
849 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
850 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
851 array($drug_id, $selector));
852 if (!empty($drow)) {
853 $rxobj = new Prescription($rxid);
854 $rxobj->set_patient_id($this->pid);
855 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
856 $rxobj->set_drug_id($drug_id);
857 $rxobj->set_quantity($units);
858 $rxobj->set_per_refill($units);
859 $rxobj->set_start_date_y(substr($this->visit_date,0,4));
860 $rxobj->set_start_date_m(substr($this->visit_date,5,2));
861 $rxobj->set_start_date_d(substr($this->visit_date,8,2));
862 $rxobj->set_date_added($this->visit_date);
863 // Remaining attributes are the drug and template defaults.
864 $rxobj->set_drug($drow['name']);
865 $rxobj->set_unit($drow['unit']);
866 $rxobj->set_dosage($drow['dosage']);
867 $rxobj->set_form($drow['form']);
868 $rxobj->set_refills($drow['refills']);
869 $rxobj->set_size($drow['size']);
870 $rxobj->set_route($drow['route']);
871 $rxobj->set_interval($drow['period']);
872 $rxobj->set_substitute($drow['substitute']);
874 $rxobj->persist();
875 // Set drug_sales.prescription_id to $rxobj->get_id().
876 $oldrxid = $rxid;
877 $rxid = 0 + $rxobj->get_id();
878 if ($rxid != $oldrxid) {
879 sqlStatement("UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
880 array($rxid, $sale_id));
884 } // end for
886 // Set default and/or supervising provider for the encounter.
887 if (isset($main_provid) && $main_provid != $this->provider_id) {
888 $this->logFSMessage(xl('Default provider changed'));
889 sqlStatement("UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
890 array($main_provid, $this->pid, $this->encounter));
891 $this->provider_id = $main_provid;
893 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
894 sqlStatement("UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
895 array($main_supid, $this->pid, $this->encounter));
896 $this->supervisor_id = $main_supid;
899 // Save-and-Close is currently specific to Family Planning but might be more
900 // generally useful. It provides the ability to mark an encounter as billed
901 // directly from the Fee Sheet, if there are no charges.
902 if ($mark_as_closed) {
903 $tmp1 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
904 "pid = ? AND encounter = ? AND billed = 0",
905 array($this->pid, $this->encounter));
906 $tmp2 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
907 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
908 array($this->pid, $this->encounter));
909 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
910 sqlStatement("update drug_sales SET billed = 1 WHERE " .
911 "pid = ? AND encounter = ? AND billed = 0",
912 array($this->pid, $this->encounter));
913 sqlStatement("UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
914 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
915 array($this->pid, $this->encounter));
917 else {
918 // Would be good to display an error message here... they clicked
919 // Save and Close but the close could not be done. However the
920 // framework does not provide an easy way to do that.
925 // Call this after save() for Family Planning implementations.
926 // It checks the contraception form, or makes a new one if $newmauser is set.
927 // Returns 0 unless user intervention is required to fix a missing or incorrect form,
928 // and in that case the return value is an existing form ID, or -1 if none.
930 // Returns FALSE if user intervention is required to fix a missing or incorrect form.
932 public function doContraceptionForm($ippfconmeth=NULL, $newmauser=NULL, $main_provid=0) {
933 if (!empty($ippfconmeth)) {
934 $csrow = sqlQuery("SELECT f.form_id, ld.field_value FROM forms AS f " .
935 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
936 "WHERE " .
937 "f.pid = ? AND f.encounter = ? AND " .
938 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
939 "ORDER BY f.form_id DESC LIMIT 1",
940 array($this->pid, $this->encounter));
941 if (isset($newmauser)) {
942 // pastmodern is 0 iff new to modern contraception
943 $pastmodern = $newmauser == '2' ? 0 : 1;
944 if ($newmauser == '2') $newmauser = '1';
945 // Add contraception form but only if it does not already exist
946 // (if it does, must be 2 users working on the visit concurrently).
947 if (empty($csrow)) {
948 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
949 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
950 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
951 // Do we care about a service-specific provider here?
952 $this->insert_lbf_item($newid, 'provider', $main_provid);
953 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
956 else if (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
957 // Contraceptive method does not match what is in an existing Contraception
958 // form for this visit, or there is no such form. User intervention is needed.
959 return empty($csrow) ? -1 : intval($csrow['form_id']);
962 return 0;
965 // Get price level from patient demographics.
967 public function getPriceLevel() {
968 return $this->patient_pricelevel;
971 // Update price level in patient demographics if it's changed.
973 public function updatePriceLevel($pricelevel) {
974 if (!empty($pricelevel)) {
975 if ($this->patient_pricelevel != $pricelevel) {
976 $this->logFSMessage(xl('Price level changed'));
977 sqlStatement("UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
978 array($pricelevel, $this->pid));
979 $this->patient_pricelevel = $pricelevel;
984 // Create JSON string representing code type, code and selector.
985 // This can be a checkbox value for parsing when the checkbox is clicked.
986 // As a side effect note if the code is already selected in the Fee Sheet.
988 public function genCodeSelectorValue($codes) {
989 global $code_types;
990 list($codetype, $code, $selector) = explode(':', $codes);
991 if ($codetype == 'PROD') {
992 $crow = sqlQuery("SELECT sale_id " .
993 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
994 "LIMIT 1",
995 array($this->pid, $this->encounter, $code));
996 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
997 $cbarray = array($codetype, $code, $selector);
999 else {
1000 $crow = sqlQuery("SELECT c.id AS code_id, b.id " .
1001 "FROM codes AS c " .
1002 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1003 "WHERE c.code_type = ? AND c.code = ? LIMIT 1",
1004 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code));
1005 $this->code_is_in_fee_sheet = !empty($crow['id']);
1006 $cbarray = array($codetype, $code);
1008 $cbval = json_encode($cbarray);
1009 return $cbval;