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