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