2 // Copyright (C) 2006-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 require_once("../globals.php");
10 require_once("$srcdir/acl.inc");
11 require_once("$srcdir/patient.inc");
12 require_once("$srcdir/forms.inc");
13 require_once("$srcdir/sl_eob.inc.php");
14 require_once("$srcdir/invoice_summary.inc.php");
15 require_once("../../custom/code_types.inc.php");
17 $INTEGRATED_AR = $GLOBALS['oer_config']['ws_accounting']['enabled'] === 2;
21 <?php
html_header_show();?
>
22 <link rel
='stylesheet' href
='<?php echo $css_header ?>' type
='text/css'>
25 // Format dollars for display.
27 function bucks($amount) {
29 $amount = sprintf("%.2f", $amount);
30 if ($amount != 0.00) return $amount;
35 // Get the co-pay amount that is effective on the given date.
36 // Or if no insurance on that date, return -1.
38 function getCopay($patient_id, $encdate) {
39 $tmp = sqlQuery("SELECT provider, copay FROM insurance_data " .
40 "WHERE pid = '$patient_id' AND type = 'primary' " .
41 "AND date <= '$encdate' ORDER BY date DESC LIMIT 1");
42 if ($tmp['provider']) return sprintf('%01.2f', 0 +
$tmp['copay']);
46 // Display a row of data for an encounter.
48 function echoLine($iname, $date, $charges, $ptpaid, $inspaid, $duept) {
49 $balance = bucks($charges - $ptpaid - $inspaid);
50 $getfrompt = ($duept > 0) ?
$duept : 0;
52 echo " <td class='detail'>$date</td>\n";
53 echo " <td class='detail' align='right'>" . bucks($charges) . "</td>\n";
54 echo " <td class='detail' align='right'>" . bucks($ptpaid) . "</td>\n";
55 echo " <td class='detail' align='right'>" . bucks($inspaid) . "</td>\n";
56 echo " <td class='detail' align='right'>$balance</td>\n";
57 echo " <td class='detail' align='right'>" . bucks($duept) . "</td>\n";
58 echo " <td class='detail' align='right'><input type='text' name='$iname' " .
59 "size='6' value='" . bucks($getfrompt) . "' onchange='calctotal()' " .
60 "onkeyup='calctotal()' /></td>\n";
64 // Post a payment to the payments table.
66 function frontPayment($patient_id, $encounter, $method, $source, $amount1, $amount2) {
68 $payid = sqlInsert("INSERT INTO payments ( " .
69 "pid, encounter, dtime, user, method, source, amount1, amount2 " .
74 "'" . $_SESSION['authUser'] . "', " .
83 // Get the patient's encounter ID for today, creating it if there is none.
84 // In the case of more than one encounter today, pick the last one.
86 function todaysEncounter($patient_id) {
89 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
90 "pid = '$patient_id' AND date = '$today 00:00:00' " .
91 "ORDER BY encounter DESC LIMIT 1");
93 if (!empty($tmprow['encounter'])) return $tmprow['encounter'];
95 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
96 "WHERE id = '" . $_SESSION["authUserID"] . "'");
97 $username = $tmprow['username'];
98 $facility = $tmprow['facility'];
99 $facility_id = $tmprow['facility_id'];
100 $conn = $GLOBALS['adodb']['db'];
101 $encounter = $conn->GenID("sequences");
102 addForm($encounter, "New Patient Encounter",
103 sqlInsert("INSERT INTO form_encounter SET " .
104 "date = '$today', " .
105 "onset_date = '$today', " .
106 "reason = 'Please indicate visit reason', " .
107 "facility = '$facility', " .
108 "facility_id = '$facility_id', " .
109 "pid = '$patient_id', " .
110 "encounter = '$encounter'"
112 "newpatient", $patient_id, "1", "NOW()", $username
117 // We use this to put dashes, colons, etc. back into a timestamp.
119 function decorateString($fmt, $str) {
122 $fc = substr($fmt, 0, 1);
123 $fmt = substr($fmt, 1);
125 $res .= substr($str, 0, 1);
126 $str = substr($str, 1);
134 // Compute taxes from a tax rate string and a possibly taxable amount.
136 function calcTaxes($row, $amount) {
138 if (empty($row['taxrates'])) return $total;
139 $arates = explode(':', $row['taxrates']);
140 if (empty($arates)) return $total;
141 foreach ($arates as $value) {
142 if (empty($value)) continue;
143 $trow = sqlQuery("SELECT option_value FROM list_options WHERE " .
144 "list_id = 'taxrate' AND option_id = '$value' LIMIT 1");
145 if (empty($trow['option_value'])) {
146 echo "<!-- Missing tax rate '$value'! -->\n";
149 $tax = sprintf("%01.2f", $amount * $trow['option_value']);
150 echo "<!-- Rate = '$value', amount = '$amount', tax = '$tax' -->\n";
156 $payment_methods = array(
166 $today = date('Y-m-d', $now);
167 $timestamp = date('Y-m-d H:i:s', $now);
169 if (!$INTEGRATED_AR) slInitialize();
171 // $patdata = getPatientData($pid, 'fname,lname,pubpid');
173 $patdata = sqlQuery("SELECT " .
174 "p.fname, p.mname, p.lname, p.pubpid, i.copay " .
175 "FROM patient_data AS p " .
176 "LEFT OUTER JOIN insurance_data AS i ON " .
177 "i.pid = p.pid AND i.type = 'primary' " .
178 "WHERE p.pid = '$pid' ORDER BY i.date DESC LIMIT 1");
180 $alertmsg = ''; // anything here pops up in an alert box
182 // If the Save button was clicked...
183 if ($_POST['form_save']) {
184 $form_pid = $_POST['form_pid'];
185 $form_method = trim($_POST['form_method']);
186 $form_source = trim($_POST['form_source']);
188 // Post payments for unbilled encounters. These go into the billing table.
189 if ($_POST['form_upay']) {
190 foreach ($_POST['form_upay'] as $enc => $payment) {
191 if ($amount = 0 +
$payment) {
192 if (!$enc) $enc = todaysEncounter($form_pid);
193 addBilling($enc, 'COPAY', sprintf('%.2f', $amount),
194 $form_method, $form_pid, 1, $_SESSION["authUserID"],
195 '', 1, 0 - $amount, '', '');
196 frontPayment($form_pid, $enc, $form_method, $form_source, $amount, 0);
201 // Post payments for previously billed encounters. These go to A/R.
202 if ($_POST['form_bpay']) {
203 foreach ($_POST['form_bpay'] as $enc => $payment) {
204 if ($amount = 0 +
$payment) {
205 if ($INTEGRATED_AR) {
208 $thissrc .= $form_method;
209 if ($form_source) $thissrc .= " $form_source";
211 $session_id = 0; // Is this OK?
212 arPostPayment($form_pid, $enc, $session_id, $amount, '', 0, $thissrc, 0);
217 $thissrc .= $form_method;
218 if ($form_source) $thissrc .= " $form_source";
220 $trans_id = SLQueryValue("SELECT id FROM ar WHERE " .
221 "ar.invnumber = '$form_pid.$enc' LIMIT 1");
222 if (! $trans_id) die("Cannot find invoice '$form_pid.$enc'!");
223 slPostPayment($trans_id, $amount, date('Y-m-d'), $thissrc,
226 frontPayment($form_pid, $enc, $form_method, $form_source, 0, $amount);
234 if ($_POST['form_save'] ||
$_REQUEST['receipt']) {
236 if ($_REQUEST['receipt']) {
237 $form_pid = $_GET['patient'];
238 $timestamp = decorateString('....-..-.. ..:..:..', $_GET['time']);
241 // Get details for what we guess is the primary facility.
242 $frow = sqlQuery("SELECT * FROM facility " .
243 "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
245 // Get the patient's name and chart number.
246 $patdata = getPatientData($form_pid, 'fname,mname,lname,pubpid');
248 // Re-fetch payment info.
249 $payrow = sqlQuery("SELECT " .
250 "SUM(amount1) AS amount1, " .
251 "SUM(amount2) AS amount2, " .
252 "MAX(method) AS method, " .
253 "MAX(source) AS source, " .
254 "MAX(dtime) AS dtime, " .
255 // "MAX(user) AS user " .
256 "MAX(user) AS user, " .
257 "MAX(encounter) as encounter ".
258 "FROM payments WHERE " .
259 "pid = '$form_pid' AND dtime = '$timestamp'");
261 // Create key for deleting, just in case.
262 $payment_key = $form_pid . '.' . preg_replace('/[^0-9]/', '', $timestamp);
264 // get facility from encounter
265 $tmprow = sqlQuery(sprintf("
268 WHERE encounter = '%s'",
271 $frow = sqlQuery(sprintf("SELECT * FROM facility " .
272 " WHERE id = '%s'",$tmprow['facility_id']));
274 // Now proceed with printing the receipt.
277 <title
><?php
xl('Receipt for Payment','e'); ?
></title
>
278 <script type
="text/javascript" src
="../../library/dialog.js"></script
>
279 <script language
="JavaScript">
281 <?php
require($GLOBALS['srcdir'] . "/restoreSession.php"); ?
>
283 // Process click on Print button.
285 var divstyle
= document
.getElementById('hideonprint').style
;
286 divstyle
.display
= 'none';
288 // divstyle.display = 'block';
290 // Process click on Delete button.
291 function deleteme() {
292 dlgopen('deleter.php?payment=<?php echo $payment_key ?>', '_blank', 500, 450);
295 // Called by the deleteme.php window on a successful delete.
296 function imdeleted() {
302 <body bgcolor
='#ffffff'>
305 <p
><h2
><?php
xl('Receipt for Payment','e'); ?
></h2
>
307 <p
><?php
echo htmlentities($frow['name']) ?
>
308 <br
><?php
echo htmlentities($frow['street']) ?
>
309 <br
><?php
echo htmlentities($frow['city'] . ', ' . $frow['state']) . ' ' .
310 $frow['postal_code'] ?
>
311 <br
><?php
echo htmlentities($frow['phone']) ?
>
314 <table border
='0' cellspacing
='8'>
316 <td
><?php
xl('Date','e'); ?
>:</td
>
317 <td
><?php
echo date('Y-m-d', strtotime($payrow['dtime'])) ?
></td
>
320 <td
><?php
xl('Patient','e'); ?
>:</td
>
321 <td
><?php
echo $patdata['fname'] . " " . $patdata['mname'] . " " .
322 $patdata['lname'] . " (" . $patdata['pubpid'] . ")" ?
></td
>
325 <td
><?php
xl('Paid Via','e'); ?
>:</td
>
326 <td
><?php
echo $payrow['method'] ?
></td
>
329 <td
><?php
xl('Check/Ref Number','e'); ?
>:</td
>
330 <td
><?php
echo $payrow['source'] ?
></td
>
333 <td
><?php
xl('Amount for This Visit','e'); ?
>:</td
>
334 <td
><?php
echo $payrow['amount1'] ?
></td
>
337 <td
><?php
xl('Amount for Past Balance','e'); ?
>:</td
>
338 <td
><?php
echo $payrow['amount2'] ?
></td
>
341 <td
><?php
xl('Received By','e'); ?
>:</td
>
342 <td
><?php
echo $payrow['user'] ?
></td
>
346 <div id
='hideonprint'>
348 <input type
='button' value
='<?php xl('Print','e
'); ?>' onclick
='printme()' />
350 <?php
if (acl_check('admin', 'super')) { ?
>
352 <input type
='button' value
='<?php xl('Delete
','e
'); ?>' style
='color:red' onclick
='deleteme()' />
361 // End of receipt printing logic.
365 // Here we display the form for data entry.
368 <title
><?php
xl('Record Payment','e'); ?
></title
>
370 <style type
="text/css">
371 body
{ font
-family
:sans
-serif
; font
-size
:10pt
; font
-weight
:normal
}
372 .dehead
{ color
:#000000; font-family:sans-serif; font-size:10pt; font-weight:bold }
373 .detail
{ color
:#000000; font-family:sans-serif; font-size:10pt; font-weight:normal }
376 <script type
="text/javascript" src
="../../library/topdialog.js"></script
>
377 <script type
="text/javascript" src
="../../library/dialog.js"></script
>
379 <script language
="JavaScript">
380 <?php
require($GLOBALS['srcdir'] . "/restoreSession.php"); ?
>
382 function calctotal() {
383 var f
= document
.forms
[0];
385 for (var i
= 0; i
< f
.elements
.length
; ++i
) {
386 var elem
= f
.elements
[i
];
387 var ename
= elem
.name
;
388 if (ename
.indexOf('form_upay[') == 0 || ename
.indexOf('form_bpay[') == 0) {
389 if (elem
.value
.length
> 0) total +
= Number(elem
.value
);
392 f
.form_paytotal
.value
= Number(total
).toFixed(2);
400 <body
class="body_top" onunload
='imclosing()'>
402 <form method
='post' action
='front_payment.php<?php if ($payid) echo "?payid=$payid"; ?>'
403 onsubmit
='return top.restoreSession()'>
404 <input type
='hidden' name
='form_pid' value
='<?php echo $pid ?>' />
408 <table border
='0' cellspacing
='8'>
411 <td colspan
='2' align
='center'>
413 <b
><?php
xl('Accept Payment for ','e','',' '); ?
><?php
echo $patdata['fname'] . " " .
414 $patdata['lname'] . " (" . $patdata['pubpid'] . ")" ?
></b
>
421 <?php
xl('Payment Method','e'); ?
>:
424 <select name
='form_method'>
426 foreach ($payment_methods as $value) {
427 echo " <option value='$value'";
428 if ($value == $payrow['method']) echo " selected";
429 echo ">$value</option>\n";
438 <?php
xl('Check/Reference Number','e'); ?
>:
441 <input type
='text' name
='form_source' size
='10' value
='<?php echo $payrow['source
'] ?>'>
447 <table border
='0' cellpadding
='2' cellspacing
='0' width
='98%'>
448 <tr bgcolor
="#cccccc">
450 <?php
xl('DOS','e')?
>
452 <td
class="dehead" align
="right">
453 <?php
xl('Charges','e')?
>
455 <td
class="dehead" align
="right">
456 <?php
xl('Pt Paid','e')?
> 
;
458 <td
class="dehead" align
="right">
459 <?php
xl('Insurance','e')?
>
461 <td
class="dehead" align
="right">
462 <?php
xl('Balance','e')?
>
464 <td
class="dehead" align
="right">
465 <?php
xl('Due Pt','e')?
>
467 <td
class="dehead" align
="right">
468 <?php
xl('Paying','e')?
>
475 // Get the unbilled service charges and payments by encounter for this patient.
477 $query = "SELECT b.encounter, b.code_type, b.code, b.modifier, b.fee, " .
478 "LEFT(fe.date, 10) AS encdate " .
479 "FROM billing AS b, form_encounter AS fe WHERE " .
480 "b.pid = '$pid' AND b.activity = 1 AND b.billed = 0 AND " .
481 "b.code_type != 'TAX' AND b.fee != 0 " .
482 "AND fe.pid = b.pid AND fe.encounter = b.encounter " .
483 "ORDER BY b.encounter";
484 $bres = sqlStatement($query);
486 while ($brow = sqlFetchArray($bres)) {
487 $key = 0 - $brow['encounter'];
488 if (empty($encs[$key])) {
490 'encounter' => $brow['encounter'],
491 'date' => $brow['encdate'],
495 if ($brow['code_type'] === 'COPAY') {
496 $encs[$key]['payments'] -= $brow['fee'];
498 $encs[$key]['charges'] +
= $brow['fee'];
500 $query = "SELECT taxrates FROM codes WHERE " .
501 "code_type = '" . $code_types[$brow['code_type']]['id'] . "' AND " .
502 "code = '" . $brow['code'] . "' AND ";
503 if ($brow['modifier']) {
504 $query .= "modifier = '" . $brow['modifier'] . "'";
506 $query .= "(modifier IS NULL OR modifier = '')";
508 $query .= " LIMIT 1";
509 $trow = sqlQuery($query);
510 $encs[$key]['charges'] +
= calcTaxes($trow, $brow['fee']);
514 // Do the same for unbilled product sales.
516 $query = "SELECT s.encounter, s.drug_id, s.fee, " .
517 "LEFT(fe.date, 10) AS encdate " .
518 "FROM drug_sales AS s, form_encounter AS fe " .
519 "WHERE s.pid = '$pid' AND s.billed = 0 AND s.fee != 0 " .
520 "AND fe.pid = s.pid AND fe.encounter = s.encounter " .
521 "ORDER BY s.encounter";
522 $dres = sqlStatement($query);
524 while ($drow = sqlFetchArray($dres)) {
525 $key = 0 - $drow['encounter'];
526 if (empty($encs[$key])) {
528 'encounter' => $drow['encounter'],
529 'date' => $drow['encdate'],
533 $encs[$key]['charges'] +
= $drow['fee'];
535 $trow = sqlQuery("SELECT taxrates FROM drug_templates WHERE drug_id = '" .
536 $drow['drug_id'] . "' ORDER BY selector LIMIT 1");
537 $encs[$key]['charges'] +
= calcTaxes($trow, $drow['fee']);
540 ksort($encs, SORT_NUMERIC
);
542 foreach ($encs as $key => $value) {
543 $enc = $value['encounter'];
544 $dispdate = $value['date'];
545 if (strcmp($dispdate, $today) == 0 && !$gottoday) {
546 $dispdate = xl('Today');
549 $inscopay = getCopay($pid, $value['date']);
550 $balance = bucks($value['charges'] - $value['payments']);
551 $duept = (($inscopay >= 0) ?
$inscopay : $value['charges']) - $value['payments'];
552 echoLine("form_upay[$enc]", $dispdate, $value['charges'],
553 $value['payments'], 0, $duept);
556 // If no billing was entered yet for today, then generate a line for
557 // entering today's co-pay.
560 $inscopay = getCopay($pid, $today);
561 $duept = ($inscopay >= 0) ?
$inscopay : 0;
562 echoLine("form_upay[0]", xl('Today'), 0, 0, 0, $duept);
565 // Now list previously billed visits.
567 if ($INTEGRATED_AR) {
568 $query = "SELECT f.id, f.pid, f.encounter, f.date, " .
569 "f.last_level_billed, f.last_level_closed, f.stmt_count, " .
570 "p.fname, p.mname, p.lname, p.pubpid, p.genericname2, p.genericval2, " .
571 "( SELECT SUM(s.fee) FROM drug_sales AS s WHERE " .
572 "s.pid = f.pid AND s.encounter = f.encounter AND s.billed != 0 ) AS sales, " .
573 "( SELECT SUM(b.fee) FROM billing AS b WHERE " .
574 "b.pid = f.pid AND b.encounter = f.encounter AND " .
575 "b.activity = 1 AND b.code_type != 'COPAY' AND b.billed != 0 ) AS charges, " .
576 "( SELECT SUM(b.fee) FROM billing AS b WHERE " .
577 "b.pid = f.pid AND b.encounter = f.encounter AND " .
578 "b.activity = 1 AND b.code_type = 'COPAY' AND b.billed != 0 ) AS copays, " .
579 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
580 "a.pid = f.pid AND a.encounter = f.encounter AND " .
581 "a.payer_type = 0 ) AS ptpaid, " .
582 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
583 "a.pid = f.pid AND a.encounter = f.encounter AND " .
584 "a.payer_type != 0 ) AS inspaid, " .
585 "( SELECT SUM(a.adj_amount) FROM ar_activity AS a WHERE " .
586 "a.pid = f.pid AND a.encounter = f.encounter ) AS adjustments " .
587 "FROM form_encounter AS f " .
588 "JOIN patient_data AS p ON p.pid = f.pid " .
589 "WHERE f.pid = '$pid' " .
590 "ORDER BY f.pid, f.encounter";
592 // Note that unlike the SQL-Ledger case, this query does not weed
593 // out encounters that are paid up. Also the use of sub-selects
594 // will require MySQL 4.1 or greater.
596 $ires = sqlStatement($query);
597 $num_invoices = mysql_num_rows($ires);
599 while ($irow = sqlFetchArray($ires)) {
600 $balance = $irow['charges'] +
$irow['sales'] +
$irow['copays']
601 - $irow['ptpaid'] - $irow['inspaid'] - $irow['adjustments'];
602 if (!$balance) continue;
604 $patient_id = $irow['pid'];
605 $enc = $irow['encounter'];
606 $svcdate = substr($irow['date'], 0, 10);
607 $duncount = $irow['stmt_count'];
609 for ($i = 1; $i <= 3 && arGetPayerID($irow['pid'], $irow['date'], $i); ++
$i) ;
610 $duncount = $irow['last_level_closed'] +
1 - $i;
613 $inspaid = $irow['inspaid'] +
$irow['adjustments'];
614 $ptpaid = $irow['ptpaid'] - $irow['copays'];
615 $duept = ($duncount < 0) ?
0 : $balance;
617 echoLine("form_bpay[$enc]", $svcdate, $irow['charges'] +
$irow['sales'],
618 $ptpaid, $inspaid, $duept);
620 } // end $INTEGRATED_AR
622 // Query for all open invoices.
623 $query = "SELECT ar.id, ar.invnumber, ar.amount, ar.paid, " .
624 "ar.intnotes, ar.notes, ar.shipvia, " .
625 "(SELECT SUM(invoice.sellprice * invoice.qty) FROM invoice WHERE " .
626 "invoice.trans_id = ar.id AND invoice.sellprice > 0) AS charges, " .
627 "(SELECT SUM(invoice.sellprice * invoice.qty) FROM invoice WHERE " .
628 "invoice.trans_id = ar.id AND invoice.sellprice < 0) AS adjustments, " .
629 "(SELECT SUM(acc_trans.amount) FROM acc_trans WHERE " .
630 "acc_trans.trans_id = ar.id AND acc_trans.chart_id = $chart_id_cash " .
631 "AND acc_trans.source NOT LIKE 'Ins%') AS ptpayments " .
632 "FROM ar WHERE ar.invnumber LIKE '$pid.%' AND " .
633 "ar.amount != ar.paid " .
634 "ORDER BY ar.invnumber";
635 $ires = SLQuery($query);
636 if ($sl_err) die($sl_err);
637 $num_invoices = SLRowCount($ires);
639 for ($ix = 0; $ix < $num_invoices; ++
$ix) {
640 $irow = SLGetRow($ires, $ix);
642 // Get encounter ID and date of service.
643 list($patient_id, $enc) = explode(".", $irow['invnumber']);
644 $tmp = sqlQuery("SELECT LEFT(date, 10) AS encdate FROM form_encounter " .
645 "WHERE encounter = '$enc'");
646 $svcdate = $tmp['encdate'];
648 // Compute $duncount as in sl_eob_search.php to determine if
649 // this invoice is at patient responsibility.
650 $duncount = substr_count(strtolower($irow['intnotes']), "statement sent");
652 $insgot = strtolower($irow['notes']);
653 $inseobs = strtolower($irow['shipvia']);
654 foreach (array('ins1', 'ins2', 'ins3') as $value) {
655 if (strpos($insgot, $value) !== false &&
656 strpos($inseobs, $value) === false)
661 $inspaid = $irow['paid'] +
$irow['ptpayments'] - $irow['adjustments'];
662 $balance = $irow['amount'] - $irow['paid'];
663 $duept = ($duncount < 0) ?
0 : $balance;
665 echoLine("form_bpay[$enc]", $svcdate, $irow['charges'],
666 0 - $irow['ptpayments'], $inspaid, $duept);
668 } // end not $INTEGRATED_AR
670 // Continue with display of the data entry form.
673 <tr bgcolor
="#cccccc">
674 <td
class="dehead" colspan
="6">
675 <?php
xl('Total Amount Paid','e')?
>
677 <td
class="dehead" align
="right">
678 <input type
='text' name
='form_paytotal' size
='6' value
=''
679 style
='color:#00aa00' readonly
/>
686 <input type
='submit' name
='form_save' value
='<?php xl('Save
','e
'); ?>' />  
;
687 <input type
='button' value
='<?php xl('Cancel
','e
'); ?>' onclick
='window.close()' />
691 <script language
="JavaScript">
698 if (!$INTEGRATED_AR) SLClose();