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