remove invoice deletion (and ancient & unused config settings), RT#37157
[freeside.git] / httemplate / view / cust_main / payment_history.html
index f794ccf..e3599bc 100644 (file)
-<%
-  my( $cust_main ) = @_;
-  my $custnum = $cust_main->custnum;
-
-  my $conf = new FS::Conf;
-
-  my @payby = $conf->config('payby');
-  #@payby = (qw( CARD DCRD CHEK DCHK LECB BILL CASH WEST COMP ))
-  @payby = (qw( CARD DCRD CHEK DCHK LECB BILL CASH COMP ))
-    unless grep /\w/, @payby;
-  my %payby = map { $_=>1 } @payby;
-
-  my $s = 0;
-
-%>
-
-<BR><BR><A NAME="history"><FONT SIZE="+2">Payment History</FONT></A><BR>
-
-<% if ( $payby{'BILL'} ) { %>
-
-  <%= $s++ ? ' | ' : '' %>
-  <A HREF="<%= $p %>edit/cust_pay.cgi?payby=BILL;custnum=<%= $custnum %>">Post check payment</A>
-
-<% } %>
-
-<% if ( $payby{'CASH'} ) { %>
-
-  <%= $s++ ? ' | ' : '' %>
-  <A HREF="<%= $p %>edit/cust_pay.cgi?payby=CASH;custnum=<%= $custnum %>">Post cash payment</A>
+<TABLE>
+  <TR>
+    <TD ALIGN="left">
+
+%# batched payment links
+
+% if ( ( $conf->exists('batch-enable') || $conf->config('batch-enable_payby') )
+%      && $curuser->access_right('View customer batched payments')
+%    )
+% { 
+    <% mt('View batched payments:') |h %> 
+%   foreach my $status (qw( Queued In-transit Complete All )) {
+      <A HREF="<% $p %>search/cust_pay_batch.cgi?status=<% $status{$status} %>;custnum=<% $custnum %>"><% mt($status) |h %></A> 
+      <% $status ne 'All' ? '|' : '' %>
+%   }
+    <BR>
+% } 
 
-<% } %>
+    </TD>
+  </TR>
+  <TR>
+    <TD COLSPAN=2>
 
