add net vs gross amounts to invoice report; make the "net sales" links on sales/credi...
[freeside.git] / httemplate / search / cust_bill.html
1 <% include( 'elements/search.html',
2                  'title'       => 'Invoice Search Results',
3                  'html_init'   => $html_init,
4                  'menubar'     => $menubar,
5                  'name'        => 'invoices',
6                  'query'       => $sql_query,
7                  'count_query' => $count_query,
8                  'count_addl'  => $count_addl,
9                  'redirect'    => $link,
10                  'header'      => [ 'Invoice #',
11                                     'Balance',
12                                     'Net Amount',
13                                     'Gross Amount',
14                                     'Date',
15                                     FS::UI::Web::cust_header(),
16                                   ],
17                  'fields'      => [
18                    'invnum',
19                    sub { sprintf($money_char.'%.2f', shift->get('owed') ) },
20                    sub { sprintf($money_char.'%.2f', shift->get('net') ) },
21                    sub { sprintf($money_char.'%.2f', shift->charged     ) },
22                    sub { time2str('%b %d %Y', shift->_date ) },
23                    \&FS::UI::Web::cust_fields,
24                  ],
25                  'align' => 'rrrr'.FS::UI::Web::cust_aligns(),
26                  'links' => [
27                    $link,
28                    $link,
29                    $link,
30                    $link,
31                    $link,
32                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
33                          FS::UI::Web::cust_header()
34                    ),
35                  ],
36                  'color' => [ 
37                               '',
38                               '',
39                               '',
40                               '',
41                               '',
42                               FS::UI::Web::cust_colors(),
43                             ],
44                  'style' => [ 
45                               '',
46                               '',
47                               '',
48                               '',
49                               '',
50                               FS::UI::Web::cust_styles(),
51                             ],
52
53   
54       )
55 %>
56 <%init>
57
58 die "access denied"
59   unless $FS::CurrentUser::CurrentUser->access_right('List invoices');
60
61 my $join_cust_main = 'LEFT JOIN cust_main USING ( custnum )';
62 #here is the agent virtualization
63 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
64
65 my( $count_query, $sql_query );
66 my $count_addl = '';
67 #my $distinct = '';
68 my %search;
69
70 if ( $cgi->param('invnum') =~ /^\s*(FS-)?(\d+)\s*$/ ) {
71
72   $count_query =
73     "SELECT COUNT(*) FROM cust_bill $join_cust_main".
74     "  WHERE invnum = $2 AND $agentnums_sql"; #agent virtualization
75   $sql_query = {
76     'table'     => 'cust_bill',
77     'addl_from' => $join_cust_main,
78     'hashref'   => { 'invnum' => $2 },
79     #'select'    => '*',
80     'extra_sql' => " AND $agentnums_sql", #agent virtualization
81   };
82
83 } else {
84
85   #some false laziness w/cust_bill::re_X
86   my @where;
87   my $orderby = 'ORDER BY cust_bill._date';
88
89   if ( $cgi->param('beginning')
90        && $cgi->param('beginning') =~ /^([ 0-9\-\/]{0,10})$/ ) {
91     $search{'begin'} = str2time($1);
92     push @where, 'cust_bill._date >= '. $search{'begin'};
93   }
94   if ( $cgi->param('ending')
95         && $cgi->param('ending') =~ /^([ 0-9\-\/]{0,10})$/ ) {
96     $search{'end'} = str2time($1) + 86399;
97     push @where, 'cust_bill._date < '. $search{'end'};
98   }
99
100   if ( $cgi->param('begin') =~ /^(\d+)$/ ) {
101     $search{'begin'} = $1;
102     push @where, 'cust_bill._date >= '. $search{'begin'};
103   }
104   if ( $cgi->param('end') =~ /^(\d+)$/ ) {
105     $search{'end'} = $1;
106     push @where, 'cust_bill._date < '. $search{'end'};
107   }
108
109   if ( $cgi->param('invnum_min') =~ /^\s*(\d+)\s*$/ ) {
110     $search{'invnum_min'} = $1;
111     push @where, 'cust_bill.invnum >= '. $search{'invnum_min'};
112   }
113   if ( $cgi->param('invnum_max') =~ /^\s*(\d+)\s*$/ ) {
114     $search{'invnum_max'} = $1;
115     push @where, 'cust_bill.invnum <= '. $search{'invnum_max'};
116   }
117
118   if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
119     $search{'agentnum'} = $1;
120     push @where, 'cust_main.agentnum = '. $search{'agentnum'};
121   }
122
123   if ( $cgi->param('open') ) {
124     push @where, '0 != '. FS::cust_bill->owed_sql;
125     $search{'open'} = 1;
126   }
127
128   if ( $cgi->param('net') ) {
129     push @where, '0 != '. FS::cust_bill->net_sql;
130     $search{'net'} = 1;
131   }
132
133   my($query) = $cgi->keywords;
134   if ( $query =~ /^(OPEN(\d*)_)?(invnum|date|custnum)$/ ) {
135     ($search{'open'}, $search{'days'}, my $field) = ($1, $2, $3);
136     $field = "_date" if $field eq 'date';
137     $orderby = "ORDER BY cust_bill.$field";
138     push @where, '0 != '. FS::cust_bill->owed_sql if $search{'open'};
139     push @where, "cust_bill._date < ". (time-86400*$search{'days'})
140       if $search{'days'};
141   }
142
143   if ( $cgi->param('newest_percust') ) {
144     $search{'newest_percust'} = 1;
145
146     #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
147     #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
148     #$count_query = "SELECT 'N/A', 'N/A', 'N/A'"; #XXXXXXX fix
149     
150     my @newest_where = map { my $x = $_;
151                              $x =~ s/\bcust_bill\./newest_cust_bill./g;
152                              $x;
153                           }
154                            grep ! /^cust_main./, @where;
155     my $newest_where = scalar(@newest_where)
156                          ? ' AND '. join(' AND ', @newest_where)
157                          : '';
158
159     push @where, "cust_bill._date = (
160       SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
161         WHERE newest_cust_bill.custnum = cust_bill.custnum
162           $newest_where
163     )";
164
165
166     $count_query = "SELECT COUNT(DISTINCT cust_bill.custnum), 'N/A', 'N/A'";
167   }
168
169   #here is the agent virtualization
170   push @where, $agentnums_sql;
171
172   my $extra_sql = scalar(@where) ? 'WHERE '. join(' AND ', @where) : '';
173
174   unless ( $count_query ) {
175     $count_query = 'SELECT COUNT(*), '. join(', ',
176                      map "SUM($_)",
177                          ( 'charged',
178                            FS::cust_bill->net_sql,
179                            FS::cust_bill->owed_sql,
180                          )
181                    );
182     $count_addl = [ '$%.2f invoiced (gross)',
183                     '$%.2f invoiced (net)',
184                     '$%.2f outstanding balance',
185                   ];
186   }
187   $count_query .=  " FROM cust_bill $join_cust_main $extra_sql";
188
189   $sql_query = {
190     'table'     => 'cust_bill',
191     'addl_from' => $join_cust_main,
192     'hashref'   => {},
193     #'select'    => "$distinct ". join(', ',
194     'select'    => join(', ',
195                      'cust_bill.*',
196                      #( map "cust_main.$_", qw(custnum last first company) ),
197                      'cust_main.custnum as cust_main_custnum',
198                      FS::UI::Web::cust_sql_fields(),
199                      FS::cust_bill->owed_sql. ' AS owed',
200                      FS::cust_bill->net_sql.  ' AS net',
201                    ),
202     'extra_sql' => "$extra_sql $orderby"
203   };
204
205 }
206
207 my $link  = [ "${p}view/cust_bill.cgi?", 'invnum', ];
208 my $clink = sub {
209   my $cust_bill = shift;
210   $cust_bill->cust_main_custnum
211     ? [ "${p}view/cust_main.cgi?", 'custnum' ]
212     : '';
213 };
214
215 my $conf = new FS::Conf;
216 my $money_char = $conf->config('money_char') || '$';
217
218 my $html_init = join("\n", map {
219  ( my $action = $_ ) =~ s/_$//;
220  include('/elements/progress-init.html',
221            $_.'form',
222            [ keys %search ],
223            "../misc/${_}invoices.cgi",
224            { 'message' => "Invoices re-${action}ed" }, #would be nice to show the number of them, but...
225            $_, #key
226         ),
227  qq!<FORM NAME="${_}form">!,
228  ( map qq!<INPUT TYPE="hidden" NAME="$_" VALUE="$search{$_}">!, keys %search ),
229  qq!</FORM>!
230 } qw( print_ email_ fax_ ) ). 
231
232 '<SCRIPT TYPE="text/javascript">
233
234 function confirm_print_process() {
235   if ( ! confirm("Are you sure you want to reprint these invoices?") ) {
236     return;
237   }
238   print_process();
239 }
240 function confirm_email_process() {
241   if ( ! confirm("Are you sure you want to re-email these invoices?") ) {
242     return;
243   }
244   email_process();
245 }
246 function confirm_fax_process() {
247   if ( ! confirm("Are you sure you want to re-fax these invoices?") ) {
248     return;
249   }
250   fax_process();
251 }
252
253 </SCRIPT>';
254
255 my $menubar =  [
256                 'Main menu' => $p,
257                 'Print these invoices' =>
258                   "javascript:confirm_print_process()",
259                 'Email these invoices' =>
260                   "javascript:confirm_email_process()",
261               ];
262
263 push @$menubar, 'Fax these invoices' =>
264                  "javascript:confirm_fax_process()"
265  if $conf->exists('hylafax');
266
267 </%init>