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