-<% if ( $payby{'WEST'} ) { %>
+%# and now the table
 
-  <%= $s++ ? ' | ' : '' %>
-  <A HREF="<%= $p %>edit/cust_pay.cgi?payby=WEST;custnum=<%= $custnum %>">Post Western Union payment</A>
+<& /elements/table-grid.html &>
+% my $bgcolor1 = '#eeeeee';
+%   my $bgcolor2 = '#ffffff';
+%   my $bgcolor = '';
 
-<% } %>
+<THEAD>
+<TR>
+  <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('Date') |h %></TH>
+  <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('Description') |h %></TH>
+  <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1><% mt('Invoice') |h %></FONT></TH>
+  <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1><% mt('Payment') |h %></FONT></TH>
+  <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1><% mt('In-house Credit') |h %></FONT></TH>
+  <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1><% mt('Refund') |h %></FONT></TH>
+  <TH CLASS="grid" BGCOLOR="#cccccc"><FONT SIZE=-1><% mt('Balance') |h %></FONT></TH>
+</TR>
+</THEAD>
+
+%#display payment history
+
+%my %target = ();
+%
+%my $hidden = 0;
+%my $seen = 0;
+%my $old_history = 0;
+%my $lastdate = 0;
+%
+%foreach my $item ( @history ) {
+%
+%  $lastdate = $item->{'date'};
+%
+%  my $display = '';
+%  if ( $item->{'hide'} ) {
+%    $display = ' STYLE="display:none" ';
+%  }
+%
+%  if ( $bgcolor eq $bgcolor1 ) {
+%    $bgcolor = $bgcolor2;
+%  } else {
+%    $bgcolor = $bgcolor1;
+%  }
+%
+%  my $charge  = exists($item->{'charge'})
+%                  ? sprintf("$money_char\%.2f", $item->{'charge'})
+%                  : exists($item->{'charge_nobal'})
+%                    ? sprintf("$money_char\%.2f", $item->{'charge_nobal'})
+%                    : exists($item->{'void_charge'})
+%                      ? sprintf("<DEL>$money_char\%.2f</DEL>", $item->{'void_charge'})
+%                      : '';
+%
+%  my $payment = exists($item->{'payment'})
+%                  ? sprintf("-&nbsp;$money_char\%.2f", $item->{'payment'})
+%                  : '';
+%
+%  $payment ||= sprintf( "<DEL>-&nbsp;$money_char\%.2f</DEL>",
+%                        $item->{'void_payment'}
+%                      )
+%    if exists($item->{'void_payment'});
+%
+%  my $credit  = exists($item->{'credit'})
+%                  ? sprintf("-&nbsp;$money_char\%.2f", $item->{'credit'})
+%                  : '';
+%
+%  $credit ||= sprintf( "<DEL>-&nbsp;$money_char\%.2f</DEL>",
+%                       $item->{'void_credit'}
+%                     )
+%    if exists($item->{'void_credit'});
+%
+%  my $refund  = exists($item->{'refund'})
+%                  ? sprintf("$money_char\%.2f", $item->{'refund'})
+%                  : '';
+%
+%  my $target = exists($item->{'target'}) ? $item->{'target'} : '';
+%
+%  my $showbalance = $money_char . $item->{'balance'};
+%  $showbalance =~ s/^\$\-/-&nbsp;\$/;
+
+  <TR <% $display ? $display.' ID="old_history'.$old_history++.'"'  : ''%>>
+    <TD VALIGN="top" CLASS="grid" BGCOLOR="<% $bgcolor %>">
+% unless ( !$target || $target{$target}++ ) { 
+
+        <A NAME="<% $target %>">
+% } 
+
+      <% time2str($date_format, $item->{'date'}) %>
+% if ( $target && $target{$target} == 1 ) { 
 
-<% if ( $payby{'CARD'} || $payby{'DCRD'} ) { %>
+        </A>
+% } 
 
-  <%= $s++ ? ' | ' : '' %>
-  <A HREF="<%= $p %>misc/payment.cgi?payby=CARD;custnum=<%= $custnum %>">Process credit card payment</A>
+      </FONT>
+    </TD>
+    <TD CLASS="grid" BGCOLOR="<% $bgcolor %>">
+      <% $item->{'desc'} %>
+    </TD>
+    <TD VALIGN="top" ALIGN="right" CLASS="grid" BGCOLOR="<% $bgcolor %>">
+      <% $charge  %>
+    </TD>
+    <TD VALIGN="top" ALIGN="right" CLASS="grid" BGCOLOR="<% $bgcolor %>">
+      <% $payment %>
+    </TD>
+    <TD VALIGN="top" ALIGN="right" CLASS="grid" BGCOLOR="<% $bgcolor %>">
+      <% $credit  %>
+    </TD>
+    <TD VALIGN="top" ALIGN="right" CLASS="grid" BGCOLOR="<% $bgcolor %>">
+      <% $refund  %>
+    </TD>
+    <TD VALIGN="top" ALIGN="right" CLASS="grid" BGCOLOR="<% $bgcolor %>">
+      <% $showbalance %>
+    </TD>
+  </TR>
 
-<% } %>
+% if ( $item->{'balance_forward'} ) {
+<& .balance_forward_row, $item->{'balance'}, $item->{'date'} &>
+% } 
+%} # foreach $item
 
-<% if ( $payby{'CHEK'} || $payby{'DCHK'} ) { %>
+</TABLE>
+    </TD>
+  </TR>
+</TABLE>
 
-  <%= $s++ ? ' | ' : '' %>
-  <A HREF="<%= $p %>misc/payment.cgi?payby=CHEK;custnum=<%= $custnum %>">Process electronic check (ACH) payment</A>
+<SCRIPT TYPE="text/javascript">
 
-<% } %>
+function show_history () {
+  //alert('showing history!');
 
-<% if ( $payby{'MCRD'} ) { %>
+  var balance_forward_row = document.getElementById('balance_forward_row');
 
-  <%= $s++ ? ' | ' : '' %>
-  <A HREF="<%= $p %>edit/cust_pay.cgi?payby=MCRD;custnum=<%= $custnum %>">Post manual credit card payment</A>
+  balance_forward_row.style.display = 'none';
+  for ( var i = 0; i < <% $old_history %>; i++ ) {
+    var oldRow = document.getElementById('old_history'+i);
+    oldRow.style.display = '';
+  }
 
-<% } %>
+}
 
