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