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