This commit was manufactured by cvs2svn to create tag 'freeside_2_1_0'.
[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                    '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                  'links'       => [
42                    '',
43                    '',
44                    '',
45                    '',
46                    '',
47                    $ilink,
48                    $ilink,
49                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
50                          FS::UI::Web::cust_header()
51                    ),
52                  ],
53                  'align' => 'rrlllrr'.FS::UI::Web::cust_aligns(),
54                  'color' => [ 
55                               '',
56                               '',
57                               '',
58                               '',
59                               '',
60                               '',
61                               '',
62                               FS::UI::Web::cust_colors(),
63                             ],
64                  'style' => [ 
65                               '',
66                               '',
67                               '',
68                               '',
69                               '',
70                               '',
71                               '',
72                               FS::UI::Web::cust_styles(),
73                             ],
74            )
75 %>
76 <%init>
77
78 #LOTS of false laziness below w/cust_bill_pkg.cgi
79
80 die "access denied"
81   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
82
83 my $conf = new FS::Conf;
84
85 #here is the agent virtualization
86 my $agentnums_sql =
87   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
88
89 my @where = ( $agentnums_sql );
90
91 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
92 push @where, "cust_bill._date >= $beginning",
93              "cust_bill._date <= $ending";
94
95 push @where , " payby != 'COMP' "
96   unless $cgi->param('include_comp_cust');
97
98 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
99   push @where, "cust_main.agentnum = $1";
100 }
101
102 #classnum
103 # not specified: all classes
104 # 0: empty class
105 # N: classnum
106 my $use_override = $cgi->param('use_override');
107 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
108   my $comparison = '';
109   if ( $1 == 0 ) {
110     $comparison = "IS NULL";
111   } else {
112     $comparison = "= $1";
113   }
114
115   if ( $use_override ) {
116     push @where, "(
117       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
118       override.classnum $comparison AND pkgpart_override IS NOT NULL
119     )";
120   } else {
121     push @where, "part_pkg.classnum $comparison";
122   }
123 }
124
125 if ( $cgi->param('taxclass')
126      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
127                                 #(should we save a taxclass or a link to taxnum
128                                 # in cust_bill_pkg or something like
129                                 # cust_bill_pkg_tax_location?)
130    )
131 {
132
133   #override taxclass when use_override is specified?  probably
134   #if ( $use_override ) {
135   #
136   #  push @where,
137   #    ' ( '. join(' OR ',
138   #                  map {
139   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
140   #                        '      AND pkgpart_override IS NULL '.
141   #                        '   OR '.
142   #                        '      override.taxclass = '. dbh->quote($_).
143   #                        '      AND pkgpart_override IS NOT NULL '.
144   #                        ' ) '
145   #                      }
146   #                      $cgi->param('taxclass')
147   #               ).
148   #    ' ) ';
149   #
150   #} else {
151
152     push @where,
153       ' ( '. join(' OR ',
154                     map ' part_pkg.taxclass = '.dbh->quote($_),
155                         $cgi->param('taxclass')
156                  ).
157       ' ) ';
158
159   #}
160
161 }
162
163 my @loc_param = qw( city county state country );
164
165 if ( $cgi->param('out') ) {
166
167   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
168   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
169     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
170   }
171
172   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
173     if $cgi->param('istax');
174
175   push @where, "
176     0 = (
177           SELECT COUNT(*) FROM cust_main_county
178            WHERE cust_main_county.tax > 0
179              AND $loc_sql
180         )
181   ";
182
183   #not linked to by anything, but useful for debugging "out of taxable region"
184   if ( grep $cgi->param($_), @loc_param ) {
185
186     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
187
188     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
189     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
190       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
191     }
192
193     push @where, $loc_sql;
194
195   }
196
197 } elsif ( $cgi->param('country') ) {
198
199   my @counties = $cgi->param('county');
200    
201   if ( scalar(@counties) > 1 ) {
202
203     #hacky, could be more efficient.  care if it is ever used for more than the
204     # tax-report_groups filtering kludge
205
206     my $locs_sql =
207       ' ( '. join(' OR ', map {
208
209           my %ph = ( 'county' => dbh->quote($_),
210                      map { $_ => dbh->quote( $cgi->param($_) ) }
211                        qw( city state country )
212                    );
213
214           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
215           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
216             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
217           }
218
219           $loc_sql;
220
221         } @counties
222
223       ). ' ) ';
224
225     push @where, $locs_sql;
226
227   } else {
228
229     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
230
231     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
232     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
233       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
234     }
235
236     push @where, $loc_sql;
237
238   }
239    
240   my($title, $name);
241   if ( $cgi->param('istax') ) {
242     $title = 'Tax credits';
243     $name  = 'tax credits';
244     if ( $cgi->param('taxname') ) {
245       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
246     #} elsif ( $cgi->param('taxnameNULL') {
247     } else {
248       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
249     }
250   } elsif ( $cgi->param('nottax') ) {
251     $title = 'Credit applications to line items';
252     $name  = 'applications';
253     #what can we usefully do with "taxname" ????  look up a class???
254   } else {
255     $title = 'Credit applications to line items';
256     $name  = 'applications';
257     #warn "neither nottax nor istax parameters specified";
258   }
259
260   if ( $cgi->param('taxclassNULL') ) {
261
262     my %hash = ( 'country' => scalar($cgi->param('country')) );
263     foreach (qw( state county )) {
264       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
265     }
266     my $cust_main_county = qsearchs('cust_main_county', \%hash);
267     die "unknown base region for empty taxclass" unless $cust_main_county;
268
269     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
270     push @where, $same_sql if $same_sql;
271
272   }
273
274 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
275
276   # this should really be shoved out to FS::cust_pkg->location_sql or something
277   # along with the code in report_newtax.cgi
278
279   my %pn = (
280    'county'        => 'tax_rate_location.county',
281    'state'         => 'tax_rate_location.state',
282    'city'          => 'tax_rate_location.city',
283    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
284   );
285
286   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
287            qw( city county state locationtaxid );
288
289   push @where,
290     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
291                    keys %ph
292     );
293
294 }
295
296 if ( $cgi->param('itemdesc') ) {
297   if ( $cgi->param('itemdesc') eq 'Tax' ) {
298     push @where, "(itemdesc='Tax' OR itemdesc is null)";
299   } else {
300     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
301   }
302 }
303
304 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
305   my ( $group_op, $group_value ) = ( $1, $2 );
306   if ( $group_op eq '=' ) {
307     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
308     push @where, 'itemdesc = '. dbh->quote($group_value);
309   } elsif ( $group_op eq '!=' ) {
310     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
311   } else {
312     die "guru meditation #00de: group_op $group_op\n";
313   }
314   
315 }
316
317 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
318 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
319
320 if ( $cgi->param('cust_tax') ) {
321   #false laziness -ish w/report_tax.cgi
322   my $cust_exempt;
323   if ( $cgi->param('taxname') ) {
324     my $q_taxname = dbh->quote($cgi->param('taxname'));
325     $cust_exempt =
326       "( tax = 'Y'
327          OR EXISTS ( SELECT 1 FROM cust_main_exemption
328                        WHERE cust_main_exemption.custnum = cust_main.custnum
329                          AND cust_main_exemption.taxname = $q_taxname )
330        )
331       ";
332   } else {
333     $cust_exempt = " tax = 'Y' ";
334   }
335
336   push @where, $cust_exempt;
337 }
338
339 my $use_usage = $cgi->param('use_usage');
340
341 my $count_query;
342 if ( $cgi->param('pkg_tax') ) { #does this mean anything here?
343
344   $count_query =
345     "SELECT COUNT(*),
346             SUM(
347                  ( CASE WHEN part_pkg.setuptax = 'Y'
348                         THEN cust_bill_pkg.setup
349                         ELSE 0
350                    END
351                  )
352                  +
353                  ( CASE WHEN part_pkg.recurtax = 'Y'
354                         THEN cust_bill_pkg.recur
355                         ELSE 0
356                    END
357                  )
358                )
359     ";
360
361   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
362                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
363                "( tax != 'Y' OR tax IS NULL )";
364
365 } elsif ( $cgi->param('taxable') ) { #again, meaningful?
366
367   my $setup_taxable = "(
368     CASE WHEN part_pkg.setuptax = 'Y'
369          THEN 0
370          ELSE cust_bill_pkg.setup
371     END
372   )";
373
374   my $recur_taxable = "(
375     CASE WHEN part_pkg.recurtax = 'Y'
376          THEN 0
377          ELSE cust_bill_pkg.recur
378     END
379   )";
380
381   my $exempt = "(
382     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
383       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
384   )";
385
386   $count_query =
387     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
388
389   push @where,
390     #not tax-exempt package (setup or recur)
391     "(
392           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
393             AND cust_bill_pkg.setup > 0 )
394        OR
395           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
396             AND cust_bill_pkg.recur > 0 )
397     )",
398     #not a tax_exempt customer
399     "( tax != 'Y' OR tax IS NULL )";
400     #not covered in full by a monthly tax exemption (texas tax)
401     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
402
403 } else {
404
405   $count_query = "SELECT COUNT(*), ";
406
407   if ( $use_usage eq 'recurring' ) { #mean anything?
408     $count_query .= "SUM(setup + recur - usage)";
409   } elsif ( $use_usage eq 'usage' ) { #mean anything?
410     $count_query .= "SUM(usage)";
411   } else {
412     $count_query .= "SUM(cust_credit_bill_pkg.amount)";
413   }
414
415 }
416
417 my $join_cust =
418   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum ) 
419     LEFT JOIN cust_main ON ( cust_bill.custnum = cust_main.custnum ) ';
420
421
422 my $join_pkg;
423
424 my $join_cust_bill_pkg = 'LEFT JOIN cust_bill_pkg USING ( billpkgnum ';
425
426 if ( $cgi->param('nottax') ) {
427
428   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
429                  LEFT JOIN part_pkg USING ( pkgpart )
430                  LEFT JOIN part_pkg AS override
431                    ON pkgpart_override = override.pkgpart ';
432   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
433     if $conf->exists('tax-pkg_address');
434
435 } elsif ( $cgi->param('istax') ) {
436
437   #false laziness w/report_tax.cgi $taxfromwhere
438   if ( $conf->exists('tax-pkg_address') ) {
439     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
440                    LEFT JOIN cust_location              USING ( locationnum ) ';
441
442     #quelle kludge, somewhat false laziness w/report_tax.cgi
443     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
444   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
445             $cgi->param('iscredit') eq 'rate') {
446     $join_pkg .=
447       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
448       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
449   }
450
451     if ( $conf->exists('tax-pkg_address') ) {
452       $join_cust_bill_pkg .= ', billpkgtaxlocationnum )';
453       push @where, "billpkgtaxratelocationnum IS NULL";
454     #} elsif ( $cgi->param('iscredit') eq 'rate' ) {
455     #  $join_pkg .= ', billpkgtaxratelocationnum )';
456     } else {
457       $join_cust_bill_pkg .= ' )';
458       push @where, "billpkgtaxratelocationnum IS NULL";
459     }
460
461 } else { 
462
463   #die?
464   warn "neiether nottax nor istax parameters specified";
465   #same as before?
466   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
467                  LEFT JOIN part_pkg USING ( pkgpart ) ';
468
469 }
470
471 my $where = ' WHERE '. join(' AND ', @where);
472
473 my $join_credit = ' LEFT JOIN cust_credit_bill USING ( creditbillnum )
474                     LEFT JOIN cust_credit      USING ( crednum ) ';
475
476 #if ($use_usage) {
477 #  $count_query .=
478 #    " FROM (SELECT cust_bill_pkg.setup, cust_bill_pkg.recur, 
479 #             ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_bill_pkg_detail
480 #               WHERE cust_bill_pkg.billpkgnum = cust_bill_pkg_detail.billpkgnum
481 #             ) AS usage FROM cust_bill_pkg  $join_cust $join_pkg $where
482 #           ) AS countquery";
483 #} else {
484   $count_query .= " FROM cust_credit_bill_pkg
485                         $join_pkg
486                         $join_cust_bill_pkg
487                         $join_credit
488                         $join_cust
489                       $where";
490 #}
491
492 my @select = ( 'cust_credit_bill_pkg.*',
493                'cust_bill_pkg.*',
494                'cust_credit.otaker',
495                'cust_credit._date AS cust_credit_date',
496                'cust_bill._date',
497              );
498 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
499 push @select, 'cust_main.custnum',
500               FS::UI::Web::cust_sql_fields();
501
502 my $query = {
503   'table'     => 'cust_credit_bill_pkg',
504   'addl_from' => "$join_pkg
505                   $join_cust_bill_pkg
506                   $join_credit
507                   $join_cust",
508   'hashref'   => {},
509   'select'    => join(', ', @select ),
510   'extra_sql' => $where,
511   'order_by'  => 'ORDER BY creditbillpkgnum', #cust_bill. or cust_credit._date?
512 };
513
514 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
515 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
516
517 my $conf = new FS::Conf;
518 my $money_char = $conf->config('money_char') || '$';
519
520 </%init>