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