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