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