fix A/R report
[freeside.git] / httemplate / search / cust_bill.html
index 79c05dc..6e3617b 100755 (executable)
-<%
-
-   my $join_cust_main = 'LEFT JOIN cust_main USING ( custnum )';
-   #here is the agent virtualization
-   my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
-
-   my( $count_query, $sql_query );
-   my( $count_addl ) = ( '' );
-   my( $distinct ) = ( '' );
-   my($begin, $end) = ( '', '' );
-   my($agentnum) = ( '' );
-   my($open, $days) = ( '', '' );
-   if ( $cgi->param('invnum') =~ /^\s*(FS-)?(\d+)\s*$/ ) {
-     $count_query =
-       "SELECT COUNT(*) FROM cust_bill $join_cust_main".
-       "  WHERE invnum = $2 AND $agentnums_sql"; #agent virtualization
-     $sql_query = {
-       'table'     => 'cust_bill',
-       'addl_from' => $join_cust_main,
-       'hashref'   => { 'invnum' => $2 },
-       #'select'    => '*',
-       'extra_sql' => " AND $agentnums_sql", #agent virtualization
-     };
-   } else {
-   #if ( $cgi->param('begin') || $cgi->param('end')
-   #     || $cgi->param('beginning') || $cgi->param('ending')
-   #     || $cgi->keywords
-   #   )
-   #{
-
-     #some false laziness w/cust_bill::re_X
-     my @where;
-     my $orderby = 'ORDER BY cust_bill._date';
-
-     if ( $cgi->param('beginning')
-          && $cgi->param('beginning') =~ /^([ 0-9\-\/]{0,10})$/ ) {
-       $begin = str2time($1);
-       push @where, "cust_bill._date >= $begin";
-     }
-     if ( $cgi->param('ending')
-           && $cgi->param('ending') =~ /^([ 0-9\-\/]{0,10})$/ ) {
-       $end = str2time($1) + 86399;
-       push @where, "cust_bill._date < $end";
-     }
-
-     if ( $cgi->param('begin') =~ /^(\d+)$/ ) {
-       $begin = $1;
-       push @where, "cust_bill._date >= $begin";
-     }
-     if ( $cgi->param('end') =~ /^(\d+)$/ ) {
-       $end = $1;
-       push @where, "cust_bill._date < $end";
-     }
-
-     if ( $cgi->param('invnum_min') =~ /^\s*(\d+)\s*$/ ) {
-       push @where, "cust_bill.invnum >= $1";
-     }
-     if ( $cgi->param('invnum_max') =~ /^\s*(\d+)\s*$/ ) {
-       push @where, "cust_bill.invnum <= $1";
-     }
-
-     if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
-       $agentnum = $1;
-       push @where, "cust_main.agentnum = $agentnum";
-     }
-
-     my $owed =
-       "charged - ( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
-                    WHERE cust_bill_pay.invnum = cust_bill.invnum )
-                - ( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
-                    WHERE cust_credit_bill.invnum = cust_bill.invnum )";
-
-     if ( $cgi->param('open') ) {
-       push @where, "0 != $owed";
-       $open = 1;
-     }
-
-     my($query) = $cgi->keywords;
-     if ( $query =~ /^(OPEN(\d*)_)?(invnum|date|custnum)$/ ) {
-       ($open, $days, my $field) = ($1, $2, $3);
-       $field = "_date" if $field eq 'date';
-       $orderby = "ORDER BY cust_bill.$field";
-       push @where, "0 != $owed" if $open;
-       push @where, "cust_bill._date < ". (time-86400*$days) if $days;
-     }
-
-     #here is the agent virtualization
-     push @where, $agentnums_sql;
-     my $extra_sql = scalar(@where) ? 'WHERE '. join(' AND ', @where) : '';
-
-     if ( $cgi->param('newest_percust') ) {
-       $distinct = 'DISTINCT ON ( cust_bill.custnum )';
-       $orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
-       #$count_query = "SELECT 'N/A', 'N/A', 'N/A'"; #XXXXXXX fix
-       $count_query = "SELECT COUNT(DISTINCT cust_bill.custnum), 'N/A', 'N/A'";
-     }
-   
-     unless ( $count_query ) {
-       $count_query = "SELECT COUNT(*), sum(charged), sum($owed)";
-       $count_addl = [ '$%.2f total invoiced',
-                       '$%.2f total outstanding balance',
-                     ];
-     }
-     $count_query .=  " FROM cust_bill $join_cust_main $extra_sql";
-   
-     $sql_query = {
-       'table'     => 'cust_bill',
-       'addl_from' => $join_cust_main,
-       'hashref'   => {},
-       'select'    => "$distinct ". join(', ',
-                        'cust_bill.*',
-                        #( map "cust_main.$_", qw(custnum last first company) ),
-                        'cust_main.custnum as cust_main_custnum',
-                        FS::UI::Web::cust_sql_fields(),
-                        "$owed as owed",
-                      ),
-       'extra_sql' => "$extra_sql $orderby"
-     };
-   
-   }
-
-   my $link  = [ "${p}view/cust_bill.cgi?", 'invnum', ];
-   my $clink = sub {
-     my $cust_bill = shift;
-     $cust_bill->cust_main_custnum
-       ? [ "${p}view/cust_main.cgi?", 'custnum' ]
-       : '';
-   };
-
-  my $conf = new FS::Conf;
-  my $money_char = $conf->config('money_char') || '$';
-
-  my $html_init = join("\n", map {
-    ( my $action = $_ ) =~ s/_$//;
-    include('/elements/progress-init.html',
-              $_.'form',
-              [ 'begin', 'end', 'agentnum', 'open', 'days', 'newest_percust' ],
-              "../misc/${_}invoices.cgi",
-              { 'message' => "Invoices re-${action}ed" }, #would be nice to show the number of them, but...
-              $_, #key
-           ),
-    qq!<FORM NAME="${_}form">!,
-    qq!<INPUT TYPE="hidden" NAME="begin"     VALUE="$begin">!,
-    qq!<INPUT TYPE="hidden" NAME="end"       VALUE="$end">!,
-    qq!<INPUT TYPE="hidden" NAME="agentnum"  VALUE="$agentnum">!,
-    qq!<INPUT TYPE="hidden" NAME="open"      VALUE="$open">!,
-    qq!<INPUT TYPE="hidden" NAME="days"      VALUE="$days">!,
-    qq!</FORM>!
-  } qw( print_ email_ fax_ ) );
-
-  my $menubar =  [
-                   'Main menu' => $p,
-                   'Print these invoices' =>
-                     "javascript:print_process()",
-                   'Email these invoices' =>
-                     "javascript:email_process()",
-                 ];
-
-  push @$menubar, 'Fax these invoices' =>
-                    "javascript:fax_process()"
-    if $conf->exists('hylafax');
+<& elements/search.html,
+  'title'       => emt('Invoice Search Results'),
+  'html_init'   => $html_init,
+  'menubar'     => $menubar,
+  'name'        => 'invoices',
+  'query'       => $sql_query,
+  'count_query' => $count_query,
+  'count_addl'  => $count_addl,
+  'redirect'    => $link,
+  'header'      => [ emt('Invoice #'),
+                     emt($invoiced ? 'Charged' : 'Gross Amount'),
+                     emt('Discount'),
+                     emt('Credits'),
+                     emt('Net Amount'),
+                     emt('Balance'),
+                     emt('Date'),
+                     FS::UI::Web::cust_header(),
+                   ],
+  'fields'      => [
+    'display_invnum',
+    $invoiced ? 'charged' : 'gross',
+    'discounted',
+    'credited',
+    'net',
+    'owed',
+    sub { time2str('%b %d %Y', shift->_date ) },
+    \&FS::UI::Web::cust_fields,
+  ],
+  'sort_fields' => [
+    'COALESCE( agent_invid, invnum )',
+    $invoiced ? 'charged' : 'gross',
+    'discounted',
+    'credited',
+    'net',
+    'owed',
+    '_date',
+  ],
+  'format' => [
+    '',
+    $money_char.'%.2f',
+    $money_char.'%.2f',
+    $money_char.'%.2f',
+    $money_char.'%.2f',
+    $money_char.'%.2f',
+    '',
+  ],
+  'align' => 'rrrrrrl'.FS::UI::Web::cust_aligns(),
+  'links' => [
+    $link,
+    $link,
+    $link,
+    $link,
+    $link,
+    $link,
+    $link,
+    ( map { $_ ne 'Cust. Status' ? $clink : '' }
+          FS::UI::Web::cust_header()
+    ),
+  ],
+  'color' => [ 
+               '',
+               '',
+               '',
+               '',
+               '',
+               '',
+               '',
+               FS::UI::Web::cust_colors(),
+             ],
+  'style' => [ 
+               '',
+               '',
+               '',
+               '',
+               '',
+               '',
+               '',
+               FS::UI::Web::cust_styles(),
+             ],
+&>
+<%init>
+
+die "access denied"
+  unless $FS::CurrentUser::CurrentUser->access_right('List invoices');
+
+my( $count_query, $sql_query );
+my $count_addl = '';
+my %search = ();
+
+# show invoiced amount (charged) instead of gross sales
+my $invoiced = $cgi->param('invoiced') ? 1 : 0;
+
+if ( $cgi->param('invnum') =~ /^\s*(FS-)?(\d+)\s*$/ ) {
 
-%><%= include( 'elements/search.html',
-                 'title'       => 'Invoice Search Results',
-                 'html_init'   => $html_init,
-                 'menubar'     => $menubar,
-                 'name'        => 'invoices',
-                 'query'       => $sql_query,
-                 'count_query' => $count_query,
-                 'count_addl'  => $count_addl,
-                 'redirect'    => $link,
-                 'header'      => [ 'Invoice #',
-                                    'Balance',
-                                    'Amount',
-                                    'Date',
-                                    FS::UI::Web::cust_header(),
-                                  ],
-                 'fields'      => [
-                   'invnum',
-                   sub { sprintf($money_char.'%.2f', shift->get('owed') ) },
-                   sub { sprintf($money_char.'%.2f', shift->charged     ) },
-                   sub { time2str('%b %d %Y', shift->_date ) },
-                   \&FS::UI::Web::cust_fields,
-                 ],
-                 'align' => 'rrrrll',
-                 'links' => [
-                   $link,
-                   $link,
-                   $link,
-                   $link,
-                   ( map { $clink } FS::UI::Web::cust_header() ),
-                 ],
+  my $join_cust_main = FS::UI::Web::join_cust_main('cust_bill');
+  #here is the agent virtualization
+  my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
+
+  my $invnum_or_invid = "( invnum = $2 OR agent_invid = $2 )";
+  my $where = "WHERE $invnum_or_invid AND $agentnums_sql";
   
-      )
-%>
+  $count_query = "SELECT COUNT(*) FROM cust_bill $join_cust_main $where";
+
+  $sql_query = {
+    'table'     => 'cust_bill',
+    'addl_from' => $join_cust_main,
+    'hashref'   => {},
+    'extra_sql' => $where,
+  };
+
+  if ( FS::Record->scalar_sql($count_query) == 0 ) {
+
+    # check for a voided invoice
+    $count_query =~ s/cust_bill/cust_bill_void/g;
+    if ( FS::Record->scalar_sql($count_query) > 0 ) {
+      # Redirect to the void search.
+      my $url = $cgi->self_url;
+      $url =~ s(search/cust_bill)(search/cust_bill_void);
+      $m->clear_buffer;
+      $m->print($cgi->redirect($url));
+      $m->abort;
+    }
+  }
+
+} else {
+
+  #deal with some old-style URLs
+  my($query) = $cgi->keywords;
+  if ( $query =~ /^(OPEN(\d*)_)?(invnum|date|custnum)$/ ) {
+    $search{'open'} = 1 if $1;
+    ($search{'days'}, my $field) = ($2, $3);
+    $field = "_date" if $field eq 'date';
+    $search{'order_by'} = "cust_bill.$field";
+  }
+
+  #scalars
+  for (qw( agentnum custnum cust_status refnum invnum_min invnum_max
+           open net newest_percust invoiced
+
+      )) 
+  {
+    $search{$_} = $cgi->param($_) if length($cgi->param($_));
+  }
+
+  #arrays
+  for my $param (qw( cust_classnum )) {
+  $search{$param} = [ $cgi->param($param) ]
+    if grep { $_ eq $param } $cgi->param;
+  }
+
+  #amounts (range)
+  $search{$_} = [ FS::UI::Web::parse_lt_gt($cgi, $_) ]
+    foreach qw( charged owed );
+
+  my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi, '');
+  $search{'_date'} = [ $beginning, $ending ]
+    unless $beginning == 0 && $ending == 4294967295;
+
+  # promised date
+  my $start_of_day = timelocal(0, 0, 0, (localtime(time))[3,4,5]);
+  foreach ( $cgi->param('promised_date') ) {
+    # only if at least one box is checked
+    $search{promised_date} ||= [ $start_of_day, $start_of_day, 0 ];
+    if ($_ eq 'past') {
+      # accept everything before today
+      $search{promised_date}[0] = 0;
+    }
+    elsif ( $_ eq 'future' ) {
+      # accept everything after today
+      $search{promised_date}[1] = 4294967295;
+    }
+    elsif ( $_ eq 'null' ) {
+      # accept nulls
+      $search{promised_date}[2] = 1;
+    }
+  }
+
+  $sql_query   = FS::cust_bill->search(\%search);
+  $count_query = delete( $sql_query->{'count_query'} );
+  $count_addl  = delete( $sql_query->{'count_addl'}  );
+
+}
+
+my $link  = [ "${p}view/cust_bill.cgi?", 'invnum', ];
+my $clink = sub {
+  my $cust_bill = shift;
+  $cust_bill->cust_main_custnum
+    ? [ "${p}view/cust_main.cgi?", 'custnum' ]
+    : '';
+};
+
+my $conf = new FS::Conf;
+my $money_char = $conf->config('money_char') || '$';
+
+my $html_init = join("\n", map {
+ ( my $action = $_ ) =~ s/_$//;
+ include('/elements/progress-init.html',
+           $_.'form',
+           [ sort keys %search ],
+           "../misc/${_}invoices.cgi",
+           { 'message' => "Invoices re-${action}ed" }, #would be nice to show the number of them, but...
+           $_, #key
+        ),
+ qq!<FORM NAME="${_}form">!,
+ ( map { my $f = $_;
+         my @values = ref($search{$f}) ? @{ $search{$f} } : $search{$f};
+         map qq!<INPUT TYPE="hidden" NAME="$f" VALUE="$_">!, @values;
+       }
+       sort keys %search
+ ),
+ qq!</FORM>!
+} qw( print_ email_ fax_ ftp_ spool_ ) ). 
+
+'<SCRIPT TYPE="text/javascript">
+
+function confirm_print_process() {
+  if ( ! confirm('.js_mt("Are you sure you want to reprint these invoices?").') ) {
+    return;
+  }
+  print_process();
+}
+function confirm_email_process() {
+  if ( ! confirm('.js_mt("Are you sure you want to re-email these invoices?").') ) {
+    return;
+  }
+  email_process();
+}
+function confirm_fax_process() {
+  if ( ! confirm('.js_mt("Are you sure you want to re-fax these invoices?").') ) {
+    return;
+  }
+  fax_process();
+}
+function confirm_ftp_process() {
+  if ( ! confirm('.js_mt("Are you sure you want to re-FTP these invoices?").') ) {
+    return;
+  }
+  ftp_process();
+}
+function confirm_spool_process() {
+  if ( ! confirm('.js_mt("Are you sure you want to re-spool these invoices?").') ) {
+    return;
+  }
+  spool_process();
+}
+
+</SCRIPT>';
+
+my $menubar = [];
+
+if ( $FS::CurrentUser::CurrentUser->access_right('Resend invoices') ) {
+
+  push @$menubar, emt('Print these invoices') =>
+                    "javascript:confirm_print_process()",
+                  emt('Email these invoices') =>
+                    "javascript:confirm_email_process()";
+
+  push @$menubar, emt('Fax these invoices') =>
+                    "javascript:confirm_fax_process()"
+    if $conf->exists('hylafax');
+
+  push @$menubar, emt('FTP these invoices') =>
+                    "javascript:confirm_ftp_process()"
+    if $conf->exists('cust_bill-ftpformat');
+
+  push @$menubar, emt('Spool these invoices') =>
+                    "javascript:confirm_spool_process()"
+    if $conf->exists('cust_bill-spoolformat');
+
+}
+
+</%init>