Optimize "Customer has a referring customer" condition, RT#74452
[freeside.git] / httemplate / search / cust_pay_batch.cgi
index 2fceb93..6b175ad 100755 (executable)
@@ -1,72 +1,63 @@
-<% include('elements/search.html',
+<& elements/search.html,
               'title'       => 'Batch payment details',
               'name'        => 'batch details',
              'query'       => $sql_query,
              'count_query' => $count_query,
               'html_init'   => $pay_batch ? $html_init : '',
+              'disable_download' => 1,
              'header'      => [ '#',
                                 'Inv #',
-                                'Customer',
+                                 'Cust #',
                                 'Customer',
                                 'Card Name',
                                 'Card',
                                 'Exp',
                                 'Amount',
                                 'Status',
+                                 '', # delete link
+                                 '', # error_message
                               ],
-             'fields'      => [ sub {
-                                  shift->[0];
-                                },
-                                sub {
-                                  shift->[1];
-                                },
-                                sub {
-                                  shift->[2];
-                                },
-                                sub {
-                                  my $cpb = shift;
-                                  $cpb->[3] . ', ' . $cpb->[4];
-                                },
-                                sub {
-                                  shift->[5];
-                                },
-                                sub {
-                                  my $cardnum = shift->[6];
-                                   'x'x(length($cardnum)-4). substr($cardnum,(length($cardnum)-4));
-                                },
-                                sub {
-                                  shift->[7] =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
-                                   my( $mon, $year ) = ( $2, $1 );
-                                   $mon = "0$mon" if length($mon) == 1;
-                                   "$mon/$year";
-                                },
-                                sub {
-                                  shift->[8];
-                                },
-                                sub {
-                                  shift->[9];
-                                },
-                              ],
-             'align'       => 'lllllllrl',
-             'links'       => [ ['', sub{'#';}],
-                                ["${p}view/cust_bill.cgi?", sub{shift->[1];},],
-                                ["${p}view/cust_main.cgi?", sub{shift->[2];},],
-                                ["${p}view/cust_main.cgi?", sub{shift->[2];},],
+              'fields'      => [  'paybatchnum',
+                                  'invnum',
+                                  'custnum',
+                                  sub { $_[0]->cust_main->name_short },
+                                  'payname',
+                                  'mask_payinfo',
+                                  sub {
+                                    return('') if $_[0]->payby ne 'CARD';
+                                    $_[0]->get('exp') =~ /^\d\d(\d\d)-(\d\d)/;
+                                    sprintf('%02d/%02d',$1,$2);
+                                  },
+                                  sub {
+                                    sprintf('%.02f', $_[0]->amount)
+                                  },
+                                  sub { $_[0]->display_status },
+                                  $sub_unbatch,
+                                  'error_message',
+                                ],
+             'align'       => 'rrrlllcrllll',
+             'links'       => [ '',
+                                ["${p}view/cust_bill.cgi?", 'invnum'],
+                                (["${p}view/cust_main.cgi?", 'custnum']) x 2,
                               ],
-      )
-%>
+              'link_onclicks' => [ ('') x 8,
+                                   $sub_receipt
+                                 ],
+&>
 <%init>
 
 my $conf = new FS::Conf;
 
+my $curuser = $FS::CurrentUser::CurrentUser;
+
 die "access denied"
-  unless $FS::CurrentUser::CurrentUser->access_right('Financial reports')
-      || $FS::CurrentUser::CurrentUser->access_right('Process batches')
+  unless $curuser->access_right('Financial reports')
+      || $curuser->access_right('Process batches')
+      || $curuser->access_right('Process global batches')
       || ( $cgi->param('custnum') 
            && (    $conf->exists('batch-enable')
                 || $conf->config('batch-enable_payby')
               )
-           #&& $FS::CurrentUser::CurrentUser->access_right('View customer batched payments')
          );
 
 my( $count_query, $sql_query );
@@ -83,7 +74,7 @@ if ( $cgi->param('batchnum') && $cgi->param('batchnum') =~ /^(\d+)$/ ) {
 }
 
 if ( $cgi->param('custnum') && $cgi->param('custnum') =~ /^(\d+)$/ ) {
-  push @search, "custnum = $1";
+  push @search, "cust_pay_batch.custnum = $1";
 }
 
 if ( $cgi->param('status') && $cgi->param('status') =~ /^(\w)$/ ) {
@@ -98,7 +89,7 @@ if ( $cgi->param('payby') ) {
 }
 
 if ( not $cgi->param('dcln') ) {
-  push @search, "cpb.status IS DISTINCT FROM 'Approved'";
+  push @search, "cust_pay_batch.status IS DISTINCT FROM 'Approved'";
 }
 
 my ($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
@@ -108,89 +99,71 @@ unless ($pay_batch){
   $orderby = "pay_batch.download,paybatchnum";
 }
 
-push @search, $FS::CurrentUser::CurrentUser->agentnums_sql;
+push @search, $curuser->agentnums_sql({ table => 'cust_main' });
+
+push @search, $curuser->agentnums_sql({ table      => 'pay_batch',
+                                        null_right => 'Process global batches',
+                                     });
+
 my $search = ' WHERE ' . join(' AND ', @search);
 
-$count_query = 'SELECT COUNT(*) FROM cust_pay_batch AS cpb ' .
+$count_query = 'SELECT COUNT(*) FROM cust_pay_batch ' .
                   'LEFT JOIN cust_main USING ( custnum ) ' .
                   'LEFT JOIN pay_batch USING ( batchnum )' .
                  $search;
 
-#grr
-$sql_query = "SELECT paybatchnum,invnum,custnum,cpb.last,cpb.first," .
-             "cpb.payname,cpb.payinfo,cpb.exp,amount,cpb.status " .
-            "FROM cust_pay_batch AS cpb " .
-             'LEFT JOIN cust_main USING ( custnum ) ' .
-             'LEFT JOIN pay_batch USING ( batchnum ) ' .
-             "$search ORDER BY $orderby";
+$sql_query = {
+  'table'     => 'cust_pay_batch',
+  'select'    => 'cust_pay_batch.*, cust_pay.paynum',
+  'hashref'   => {},
+  'addl_from' => 'LEFT JOIN pay_batch USING ( batchnum ) '.
+                 'LEFT JOIN cust_main USING ( custnum ) '.
+                 'LEFT JOIN cust_pay  USING ( batchnum, custnum ) ',
+  'extra_sql' => $search,
+  'order_by'  => "ORDER BY $orderby",
+};
+
+my $sub_receipt = sub {
+  my $paynum = shift->paynum or return '';
+  include('/elements/popup_link_onclick.html',
+    'action'  => $p.'view/cust_pay.html?link=popup;paynum='.$paynum,
+    'actionlabel' => emt('Payment Receipt'),
+  );
+};
+
+my $sub_unbatch = '';
+if ( ($pay_batch && ($pay_batch->status eq 'O')) 
+  && ( $curuser->access_right('Process batches')
+       || $curuser->access_right('Process global batches') )
+) {
+  $sub_unbatch = sub {
+    my $self = shift;
+    return '' if $self->status; # sanity check, shouldn't happen
+    my $batchnum = $self->batchnum;
+    my $paybatchnum = $self->paybatchnum;
+    my $out = <<EOF;
+<FORM name="delete_cust_pay_batch_$paybatchnum">
+<INPUT TYPE="hidden" name="paybatchnum" value="$paybatchnum">
+</FORM>
+EOF
+    $out .= include('/elements/progress-init.html',
+              "delete_cust_pay_batch_$paybatchnum",
+              [ 'paybatchnum' ],
+              $p.'misc/process/delete-cust_pay_batch.cgi',
+              $p.'search/cust_pay_batch.cgi?' . $cgi->query_string,
+              "paybatchnum$paybatchnum",
+            );
+    my $onclick = 'if ( confirm(\'';
+    $onclick .= emt('Are you sure you want to delete batch payment ') . $self->paybatchnum;
+    $onclick .= emt(' from payment batch ') . $self->batchnum;
+    $onclick .= '\') ) { paybatchnum' . $paybatchnum . 'process() }';
+    return $out . '<A HREF="javascript:void(0)" ONCLICK="' . $onclick . '">delete</A>';
+  };
+}
 
 my $html_init = '';
 if ( $pay_batch ) {
-  my $fixed = $conf->config('batch-fixed_format-'. $pay_batch->payby);
-  if (
-       $pay_batch->status eq 'O' 
-       || ( $pay_batch->status eq 'I'
-            && $FS::CurrentUser::CurrentUser->access_right('Reprocess batches')
-          ) 
-       || ( $pay_batch->status eq 'R'
-            && $FS::CurrentUser::CurrentUser->access_right('Redownload resolved batches')
-          ) 
-  ) {
-    $html_init .= qq!<FORM ACTION="$p/misc/download-batch.cgi" METHOD="POST">!;
-    if ( $fixed ) {
-      $html_init .= qq!<INPUT TYPE="hidden" NAME="format" VALUE="$fixed">!;
-    } else {
-      $html_init .= qq!Download batch in format <SELECT NAME="format">!.
-                    qq!<OPTION VALUE="">Default batch mode</OPTION>!.
-                    qq!<OPTION VALUE="csv-td_canada_trust-merchant_pc_batch">CSV file for TD Canada Trust Merchant PC Batch</OPTION>!.
-                    qq!<OPTION VALUE="csv-chase_canada-E-xactBatch">CSV file for Chase Canada E-xactBatch</OPTION>!.
-                    qq!<OPTION VALUE="PAP">80 byte file for TD Canada Trust PAP Batch</OPTION>!.
-                    qq!<OPTION VALUE="BoM">Bank of Montreal ECA batch</OPTION>!.
-                    qq!<OPTION VALUE="ach-spiritone">Spiritone ACH batch</OPTION>!.
-                    qq!</SELECT>!;
-    }
-    $html_init .= qq!<INPUT TYPE="hidden" NAME="batchnum" VALUE="$batchnum"><INPUT TYPE="submit" VALUE="Download"></FORM><BR>!;
-  }
-
-  if (
-       $pay_batch->status eq 'I' 
-       || ( $pay_batch->status eq 'R'
-            && $FS::CurrentUser::CurrentUser->access_right('Reprocess batches')
-          ) 
-  ) {
-    $html_init .= qq!<FORM ACTION="$p/misc/upload-batch.cgi" METHOD="POST" ENCTYPE="multipart/form-data">!.
-                  qq!Upload results<BR>!.
-                  qq!Filename <INPUT TYPE="file" NAME="batch_results"><BR>!;
-    if ( $fixed ) {
-      $html_init .= qq!<INPUT TYPE="hidden" NAME="format" VALUE="$fixed">!;
-    } else {
-      $html_init .= qq!Format <SELECT NAME="format">!.
-                    qq!<OPTION VALUE="">Default batch mode</OPTION>!.
-                    qq!<OPTION VALUE="csv-td_canada_trust-merchant_pc_batch">CSV results from TD Canada Trust Merchant PC Batch</OPTION>!.
-                    qq!<OPTION VALUE="csv-chase_canada-E-xactBatch">CSV file for Chase Canada E-xactBatch</OPTION>!.
-                    qq!<OPTION VALUE="PAP">264 byte results for TD Canada Trust PAP Batch</OPTION>!.
-                    qq!<OPTION VALUE="BoM">Bank of Montreal ECA results</OPTION>!.
-                    qq!<OPTION VALUE="ach-spiritone">Spiritone ACH batch</OPTION>!.
-                    qq!</SELECT><BR>!;
-    }
-    $html_init .= qq!<INPUT TYPE="hidden" NAME="batchnum" VALUE="$batchnum">!;
-    $html_init .= '<INPUT TYPE="submit" VALUE="Upload"></FORM><BR>';
-  }
-
-}
-
-if ($pay_batch) {
-  my $sth = dbh->prepare($count_query) or die dbh->errstr. "doing $count_query";
-  $sth->execute or die "Error executing \"$count_query\": ". $sth->errstr;
-  my $cards = $sth->fetchrow_arrayref->[0];
-
-  my $st = "SELECT SUM(amount) from cust_pay_batch WHERE batchnum=". $batchnum;
-  $sth = dbh->prepare($st) or die dbh->errstr. "doing $st";
-  $sth->execute or die "Error executing \"$st\": ". $sth->errstr;
-  my $total = $sth->fetchrow_arrayref->[0];
-
-  $html_init .= "$cards credit card payments batched<BR>\$" .
-                sprintf("%.2f", $total) ." total in batch<BR>";
+  $html_init = include('elements/cust_pay_batch_top.html', 
+                    'pay_batch' => $pay_batch);
 }
-
 </%init>