POS default selection for encounter (#1088)
[openemr.git] / library / billing.inc
blobe3b918879535ac0411fecfe7ab739c4a6894848d
1 <?php
4 function getBillingById($id, $cols = "*")
6     return sqlQuery("select $cols from billing where id='$id' and activity=1 order by date DESC limit 0,1");
9 function getBillingByPid($pid, $cols = "*")
11     return  sqlQuery("select $cols from billing where pid ='$pid' and activity=1 order by date DESC limit 0,1");
14 function getBillingByEncounter($pid, $encounter, $cols = "code_type, code, code_text")
16     $res = sqlStatement("select $cols from billing where encounter = ? and pid=? and activity=1 order by code_type, date ASC", array($encounter,$pid));
18     $all=array();
19     for ($iter=0; $row=sqlFetchArray($res); $iter++) {
20         $all[$iter] = $row;
21     }
23     return $all;
26 function addBilling(
27     $encounter_id,
28     $code_type,
29     $code,
30     $code_text,
31     $pid,
32     $authorized = "0",
33     $provider,
34     $modifier = "",
35     $units = "",
36     $fee = "0.00",
37     $ndc_info = '',
38     $justify = '',
39     $billed = 0,
40     $notecodes = '',
41     $pricelevel = '',
42     $revenue_code = ""
43 ) {
45     $sql = "insert into billing (date, encounter, code_type, code, code_text, " .
46     "pid, authorized, user, groupname, activity, billed, provider_id, " .
47     "modifier, units, fee, ndc_info, justify, notecodes, pricelevel, revenue_code) values (" .
48     "NOW(), ?, ?, ?, ?, ?, ?, ?, ?,  1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
49     return sqlInsert($sql, array($encounter_id,$code_type,$code,$code_text,$pid,$authorized,
50         $_SESSION['authId'],$_SESSION['authProvider'],$billed,$provider,$modifier,$units,$fee,
51     $ndc_info,$justify,$notecodes,$pricelevel,$revenue_code));
54 function authorizeBilling($id, $authorized = "1")
56     sqlQuery("update billing set authorized = '$authorized' where id = '$id'");
59 function deleteBilling($id)
61     sqlStatement("update billing set activity = 0 where id = '$id'");
64 function clearBilling($id)
66     sqlStatement("update billing set justify = '' where id = '$id'");
69 // This function supports the Billing page (billing_process.php),
70 // and initiation of secondary processing (sl_eob.inc.php).
71 // It is called in the following situations:
73 // * billing_process.php sets bill_time, bill_process, payer and target on
74 //   queueing a claim for processing.  Create claims row.
75 // * billing_process.php sets claim status to 2, and payer, on marking a
76 //   claim as billed without actually generating any billing.  Create a
77 //   claims row.  In this case bill_process will remain at 0 and process_time
78 //   and process_file will not be set.
79 // * billing_process.php sets bill_process, payer, target and x12 partner
80 //   before calling gen_x12_837.  Create a claims row.
81 // * billing_process.php sets claim status to 2 (billed), bill_process to 2,
82 //   process_time and process_file after calling gen_x12_837.  Claims row
83 //   already exists.
84 // * billing_process.php sets claim status to 2 (billed) after creating
85 //   an electronic batch (hcfa-only with recent changes).  Claims
86 //   row already exists.
87 // * EOB posting updates claim status to mark a payer as done.  Claims row
88 //   already exists.
89 // * EOB posting reopens an encounter for billing a secondary payer.  Create
90 //   a claims row.
92 // $newversion should be passed to us to indicate if a new claims row
93 // is to be generated, otherwise one must already exist.  The payer, if
94 // passed in for the latter case, must match the existing claim.
96 // Currently on the billing page the user can select any of the patient's
97 // payers.  That logic will tailor the payer choices to the encounter date.
99 function updateClaim(
100     $newversion,
101     $patient_id,
102     $encounter_id,
103     $payer_id = -1,
104     $payer_type = -1,
105     $status = -1,
106     $bill_process = -1,
107     $process_file = '',
108     $target = '',
109     $partner_id = -1,
110     $crossover = 0,
111     $submitted_claim = ''
112 ) {
114     if (!$newversion) {
115         $sql = "SELECT * FROM claims WHERE patient_id = '$patient_id' AND " .
116         "encounter_id = '$encounter_id' AND status > 0 AND status < 4 ";
117         if ($payer_id >= 0) {
118             $sql .= "AND payer_id = '$payer_id' ";
119         }
121         $sql .= "ORDER BY version DESC LIMIT 1";
122         $row = sqlQuery($sql);
123         if (!$row) {
124             return 0;
125         }
127         if ($payer_id     < 0) {
128             $payer_id     = $row['payer_id'];
129         }
131         if ($status       < 0) {
132             $status       = $row['status'];
133         }
135         if ($bill_process < 0) {
136             $bill_process = $row['bill_process'];
137         }
139         if ($partner_id   < 0) {
140             $partner_id   = $row['x12_partner_id'];
141         }
143         if (!$process_file) {
144             $process_file = $row['process_file'];
145         }
147         if (!$target) {
148             $target       = $row['target'];
149         }
150     }
152     $claimset = "";
153     $billset = "";
154     if (empty($payer_id) || $payer_id < 0) {
155         $payer_id = 0;
156     }
158     if ($status==7) {//$status==7 is the claim denial case.
159         $claimset .= ", status = '$status'";
160     } elseif ($status >= 0) {
161         $claimset .= ", status = '$status'";
162         if ($status > 1) {
163             $billset .= ", billed = 1";
164             if ($status == 2) {
165                 $billset  .= ", bill_date = NOW()";
166             }
167         } else {
168             $billset .= ", billed = 0";
169         }
170     }
172     if ($status==7) {//$status==7 is the claim denial case.
173         $billset  .= ", bill_process = '$status'";
174     } elseif ($bill_process >= 0) {
175         $claimset .= ", bill_process = '$bill_process'";
176         $billset  .= ", bill_process = '$bill_process'";
177     }
179     if ($status==7) {//$status==7 is the claim denial case.
180         $claimset  .= ", process_file = '$process_file'";//Denial reason code is stored here
181     } elseif ($process_file) {
182         $claimset .= ", process_file = '$process_file', process_time = NOW()";
183         $billset  .= ", process_file = '$process_file', process_date = NOW()";
184     }
186     if ($target) {
187         $claimset .= ", target = '$target'";
188         $billset  .= ", target = '$target'";
189     }
191     if ($payer_id >= 0) {
192         $claimset .= ", payer_id = '$payer_id', payer_type = '$payer_type'";
193         $billset  .= ", payer_id = '$payer_id'";
194     }
196     if ($partner_id >= 0) {
197         $claimset .= ", x12_partner_id = '$partner_id'";
198         $billset  .= ", x12_partner_id = '$partner_id'";
199     }
201     if ($billset) {
202         $billset = substr($billset, 2);
203         sqlStatement("UPDATE billing SET $billset WHERE " .
204         "encounter = '$encounter_id' AND pid='$patient_id' AND activity = 1");
205     }
207     $claimset .= ", submitted_claim = '$submitted_claim'";
209   // If a new claim version is requested, insert its row.
210   //
211     if ($newversion) {
212         /****
213         $payer_id = ($payer_id < 0) ? $row['payer_id'] : $payer_id;
214         $bill_process = ($bill_process < 0) ? $row['bill_process'] : $bill_process;
215         $process_file = ($process_file) ? $row['process_file'] : $process_file;
216         $target = ($target) ? $row['target'] : $target;
217         $partner_id = ($partner_id < 0) ? $row['x12_partner_id'] : $partner_id;
218         $sql = "INSERT INTO claims SET " .
219         "patient_id = '$patient_id', " .
220         "encounter_id = '$encounter_id', " .
221         "bill_time = UNIX_TIMESTAMP(NOW()), " .
222         "payer_id = '$payer_id', " .
223         "status = '$status', " .
224         "payer_type = '" . $row['payer_type'] . "', " .
225         "bill_process = '$bill_process', " .
226         "process_time = '" . $row['process_time'] . "', " .
227         "process_file = '$process_file', " .
228         "target = '$target', " .
229         "x12_partner_id = '$partner_id'";
230         ****/
231         sqlBeginTrans();
232         $version = sqlQuery("SELECT IFNULL(MAX(version),0) + 1 AS increment FROM claims WHERE patient_id = ? AND encounter_id = ?", array( $patient_id, $encounter_id ));
233         if ($crossover<>1) {
234             $sql .= "INSERT INTO claims SET " .
235               "patient_id = $patient_id, " .
236               "encounter_id = $encounter_id, " .
237               "bill_time = NOW() $claimset ," .
238               "version = " . $version['increment'];
239         } else {//Claim automatic forward case.startTra
240             $sql= "INSERT INTO claims SET " .
241               "patient_id = $patient_id, " .
242               "encounter_id = $encounter_id, " .
243               "bill_time = NOW(), status=$status ," .
244               "version = " . $version['increment'];
245         }
247         sqlStatement($sql);
248         sqlCommitTrans();
249     } // Otherwise update the existing claim row.
250   //
251     else if ($claimset) {
252         $claimset = substr($claimset, 2);
253         sqlStatement("UPDATE claims SET $claimset WHERE " .
254         "patient_id = '$patient_id' AND encounter_id = '$encounter_id' AND " .
255         // "payer_id = '" . $row['payer_id'] . "' AND " .
256         "version = '" . $row['version'] . "'");
257     }
259   // Whenever a claim is marked billed, update A/R accordingly.
260   //
261     if ($status == 2) {
262         if ($payer_type > 0) {
263             sqlStatement("UPDATE form_encounter SET " .
264             "last_level_billed = '$payer_type' WHERE " .
265             "pid = '$patient_id' AND encounter = '$encounter_id'");
266         }
267     }
269     return 1;
272 // Determine if the encounter is billed.  It is considered billed if it
273 // has at least one chargeable item, and all of them are billed.
275 function isEncounterBilled($pid, $encounter)
277     $billed = -1; // no chargeable services yet
279     $bres = sqlStatement(
280         "SELECT " .
281         "billing.billed FROM billing, code_types WHERE " .
282         "billing.pid = ? AND " .
283         "billing.encounter = ? AND " .
284         "billing.activity = 1 AND " .
285         "code_types.ct_key = billing.code_type AND " .
286         "code_types.ct_fee = 1 " .
287         "UNION " .
288         "SELECT billed FROM drug_sales WHERE " .
289         "pid = ? AND " .
290         "encounter = ?",
291         array($pid, $encounter, $pid, $encounter)
292     );
294     while ($brow = sqlFetchArray($bres)) {
295         if ($brow['billed'] == 0) {
296             $billed = 0;
297         } else {
298             if ($billed < 0) {
299                 $billed = 1;
300             }
301         }
302     }
304     return $billed > 0;
307 // Get the co-pay amount that is effective on the given date.
308 // Or if no insurance on that date, return -1.
310 function getCopay($patient_id, $encdate)
312     $tmp = sqlQuery("SELECT provider, copay FROM insurance_data " .
313     "WHERE pid = '$patient_id' AND type = 'primary' " .
314     "AND date <= '$encdate' ORDER BY date DESC LIMIT 1");
315     if ($tmp['provider']) {
316         return sprintf('%01.2f', 0 + $tmp['copay']);
317     }
319     return 0;
322 // Get the total co-pay amount paid by the patient for an encounter
323 function getPatientCopay($patient_id, $encounter)
325         $resMoneyGot = sqlStatement(
326             "SELECT sum(pay_amount) as PatientPay FROM ar_activity where ".
327             "pid = ? and encounter = ? and payer_type=0 and account_code='PCP'",
328             array($patient_id,$encounter)
329         );
330          //new fees screen copay gives account_code='PCP'
331         $rowMoneyGot = sqlFetchArray($resMoneyGot);
332         $Copay=$rowMoneyGot['PatientPay'];
333         return $Copay*-1;
336 // Get the "next invoice reference number" from this user's pool of reference numbers.
338 function getInvoiceRefNumber()
340     $trow = sqlQuery(
341         "SELECT lo.notes " .
342         "FROM users AS u, list_options AS lo " .
343         "WHERE u.username = ? AND " .
344         "lo.list_id = 'irnpool' AND lo.option_id = u.irnpool AND lo.activity = 1 LIMIT 1",
345         array($_SESSION['authUser'])
346     );
347     return empty($trow['notes']) ? '' : $trow['notes'];
350 // Increment the "next invoice reference number" of this user's pool.
351 // This identifies the "digits" portion of that number and adds 1 to it.
352 // If it contains more than one string of digits, the last is used.
354 function updateInvoiceRefNumber()
356     $irnumber = getInvoiceRefNumber();
357   // Here "?" specifies a minimal match, to get the most digits possible:
358     if (preg_match('/^(.*?)(\d+)(\D*)$/', $irnumber, $matches)) {
359         $newdigs = sprintf('%0' . strlen($matches[2]) . 'd', $matches[2] + 1);
360         $newnumber = $matches[1] . $newdigs . $matches[3];
361         sqlStatement(
362             "UPDATE users AS u, list_options AS lo " .
363             "SET lo.notes = ? WHERE " .
364             "u.username = ? AND " .
365             "lo.list_id = 'irnpool' AND lo.option_id = u.irnpool",
366             array($newnumber, $_SESSION['authUser'])
367         );
368     }
370     return $irnumber;
373 // Common function for voiding a receipt or checkout.  When voiding a checkout you can specify
374 // $time as a timestamp (yyyy-mm-dd hh:mm:ss) or 'all'; default is the last checkout.
376 function doVoid($patient_id, $encounter_id, $purge = false, $time = '')
378     $what_voided = $purge ? 'checkout' : 'receipt';
379     $date_original = '';
380     $adjustments = 0;
381     $payments = 0;
383     if (!$time) {
384         // Get last checkout timestamp.
385         $corow = sqlQuery(
386             "(SELECT bill_date FROM billing WHERE " .
387             "pid = ? AND encounter = ? AND activity = 1 AND bill_date IS NOT NULL) " .
388             "UNION " .
389             "(SELECT bill_date FROM drug_sales WHERE " .
390             "pid = ? AND encounter = ? AND bill_date IS NOT NULL) " .
391             "ORDER BY bill_date DESC LIMIT 1",
392             array($patient_id, $encounter_id, $patient_id, $encounter_id)
393         );
394         if (!empty($corow['bill_date'])) {
395               $date_original = $corow['bill_date'];
396         }
397     } else if ($time == 'all') {
398         $row = sqlQuery(
399             "SELECT SUM(pay_amount) AS payments, " .
400             "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
401             "pid = ? AND encounter = ?",
402             array($patient_id, $encounter_id)
403         );
404         $adjustments = $row['adjustments'];
405         $payments = $row['payments'];
406     } else {
407         $date_original = $time;
408     }
410   // Get its charges and adjustments.
411     if ($date_original) {
412         $row = sqlQuery(
413             "SELECT SUM(pay_amount) AS payments, " .
414             "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
415             "pid = ? AND encounter = ? AND post_time = ?",
416             array($patient_id, $encounter_id, $date_original)
417         );
418         $adjustments = $row['adjustments'];
419         $payments = $row['payments'];
420     }
422   // Get old invoice reference number.
423     $encrow = sqlQuery(
424         "SELECT invoice_refno FROM form_encounter WHERE " .
425         "pid = ? AND encounter = ? LIMIT 1",
426         array($patient_id, $encounter_id)
427     );
428     $old_invoice_refno = $encrow['invoice_refno'];
429   //
430     $usingirnpools = getInvoiceRefNumber();
431   // If not (undoing a checkout or using IRN pools), nothing is done.
432     if ($purge || $usingirnpools) {
433         $query = "INSERT INTO voids SET " .
434         "patient_id = ?, " .
435         "encounter_id = ?, " .
436         "what_voided = ?, " .
437         "date_voided = NOW(), " .
438         "user_id = ?, " .
439         "amount1 = ?, " .
440         "amount2 = ?, " .
441         "other_info = ?";
442         $sqlarr = array($patient_id, $encounter_id, $what_voided, $_SESSION['authUserID'], $row['adjustments'],
443         $row['payments'], $old_invoice_refno);
444         if ($date_original) {
445               $query .= ", date_original = ?";
446               $sqlarr[] = $date_original;
447         }
449         sqlStatement($query, $sqlarr);
450     }
452     if ($purge) {
453         // Purge means delete adjustments and payments from the last checkout
454         // and re-open the visit.
455         if ($date_original) {
456             sqlStatement(
457                 "DELETE FROM ar_activity WHERE " .
458                 "pid = ? AND encounter = ? AND post_time = ?",
459                 array($patient_id, $encounter_id, $date_original)
460             );
461             sqlStatement(
462                 "UPDATE billing SET billed = 0, bill_date = NULL WHERE " .
463                 "pid = ? AND encounter = ? AND activity = 1 AND " .
464                 "bill_date IS NOT NULL AND bill_date = ?",
465                 array($patient_id, $encounter_id, $date_original)
466             );
467             sqlStatement(
468                 "update drug_sales SET billed = 0, bill_date = NULL WHERE " .
469                 "pid = ? AND encounter = ? AND " .
470                 "bill_date IS NOT NULL AND bill_date = ?",
471                 array($patient_id, $encounter_id, $date_original)
472             );
473         } else {
474             if ($time == 'all') {
475                 sqlStatement(
476                     "DELETE FROM ar_activity WHERE " .
477                     "pid = ? AND encounter = ?",
478                     array($patient_id, $encounter_id)
479                 );
480             }
482             sqlStatement(
483                 "UPDATE billing SET billed = 0, bill_date = NULL WHERE " .
484                 "pid = ? AND encounter = ? AND activity = 1",
485                 array($patient_id, $encounter_id)
486             );
487             sqlStatement(
488                 "update drug_sales SET billed = 0, bill_date = NULL WHERE " .
489                 "pid = ? AND encounter = ?",
490                 array($patient_id, $encounter_id)
491             );
492         }
494         sqlStatement(
495             "UPDATE form_encounter SET last_level_billed = 0, " .
496             "last_level_closed = 0, stmt_count = 0, last_stmt_date = NULL " .
497             "WHERE pid = ? AND encounter = ?",
498             array($patient_id, $encounter_id)
499         );
500     } else if ($usingirnpools) {
501         // Non-purge means just assign a new invoice reference number.
502         $new_invoice_refno = add_escape_custom(updateInvoiceRefNumber());
503         sqlStatement(
504             "UPDATE form_encounter " .
505             "SET invoice_refno = ? " .
506             "WHERE pid = ? AND encounter = ?",
507             array($new_invoice_refno, $patient_id, $encounter_id)
508         );
509     }