Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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 if ( $cgi->param('refnum') =~ /^(\d+)$/ ) {
175   push @where, "cust_main.refnum = $1";
176 }
177
178 #classnum
179 # not specified: all classes
180 # 0: empty class
181 # N: classnum
182 my $use_override = $cgi->param('use_override');
183 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
184   my $comparison = '';
185   if ( $1 == 0 ) {
186     $comparison = "IS NULL";
187   } else {
188     $comparison = "= $1";
189   }
190
191   if ( $use_override ) {
192     push @where, "(
193       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
194       override.classnum $comparison AND pkgpart_override IS NOT NULL
195     )";
196   } else {
197     push @where, "part_pkg.classnum $comparison";
198   }
199 }
200
201 if ( $cgi->param('taxclass')
202      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
203                                 #(should we save a taxclass or a link to taxnum
204                                 # in cust_bill_pkg or something like
205                                 # cust_bill_pkg_tax_location?)
206    )
207 {
208
209   #override taxclass when use_override is specified?  probably
210   #if ( $use_override ) {
211   #
212   #  push @where,
213   #    ' ( '. join(' OR ',
214   #                  map {
215   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
216   #                        '      AND pkgpart_override IS NULL '.
217   #                        '   OR '.
218   #                        '      override.taxclass = '. dbh->quote($_).
219   #                        '      AND pkgpart_override IS NOT NULL '.
220   #                        ' ) '
221   #                      }
222   #                      $cgi->param('taxclass')
223   #               ).
224   #    ' ) ';
225   #
226   #} else {
227
228     push @where, ' part_pkg.taxclass IN ( '.
229                    join(', ', map dbh->quote($_), $cgi->param('taxclass') ).
230                  ' ) ';
231
232   #}
233
234 }
235
236 my @loc_param = qw( district city county state country );
237
238 if ( $cgi->param('out') ) {
239
240   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
241   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
242     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
243   }
244
245   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
246     if $cgi->param('istax');
247
248   push @where, "
249     0 = (
250           SELECT COUNT(*) FROM cust_main_county
251            WHERE cust_main_county.tax > 0
252              AND $loc_sql
253         )
254   ";
255
256   #not linked to by anything, but useful for debugging "out of taxable region"
257   if ( grep $cgi->param($_), @loc_param ) {
258
259     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
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     push @where, $loc_sql;
267
268   }
269
270 } elsif ( $cgi->param('country') ) {
271
272   my @counties = $cgi->param('county');
273    
274   if ( scalar(@counties) > 1 ) {
275
276     #hacky, could be more efficient.  care if it is ever used for more than the
277     # tax-report_groups filtering kludge
278
279     my $locs_sql =
280       ' ( '. join(' OR ', map {
281
282           my %ph = ( 'county' => dbh->quote($_),
283                      map { $_ => dbh->quote( $cgi->param($_) ) }
284                        qw( district city state country )
285                    );
286
287           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
288           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
289             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
290           }
291
292           $loc_sql;
293
294         } @counties
295
296       ). ' ) ';
297
298     push @where, $locs_sql;
299
300   } else {
301
302     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
303
304     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
305     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
306       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
307     }
308
309     push @where, $loc_sql;
310
311   }
312    
313   if ( $cgi->param('istax') ) {
314     if ( $cgi->param('taxname') ) {
315       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
316     #} elsif ( $cgi->param('taxnameNULL') {
317     } else {
318       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
319     }
320   } elsif ( $cgi->param('nottax') ) {
321     #what can we usefully do with "taxname" ????  look up a class???
322   } else {
323     #warn "neither nottax nor istax parameters specified";
324   }
325
326   if ( $cgi->param('taxclassNULL')
327        && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
328                                   #(see comment above?)
329      )
330   {
331     my %hash = ( 'country' => scalar($cgi->param('country')) );
332     foreach (qw( state county )) {
333       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
334     }
335     my $cust_main_county = qsearchs('cust_main_county', \%hash);
336     die "unknown base region for empty taxclass" unless $cust_main_county;
337
338     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
339     $same_sql =~ s/taxclass/part_pkg.taxclass/g;
340     push @where, $same_sql if $same_sql;
341
342   }
343
344 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
345
346   push @where, FS::tax_rate_location->location_sql(
347                  map { $_ => (scalar($cgi->param($_)) || '') }
348                    qw( district city county state locationtaxid )
349                );
350
351 }
352
353 # unearned revenue mode
354 if ( $cgi->param('unearned_now') =~ /^(\d+)$/ ) {
355
356   $unearned = $1;
357   $unearned_mode = $cgi->param('mode');
358
359   push @where, "cust_bill_pkg.sdate < $unearned",
360                "cust_bill_pkg.edate > $unearned",
361                "cust_bill_pkg.recur != 0",
362                "part_pkg.freq != '0'";
363
364   if ( !$cgi->param('include_monthly') ) {
365     push @where,
366                "part_pkg.freq != '1'",
367                "part_pkg.freq NOT LIKE '%h'",
368                "part_pkg.freq NOT LIKE '%d'",
369                "part_pkg.freq NOT LIKE '%w'";
370   }
371
372   my $usage_sql = FS::cust_bill_pkg->usage_sql;
373   push @select, "($usage_sql) AS usage"; # we need this
374   my $paid_sql = 'GREATEST(' .
375     FS::cust_bill_pkg->paid_sql($unearned, '', setuprecur => 'recur') .
376     " - $usage_sql, 0)";
377
378   push @select, "$paid_sql AS paid_no_usage"; # need this either way
379
380   if ( $unearned_mode eq 'paid' ) {
381     # then use the amount paid, minus usage charges
382     $unearned_base = $paid_sql;
383   }
384   else {
385     # use the amount billed, minus usage charges and credits
386     $unearned_base = "GREATEST( cust_bill_pkg.recur - ".
387       FS::cust_bill_pkg->credited_sql($unearned, '', setuprecur => 'recur') .
388       " - $usage_sql, 0)";
389       # include only rows that have some non-usage, non-credited portion
390   }
391   # whatever we're using as the base, only show rows where it's positive
392   push @where, "$unearned_base > 0";
393
394   my $period = "CAST(cust_bill_pkg.edate - cust_bill_pkg.sdate AS REAL)";
395   my $elapsed = "GREATEST( $unearned - cust_bill_pkg.sdate, 0 )";
396   my $remaining = "(1 - $elapsed/$period)";
397
398   $unearned_sql = "CAST( $unearned_base * $remaining AS DECIMAL(10,2) )";
399   push @select, "$unearned_sql AS unearned_revenue";
400
401   # last payment/credit date
402   my %t = (pay => 'cust_bill_pay', credit => 'cust_credit_bill');
403   foreach my $x (qw(pay credit)) {
404     my $table = $t{$x};
405     my $link = $table.'_pkg';
406     my $pkey = dbdef->table($table)->primary_key;
407     my $last_date_sql = "SELECT MAX(_date) 
408     FROM $table JOIN $link USING ($pkey)
409     WHERE $link.billpkgnum = cust_bill_pkg.billpkgnum 
410     AND $table._date <= $unearned";
411     push @select, "($last_date_sql) AS last_$x";
412   }
413
414 }
415
416 if ( $cgi->param('itemdesc') ) {
417   if ( $cgi->param('itemdesc') eq 'Tax' ) {
418     push @where, "(itemdesc='Tax' OR itemdesc is null)";
419   } else {
420     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
421   }
422 }
423
424 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
425   my ( $group_op, $group_value ) = ( $1, $2 );
426   if ( $group_op eq '=' ) {
427     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
428     push @where, 'itemdesc = '. dbh->quote($group_value);
429   } elsif ( $group_op eq '!=' ) {
430     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
431   } else {
432     die "guru meditation #00de: group_op $group_op\n";
433   }
434   
435 }
436
437 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
438 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
439
440 if ( $cgi->param('cust_tax') ) {
441   #false laziness -ish w/report_tax.cgi
442   my $cust_exempt;
443   if ( $cgi->param('taxname') ) {
444     my $q_taxname = dbh->quote($cgi->param('taxname'));
445     $cust_exempt =
446       "( tax = 'Y'
447          OR EXISTS ( SELECT 1 FROM cust_main_exemption
448                        WHERE cust_main_exemption.custnum = cust_main.custnum
449                          AND cust_main_exemption.taxname = $q_taxname )
450        )
451       ";
452   } else {
453     $cust_exempt = " tax = 'Y' ";
454   }
455
456   push @where, $cust_exempt;
457 }
458
459 my $use_usage = $cgi->param('use_usage');
460
461 my $count_query;
462 if ( $cgi->param('pkg_tax') ) {
463
464   $count_query =
465     "SELECT COUNT(*),
466             SUM(
467                  ( CASE WHEN part_pkg.setuptax = 'Y'
468                         THEN cust_bill_pkg.setup
469                         ELSE 0
470                    END
471                  )
472                  +
473                  ( CASE WHEN part_pkg.recurtax = 'Y'
474                         THEN cust_bill_pkg.recur
475                         ELSE 0
476                    END
477                  )
478                )
479     ";
480
481   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
482                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
483                "( tax != 'Y' OR tax IS NULL )";
484
485 } elsif ( $cgi->param('taxable') ) {
486
487   my $setup_taxable = "(
488     CASE WHEN part_pkg.setuptax = 'Y'
489          THEN 0
490          ELSE cust_bill_pkg.setup
491     END
492   )";
493
494   my $recur_taxable = "(
495     CASE WHEN part_pkg.recurtax = 'Y'
496          THEN 0
497          ELSE cust_bill_pkg.recur
498     END
499   )";
500
501   my $exempt = "(
502     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
503       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
504   )";
505
506   $count_query =
507     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
508
509   push @where,
510     #not tax-exempt package (setup or recur)
511     "(
512           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
513             AND cust_bill_pkg.setup > 0 )
514        OR
515           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
516             AND cust_bill_pkg.recur > 0 )
517     )",
518     #not a tax_exempt customer
519     "( tax != 'Y' OR tax IS NULL )";
520     #not covered in full by a monthly tax exemption (texas tax)
521     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
522
523 } else {
524
525   if ( $use_usage ) {
526     $count_query = "SELECT COUNT(*), ";
527   } else {
528     $count_query = "SELECT COUNT(DISTINCT billpkgnum), ";
529   }
530
531   if ( $unearned ) {
532     $count_query .= "SUM( $unearned_base ), SUM( $unearned_sql )";
533   } elsif ( $use_usage eq 'recurring' ) {
534     $count_query .= "SUM(cust_bill_pkg.setup + cust_bill_pkg.recur - usage)";
535   } elsif ( $use_usage eq 'usage' ) {
536     $count_query .= "SUM(usage)";
537   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
538     $count_query .= "SUM( COALESCE(cust_bill_pkg_tax_rate_location.amount, cust_bill_pkg.setup + cust_bill_pkg.recur))";
539   } elsif ( $cgi->param('iscredit') eq 'rate') {
540     $count_query .= "SUM( cust_credit_bill_pkg.amount )";
541   } else {
542     $count_query .= "SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
543   }
544
545 }
546
547 $join_cust =  '        JOIN cust_bill USING ( invnum )
548                   LEFT JOIN cust_main USING ( custnum ) ';
549
550 if ( $cgi->param('nottax') ) {
551
552   $join_pkg .=  ' LEFT JOIN cust_pkg USING ( pkgnum )
553                   LEFT JOIN part_pkg USING ( pkgpart )
554                   LEFT JOIN part_pkg AS override
555                     ON pkgpart_override = override.pkgpart ';
556   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
557     if $conf->exists('tax-pkg_address');
558
559 } elsif ( $cgi->param('istax') ) {
560
561   #false laziness w/report_tax.cgi $taxfromwhere
562   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
563             $cgi->param('iscredit') eq 'rate') {
564
565     $join_pkg .=
566       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
567       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
568
569   } elsif ( $conf->exists('tax-pkg_address') ) {
570
571     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
572                    LEFT JOIN cust_location              USING ( locationnum ) ';
573
574     #quelle kludge, somewhat false laziness w/report_tax.cgi
575     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
576   }
577
578   if ( $cgi->param('iscredit') ) {
579     $join_pkg .= ' JOIN cust_credit_bill_pkg USING ( billpkgnum';
580     if ( $cgi->param('iscredit') eq 'rate' ) {
581       $join_pkg .= ', billpkgtaxratelocationnum )';
582     } elsif ( $conf->exists('tax-pkg_address') ) {
583       $join_pkg .= ', billpkgtaxlocationnum )';
584       push @where, "billpkgtaxratelocationnum IS NULL";
585     } else {
586       $join_pkg .= ' )';
587       push @where, "billpkgtaxratelocationnum IS NULL";
588     }
589   }
590
591 } else { 
592
593   #die?
594   warn "neiether nottax nor istax parameters specified";
595   #same as before?
596   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
597                  LEFT JOIN part_pkg USING ( pkgpart ) ';
598
599 }
600
601 my $where = ' WHERE '. join(' AND ', @where);
602
603 if ($use_usage) {
604   $count_query .=
605     " FROM (SELECT cust_bill_pkg.setup, cust_bill_pkg.recur, 
606              ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_bill_pkg_detail
607                WHERE cust_bill_pkg.billpkgnum = cust_bill_pkg_detail.billpkgnum
608              ) AS usage FROM cust_bill_pkg  $join_cust $join_pkg $where
609            ) AS countquery";
610 } else {
611   $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
612 }
613
614 push @select, 'part_pkg.pkg',
615               'part_pkg.freq',
616   unless $cgi->param('istax');
617
618 push @select, 'cust_main.custnum',
619               FS::UI::Web::cust_sql_fields();
620
621 my $query = {
622   'table'     => 'cust_bill_pkg',
623   'addl_from' => "$join_cust $join_pkg",
624   'hashref'   => {},
625   'select'    => join(",\n", @select ),
626   'extra_sql' => $where,
627   'order_by'  => 'ORDER BY cust_bill._date, billpkgnum',
628 };
629
630 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
631 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
632
633 my $conf = new FS::Conf;
634 my $money_char = $conf->config('money_char') || '$';
635
636 my $owed_sub = sub {
637   $money_char . shift->get('owed') # owed_recur is not correct here
638 };
639 my $payment_date_sub = sub {
640   #my $cust_bill_pkg = shift;
641   my @cust_pay = sort { $a->_date <=> $b->_date }
642                       map $_->cust_bill_pay->cust_pay,
643                           shift->cust_bill_pay_pkg('recur') #recur :/
644     or return '';
645   time2str('%b %d %Y', $cust_pay[-1]->_date );
646 };
647
648 </%init>