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