63d70c27e06498ad18eb2b8c927d1ca694fbac91
[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
207   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
208   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
209     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
210   }
211
212   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
213     if $cgi->param('istax');
214
215   push @where, "
216     0 = (
217           SELECT COUNT(*) FROM cust_main_county
218            WHERE cust_main_county.tax > 0
219              AND $loc_sql
220         )
221   ";
222
223   #not linked to by anything, but useful for debugging "out of taxable region"
224   if ( grep $cgi->param($_), @loc_param ) {
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 } elsif ( $cgi->param('country') ) {
238
239   my @counties = $cgi->param('county');
240    
241   if ( scalar(@counties) > 1 ) {
242
243     #hacky, could be more efficient.  care if it is ever used for more than the
244     # tax-report_groups filtering kludge
245
246     my $locs_sql =
247       ' ( '. join(' OR ', map {
248
249           my %ph = ( 'county' => dbh->quote($_),
250                      map { $_ => dbh->quote( $cgi->param($_) ) }
251                        qw( district city state country )
252                    );
253
254           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
255           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
256             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
257           }
258
259           $loc_sql;
260
261         } @counties
262
263       ). ' ) ';
264
265     push @where, $locs_sql;
266
267   } else {
268
269     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
270
271     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
272     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
273       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
274     }
275
276     push @where, $loc_sql;
277
278   }
279    
280   my($title, $name);
281   if ( $cgi->param('istax') ) {
282     $title = 'Tax credits';
283     $name  = 'tax credits';
284     if ( $cgi->param('taxname') ) {
285       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
286     #} elsif ( $cgi->param('taxnameNULL') {
287     } else {
288       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
289     }
290   } elsif ( $cgi->param('nottax') ) {
291     $title = 'Credit applications to line items';
292     $name  = 'applications';
293     #what can we usefully do with "taxname" ????  look up a class???
294   } else {
295     $title = 'Credit applications to line items';
296     $name  = 'applications';
297     #warn "neither nottax nor istax parameters specified";
298   }
299
300   if ( $cgi->param('taxclassNULL')
301        && ! $cgi->param('istax')  #no taxclass in this case
302      )
303   {
304
305     my %hash = ( 'country' => scalar($cgi->param('country')) );
306     foreach (qw( state county )) {
307       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
308     }
309     my $cust_main_county = qsearchs('cust_main_county', \%hash);
310     die "unknown base region for empty taxclass" unless $cust_main_county;
311
312     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
313     push @where, $same_sql if $same_sql;
314
315   }
316
317 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
318
319   # this should really be shoved out to FS::cust_pkg->location_sql or something
320   # along with the code in report_newtax.cgi
321
322   my %pn = (
323    'county'        => 'tax_rate_location.county',
324    'state'         => 'tax_rate_location.state',
325    'city'          => 'tax_rate_location.city',
326    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
327   );
328
329   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
330            qw( city county state locationtaxid );
331
332   push @where,
333     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
334                    keys %ph
335     );
336
337 }
338
339 if ( $cgi->param('itemdesc') ) {
340   if ( $cgi->param('itemdesc') eq 'Tax' ) {
341     push @where, "(itemdesc='Tax' OR itemdesc is null)";
342   } else {
343     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
344   }
345 }
346
347 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
348   my ( $group_op, $group_value ) = ( $1, $2 );
349   if ( $group_op eq '=' ) {
350     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
351     push @where, 'itemdesc = '. dbh->quote($group_value);
352   } elsif ( $group_op eq '!=' ) {
353     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
354   } else {
355     die "guru meditation #00de: group_op $group_op\n";
356   }
357   
358 }
359
360 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
361 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
362
363 if ( $cgi->param('cust_tax') ) {
364   #false laziness -ish w/report_tax.cgi
365   my $cust_exempt;
366   if ( $cgi->param('taxname') ) {
367     my $q_taxname = dbh->quote($cgi->param('taxname'));
368     $cust_exempt =
369       "( tax = 'Y'
370          OR EXISTS ( SELECT 1 FROM cust_main_exemption
371                        WHERE cust_main_exemption.custnum = cust_main.custnum
372                          AND cust_main_exemption.taxname = $q_taxname )
373        )
374       ";
375   } else {
376     $cust_exempt = " tax = 'Y' ";
377   }
378
379   push @where, $cust_exempt;
380 }
381
382 my $count_query = "SELECT COUNT(DISTINCT creditbillpkgnum),
383                           SUM(cust_credit_bill_pkg.amount)";
384
385 my $join_cust =
386   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum )'.
387   FS::UI::Web::join_cust_main('cust_bill', 'cust_pkg');
388
389
390 my $join_pkg;
391
392 my $join_cust_bill_pkg = 'LEFT JOIN cust_bill_pkg USING ( billpkgnum )';
393
394 if ( $cgi->param('nottax') ) {
395
396   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
397                  LEFT JOIN part_pkg USING ( pkgpart )
398                  LEFT JOIN part_pkg AS override
399                    ON pkgpart_override = override.pkgpart ';
400   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
401     if $conf->exists('tax-pkg_address');
402
403 } elsif ( $cgi->param('istax') ) {
404
405   #false laziness w/report_tax.cgi $taxfromwhere
406   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
407             $cgi->param('iscredit') eq 'rate') {
408
409     $join_pkg .=
410       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ';
411     if ( $cgi->param('iscredit') eq 'rate' ) {
412       $join_pkg .= ', billpkgtaxratelocationnum )';
413     } elsif ( $conf->exists('tax-pkg_address') ) {
414       $join_pkg .= ', billpkgtaxlocationnum )';
415       push @where, "billpkgtaxratelocationnum IS NULL";
416     } else {
417       $join_pkg .= ' )';
418       push @where, "billpkgtaxratelocationnum IS NULL";
419     }
420
421     $join_pkg .= ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
422
423   } elsif ( $conf->exists('tax-pkg_address') ) {
424
425     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
426                    LEFT JOIN cust_location              USING ( locationnum ) ';
427
428     #quelle kludge, somewhat false laziness w/report_tax.cgi
429     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
430   }
431
432 } else {
433
434   #warn "neither nottax nor istax parameters specified";
435   #same as before?
436   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
437                  LEFT JOIN part_pkg USING ( pkgpart ) ';
438
439 }
440
441 my $where = ' WHERE '. join(' AND ', @where);
442
443 my $join_credit = ' LEFT JOIN cust_credit_bill USING ( creditbillnum )
444                     LEFT JOIN cust_credit      USING ( crednum ) ';
445
446 $count_query .= " FROM cust_credit_bill_pkg
447                          $join_cust_bill_pkg
448                          $join_pkg
449                          $join_credit
450                          $join_cust
451                        $where";
452
453 my @select = ( 'cust_credit_bill_pkg.*',
454                'cust_bill_pkg.*',
455                'cust_credit.otaker',
456                'cust_credit._date AS cust_credit_date',
457                'cust_bill._date',
458              );
459 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
460 push @select, 'cust_main.custnum',
461               FS::UI::Web::cust_sql_fields();
462
463 my @post_desc_header = ();
464 my @post_desc = ();
465 my @post_desc_null = ();
466 my $post_desc_align = '';
467 if ( $conf->exists('enable_taxclasses') && ! $cgi->param('istax') ) {
468   push @post_desc_header, 'Tax class';
469   push @post_desc, 'taxclass';
470   push @post_desc_null, '';
471   $post_desc_align .= 'l';
472   push @select, 'part_pkg.taxclass'; # or should this use override?
473 }
474
475 my $query = {
476   'table'     => 'cust_credit_bill_pkg',
477   'addl_from' => "$join_cust_bill_pkg
478                   $join_pkg
479                   $join_credit
480                   $join_cust",
481   'hashref'   => {},
482   'select'    => join(', ', @select ),
483   'extra_sql' => $where,
484   'order_by'  => 'ORDER BY creditbillpkgnum', #cust_bill. or cust_credit._date?
485 };
486
487 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
488 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
489
490 my $conf = new FS::Conf;
491 my $money_char = $conf->config('money_char') || '$';
492
493 my $tax_pkg_address = $conf->exists('tax-pkg_address');
494 my $tax_ship_address = $conf->exists('tax-ship_address');
495
496 my $location_sub = sub {
497   #my $cust_credit_bill_pkg = shift;
498   my $self = shift;
499   my $tax_Xlocation = $self->cust_bill_pkg_tax_Xlocation;
500   if ( defined($tax_Xlocation) && $tax_Xlocation ) {
501
502     if ( ref($tax_Xlocation) eq 'FS::cust_bill_pkg_tax_location' ) {
503
504       if ( $tax_Xlocation->taxtype eq 'FS::cust_main_county' ) {
505         my $cust_main_county = $tax_Xlocation->cust_main_county;
506         if ( $cust_main_county ) {
507           $cust_main_county->label;
508         } else {
509           ''; #cust_main_county record is gone... history?  yuck.
510         }
511       } else {
512         '(CCH tax_rate)'; #XXX FS::tax_rate.. vendor taxes not yet handled here
513       }
514
515     } elsif ( ref($tax_Xlocation) eq 'FS::cust_bill_pkg_tax_rate_location' ) {
516       '(CCH)'; #XXX vendor taxes not yet handled here
517     } else {
518       'unknown tax_Xlocation '. ref($tax_Xlocation);
519     }
520
521   } else {
522
523     my $cust_bill_pkg = $self->cust_bill_pkg;
524     if ( $cust_bill_pkg->pkgnum > 0 ) {
525       my $cust_pkg = $cust_bill_pkg->cust_pkg;
526       if ( $tax_pkg_address && (my $cust_location = $cust_pkg->cust_location) ){
527         $cust_location->county_state_country;
528       } else {
529         my $cust_main = $cust_pkg->cust_main;
530         if ( $tax_ship_address && $cust_main->has_ship_address ) {
531           $cust_main->county_state_country('ship_');
532         } else {
533           $cust_main->county_state_country;
534         }
535       }
536
537     } else {
538       #tax?  we shouldn't have wound up here then...
539       ''; #return customer ship or bill address? (depending on tax-ship_address)
540     }
541
542   }
543
544 };
545
546 </%init>