-<BR><A HREF="<%= $p %>edit/cust_credit.cgi?<%= $custnum %>">Post credit</A>
-<BR>
+</SCRIPT>
+<%def .balance_forward_row>
+%  my( $b, $date ) = @_;
+%  ( my $balance_forward = $money_char. $b ) =~ s/^\$\-/-&nbsp;\$/;
+
+   <TR ID="balance_forward_row">
+     <TD CLASS="grid" BGCOLOR="#dddddd">
+       <% time2str($date_format, $date) %>
+     </TD>
+
+     <TD CLASS="grid" BGCOLOR="#dddddd">
+       <I><% mt("Starting balance on [_1]", time2str($date_format, $date) ) |h %></I>
+       (<A HREF="javascript:void(0);" onClick="show_history();"><% mt('show prior history') |h %></A>)
+     </TD>
+
+     <TD CLASS="grid" BGCOLOR="#dddddd"></TD>
+     <TD CLASS="grid" BGCOLOR="#dddddd"></TD>
+     <TD CLASS="grid" BGCOLOR="#dddddd"></TD>
+     <TD CLASS="grid" BGCOLOR="#dddddd"></TD>
+     <TD CLASS="grid" BGCOLOR="#dddddd" ALIGN="right"><I><% $balance_forward %></I></TD>
+
+   </TR>
+</%def>
+<%shared>
+my $conf = new FS::Conf;
+my $date_format = $conf->config('date_format') || '%m/%d/%Y';
+my $money_char = $conf->config('money_char') || '$';
+</%shared>
+<%init>
+
+my( $cust_main ) = @_;
+my $custnum = $cust_main->custnum;
+
+my $curuser = $FS::CurrentUser::CurrentUser;
+
+my @payby = grep /\w/, $conf->config('payby');
+#@payby = (qw( CARD DCRD CHEK DCHK LECB BILL CASH WEST COMP ))
+@payby = (qw( CARD DCRD CHEK DCHK LECB BILL CASH COMP ))
+  unless @payby;
+my %payby = map { $_=>1 } @payby;
+
+my %status = (
+  'Queued'     => 'O', #Open
+  'In-transit' => 'I',
+  'Complete'   => 'R', #Resolved
+  'All'        => '',
+);
 
-<%
 #get payment history
 my @history = ();
 
+my %opt = (
+
+  #config
+  ( map { $_ => scalar($conf->config($_)) }
+        qw( card_refund-days date_format )
+  ),
+  ( map { $_ => $conf->exists($_) } 
+        qw( deletepayments deleterefunds pkg-balances
+            cust_credit_bill_pkg-manual cust_bill_pay_pkg-manual
+          )
+  ),
+  'money_char             ' => $money_char,
+
+  #rights
+  ( map { $_ => $curuser->access_right($_) }
+      (
+        'View invoices', 'Void invoices', 'Unvoid invoices',
+        'Apply payment', 'Refund credit card payment', 'Refund Echeck payment',
+        'Credit card void', 'Echeck void', 'Void payments', 'Unvoid payments',
+        'Delete payment', 'Unapply payment',
+        'Apply credit', 'Delete credit', 'Unapply credit', 'Void credit', 'Unvoid credit',
+        'Delete refund',
+        'Billing event reports', 'View customer billing events',
+      )
+  ),
+
+  #customer information
+  'total_owed'              => $cust_main->total_owed,
+  'total_unapplied_refunds' => $cust_main->total_unapplied_refunds,
+);
+
+$opt{'date_format'} ||= '%m/%d/%Y';
+
+#legacy invoices
+foreach my $legacy_cust_bill ($cust_main->legacy_cust_bill) {
+  push @history, {
+    'date'   => $legacy_cust_bill->_date,
+    'order'  => 1,
+    'num'    => $legacy_cust_bill->legacyid,
+    'desc'   => include('payment_history/legacy_invoice.html', $legacy_cust_bill, %opt ),
+    'charge_nobal' => $legacy_cust_bill->charged,
+  };
+}
+
 #invoices
+my $num_cust_bill = 0;
 foreach my $cust_bill ($cust_main->cust_bill) {
-  my $pre = ( $cust_bill->owed > 0 )
-              ? '<B><FONT SIZE="+1" COLOR="#FF0000">Open '
-              : '';
-  my $post = ( $cust_bill->owed > 0 ) ? '</FONT></B>' : '';
-  my $invnum = $cust_bill->invnum;
   push @history, {
     'date'   => $cust_bill->_date,
-    'desc'   => qq!<A HREF="${p}view/cust_bill.cgi?$invnum">!. $pre.
-                "Invoice #$invnum (Balance \$". $cust_bill->owed. ')'.
-                $post. '</A>',
+    'order'  => 1,
+    'num'    => $cust_bill->invnum,
+    'desc'   => include('payment_history/invoice.html', $cust_bill, %opt ),
     'charge' => $cust_bill->charged,
   };
+  $num_cust_bill++;
 }
 
