improve speed in customer search, #13364
[freeside.git] / httemplate / search / cust_credit_bill_pkg.html
1 <% include( 'elements/search.html',
2               'title'       => 'Tax credits', #well, actually application of
3               'name'        => 'tax credits', # credit to line item
4               'query'       => $query,
5               'count_query' => $count_query,
6                  'count_addl'  => [ $money_char. '%.2f total', ],
7                  'header'      => [
8                    #'#',
9
10                    'Amount',
11
12                    #credit
13                    'Date',
14                    'By',
15                    'Reason',
16
17                    # line item
18                    'Description',
19
20                    #invoice
21                    'Invoice',
22                    'Date',
23                    FS::UI::Web::cust_header(),
24                  ],
25                  'fields'      => [
26                    #'creditbillpkgnum',
27                    sub { sprintf($money_char.'%.2f', shift->amount ) },
28
29                    sub { time2str('%b %d %Y', shift->get('cust_credit_date') ) },
30                    sub { shift->cust_credit_bill->cust_credit->otaker },
31                    sub { shift->cust_credit_bill->cust_credit->reason },
32
33                    sub { $_[0]->pkgnum > 0
34                            ? $_[0]->get('pkg')      # possibly use override.pkg
35                            : $_[0]->get('itemdesc') # but i think this correct
36                        },
37                    'invnum',
38                    sub { time2str('%b %d %Y', shift->_date ) },
39                    \&FS::UI::Web::cust_fields,
40                  ],
41                  'sort_fields' => [
42                    'amount',
43                    'cust_credit_date',
44                    '', #'otaker',
45                    '', #reason
46                    '', #line item description
47                    'invnum',
48                    '_date',
49                    #cust fields
50                  ],
51                  'links'       => [
52                    '',
53                    '',
54                    '',
55                    '',
56                    '',
57                    $ilink,
58                    $ilink,
59                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
60                          FS::UI::Web::cust_header()
61                    ),
62                  ],
63                  'align' => 'rrlllrr'.FS::UI::Web::cust_aligns(),
64                  'color' => [ 
65                               '',
66                               '',
67                               '',
68                               '',
69                               '',
70                               '',
71                               '',
72                               FS::UI::Web::cust_colors(),
73                             ],
74                  'style' => [ 
75                               '',
76                               '',
77                               '',
78                               '',
79                               '',
80                               '',
81                               '',
82                               FS::UI::Web::cust_styles(),
83                             ],
84            )
85 %>
86 <%init>
87
88 #LOTS of false laziness below w/cust_bill_pkg.cgi
89
90 die "access denied"
91   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
92
93 my $conf = new FS::Conf;
94
95 #here is the agent virtualization
96 my $agentnums_sql =
97   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
98
99 my @where = ( $agentnums_sql );
100
101 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
102 push @where, "cust_bill._date >= $beginning",
103              "cust_bill._date <= $ending";
104
105 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
106   push @where, "cust_main.agentnum = $1";
107 }
108
109 #classnum
110 # not specified: all classes
111 # 0: empty class
112 # N: classnum
113 my $use_override = $cgi->param('use_override');
114 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
115   my $comparison = '';
116   if ( $1 == 0 ) {
117     $comparison = "IS NULL";
118   } else {
119     $comparison = "= $1";
120   }
121
122   if ( $use_override ) {
123     push @where, "(
124       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
125       override.classnum $comparison AND pkgpart_override IS NOT NULL
126     )";
127   } else {
128     push @where, "part_pkg.classnum $comparison";
129   }
130 }
131
132 if ( $cgi->param('taxclass')
133      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
134                                 #(should we save a taxclass or a link to taxnum
135                                 # in cust_bill_pkg or something like
136                                 # cust_bill_pkg_tax_location?)
137    )
138 {
139
140   #override taxclass when use_override is specified?  probably
141   #if ( $use_override ) {
142   #
143   #  push @where,
144   #    ' ( '. join(' OR ',
145   #                  map {
146   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
147   #                        '      AND pkgpart_override IS NULL '.
148   #                        '   OR '.
149   #                        '      override.taxclass = '. dbh->quote($_).
150   #                        '      AND pkgpart_override IS NOT NULL '.
151   #                        ' ) '
152   #                      }
153   #                      $cgi->param('taxclass')
154   #               ).
155   #    ' ) ';
156   #
157   #} else {
158
159     push @where,
160       ' ( '. join(' OR ',
161                     map ' part_pkg.taxclass = '.dbh->quote($_),
162                         $cgi->param('taxclass')
163                  ).
164       ' ) ';
165
166   #}
167
168 }
169
170 my @loc_param = qw( city county state country );
171
172 if ( $cgi->param('out') ) {
173
174   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
175   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
176     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
177   }
178
179   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
180     if $cgi->param('istax');
181
182   push @where, "
183     0 = (
184           SELECT COUNT(*) FROM cust_main_county
185            WHERE cust_main_county.tax > 0
186              AND $loc_sql
187         )
188   ";
189
190   #not linked to by anything, but useful for debugging "out of taxable region"
191   if ( grep $cgi->param($_), @loc_param ) {
192
193     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
194
195     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
196     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
197       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
198     }
199
200     push @where, $loc_sql;
201
202   }
203
204 } elsif ( $cgi->param('country') ) {
205
206   my @counties = $cgi->param('county');
207    
208   if ( scalar(@counties) > 1 ) {
209
210     #hacky, could be more efficient.  care if it is ever used for more than the
211     # tax-report_groups filtering kludge
212
213     my $locs_sql =
214       ' ( '. join(' OR ', map {
215
216           my %ph = ( 'county' => dbh->quote($_),
217                      map { $_ => dbh->quote( $cgi->param($_) ) }
218                        qw( city state country )
219                    );
220
221           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
222           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
223             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
224           }
225
226           $loc_sql;
227
228         } @counties
229
230       ). ' ) ';
231
232     push @where, $locs_sql;
233
234   } else {
235
236     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
237
238     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
239     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
240       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
241     }
242
243     push @where, $loc_sql;
244
245   }
246    
247   my($title, $name);
248   if ( $cgi->param('istax') ) {
249     $title = 'Tax credits';
250     $name  = 'tax credits';
251     if ( $cgi->param('taxname') ) {
252       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
253     #} elsif ( $cgi->param('taxnameNULL') {
254     } else {
255       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
256     }
257   } elsif ( $cgi->param('nottax') ) {
258     $title = 'Credit applications to line items';
259     $name  = 'applications';
260     #what can we usefully do with "taxname" ????  look up a class???
261   } else {
262     $title = 'Credit applications to line items';
263     $name  = 'applications';
264     #warn "neither nottax nor istax parameters specified";
265   }
266
267   if ( $cgi->param('taxclassNULL') ) {
268
269     my %hash = ( 'country' => scalar($cgi->param('country')) );
270     foreach (qw( state county )) {
271       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
272     }
273     my $cust_main_county = qsearchs('cust_main_county', \%hash);
274     die "unknown base region for empty taxclass" unless $cust_main_county;
275
276     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
277     push @where, $same_sql if $same_sql;
278
279   }
280
281 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
282
283   # this should really be shoved out to FS::cust_pkg->location_sql or something
284   # along with the code in report_newtax.cgi
285
286   my %pn = (
287    'county'        => 'tax_rate_location.county',
288    'state'         => 'tax_rate_location.state',
289    'city'          => 'tax_rate_location.city',
290    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
291   );
292
293   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
294            qw( city county state locationtaxid );
295
296   push @where,
297     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
298                    keys %ph
299     );
300
301 }
302
303 if ( $cgi->param('itemdesc') ) {
304   if ( $cgi->param('itemdesc') eq 'Tax' ) {
305     push @where, "(itemdesc='Tax' OR itemdesc is null)";
306   } else {
307     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
308   }
309 }
310
311 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
312   my ( $group_op, $group_value ) = ( $1, $2 );
313   if ( $group_op eq '=' ) {
314     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
315     push @where, 'itemdesc = '. dbh->quote($group_value);
316   } elsif ( $group_op eq '!=' ) {
317     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
318   } else {
319     die "guru meditation #00de: group_op $group_op\n";
320   }
321   
322 }
323
324 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
325 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
326
327 if ( $cgi->param('cust_tax') ) {
328   #false laziness -ish w/report_tax.cgi
329   my $cust_exempt;
330   if ( $cgi->param('taxname') ) {
331     my $q_taxname = dbh->quote($cgi->param('taxname'));
332     $cust_exempt =
333       "( tax = 'Y'
334          OR EXISTS ( SELECT 1 FROM cust_main_exemption
335                        WHERE cust_main_exemption.custnum = cust_main.custnum
336                          AND cust_main_exemption.taxname = $q_taxname )
337        )
338       ";
339   } else {
340     $cust_exempt = " tax = 'Y' ";
341   }
342
343   push @where, $cust_exempt;
344 }
345
346 my $count_query = "SELECT COUNT(DISTINCT billpkgnum),
347                           SUM(cust_credit_bill_pkg.amount)";
348
349 my $join_cust =
350   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum ) 
351     LEFT JOIN cust_main ON ( cust_bill.custnum = cust_main.custnum ) ';
352
353
354 my $join_pkg;
355
356 my $join_cust_bill_pkg = 'LEFT JOIN cust_bill_pkg USING ( billpkgnum )';
357
358 if ( $cgi->param('nottax') ) {
359
360   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
361                  LEFT JOIN part_pkg USING ( pkgpart )
362                  LEFT JOIN part_pkg AS override
363                    ON pkgpart_override = override.pkgpart ';
364   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
365     if $conf->exists('tax-pkg_address');
366
367 } elsif ( $cgi->param('istax') ) {
368
369   #false laziness w/report_tax.cgi $taxfromwhere
370   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
371             $cgi->param('iscredit') eq 'rate') {
372
373     $join_pkg .=
374       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ';
375     if ( $cgi->param('iscredit') eq 'rate' ) {
376       $join_pkg .= ', billpkgtaxratelocationnum )';
377     } elsif ( $conf->exists('tax-pkg_address') ) {
378       $join_pkg .= ', billpkgtaxlocationnum )';
379       push @where, "billpkgtaxratelocationnum IS NULL";
380     } else {
381       $join_pkg .= ' )';
382       push @where, "billpkgtaxratelocationnum IS NULL";
383     }
384
385     $join_pkg .= ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
386
387   } elsif ( $conf->exists('tax-pkg_address') ) {
388
389     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
390                    LEFT JOIN cust_location              USING ( locationnum ) ';
391
392     #quelle kludge, somewhat false laziness w/report_tax.cgi
393     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
394   }
395
396 } else { 
397
398   #die?
399   warn "neiether nottax nor istax parameters specified";
400   #same as before?
401   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
402                  LEFT JOIN part_pkg USING ( pkgpart ) ';
403
404 }
405
406 my $where = ' WHERE '. join(' AND ', @where);
407
408 my $join_credit = ' LEFT JOIN cust_credit_bill USING ( creditbillnum )
409                     LEFT JOIN cust_credit      USING ( crednum ) ';
410
411 $count_query .= " FROM cust_credit_bill_pkg
412                          $join_pkg
413                          $join_cust_bill_pkg
414                          $join_credit
415                          $join_cust
416                        $where";
417
418 my @select = ( 'cust_credit_bill_pkg.*',
419                'cust_bill_pkg.*',
420                'cust_credit.otaker',
421                'cust_credit._date AS cust_credit_date',
422                'cust_bill._date',
423              );
424 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
425 push @select, 'cust_main.custnum',
426               FS::UI::Web::cust_sql_fields();
427
428 my $query = {
429   'table'     => 'cust_credit_bill_pkg',
430   'addl_from' => "$join_pkg
431                   $join_cust_bill_pkg
432                   $join_credit
433                   $join_cust",
434   'hashref'   => {},
435   'select'    => join(', ', @select ),
436   'extra_sql' => $where,
437   'order_by'  => 'ORDER BY creditbillpkgnum', #cust_bill. or cust_credit._date?
438 };
439
440 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
441 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
442
443 my $conf = new FS::Conf;
444 my $money_char = $conf->config('money_char') || '$';
445
446 </%init>