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