function ar_responsible_party($patient_id, $encounter_id) { $row = sqlQuery("SELECT date, last_level_billed, last_level_closed " . "FROM form_encounter WHERE " . "pid = '{$patient_id}' AND encounter = '{$encounter_id}' " . "ORDER BY id DESC LIMIT 1"); if (empty($row)) { return -1; } $next_level = $row['last_level_closed'] + 1; if ($next_level <= $row['last_level_billed']) { return $next_level; } if (arGetPayerID($patient_id, substr($row['date'], 0, 10), $payer_type)) { return $next_level; } // There is no unclosed insurance, so see if there is an unpaid balance. // Currently hoping that form_encounter.balance_due can be discarded. $balance = 0; $codes = ar_get_invoice_summary($patient_id, $encounter_id); foreach ($codes as $cdata) { $balance += $cdata['bal']; } if ($balance > 0) { return 0; } return -1; }
} $coded = ""; $arid = 0; if ($thisauth && $auth_sensitivity) { $binfo = array('', '', '', '', ''); if ($subresult2 = getBillingByEncounter($pid, $result4['encounter'], "code_type, code, modifier, code_text, fee")) { // Get A/R info, if available, for this encounter. $arinvoice = array(); $arlinkbeg = ""; $arlinkend = ""; if ($billing_view && $accounting_enabled) { if ($INTEGRATED_AR) { $tmp = sqlQuery("SELECT id FROM form_encounter WHERE " . "pid = ? AND encounter = ?", array($pid, $result4['encounter'])); $arid = 0 + $tmp['id']; if ($arid) { $arinvoice = ar_get_invoice_summary($pid, $result4['encounter'], true); } } else { $arid = SLQueryValue("SELECT id FROM ar WHERE invnumber = " . "'{$pid}.{$result4['encounter']}'"); if ($arid) { $arinvoice = get_invoice_summary($arid, true); } } if ($arid) { $arlinkbeg = "<a href='../../billing/sl_eob_invoice.php?id=" . htmlspecialchars($arid, ENT_QUOTES) . "'" . " target='_blank' class='text' style='color:#00cc00'>"; $arlinkend = "</a>"; } } // Throw in product sales. $query = "SELECT s.drug_id, s.fee, d.name " . "FROM drug_sales AS s " . "LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " . "WHERE s.pid = ? AND s.encounter = ? " . "ORDER BY s.sale_id"; $sres = sqlStatement($query, array($pid, $result4['encounter']));
$stmt['to'][] = $row['street']; } $stmt['to'][] = $row['city'] . ", " . $row['state'] . " " . $row['postal_code']; $stmt['lines'] = array(); $stmt['amount'] = '0.00'; $stmt['today'] = $today; $stmt['duedate'] = $duedate; } else { // Report the oldest due date. if ($duedate < $stmt['duedate']) { $stmt['duedate'] = $duedate; } } // Recompute age at each invoice. $stmt['age'] = round((strtotime($today) - strtotime($stmt['duedate'])) / (24 * 60 * 60)); $invlines = ar_get_invoice_summary($row['pid'], $row['encounter'], true); foreach ($invlines as $key => $value) { $line = array(); $line['dos'] = $svcdate; $line['desc'] = $key == 'CO-PAY' ? "Patient Payment" : "Procedure {$key}"; $line['amount'] = sprintf("%.2f", $value['chg']); $line['adjust'] = sprintf("%.2f", $value['adj']); $line['paid'] = sprintf("%.2f", $value['chg'] - $value['bal']); $line['notice'] = $duncount + 1; $line['detail'] = $value['dtl']; $stmt['lines'][] = $line; $stmt['amount'] = sprintf("%.2f", $stmt['amount'] + $value['bal']); } // Record that this statement was run. if (!$DEBUG && !$_POST['form_without']) { sqlStatement("UPDATE form_encounter SET " . "last_stmt_date = '{$today}', stmt_count = stmt_count + 1 " . "WHERE id = " . $row['id']);
function era_callback(&$out) { global $encount, $debug, $claim_status_codes, $adjustment_reasons, $remark_codes; global $invoice_total, $last_code, $paydate, $INTEGRATED_AR; global $InsertionId; //last inserted ID of // Some heading information. $chk_123 = $out['check_number']; $chk_123 = str_replace(' ', '_', $chk_123); if (isset($_REQUEST['chk' . $chk_123])) { if ($encount == 0) { writeMessageLine('#ffffff', 'infdetail', "Payer: " . htmlspecialchars($out['payer_name'], ENT_QUOTES)); if ($debug) { writeMessageLine('#ffffff', 'infdetail', "WITHOUT UPDATE is selected; no changes will be applied."); } } $last_code = ''; $invoice_total = 0.0; $bgcolor = ++$encount & 1 ? "#ddddff" : "#ffdddd"; list($pid, $encounter, $invnumber) = slInvoiceNumber($out); // Get details, if we have them, for the invoice. $inverror = true; $codes = array(); if ($pid && $encounter) { // Get invoice data into $arrow or $ferow. if ($INTEGRATED_AR) { $ferow = sqlQuery("SELECT e.*, p.fname, p.mname, p.lname " . "FROM form_encounter AS e, patient_data AS p WHERE " . "e.pid = '{$pid}' AND e.encounter = '{$encounter}' AND " . "p.pid = e.pid"); if (empty($ferow)) { $pid = $encounter = 0; $invnumber = $out['our_claim_id']; } else { $inverror = false; $codes = ar_get_invoice_summary($pid, $encounter, true); // $svcdate = substr($ferow['date'], 0, 10); } } else { $arres = SLQuery("SELECT ar.id, ar.notes, ar.shipvia, customer.name " . "FROM ar, customer WHERE ar.invnumber = '{$invnumber}' AND " . "customer.id = ar.customer_id"); if ($sl_err) { die($sl_err); } $arrow = SLGetRow($arres, 0); if ($arrow) { $inverror = false; $codes = get_invoice_summary($arrow['id'], true); } else { // oops, no such invoice $pid = $encounter = 0; $invnumber = $out['our_claim_id']; } } // end not internal a/r } // Show the claim status. $csc = $out['claim_status_code']; $inslabel = 'Ins1'; if ($csc == '1' || $csc == '19') { $inslabel = 'Ins1'; } if ($csc == '2' || $csc == '20') { $inslabel = 'Ins2'; } if ($csc == '3' || $csc == '21') { $inslabel = 'Ins3'; } $primary = $inslabel == 'Ins1'; writeMessageLine($bgcolor, 'infdetail', "Claim status {$csc}: " . $claim_status_codes[$csc]); // Show an error message if the claim is missing or already posted. if ($inverror) { writeMessageLine($bgcolor, 'errdetail', "The following claim is not in our database"); } else { // Skip this test. Claims can get multiple CLPs from the same payer! // // $insdone = strtolower($arrow['shipvia']); // if (strpos($insdone, 'ins1') !== false) { // $inverror = true; // writeMessageLine($bgcolor, 'errdetail', // "Primary insurance EOB was already posted for the following claim"); // } } if ($csc == '4') { //Denial case, code is stored in the claims table for display in the billing manager screen with reason explained. $inverror = true; if (!$debug) { if ($pid && $encounter) { $code_value = ''; foreach ($out['svc'] as $svc) { foreach ($svc['adj'] as $adj) { //Per code and modifier the reason will be showed in the billing manager. $code_value .= $svc['code'] . '_' . $svc['mod'] . '_' . $adj['group_code'] . '_' . $adj['reason_code'] . ','; } } $code_value = substr($code_value, 0, -1); //We store the reason code to display it with description in the billing manager screen. //process_file is used as for the denial case file name will not be there, and extra field(to store reason) can be avoided. updateClaim(true, $pid, $encounter, $_REQUEST['InsId'], substr($inslabel, 3), 7, 0, $code_value); } } writeMessageLine($bgcolor, 'errdetail', "Not posting adjustments for denied claims, please follow up manually!"); } else { if ($csc == '22') { $inverror = true; writeMessageLine($bgcolor, 'errdetail', "Payment reversals are not automated, please enter manually!"); } } if ($out['warnings']) { writeMessageLine($bgcolor, 'infdetail', nl2br(rtrim($out['warnings']))); } // Simplify some claim attributes for cleaner code. $service_date = parse_date($out['dos']); $check_date = $paydate ? $paydate : parse_date($out['check_date']); $production_date = $paydate ? $paydate : parse_date($out['production_date']); if ($INTEGRATED_AR) { $insurance_id = arGetPayerID($pid, $service_date, substr($inslabel, 3)); if (empty($ferow['lname'])) { $patient_name = $out['patient_fname'] . ' ' . $out['patient_lname']; } else { $patient_name = $ferow['fname'] . ' ' . $ferow['lname']; } } else { $insurance_id = 0; foreach ($codes as $cdata) { if ($cdata['ins']) { $insurance_id = $cdata['ins']; break; } } $patient_name = $arrow['name'] ? $arrow['name'] : $out['patient_fname'] . ' ' . $out['patient_lname']; } $error = $inverror; // This loops once for each service item in this claim. foreach ($out['svc'] as $svc) { // Treat a modifier in the remit data as part of the procedure key. // This key will then make its way into SQL-Ledger. $codekey = $svc['code']; if ($svc['mod']) { $codekey .= ':' . $svc['mod']; } $prev = $codes[$codekey]; $codetype = ''; //will hold code type, if exists // This reports detail lines already on file for this service item. if ($prev) { $codetype = $codes[$codekey]['code_type']; //store code type writeOldDetail($prev, $patient_name, $invnumber, $service_date, $codekey, $bgcolor); // Check for sanity in amount charged. $prevchg = sprintf("%.2f", $prev['chg'] + $prev['adj']); if ($prevchg != abs($svc['chg'])) { writeMessageLine($bgcolor, 'errdetail', "EOB charge amount " . $svc['chg'] . " for this code does not match our invoice"); $error = true; } // Check for already-existing primary remittance activity. // Removed this check because it was not allowing for copays manually // entered into the invoice under a non-copay billing code. /**** if ((sprintf("%.2f",$prev['chg']) != sprintf("%.2f",$prev['bal']) || $prev['adj'] != 0) && $primary) { writeMessageLine($bgcolor, 'errdetail', "This service item already has primary payments and/or adjustments!"); $error = true; } ****/ unset($codes[$codekey]); } else { // This is not an error. If we are not in error mode and not debugging, // insert the service item into SL. Then display it (in green if it // was inserted, or in red if we are in error mode). $description = "CPT4:{$codekey} Added by {$inslabel} {$production_date}"; if (!$error && !$debug) { if ($INTEGRATED_AR) { arPostCharge($pid, $encounter, 0, $svc['chg'], 1, $service_date, $codekey, $description, $debug, '', $codetype); } else { slPostCharge($arrow['id'], $svc['chg'], 1, $service_date, $codekey, $insurance_id, $description, $debug); } $invoice_total += $svc['chg']; } $class = $error ? 'errdetail' : 'newdetail'; writeDetailLine($bgcolor, $class, $patient_name, $invnumber, $codekey, $production_date, $description, $svc['chg'], $error ? '' : $invoice_total); } $class = $error ? 'errdetail' : 'newdetail'; // Report Allowed Amount. if ($svc['allowed']) { // A problem here is that some payers will include an adjustment // reflecting the allowed amount, others not. So here we need to // check if the adjustment exists, and if not then create it. We // assume that any nonzero CO (Contractual Obligation) or PI // (Payer Initiated) adjustment is good enough. $contract_adj = sprintf("%.2f", $svc['chg'] - $svc['allowed']); foreach ($svc['adj'] as $adj) { if (($adj['group_code'] == 'CO' || $adj['group_code'] == 'PI') && $adj['amount'] != 0) { $contract_adj = 0; } } if ($contract_adj > 0) { $svc['adj'][] = array('group_code' => 'CO', 'reason_code' => 'A2', 'amount' => $contract_adj); } writeMessageLine($bgcolor, 'infdetail', 'Allowed amount is ' . sprintf("%.2f", $svc['allowed'])); } // Report miscellaneous remarks. if ($svc['remark']) { $rmk = $svc['remark']; writeMessageLine($bgcolor, 'infdetail', "{$rmk}: " . $remark_codes[$rmk]); } // Post and report the payment for this service item from the ERA. // By the way a 'Claim' level payment is probably going to be negative, // i.e. a payment reversal. if ($svc['paid']) { if (!$error && !$debug) { if ($INTEGRATED_AR) { arPostPayment($pid, $encounter, $InsertionId[$out['check_number']], $svc['paid'], $codekey, substr($inslabel, 3), $out['check_number'], $debug, '', $codetype); } else { slPostPayment($arrow['id'], $svc['paid'], $check_date, "{$inslabel}/" . $out['check_number'], $codekey, $insurance_id, $debug); } $invoice_total -= $svc['paid']; } $description = "{$inslabel}/" . $out['check_number'] . ' payment'; if ($svc['paid'] < 0) { $description .= ' reversal'; } writeDetailLine($bgcolor, $class, $patient_name, $invnumber, $codekey, $check_date, $description, 0 - $svc['paid'], $error ? '' : $invoice_total); } // Post and report adjustments from this ERA. Posted adjustment reasons // must be 25 characters or less in order to fit on patient statements. foreach ($svc['adj'] as $adj) { $description = $adj['reason_code'] . ': ' . $adjustment_reasons[$adj['reason_code']]; if ($adj['group_code'] == 'PR' || !$primary) { // Group code PR is Patient Responsibility. Enter these as zero // adjustments to retain the note without crediting the claim. if ($primary) { /**** $reason = 'Pt resp: '; // Reasons should be 25 chars or less. if ($adj['reason_code'] == '1') $reason = 'To deductible: '; else if ($adj['reason_code'] == '2') $reason = 'Coinsurance: '; else if ($adj['reason_code'] == '3') $reason = 'Co-pay: '; ****/ $reason = "{$inslabel} ptresp: "; // Reasons should be 25 chars or less. if ($adj['reason_code'] == '1') { $reason = "{$inslabel} dedbl: "; } else { if ($adj['reason_code'] == '2') { $reason = "{$inslabel} coins: "; } else { if ($adj['reason_code'] == '3') { $reason = "{$inslabel} copay: "; } } } } else { $reason = "{$inslabel} note " . $adj['reason_code'] . ': '; /**** $reason .= sprintf("%.2f", $adj['amount']); ****/ } $reason .= sprintf("%.2f", $adj['amount']); // Post a zero-dollar adjustment just to save it as a comment. if (!$error && !$debug) { if ($INTEGRATED_AR) { arPostAdjustment($pid, $encounter, $InsertionId[$out['check_number']], 0, $codekey, substr($inslabel, 3), $reason, $debug, '', $codetype); } else { slPostAdjustment($arrow['id'], 0, $production_date, $out['check_number'], $codekey, $insurance_id, $reason, $debug); } } writeMessageLine($bgcolor, $class, $description . ' ' . sprintf("%.2f", $adj['amount'])); } else { if (!$error && !$debug) { if ($INTEGRATED_AR) { arPostAdjustment($pid, $encounter, $InsertionId[$out['check_number']], $adj['amount'], $codekey, substr($inslabel, 3), "Adjust code " . $adj['reason_code'], $debug, '', $codetype); } else { slPostAdjustment($arrow['id'], $adj['amount'], $production_date, $out['check_number'], $codekey, $insurance_id, "{$inslabel} adjust code " . $adj['reason_code'], $debug); } $invoice_total -= $adj['amount']; } writeDetailLine($bgcolor, $class, $patient_name, $invnumber, $codekey, $production_date, $description, 0 - $adj['amount'], $error ? '' : $invoice_total); } } } // End of service item // Report any existing service items not mentioned in the ERA, and // determine if any of them are still missing an insurance response // (if so, then insurance is not yet done with the claim). $insurance_done = true; foreach ($codes as $code => $prev) { // writeOldDetail($prev, $arrow['name'], $invnumber, $service_date, $code, $bgcolor); writeOldDetail($prev, $patient_name, $invnumber, $service_date, $code, $bgcolor); $got_response = false; foreach ($prev['dtl'] as $ddata) { if ($ddata['pmt'] || $ddata['rsn']) { $got_response = true; } } if (!$got_response) { $insurance_done = false; } } // Cleanup: If all is well, mark Ins<x> done and check for secondary billing. if (!$error && !$debug && $insurance_done) { if ($INTEGRATED_AR) { $level_done = 0 + substr($inslabel, 3); if ($out['crossover'] == 1) { //Automatic forward case.So need not again bill from the billing manager screen. sqlStatement("UPDATE form_encounter " . "SET last_level_closed = {$level_done},last_level_billed=" . $level_done . " WHERE " . "pid = '{$pid}' AND encounter = '{$encounter}'"); writeMessageLine($bgcolor, 'infdetail', 'This claim is processed by Insurance ' . $level_done . ' and automatically forwarded to Insurance ' . ($level_done + 1) . ' for processing. '); } else { "UPDATE form_encounter " . "SET last_level_closed = {$level_done} WHERE " . "pid = '{$pid}' AND encounter = '{$encounter}'"; } // Check for secondary insurance. if ($primary && arGetPayerID($pid, $service_date, 2)) { arSetupSecondary($pid, $encounter, $debug, $out['crossover']); if ($out['crossover'] != 1) { writeMessageLine($bgcolor, 'infdetail', 'This claim is now re-queued for secondary paper billing'); } } } else { $shipvia = 'Done: Ins1'; if ($inslabel != 'Ins1') { $shipvia .= ',Ins2'; } if ($inslabel == 'Ins3') { $shipvia .= ',Ins3'; } $query = "UPDATE ar SET shipvia = '{$shipvia}' WHERE id = " . $arrow['id']; SLQuery($query); if ($sl_err) { die($sl_err); } // Check for secondary insurance. $insgot = strtolower($arrow['notes']); if ($primary && strpos($insgot, 'ins2') !== false) { slSetupSecondary($arrow['id'], $debug); if ($out['crossover'] != 1) { writeMessageLine($bgcolor, 'infdetail', 'This claim is now re-queued for secondary paper billing'); } } } } } }
if (!$INTEGRATED_AR) { SLClose(); } exit; } if ($INTEGRATED_AR) { /***************************************************************** $ferow = sqlQuery("SELECT e.*, p.fname, p.mname, p.lname " . "FROM form_encounter AS e, patient_data AS p WHERE " . "e.pid = '$patient_id' AND e.encounter = '$encounter_id' AND ". "p.pid = e.pid"); if (empty($ferow)) die("There is no encounter $patient_id.$encounter_id."); $svcdate = substr($ferow['date'], 0, 10); *****************************************************************/ // Get invoice charge details. $codes = ar_get_invoice_summary($patient_id, $encounter_id, true); } else { // Get invoice data into $arrow. $arres = SLQuery("select ar.*, customer.name, employee.name as doctor " . "from ar, customer, employee where ar.id = {$trans_id} and " . "customer.id = ar.customer_id and employee.id = ar.employee_id"); if ($sl_err) { die($sl_err); } $arrow = SLGetRow($arres, 0); if (!$arrow) { die(xl("There is no match for invoice id = ") . $trans_id); } // // Determine the date of service. An 8-digit encounter number is // presumed to be a date of service imported during conversion. // Otherwise look it up in the form_encounter table. //
function loadPayerInfo(&$billrow) { global $sl_err; $encounter_date = substr($this->encounter['date'], 0, 10); // Create the $payers array. This contains data for all insurances // with the current one always at index 0, and the others in payment // order starting at index 1. // $this->payers = array(); $this->payers[0] = array(); $query = "SELECT * FROM insurance_data WHERE " . "pid = '{$this->pid}' AND " . "date <= '{$encounter_date}' " . "ORDER BY type ASC, date DESC"; $dres = sqlStatement($query); $prevtype = ''; while ($drow = sqlFetchArray($dres)) { if (strcmp($prevtype, $drow['type']) == 0) { continue; } $prevtype = $drow['type']; // Very important to look at entries with a missing provider because // they indicate no insurance as of the given date. if (empty($drow['provider'])) { continue; } $ins = count($this->payers); if ($drow['provider'] == $billrow['payer_id'] && empty($this->payers[0]['data'])) { $ins = 0; } $crow = sqlQuery("SELECT * FROM insurance_companies WHERE " . "id = '" . $drow['provider'] . "'"); $orow = new InsuranceCompany($drow['provider']); $this->payers[$ins] = array(); $this->payers[$ins]['data'] = $drow; $this->payers[$ins]['company'] = $crow; $this->payers[$ins]['object'] = $orow; } // This kludge hands most cases of a rare ambiguous situation, where // the primary insurance company is the same as the secondary. It seems // nobody planned for that! // for ($i = 1; $i < count($this->payers); ++$i) { if ($billrow['process_date'] && $this->payers[0]['data']['provider'] == $this->payers[$i]['data']['provider']) { $tmp = $this->payers[0]; $this->payers[0] = $this->payers[$i]; $this->payers[$i] = $tmp; } } $this->using_modifiers = true; // Get payment and adjustment details if there are any previous payers. // $this->invoice = array(); if ($this->payerSequence() != 'P') { if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) { $this->invoice = ar_get_invoice_summary($this->pid, $this->encounter_id, true); } else { if ($GLOBALS['oer_config']['ws_accounting']['enabled']) { SLConnect(); $arres = SLQuery("select id from ar where invnumber = " . "'{$this->pid}.{$this->encounter_id}'"); if ($sl_err) { die($sl_err); } $arrow = SLGetRow($arres, 0); if ($arrow) { $this->invoice = get_invoice_summary($arrow['id'], true); } SLClose(); } } // Secondary claims might not have modifiers in SQL-Ledger data. // In that case, note that we should not try to match on them. $this->using_modifiers = false; foreach ($this->invoice as $key => $trash) { if (strpos($key, ':')) { $this->using_modifiers = true; } } } }
} $coded = ""; $arid = 0; if ($thisauth && $auth_sensitivity) { $binfo = array('', '', '', '', ''); if ($subresult2 = getBillingByEncounter($pid, $iter['encounter'], "code_type, code, modifier, code_text, fee")) { // Get A/R info, if available, for this encounter. $arinvoice = array(); $arlinkbeg = ""; $arlinkend = ""; if ($billing_view && $accounting_enabled) { if ($INTEGRATED_AR) { $tmp = sqlQuery("SELECT id FROM form_encounter WHERE " . "pid = ? AND encounter = ?", array($pid, $iter['encounter'])); $arid = 0 + $tmp['id']; if ($arid) { $arinvoice = ar_get_invoice_summary($pid, $iter['encounter'], true); } } else { $arid = SLQueryValue("SELECT id FROM ar WHERE invnumber = " . "'{$pid}.{$iter['encounter']}'"); if ($arid) { $arinvoice = get_invoice_summary($arid, true); } } if ($arid) { $arlinkbeg = "<a href='../../billing/sl_eob_invoice.php?id=" . htmlspecialchars($arid, ENT_QUOTES) . "'" . " target='_blank' class='text' style='color:#00cc00'>"; $arlinkend = "</a>"; } } // Throw in product sales. $query = "SELECT s.drug_id, s.fee, d.name " . "FROM drug_sales AS s " . "LEFT JOIN drugs AS d ON d.drug_id = s.drug_id " . "WHERE s.pid = ? AND s.encounter = ? " . "ORDER BY s.sale_id"; $sres = sqlStatement($query, array($pid, $iter['encounter']));