add credited sales column to tax report, #37088
[freeside.git] / httemplate / search / cust_credit_bill_pkg.html
1 <& elements/search.html,
2               'title'         => 'Credit application detail', #to line item
3               'name_singular' => 'credit application',
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                    'Location',
20                    @post_desc_header,
21
22                    #invoice
23                    'Invoice',
24                    'Date',
25                    FS::UI::Web::cust_header(),
26                ],
27                'fields'       => [
28                    #'creditbillpkgnum',
29                    sub { sprintf($money_char.'%.2f', shift->amount ) },
30
31                    sub { time2str('%b %d %Y', shift->get('cust_credit_date') ) },
32                    sub { shift->cust_credit_bill->cust_credit->otaker },
33                    sub { shift->cust_credit_bill->cust_credit->reason },
34
35                    sub { $_[0]->pkgnum > 0
36                            ? $_[0]->get('pkg')      # possibly use override.pkg
37                            : $_[0]->get('itemdesc') # but i think this correct
38                        },
39                    $location_sub,
40                    @post_desc,
41                    'invnum',
42                    sub { time2str('%b %d %Y', shift->_date ) },
43                    \&FS::UI::Web::cust_fields,
44                ],
45                'sort_fields'  => [
46                    'amount',
47                    'cust_credit_date',
48                    '', #'otaker',
49                    '', #reason
50                    '', #line item description
51                    '', #location
52                    @post_desc_null,
53                    'invnum',
54                    '_date',
55                    #cust fields
56                ],
57                'links' => [
58                    '',
59                    '',
60                    '',
61                    '',
62                    '',
63                    '',
64                    @post_desc_null,
65                    $ilink,
66                    $ilink,
67                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
68                          FS::UI::Web::cust_header()
69                    ),
70                ],
71                'align' => 'rrllll'.
72                           $post_desc_align.
73                           'rr'.
74                           FS::UI::Web::cust_aligns(),
75                'color' => [ 
76                               '',
77                               '',
78                               '',
79                               '',
80                               '',
81                               '',
82                               @post_desc_null,
83                               '',
84                               '',
85                               FS::UI::Web::cust_colors(),
86                             ],
87                'style' => [ 
88                               '',
89                               '',
90                               '',
91                               '',
92                               '',
93                               '',
94                               @post_desc_null,
95                               '',
96                               '',
97                               FS::UI::Web::cust_styles(),
98                           ],
99            
100 &>
101 <%init>
102
103 #LOTS of false laziness below w/cust_bill_pkg.cgi
104 # and a little w/cust_credit.html
105
106 die "access denied"
107   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
108
109 my $conf = new FS::Conf;
110
111 #here is the agent virtualization
112 my $agentnums_sql =
113   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
114
115 my @where = ( $agentnums_sql );
116
117 if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
118   push @where, "cust_credit.usernum = $1";
119 }
120
121 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
122 push @where, "cust_bill._date >= $beginning",
123              "cust_bill._date <= $ending";
124
125 my($cr_begin, $cr_end) = FS::UI::Web::parse_beginning_ending($cgi, 'credit');
126 push @where, "cust_credit._date >= $cr_begin",
127              "cust_credit._date <= $cr_end";
128
129 #credit amount?  seems more what is expected than the applied amount
130 my @lt_gt = FS::UI::Web::parse_lt_gt($cgi, 'amount' );
131 s/amount/cust_credit.amount/g foreach (@lt_gt);
132 push @where, @lt_gt;
133
134 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
135   push @where, "cust_main.agentnum = $1";
136 }
137
138 if ( $cgi->param('billpkgnum') =~ /^(\d+)$/ ) {
139   push @where, "billpkgnum = $1";
140 }
141
142 #classnum
143 # not specified: all classes
144 # 0: empty class
145 # N: classnum
146 my $use_override = $cgi->param('use_override');
147 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
148   my $comparison = '';
149   if ( $1 == 0 ) {
150     $comparison = "IS NULL";
151   } else {
152     $comparison = "= $1";
153   }
154
155   if ( $use_override ) {
156     push @where, "(
157       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
158       override.classnum $comparison AND pkgpart_override IS NOT NULL
159     )";
160   } else {
161     push @where, "part_pkg.classnum $comparison";
162   }
163 }
164
165 if ( $cgi->param('taxclass')
166      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
167                                 #(should we save a taxclass or a link to taxnum
168                                 # in cust_bill_pkg or something like
169                                 # cust_bill_pkg_tax_location?)
170    )
171 {
172
173   #override taxclass when use_override is specified?  probably
174   #if ( $use_override ) {
175   #
176   #  push @where,
177   #    ' ( '. join(' OR ',
178   #                  map {
179   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
180   #                        '      AND pkgpart_override IS NULL '.
181   #                        '   OR '.
182   #                        '      override.taxclass = '. dbh->quote($_).
183   #                        '      AND pkgpart_override IS NOT NULL '.
184   #                        ' ) '
185   #                      }
186   #                      $cgi->param('taxclass')
187   #               ).
188   #    ' ) ';
189   #
190   #} else {
191
192     push @where,
193       ' ( '. join(' OR ',
194                     map ' part_pkg.taxclass = '.dbh->quote($_),
195                         $cgi->param('taxclass')
196                  ).
197       ' ) ';
198
199   #}
200
201 }
202
203 my @loc_param = qw( district city county state country );
204
205 if ( $cgi->param('out') ) {
206   # probably don't need this part
207
208   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
209   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
210     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
211   }
212
213   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
214     if $cgi->param('istax');
215
216   push @where, "
217     0 = (
218           SELECT COUNT(*) FROM cust_main_county
219            WHERE cust_main_county.tax > 0
220              AND $loc_sql
221         )
222   ";
223
224   #not linked to by anything, but useful for debugging "out of taxable region"
225   if ( grep $cgi->param($_), @loc_param ) {
226
227     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
228
229     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
230     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
231       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
232     }
233
234     push @where, $loc_sql;
235
236   }
237
238 } elsif ( $cgi->param('country') ) {
239
240   my @counties = $cgi->param('county');
241    
242   if ( scalar(@counties) > 1 ) {
243
244     #hacky, could be more efficient.  care if it is ever used for more than the
245     # tax-report_groups filtering kludge
246     # (does that even still exist? if so, correct this (or location_sql itself)
247     # to work with modern cust_location links)
248
249     my $locs_sql =
250       ' ( '. join(' OR ', map {
251
252           my %ph = ( 'county' => dbh->quote($_),
253                      map { $_ => dbh->quote( $cgi->param($_) ) }
254                        qw( district city state country )
255                    );
256
257           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
258           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
259             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
260           }
261
262           $loc_sql;
263
264         } @counties
265
266       ). ' ) ';
267
268     push @where, $locs_sql;
269
270   } else {
271
272     my @loc_where;
273     foreach (@loc_param) {
274       if ( length($cgi->param($_)) ) {
275         my $quoted = dbh->quote($cgi->param($_));
276         push @loc_where, "(COALESCE(cust_location.$_, '') = $quoted)";
277       }
278     }
279     my $loc_sql = join(' AND ', @loc_where);
280
281     #my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
282     #
283     #my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
284     #while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
285     #  $loc_sql =~ s/\?/$ph{shift(@param)}/e;
286     #}
287
288     push @where, $loc_sql;
289 warn $loc_sql;
290   }
291    
292   my($title, $name);
293   if ( $cgi->param('istax') ) {
294     $title = 'Tax credits';
295     $name  = 'tax credits';
296     if ( $cgi->param('taxname') ) {
297       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
298     #} elsif ( $cgi->param('taxnameNULL') {
299     } else {
300       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
301     }
302   } elsif ( $cgi->param('nottax') ) {
303     $title = 'Credit applications to line items';
304     $name  = 'applications';
305     #what can we usefully do with "taxname" ????  look up a class???
306   } else {
307     $title = 'Credit applications to line items';
308     $name  = 'applications';
309     #warn "neither nottax nor istax parameters specified";
310   }
311
312   if ( $cgi->param('taxclassNULL')
313        && ! $cgi->param('istax')  #no taxclass in this case
314      )
315   {
316
317     my %hash = ( 'country' => scalar($cgi->param('country')) );
318     foreach (qw( state county )) {
319       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
320     }
321     my $cust_main_county = qsearchs('cust_main_county', \%hash);
322     die "unknown base region for empty taxclass" unless $cust_main_county;
323
324     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
325     push @where, $same_sql if $same_sql;
326
327   }
328
329 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
330
331   # this should really be shoved out to FS::cust_pkg->location_sql or something
332   # along with the code in report_newtax.cgi
333
334   my %pn = (
335    'county'        => 'tax_rate_location.county',
336    'state'         => 'tax_rate_location.state',
337    'city'          => 'tax_rate_location.city',
338    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
339   );
340
341   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
342            qw( city county state locationtaxid );
343
344   push @where,
345     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
346                    keys %ph
347     );
348
349 }
350
351 if ( $cgi->param('itemdesc') ) {
352   if ( $cgi->param('itemdesc') eq 'Tax' ) {
353     push @where, "(itemdesc='Tax' OR itemdesc is null)";
354   } else {
355     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
356   }
357 }
358
359 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
360   my ( $group_op, $group_value ) = ( $1, $2 );
361   if ( $group_op eq '=' ) {
362     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
363     push @where, 'itemdesc = '. dbh->quote($group_value);
364   } elsif ( $group_op eq '!=' ) {
365     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
366   } else {
367     die "guru meditation #00de: group_op $group_op\n";
368   }
369   
370 }
371
372 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
373 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
374
375 if ( $cgi->param('cust_tax') ) {
376   #false laziness -ish w/report_tax.cgi
377   my $cust_exempt;
378   if ( $cgi->param('taxname') ) {
379     my $q_taxname = dbh->quote($cgi->param('taxname'));
380     $cust_exempt =
381       "( tax = 'Y'
382          OR EXISTS ( SELECT 1 FROM cust_main_exemption
383                        WHERE cust_main_exemption.custnum = cust_main.custnum
384                          AND cust_main_exemption.taxname = $q_taxname )
385        )
386       ";
387   } else {
388     $cust_exempt = " tax = 'Y' ";
389   }
390
391   push @where, $cust_exempt;
392 }
393
394 my $count_query = "SELECT COUNT(DISTINCT creditbillpkgnum),
395                           SUM(cust_credit_bill_pkg.amount)";
396
397 my $join_cust =
398   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum )'.
399   FS::UI::Web::join_cust_main('cust_bill', 'cust_pkg');
400
401
402 my $join_pkg;
403
404 my $join_cust_bill_pkg = 'LEFT JOIN cust_bill_pkg USING ( billpkgnum )';
405
406 if ( $cgi->param('nottax') ) {
407
408   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
409                  LEFT JOIN part_pkg USING ( pkgpart )
410                  LEFT JOIN part_pkg AS override
411                    ON pkgpart_override = override.pkgpart ';
412   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
413     if $conf->exists('tax-pkg_address');
414
415 } elsif ( $cgi->param('istax') ) {
416
417   #false laziness w/report_tax.cgi $taxfromwhere
418   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
419             $cgi->param('iscredit') eq 'rate') {
420
421     $join_pkg .=
422       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ';
423     if ( $cgi->param('iscredit') eq 'rate' ) {
424       $join_pkg .= ', billpkgtaxratelocationnum )';
425     } elsif ( $conf->exists('tax-pkg_address') ) {
426       $join_pkg .= ', billpkgtaxlocationnum )';
427       push @where, "billpkgtaxratelocationnum IS NULL";
428     } else {
429       $join_pkg .= ' )';
430       push @where, "billpkgtaxratelocationnum IS NULL";
431     }
432
433     $join_pkg .= ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
434
435   } elsif ( $conf->exists('tax-pkg_address') ) {
436
437     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
438                    LEFT JOIN cust_location              USING ( locationnum ) ';
439
440     #quelle kludge, somewhat false laziness w/report_tax.cgi
441     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
442   }
443
444 } else {
445
446   #warn "neither nottax nor istax parameters specified";
447   #same as before?
448   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
449                  LEFT JOIN part_pkg USING ( pkgpart ) ';
450
451 }
452
453 my $where = ' WHERE '. join(' AND ', @where);
454
455 my $join_credit = ' LEFT JOIN cust_credit_bill USING ( creditbillnum )
456                     LEFT JOIN cust_credit      USING ( crednum ) ';
457
458 $count_query .= " FROM cust_credit_bill_pkg
459                          $join_cust_bill_pkg
460                          $join_pkg
461                          $join_credit
462                          $join_cust
463                        $where";
464
465 my @select = ( 'cust_credit_bill_pkg.*',
466                'cust_bill_pkg.*',
467                'cust_credit.otaker',
468                'cust_credit._date AS cust_credit_date',
469                'cust_bill._date',
470              );
471 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
472 push @select, 'cust_main.custnum',
473               FS::UI::Web::cust_sql_fields();
474
475 my @post_desc_header = ();
476 my @post_desc = ();
477 my @post_desc_null = ();
478 my $post_desc_align = '';
479 if ( $conf->exists('enable_taxclasses') && ! $cgi->param('istax') ) {
480   push @post_desc_header, 'Tax class';
481   push @post_desc, 'taxclass';
482   push @post_desc_null, '';
483   $post_desc_align .= 'l';
484   push @select, 'part_pkg.taxclass'; # or should this use override?
485 }
486
487 my $query = {
488   'table'     => 'cust_credit_bill_pkg',
489   'addl_from' => "$join_cust_bill_pkg
490                   $join_pkg
491                   $join_credit
492                   $join_cust",
493   'hashref'   => {},
494   'select'    => join(', ', @select ),
495   'extra_sql' => $where,
496   'order_by'  => 'ORDER BY creditbillpkgnum', #cust_bill. or cust_credit._date?
497 };
498
499 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
500 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
501
502 my $conf = new FS::Conf;
503 my $money_char = $conf->config('money_char') || '$';
504
505 my $tax_pkg_address = $conf->exists('tax-pkg_address');
506 my $tax_ship_address = $conf->exists('tax-ship_address');
507
508 my $location_sub = sub {
509   #my $cust_credit_bill_pkg = shift;
510   my $self = shift;
511   my $tax_Xlocation = $self->cust_bill_pkg_tax_Xlocation;
512   if ( defined($tax_Xlocation) && $tax_Xlocation ) {
513
514     if ( ref($tax_Xlocation) eq 'FS::cust_bill_pkg_tax_location' ) {
515
516       if ( $tax_Xlocation->taxtype eq 'FS::cust_main_county' ) {
517         my $cust_main_county = $tax_Xlocation->cust_main_county;
518         if ( $cust_main_county ) {
519           $cust_main_county->label;
520         } else {
521           ''; #cust_main_county record is gone... history?  yuck.
522         }
523       } else {
524         '(CCH tax_rate)'; #XXX FS::tax_rate.. vendor taxes not yet handled here
525       }
526
527     } elsif ( ref($tax_Xlocation) eq 'FS::cust_bill_pkg_tax_rate_location' ) {
528       '(CCH)'; #XXX vendor taxes not yet handled here
529     } else {
530       'unknown tax_Xlocation '. ref($tax_Xlocation);
531     }
532
533   } else {
534
535     my $cust_bill_pkg = $self->cust_bill_pkg;
536     if ( $cust_bill_pkg->pkgnum > 0 ) {
537       my $cust_pkg = $cust_bill_pkg->cust_pkg;
538       if ( $tax_pkg_address && (my $cust_location = $cust_pkg->cust_location) ){
539         $cust_location->county_state_country;
540       } else {
541         my $cust_main = $cust_pkg->cust_main;
542         if ( $tax_ship_address && $cust_main->has_ship_address ) {
543           $cust_main->county_state_country('ship_');
544         } else {
545           $cust_main->county_state_country;
546         }
547       }
548
549     } else {
550       #tax?  we shouldn't have wound up here then...
551       ''; #return customer ship or bill address? (depending on tax-ship_address)
552     }
553
554   }
555
556 };
557
558 </%init>