option to count subpackages outside packages in sales report #5588
[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')      # possibly use override.pkg
20                            : $_[0]->get('itemdesc') # but i think this correct
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 my $use_override = $cgi->param('use_override');
91 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
92   my $comparison = '';
93   if ( $1 == 0 ) {
94     $comparison = "IS NULL";
95   } else {
96     $comparison = "= $1";
97   }
98
99   if ( $use_override ) {
100     push @where, "(
101       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
102       override.classnum $comparison AND pkgpart_override IS NOT NULL
103     )";
104   } else {
105     push @where, "part_pkg.classnum $comparison";
106   }
107 }
108
109 push @where, ' ( '. join(' OR ',
110                       map ' taxclass = '.dbh->quote($_), $cgi->param('taxclass')
111                     ).
112              ' ) '
113   if $cgi->param('taxclass')
114   && ! $cgi->param('istax'); #no part_pkg.taxclass in this case
115                              #(should we save a taxclass or a link to taxnum
116                              # in cust_bill_pkg or something like
117                              # cust_bill_pkg_tax_location?)
118
119 #sub _where {
120 # my $table = shift;
121 # my $prefix = @_ ? shift : '';
122 # "
123 #      (    cust_main_county.county  = $table.${prefix}.county
124 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county  =  '' )
125 #      OR ( cust_main_county.county  =  ''  AND $table.${prefix}.county IS NULL)
126 #      OR ( cust_main_county.county IS NULL AND $table.${prefix}.county IS NULL)
127 #      )
128 #  AND (    cust_main_county.state   = $table.${prefix}.state
129 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state  =  ''  )
130 #      OR ( cust_main_county.state   =  ''  AND $table.${prefix}.state IS NULL )
131 #      OR ( cust_main_county.state  IS NULL AND $table.${prefix}.state IS NULL )
132 #      )
133 #  AND cust_main_county.country = $table.${prefix}.country
134 # ";
135 #
136 #}
137
138 if ( $cgi->param('out') ) {
139
140   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
141   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
142     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
143   }
144
145   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
146     if $cgi->param('istax');
147
148   push @where, "
149     0 = (
150           SELECT COUNT(*) FROM cust_main_county
151            WHERE cust_main_county.tax > 0
152              AND $loc_sql
153         )
154   ";
155
156   #not linked to by anything, but useful for debugging "out of taxable region"
157   if ( grep $cgi->param($_), qw( county state country ) ) {
158
159     my %ph = map { $_ => dbh->quote( $cgi->param($_) ) }
160                  qw( county state country );
161
162     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
163     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
164       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
165     }
166
167     push @where, $loc_sql;
168
169   }
170
171 } elsif ( $cgi->param('country') ) {
172
173   my @counties = $cgi->param('county');
174    
175   if ( scalar(@counties) > 1 ) {
176
177     #hacky, could be more efficient.  care if it is ever used for more than the
178     # tax-report_groups filtering kludge
179
180     my $locs_sql =
181       ' ( '. join(' OR ', map {
182
183           my %ph = ( 'county' => dbh->quote($_),
184                      map { $_ => dbh->quote( $cgi->param($_) ) }
185                        qw( state country )
186                    );
187
188           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
189           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
190             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
191           }
192
193           $loc_sql;
194
195         } @counties
196
197       ). ' ) ';
198
199     push @where, $locs_sql;
200
201   } else {
202
203     my %ph = map { $_ => dbh->quote( $cgi->param($_) ) }
204                  qw( county state country );
205
206     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
207     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
208       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
209     }
210
211     push @where, $loc_sql;
212
213   }
214    
215   if ( $cgi->param('istax') ) {
216     if ( $cgi->param('taxname') ) {
217       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
218     #} elsif ( $cgi->param('taxnameNULL') {
219     } else {
220       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
221     }
222   } elsif ( $cgi->param('nottax') ) {
223     #what can we usefully do with "taxname" ????  look up a class???
224   } else {
225     #warn "neither nottax nor istax parameters specified";
226   }
227
228   if ( $cgi->param('taxclassNULL') ) {
229
230     my %hash = ( 'country' => scalar($cgi->param('country')) );
231     foreach (qw( state county )) {
232       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
233     }
234     my $cust_main_county = qsearchs('cust_main_county', \%hash);
235     die "unknown base region for empty taxclass" unless $cust_main_county;
236
237     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
238     push @where, $same_sql if $same_sql;
239
240   }
241
242 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
243
244   # this should really be shoved out to FS::cust_pkg->location_sql or something
245   # along with the code in report_newtax.cgi
246
247   my %pn = (
248    'county'        => 'tax_rate_location.county',
249    'state'         => 'tax_rate_location.state',
250    'city'          => 'tax_rate_location.city',
251    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
252   );
253
254   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
255            qw( county state city locationtaxid );
256
257   push @where,
258     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
259                    keys %ph
260     );
261
262 }
263
264 if ( $cgi->param('itemdesc') ) {
265   if ( $cgi->param('itemdesc') eq 'Tax' ) {
266     push @where, "(itemdesc='Tax' OR itemdesc is null)";
267   } else {
268     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
269   }
270 }
271
272 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
273   my ( $group_op, $group_value ) = ( $1, $2 );
274   if ( $group_op eq '=' ) {
275     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
276     push @where, 'itemdesc = '. dbh->quote($group_value);
277   } elsif ( $group_op eq '!=' ) {
278     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
279   } else {
280     die "guru meditation #00de: group_op $group_op\n";
281   }
282   
283 }
284
285 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
286 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
287
288 if ( $cgi->param('cust_tax') ) {
289   #false laziness -ish w/report_tax.cgi
290   my $cust_exempt;
291   if ( $cgi->param('taxname') ) {
292     my $q_taxname = dbh->quote($cgi->param('taxname'));
293     $cust_exempt =
294       "( tax = 'Y'
295          OR EXISTS ( SELECT 1 FROM cust_main_exemption
296                        WHERE cust_main_exemption.custnum = cust_main.custnum
297                          AND cust_main_exemption.taxname = $q_taxname )
298        )
299       ";
300   } else {
301     $cust_exempt = " tax = 'Y' ";
302   }
303
304   push @where, $cust_exempt;
305 }
306
307 my $count_query;
308 if ( $cgi->param('pkg_tax') ) {
309
310   $count_query =
311     "SELECT COUNT(*),
312             SUM(
313                  ( CASE WHEN part_pkg.setuptax = 'Y'
314                         THEN cust_bill_pkg.setup
315                         ELSE 0
316                    END
317                  )
318                  +
319                  ( CASE WHEN part_pkg.recurtax = 'Y'
320                         THEN cust_bill_pkg.recur
321                         ELSE 0
322                    END
323                  )
324                )
325     ";
326
327   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
328                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
329                "( tax != 'Y' OR tax IS NULL )";
330
331 } elsif ( $cgi->param('taxable') ) {
332
333   my $setup_taxable = "(
334     CASE WHEN part_pkg.setuptax = 'Y'
335          THEN 0
336          ELSE cust_bill_pkg.setup
337     END
338   )";
339
340   my $recur_taxable = "(
341     CASE WHEN part_pkg.recurtax = 'Y'
342          THEN 0
343          ELSE cust_bill_pkg.recur
344     END
345   )";
346
347   my $exempt = "(
348     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
349       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
350   )";
351
352   $count_query =
353     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
354
355   push @where,
356     #not tax-exempt package (setup or recur)
357     "(
358           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
359             AND cust_bill_pkg.setup > 0 )
360        OR
361           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
362             AND cust_bill_pkg.recur > 0 )
363     )",
364     #not a tax_exempt customer
365     "( tax != 'Y' OR tax IS NULL )";
366     #not covered in full by a monthly tax exemption (texas tax)
367     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
368
369 } else {
370
371   $count_query =
372     "SELECT COUNT(*), SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
373
374 }
375
376 my $where = ' WHERE '. join(' AND ', @where);
377
378 my $join_cust =  '      JOIN cust_bill USING ( invnum ) 
379                    LEFT JOIN cust_main USING ( custnum ) ';
380
381
382 my $join_pkg;
383 if ( $cgi->param('nottax') ) {
384
385   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
386                  LEFT JOIN part_pkg USING ( pkgpart )
387                  LEFT JOIN part_pkg AS override
388                    ON pkgpart_override = override.pkgpart ';
389   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
390     if $conf->exists('tax-pkg_address');
391
392 } elsif ( $cgi->param('istax') ) {
393
394   #false laziness w/report_tax.cgi $taxfromwhere
395   if ( $conf->exists('tax-pkg_address') ) {
396     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
397                    LEFT JOIN cust_location              USING ( locationnum ) ';
398
399     #quelle kludge, false laziness w/report_tax.cgi
400     $where =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g; 
401   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
402     $join_pkg .=
403       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
404       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
405   }
406
407 } else { 
408
409   #die?
410   warn "neiether nottax nor istax parameters specified";
411   #same as before?
412   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
413                  LEFT JOIN part_pkg USING ( pkgpart ) ';
414
415 }
416
417 $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
418
419 my @select = (
420                'cust_bill_pkg.*',
421                'cust_bill._date',
422              );
423 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
424 push @select, 'cust_main.custnum',
425               FS::UI::Web::cust_sql_fields();
426
427 my $query = {
428   'table'     => 'cust_bill_pkg',
429   'addl_from' => "$join_cust $join_pkg",
430   'hashref'   => {},
431   'select'    => join(', ', @select ),
432   'extra_sql' => $where,
433   'order_by'  => 'ORDER BY _date, billpkgnum',
434 };
435
436 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
437 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
438
439 my $conf = new FS::Conf;
440 my $money_char = $conf->config('money_char') || '$';
441
442 </%init>