fixing a bunch of undefined variables
[openemr.git] / interface / patient_file / front_payment.php
bloba1627800c02d1f336a36bd8235763e3a6278e860
1 <?php
2 // Copyright (C) 2006-2010 Rod Roark <rod@sunsetsystems.com>
3 //
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");
16 require_once("$srcdir/formatting.inc.php");
18 $INTEGRATED_AR = $GLOBALS['oer_config']['ws_accounting']['enabled'] === 2;
20 <html>
21 <head>
22 <?php html_header_show();?>
23 <link rel='stylesheet' href='<?php echo $css_header ?>' type='text/css'>
24 <?php
26 // Format dollars for display.
28 function bucks($amount) {
29 if ($amount) {
30 $amount = oeFormatMoney($amount);
31 return $amount;
33 return '';
36 function rawbucks($amount) {
37 if ($amount) {
38 $amount = sprintf("%.2f", $amount);
39 return $amount;
41 return '';
44 // Get the co-pay amount that is effective on the given date.
45 // Or if no insurance on that date, return -1.
47 function getCopay($patient_id, $encdate) {
48 $tmp = sqlQuery("SELECT provider, copay FROM insurance_data " .
49 "WHERE pid = '$patient_id' AND type = 'primary' " .
50 "AND date <= '$encdate' ORDER BY date DESC LIMIT 1");
51 if ($tmp['provider']) return sprintf('%01.2f', 0 + $tmp['copay']);
52 return -1;
55 // Display a row of data for an encounter.
57 function echoLine($iname, $date, $charges, $ptpaid, $inspaid, $duept) {
58 $balance = bucks($charges - $ptpaid - $inspaid);
59 $getfrompt = ($duept > 0) ? $duept : 0;
60 echo " <tr>\n";
61 echo " <td class='detail'>" . oeFormatShortDate($date) . "</td>\n";
62 echo " <td class='detail' align='right'>" . bucks($charges) . "</td>\n";
63 echo " <td class='detail' align='right'>" . bucks($ptpaid) . "</td>\n";
64 echo " <td class='detail' align='right'>" . bucks($inspaid) . "</td>\n";
65 echo " <td class='detail' align='right'>$balance</td>\n";
66 echo " <td class='detail' align='right'>" . bucks($duept) . "</td>\n";
67 echo " <td class='detail' align='right'><input type='text' name='$iname' " .
68 "size='6' value='" . rawbucks($getfrompt) . "' onchange='calctotal()' " .
69 "onkeyup='calctotal()' /></td>\n";
70 echo " </tr>\n";
73 // Post a payment to the payments table.
75 function frontPayment($patient_id, $encounter, $method, $source, $amount1, $amount2) {
76 global $timestamp;
77 $payid = sqlInsert("INSERT INTO payments ( " .
78 "pid, encounter, dtime, user, method, source, amount1, amount2 " .
79 ") VALUES ( " .
80 "'$patient_id', " .
81 "'$encounter', " .
82 "'$timestamp', " .
83 "'" . $_SESSION['authUser'] . "', " .
84 "'$method', " .
85 "'$source', " .
86 "'$amount1', " .
87 "'$amount2' " .
88 ")");
89 return $payid;
92 // Get the patient's encounter ID for today, if it exists.
93 // In the case of more than one encounter today, pick the last one.
95 function todaysEncounterIf($patient_id) {
96 global $today;
97 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
98 "pid = '$patient_id' AND date = '$today 00:00:00' " .
99 "ORDER BY encounter DESC LIMIT 1");
100 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
103 // Get the patient's encounter ID for today, creating it if there is none.
105 function todaysEncounter($patient_id) {
106 global $today;
108 $encounter = todaysEncounterIf($patient_id);
109 if ($encounter) return $encounter;
111 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
112 "WHERE id = '" . $_SESSION["authUserID"] . "'");
113 $username = $tmprow['username'];
114 $facility = $tmprow['facility'];
115 $facility_id = $tmprow['facility_id'];
116 $conn = $GLOBALS['adodb']['db'];
117 $encounter = $conn->GenID("sequences");
118 addForm($encounter, "New Patient Encounter",
119 sqlInsert("INSERT INTO form_encounter SET " .
120 "date = '$today', " .
121 "onset_date = '$today', " .
122 "reason = 'Please indicate visit reason', " .
123 "facility = '$facility', " .
124 "facility_id = '$facility_id', " .
125 "pid = '$patient_id', " .
126 "encounter = '$encounter'"
128 "newpatient", $patient_id, "1", "NOW()", $username
130 return $encounter;
133 // We use this to put dashes, colons, etc. back into a timestamp.
135 function decorateString($fmt, $str) {
136 $res = '';
137 while ($fmt) {
138 $fc = substr($fmt, 0, 1);
139 $fmt = substr($fmt, 1);
140 if ($fc == '.') {
141 $res .= substr($str, 0, 1);
142 $str = substr($str, 1);
143 } else {
144 $res .= $fc;
147 return $res;
150 // Compute taxes from a tax rate string and a possibly taxable amount.
152 function calcTaxes($row, $amount) {
153 $total = 0;
154 if (empty($row['taxrates'])) return $total;
155 $arates = explode(':', $row['taxrates']);
156 if (empty($arates)) return $total;
157 foreach ($arates as $value) {
158 if (empty($value)) continue;
159 $trow = sqlQuery("SELECT option_value FROM list_options WHERE " .
160 "list_id = 'taxrate' AND option_id = '$value' LIMIT 1");
161 if (empty($trow['option_value'])) {
162 echo "<!-- Missing tax rate '$value'! -->\n";
163 continue;
165 $tax = sprintf("%01.2f", $amount * $trow['option_value']);
166 // echo "<!-- Rate = '$value', amount = '$amount', tax = '$tax' -->\n";
167 $total += $tax;
169 return $total;
172 $payment_methods = array(
173 xl('Cash'),
174 xl('Check'),
175 xl('MC'),
176 xl('VISA'),
177 xl('AMEX'),
178 xl('DISC'),
179 xl('Other'));
181 $now = time();
182 $today = date('Y-m-d', $now);
183 $timestamp = date('Y-m-d H:i:s', $now);
185 if (!$INTEGRATED_AR) slInitialize();
187 // $patdata = getPatientData($pid, 'fname,lname,pubpid');
189 $patdata = sqlQuery("SELECT " .
190 "p.fname, p.mname, p.lname, p.pubpid, i.copay " .
191 "FROM patient_data AS p " .
192 "LEFT OUTER JOIN insurance_data AS i ON " .
193 "i.pid = p.pid AND i.type = 'primary' " .
194 "WHERE p.pid = '$pid' ORDER BY i.date DESC LIMIT 1");
196 $alertmsg = ''; // anything here pops up in an alert box
198 // If the Save button was clicked...
199 if ($_POST['form_save']) {
200 $form_pid = $_POST['form_pid'];
201 $form_method = trim($_POST['form_method']);
202 $form_source = trim($_POST['form_source']);
204 // Post payments for unbilled encounters. These go into the billing table.
205 if ($_POST['form_upay']) {
206 foreach ($_POST['form_upay'] as $enc => $payment) {
207 if ($amount = 0 + $payment) {
208 if (!$enc) $enc = todaysEncounter($form_pid);
209 addBilling($enc, 'COPAY', sprintf('%.2f', $amount),
210 $form_method, $form_pid, 1, $_SESSION["authUserID"],
211 '', 1, 0 - $amount, '', '');
212 frontPayment($form_pid, $enc, $form_method, $form_source, $amount, 0);
217 // Post payments for previously billed encounters. These go to A/R.
218 if ($_POST['form_bpay']) {
219 foreach ($_POST['form_bpay'] as $enc => $payment) {
220 if ($amount = 0 + $payment) {
221 if ($INTEGRATED_AR) {
222 $thissrc = '';
223 if ($form_method) {
224 $thissrc .= $form_method;
225 if ($form_source) $thissrc .= " $form_source";
227 $session_id = 0; // Is this OK?
228 arPostPayment($form_pid, $enc, $session_id, $amount, '', 0, $thissrc, 0);
230 else {
231 $thissrc = 'Pt/';
232 if ($form_method) {
233 $thissrc .= $form_method;
234 if ($form_source) $thissrc .= " $form_source";
236 $trans_id = SLQueryValue("SELECT id FROM ar WHERE " .
237 "ar.invnumber = '$form_pid.$enc' LIMIT 1");
238 if (! $trans_id) die("Cannot find invoice '$form_pid.$enc'!");
239 slPostPayment($trans_id, $amount, date('Y-m-d'), $thissrc,
240 '', 0, 0);
242 frontPayment($form_pid, $enc, $form_method, $form_source, 0, $amount);
249 <?php
250 if ($_POST['form_save'] || $_REQUEST['receipt']) {
252 if ($_REQUEST['receipt']) {
253 $form_pid = $_GET['patient'];
254 $timestamp = decorateString('....-..-.. ..:..:..', $_GET['time']);
257 // Get details for what we guess is the primary facility.
258 $frow = sqlQuery("SELECT * FROM facility " .
259 "ORDER BY billing_location DESC, accepts_assignment DESC, id LIMIT 1");
261 // Get the patient's name and chart number.
262 $patdata = getPatientData($form_pid, 'fname,mname,lname,pubpid');
264 // Re-fetch payment info.
265 $payrow = sqlQuery("SELECT " .
266 "SUM(amount1) AS amount1, " .
267 "SUM(amount2) AS amount2, " .
268 "MAX(method) AS method, " .
269 "MAX(source) AS source, " .
270 "MAX(dtime) AS dtime, " .
271 // "MAX(user) AS user " .
272 "MAX(user) AS user, " .
273 "MAX(encounter) as encounter ".
274 "FROM payments WHERE " .
275 "pid = '$form_pid' AND dtime = '$timestamp'");
277 // Create key for deleting, just in case.
278 $payment_key = $form_pid . '.' . preg_replace('/[^0-9]/', '', $timestamp);
280 // get facility from encounter
281 $tmprow = sqlQuery(sprintf("
282 SELECT facility_id
283 FROM form_encounter
284 WHERE encounter = '%s'",
285 $payrow['encounter']
287 $frow = sqlQuery(sprintf("SELECT * FROM facility " .
288 " WHERE id = '%s'",$tmprow['facility_id']));
290 // Now proceed with printing the receipt.
293 <title><?php xl('Receipt for Payment','e'); ?></title>
294 <script type="text/javascript" src="../../library/dialog.js"></script>
295 <script language="JavaScript">
297 <?php require($GLOBALS['srcdir'] . "/restoreSession.php"); ?>
299 // Process click on Print button.
300 function printme() {
301 var divstyle = document.getElementById('hideonprint').style;
302 divstyle.display = 'none';
303 window.print();
304 // divstyle.display = 'block';
306 // Process click on Delete button.
307 function deleteme() {
308 dlgopen('deleter.php?payment=<?php echo $payment_key ?>', '_blank', 500, 450);
309 return false;
311 // Called by the deleteme.php window on a successful delete.
312 function imdeleted() {
313 window.close();
316 // Called to switch to the specified encounter having the specified DOS.
317 // This also closes the popup window.
318 function toencounter(enc, datestr, topframe) {
319 topframe.restoreSession();
320 <?php if ($GLOBALS['concurrent_layout']) { ?>
321 // Hard-coding of RBot for this purpose is awkward, but since this is a
322 // pop-up and our openemr is left_nav, we have no good clue as to whether
323 // the top frame is more appropriate.
324 topframe.left_nav.forceDual();
325 topframe.left_nav.setEncounter(datestr, enc, '');
326 topframe.left_nav.setRadio('RBot', 'enc');
327 topframe.left_nav.loadFrame('enc2', 'RBot', 'patient_file/encounter/encounter_top.php?set_encounter=' + enc);
328 <?php } else { ?>
329 topframe.Title.location.href = 'encounter/encounter_title.php?set_encounter=' + enc;
330 topframe.Main.location.href = 'encounter/patient_encounter.php?set_encounter=' + enc;
331 <?php } ?>
332 window.close();
335 </script>
336 </head>
337 <body bgcolor='#ffffff'>
338 <center>
340 <p><h2><?php xl('Receipt for Payment','e'); ?></h2>
342 <p><?php echo htmlentities($frow['name']) ?>
343 <br><?php echo htmlentities($frow['street']) ?>
344 <br><?php echo htmlentities($frow['city'] . ', ' . $frow['state']) . ' ' .
345 $frow['postal_code'] ?>
346 <br><?php echo htmlentities($frow['phone']) ?>
349 <table border='0' cellspacing='8'>
350 <tr>
351 <td><?php xl('Date','e'); ?>:</td>
352 <td><?php echo oeFormatSDFT(strtotime($payrow['dtime'])) ?></td>
353 </tr>
354 <tr>
355 <td><?php xl('Patient','e'); ?>:</td>
356 <td><?php echo $patdata['fname'] . " " . $patdata['mname'] . " " .
357 $patdata['lname'] . " (" . $patdata['pubpid'] . ")" ?></td>
358 </tr>
359 <tr>
360 <td><?php xl('Paid Via','e'); ?>:</td>
361 <td><?php echo $payrow['method'] ?></td>
362 </tr>
363 <tr>
364 <td><?php xl('Check/Ref Number','e'); ?>:</td>
365 <td><?php echo $payrow['source'] ?></td>
366 </tr>
367 <tr>
368 <td><?php xl('Amount for This Visit','e'); ?>:</td>
369 <td><?php echo oeFormatMoney($payrow['amount1']) ?></td>
370 </tr>
371 <tr>
372 <td><?php xl('Amount for Past Balance','e'); ?>:</td>
373 <td><?php echo oeFormatMoney($payrow['amount2']) ?></td>
374 </tr>
375 <tr>
376 <td><?php xl('Received By','e'); ?>:</td>
377 <td><?php echo $payrow['user'] ?></td>
378 </tr>
379 </table>
381 <div id='hideonprint'>
383 <input type='button' value='<?php xl('Print','e'); ?>' onclick='printme()' />
385 <?php
386 $todaysenc = todaysEncounterIf($pid);
387 if ($todaysenc && $todaysenc != $encounter) {
388 echo "&nbsp;<input type='button' " .
389 "value='" . htmlspecialchars(xl('Open Today`s Visit')) . "' " .
390 "onclick='toencounter($todaysenc,\"$today\",opener.top)' />\n";
394 <?php if (acl_check('admin', 'super')) { ?>
395 &nbsp;
396 <input type='button' value='<?php xl('Delete','e'); ?>' style='color:red' onclick='deleteme()' />
397 <?php } ?>
399 </div>
400 </center>
401 </body>
403 <?php
405 // End of receipt printing logic.
407 } else {
409 // Here we display the form for data entry.
412 <title><?php xl('Record Payment','e'); ?></title>
414 <style type="text/css">
415 body { font-family:sans-serif; font-size:10pt; font-weight:normal }
416 .dehead { color:#000000; font-family:sans-serif; font-size:10pt; font-weight:bold }
417 .detail { color:#000000; font-family:sans-serif; font-size:10pt; font-weight:normal }
418 </style>
420 <script type="text/javascript" src="../../library/topdialog.js"></script>
421 <script type="text/javascript" src="../../library/dialog.js"></script>
423 <script language="JavaScript">
424 <?php require($GLOBALS['srcdir'] . "/restoreSession.php"); ?>
426 function calctotal() {
427 var f = document.forms[0];
428 var total = 0;
429 for (var i = 0; i < f.elements.length; ++i) {
430 var elem = f.elements[i];
431 var ename = elem.name;
432 if (ename.indexOf('form_upay[') == 0 || ename.indexOf('form_bpay[') == 0) {
433 if (elem.value.length > 0) total += Number(elem.value);
436 f.form_paytotal.value = Number(total).toFixed(2);
437 return true;
440 </script>
442 </head>
444 <body class="body_top" onunload='imclosing()'>
446 <form method='post' action='front_payment.php<?php if ($payid) echo "?payid=$payid"; ?>'
447 onsubmit='return top.restoreSession()'>
448 <input type='hidden' name='form_pid' value='<?php echo $pid ?>' />
450 <center>
452 <table border='0' cellspacing='8'>
454 <tr>
455 <td colspan='2' align='center'>
456 &nbsp;<br>
457 <b><?php xl('Accept Payment for ','e','',' '); ?><?php echo $patdata['fname'] . " " .
458 $patdata['lname'] . " (" . $patdata['pubpid'] . ")" ?></b>
459 <br>&nbsp;
460 </td>
461 </tr>
463 <tr>
464 <td>
465 <?php xl('Payment Method','e'); ?>:
466 </td>
467 <td>
468 <select name='form_method'>
469 <?php
470 foreach ($payment_methods as $value) {
471 echo " <option value='$value'";
472 if ($value == $payrow['method']) echo " selected";
473 echo ">$value</option>\n";
476 </select>
477 </td>
478 </tr>
480 <tr>
481 <td>
482 <?php xl('Check/Reference Number','e'); ?>:
483 </td>
484 <td>
485 <input type='text' name='form_source' size='10' value='<?php echo $payrow['source'] ?>'>
486 </td>
487 </tr>
489 </table>
491 <table border='0' cellpadding='2' cellspacing='0' width='98%'>
492 <tr bgcolor="#cccccc">
493 <td class="dehead">
494 <?php xl('DOS','e')?>
495 </td>
496 <td class="dehead" align="right">
497 <?php xl('Charges','e')?>
498 </td>
499 <td class="dehead" align="right">
500 <?php xl('Pt Paid','e')?>&nbsp;
501 </td>
502 <td class="dehead" align="right">
503 <?php xl('Insurance','e')?>
504 </td>
505 <td class="dehead" align="right">
506 <?php xl('Balance','e')?>
507 </td>
508 <td class="dehead" align="right">
509 <?php xl('Due Pt','e')?>
510 </td>
511 <td class="dehead" align="right">
512 <?php xl('Paying','e')?>
513 </td>
514 </tr>
516 <?php
517 $encs = array();
519 // Get the unbilled service charges and payments by encounter for this patient.
521 $query = "SELECT b.encounter, b.code_type, b.code, b.modifier, b.fee, " .
522 "LEFT(fe.date, 10) AS encdate " .
523 "FROM billing AS b, form_encounter AS fe WHERE " .
524 "b.pid = '$pid' AND b.activity = 1 AND b.billed = 0 AND " .
525 "b.code_type != 'TAX' AND b.fee != 0 " .
526 "AND fe.pid = b.pid AND fe.encounter = b.encounter " .
527 "ORDER BY b.encounter";
528 $bres = sqlStatement($query);
530 while ($brow = sqlFetchArray($bres)) {
531 $key = 0 - $brow['encounter'];
532 if (empty($encs[$key])) {
533 $encs[$key] = array(
534 'encounter' => $brow['encounter'],
535 'date' => $brow['encdate'],
536 'charges' => 0,
537 'payments' => 0);
539 if ($brow['code_type'] === 'COPAY') {
540 $encs[$key]['payments'] -= $brow['fee'];
541 } else {
542 $encs[$key]['charges'] += $brow['fee'];
543 // Add taxes.
544 $query = "SELECT taxrates FROM codes WHERE " .
545 "code_type = '" . $code_types[$brow['code_type']]['id'] . "' AND " .
546 "code = '" . $brow['code'] . "' AND ";
547 if ($brow['modifier']) {
548 $query .= "modifier = '" . $brow['modifier'] . "'";
549 } else {
550 $query .= "(modifier IS NULL OR modifier = '')";
552 $query .= " LIMIT 1";
553 $trow = sqlQuery($query);
554 $encs[$key]['charges'] += calcTaxes($trow, $brow['fee']);
558 // Do the same for unbilled product sales.
560 $query = "SELECT s.encounter, s.drug_id, s.fee, " .
561 "LEFT(fe.date, 10) AS encdate " .
562 "FROM drug_sales AS s, form_encounter AS fe " .
563 "WHERE s.pid = '$pid' AND s.billed = 0 AND s.fee != 0 " .
564 "AND fe.pid = s.pid AND fe.encounter = s.encounter " .
565 "ORDER BY s.encounter";
566 $dres = sqlStatement($query);
568 while ($drow = sqlFetchArray($dres)) {
569 $key = 0 - $drow['encounter'];
570 if (empty($encs[$key])) {
571 $encs[$key] = array(
572 'encounter' => $drow['encounter'],
573 'date' => $drow['encdate'],
574 'charges' => 0,
575 'payments' => 0);
577 $encs[$key]['charges'] += $drow['fee'];
578 // Add taxes.
579 $trow = sqlQuery("SELECT taxrates FROM drug_templates WHERE drug_id = '" .
580 $drow['drug_id'] . "' ORDER BY selector LIMIT 1");
581 $encs[$key]['charges'] += calcTaxes($trow, $drow['fee']);
584 ksort($encs, SORT_NUMERIC);
585 $gottoday = false;
586 foreach ($encs as $key => $value) {
587 $enc = $value['encounter'];
588 $dispdate = $value['date'];
589 if (strcmp($dispdate, $today) == 0 && !$gottoday) {
590 $dispdate = xl('Today');
591 $gottoday = true;
593 $inscopay = getCopay($pid, $value['date']);
594 $balance = rawbucks($value['charges'] - $value['payments']);
595 $duept = (($inscopay >= 0) ? $inscopay : $value['charges']) - $value['payments'];
596 echoLine("form_upay[$enc]", $dispdate, $value['charges'],
597 $value['payments'], 0, $duept);
600 // If no billing was entered yet for today, then generate a line for
601 // entering today's co-pay.
603 if (! $gottoday) {
604 $inscopay = getCopay($pid, $today);
605 $duept = ($inscopay >= 0) ? $inscopay : 0;
606 echoLine("form_upay[0]", xl('Today'), 0, 0, 0, $duept);
609 // Now list previously billed visits.
611 if ($INTEGRATED_AR) {
612 $query = "SELECT f.id, f.pid, f.encounter, f.date, " .
613 "f.last_level_billed, f.last_level_closed, f.stmt_count, " .
614 "p.fname, p.mname, p.lname, p.pubpid, p.genericname2, p.genericval2, " .
615 "( SELECT SUM(s.fee) FROM drug_sales AS s WHERE " .
616 "s.pid = f.pid AND s.encounter = f.encounter AND s.billed != 0 ) AS sales, " .
617 "( SELECT SUM(b.fee) FROM billing AS b WHERE " .
618 "b.pid = f.pid AND b.encounter = f.encounter AND " .
619 "b.activity = 1 AND b.code_type != 'COPAY' AND b.billed != 0 ) AS charges, " .
620 "( SELECT SUM(b.fee) FROM billing AS b WHERE " .
621 "b.pid = f.pid AND b.encounter = f.encounter AND " .
622 "b.activity = 1 AND b.code_type = 'COPAY' AND b.billed != 0 ) AS copays, " .
623 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
624 "a.pid = f.pid AND a.encounter = f.encounter AND " .
625 "a.payer_type = 0 ) AS ptpaid, " .
626 "( SELECT SUM(a.pay_amount) FROM ar_activity AS a WHERE " .
627 "a.pid = f.pid AND a.encounter = f.encounter AND " .
628 "a.payer_type != 0 ) AS inspaid, " .
629 "( SELECT SUM(a.adj_amount) FROM ar_activity AS a WHERE " .
630 "a.pid = f.pid AND a.encounter = f.encounter ) AS adjustments " .
631 "FROM form_encounter AS f " .
632 "JOIN patient_data AS p ON p.pid = f.pid " .
633 "WHERE f.pid = '$pid' " .
634 "ORDER BY f.pid, f.encounter";
636 // Note that unlike the SQL-Ledger case, this query does not weed
637 // out encounters that are paid up. Also the use of sub-selects
638 // will require MySQL 4.1 or greater.
640 $ires = sqlStatement($query);
641 $num_invoices = mysql_num_rows($ires);
643 while ($irow = sqlFetchArray($ires)) {
644 $balance = $irow['charges'] + $irow['sales'] + $irow['copays']
645 - $irow['ptpaid'] - $irow['inspaid'] - $irow['adjustments'];
646 if (!$balance) continue;
648 $patient_id = $irow['pid'];
649 $enc = $irow['encounter'];
650 $svcdate = substr($irow['date'], 0, 10);
651 $duncount = $irow['stmt_count'];
652 if (! $duncount) {
653 for ($i = 1; $i <= 3 && arGetPayerID($irow['pid'], $irow['date'], $i); ++$i) ;
654 $duncount = $irow['last_level_closed'] + 1 - $i;
657 $inspaid = $irow['inspaid'] + $irow['adjustments'];
658 $ptpaid = $irow['ptpaid'] - $irow['copays'];
659 $duept = ($duncount < 0) ? 0 : $balance;
661 echoLine("form_bpay[$enc]", $svcdate, $irow['charges'] + $irow['sales'],
662 $ptpaid, $inspaid, $duept);
664 } // end $INTEGRATED_AR
665 else {
666 // Query for all open invoices.
667 $query = "SELECT ar.id, ar.invnumber, ar.amount, ar.paid, " .
668 "ar.intnotes, ar.notes, ar.shipvia, " .
669 "(SELECT SUM(invoice.sellprice * invoice.qty) FROM invoice WHERE " .
670 "invoice.trans_id = ar.id AND invoice.sellprice > 0) AS charges, " .
671 "(SELECT SUM(invoice.sellprice * invoice.qty) FROM invoice WHERE " .
672 "invoice.trans_id = ar.id AND invoice.sellprice < 0) AS adjustments, " .
673 "(SELECT SUM(acc_trans.amount) FROM acc_trans WHERE " .
674 "acc_trans.trans_id = ar.id AND acc_trans.chart_id = $chart_id_cash " .
675 "AND acc_trans.source NOT LIKE 'Ins%') AS ptpayments " .
676 "FROM ar WHERE ar.invnumber LIKE '$pid.%' AND " .
677 "ar.amount != ar.paid " .
678 "ORDER BY ar.invnumber";
679 $ires = SLQuery($query);
680 if ($sl_err) die($sl_err);
681 $num_invoices = SLRowCount($ires);
683 for ($ix = 0; $ix < $num_invoices; ++$ix) {
684 $irow = SLGetRow($ires, $ix);
686 // Get encounter ID and date of service.
687 list($patient_id, $enc) = explode(".", $irow['invnumber']);
688 $tmp = sqlQuery("SELECT LEFT(date, 10) AS encdate FROM form_encounter " .
689 "WHERE encounter = '$enc'");
690 $svcdate = $tmp['encdate'];
692 // Compute $duncount as in sl_eob_search.php to determine if
693 // this invoice is at patient responsibility.
694 $duncount = substr_count(strtolower($irow['intnotes']), "statement sent");
695 if (! $duncount) {
696 $insgot = strtolower($irow['notes']);
697 $inseobs = strtolower($irow['shipvia']);
698 foreach (array('ins1', 'ins2', 'ins3') as $value) {
699 if (strpos($insgot, $value) !== false &&
700 strpos($inseobs, $value) === false)
701 --$duncount;
705 $inspaid = $irow['paid'] + $irow['ptpayments'] - $irow['adjustments'];
706 $balance = $irow['amount'] - $irow['paid'];
707 $duept = ($duncount < 0) ? 0 : $balance;
709 echoLine("form_bpay[$enc]", $svcdate, $irow['charges'],
710 0 - $irow['ptpayments'], $inspaid, $duept);
712 } // end not $INTEGRATED_AR
714 // Continue with display of the data entry form.
717 <tr bgcolor="#cccccc">
718 <td class="dehead" colspan="6">
719 <?php xl('Total Amount Paid','e')?>
720 </td>
721 <td class="dehead" align="right">
722 <input type='text' name='form_paytotal' size='6' value=''
723 style='color:#00aa00' readonly />
724 </td>
725 </tr>
727 </table>
730 <input type='submit' name='form_save' value='<?php xl('Save','e'); ?>' /> &nbsp;
731 <input type='button' value='<?php xl('Cancel','e'); ?>' onclick='window.close()' />
733 </center>
734 </form>
735 <script language="JavaScript">
736 calctotal();
737 </script>
738 </body>
740 <?php
742 if (!$INTEGRATED_AR) SLClose();
744 </html>