2 // Copyright (C) 2005-2008 Rod Roark <rod@sunsetsystems.com>
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License
6 // as published by the Free Software Foundation; either version 2
7 // of the License, or (at your option) any later version.
9 include_once("patient.inc");
10 include_once("billing.inc");
12 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] !== 2) {
13 include_once("sql-ledger.inc");
14 include_once("invoice_summary.inc.php");
22 function slInitialize() {
23 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
25 global $chart_id_cash, $chart_id_ar, $chart_id_income, $services_id;
26 global $sl_cash_acc, $sl_ar_acc, $sl_income_acc, $sl_services_id;
30 $chart_id_cash = SLQueryValue("select id from chart where accno = '$sl_cash_acc'");
31 if ($sl_err) die($sl_err);
32 if (! $chart_id_cash) die(xl("There is no COA entry for cash account ") . "'$sl_cash_acc'");
34 $chart_id_ar = SLQueryValue("select id from chart where accno = '$sl_ar_acc'");
35 if ($sl_err) die($sl_err);
36 if (! $chart_id_ar) die(xl("There is no COA entry for AR account ") . "'$sl_ar_acc'");
38 $chart_id_income = SLQueryValue("select id from chart where accno = '$sl_income_acc'");
39 if ($sl_err) die($sl_err);
40 if (! $chart_id_income) die(xl("There is no COA entry for income account ") . "'$sl_income_acc'");
42 $services_id = SLQueryValue("select id from parts where partnumber = '$sl_services_id'");
43 if ($sl_err) die($sl_err);
44 if (! $services_id) die(xl("There is no parts entry for services ID ") . "'$sl_services_id'");
47 function slTerminate() {
48 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
52 // Try to figure out our invoice number (pid.encounter) from the
53 // claim ID and other stuff in the ERA. This should be straightforward
54 // except that some payers mangle the claim ID that we give them.
56 function slInvoiceNumber(&$out) {
57 $invnumber = $out['our_claim_id'];
58 $atmp = preg_split('/[ -]/', $invnumber);
59 $acount = count($atmp);
65 $encounter = $atmp[1];
67 else if ($acount == 3) {
69 $brow = sqlQuery("SELECT encounter FROM billing WHERE " .
70 "pid = '$pid' AND id = '" . $atmp[1] . "' AND activity = 1");
71 $encounter = $brow['encounter'];
73 else if ($acount == 1) {
74 $pres = sqlStatement("SELECT pid FROM patient_data WHERE " .
75 "lname LIKE '" . addslashes($out['patient_lname']) . "' AND " .
76 "fname LIKE '" . addslashes($out['patient_fname']) . "' " .
78 while ($prow = sqlFetchArray($pres)) {
79 if (strpos($invnumber, $prow['pid']) === 0) {
81 $encounter = substr($invnumber, strlen($pid));
87 if ($pid && $encounter) $invnumber = "$pid.$encounter";
88 return array($pid, $encounter, $invnumber);
91 // Insert a row into the acc_trans table.
92 // This should never be called if SQL-Ledger is not used.
94 function slAddTransaction($invid, $chartid, $amount, $date, $source, $memo, $insplan, $debug) {
96 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2)
97 die("Internal error calling slAddTransaction()");
98 $date = fixDate($date);
99 $query = "INSERT INTO acc_trans ( " .
108 "$invid, " . // trans_id
109 "$chartid, " . // chart_id
110 "$amount, " . // amount
111 "'$date', " . // transdate
112 "'$source', " . // source
113 "$insplan, " . // project_id
117 echo $query . "<br>\n";
120 if ($sl_err) die($sl_err);
124 // Insert a row into the invoice table.
125 // This should never be called if SQL-Ledger is not used.
127 function slAddLineItem($invid, $serialnumber, $amount, $units, $insplan, $description, $debug) {
128 global $sl_err, $services_id;
129 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2)
130 die("Internal error calling slAddLineItem()");
131 $units = max(1, intval($units));
132 $price = $amount / $units;
133 $tmp = sprintf("%01.2f", $price);
134 if (abs($price - $tmp) < 0.000001) $price = $tmp;
135 $query = "INSERT INTO invoice ( " .
148 "$invid, " . // trans_id
149 "$services_id, " . // parts_id
150 "'$description', " . // description
153 "$price, " . // sellprice
154 "$price, " . // fxsellprice
157 "$insplan, " . // project_id
158 "'$serialnumber'" . // serialnumber
161 echo $query . "<br>\n";
164 if ($sl_err) die($sl_err);
168 // Update totals and payment date in the invoice header. Dollar amounts are
169 // stored as double precision floats so we have to be careful about rounding.
170 // This should never be called if SQL-Ledger is not used.
172 function slUpdateAR($invid, $amount, $paid = 0, $paydate = "", $debug) {
174 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2)
175 die("Internal error calling slUpdateAR()");
176 $paydate = fixDate($paydate);
177 $query = "UPDATE ar SET amount = round(CAST (amount AS numeric) + $amount, 2), " .
178 "netamount = round(CAST (netamount AS numeric) + $amount, 2)";
179 if ($paid) $query .= ", paid = round(CAST (paid AS numeric) + $paid, 2), datepaid = '$paydate'";
180 $query .= " WHERE id = $invid";
182 echo $query . "<br>\n";
185 if ($sl_err) die($sl_err);
189 // This gets a posting session ID. If the payer ID is not 0 and a matching
190 // session already exists, then its ID is returned. Otherwise a new session
193 function arGetSession($payer_id, $reference, $check_date, $deposit_date='', $pay_total=0) {
194 if (empty($deposit_date)) $deposit_date = $check_date;
196 $row = sqlQuery("SELECT session_id FROM ar_session WHERE " .
197 "payer_id = '$payer_id' AND reference = '$reference' AND " .
198 "check_date = '$check_date' AND deposit_date = '$deposit_date' " .
199 "ORDER BY session_id DESC LIMIT 1");
200 if (!empty($row['session_id'])) return $row['session_id'];
202 return sqlInsert("INSERT INTO ar_session ( " .
203 "payer_id, user_id, reference, check_date, deposit_date, pay_total " .
206 "'" . $_SESSION['authUserID'] . "', " .
209 "'$deposit_date', " .
214 // Post a payment, SQL-Ledger style.
216 function slPostPayment($trans_id, $thispay, $thisdate, $thissrc, $code, $thisins, $debug) {
217 global $chart_id_cash, $chart_id_ar;
218 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2)
219 die("Internal error calling slPostPayment()");
220 // Post a payment: add to ar, subtract from cash.
221 slAddTransaction($trans_id, $chart_id_ar , $thispay , $thisdate, $thissrc, $code, $thisins, $debug);
222 slAddTransaction($trans_id, $chart_id_cash, 0 - $thispay, $thisdate, $thissrc, $code, $thisins, $debug);
223 slUpdateAR($trans_id, 0, $thispay, $thisdate, $debug);
226 // Post a payment, new style.
228 function arPostPayment($patient_id, $encounter_id, $session_id, $amount, $code, $payer_type, $memo, $debug, $time='') {
231 $tmp = strpos($code, ':');
233 $codeonly = substr($code, 0, $tmp);
234 $modifier = substr($code, $tmp+
1);
236 if (empty($time)) $time = date('Y-m-d H:i:s');
237 $query = "INSERT INTO ar_activity ( " .
238 "pid, encounter, code, modifier, payer_type, post_time, post_user, " .
239 "session_id, memo, pay_amount " .
242 "'$encounter_id', " .
247 "'" . $_SESSION['authUserID'] . "', " .
252 sqlStatement($query);
256 // Post a charge. This is called only from sl_eob_process.php where
257 // automated remittance processing can create a new service item.
258 // Here we add it as an unauthorized item to the billing table.
260 function arPostCharge($patient_id, $encounter_id, $session_id, $amount, $units, $thisdate, $code, $description, $debug) {
261 /*****************************************************************
262 // Select an existing billing item as a template.
263 $row= sqlQuery("SELECT * FROM billing WHERE " .
264 "pid = '$patient_id' AND encounter = '$encounter_id' AND " .
265 "code_type = 'CPT4' AND activity = 1 " .
266 "ORDER BY id DESC LIMIT 1");
267 $this_authorized = 0;
270 $this_authorized = $row['authorized'];
271 $this_provider = $row['provider_id'];
273 *****************************************************************/
277 $tmp = strpos($code, ':');
279 $codeonly = substr($code, 0, $tmp);
280 $modifier = substr($code, $tmp+
1);
283 addBilling($encounter_id,
286 addslashes($description),
297 // See comments above.
298 // In the SQL-Ledger case this service item is added only to SL and
299 // not to the billing table.
301 function slPostCharge($trans_id, $thisamt, $thisunits, $thisdate, $code, $thisins, $description, $debug) {
302 global $chart_id_income, $chart_id_ar;
303 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2)
304 die("Internal error calling slPostCharge()");
305 // Post an adjustment: add negative invoice item, add to ar, subtract from income
306 slAddLineItem($trans_id, $code, $thisamt, $thisunits, $thisins, $description, $debug);
308 slAddTransaction($trans_id, $chart_id_ar , 0 - $thisamt, $thisdate, $description, $code, $thisins, $debug);
309 slAddTransaction($trans_id, $chart_id_income, $thisamt , $thisdate, $description, $code, $thisins, $debug);
310 slUpdateAR($trans_id, $thisamt, 0, '', $debug);
314 // Post an adjustment, SQL-Ledger style.
316 function slPostAdjustment($trans_id, $thisadj, $thisdate, $thissrc, $code, $thisins, $reason, $debug) {
317 global $chart_id_income, $chart_id_ar;
318 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2)
319 die("Internal error calling slPostAdjustment()");
320 // Post an adjustment: add negative invoice item, add to ar, subtract from income
321 $adjdate = fixDate($thisdate);
322 $description = "Adjustment $adjdate $reason";
323 slAddLineItem($trans_id, $code, 0 - $thisadj, 1, $thisins, $description, $debug);
325 slAddTransaction($trans_id, $chart_id_ar, $thisadj, $thisdate, "InvAdj $thissrc", $code, $thisins, $debug);
326 slAddTransaction($trans_id, $chart_id_income, 0 - $thisadj, $thisdate, "InvAdj $thissrc", $code, $thisins, $debug);
327 slUpdateAR($trans_id, 0 - $thisadj, 0, '', $debug);
331 // Post an adjustment, new style.
333 function arPostAdjustment($patient_id, $encounter_id, $session_id, $amount, $code, $payer_type, $reason, $debug, $time='') {
336 $tmp = strpos($code, ':');
338 $codeonly = substr($code, 0, $tmp);
339 $modifier = substr($code, $tmp+
1);
341 if (empty($time)) $time = date('Y-m-d H:i:s');
342 $query = "INSERT INTO ar_activity ( " .
343 "pid, encounter, code, modifier, payer_type, post_user, post_time, " .
344 "session_id, memo, adj_amount " .
347 "'$encounter_id', " .
351 "'" . $_SESSION['authUserID'] . "', " .
357 sqlStatement($query);
361 function arGetPayerID($patient_id, $date_of_service, $payer_type) {
362 if ($payer_type < 1 ||
$payer_type > 3) return 0;
363 $tmp = array(1 => 'primary', 2 => 'secondary', 3 => 'tertiary');
364 $value = $tmp[$payer_type];
365 $query = "SELECT provider FROM insurance_data WHERE " .
366 "pid = '$patient_id' AND type = '$value' AND date <= '$date_of_service' " .
367 "ORDER BY date DESC LIMIT 1";
368 $nprow = sqlQuery($query);
369 echo "<!-- $query => '" . $nprow['provider'] . "' -->\n"; // debugging
370 if (empty($nprow)) return 0;
371 return $nprow['provider'];
374 // Make this invoice re-billable, new style.
376 function arSetupSecondary($patient_id, $encounter_id, $debug) {
378 // Determine the next insurance level to be billed.
379 $ferow = sqlQuery("SELECT date, last_level_billed " .
380 "FROM form_encounter WHERE " .
381 "pid = '$patient_id' AND encounter = '$encounter_id'");
382 $date_of_service = substr($ferow['date'], 0, 10);
383 $new_payer_type = 0 +
$ferow['last_level_billed'];
384 if ($new_payer_type < 3 && !empty($ferow['last_level_billed']) ||
$new_payer_type == 0)
387 $new_payer_id = arGetPayerID($patient_id, $date_of_service, $new_payer_type);
390 // Queue up the claim.
392 updateClaim(true, $patient_id, $encounter_id, $new_payer_id, $new_payer_type, 1, 5, '', 'hcfa');
395 // Just reopen the claim.
397 updateClaim(true, $patient_id, $encounter_id, -1, -1, 1, 0, '');
400 return xl("Encounter ") . $encounter . xl(" is ready for re-billing.");
403 // Make this invoice re-billable, SQL-Ledger style.
405 function slSetupSecondary($invid, $debug) {
406 global $sl_err, $GLOBALS;
408 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2)
409 die("Internal error calling slSetupSecondary()");
413 // Get some needed items from the SQL-Ledger invoice.
414 $arres = SLQuery("select invnumber, transdate, customer_id, employee_id, " .
415 "shipvia from ar where ar.id = $invid");
416 if ($sl_err) die($sl_err);
417 $arrow = SLGetRow($arres, 0);
418 if (! $arrow) die(xl('There is no match for invoice id') . ' = ' . "$trans_id.");
419 $customer_id = $arrow['customer_id'];
420 $date_of_service = $arrow['transdate'];
421 list($trash, $encounter) = explode(".", $arrow['invnumber']);
423 // Get the OpenEMR PID corresponding to the customer.
424 $pdrow = sqlQuery("SELECT patient_data.pid " .
425 "FROM integration_mapping, patient_data WHERE " .
426 "integration_mapping.foreign_id = $customer_id AND " .
427 "integration_mapping.foreign_table = 'customer' AND " .
428 "patient_data.id = integration_mapping.local_id");
429 $pid = $pdrow['pid'];
430 if (! $pid) die(xl("Cannot find patient from SQL-Ledger customer id") . " = $customer_id.");
432 // Determine the ID of the next insurance company (if any) to be billed.
434 $new_payer_type = -1;
435 $insdone = strtolower($arrow['shipvia']);
436 foreach (array('ins1' => 'primary', 'ins2' => 'secondary', 'ins3' => 'tertiary') as $key => $value) {
437 if (strpos($insdone, $key) === false) {
438 $nprow = sqlQuery("SELECT provider FROM insurance_data WHERE " .
439 "pid = '$pid' AND type = '$value' AND date <= '$date_of_service' " .
440 "ORDER BY date DESC LIMIT 1");
441 if (!empty($nprow['provider'])) {
442 $new_payer_id = $nprow['provider'];
443 $new_payer_type = substr($key, 3);
449 // Find out if the encounter exists.
450 $ferow = sqlQuery("SELECT pid FROM form_encounter WHERE " .
451 "encounter = $encounter");
452 $encounter_pid = $ferow['pid'];
454 // If it exists, just update the billing items.
455 if ($encounter_pid) {
456 if ($encounter_pid != $pid)
457 die(xl("Expected form_encounter.pid to be ") . $pid . ', ' . xl(' but was ') . $encounter_pid);
459 // If there's a payer ID queue it up, otherwise just reopen it.
460 if ($new_payer_id > 0) {
461 // TBD: implement a default bill_process and target in config.php,
462 // it should not really be hard-coded here.
464 updateClaim(true, $pid, $encounter, $new_payer_id, $new_payer_type, 1, 5, '', 'hcfa');
467 updateClaim(true, $pid, $encounter, -1, -1, 1, 0, '');
470 $info_msg = xl("Encounter ") . $encounter . xl(" is ready for re-billing.");
474 // If we get here then the encounter does not already exist. This should
475 // only happen if A/R was converted from an earlier system. In this case
476 // the encounter ID should be the date of service, and we will create the
479 // If it does not exist then it better be (or start with) a date.
480 if (! preg_match("/^20\d\d\d\d\d\d/", $encounter))
481 die(xl("Internal error: encounter '") . $encounter . xl("' should exist but does not."));
483 $employee_id = $arrow['employee_id'];
485 // Get the OpenEMR provider info corresponding to the SQL-Ledger salesman.
486 $drrow = sqlQuery("SELECT users.id, users.username, users.facility_id " .
487 "FROM integration_mapping, users WHERE " .
488 "integration_mapping.foreign_id = $employee_id AND " .
489 "integration_mapping.foreign_table = 'salesman' AND " .
490 "users.id = integration_mapping.local_id");
491 $provider_id = $drrow['id'];
492 if (! $provider_id) die(xl("Cannot find provider from SQL-Ledger employee = ") . $employee_id );
494 if (! $date_of_service) die(xl("Invoice has no date!"));
496 // Generate a new encounter number.
497 $conn = $GLOBALS['adodb']['db'];
498 $new_encounter = $conn->GenID("sequences");
500 // Create the "new encounter".
502 $query = "INSERT INTO form_encounter ( " .
503 "date, reason, facility_id, pid, encounter, onset_date " .
505 "'$date_of_service', " .
506 "'" . xl('Imported from Accounting') . "', " .
507 "'" . addslashes($drrow['facility_id']) . "', " .
510 "'$date_of_service' " .
513 echo $query . "<br>\n";
514 echo xl("Call to addForm() goes here.<br>") . "\n";
516 $encounter_id = idSqlStatement($query);
517 if (! $encounter_id) die(xl("Insert failed: ") . $query);
518 addForm($new_encounter, xl("New Patient Encounter"), $encounter_id,
519 "newpatient", $pid, 1, $date_of_service);
520 $info_msg = xl("Encounter ") . $new_encounter . xl(" has been created. ");
523 // For each invoice line item with a billing code we will insert
524 // a billing row with payer_id set to -1. Order the line items
525 // chronologically so that each procedure code will be followed by
526 // its associated icd9 code.
528 $inres = SLQuery("SELECT * FROM invoice WHERE trans_id = $invid " .
530 if ($sl_err) die($sl_err);
532 // When nonzero, this will be the ID of a billing row that needs to
533 // have its justify field set.
536 for ($irow = 0; $irow < SLRowCount($inres); ++
$irow) {
537 $row = SLGetRow($inres, $irow);
538 // $amount = $row['sellprice'];
539 $amount = sprintf('%01.2f', $row['sellprice'] * $row['qty']);
541 // Extract the billing code.
542 $code = xl("Unknown");
543 if (preg_match("/([A-Za-z0-9]\d\d\S*)/", $row['serialnumber'], $matches)) {
544 $code = strtoupper($matches[1]);
546 else if (preg_match("/([A-Za-z0-9]\d\d\S*)/", $row['description'], $matches)) {
547 $code = strtoupper($matches[1]);
550 list($code, $modifier) = explode("-", $code);
552 // Set the billing code type and description.
556 foreach ($code_types as $key => $value) {
557 if (preg_match("/$key/", $row['serialnumber'])) {
560 $code_text = xl("Procedure") . " $code";
562 $code_text = xl("Diagnosis") . " $code";
564 $query = "UPDATE billing SET justify = '$code' WHERE id = $proc_ins_id";
566 echo $query . "<br>\n";
578 if (! $code_type) continue;
580 // Insert the billing item. If this for a procedure code then save
581 // the row ID so that we can update the "justify" field with the ICD9
582 // code, which should come next in the loop.
584 $query = "INSERT INTO billing ( " .
585 "date, code_type, code, pid, provider_id, user, groupname, authorized, " .
586 "encounter, code_text, activity, payer_id, billed, bill_process, " .
587 "bill_date, modifier, units, fee, justify, target " .
594 "'" . $_SESSION['authId'] . "', " .
595 "'" . $_SESSION['authProvider'] . "', " .
601 ($new_payer_id > 0 ?
"1, " : "0, ") .
602 ($new_payer_id > 0 ?
"5, " : "0, ") .
603 ($new_payer_id > 0 ?
"NOW(), " : "NULL, ") .
608 ($new_payer_id > 0 ?
"'hcfa' " : "NULL ") .
611 echo $query . "<br>\n";
613 $proc_ins_id = idSqlStatement($query);
614 if ($code_type != "CPT4" && $code_type != "HCPCS")
619 // Finally, change this invoice number to contain the new encounter number.
621 $new_invnumber = "$pid.$new_encounter";
622 $query = "UPDATE ar SET invnumber = '$new_invnumber' WHERE id = $invid";
624 echo $query . "<br>\n";
627 if ($sl_err) die($sl_err);
628 $info_msg .= xl("This invoice number has been changed to ") . $new_invnumber;