maybe this willf inally fix total line links on tax report when using report_group...
[freeside.git] / httemplate / search / cust_bill_pkg.cgi
1 <% include( 'elements/search.html',
2                  'title'       => 'Line items',
3                  'name'        => 'line items',
4                  'query'       => $query,
5                  'count_query' => $count_query,
6                  'count_addl'  => [ $money_char. '%.2f total', ],
7                  'header'      => [
8                    '#',
9                    'Description',
10                    'Setup charge',
11                    'Recurring charge',
12                    'Invoice',
13                    'Date',
14                    FS::UI::Web::cust_header(),
15                  ],
16                  'fields'      => [
17                    'billpkgnum',
18                    sub { $_[0]->pkgnum > 0
19                            ? $_[0]->get('pkg')
20                            : $_[0]->get('itemdesc')
21                        },
22                    #strikethrough or "N/A ($amount)" or something these when
23                    # they're not applicable to pkg_tax search
24                    sub { sprintf($money_char.'%.2f', shift->setup ) },
25                    sub { sprintf($money_char.'%.2f', shift->recur ) },
26                    'invnum',
27                    sub { time2str('%b %d %Y', shift->_date ) },
28                    \&FS::UI::Web::cust_fields,
29                  ],
30                  'links'       => [
31                    '',
32                    '',
33                    '',
34                    '',
35                    $ilink,
36                    $ilink,
37                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
38                          FS::UI::Web::cust_header()
39                    ),
40                  ],
41                  'align' => 'rlrrrc'.FS::UI::Web::cust_aligns(),
42                  'color' => [ 
43                               '',
44                               '',
45                               '',
46                               '',
47                               '',
48                               '',
49                               FS::UI::Web::cust_colors(),
50                             ],
51                  'style' => [ 
52                               '',
53                               '',
54                               '',
55                               '',
56                               '',
57                               '',
58                               FS::UI::Web::cust_styles(),
59                             ],
60            )
61 %>
62 <%init>
63
64 die "access denied"
65   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
66
67 my $conf = new FS::Conf;
68
69 #here is the agent virtualization
70 my $agentnums_sql =
71   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
72
73 my @where = ( $agentnums_sql );
74
75 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
76 push @where, "_date >= $beginning",
77              "_date <= $ending";
78
79 push @where , " payby != 'COMP' "
80   unless $cgi->param('include_comp_cust');
81
82 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
83   push @where, "cust_main.agentnum = $1";
84 }
85
86 #classnum
87 # not specified: all classes
88 # 0: empty class
89 # N: classnum
90 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
91   if ( $1 == 0 ) {
92     push @where, "classnum IS NULL";
93   } else {
94     push @where, "classnum = $1";
95   }
96 }
97
98 push @where, map ' taxclass = '.dbh->quote($_), $cgi->param('taxclass')
99   if $cgi->param('taxclass')
100   && ! $cgi->param('istax'); #no part_pkg.taxclass in this case
101                              #(should we save a taxclass or a link to taxnum
102                              # in cust_bill_pkg or something like
103                              # cust_bill_pkg_tax_location?)
104
105 #sub _where {
106 # my $table = shift;
107 # my $prefix = @_ ? shift : '';
108 # "
109 #      (    cust_main_county.county  = $table.${prefix}.county
110 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county  =  '' )
111 #      OR ( cust_main_county.county  =  ''  AND $table.${prefix}.county IS NULL)
112 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county IS NULL)
113 #      )
114 #  AND (    cust_main_county.state   = $table.${prefix}.state
115 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state  =  ''  )
116 #      OR ( cust_main_county.state   =  ''  AND $table.${prefix}.state IS NULL )
117 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state IS NULL )
118 #      )
119 #  AND cust_main_county.country = $table.${prefix}.country
120 # ";
121 #
122 #}
123
124 if ( $cgi->param('out') ) {
125
126   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
127   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
128     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
129   }
130
131   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
132     if $cgi->param('istax');
133
134   push @where, "
135     0 = (
136           SELECT COUNT(*) FROM cust_main_county
137            WHERE cust_main_county.tax > 0
138              AND $loc_sql
139         )
140   ";
141
142   #not linked to by anything, but useful for debugging "out of taxable region"
143   if ( grep $cgi->param($_), qw( county state country ) ) {
144
145     my %ph = map { $_ => dbh->quote( $cgi->param($_) ) }
146                  qw( county state country );
147
148     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
149     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
150       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
151     }
152
153     push @where, $loc_sql;
154
155   }
156
157 } elsif ( $cgi->param('country') ) {
158
159   my @counties = $cgi->param('county');
160    
161   if ( scalar(@counties) > 1 ) {
162
163     #hacky, could be more efficient.  care if it is ever used for more than the
164     # tax-report_groups filtering kludge
165
166     my $locs_sql =
167       ' ( '. join(' OR ', map {
168
169           my %ph = ( 'county' => $_,
170                      map { $_ => dbh->quote( $cgi->param($_) ) }
171                        qw( state country )
172                    );
173
174           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
175           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
176             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
177           }
178
179           $loc_sql;
180
181         } @counties
182
183       ). ' ) ';
184
185     push @where, $locs_sql;
186
187   } else {
188
189     my %ph = map { $_ => dbh->quote( $cgi->param($_) ) }
190                  qw( county state country );
191
192     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
193     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
194       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
195     }
196
197     push @where, $loc_sql;
198
199   }
200    
201   if ( $cgi->param('istax') ) {
202     if ( $cgi->param('taxname') ) {
203       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
204     #} elsif ( $cgi->param('taxnameNULL') {
205     } else {
206       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
207     }
208   } elsif ( $cgi->param('nottax') ) {
209     #what can we usefully do with "taxname" ????  look up a class???
210   } else {
211     #warn "neither nottax nor istax parameters specified";
212   }
213
214   if ( $cgi->param('taxclassNULL') ) {
215
216     my %hash = ( 'country' => scalar($cgi->param('country')) );
217     foreach (qw( state county )) {
218       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
219     }
220     my $cust_main_county = qsearchs('cust_main_county', \%hash);
221     die "unknown base region for empty taxclass" unless $cust_main_county;
222
223     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
224     push @where, $same_sql if $same_sql;
225
226   }
227
228 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
229
230   # this should really be shoved out to FS::cust_pkg->location_sql or something
231   # along with the code in report_newtax.cgi
232
233   my %pn = (
234    'county'        => 'tax_rate_location.county',
235    'state'         => 'tax_rate_location.state',
236    'city'          => 'tax_rate_location.city',
237    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
238   );
239
240   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
241            qw( county state city locationtaxid );
242
243   push @where,
244     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
245                    keys %ph
246     );
247
248 }
249
250 if ( $cgi->param('itemdesc') ) {
251   if ( $cgi->param('itemdesc') eq 'Tax' ) {
252     push @where, "(itemdesc='Tax' OR itemdesc is null)";
253   } else {
254     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
255   }
256 }
257
258 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
259   my ( $group_op, $group_value ) = ( $1, $2 );
260   if ( $group_op eq '=' ) {
261     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
262     push @where, 'itemdesc = '. dbh->quote($group_value);
263   } elsif ( $group_op eq '!=' ) {
264     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
265   } else {
266     die "guru meditation #00de: group_op $group_op\n";
267   }
268   
269 }
270
271 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
272 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
273
274 push @where, " tax = 'Y' " if $cgi->param('cust_tax');
275
276 my $count_query;
277 if ( $cgi->param('pkg_tax') ) {
278
279   $count_query =
280     "SELECT COUNT(*),
281             SUM(
282                  ( CASE WHEN part_pkg.setuptax = 'Y'
283                         THEN cust_bill_pkg.setup
284                         ELSE 0
285                    END
286                  )
287                  +
288                  ( CASE WHEN part_pkg.recurtax = 'Y'
289                         THEN cust_bill_pkg.recur
290                         ELSE 0
291                    END
292                  )
293                )
294     ";
295
296   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
297                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
298                "( tax != 'Y' OR tax IS NULL )";
299
300 } elsif ( $cgi->param('taxable') ) {
301
302   my $setup_taxable = "(
303     CASE WHEN part_pkg.setuptax = 'Y'
304          THEN 0
305          ELSE cust_bill_pkg.setup
306     END
307   )";
308
309   my $recur_taxable = "(
310     CASE WHEN part_pkg.recurtax = 'Y'
311          THEN 0
312          ELSE cust_bill_pkg.recur
313     END
314   )";
315
316   my $exempt = "(
317     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
318       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
319   )";
320
321   $count_query =
322     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
323
324   push @where,
325     #not tax-exempt package (setup or recur)
326     "(
327           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
328             AND cust_bill_pkg.setup > 0 )
329        OR
330           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
331             AND cust_bill_pkg.recur > 0 )
332     )",
333     #not a tax_exempt customer
334     "( tax != 'Y' OR tax IS NULL )";
335     #not covered in full by a monthly tax exemption (texas tax)
336     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
337
338 } else {
339
340   $count_query =
341     "SELECT COUNT(*), SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
342
343 }
344
345 my $where = ' WHERE '. join(' AND ', @where);
346
347 my $join_cust =  '      JOIN cust_bill USING ( invnum ) 
348                    LEFT JOIN cust_main USING ( custnum ) ';
349
350
351 my $join_pkg;
352 if ( $cgi->param('nottax') ) {
353
354   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
355                  LEFT JOIN part_pkg USING ( pkgpart ) ';
356   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
357     if $conf->exists('tax-pkg_address');
358
359 } elsif ( $cgi->param('istax') ) {
360
361   #false laziness w/report_tax.cgi $taxfromwhere
362   if ( $conf->exists('tax-pkg_address') ) {
363     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
364                    LEFT JOIN cust_location              USING ( locationnum ) ';
365
366     #quelle kludge, false laziness w/report_tax.cgi
367     $where =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g; 
368   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
369     $join_pkg .=
370       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
371       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
372   }
373
374 } else { 
375
376   #die?
377   warn "neiether nottax nor istax parameters specified";
378   #same as before?
379   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
380                  LEFT JOIN part_pkg USING ( pkgpart ) ';
381
382 }
383
384 $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
385
386 my @select = (
387                'cust_bill_pkg.*',
388                'cust_bill._date',
389              );
390 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
391 push @select, 'cust_main.custnum',
392               FS::UI::Web::cust_sql_fields();
393
394 my $query = {
395   'table'     => 'cust_bill_pkg',
396   'addl_from' => "$join_cust $join_pkg",
397   'hashref'   => {},
398   'select'    => join(', ', @select ),
399   'extra_sql' => $where,
400   'order_by'  => 'ORDER BY _date, billpkgnum',
401 };
402
403 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
404 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
405
406 my $conf = new FS::Conf;
407 my $money_char = $conf->config('money_char') || '$';
408
409 </%init>