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