fix for attendance form
[openemr.git] / library / FeeSheet.class.php
blob4532126b1af943a222222fdbacb7068440578731
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
26 $fake_register_globals = false;
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 {
47 public $pid; // patient id
48 public $encounter; // encounter id
49 public $got_warehouses = false; // if there is more than 1 warehouse
50 public $default_warehouse = ''; // logged-in user's default warehouse
51 public $visit_date = ''; // YYYY-MM-DD date of this visit
52 public $match_services_to_products = false; // For IPPF
53 public $patient_age = 0; // Age in years as of the visit date
54 public $patient_male = 0; // 1 if male
55 public $patient_pricelevel = ''; // From patient_data.pricelevel
56 public $provider_id = 0;
57 public $supervisor_id = 0;
58 public $code_is_in_fee_sheet = false; // Set by genCodeSelectorValue()
60 // Possible units of measure for NDC drug quantities.
61 public $ndc_uom_choices = array(
62 'ML' => 'ML',
63 'GR' => 'Grams',
64 'ME' => 'Milligrams',
65 'F2' => 'I.U.',
66 'UN' => 'Units'
69 // Set by checkRelatedForContraception():
70 public $line_contra_code = '';
71 public $line_contra_cyp = 0;
72 public $line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
74 // Array of line items generated by addServiceLineItem().
75 // Each element is an array of line item attributes.
76 public $serviceitems = array();
78 // Array of line items generated by addProductLineItem().
79 // Each element is an array of line item attributes.
80 public $productitems = array();
82 // Indicates if any line item has a fee.
83 public $hasCharges = false;
85 // Indicates if any clinical services or products are in the fee sheet.
86 public $required_code_count = 0;
88 // These variables are used to compute the initial consult service with highest CYP (IPPF).
89 public $contraception_code = '';
90 public $contraception_cyp = 0;
92 public $ALLOW_COPAYS = false;
94 function __construct($pid=0, $encounter=0) {
95 if (empty($pid)) $pid = $GLOBALS['pid'];
96 if (empty($encounter)) $encounter = $GLOBALS['encounter'];
97 $this->pid = $pid;
98 $this->encounter = $encounter;
100 // IPPF doesn't want any payments to be made or displayed in the Fee Sheet.
101 $this->ALLOW_COPAYS = !$GLOBALS['ippf_specific'];
103 // Get the user's default warehouse and an indicator if there's a choice of warehouses.
104 $wrow = sqlQuery("SELECT count(*) AS count FROM list_options WHERE list_id = 'warehouse' AND activity = 1");
105 $this->got_warehouses = $wrow['count'] > 1;
106 $wrow = sqlQuery("SELECT default_warehouse FROM users WHERE username = ?",
107 array($_SESSION['authUser']));
108 $this->default_warehouse = empty($wrow['default_warehouse']) ? '' : $wrow['default_warehouse'];
110 // Get some info about this visit.
111 $visit_row = sqlQuery("SELECT fe.date, fe.provider_id, fe.supervisor_id, " .
112 "opc.pc_catname, fac.extra_validation " .
113 "FROM form_encounter AS fe " .
114 "LEFT JOIN openemr_postcalendar_categories AS opc ON opc.pc_catid = fe.pc_catid " .
115 "LEFT JOIN facility AS fac ON fac.id = fe.facility_id " .
116 "WHERE fe.pid = ? AND fe.encounter = ? LIMIT 1", array($this->pid, $this->encounter) );
117 $this->visit_date = substr($visit_row['date'], 0, 10);
118 $this->provider_id = $visit_row['provider_id'];
119 if (empty($this->provider_id)) $this->provider_id = $this->findProvider();
120 $this->supervisor_id = $visit_row['supervisor_id'];
121 // This flag is specific to IPPF validation at form submit time. It indicates
122 // that most contraceptive services and products should match up on the fee sheet.
123 $this->match_services_to_products = $GLOBALS['ippf_specific'] &&
124 !empty($visit_row['extra_validation']);
126 // Get some information about the patient.
127 $patientrow = getPatientData($this->pid, "DOB, sex, pricelevel");
128 $this->patient_age = $this->getAge($patientrow['DOB'], $this->visit_date);
129 $this->patient_male = strtoupper(substr($patientrow['sex'], 0, 1)) == 'M' ? 1 : 0;
130 $this->patient_pricelevel = $patientrow['pricelevel'];
133 // Convert numeric code type to the alpha version.
135 public static function alphaCodeType($id) {
136 global $code_types;
137 foreach ($code_types as $key => $value) {
138 if ($value['id'] == $id) return $key;
140 return '';
143 // Compute age in years given a DOB and "as of" date.
145 public static function getAge($dob, $asof='') {
146 if (empty($asof)) $asof = date('Y-m-d');
147 $a1 = explode('-', substr($dob , 0, 10));
148 $a2 = explode('-', substr($asof, 0, 10));
149 $age = $a2[0] - $a1[0];
150 if ($a2[1] < $a1[1] || ($a2[1] == $a1[1] && $a2[2] < $a1[2])) --$age;
151 return $age;
154 // Gets the provider from the encounter, logged-in user or patient demographics.
155 // Adapted from work by Terry Hill.
157 public function findProvider() {
158 $find_provider = sqlQuery("SELECT provider_id FROM form_encounter " .
159 "WHERE pid = ? AND encounter = ? ORDER BY id DESC LIMIT 1",
160 array($this->pid, $this->encounter));
161 $providerid = $find_provider['provider_id'];
162 if (!$providerid) {
163 $get_authorized = $_SESSION['userauthorized'];
164 if ($get_authorized == 1) {
165 $providerid = $_SESSION['authUserID'];
168 if (!$providerid) {
169 $find_provider = sqlQuery("SELECT providerID FROM patient_data " .
170 "WHERE pid = ?", array($this->pid) );
171 $providerid = $find_provider['providerID'];
173 return intval($providerid);
176 // Log a message that is easy for the Re-Opened Visits Report to interpret.
178 public function logFSMessage($action) {
179 newEvent('fee-sheet', $_SESSION['authUser'], $_SESSION['authProvider'], 1,
180 $action, $this->pid, $this->encounter);
183 // Compute a current checksum of this encounter's Fee Sheet data from the database.
185 public function visitChecksum($saved=false) {
186 $rowb = sqlQuery("SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
187 "id, code, modifier, units, fee, authorized, provider_id, ndc_info, justify, billed" .
188 "))) AS checksum FROM billing WHERE " .
189 "pid = ? AND encounter = ? AND activity = 1",
190 array($this->pid, $this->encounter));
191 $rowp = sqlQuery("SELECT BIT_XOR(CRC32(CONCAT_WS(',', " .
192 "sale_id, inventory_id, prescription_id, quantity, fee, sale_date, billed" .
193 "))) AS checksum FROM drug_sales WHERE " .
194 "pid = ? AND encounter = ?",
195 array($this->pid, $this->encounter));
196 $ret = intval($rowb['checksum']) ^ intval($rowp['checksum']);
197 if (CHECKSUM_LOGGING) {
198 $comment = "Checksum = '$ret'";
199 $comment .= ", Saved = " . ($saved ? "true" : "false");
200 newEvent("checksum", $_SESSION['authUser'], $_SESSION['authProvider'], 1, $comment, $this->pid);
202 return $ret;
205 // IPPF-specific; get contraception attributes of the related codes.
207 public function checkRelatedForContraception($related_code, $is_initial_consult=false) {
208 $this->line_contra_code = '';
209 $this->line_contra_cyp = 0;
210 $this->line_contra_methtype = 0; // 0 = None, 1 = Not initial, 2 = Initial consult
211 if (!empty($related_code)) {
212 $relcodes = explode(';', $related_code);
213 foreach ($relcodes as $relstring) {
214 if ($relstring === '') continue;
215 list($reltype, $relcode) = explode(':', $relstring);
216 if ($reltype !== 'IPPFCM') continue;
217 $methtype = $is_initial_consult ? 2 : 1;
218 $tmprow = sqlQuery("SELECT cyp_factor FROM codes WHERE " .
219 "code_type = '32' AND code = ? LIMIT 1", array($relcode));
220 $cyp = 0 + $tmprow['cyp_factor'];
221 if ($cyp > $this->line_contra_cyp) {
222 $this->line_contra_cyp = $cyp;
223 // Note this is an IPPFCM code, not an IPPF2 code.
224 $this->line_contra_code = $relcode;
225 $this->line_contra_methtype = $methtype;
231 // Insert a row into the lbf_data table. Returns a new form ID if that is not provided.
232 // This is only needed for auto-creating Contraception forms.
234 public function insert_lbf_item($form_id, $field_id, $field_value) {
235 if ($form_id) {
236 sqlInsert("INSERT INTO lbf_data (form_id, field_id, field_value) " .
237 "VALUES (?, ?, ?)", array($form_id, $field_id, $field_value));
239 else {
240 $form_id = sqlInsert("INSERT INTO lbf_data (field_id, field_value) " .
241 "VALUES (?, ?)", array($field_id, $field_value));
243 return $form_id;
246 // Create an array of data for a particular billing table item that is useful
247 // for building a user interface form row. $args is an array containing:
248 // codetype
249 // code
250 // modifier
251 // ndc_info
252 // auth
253 // del
254 // units
255 // fee
256 // id
257 // billed
258 // code_text
259 // justify
260 // provider_id
261 // notecodes
262 // pricelevel
263 public function addServiceLineItem($args) {
264 global $code_types;
266 // echo "<!-- \n"; // debugging
267 // print_r($args); // debugging
268 // echo "--> \n"; // debugging
270 $li = array();
271 $li['hidden'] = array();
273 $codetype = $args['codetype'];
274 $code = $args['code'];
275 $modifier = isset($args['modifier']) ? $args['modifier'] : '';
276 $code_text = isset($args['code_text']) ? $args['code_text'] : '';
277 $units = isset($args['units']) ? $args['units'] : 0;
278 $units = max(1, intval($units));
279 $billed = !empty($args['billed']);
280 $auth = !empty($args['auth']);
281 $id = isset($args['id']) ? intval($args['id']) : 0;
282 $ndc_info = isset($args['ndc_info']) ? $args['ndc_info'] : '';
283 $provider_id = isset($args['provider_id']) ? intval($args['provider_id']) : 0;
284 $justify = isset($args['justify']) ? $args['justify'] : '';
285 $notecodes = isset($args['notecodes']) ? $args['notecodes'] : '';
286 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
287 // Price level should be unset only if adding a new line item.
288 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
289 $del = !empty($args['del']);
291 // If using line item billing and user wishes to default to a selected provider, then do so.
292 if(!empty($GLOBALS['default_fee_sheet_line_item_provider']) && !empty($GLOBALS['support_fee_sheet_line_item_provider'])) {
293 if ($provider_id == 0) {
294 $provider_id = 0 + $this->findProvider();
298 if ($codetype == 'COPAY') {
299 if (!$code_text) $code_text = 'Cash';
300 if ($fee > 0) $fee = 0 - $fee;
303 // Get the matching entry from the codes table.
304 $sqlArray = array();
305 $query = "SELECT id, units, code_text FROM codes WHERE " .
306 "code_type = ? AND code = ?";
307 array_push($sqlArray, $code_types[$codetype]['id'], $code);
308 if ($modifier) {
309 $query .= " AND modifier = ?";
310 array_push($sqlArray, $modifier);
312 else {
313 $query .= " AND (modifier IS NULL OR modifier = '')";
315 $result = sqlQuery($query, $sqlArray);
316 $codes_id = $result['id'];
318 if (!$code_text) {
319 $code_text = $result['code_text'];
320 if (empty($units)) $units = max(1, intval($result['units']));
321 if (!isset($args['fee'])) {
322 // Fees come from the prices table now.
323 $query = "SELECT pr_price FROM prices WHERE " .
324 "pr_id = ? AND pr_selector = '' AND pr_level = ? " .
325 "LIMIT 1";
326 // echo "\n<!-- $query -->\n"; // debugging
327 $prrow = sqlQuery($query, array($codes_id, $pricelevel));
328 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
331 $fee = sprintf('%01.2f', $fee);
333 $li['hidden']['code_type'] = $codetype;
334 $li['hidden']['code' ] = $code;
335 $li['hidden']['mod' ] = $modifier;
336 $li['hidden']['billed' ] = $billed;
337 $li['hidden']['id' ] = $id;
338 $li['hidden']['codes_id' ] = $codes_id;
340 // This logic is only used for family planning clinics, and then only when
341 // the option is chosen to use or auto-generate Contraception forms.
342 // It adds contraceptive method and effectiveness to relevant lines.
343 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy'] && $codetype == 'MA') {
344 $codesrow = sqlQuery("SELECT related_code, cyp_factor FROM codes WHERE " .
345 "code_type = ? AND code = ? LIMIT 1",
346 array($code_types[$codetype]['id'], $code));
347 $this->checkRelatedForContraception($codesrow['related_code'], $codesrow['cyp_factor']);
348 if ($this->line_contra_code) {
349 $li['hidden']['method' ] = $this->line_contra_code;
350 $li['hidden']['cyp' ] = $this->line_contra_cyp;
351 $li['hidden']['methtype'] = $this->line_contra_methtype;
352 // contraception_code is only concerned with initial consults.
353 if ($this->line_contra_cyp > $this->contraception_cyp && $this->line_contra_methtype == 2) {
354 $this->contraception_cyp = $this->line_contra_cyp;
355 $this->contraception_code = $this->line_contra_code;
360 if($codetype == 'COPAY') {
361 $li['codetype'] = xl($codetype);
362 if ($ndc_info) $li['codetype'] .= " ($ndc_info)";
363 $ndc_info = '';
365 else {
366 $li['codetype'] = $codetype;
369 $li['code' ] = $codetype == 'COPAY' ? '' : $code;
370 $li['mod' ] = $modifier;
371 $li['fee' ] = $fee;
372 $li['price' ] = $fee / $units;
373 $li['pricelevel'] = $pricelevel;
374 $li['units' ] = $units;
375 $li['provid' ] = $provider_id;
376 $li['justify' ] = $justify;
377 $li['notecodes'] = $notecodes;
378 $li['del' ] = $id && $del;
379 $li['code_text'] = $code_text;
380 $li['auth' ] = $auth;
382 $li['hidden']['price'] = $li['price'];
384 // If NDC info exists or may be required, add stuff for it.
385 if ($codetype == 'HCPCS' && !$billed) {
386 $ndcnum = ''; $ndcuom = ''; $ndcqty = '';
387 if (preg_match('/^N4(\S+)\s+(\S\S)(.*)/', $ndc_info, $tmp)) {
388 $ndcnum = $tmp[1]; $ndcuom = $tmp[2]; $ndcqty = $tmp[3];
390 $li['ndcnum' ] = $ndcnum;
391 $li['ndcuom' ] = $ndcuom;
392 $li['ndcqty' ] = $ndcqty;
394 else if ($ndc_info) {
395 $li['ndc_info' ] = $ndc_info;
398 // For Family Planning.
399 if ($codetype == 'MA') ++$this->required_code_count;
400 if ($fee != 0) $this->hasCharges = true;
402 $this->serviceitems[] = $li;
405 // Create an array of data for a particular drug_sales table item that is useful
406 // for building a user interface form row. $args is an array containing:
407 // drug_id
408 // selector
409 // sale_id
410 // rx (boolean)
411 // del (boolean)
412 // units
413 // fee
414 // billed
415 // warehouse_id
416 // pricelevel
418 public function addProductLineItem($args) {
419 global $code_types;
421 $li = array();
422 $li['hidden'] = array();
424 $drug_id = $args['drug_id'];
425 $selector = isset($args['selector']) ? $args['selector'] : '';
426 $sale_id = isset($args['sale_id']) ? intval($args['sale_id']) : 0;
427 $units = isset($args['units']) ? $args['units'] : 0;
428 $units = max(1, intval($units));
429 $billed = !empty($args['billed']);
430 $rx = !empty($args['rx']);
431 $del = !empty($args['del']);
432 $fee = isset($args['fee']) ? (0 + $args['fee']) : 0;
433 $pricelevel = isset($args['pricelevel']) ? $args['pricelevel'] : $this->patient_pricelevel;
434 $warehouse_id = isset($args['warehouse_id']) ? $args['warehouse_id'] : '';
436 $drow = sqlQuery("SELECT name, related_code FROM drugs WHERE drug_id = ?", array($drug_id) );
437 $code_text = $drow['name'];
439 // If no warehouse ID passed, use the logged-in user's default.
440 if ($this->got_warehouses && $warehouse_id === '') $warehouse_id = $this->default_warehouse;
442 // If fee is not provided, get it from the prices table.
443 // It is assumed in this case that units will match what is in the product template.
444 if (!isset($args['fee'])) {
445 $query = "SELECT pr_price FROM prices WHERE " .
446 "pr_id = ? AND pr_selector = ? AND pr_level = ? " .
447 "LIMIT 1";
448 $prrow = sqlQuery($query, array($drug_id, $selector, $pricelevel));
449 $fee = empty($prrow) ? 0 : $prrow['pr_price'];
452 $fee = sprintf('%01.2f', $fee);
454 $li['fee' ] = $fee;
455 $li['price' ] = $fee / $units;
456 $li['pricelevel'] = $pricelevel;
457 $li['units' ] = $units;
458 $li['del' ] = $sale_id && $del;
459 $li['code_text'] = $code_text;
460 $li['warehouse'] = $warehouse_id;
461 $li['rx' ] = $rx;
463 $li['hidden']['drug_id'] = $drug_id;
464 $li['hidden']['selector'] = $selector;
465 $li['hidden']['sale_id'] = $sale_id;
466 $li['hidden']['billed' ] = $billed;
467 $li['hidden']['price' ] = $li['price'];
469 // This logic is only used for family planning clinics, and then only when
470 // the option is chosen to use or auto-generate Contraception forms.
471 // It adds contraceptive method and effectiveness to relevant lines.
472 if ($GLOBALS['ippf_specific'] && $GLOBALS['gbl_new_acceptor_policy']) {
473 $this->checkRelatedForContraception($drow['related_code']);
474 if ($this->line_contra_code) {
475 $li['hidden']['method' ] = $this->line_contra_code;
476 $li['hidden']['methtype'] = $this->line_contra_methtype;
480 // For Family Planning.
481 ++$this->required_code_count;
482 if ($fee != 0) $this->hasCharges = true;
484 $this->productitems[] = $li;
487 // Generate rows for items already in the billing table for this encounter.
489 public function loadServiceItems() {
490 $billresult = getBillingByEncounter($this->pid, $this->encounter, "*");
491 if ($billresult) {
492 foreach ($billresult as $iter) {
493 if (!$this->ALLOW_COPAYS && $iter["code_type"] == 'COPAY') continue;
494 $justify = trim($iter['justify']);
495 if ($justify) $justify = substr(str_replace(':', ',', $justify), 0, strlen($justify) - 1);
496 $this->addServiceLineItem(array(
497 'id' => $iter['id'],
498 'codetype' => $iter['code_type'],
499 'code' => trim($iter['code']),
500 'modifier' => trim($iter["modifier"]),
501 'code_text' => trim($iter['code_text']),
502 'units' => $iter['units'],
503 'fee' => $iter['fee'],
504 'pricelevel' => $iter['pricelevel'],
505 'billed' => $iter['billed'],
506 'ndc_info' => $iter['ndc_info'],
507 'provider_id' => $iter['provider_id'],
508 'justify' => $justify,
509 'notecodes' => trim($iter['notecodes']),
513 // echo "<!-- \n"; // debugging
514 // print_r($this->serviceitems); // debugging
515 // echo "--> \n"; // debugging
518 // Generate rows for items already in the drug_sales table for this encounter.
520 public function loadProductItems() {
521 $query = "SELECT ds.*, di.warehouse_id FROM drug_sales AS ds, drug_inventory AS di WHERE " .
522 "ds.pid = ? AND ds.encounter = ? AND di.inventory_id = ds.inventory_id " .
523 "ORDER BY ds.sale_id";
524 $sres = sqlStatement($query, array($this->pid, $this->encounter));
525 while ($srow = sqlFetchArray($sres)) {
526 $this->addProductLineItem(array(
527 'drug_id' => $srow['drug_id'],
528 'selector' => $srow['selector'],
529 'sale_id' => $srow['sale_id'],
530 'rx' => !empty($srow['prescription_id']),
531 'units' => $srow['quantity'],
532 'fee' => $srow['fee'],
533 'pricelevel' => $srow['pricelevel'],
534 'billed' => $srow['billed'],
535 'warehouse_id' => $srow['warehouse_id'],
540 // Check for insufficient product inventory levels.
541 // Returns an error message if any product items cannot be filled.
542 // You must call this before save().
544 public function checkInventory(&$prod) {
545 $alertmsg = '';
546 $insufficient = 0;
547 $expiredlots = false;
548 if (is_array($prod)) foreach ($prod as $iter) {
549 if (!empty($iter['billed'])) continue;
550 $drug_id = $iter['drug_id'];
551 $sale_id = empty($iter['sale_id']) ? 0 : intval($iter['sale_id']); // present only if already saved
552 $units = empty($iter['units']) ? 1 : intval($iter['units']);
553 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
555 // Deleting always works.
556 if (!empty($iter['del'])) continue;
558 // If the item is already in the database...
559 if ($sale_id) {
560 $query = "SELECT ds.quantity, ds.inventory_id, di.on_hand, di.warehouse_id " .
561 "FROM drug_sales AS ds " .
562 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
563 "WHERE ds.sale_id = ?";
564 $dirow = sqlQuery($query, array($sale_id));
565 // There's no inventory ID when this is a non-dispensible product (i.e. no inventory).
566 if (!empty($dirow['inventory_id'])) {
567 if ($warehouse_id && $warehouse_id != $dirow['warehouse_id']) {
568 // Changing warehouse so check inventory in the new warehouse.
569 // Nothing is updated by this call.
570 if (!sellDrug($drug_id, $units, 0, $this->pid, $this->encounter, 0,
571 $this->visit_date, '', $warehouse_id, true, $expiredlots)) {
572 $insufficient = $drug_id;
575 else {
576 if (($dirow['on_hand'] + $dirow['quantity'] - $units) < 0) {
577 $insufficient = $drug_id;
582 // Otherwise it's a new item...
583 else {
584 // This only checks for sufficient inventory, nothing is updated.
585 if (!sellDrug($drug_id, $units, 0, $this->pid, $this->encounter, 0,
586 $this->visit_date, '', $warehouse_id, true, $expiredlots)) {
587 $insufficient = $drug_id;
590 } // end for
591 if ($insufficient) {
592 $drow = sqlQuery("SELECT name FROM drugs WHERE drug_id = ?", array($insufficient));
593 $alertmsg = xl('Insufficient inventory for product') . ' "' . $drow['name'] . '".';
594 if ($expiredlots) $alertmsg .= " " . xl('Check expiration dates.');
596 return $alertmsg;
599 // Save posted data to the database. $bill and $prod are the incoming arrays of line items, with
600 // key names corresponding to those generated by addServiceLineItem() and addProductLineItem().
602 public function save(&$bill, &$prod, $main_provid=NULL, $main_supid=NULL, $default_warehouse=NULL,
603 $mark_as_closed=false) {
604 global $code_types;
606 if (isset($main_provid) && $main_supid == $main_provid) $main_supid = 0;
608 $copay_update = FALSE;
609 $update_session_id = '';
610 $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted
611 $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted
612 $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted
614 if (is_array($bill)) foreach ($bill as $iter) {
615 // Skip disabled (billed) line items.
616 if (!empty($iter['billed'])) continue;
618 $id = $iter['id'];
619 $code_type = $iter['code_type'];
620 $code = $iter['code'];
621 $del = !empty($iter['del']);
622 $units = empty($iter['units']) ? 1 : intval($iter['units']);
623 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
624 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
625 $modifier = empty($iter['mod']) ? '' : trim($iter['mod']);
626 $justify = empty($iter['justify' ]) ? '' : trim($iter['justify']);
627 $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']);
628 $provid = empty($iter['provid' ]) ? 0 : intval($iter['provid']);
630 $fee = sprintf('%01.2f', $price * $units);
632 if(!$cod0 && $code_types[$code_type]['fee'] == 1) {
633 $mod0 = $modifier;
634 $cod0 = $code;
635 $ct0 = $code_type;
638 if ($code_type == 'COPAY') {
639 if ($fee < 0) {
640 $fee = $fee * -1;
642 if (!$id) {
643 // adding new copay from fee sheet into ar_session and ar_activity tables
644 $session_id = idSqlStatement("INSERT INTO ar_session " .
645 "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " .
646 "adjustment_code, post_to_date) " .
647 "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())",
648 array($_SESSION['authId'], $fee, $this->pid));
649 sqlBeginTrans();
650 $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " .
651 "pid = ? AND encounter = ?", array($this->pid, $this->encounter));
652 SqlStatement("INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " .
653 "payer_type, post_time, post_user, session_id, " .
654 "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')",
655 array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0,
656 $_SESSION['authId'], $session_id, $fee));
657 sqlCommitTrans();
659 else {
660 // editing copay saved to ar_session and ar_activity
661 $session_id = $id;
662 $res_amount = sqlQuery("SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?",
663 array($this->pid, $this->encounter, $session_id));
664 if ($fee != $res_amount['pay_amount']) {
665 sqlStatement("UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?",
666 array($_SESSION['authId'], $fee, $session_id));
667 sqlStatement("UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now(),".
668 "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?",
669 array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id));
672 if (!$cod0){
673 $copay_update = TRUE;
674 $update_session_id = $session_id;
676 continue;
679 # Code to create justification for all codes based on first justification
680 if ($GLOBALS['replicate_justification'] == '1') {
681 if ($justify != '') {
682 $autojustify = $justify;
685 if (($GLOBALS['replicate_justification'] == '1') && ($justify == '') && check_is_code_type_justify($code_type)) {
686 $justify = $autojustify;
689 if ($justify) $justify = str_replace(',', ':', $justify) . ':';
690 $auth = "1";
692 $ndc_info = '';
693 if (!empty($iter['ndcnum'])) {
694 $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] .
695 trim($iter['ndcqty']);
698 // If the item is already in the database...
699 if ($id) {
700 if ($del) {
701 $this->logFSMessage(xl('Service deleted'));
702 deleteBilling($id);
704 else {
705 $tmp = sqlQuery("SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1",
706 array($id));
707 if (!empty($tmp)) {
708 $tmparr = array('code' => $code, 'authorized' => $auth);
709 if (isset($iter['units' ])) $tmparr['units' ] = $units;
710 if (isset($iter['price' ])) $tmparr['fee' ] = $fee;
711 if (isset($iter['pricelevel'])) $tmparr['pricelevel'] = $pricelevel;
712 if (isset($iter['mod' ])) $tmparr['modifier' ] = $modifier;
713 if (isset($iter['provid' ])) $tmparr['provider_id'] = $provid;
714 if (isset($iter['ndcnum' ])) $tmparr['ndc_info' ] = $ndc_info;
715 if (isset($iter['justify' ])) $tmparr['justify' ] = $justify;
716 if (isset($iter['notecodes'])) $tmparr['notecodes' ] = $notecodes;
717 foreach ($tmparr AS $key => $value) {
718 if ($tmp[$key] != $value) {
719 if ('fee' == $key) $this->logFSMessage(xl('Price changed'));
720 if ('units' == $key) $this->logFSMessage(xl('Quantity changed'));
721 if ('provider_id' == $key) $this->logFSMessage(xl('Service provider changed'));
722 sqlStatement("UPDATE billing SET `$key` = ? WHERE id = ?", array($value, $id));
728 // Otherwise it's a new item...
729 else if (!$del) {
730 $this->logFSMessage(xl('Service added'));
731 $code_text = lookup_code_descriptions($code_type.":".$code);
732 addBilling($this->encounter, $code_type, $code, $code_text, $this->pid, $auth,
733 $provid, $modifier, $units, $fee, $ndc_info, $justify, 0, $notecodes, $pricelevel);
735 } // end for
737 // if modifier is not inserted during loop update the record using the first
738 // non-empty modifier and code
739 if($copay_update == TRUE && $update_session_id != '' && $mod0 != '') {
740 sqlStatement("UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?".
741 " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?",
742 array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id));
745 // Doing similarly to the above but for products.
746 if (is_array($prod)) foreach ($prod as $iter) {
747 // Skip disabled (billed) line items.
748 if (!empty($iter['billed'])) continue;
750 $drug_id = $iter['drug_id'];
751 $selector = empty($iter['selector']) ? '' : $iter['selector'];
752 $sale_id = $iter['sale_id']; // present only if already saved
753 $units = max(1, intval(trim($iter['units'])));
754 $price = empty($iter['price']) ? 0 : (0 + trim($iter['price']));
755 $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel'];
756 $fee = sprintf('%01.2f', $price * $units);
757 $del = !empty($iter['del']);
758 $rxid = 0;
759 $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse'];
760 $somechange = false;
762 // If the item is already in the database...
763 if ($sale_id) {
764 $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " .
765 "ds.sale_date, di.warehouse_id " .
766 "FROM drug_sales AS ds " .
767 "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " .
768 "WHERE ds.sale_id = ?", array($sale_id));
769 $rxid = 0 + $tmprow['prescription_id'];
770 if ($del) {
771 if (!empty($tmprow)) {
772 // Delete this sale and reverse its inventory update.
773 $this->logFSMessage(xl('Product deleted'));
774 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
775 if (!empty($tmprow['inventory_id'])) {
776 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
777 array($tmprow['quantity'], $tmprow['inventory_id']));
780 if ($rxid) {
781 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
784 else {
785 // Modify the sale and adjust inventory accordingly.
786 if (!empty($tmprow)) {
787 foreach (array(
788 'quantity' => $units,
789 'fee' => $fee,
790 'pricelevel' => $pricelevel,
791 'selector' => $selector,
792 'sale_date' => $this->visit_date,
793 ) AS $key => $value) {
794 if ($tmprow[$key] != $value) {
795 $somechange = true;
796 if ('fee' == $key) $this->logFSMessage(xl('Price changed'));
797 if ('pricelevel' == $key) $this->logFSMessage(xl('Price level changed'));
798 if ('selector' == $key) $this->logFSMessage(xl('Template selector changed'));
799 if ('quantity' == $key) $this->logFSMessage(xl('Quantity changed'));
800 sqlStatement("UPDATE drug_sales SET `$key` = ? WHERE sale_id = ?",
801 array($value, $sale_id));
802 if ($key == 'quantity' && $tmprow['inventory_id']) {
803 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?",
804 array($units - $tmprow['quantity'], $tmprow['inventory_id']));
808 if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) {
809 // Changing warehouse. Requires deleting and re-adding the sale.
810 // Not setting $somechange because this alone does not affect a prescription.
811 $this->logFSMessage(xl('Warehouse changed'));
812 sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id));
813 sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?",
814 array($units, $tmprow['inventory_id']));
815 $tmpnull = null;
816 $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter,
817 (empty($iter['rx']) ? 0 : $rxid), $this->visit_date, '', $warehouse_id,
818 false, $tmpnull, $pricelevel, $selector);
821 // Delete Rx if $rxid and flag not set.
822 if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) {
823 sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id));
824 sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid));
829 // Otherwise it's a new item...
830 else if (! $del) {
831 $somechange = true;
832 $this->logFSMessage(xl('Product added'));
833 $tmpnull = null;
834 $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter, 0,
835 $this->visit_date, '', $warehouse_id, false, $tmpnull, $pricelevel, $selector);
836 if (!$sale_id) die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\".");
839 // If a prescription applies, create or update it.
840 if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) {
841 // If an active rx already exists for this drug and date we will
842 // replace it, otherwise we'll make a new one.
843 if (empty($rxid)) $rxid = '';
844 // Get default drug attributes; prefer the template with the matching selector.
845 $drow = sqlQuery("SELECT dt.*, " .
846 "d.name, d.form, d.size, d.unit, d.route, d.substitute " .
847 "FROM drugs AS d, drug_templates AS dt WHERE " .
848 "d.drug_id = ? AND dt.drug_id = d.drug_id " .
849 "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1",
850 array($drug_id, $selector));
851 if (!empty($drow)) {
852 $rxobj = new Prescription($rxid);
853 $rxobj->set_patient_id($this->pid);
854 $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id);
855 $rxobj->set_drug_id($drug_id);
856 $rxobj->set_quantity($units);
857 $rxobj->set_per_refill($units);
858 $rxobj->set_start_date_y(substr($this->visit_date,0,4));
859 $rxobj->set_start_date_m(substr($this->visit_date,5,2));
860 $rxobj->set_start_date_d(substr($this->visit_date,8,2));
861 $rxobj->set_date_added($this->visit_date);
862 // Remaining attributes are the drug and template defaults.
863 $rxobj->set_drug($drow['name']);
864 $rxobj->set_unit($drow['unit']);
865 $rxobj->set_dosage($drow['dosage']);
866 $rxobj->set_form($drow['form']);
867 $rxobj->set_refills($drow['refills']);
868 $rxobj->set_size($drow['size']);
869 $rxobj->set_route($drow['route']);
870 $rxobj->set_interval($drow['period']);
871 $rxobj->set_substitute($drow['substitute']);
873 $rxobj->persist();
874 // Set drug_sales.prescription_id to $rxobj->get_id().
875 $oldrxid = $rxid;
876 $rxid = 0 + $rxobj->get_id();
877 if ($rxid != $oldrxid) {
878 sqlStatement("UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?",
879 array($rxid, $sale_id));
883 } // end for
885 // Set default and/or supervising provider for the encounter.
886 if (isset($main_provid) && $main_provid != $this->provider_id) {
887 $this->logFSMessage(xl('Default provider changed'));
888 sqlStatement("UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?",
889 array($main_provid, $this->pid, $this->encounter));
890 $this->provider_id = $main_provid;
892 if (isset($main_supid) && $main_supid != $this->supervisor_id) {
893 sqlStatement("UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?",
894 array($main_supid, $this->pid, $this->encounter));
895 $this->supervisor_id = $main_supid;
898 // Save-and-Close is currently specific to Family Planning but might be more
899 // generally useful. It provides the ability to mark an encounter as billed
900 // directly from the Fee Sheet, if there are no charges.
901 if ($mark_as_closed) {
902 $tmp1 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " .
903 "pid = ? AND encounter = ? AND billed = 0",
904 array($this->pid, $this->encounter));
905 $tmp2 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " .
906 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
907 array($this->pid, $this->encounter));
908 if ($tmp1['sum'] + $tmp2['sum'] == 0) {
909 sqlStatement("update drug_sales SET billed = 1 WHERE " .
910 "pid = ? AND encounter = ? AND billed = 0",
911 array($this->pid, $this->encounter));
912 sqlStatement("UPDATE billing SET billed = 1, bill_date = NOW() WHERE " .
913 "pid = ? AND encounter = ? AND billed = 0 AND activity = 1",
914 array($this->pid, $this->encounter));
916 else {
917 // Would be good to display an error message here... they clicked
918 // Save and Close but the close could not be done. However the
919 // framework does not provide an easy way to do that.
924 // Call this after save() for Family Planning implementations.
925 // It checks the contraception form, or makes a new one if $newmauser is set.
926 // Returns 0 unless user intervention is required to fix a missing or incorrect form,
927 // and in that case the return value is an existing form ID, or -1 if none.
929 // Returns FALSE if user intervention is required to fix a missing or incorrect form.
931 public function doContraceptionForm($ippfconmeth=NULL, $newmauser=NULL, $main_provid=0) {
932 if (!empty($ippfconmeth)) {
933 $csrow = sqlQuery("SELECT f.form_id, ld.field_value FROM forms AS f " .
934 "LEFT JOIN lbf_data AS ld ON ld.form_id = f.form_id AND ld.field_id = 'newmethod' " .
935 "WHERE " .
936 "f.pid = ? AND f.encounter = ? AND " .
937 "f.formdir = 'LBFccicon' AND f.deleted = 0 " .
938 "ORDER BY f.form_id DESC LIMIT 1",
939 array($this->pid, $this->encounter));
940 if (isset($newmauser)) {
941 // pastmodern is 0 iff new to modern contraception
942 $pastmodern = $newmauser == '2' ? 0 : 1;
943 if ($newmauser == '2') $newmauser = '1';
944 // Add contraception form but only if it does not already exist
945 // (if it does, must be 2 users working on the visit concurrently).
946 if (empty($csrow)) {
947 $newid = $this->insert_lbf_item(0, 'newmauser', $newmauser);
948 $this->insert_lbf_item($newid, 'newmethod', "IPPFCM:$ippfconmeth");
949 $this->insert_lbf_item($newid, 'pastmodern', $pastmodern);
950 // Do we care about a service-specific provider here?
951 $this->insert_lbf_item($newid, 'provider', $main_provid);
952 addForm($this->encounter, 'Contraception', $newid, 'LBFccicon', $this->pid, $GLOBALS['userauthorized']);
955 else if (empty($csrow) || $csrow['field_value'] != "IPPFCM:$ippfconmeth") {
956 // Contraceptive method does not match what is in an existing Contraception
957 // form for this visit, or there is no such form. User intervention is needed.
958 return empty($csrow) ? -1 : intval($csrow['form_id']);
961 return 0;
964 // Get price level from patient demographics.
966 public function getPriceLevel() {
967 return $this->patient_pricelevel;
970 // Update price level in patient demographics if it's changed.
972 public function updatePriceLevel($pricelevel) {
973 if (!empty($pricelevel)) {
974 if ($this->patient_pricelevel != $pricelevel) {
975 $this->logFSMessage(xl('Price level changed'));
976 sqlStatement("UPDATE patient_data SET pricelevel = ? WHERE pid = ?",
977 array($pricelevel, $this->pid));
978 $this->patient_pricelevel = $pricelevel;
983 // Create JSON string representing code type, code and selector.
984 // This can be a checkbox value for parsing when the checkbox is clicked.
985 // As a side effect note if the code is already selected in the Fee Sheet.
987 public function genCodeSelectorValue($codes) {
988 global $code_types;
989 list($codetype, $code, $selector) = explode(':', $codes);
990 if ($codetype == 'PROD') {
991 $crow = sqlQuery("SELECT sale_id " .
992 "FROM drug_sales WHERE pid = ? AND encounter = ? AND drug_id = ? " .
993 "LIMIT 1",
994 array($this->pid, $this->encounter, $code));
995 $this->code_is_in_fee_sheet = !empty($crow['sale_id']);
996 $cbarray = array($codetype, $code, $selector);
998 else {
999 $crow = sqlQuery("SELECT c.id AS code_id, b.id " .
1000 "FROM codes AS c " .
1001 "LEFT JOIN billing AS b ON b.pid = ? AND b.encounter = ? AND b.code_type = ? AND b.code = c.code AND b.activity = 1 " .
1002 "WHERE c.code_type = ? AND c.code = ? LIMIT 1",
1003 array($this->pid, $this->encounter, $codetype, $code_types[$codetype]['id'], $code));
1004 $this->code_is_in_fee_sheet = !empty($crow['id']);
1005 $cbarray = array($codetype, $code);
1007 $cbval = json_encode($cbarray);
1008 return $cbval;