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