-#payments (some false laziness w/credits)
-foreach my $cust_pay ($cust_main->cust_pay) {
-
-  my $payby = $cust_pay->payby;
-
-  my $payinfo;
-  if ( $payby eq 'CARD' ) {
-    $payinfo = $cust_pay->payinfo_masked;
-  } elsif ( $payby eq 'CHEK' && $cust_pay->payinfo =~ /^(\d+)\@(\d+)$/ ) {
-    $payinfo = "ABA $2, Acct# $1";
-  } else {
-    $payinfo = $cust_pay->payinfo;
-  }
-  my @cust_bill_pay = $cust_pay->cust_bill_pay;
-  my @cust_pay_refund = $cust_pay->cust_pay_refund;
-
-  my $target = "$payby$payinfo";
-  $payby =~ s/^BILL$/Check #/ if $payinfo;
-  $payby =~ s/^CHEK$/Electronic check /;
-  $payby =~ s/^PREP$/Prepaid card /;
-  $payby =~ s/^CARD$/Credit card #/; 
-  $payby =~ s/^COMP$/Complimentary by /; 
-  $payby =~ s/^CASH$/Cash/;
-  $payby =~ s/^WEST$/Western Union/;
-  $payby =~ s/^MCRD$/Manual credit card/;
-  $payby =~ s/^BILL$//;
-  my $info = $payby ? " ($payby$payinfo)" : '';
-
-  my( $pre, $post, $desc, $apply, $ext ) = ( '', '', '', '', '' );
-  if (    scalar(@cust_bill_pay)   == 0
-       && scalar(@cust_pay_refund) == 0 ) {
-    #completely unapplied
-    $pre = '<B><FONT COLOR="#FF0000">Unapplied ';
-    $post = '</FONT></B>';
-    $apply = qq! (<A HREF="${p}edit/cust_bill_pay.cgi?!.
-             $cust_pay->paynum. '">apply</A>)';
-  } elsif (    scalar(@cust_bill_pay)   == 1
-            && scalar(@cust_pay_refund) == 0
-            && $cust_pay->unapplied == 0     ) {
-    #applied to one invoice, the usual situation
-    $desc = ' applied to Invoice #'. $cust_bill_pay[0]->invnum;
-  } elsif (    scalar(@cust_bill_pay)   == 0
-            && scalar(@cust_pay_refund) == 1
-            && $cust_pay->unapplied == 0     ) {
-    #applied to one refund
-    $desc = ' refunded on '. time2str("%D", $cust_pay_refund[0]->_date);
-  } else {
-    #complicated
-    $desc = '<BR>';
-    foreach my $app ( sort { $a->_date <=> $b->_date }
-                           ( @cust_bill_pay, @cust_pay_refund ) ) {
-      if ( $app->isa('FS::cust_bill_pay') ) {
-        $desc .= '&nbsp;&nbsp;'.
-                 '$'. $app->amount.
-                 ' applied to Invoice #'. $app->invnum.
-                 '<BR>';
-                 #' on '. time2str("%D", $cust_bill_pay->_date).
-      } elsif ( $app->isa('FS::cust_pay_refund') ) {
-        $desc .= '&nbsp;&nbsp;'.
-                 '$'. $app->amount.
-                 ' refunded on'. time2str("%D", $app->_date).
-                 '<BR>';
-      } else {
-        die "$app is not a FS::cust_bill_pay or FS::cust_pay_refund";
-      }
-    }
-    if ( $cust_pay->unapplied > 0 ) {
-      $desc .= '&nbsp;&nbsp;'.
-               '<B><FONT COLOR="#FF0000">$'.
-               $cust_pay->unapplied. ' unapplied</FONT></B>'.
-               qq! (<A HREF="${p}edit/cust_bill_pay.cgi?!.
-               $cust_pay->paynum. '">apply</A>)'.
-               '<BR>';
-    }
-  }
-
-  my $refund = '';
-  my $refund_days = $conf->config('card_refund-days') || 120;
-  if (    $cust_pay->closed !~ /^Y/i
-       && $cust_pay->payby =~ /^(CARD|CHEK)$/
-       && time-$cust_pay->_date < $refund_days*86400
-       && $cust_pay->unrefunded > 0
-  ) {
-    $refund = qq! (<A HREF="${p}edit/cust_refund.cgi?payby=$1;!.
-              qq!paynum=!. $cust_pay->paynum. '"'.
-              qq! TITLE="Send a refund for this payment to the payment gateway"!.
-              qq!>refund</A>)!;
-  }
-
-  my $void = '';
-  if (    $cust_pay->closed !~ /^Y/i
-       && ( $cust_pay->payby ne 'CARD' || $conf->exists('cc-void')     )
-       && ( $cust_pay->payby ne 'CHEK' || $conf->exists('echeck-void') ) 
-     ) {
-    $void = qq! (<A HREF="javascript:areyousure('!.
-            qq!${p}misc/void-cust_pay.cgi?!. $cust_pay->paynum.
-            qq!', 'Are you sure you want to void this payment?')"!.
-            qq! TITLE="Void this payment from the database!.
-              ( $cust_pay->payby =~ /^(CARD|CHEK)$/
-                ? ' (do not send anything to the payment gateway)'
-                : '' 
-              ). '"'.
-            qq!>void</A>)!;
-  }
-
-  my $delete = '';
-  if ( $cust_pay->closed !~ /^Y/i && $conf->exists('deletepayments') ) {
-    $delete = qq! (<A HREF="javascript:areyousure('!.
-              qq!${p}misc/delete-cust_pay.cgi?!. $cust_pay->paynum.
-              qq!', 'Are you sure you want to delete this payment?')"!.
-              qq! TITLE="Delete this payment from the database completely - not recommended"!.
-              qq!>delete</A>)!;
-  }
+#voided invoices
+foreach my $cust_bill_void ($cust_main->cust_bill_void) {
+  push @history, {
+    'date'        => $cust_bill_void->_date,
+    'order'       => 0,
+    'num'         => $cust_bill_void->invnum,
+    'desc'        => include('payment_history/voided_invoice.html', $cust_bill_void, %opt ),
+    'void_charge' => $cust_bill_void->charged,
+  };
+}
 
-  my $unapply = '';
-  if (    $cust_pay->closed !~ /^Y/i
-       && $conf->exists('unapplypayments')
-       && scalar(@cust_bill_pay)           ) {
-    $unapply = qq! (<A HREF="javascript:areyousure('!.
-               qq!${p}misc/unapply-cust_pay.cgi?!. $cust_pay->paynum.
-               qq!', 'Are you sure you want to unapply this payment?')"!.
-               qq! TITLE="Keep this payment, but dissociate it from the invoices it is currently applied against"!.
-               qq!>unapply</A>)!;
-  }
+#statements
+foreach my $cust_statement ($cust_main->cust_statement) {
+  push @history, {
+    'date'   => $cust_statement->_date,
+    'order'  => 2,
+    'num'    => $cust_statement->statementnum,
+    'desc'   => include('payment_history/statement.html', $cust_statement, %opt ),
+    #'charge' => $cust_bill->charged,
+  };
+}
 
+#payments (some false laziness w/credits)
+foreach my $cust_pay ($cust_main->cust_pay) {
   push @history, {
     'date'    => $cust_pay->_date,
-    'desc'    => $pre. "Payment$post$info$desc".
-                 "$apply$refund$void$delete$unapply",
+    'order'   => 6,
+    'num'     => $cust_pay->paynum,
+    'desc'    => include('payment_history/payment.html', $cust_pay, %opt ),
     'payment' => $cust_pay->paid,
-    'target'  => $target,
+    #'target'  => $target, #XXX
   };
 }
 
-#voided payments
-foreach my $cust_pay_void ($cust_main->cust_pay_void) {
-
-  my $payby = $cust_pay_void->payby;
-  my $payinfo = $payby eq 'CARD'
-                  ? $cust_pay_void->payinfo_masked
-                  : $cust_pay_void->payinfo;
+#pending payments 
+foreach my $cust_pay_pending ($cust_main->cust_pay_pending) {
+  push @history, {
+    'date'    => $cust_pay_pending->_date,
+    'order'   => 4,
+    'num'     => $cust_pay_pending->paypendingnum,
+    'desc'    => include('payment_history/pending_payment.html', $cust_pay_pending, %opt ),
+    'void_payment' => $cust_pay_pending->paid, 
+  };
+}
 
-  $payby =~ s/^BILL$/Check #/ if $payinfo;
-  $payby =~ s/^CHEK$/Electronic check /;
-  $payby =~ s/^BILL$//;
-  $payby =~ s/^(CARD|COMP)$/$1 /;
-  my $info = $payby ? " ($payby$payinfo)" : '';
 
+#voided payments
+foreach my $cust_pay_void ($cust_main->cust_pay_void) {
   push @history, {
     'date'   => $cust_pay_void->_date,
-    'desc'   => "<DEL>Payment $info</DEL> <I>voided ".
-                time2str("%D", $cust_pay_void->void_date).
-                " by ". $cust_pay_void->otaker. '</i>',
+    'order'  => 3,
+    'num'    => $cust_pay_void->paynum,
+    'desc'   => include('payment_history/voided_payment.html', $cust_pay_void, %opt ),
     'void_payment' => $cust_pay_void->paid,
   };
 
 }
 
+#voided credits 
+foreach my $cust_credit_void ($cust_main->cust_credit_void) {
+  push @history, {
+    'date'        => $cust_credit_void->_date,
+    'order'       => 7,
+    'num'         => $cust_credit_void->paynum,
+    'desc'        => include('payment_history/voided_credit.html', $cust_credit_void, %opt ),
+    'void_credit' => $cust_credit_void->amount,
+  };
+}
+
+#declined payments
+foreach my $cust_pay_pending ($cust_main->cust_pay_pending_attempt) {
+  push @history, {
+    'date'    => $cust_pay_pending->_date,
+    'order'   => 5,
+    'num'     => $cust_pay_pending->paypendingnum,
+    'desc'    => include('payment_history/attempted_payment.html', $cust_pay_pending, %opt ),
+    'void_payment' => $cust_pay_pending->paid, #??
+    #'target'  => $target, #XXX
+  };
+}
+#declined batch payments
+foreach my $cust_pay_batch (
+  $cust_main->cust_pay_batch(hashref => {status => 'Declined'})
+) {
+  my $pay_batch = $cust_pay_batch->pay_batch;
+  push @history, {
+    'date'    => $pay_batch->upload,
+    'order'   => 5,
+    'num'     => $cust_pay_batch->paybatchnum,
+    'desc'    => include('payment_history/attempted_batch_payment.html', $cust_pay_batch, %opt),
+    'void_payment' => $cust_pay_batch->amount,
+  };
+}
+
 #credits (some false laziness w/payments)
 foreach my $cust_credit ($cust_main->cust_credit) {
-
-  my @cust_credit_bill = $cust_credit->cust_credit_bill;
-  my @cust_credit_refund = $cust_credit->cust_credit_refund;
-
-  my( $pre, $post, $desc, $apply, $ext ) = ( '', '', '', '', '' );
-  if (    scalar(@cust_credit_bill)   == 0
-       && scalar(@cust_credit_refund) == 0 ) {
-    #completely unapplied
-    $pre = '<B><FONT COLOR="#FF0000">Unapplied ';
-    $post = '</FONT></B>';
-    $apply = qq! (<A HREF="${p}edit/cust_credit_bill.cgi?!.
-             $cust_credit->crednum. '">apply</A>)';
-  } elsif (    scalar(@cust_credit_bill)   == 1
-            && scalar(@cust_credit_refund) == 0
-            && $cust_credit->credited == 0      ) {
-    #applied to one invoice, the usual situation
-    $desc = ' applied to Invoice #'. $cust_credit_bill[0]->invnum;
-  } elsif (    scalar(@cust_credit_bill)   == 0
-            && scalar(@cust_credit_refund) == 1
-            && $cust_credit->credited == 0      ) {
-    #applied to one refund
-    $desc = ' refunded on '.  time2str("%D", $cust_credit_refund[0]->_date);
-  } else {
-    #complicated
-    $desc = '<BR>';
-    foreach my $app ( sort { $a->_date <=> $b->_date }
-                           ( @cust_credit_bill, @cust_credit_refund ) ) {
-      if ( $app->isa('FS::cust_credit_bill') ) {
-        $desc .= '&nbsp;&nbsp;'.
-                 '$'. $app->amount.
-                 ' applied to Invoice #'. $app->invnum.
-                 '<BR>';
-                 #' on '. time2str("%D", $app->_date).
-      } elsif ( $app->isa('FS::cust_credit_refund') ) {
-        $desc .= '&nbsp;&nbsp;'.
-                 '$'. $app->amount.
-                 ' refunded on'. time2str("%D", $app->_date).
-                 '<BR>';
-      } else {
-        die "$app is not a FS::cust_credit_bill or a FS::cust_credit_refund";
-      }
-    }
-    if ( $cust_credit->credited > 0 ) {
-      $desc .= '&nbsp;&nbsp;<B><FONT COLOR="#FF0000">$'.
-               $cust_credit->credited. ' unapplied</FONT></B>'.
-               qq! (<A HREF="${p}edit/cust_credit_bill.cgi?!.
-               $cust_credit->crednum. '">apply</A>)'.
-               '<BR>';
-    }
-  }
-#
-  my $delete = '';
-  if ( $cust_credit->closed !~ /^Y/i && $conf->exists('deletecredits') ) {
-    $delete = qq! (<A HREF="javascript:areyousure('!.
-              qq!${p}misc/delete-cust_credit.cgi?!. $cust_credit->crednum.
-              qq!', 'Are you sure you want to delete this credit?')">!.
-              qq!delete</A>)!;
-  }
-  
-  my $unapply = '';
-  if (    $cust_credit->closed !~ /^Y/i
-       && $conf->exists('unapplycredits')
-       && scalar(@cust_credit_bill)       ) {
-    $unapply = qq! (<A HREF="javascript:areyousure('!.
-               qq!${p}misc/unapply-cust_credit.cgi?!. $cust_credit->crednum.
-               qq!', 'Are you sure you want to unapply this credit?')">!.
-               qq!unapply</A>)!;
-  }
-  
   push @history, {
     'date'   => $cust_credit->_date,
-    'desc'   => $pre. "Credit$post by ". $cust_credit->otaker.
-                ' ('. $cust_credit->reason. ')'.
-                "$desc$apply$delete$unapply",
+    'order'  => 8,
+    'num'    => $cust_credit->crednum,
+    'desc'   => include('payment_history/credit.html', $cust_credit, %opt ),
     'credit' => $cust_credit->amount,
   };
 
@@ -322,91 +375,115 @@ foreach my $cust_credit ($cust_main->cust_credit) {
 
 #refunds
 foreach my $cust_refund ($cust_main->cust_refund) {
-
-  my $payby = $cust_refund->payby;
-  my $payinfo = $payby eq 'CARD'
-                  ? $cust_refund->payinfo_masked
-                  : $cust_refund->payinfo;
-
-  $payby =~ s/^BILL$/Check #/ if $payinfo;
-  $payby =~ s/^CHEK$/Electronic check /;
-  $payby =~ s/^(CARD|COMP)$/$1 /;
-
   push @history, {
     'date'   => $cust_refund->_date,
-    'desc'   => "Refund ($payby$payinfo) by ". $cust_refund->otaker,
+    'order'  => 9,
+    'num'    => $cust_refund->refundnum,
+    'desc'   => include('payment_history/refund.html', $cust_refund, %opt),
     'refund' => $cust_refund->refund,
   };
 
 }
 
-%>
-
-<%= table() %>
-<TR>
-  <TH>Date</TH>
-  <TH>Description</TH>
-  <TH><FONT SIZE=-1>Charge</FONT></TH>
-  <TH><FONT SIZE=-1>Payment</FONT></TH>
-  <TH><FONT SIZE=-1>In-house<BR>Credit</FONT></TH>
-  <TH><FONT SIZE=-1>Refund</FONT></TH>
-  <TH><FONT SIZE=-1>Balance</FONT></TH>
-</TR>
-
-<%
-#display payment history
-
-my %target;
+# sort in forward order first, and calculate running balances
+my $years =  $conf->config('payment_history-years') || 2;
+my $older_than = time - $years * 31556926; #60*60*24*365.2422
 my $balance = 0;
-foreach my $item ( sort { $a->{'date'} <=> $b->{'date'} } @history ) {
-
-  my $charge  = exists($item->{'charge'})
-                  ? sprintf('$%.2f', $item->{'charge'})
-                  : '';
-  my $payment = exists($item->{'payment'})
-                  ? sprintf('-&nbsp;$%.2f', $item->{'payment'})
-                  : '';
-  $payment ||= sprintf('<DEL>-&nbsp;$%.2f</DEL>', $item->{'void_payment'})
-    if exists($item->{'void_payment'});
-  my $credit  = exists($item->{'credit'})
-                  ? sprintf('-&nbsp;$%.2f', $item->{'credit'})
-                  : '';
-  my $refund  = exists($item->{'refund'})
-                  ? sprintf('$%.2f', $item->{'refund'})
-                  : '';
-
-  my $target = exists($item->{'target'}) ? $item->{'target'} : '';
 
+@history = sort {    $a->{date}  <=> $b->{date}
+                  or $a->{order} <=> $b->{order}
+                  or $a->{num}   <=> $b->{num}
+                }
+             @history;
+
+my $i = 0;
+my $balance_forward;
+foreach my $item (@history) {
   $balance += $item->{'charge'}  if exists $item->{'charge'};
   $balance -= $item->{'payment'} if exists $item->{'payment'};
   $balance -= $item->{'credit'}  if exists $item->{'credit'};
   $balance += $item->{'refund'}  if exists $item->{'refund'};
   $balance = sprintf("%.2f", $balance);
-  $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
-  ( my $showbalance = '$'. $balance ) =~ s/^\$\-/-&nbsp;\$/;
-
-%>
+  $balance =~ s/^\-0\.00$/0.00/;
+  $item->{'balance'} = $balance;
+
+  if ( $item->{'date'} < $older_than ) {
+    $item->{'hide'} = 1;
+  } elsif ( $history[$i-1]->{'hide'} ) {
+    # this is the end of the hidden section
+    $history[$i-1]->{'balance_forward'} = 1;
+  }
+  $i++;
+}
+if ( @history and $history[-1]->{'hide'} ) {
+  # then everything is hidden
+  $history[-1]->{'balance_forward'} = 1;
+}
 
-  <TR>
-    <TD>
-      <% unless ( !$target || $target{$target}++ ) { %>
-        <A NAME="<%= $target %>">
-      <% } %>
-      <%= time2str("%D",$item->{'date'}) %>
-      <% if ( $target && $target{$target} == 1 ) { %>
-        </A>
-      <% } %>
-      </FONT>
-    </TD>
-    <TD><%= $item->{'desc'} %></TD>
-    <TD ALIGN="right"><%= $charge  %></TD>
-    <TD ALIGN="right"><%= $payment %></TD>
-    <TD ALIGN="right"><%= $credit  %></TD>
-    <TD ALIGN="right"><%= $refund  %></TD>
-    <TD ALIGN="right"><%= $showbalance %></TD>
-  </TR>
+# then sort in user-pref order
+if ( $curuser->option('history_order') eq 'newest' ) {
+  @history = sort {    $b->{date}  <=> $a->{date}
+                    or $b->{order} <=> $a->{order} #or still forward here?
+                    or $b->{num}   <=> $a->{num}
+                  }
+               @history;
+} # else it's already oldest-first, and there are no other options yet
+
+sub translate_payby {
+    my ($payby,$payinfo) = (shift,shift);
+    my %payby = (
+        FS::payby->payby2shortname,
+        BILL    => $payinfo ? emt('Check #') : '',
+        CHEK    => emt('Electronic check '),
+        PREP    => emt('Prepaid card '),
+        CARD    => emt('Credit card #'),
+        COMP    => emt('Complimentary by '),
+        #CASH    => emt('Cash'),
+        #WEST    => emt('Western Union'),
+        #MCRD    => emt('Manual credit card'),
+    );
+    $payby = (exists $payby{$payby}) ? $payby{$payby} : $payby; 
+    $payby;
+};
+
+sub translate_payby_refund {
+    my ($payby,$payinfo) = (shift,shift);
+    my %payby = (
+        FS::payby->payby2shortname,
+        BILL    => $payinfo ? emt('Check #') : emt('Check'),
+        CHEK    => emt('Electronic check '),
+        CARD    => emt('Credit card #'),
+        COMP    => emt('Complimentary by '),
+    );
+    $payby = (exists $payby{$payby}) ? $payby{$payby} : $payby; 
+    $payby;
+};
+
+sub translate_payinfo {
+    my $object = shift;
+    my $payby = $object->payby;
+    my $payinfo = $object->payinfo;
+
+    if ( $payby eq 'CARD' ) {
+        $payinfo = $object->paymask;
+    } elsif ( $payby eq 'CHEK' ) {
+        #false laziness w/payinfo_Mixin::payby_payinfo_pretty, should use that
+        my( $account, $aba ) = split('@', $object->paymask );
+        if ( $aba =~ /^(\d{5})\.(\d{3})$/ ) { #blame canada
+          my($branch, $routing) = ($1, $2);
+          $payinfo = emt("Routing [_1], Branch [_2], Acct [_3]",
+                         $routing, $branch, $account);
+        } else {
+          $payinfo = emt("Routing [_1], Acct [_2]", $aba, $account);
+        }
+    }
 
-<% } %>
+    ($payby,$payinfo);
+}
 
-</TABLE>
+sub areyousure_link {
+    my ($url,$msg,$title,$label) = (shift,shift,shift,shift);
+    ' (<A HREF="javascript:areyousure(\''.$url.'\',\''.$msg.'\')" TITLE="'.$title.'">'.$label.'</A>)';
+}
 
+</%init>