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