$id = $iter['id']; $modifier = trim($iter['mod']); if (!$cod0 && $code_types[$code_type]['fee'] == 1) { $mod0 = $modifier; $cod0 = $code; $ct0 = $code_type; } $units = max(1, intval(trim($iter['units']))); $fee = sprintf('%01.2f', (0 + trim($iter['price'])) * $units); if ($code_type == 'COPAY') { if ($id == '') { //adding new copay from fee sheet into ar_session and ar_activity tables if ($fee < 0) { $fee = $fee * -1; } $session_id = idSqlStatement("INSERT INTO ar_session(payer_id,user_id,pay_total,payment_type,description," . "patient_id,payment_method,adjustment_code,post_to_date) VALUES('0',?,?,'patient','COPAY',?,'','patient_payment',now())", array($_SESSION['authId'], $fee, $pid)); SqlStatement("INSERT INTO ar_activity (pid,encounter,code_type,code,modifier,payer_type,post_time,post_user,session_id," . "pay_amount,account_code) VALUES (?,?,?,?,?,0,now(),?,?,?,'PCP')", array($pid, $encounter, $ct0, $cod0, $mod0, $_SESSION['authId'], $session_id, $fee)); } else { //editing copay saved to ar_session and ar_activity if ($fee < 0) { $fee = $fee * -1; } $session_id = $id; $res_amount = sqlQuery("SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?", array($pid, $encounter, $session_id)); if ($fee != $res_amount['pay_amount']) { sqlStatement("UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?", array($_SESSION['authId'], $fee, $session_id)); sqlStatement("UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now()," . "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?", array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $pid, $encounter, $session_id)); } } if (!$cod0) { $copay_update = TRUE;
if ($_POST['form_amount']) { $amount = sprintf('%01.2f', trim($_POST['form_amount'])); $form_source = trim($_POST['form_source']); $paydesc = trim($_POST['form_method']); if ($INTEGRATED_AR) { //Fetching the existing code and modifier $ResultSearchNew = sqlStatement("SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key " . "WHERE code_types.ct_fee=1 AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier", array($form_pid, $form_encounter)); if ($RowSearch = sqlFetchArray($ResultSearchNew)) { $Code = $RowSearch['code']; $Modifier = $RowSearch['modifier']; } else { $Code = ''; $Modifier = ''; } $session_id = idSqlStatement("INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total," . " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) " . " VALUES ('0',?,?,now(),?,?,'','patient','COPAY',?,?,'patient_payment',now())", array($_SESSION['authId'], $form_source, $dosdate, $amount, $form_pid, $paydesc)); $insrt_id = idSqlStatement("INSERT INTO ar_activity (pid,encounter,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)" . " VALUES (?,?,?,?,0,?,?,?,?,'PCP')", array($form_pid, $form_encounter, $Code, $Modifier, $dosdate, $_SESSION['authId'], $session_id, $amount)); } else { $msg = invoice_add_line_item($invoice_info, 'COPAY', $paydesc, $form_source, 0 - $amount); if ($msg) { die($msg); } } } if (!$INTEGRATED_AR) { $msg = invoice_post($invoice_info); if ($msg) { die($msg); } } // If applicable, set the invoice reference number. $invoice_refno = '';
$QueryPart = "payer_id = '0', patient_id = '{$hidden_type_code}"; // Closing Quote in idSqlStatement below } $user_id = $_SESSION['authUserID']; $closed = 0; $modified_time = date('Y-m-d H:i:s'); $check_date = DateToYYYYMMDD(formData('check_date')); $deposit_date = DateToYYYYMMDD(formData('deposit_date')); $post_to_date = DateToYYYYMMDD(formData('post_to_date')); if ($post_to_date == '') { $post_to_date = date('Y-m-d'); } if (formData('deposit_date') == '') { $deposit_date = $post_to_date; } $payment_id = idSqlStatement("insert into ar_session set " . $QueryPart . "', user_id = '" . trim($user_id) . "', closed = '" . trim($closed) . "', reference = '" . trim(formData('check_number')) . "', check_date = '" . trim($check_date) . "', deposit_date = '" . trim($deposit_date) . "', pay_total = '" . trim(formData('payment_amount')) . "', modified_time = '" . trim($modified_time) . "', payment_type = '" . trim(formData('type_name')) . "', description = '" . trim(formData('description')) . "', adjustment_code = '" . trim(formData('adjustment_code')) . "', post_to_date = '" . trim($post_to_date) . "', payment_method = '" . trim(formData('payment_method')) . "'"); } //=============================================================================== //ar_activity addition code //=============================================================================== if ($mode == "PostPayments" || $mode == "FinishPayments") { $user_id = $_SESSION['authUserID']; $created_time = date('Y-m-d H:i:s'); for ($CountRow = 1;; $CountRow++) { if (isset($_POST["HiddenEncounter{$CountRow}"])) { DistributionInsert($CountRow, $created_time, $user_id); } else { break; } } if ($_REQUEST['global_amount'] == 'yes') {
} //---------------------------------------------------------------------------------------------------- if ($_REQUEST['radio_type_of_payment'] == 'copay') { $session_id = idSqlStatement("INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total," . " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) " . " VALUES ('0',?,?,now(),now(),?,'','patient','COPAY',?,?,'patient_payment',now())", array($_SESSION['authId'], $form_source, $amount, $form_pid, $form_method)); $insrt_id = idSqlStatement("INSERT INTO ar_activity (pid,encounter,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)" . " VALUES (?,?,?,?,0,now(),?,?,?,'PCP')", array($form_pid, $enc, $Code, $Modifier, $_SESSION['authId'], $session_id, $amount)); frontPayment($form_pid, $enc, $form_method, $form_source, $amount, 0); //insertion to 'payments' table. } if ($_REQUEST['radio_type_of_payment'] == 'invoice_balance' || $_REQUEST['radio_type_of_payment'] == 'cash') { //Payment by patient after insurance paid, cash patients similar to do not bill insurance in feesheet. if ($_REQUEST['radio_type_of_payment'] == 'cash') { sqlStatement("update form_encounter set last_level_closed=? where encounter=? and pid=? ", array(4, $enc, $form_pid)); sqlStatement("update billing set billed=? where encounter=? and pid=?", array(1, $enc, $form_pid)); } $adjustment_code = 'patient_payment'; $payment_id = idSqlStatement("insert into ar_session set " . "payer_id = ?" . ", patient_id = ?" . ", user_id = ?" . ", closed = ?" . ", reference = ?" . ", check_date = now() , deposit_date = now() " . ", pay_total = ?" . ", payment_type = 'patient'" . ", description = ?" . ", adjustment_code = ?" . ", post_to_date = now() " . ", payment_method = ?", array(0, $form_pid, $_SESSION['authUserID'], 0, $form_source, $amount, $NameNew, $adjustment_code, $form_method)); //-------------------------------------------------------------------------------------------------------------------- frontPayment($form_pid, $enc, $form_method, $form_source, 0, $amount); //insertion to 'payments' table. //-------------------------------------------------------------------------------------------------------------------- $resMoneyGot = sqlStatement("SELECT sum(pay_amount) as PatientPay FROM ar_activity where pid =? and " . "encounter =? and payer_type=0 and account_code='PCP'", array($form_pid, $enc)); //new fees screen copay gives account_code='PCP' $rowMoneyGot = sqlFetchArray($resMoneyGot); $Copay = $rowMoneyGot['PatientPay']; //-------------------------------------------------------------------------------------------------------------------- //Looping the existing code and modifier $ResultSearchNew = sqlStatement("SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key WHERE code_types.ct_fee=1 " . "AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier", array($form_pid, $enc)); while ($RowSearch = sqlFetchArray($ResultSearchNew)) { $Code = $RowSearch['code']; $Modifier = $RowSearch['modifier']; $Fee = $RowSearch['fee'];
function DistributionInsert($CountRow, $created_time, $user_id) { //Function inserts the distribution.Payment,Adjustment,Deductable,Takeback & Follow up reasons are inserted as seperate rows. //It automatically pushes to next insurance for billing. //In the screen a drop down of Ins1,Ins2,Ins3,Pat are given.The posting can be done for any level. $Affected = 'no'; if (isset($_POST["Payment{$CountRow}"]) && $_POST["Payment{$CountRow}"] * 1 > 0) { if (trim(formData('type_name')) == 'insurance') { if (trim(formData("HiddenIns{$CountRow}")) == 1) { $AccountCode = "IPP"; } if (trim(formData("HiddenIns{$CountRow}")) == 2) { $AccountCode = "ISP"; } if (trim(formData("HiddenIns{$CountRow}")) == 3) { $AccountCode = "ITP"; } } elseif (trim(formData('type_name')) == 'patient') { $AccountCode = "PP"; } sqlStatement("insert into ar_activity set " . "pid = '" . trim(formData('hidden_patient_code')) . "', encounter = '" . trim(formData("HiddenEncounter{$CountRow}")) . "', code = '" . trim(formData("HiddenCode{$CountRow}")) . "', modifier = '" . trim(formData("HiddenModifier{$CountRow}")) . "', payer_type = '" . trim(formData("HiddenIns{$CountRow}")) . "', post_time = '" . trim($created_time) . "', post_user = '******', session_id = '" . trim(formData('payment_id')) . "', modified_time = '" . trim($created_time) . "', pay_amount = '" . trim(formData("Payment{$CountRow}")) . "', adj_amount = '" . 0 . "', account_code = '" . "{$AccountCode}" . "'"); $Affected = 'yes'; } if (isset($_POST["AdjAmount{$CountRow}"]) && $_POST["AdjAmount{$CountRow}"] * 1 != 0) { if (trim(formData('type_name')) == 'insurance') { $AdjustString = "Ins adjust Ins" . trim(formData("HiddenIns{$CountRow}")); $AccountCode = "IA"; } elseif (trim(formData('type_name')) == 'patient') { $AdjustString = "Pt adjust"; $AccountCode = "PA"; } idSqlStatement("insert into ar_activity set " . "pid = '" . trim(formData('hidden_patient_code')) . "', encounter = '" . trim(formData("HiddenEncounter{$CountRow}")) . "', code = '" . trim(formData("HiddenCode{$CountRow}")) . "', modifier = '" . trim(formData("HiddenModifier{$CountRow}")) . "', payer_type = '" . trim(formData("HiddenIns{$CountRow}")) . "', post_time = '" . trim($created_time) . "', post_user = '******', session_id = '" . trim(formData('payment_id')) . "', modified_time = '" . trim($created_time) . "', pay_amount = '" . 0 . "', adj_amount = '" . trim(formData("AdjAmount{$CountRow}")) . "', memo = '" . "{$AdjustString}" . "', account_code = '" . "{$AccountCode}" . "'"); $Affected = 'yes'; } if (isset($_POST["Deductible{$CountRow}"]) && $_POST["Deductible{$CountRow}"] * 1 > 0) { idSqlStatement("insert into ar_activity set " . "pid = '" . trim(formData('hidden_patient_code')) . "', encounter = '" . trim(formData("HiddenEncounter{$CountRow}")) . "', code = '" . trim(formData("HiddenCode{$CountRow}")) . "', modifier = '" . trim(formData("HiddenModifier{$CountRow}")) . "', payer_type = '" . trim(formData("HiddenIns{$CountRow}")) . "', post_time = '" . trim($created_time) . "', post_user = '******', session_id = '" . trim(formData('payment_id')) . "', modified_time = '" . trim($created_time) . "', pay_amount = '" . 0 . "', adj_amount = '" . 0 . "', memo = '" . "Deductable \$" . trim(formData("Deductible{$CountRow}")) . "', account_code = '" . "Deduct" . "'"); $Affected = 'yes'; } if (isset($_POST["Takeback{$CountRow}"]) && $_POST["Takeback{$CountRow}"] * 1 > 0) { idSqlStatement("insert into ar_activity set " . "pid = '" . trim(formData('hidden_patient_code')) . "', encounter = '" . trim(formData("HiddenEncounter{$CountRow}")) . "', code = '" . trim(formData("HiddenCode{$CountRow}")) . "', modifier = '" . trim(formData("HiddenModifier{$CountRow}")) . "', payer_type = '" . trim(formData("HiddenIns{$CountRow}")) . "', post_time = '" . trim($created_time) . "', post_user = '******', session_id = '" . trim(formData('payment_id')) . "', modified_time = '" . trim($created_time) . "', pay_amount = '" . trim(formData("Takeback{$CountRow}")) * -1 . "', adj_amount = '" . 0 . "', account_code = '" . "Takeback" . "'"); $Affected = 'yes'; } if (isset($_POST["FollowUp{$CountRow}"]) && $_POST["FollowUp{$CountRow}"] == 'y') { idSqlStatement("insert into ar_activity set " . "pid = '" . trim(formData('hidden_patient_code')) . "', encounter = '" . trim(formData("HiddenEncounter{$CountRow}")) . "', code = '" . trim(formData("HiddenCode{$CountRow}")) . "', modifier = '" . trim(formData("HiddenModifier{$CountRow}")) . "', payer_type = '" . trim(formData("HiddenIns{$CountRow}")) . "', post_time = '" . trim($created_time) . "', post_user = '******', session_id = '" . trim(formData('payment_id')) . "', modified_time = '" . trim($created_time) . "', pay_amount = '" . 0 . "', adj_amount = '" . 0 . "', follow_up = '" . "y" . "', follow_up_note = '" . trim(formData("FollowUpReason{$CountRow}")) . "'"); $Affected = 'yes'; } if ($Affected == 'yes') { if (trim(formData('type_name')) != 'patient') { $ferow = sqlQuery("select last_level_closed from form_encounter where \n\t\tpid ='" . trim(formData('hidden_patient_code')) . "' and encounter='" . trim(formData("HiddenEncounter{$CountRow}")) . "'"); //multiple charges can come. if ($ferow['last_level_closed'] < trim(formData("HiddenIns{$CountRow}"))) { sqlStatement("update form_encounter set last_level_closed='" . trim(formData("HiddenIns{$CountRow}")) . "' where \n\t\t\tpid ='" . trim(formData('hidden_patient_code')) . "' and encounter='" . trim(formData("HiddenEncounter{$CountRow}")) . "'"); //last_level_closed gets increased. //----------------------------------- // Determine the next insurance level to be billed. $ferow = sqlQuery("SELECT date, last_level_closed " . "FROM form_encounter WHERE " . "pid = '" . trim(formData('hidden_patient_code')) . "' AND encounter = '" . trim(formData("HiddenEncounter{$CountRow}")) . "'"); $date_of_service = substr($ferow['date'], 0, 10); $new_payer_type = 0 + $ferow['last_level_closed']; if ($new_payer_type <= 3 && !empty($ferow['last_level_closed']) || $new_payer_type == 0) { ++$new_payer_type; } $new_payer_id = arGetPayerID(trim(formData('hidden_patient_code')), $date_of_service, $new_payer_type); if ($new_payer_id > 0) { arSetupSecondary(trim(formData('hidden_patient_code')), trim(formData("HiddenEncounter{$CountRow}")), 0); } //----------------------------------- } } } }
function slSetupSecondary($invid, $debug) { global $sl_err, $GLOBALS; if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) { die("Internal error calling slSetupSecondary()"); } $info_msg = ''; // Get some needed items from the SQL-Ledger invoice. $arres = SLQuery("select invnumber, transdate, customer_id, employee_id, " . "shipvia from ar where ar.id = {$invid}"); if ($sl_err) { die($sl_err); } $arrow = SLGetRow($arres, 0); if (!$arrow) { die(xl('There is no match for invoice id') . ' = ' . "{$trans_id}."); } $customer_id = $arrow['customer_id']; $date_of_service = $arrow['transdate']; list($trash, $encounter) = explode(".", $arrow['invnumber']); // Get the OpenEMR PID corresponding to the customer. $pdrow = sqlQuery("SELECT patient_data.pid " . "FROM integration_mapping, patient_data WHERE " . "integration_mapping.foreign_id = {$customer_id} AND " . "integration_mapping.foreign_table = 'customer' AND " . "patient_data.id = integration_mapping.local_id"); $pid = $pdrow['pid']; if (!$pid) { die(xl("Cannot find patient from SQL-Ledger customer id") . " = {$customer_id}."); } // Determine the ID of the next insurance company (if any) to be billed. $new_payer_id = -1; $new_payer_type = -1; $insdone = strtolower($arrow['shipvia']); foreach (array('ins1' => 'primary', 'ins2' => 'secondary', 'ins3' => 'tertiary') as $key => $value) { if (strpos($insdone, $key) === false) { $nprow = sqlQuery("SELECT provider FROM insurance_data WHERE " . "pid = '{$pid}' AND type = '{$value}' AND date <= '{$date_of_service}' " . "ORDER BY date DESC LIMIT 1"); if (!empty($nprow['provider'])) { $new_payer_id = $nprow['provider']; $new_payer_type = substr($key, 3); } break; } } // Find out if the encounter exists. $ferow = sqlQuery("SELECT pid FROM form_encounter WHERE " . "encounter = {$encounter}"); $encounter_pid = $ferow['pid']; // If it exists, just update the billing items. if ($encounter_pid) { if ($encounter_pid != $pid) { die(xl("Expected form_encounter.pid to be ") . $pid . ', ' . xl(' but was ') . $encounter_pid); } // If there's a payer ID queue it up, otherwise just reopen it. if ($new_payer_id > 0) { // TBD: implement a default bill_process and target in config.php, // it should not really be hard-coded here. if (!$debug) { updateClaim(true, $pid, $encounter, $new_payer_id, $new_payer_type, 1, 5, '', 'hcfa'); } } else { if (!$debug) { updateClaim(true, $pid, $encounter, -1, -1, 1, 0, ''); } } $info_msg = xl("Encounter ") . $encounter . xl(" is ready for re-billing."); return; } // If we get here then the encounter does not already exist. This should // only happen if A/R was converted from an earlier system. In this case // the encounter ID should be the date of service, and we will create the // encounter. // If it does not exist then it better be (or start with) a date. if (!preg_match("/^20\\d\\d\\d\\d\\d\\d/", $encounter)) { die(xl("Internal error: encounter '") . $encounter . xl("' should exist but does not.")); } $employee_id = $arrow['employee_id']; // Get the OpenEMR provider info corresponding to the SQL-Ledger salesman. $drrow = sqlQuery("SELECT users.id, users.username, users.facility_id " . "FROM integration_mapping, users WHERE " . "integration_mapping.foreign_id = {$employee_id} AND " . "integration_mapping.foreign_table = 'salesman' AND " . "users.id = integration_mapping.local_id"); $provider_id = $drrow['id']; if (!$provider_id) { die(xl("Cannot find provider from SQL-Ledger employee = ") . $employee_id); } if (!$date_of_service) { die(xl("Invoice has no date!")); } // Generate a new encounter number. $conn = $GLOBALS['adodb']['db']; $new_encounter = $conn->GenID("sequences"); // Create the "new encounter". $encounter_id = 0; $query = "INSERT INTO form_encounter ( " . "date, reason, facility_id, pid, encounter, onset_date, provider_id " . ") VALUES ( " . "'{$date_of_service}', " . "'" . xl('Imported from Accounting') . "', " . "'" . addslashes($drrow['facility_id']) . "', " . "{$pid}, " . "{$new_encounter}, " . "'{$date_of_service}', " . "'{$provider_id}' " . ")"; if ($debug) { echo $query . "<br>\n"; echo xl("Call to addForm() goes here.<br>") . "\n"; } else { $encounter_id = idSqlStatement($query); if (!$encounter_id) { die(xl("Insert failed: ") . $query); } addForm($new_encounter, xl("New Patient Encounter"), $encounter_id, "newpatient", $pid, 1, $date_of_service); $info_msg = xl("Encounter ") . $new_encounter . xl(" has been created. "); } // For each invoice line item with a billing code we will insert // a billing row with payer_id set to -1. Order the line items // chronologically so that each procedure code will be followed by // its associated icd9 code. $inres = SLQuery("SELECT * FROM invoice WHERE trans_id = {$invid} " . "ORDER BY id"); if ($sl_err) { die($sl_err); } // When nonzero, this will be the ID of a billing row that needs to // have its justify field set. $proc_ins_id = 0; for ($irow = 0; $irow < SLRowCount($inres); ++$irow) { $row = SLGetRow($inres, $irow); $amount = sprintf('%01.2f', $row['sellprice'] * $row['qty']); // Extract the billing code. $code = xl("Unknown"); if (preg_match("/([A-Za-z0-9]\\d\\d\\S*)/", $row['serialnumber'], $matches)) { $code = strtoupper($matches[1]); } else { if (preg_match("/([A-Za-z0-9]\\d\\d\\S*)/", $row['description'], $matches)) { $code = strtoupper($matches[1]); } } list($code, $modifier) = explode("-", $code); // Set the billing code type and description. $code_type = ""; $code_text = ""; foreach ($code_types as $key => $value) { if (preg_match("/{$key}/", $row['serialnumber'])) { $code_type = $key; if ($value['fee']) { $code_text = xl("Procedure") . " {$code}"; } else { $code_text = xl("Diagnosis") . " {$code}"; if ($proc_ins_id) { $query = "UPDATE billing SET justify = '{$code}' WHERE id = {$proc_ins_id}"; if ($debug) { echo $query . "<br>\n"; } else { sqlQuery($query); } $proc_ins_id = 0; } } break; } } // Skip adjustments. if (!$code_type) { continue; } // Insert the billing item. If this for a procedure code then save // the row ID so that we can update the "justify" field with the ICD9 // code, which should come next in the loop. // $query = "INSERT INTO billing ( " . "date, code_type, code, pid, provider_id, user, groupname, authorized, " . "encounter, code_text, activity, payer_id, billed, bill_process, " . "bill_date, modifier, units, fee, justify, target " . ") VALUES ( " . "NOW(), " . "'{$code_type}', " . "'{$code}', " . "{$pid}, " . "0, " . "'" . $_SESSION['authId'] . "', " . "'" . $_SESSION['authProvider'] . "', " . "1, " . "{$new_encounter}, " . "'{$code_text}', " . "1, " . "{$new_payer_id}, " . ($new_payer_id > 0 ? "1, " : "0, ") . ($new_payer_id > 0 ? "5, " : "0, ") . ($new_payer_id > 0 ? "NOW(), " : "NULL, ") . "'{$modifier}', " . "0, " . "{$amount}, " . "'', " . ($new_payer_id > 0 ? "'hcfa' " : "NULL ") . ")"; if ($debug) { echo $query . "<br>\n"; } else { $proc_ins_id = idSqlStatement($query); if ($code_type != "CPT4" && $code_type != "HCPCS") { $proc_ins_id = 0; } } } // Finally, change this invoice number to contain the new encounter number. // $new_invnumber = "{$pid}.{$new_encounter}"; $query = "UPDATE ar SET invnumber = '{$new_invnumber}' WHERE id = {$invid}"; if ($debug) { echo $query . "<br>\n"; } else { SLQuery($query); if ($sl_err) { die($sl_err); } $info_msg .= xl("This invoice number has been changed to ") . $new_invnumber; } return $info_msg; }
public function save(&$bill, &$prod, $main_provid = NULL, $main_supid = NULL, $default_warehouse = NULL, $mark_as_closed = false) { global $code_types; if (isset($main_provid) && $main_supid == $main_provid) { $main_supid = 0; } $copay_update = FALSE; $update_session_id = ''; $ct0 = ''; // takes the code type of the first fee type code type entry from the fee sheet, against which the copay is posted $cod0 = ''; // takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted $mod0 = ''; // takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted if (is_array($bill)) { foreach ($bill as $iter) { // Skip disabled (billed) line items. if (!empty($iter['billed'])) { continue; } $id = $iter['id']; $code_type = $iter['code_type']; $code = $iter['code']; $del = !empty($iter['del']); $units = empty($iter['units']) ? 1 : intval($iter['units']); $price = empty($iter['price']) ? 0 : 0 + trim($iter['price']); $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel']; $modifier = empty($iter['mod']) ? '' : trim($iter['mod']); $justify = empty($iter['justify']) ? '' : trim($iter['justify']); $notecodes = empty($iter['notecodes']) ? '' : trim($iter['notecodes']); $provid = empty($iter['provid']) ? 0 : intval($iter['provid']); $fee = sprintf('%01.2f', $price * $units); if (!$cod0 && $code_types[$code_type]['fee'] == 1) { $mod0 = $modifier; $cod0 = $code; $ct0 = $code_type; } if ($code_type == 'COPAY') { if ($fee < 0) { $fee = $fee * -1; } if (!$id) { // adding new copay from fee sheet into ar_session and ar_activity tables $session_id = idSqlStatement("INSERT INTO ar_session " . "(payer_id, user_id, pay_total, payment_type, description, patient_id, payment_method, " . "adjustment_code, post_to_date) " . "VALUES ('0',?,?,'patient','COPAY',?,'','patient_payment',now())", array($_SESSION['authId'], $fee, $this->pid)); sqlBeginTrans(); $sequence_no = sqlQuery("SELECT IFNULL(MAX(sequence_no),0) + 1 AS increment FROM ar_activity WHERE " . "pid = ? AND encounter = ?", array($this->pid, $this->encounter)); SqlStatement("INSERT INTO ar_activity (pid, encounter, sequence_no, code_type, code, modifier, " . "payer_type, post_time, post_user, session_id, " . "pay_amount, account_code) VALUES (?,?,?,?,?,?,0,now(),?,?,?,'PCP')", array($this->pid, $this->encounter, $sequence_no['increment'], $ct0, $cod0, $mod0, $_SESSION['authId'], $session_id, $fee)); sqlCommitTrans(); } else { // editing copay saved to ar_session and ar_activity $session_id = $id; $res_amount = sqlQuery("SELECT pay_amount FROM ar_activity WHERE pid=? AND encounter=? AND session_id=?", array($this->pid, $this->encounter, $session_id)); if ($fee != $res_amount['pay_amount']) { sqlStatement("UPDATE ar_session SET user_id=?,pay_total=?,modified_time=now(),post_to_date=now() WHERE session_id=?", array($_SESSION['authId'], $fee, $session_id)); sqlStatement("UPDATE ar_activity SET code_type=?, code=?, modifier=?, post_user=?, post_time=now()," . "pay_amount=?, modified_time=now() WHERE pid=? AND encounter=? AND account_code='PCP' AND session_id=?", array($ct0, $cod0, $mod0, $_SESSION['authId'], $fee, $this->pid, $this->encounter, $session_id)); } } if (!$cod0) { $copay_update = TRUE; $update_session_id = $session_id; } continue; } # Code to create justification for all codes based on first justification if ($GLOBALS['replicate_justification'] == '1') { if ($justify != '') { $autojustify = $justify; } } if ($GLOBALS['replicate_justification'] == '1' && $justify == '' && check_is_code_type_justify($code_type)) { $justify = $autojustify; } if ($justify) { $justify = str_replace(',', ':', $justify) . ':'; } $auth = "1"; $ndc_info = ''; if (!empty($iter['ndcnum'])) { $ndc_info = 'N4' . trim($iter['ndcnum']) . ' ' . $iter['ndcuom'] . trim($iter['ndcqty']); } // If the item is already in the database... if ($id) { if ($del) { $this->logFSMessage(xl('Service deleted')); deleteBilling($id); } else { $tmp = sqlQuery("SELECT * FROM billing WHERE id = ? AND (billed = 0 or billed is NULL) AND activity = 1", array($id)); if (!empty($tmp)) { $tmparr = array('code' => $code, 'authorized' => $auth); if (isset($iter['units'])) { $tmparr['units'] = $units; } if (isset($iter['price'])) { $tmparr['fee'] = $fee; } if (isset($iter['pricelevel'])) { $tmparr['pricelevel'] = $pricelevel; } if (isset($iter['mod'])) { $tmparr['modifier'] = $modifier; } if (isset($iter['provid'])) { $tmparr['provider_id'] = $provid; } if (isset($iter['ndcnum'])) { $tmparr['ndc_info'] = $ndc_info; } if (isset($iter['justify'])) { $tmparr['justify'] = $justify; } if (isset($iter['notecodes'])) { $tmparr['notecodes'] = $notecodes; } foreach ($tmparr as $key => $value) { if ($tmp[$key] != $value) { if ('fee' == $key) { $this->logFSMessage(xl('Price changed')); } if ('units' == $key) { $this->logFSMessage(xl('Quantity changed')); } if ('provider_id' == $key) { $this->logFSMessage(xl('Service provider changed')); } sqlStatement("UPDATE billing SET `{$key}` = ? WHERE id = ?", array($value, $id)); } } } } } else { if (!$del) { $this->logFSMessage(xl('Service added')); $code_text = lookup_code_descriptions($code_type . ":" . $code); addBilling($this->encounter, $code_type, $code, $code_text, $this->pid, $auth, $provid, $modifier, $units, $fee, $ndc_info, $justify, 0, $notecodes, $pricelevel); } } } } // end for // if modifier is not inserted during loop update the record using the first // non-empty modifier and code if ($copay_update == TRUE && $update_session_id != '' && $mod0 != '') { sqlStatement("UPDATE ar_activity SET code_type = ?, code = ?, modifier = ?" . " WHERE pid = ? AND encounter = ? AND account_code = 'PCP' AND session_id = ?", array($ct0, $cod0, $mod0, $this->pid, $this->encounter, $update_session_id)); } // Doing similarly to the above but for products. if (is_array($prod)) { foreach ($prod as $iter) { // Skip disabled (billed) line items. if (!empty($iter['billed'])) { continue; } $drug_id = $iter['drug_id']; $selector = empty($iter['selector']) ? '' : $iter['selector']; $sale_id = $iter['sale_id']; // present only if already saved $units = max(1, intval(trim($iter['units']))); $price = empty($iter['price']) ? 0 : 0 + trim($iter['price']); $pricelevel = empty($iter['pricelevel']) ? '' : $iter['pricelevel']; $fee = sprintf('%01.2f', $price * $units); $del = !empty($iter['del']); $rxid = 0; $warehouse_id = empty($iter['warehouse']) ? '' : $iter['warehouse']; $somechange = false; // If the item is already in the database... if ($sale_id) { $tmprow = sqlQuery("SELECT ds.prescription_id, ds.quantity, ds.inventory_id, ds.fee, " . "ds.sale_date, di.warehouse_id " . "FROM drug_sales AS ds " . "LEFT JOIN drug_inventory AS di ON di.inventory_id = ds.inventory_id " . "WHERE ds.sale_id = ?", array($sale_id)); $rxid = 0 + $tmprow['prescription_id']; if ($del) { if (!empty($tmprow)) { // Delete this sale and reverse its inventory update. $this->logFSMessage(xl('Product deleted')); sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id)); if (!empty($tmprow['inventory_id'])) { sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?", array($tmprow['quantity'], $tmprow['inventory_id'])); } } if ($rxid) { sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid)); } } else { // Modify the sale and adjust inventory accordingly. if (!empty($tmprow)) { foreach (array('quantity' => $units, 'fee' => $fee, 'pricelevel' => $pricelevel, 'selector' => $selector, 'sale_date' => $this->visit_date) as $key => $value) { if ($tmprow[$key] != $value) { $somechange = true; if ('fee' == $key) { $this->logFSMessage(xl('Price changed')); } if ('pricelevel' == $key) { $this->logFSMessage(xl('Price level changed')); } if ('selector' == $key) { $this->logFSMessage(xl('Template selector changed')); } if ('quantity' == $key) { $this->logFSMessage(xl('Quantity changed')); } sqlStatement("UPDATE drug_sales SET `{$key}` = ? WHERE sale_id = ?", array($value, $sale_id)); if ($key == 'quantity' && $tmprow['inventory_id']) { sqlStatement("UPDATE drug_inventory SET on_hand = on_hand - ? WHERE inventory_id = ?", array($units - $tmprow['quantity'], $tmprow['inventory_id'])); } } } if ($tmprow['inventory_id'] && $warehouse_id && $warehouse_id != $tmprow['warehouse_id']) { // Changing warehouse. Requires deleting and re-adding the sale. // Not setting $somechange because this alone does not affect a prescription. $this->logFSMessage(xl('Warehouse changed')); sqlStatement("DELETE FROM drug_sales WHERE sale_id = ?", array($sale_id)); sqlStatement("UPDATE drug_inventory SET on_hand = on_hand + ? WHERE inventory_id = ?", array($units, $tmprow['inventory_id'])); $tmpnull = null; $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter, empty($iter['rx']) ? 0 : $rxid, $this->visit_date, '', $warehouse_id, false, $tmpnull, $pricelevel, $selector); } } // Delete Rx if $rxid and flag not set. if ($GLOBALS['gbl_auto_create_rx'] && $rxid && empty($iter['rx'])) { sqlStatement("UPDATE drug_sales SET prescription_id = 0 WHERE sale_id = ?", array($sale_id)); sqlStatement("DELETE FROM prescriptions WHERE id = ?", array($rxid)); } } } else { if (!$del) { $somechange = true; $this->logFSMessage(xl('Product added')); $tmpnull = null; $sale_id = sellDrug($drug_id, $units, $fee, $this->pid, $this->encounter, 0, $this->visit_date, '', $warehouse_id, false, $tmpnull, $pricelevel, $selector); if (!$sale_id) { die(xlt("Insufficient inventory for product ID") . " \"" . text($drug_id) . "\"."); } } } // If a prescription applies, create or update it. if (!empty($iter['rx']) && !$del && ($somechange || empty($rxid))) { // If an active rx already exists for this drug and date we will // replace it, otherwise we'll make a new one. if (empty($rxid)) { $rxid = ''; } // Get default drug attributes; prefer the template with the matching selector. $drow = sqlQuery("SELECT dt.*, " . "d.name, d.form, d.size, d.unit, d.route, d.substitute " . "FROM drugs AS d, drug_templates AS dt WHERE " . "d.drug_id = ? AND dt.drug_id = d.drug_id " . "ORDER BY (dt.selector = ?) DESC, dt.quantity, dt.dosage, dt.selector LIMIT 1", array($drug_id, $selector)); if (!empty($drow)) { $rxobj = new Prescription($rxid); $rxobj->set_patient_id($this->pid); $rxobj->set_provider_id(isset($main_provid) ? $main_provid : $this->provider_id); $rxobj->set_drug_id($drug_id); $rxobj->set_quantity($units); $rxobj->set_per_refill($units); $rxobj->set_start_date_y(substr($this->visit_date, 0, 4)); $rxobj->set_start_date_m(substr($this->visit_date, 5, 2)); $rxobj->set_start_date_d(substr($this->visit_date, 8, 2)); $rxobj->set_date_added($this->visit_date); // Remaining attributes are the drug and template defaults. $rxobj->set_drug($drow['name']); $rxobj->set_unit($drow['unit']); $rxobj->set_dosage($drow['dosage']); $rxobj->set_form($drow['form']); $rxobj->set_refills($drow['refills']); $rxobj->set_size($drow['size']); $rxobj->set_route($drow['route']); $rxobj->set_interval($drow['period']); $rxobj->set_substitute($drow['substitute']); // $rxobj->persist(); // Set drug_sales.prescription_id to $rxobj->get_id(). $oldrxid = $rxid; $rxid = 0 + $rxobj->get_id(); if ($rxid != $oldrxid) { sqlStatement("UPDATE drug_sales SET prescription_id = ? WHERE sale_id = ?", array($rxid, $sale_id)); } } } } } // end for // Set default and/or supervising provider for the encounter. if (isset($main_provid) && $main_provid != $this->provider_id) { $this->logFSMessage(xl('Default provider changed')); sqlStatement("UPDATE form_encounter SET provider_id = ? WHERE pid = ? AND encounter = ?", array($main_provid, $this->pid, $this->encounter)); $this->provider_id = $main_provid; } if (isset($main_supid) && $main_supid != $this->supervisor_id) { sqlStatement("UPDATE form_encounter SET supervisor_id = ? WHERE pid = ? AND encounter = ?", array($main_supid, $this->pid, $this->encounter)); $this->supervisor_id = $main_supid; } // Save-and-Close is currently specific to Family Planning but might be more // generally useful. It provides the ability to mark an encounter as billed // directly from the Fee Sheet, if there are no charges. if ($mark_as_closed) { $tmp1 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM drug_sales WHERE " . "pid = ? AND encounter = ? AND billed = 0", array($this->pid, $this->encounter)); $tmp2 = sqlQuery("SELECT SUM(ABS(fee)) AS sum FROM billing WHERE " . "pid = ? AND encounter = ? AND billed = 0 AND activity = 1", array($this->pid, $this->encounter)); if ($tmp1['sum'] + $tmp2['sum'] == 0) { sqlStatement("update drug_sales SET billed = 1 WHERE " . "pid = ? AND encounter = ? AND billed = 0", array($this->pid, $this->encounter)); sqlStatement("UPDATE billing SET billed = 1, bill_date = NOW() WHERE " . "pid = ? AND encounter = ? AND billed = 0 AND activity = 1", array($this->pid, $this->encounter)); } else { // Would be good to display an error message here... they clicked // Save and Close but the close could not be done. However the // framework does not provide an easy way to do that. } } }
// $_POST["info"] = addslashes($_POST["info"]); $calvar = $_POST["calendar"] ? 1 : 0; $res = sqlStatement("select distinct username from users where username != ''"); $doit = true; while ($row = mysql_fetch_array($res)) { if ($doit == true && $row['username'] == trim(formData('rumple'))) { $doit = false; } } if ($doit == true) { //if password expiration option is enabled, calculate the expiration date of the password if ($GLOBALS['password_expiration_days'] != 0) { $exp_days = $GLOBALS['password_expiration_days']; $exp_date = date('Y-m-d', strtotime("+{$exp_days} days")); } $prov_id = idSqlStatement("insert into users set " . "username = '******'rumple')) . "', password = '******'newauthPass')) . "', fname = '" . trim(formData('fname')) . "', mname = '" . trim(formData('mname')) . "', lname = '" . trim(formData('lname')) . "', federaltaxid = '" . trim(formData('federaltaxid')) . "', authorized = '" . trim(formData('authorized')) . "', info = '" . trim(formData('info')) . "', federaldrugid = '" . trim(formData('federaldrugid')) . "', upin = '" . trim(formData('upin')) . "', npi = '" . trim(formData('npi')) . "', taxonomy = '" . trim(formData('taxonomy')) . "', facility_id = '" . trim(formData('facility_id')) . "', specialty = '" . trim(formData('specialty')) . "', see_auth = '" . trim(formData('see_auth')) . "', cal_ui = '" . trim(formData('cal_ui')) . "', default_warehouse = '" . trim(formData('default_warehouse')) . "', irnpool = '" . trim(formData('irnpool')) . "', calendar = '" . $calvar . "', pwd_expiration_date = '" . trim("{$exp_date}") . "'"); //set the facility name from the selected facility_id sqlStatement("UPDATE users, facility SET users.facility = facility.name WHERE facility.id = '" . trim(formData('facility_id')) . "' AND users.username = '******'rumple')) . "'"); sqlStatement("insert into groups set name = '" . trim(formData('groupname')) . "', user = '******'rumple')) . "'"); if (isset($phpgacl_location) && acl_check('admin', 'acl') && trim(formData('rumple'))) { // Set the access control group of user set_user_aro($_POST['access_group'], trim(formData('rumple')), trim(formData('fname')), trim(formData('mname')), trim(formData('lname'))); } $ws = new WSProvider($prov_id); } else { $alertmsg .= xl('User', '', '', ' ') . trim(formData('rumple')) . xl('already exists.', '', ' '); } if ($_POST['access_group']) { $bg_count = count($_POST['access_group']); for ($i = 0; $i < $bg_count; $i++) { if ($_POST['access_group'][$i] == "Emergency Login") {
$Code = ''; $Modifier = ''; } $strQuery1 = "INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total," . " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) " . " VALUES ('0',?,?,now(),now(),?,'','patient','COPAY',?,?,'patient_payment',now())"; $session_id = idSqlStatement($strQuery1, array($userId, $check_ref_number, $amount, $patient_id, $payment_type)); $insert_id = idSqlStatement("INSERT INTO ar_activity (pid,encounter,code_type,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)" . " VALUES (?,?,?,?,?,0,now(),?,?,?,'PCP')", array($patient_id, $visit_id, $Codetype, $Code, $Modifier, $userId, $session_id, $amount)); $result = frontPayment($patient_id, $visit_id, $payment_type, $payment_method, $amount, 0, $timestamp, $user); } if ($payment_type == 'invoice_balance' || $payment_type == 'cash') { if ($payment_type == 'cash') { sqlStatement("update form_encounter set last_level_closed=? where encounter=? and pid=? ", array(4, $visit_id, $patient_id)); sqlStatement("update billing set billed=? where encounter=? and pid=?", array(1, $visit_id, $patient_id)); } $adjustment_code = 'patient_payment'; $strQuery2 = "insert into ar_session set " . "payer_id = ?" . ", patient_id = ?" . ", user_id = ?" . ", closed = ?" . ", reference = ?" . ", check_date = now() , deposit_date = now() " . ", pay_total = ?" . ", payment_type = 'patient'" . ", description = ?" . ", adjustment_code = ?" . ", post_to_date = now() " . ", payment_method = ?"; $payment_id = idSqlStatement($strQuery2, array(0, $patient_id, $userId, 0, $check_ref_number, $amount, $NameNew, $adjustment_code, $payment_type)); $result = frontPayment($patient_id, $visit_id, $payment_type, $payment_method, 0, $amount, $timestamp, $user); //insertion to 'payments' table. $resMoneyGot = sqlStatement("SELECT sum(pay_amount) as PatientPay FROM ar_activity where pid =? and " . "encounter =? and payer_type=0 and account_code='PCP'", array($patient_id, $visit_id)); //new fees screen copay gives account_code='PCP' $rowMoneyGot = sqlFetchArray($resMoneyGot); $Copay = $rowMoneyGot['PatientPay']; $ResultSearchNew = sqlStatement("SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key WHERE code_types.ct_fee=1 " . "AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier", array($patient_id, $visit_id)); while ($RowSearch = sqlFetchArray($ResultSearchNew)) { $Codetype = $RowSearch['code_type']; $Code = $RowSearch['code']; $Modifier = $RowSearch['modifier']; $Fee = $RowSearch['fee']; $resMoneyGot = sqlStatement("SELECT sum(pay_amount) as MoneyGot FROM ar_activity where pid =? " . "and code_type=? and code=? and modifier=? and encounter =? and !(payer_type=0 and account_code='PCP')", array($patient_id, $Codetype, $Code, $Modifier, $visit_id)); $rowMoneyGot = sqlFetchArray($resMoneyGot); $MoneyGot = $rowMoneyGot['MoneyGot'];
sqlStatement($query, array($patientId, $visit_id, $userId, $time, $memo, $amount)); } if (!empty($charges)) { $amount = sprintf('%01.2f', trim($charges)); $ResultSearchNew = sqlStatement("SELECT * FROM billing LEFT JOIN code_types ON billing.code_type=code_types.ct_key " . "WHERE code_types.ct_fee=1 AND billing.activity!=0 AND billing.pid =? AND encounter=? ORDER BY billing.code,billing.modifier", array($patientId, $visit_id)); if ($RowSearch = sqlFetchArray($ResultSearchNew)) { $Codetype = $RowSearch['code_type']; $Code = $RowSearch['code']; $Modifier = $RowSearch['modifier']; } else { $Codetype = ''; $Code = ''; $Modifier = ''; } $session_id = idSqlStatement("INSERT INTO ar_session (payer_id,user_id,reference,check_date,deposit_date,pay_total," . " global_amount,payment_type,description,patient_id,payment_method,adjustment_code,post_to_date) " . " VALUES ('0',?,?,now(),?,?,'','patient','COPAY',?,?,'patient_payment',now())", array($user_id, $check_ref_number, $dosdate, $amount, $patientId, $paydesc)); $insrt_id = idSqlStatement("INSERT INTO ar_activity (pid,encounter,code_type,code,modifier,payer_type,post_time,post_user,session_id,pay_amount,account_code)" . " VALUES (?,?,?,?,?,0,?,?,?,?,'PCP')", array($patientId, $visit_id, $Codetype, $Code, $Modifier, $dosdate, $userId, $session_id, $amount)); } if ($insrt_id) { $xml_string .= "<status>0</status>"; $xml_string .= "<reason>The Checkout has been added.</reason>"; } else { $xml_string .= "<status>-1</status>"; $xml_string .= "<reason>ERROR: Sorry, there was an error processing your data. Please re-submit the information again.</reason>"; } } else { $xml_array['status'] = -2; $xml_array['reason'] = 'You are not Authorized to perform this action'; } } else { $xml_string .= "<status>-2</status>"; $xml_string .= "<reason>Invalid Token</reason>";
//takes the code of the first fee type code type entry from the fee sheet, against which the copay is posted $mod0 = ''; //takes the modifier of the first fee type code type entry from the fee sheet, against which the copay is posted $fee = sprintf('%01.2f', (0 + trim($price)) * $units); if ($fee < 0) { $fee = $fee * -1; } if ($userId = validateToken($token)) { $user = getUsername($userId); $acl_allow = acl_check('acct', 'bill', $user); $_SESSION['authProvider'] = getAuthGroup($user); $_SESSION['authId'] = $userId; if ($acl_allow) { if ($code_type == 'COPAY') { $strQuery3 = "INSERT INTO ar_session(payer_id,user_id,pay_total,payment_type,description," . "patient_id,payment_method,adjustment_code,post_to_date)" . "VALUES('0',?,?,'patient','COPAY',?,'','patient_payment',now())"; $session_id = idSqlStatement($strQuery3, array($auth, $fee, $patientId)); $getCode = "SELECT * FROM `billing` WHERE pid = ? AND encounter = ? ORDER BY `billing`.`encounter` ASC LIMIT 1"; $res = sqlQuery($getCode, array($patientId, $visit_id)); if ($res) { $cod0 = $res['code']; $ct0 = $res['code_type']; $mod0 = $res['modifier']; $strQuery4 = "INSERT INTO ar_activity (pid,encounter,code_type,code,modifier,payer_type," . "post_time,post_user,session_id,pay_amount,account_code) " . "VALUES (?,?,?,?,?,0,now(),?,?,?,'PCP')"; $result3 = SqlStatement($strQuery4, array($patientId, $visit_id, $ct0, $cod0, $mod0, $auth, $session_id, $fee)); } } else { addBilling($visit_id, $code_type, $code, $code_text, $patientId, $auth, $provider_id, $modifier, $units, $fee, $ndc_info, $justify, 0, $noteCodes); } $strQuery1 = 'UPDATE `patient_data` SET'; $strQuery1 .= ' pricelevel = "' . add_escape_custom($priceLevel) . '"'; $strQuery1 .= ' WHERE pid = ?';