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