fix small side-effect of mysql-compat change eliminating DISTINCT ON: map changing...
[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 { my $x = $_;
152                              $x =~ s/\bcust_bill\./newest_cust_bill./g;
153                              $x;
154                           }
155                            grep ! /^cust_main./, @where;
156     my $newest_where = scalar(@newest_where)
157                          ? ' AND '. join(' AND ', @newest_where)
158                          : '';
159
160     push @where, "cust_bill._date = (
161       SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
162         WHERE newest_cust_bill.custnum = cust_bill.custnum
163           $newest_where
164     )";
165
166
167     $count_query = "SELECT COUNT(DISTINCT cust_bill.custnum), 'N/A', 'N/A'";
168   }
169
170   #here is the agent virtualization
171   push @where, $agentnums_sql;
172
173   my $extra_sql = scalar(@where) ? 'WHERE '. join(' AND ', @where) : '';
174
175   unless ( $count_query ) {
176     $count_query = "SELECT COUNT(*), sum(charged), sum($owed)";
177     $count_addl = [ '$%.2f total invoiced',
178                     '$%.2f total outstanding balance',
179                   ];
180   }
181   $count_query .=  " FROM cust_bill $join_cust_main $extra_sql";
182
183   $sql_query = {
184     'table'     => 'cust_bill',
185     'addl_from' => $join_cust_main,
186     'hashref'   => {},
187     #'select'    => "$distinct ". join(', ',
188     'select'    => join(', ',
189                      'cust_bill.*',
190                      #( map "cust_main.$_", qw(custnum last first company) ),
191                      'cust_main.custnum as cust_main_custnum',
192                      FS::UI::Web::cust_sql_fields(),
193                      "$owed as owed",
194                    ),
195     'extra_sql' => "$extra_sql $orderby"
196   };
197
198 }
199
200 my $link  = [ "${p}view/cust_bill.cgi?", 'invnum', ];
201 my $clink = sub {
202   my $cust_bill = shift;
203   $cust_bill->cust_main_custnum
204     ? [ "${p}view/cust_main.cgi?", 'custnum' ]
205     : '';
206 };
207
208 my $conf = new FS::Conf;
209 my $money_char = $conf->config('money_char') || '$';
210
211 my $html_init = join("\n", map {
212  ( my $action = $_ ) =~ s/_$//;
213  include('/elements/progress-init.html',
214            $_.'form',
215            [ 'begin', 'end', 'agentnum', 'open', 'days',
216              'invnum_min', 'invnum_max', 'newest_percust',
217            ],
218            "../misc/${_}invoices.cgi",
219            { 'message' => "Invoices re-${action}ed" }, #would be nice to show the number of them, but...
220            $_, #key
221         ),
222  qq!<FORM NAME="${_}form">!,
223  qq!<INPUT TYPE="hidden" NAME="begin"           VALUE="$begin">!,
224  qq!<INPUT TYPE="hidden" NAME="end"             VALUE="$end">!,
225  qq!<INPUT TYPE="hidden" NAME="agentnum"        VALUE="$agentnum">!,
226  qq!<INPUT TYPE="hidden" NAME="open"            VALUE="$open">!,
227  qq!<INPUT TYPE="hidden" NAME="days"            VALUE="$days">!,
228  qq!<INPUT TYPE="hidden" NAME="invnum_min"      VALUE="$invnum_min">!,
229  qq!<INPUT TYPE="hidden" NAME="invnum_max"      VALUE="$invnum_max">!,
230  qq!<INPUT TYPE="hidden" NAME="newest_percust"  VALUE="$newest_percust">!,
231  qq!</FORM>!
232 } qw( print_ email_ fax_ ) ). 
233
234 '<SCRIPT TYPE="text/javascript">
235
236 function confirm_print_process() {
237   if ( ! confirm("Are you sure you want to reprint these invoices?") ) {
238     return;
239   }
240   print_process();
241 }
242 function confirm_email_process() {
243   if ( ! confirm("Are you sure you want to re-email these invoices?") ) {
244     return;
245   }
246   email_process();
247 }
248 function confirm_fax_process() {
249   if ( ! confirm("Are you sure you want to re-fax these invoices?") ) {
250     return;
251   }
252   fax_process();
253 }
254
255 </SCRIPT>';
256
257 my $menubar =  [
258                 'Main menu' => $p,
259                 'Print these invoices' =>
260                   "javascript:confirm_print_process()",
261                 'Email these invoices' =>
262                   "javascript:confirm_email_process()",
263               ];
264
265 push @$menubar, 'Fax these invoices' =>
266                  "javascript:confirm_fax_process()"
267  if $conf->exists('hylafax');
268
269 </%init>