This commit was manufactured by cvs2svn to create branch
[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 #LOTS of false laziness below w/cust_credit_bill_pkg.cgi
124
125 die "access denied"
126   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
127
128 my $conf = new FS::Conf;
129
130 my $unearned = '';
131
132 #here is the agent virtualization
133 my $agentnums_sql =
134   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
135
136 my @where = ( $agentnums_sql );
137
138 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
139 push @where, "_date >= $beginning",
140              "_date <= $ending";
141
142 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
143   push @where, "cust_main.agentnum = $1";
144 }
145
146 #classnum
147 # not specified: all classes
148 # 0: empty class
149 # N: classnum
150 my $use_override = $cgi->param('use_override');
151 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
152   my $comparison = '';
153   if ( $1 == 0 ) {
154     $comparison = "IS NULL";
155   } else {
156     $comparison = "= $1";
157   }
158
159   if ( $use_override ) {
160     push @where, "(
161       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
162       override.classnum $comparison AND pkgpart_override IS NOT NULL
163     )";
164   } else {
165     push @where, "part_pkg.classnum $comparison";
166   }
167 }
168
169 if ( $cgi->param('taxclass')
170      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
171                                 #(should we save a taxclass or a link to taxnum
172                                 # in cust_bill_pkg or something like
173                                 # cust_bill_pkg_tax_location?)
174    )
175 {
176
177   #override taxclass when use_override is specified?  probably
178   #if ( $use_override ) {
179   #
180   #  push @where,
181   #    ' ( '. join(' OR ',
182   #                  map {
183   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
184   #                        '      AND pkgpart_override IS NULL '.
185   #                        '   OR '.
186   #                        '      override.taxclass = '. dbh->quote($_).
187   #                        '      AND pkgpart_override IS NOT NULL '.
188   #                        ' ) '
189   #                      }
190   #                      $cgi->param('taxclass')
191   #               ).
192   #    ' ) ';
193   #
194   #} else {
195
196     push @where,
197       ' ( '. join(' OR ',
198                     map ' part_pkg.taxclass = '.dbh->quote($_),
199                         $cgi->param('taxclass')
200                  ).
201       ' ) ';
202
203   #}
204
205 }
206
207 my @loc_param = qw( city county state country );
208
209 if ( $cgi->param('out') ) {
210
211   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
212   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
213     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
214   }
215
216   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
217     if $cgi->param('istax');
218
219   push @where, "
220     0 = (
221           SELECT COUNT(*) FROM cust_main_county
222            WHERE cust_main_county.tax > 0
223              AND $loc_sql
224         )
225   ";
226
227   #not linked to by anything, but useful for debugging "out of taxable region"
228   if ( grep $cgi->param($_), @loc_param ) {
229
230     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
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( city 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( scalar($cgi->param($_)) ) } @loc_param;
274
275     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
276     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
277       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
278     }
279
280     push @where, $loc_sql;
281
282   }
283    
284   if ( $cgi->param('istax') ) {
285     if ( $cgi->param('taxname') ) {
286       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
287     #} elsif ( $cgi->param('taxnameNULL') {
288     } else {
289       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
290     }
291   } elsif ( $cgi->param('nottax') ) {
292     #what can we usefully do with "taxname" ????  look up a class???
293   } else {
294     #warn "neither nottax nor istax parameters specified";
295   }
296
297   if ( $cgi->param('taxclassNULL') ) {
298
299     my %hash = ( 'country' => scalar($cgi->param('country')) );
300     foreach (qw( state county )) {
301       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
302     }
303     my $cust_main_county = qsearchs('cust_main_county', \%hash);
304     die "unknown base region for empty taxclass" unless $cust_main_county;
305
306     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
307     push @where, $same_sql if $same_sql;
308
309   }
310
311 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
312
313   # this should really be shoved out to FS::cust_pkg->location_sql or something
314   # along with the code in report_newtax.cgi
315
316   my %pn = (
317    'county'        => 'tax_rate_location.county',
318    'state'         => 'tax_rate_location.state',
319    'city'          => 'tax_rate_location.city',
320    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
321   );
322
323   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
324            qw( city county state locationtaxid );
325
326   push @where,
327     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
328                    keys %ph
329     );
330
331 } elsif ( $cgi->param('unearned_now') =~ /^(\d+)$/ ) {
332
333   $unearned = $1;
334
335   push @where, "cust_bill_pkg.sdate < $unearned",
336                "cust_bill_pkg.edate > $unearned",
337                "cust_bill_pkg.recur != 0",
338                "part_pkg.freq != '0'",
339                "part_pkg.freq != '1'",
340                "part_pkg.freq NOT LIKE '%h'",
341                "part_pkg.freq NOT LIKE '%d'",
342                "part_pkg.freq NOT LIKE '%w'";
343
344 }
345
346 if ( $cgi->param('itemdesc') ) {
347   if ( $cgi->param('itemdesc') eq 'Tax' ) {
348     push @where, "(itemdesc='Tax' OR itemdesc is null)";
349   } else {
350     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
351   }
352 }
353
354 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
355   my ( $group_op, $group_value ) = ( $1, $2 );
356   if ( $group_op eq '=' ) {
357     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
358     push @where, 'itemdesc = '. dbh->quote($group_value);
359   } elsif ( $group_op eq '!=' ) {
360     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
361   } else {
362     die "guru meditation #00de: group_op $group_op\n";
363   }
364   
365 }
366
367 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
368 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
369
370 if ( $cgi->param('cust_tax') ) {
371   #false laziness -ish w/report_tax.cgi
372   my $cust_exempt;
373   if ( $cgi->param('taxname') ) {
374     my $q_taxname = dbh->quote($cgi->param('taxname'));
375     $cust_exempt =
376       "( tax = 'Y'
377          OR EXISTS ( SELECT 1 FROM cust_main_exemption
378                        WHERE cust_main_exemption.custnum = cust_main.custnum
379                          AND cust_main_exemption.taxname = $q_taxname )
380        )
381       ";
382   } else {
383     $cust_exempt = " tax = 'Y' ";
384   }
385
386   push @where, $cust_exempt;
387 }
388
389 my $use_usage = $cgi->param('use_usage');
390
391 my $count_query;
392 if ( $cgi->param('pkg_tax') ) {
393
394   $count_query =
395     "SELECT COUNT(*),
396             SUM(
397                  ( CASE WHEN part_pkg.setuptax = 'Y'
398                         THEN cust_bill_pkg.setup
399                         ELSE 0
400                    END
401                  )
402                  +
403                  ( CASE WHEN part_pkg.recurtax = 'Y'
404                         THEN cust_bill_pkg.recur
405                         ELSE 0
406                    END
407                  )
408                )
409     ";
410
411   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
412                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
413                "( tax != 'Y' OR tax IS NULL )";
414
415 } elsif ( $cgi->param('taxable') ) {
416
417   my $setup_taxable = "(
418     CASE WHEN part_pkg.setuptax = 'Y'
419          THEN 0
420          ELSE cust_bill_pkg.setup
421     END
422   )";
423
424   my $recur_taxable = "(
425     CASE WHEN part_pkg.recurtax = 'Y'
426          THEN 0
427          ELSE cust_bill_pkg.recur
428     END
429   )";
430
431   my $exempt = "(
432     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
433       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
434   )";
435
436   $count_query =
437     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
438
439   push @where,
440     #not tax-exempt package (setup or recur)
441     "(
442           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
443             AND cust_bill_pkg.setup > 0 )
444        OR
445           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
446             AND cust_bill_pkg.recur > 0 )
447     )",
448     #not a tax_exempt customer
449     "( tax != 'Y' OR tax IS NULL )";
450     #not covered in full by a monthly tax exemption (texas tax)
451     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
452
453 } else {
454
455   $count_query = "SELECT COUNT(*), ";
456
457   if ( $use_usage eq 'recurring' ) {
458     $count_query .= "SUM(setup + recur - usage)";
459   } elsif ( $use_usage eq 'usage' ) {
460     $count_query .= "SUM(usage)";
461   } elsif ( $unearned ) {
462     $count_query .= "SUM(cust_bill_pkg.recur)";
463   } else {
464     $count_query .= "SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
465   }
466
467   if ( $unearned ) {
468
469     #false laziness w/report_prepaid_income.cgi
470
471     my $float = 'REAL'; #'DOUBLE PRECISION';
472
473     my $period = "CAST(cust_bill_pkg.edate - cust_bill_pkg.sdate AS $float)";
474     my $elapsed = "(CASE WHEN cust_bill_pkg.sdate > $unearned
475                      THEN 0
476                      ELSE ($unearned - cust_bill_pkg.sdate)
477                    END)";
478     #my $elapsed = "CAST($unearned - cust_bill_pkg.sdate AS $float)";
479
480     my $remaining = "(1 - $elapsed/$period)";
481
482     $count_query .= ", SUM($remaining * cust_bill_pkg.recur)";
483
484   }
485
486 }
487
488 my $join_cust =  '      JOIN cust_bill USING ( invnum ) 
489                    LEFT JOIN cust_main USING ( custnum ) ';
490
491
492 my $join_pkg;
493 if ( $cgi->param('nottax') ) {
494
495   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
496                  LEFT JOIN part_pkg USING ( pkgpart )
497                  LEFT JOIN part_pkg AS override
498                    ON pkgpart_override = override.pkgpart ';
499   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
500     if $conf->exists('tax-pkg_address');
501
502 } elsif ( $cgi->param('istax') ) {
503
504   #false laziness w/report_tax.cgi $taxfromwhere
505   if ( $conf->exists('tax-pkg_address') ) {
506     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
507                    LEFT JOIN cust_location              USING ( locationnum ) ';
508
509     #quelle kludge, somewhat false laziness w/report_tax.cgi
510     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
511   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
512             $cgi->param('iscredit') eq 'rate') {
513     $join_pkg .=
514       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
515       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
516   }
517
518   if ( $cgi->param('iscredit') ) {
519     $join_pkg .= ' JOIN cust_credit_bill_pkg USING ( billpkgnum';
520     if ( $conf->exists('tax-pkg_address') ) {
521       $join_pkg .= ', billpkgtaxlocationnum )';
522       push @where, "billpkgtaxratelocationnum IS NULL";
523     } elsif ( $cgi->param('iscredit') eq 'rate' ) {
524       $join_pkg .= ', billpkgtaxratelocationnum )';
525     } else {
526       $join_pkg .= ' )';
527       push @where, "billpkgtaxratelocationnum IS NULL";
528     }
529   }
530
531 } else { 
532
533   #die?
534   warn "neiether nottax nor istax parameters specified";
535   #same as before?
536   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
537                  LEFT JOIN part_pkg USING ( pkgpart ) ';
538
539 }
540
541 my $where = ' WHERE '. join(' AND ', @where);
542
543 if ($use_usage) {
544   $count_query .=
545     " FROM (SELECT cust_bill_pkg.setup, cust_bill_pkg.recur, 
546              ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_bill_pkg_detail
547                WHERE cust_bill_pkg.billpkgnum = cust_bill_pkg_detail.billpkgnum
548              ) AS usage FROM cust_bill_pkg  $join_cust $join_pkg $where
549            ) AS countquery";
550 } else {
551   $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
552 }
553
554 my @select = ( 'cust_bill_pkg.*',
555                'cust_bill._date', );
556
557 push @select, 'part_pkg.pkg',
558               'part_pkg.freq',
559   unless $cgi->param('istax');
560
561 push @select, 'cust_main.custnum',
562               FS::UI::Web::cust_sql_fields();
563
564 my $query = {
565   'table'     => 'cust_bill_pkg',
566   'addl_from' => "$join_cust $join_pkg",
567   'hashref'   => {},
568   'select'    => join(', ', @select ),
569   'extra_sql' => $where,
570   'order_by'  => 'ORDER BY _date, billpkgnum',
571 };
572
573 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
574 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
575
576 my $conf = new FS::Conf;
577 my $money_char = $conf->config('money_char') || '$';
578
579 my $owed_sub = sub {
580   $money_char. shift->owed_recur; #_recur :/
581 };
582
583 my $payment_date_sub = sub {
584   #my $cust_bill_pkg = shift;
585   my @cust_pay = sort { $a->_date <=> $b->_date }
586                       map $_->cust_bill_pay->cust_pay,
587                           shift->cust_bill_pay_pkg('recur') #recur :/
588     or return '';
589   time2str('%b %d %Y', $cust_pay[-1]->_date );
590 };
591
592 </%init>