combine ticket notification scrips, #15353
[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
305     my %hash = ( 'country' => scalar($cgi->param('country')) );
306     foreach (qw( state county )) {
307       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
308     }
309     my $cust_main_county = qsearchs('cust_main_county', \%hash);
310     die "unknown base region for empty taxclass" unless $cust_main_county;
311
312     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
313     $same_sql =~ s/taxclass/part_pkg.taxclass/g;
314     push @where, $same_sql if $same_sql;
315
316   }
317
318 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
319
320   push @where, FS::tax_rate_location->location_sql(
321                  map { $_ => (scalar($cgi->param($_)) || '') }
322                    qw( city county state locationtaxid )
323                );
324
325 } elsif ( $cgi->param('unearned_now') =~ /^(\d+)$/ ) {
326
327   $unearned = $1;
328
329   push @where, "cust_bill_pkg.sdate < $unearned",
330                "cust_bill_pkg.edate > $unearned",
331                "cust_bill_pkg.recur != 0",
332                "part_pkg.freq != '0'",
333                "part_pkg.freq != '1'",
334                "part_pkg.freq NOT LIKE '%h'",
335                "part_pkg.freq NOT LIKE '%d'",
336                "part_pkg.freq NOT LIKE '%w'";
337
338 }
339
340 if ( $cgi->param('itemdesc') ) {
341   if ( $cgi->param('itemdesc') eq 'Tax' ) {
342     push @where, "(itemdesc='Tax' OR itemdesc is null)";
343   } else {
344     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
345   }
346 }
347
348 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
349   my ( $group_op, $group_value ) = ( $1, $2 );
350   if ( $group_op eq '=' ) {
351     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
352     push @where, 'itemdesc = '. dbh->quote($group_value);
353   } elsif ( $group_op eq '!=' ) {
354     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
355   } else {
356     die "guru meditation #00de: group_op $group_op\n";
357   }
358   
359 }
360
361 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
362 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
363
364 if ( $cgi->param('cust_tax') ) {
365   #false laziness -ish w/report_tax.cgi
366   my $cust_exempt;
367   if ( $cgi->param('taxname') ) {
368     my $q_taxname = dbh->quote($cgi->param('taxname'));
369     $cust_exempt =
370       "( tax = 'Y'
371          OR EXISTS ( SELECT 1 FROM cust_main_exemption
372                        WHERE cust_main_exemption.custnum = cust_main.custnum
373                          AND cust_main_exemption.taxname = $q_taxname )
374        )
375       ";
376   } else {
377     $cust_exempt = " tax = 'Y' ";
378   }
379
380   push @where, $cust_exempt;
381 }
382
383 my $use_usage = $cgi->param('use_usage');
384
385 my $count_query;
386 if ( $cgi->param('pkg_tax') ) {
387
388   $count_query =
389     "SELECT COUNT(*),
390             SUM(
391                  ( CASE WHEN part_pkg.setuptax = 'Y'
392                         THEN cust_bill_pkg.setup
393                         ELSE 0
394                    END
395                  )
396                  +
397                  ( CASE WHEN part_pkg.recurtax = 'Y'
398                         THEN cust_bill_pkg.recur
399                         ELSE 0
400                    END
401                  )
402                )
403     ";
404
405   push @where, "(    ( part_pkg.setuptax = 'Y' AND cust_bill_pkg.setup > 0 )
406                   OR ( part_pkg.recurtax = 'Y' AND cust_bill_pkg.recur > 0 ) )",
407                "( tax != 'Y' OR tax IS NULL )";
408
409 } elsif ( $cgi->param('taxable') ) {
410
411   my $setup_taxable = "(
412     CASE WHEN part_pkg.setuptax = 'Y'
413          THEN 0
414          ELSE cust_bill_pkg.setup
415     END
416   )";
417
418   my $recur_taxable = "(
419     CASE WHEN part_pkg.recurtax = 'Y'
420          THEN 0
421          ELSE cust_bill_pkg.recur
422     END
423   )";
424
425   my $exempt = "(
426     SELECT COALESCE( SUM(amount), 0 ) FROM cust_tax_exempt_pkg
427       WHERE cust_tax_exempt_pkg.billpkgnum = cust_bill_pkg.billpkgnum
428   )";
429
430   $count_query =
431     "SELECT COUNT(*), SUM( $setup_taxable + $recur_taxable - $exempt )";
432
433   push @where,
434     #not tax-exempt package (setup or recur)
435     "(
436           ( ( part_pkg.setuptax != 'Y' OR part_pkg.setuptax IS NULL )
437             AND cust_bill_pkg.setup > 0 )
438        OR
439           ( ( part_pkg.recurtax != 'Y' OR part_pkg.recurtax IS NULL )
440             AND cust_bill_pkg.recur > 0 )
441     )",
442     #not a tax_exempt customer
443     "( tax != 'Y' OR tax IS NULL )";
444     #not covered in full by a monthly tax exemption (texas tax)
445     "0 < ( $setup_taxable + $recur_taxable - $exempt )",
446
447 } else {
448
449   if ( $use_usage ) {
450     $count_query = "SELECT COUNT(*), ";
451   } else {
452     $count_query = "SELECT COUNT(DISTINCT billpkgnum), ";
453   }
454
455   if ( $use_usage eq 'recurring' ) {
456     $count_query .= "SUM(setup + recur - usage)";
457   } elsif ( $use_usage eq 'usage' ) {
458     $count_query .= "SUM(usage)";
459   } elsif ( $unearned ) {
460     $count_query .= "SUM(cust_bill_pkg.recur)";
461   } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
462     $count_query .= "SUM( COALESCE(cust_bill_pkg_tax_rate_location.amount, cust_bill_pkg.setup + cust_bill_pkg.recur))";
463   } elsif ( $cgi->param('iscredit') eq 'rate') {
464     $count_query .= "SUM( cust_credit_bill_pkg.amount )";
465   } else {
466     $count_query .= "SUM(cust_bill_pkg.setup + cust_bill_pkg.recur)";
467   }
468
469   if ( $unearned ) {
470
471     #false laziness w/report_prepaid_income.cgi
472
473     my $float = 'REAL'; #'DOUBLE PRECISION';
474
475     my $period = "CAST(cust_bill_pkg.edate - cust_bill_pkg.sdate AS $float)";
476     my $elapsed = "(CASE WHEN cust_bill_pkg.sdate > $unearned
477                      THEN 0
478                      ELSE ($unearned - cust_bill_pkg.sdate)
479                    END)";
480     #my $elapsed = "CAST($unearned - cust_bill_pkg.sdate AS $float)";
481
482     my $remaining = "(1 - $elapsed/$period)";
483
484     $count_query .= ", SUM($remaining * cust_bill_pkg.recur)";
485
486   }
487
488 }
489
490 my $join_cust =  '      JOIN cust_bill USING ( invnum ) 
491                    LEFT JOIN cust_main USING ( custnum ) ';
492
493
494 my $join_pkg;
495 if ( $cgi->param('nottax') ) {
496
497   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
498                  LEFT JOIN part_pkg USING ( pkgpart )
499                  LEFT JOIN part_pkg AS override
500                    ON pkgpart_override = override.pkgpart ';
501   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
502     if $conf->exists('tax-pkg_address');
503
504 } elsif ( $cgi->param('istax') ) {
505
506   #false laziness w/report_tax.cgi $taxfromwhere
507   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
508             $cgi->param('iscredit') eq 'rate') {
509
510     $join_pkg .=
511       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ) '.
512       ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
513
514   } elsif ( $conf->exists('tax-pkg_address') ) {
515
516     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
517                    LEFT JOIN cust_location              USING ( locationnum ) ';
518
519     #quelle kludge, somewhat false laziness w/report_tax.cgi
520     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
521   }
522
523   if ( $cgi->param('iscredit') ) {
524     $join_pkg .= ' JOIN cust_credit_bill_pkg USING ( billpkgnum';
525     if ( $cgi->param('iscredit') eq 'rate' ) {
526       $join_pkg .= ', billpkgtaxratelocationnum )';
527     } elsif ( $conf->exists('tax-pkg_address') ) {
528       $join_pkg .= ', billpkgtaxlocationnum )';
529       push @where, "billpkgtaxratelocationnum IS NULL";
530     } else {
531       $join_pkg .= ' )';
532       push @where, "billpkgtaxratelocationnum IS NULL";
533     }
534   }
535
536 } else { 
537
538   #die?
539   warn "neiether nottax nor istax parameters specified";
540   #same as before?
541   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
542                  LEFT JOIN part_pkg USING ( pkgpart ) ';
543
544 }
545
546 my $where = ' WHERE '. join(' AND ', @where);
547
548 if ($use_usage) {
549   $count_query .=
550     " FROM (SELECT cust_bill_pkg.setup, cust_bill_pkg.recur, 
551              ( SELECT COALESCE( SUM(amount), 0 ) FROM cust_bill_pkg_detail
552                WHERE cust_bill_pkg.billpkgnum = cust_bill_pkg_detail.billpkgnum
553              ) AS usage FROM cust_bill_pkg  $join_cust $join_pkg $where
554            ) AS countquery";
555 } else {
556   $count_query .= " FROM cust_bill_pkg $join_cust $join_pkg $where";
557 }
558
559 my @select = ( 'cust_bill_pkg.*',
560                'cust_bill._date', );
561
562 push @select, 'part_pkg.pkg',
563               'part_pkg.freq',
564   unless $cgi->param('istax');
565
566 push @select, 'cust_main.custnum',
567               FS::UI::Web::cust_sql_fields();
568
569 my $query = {
570   'table'     => 'cust_bill_pkg',
571   'addl_from' => "$join_cust $join_pkg",
572   'hashref'   => {},
573   'select'    => join(', ', @select ),
574   'extra_sql' => $where,
575   'order_by'  => 'ORDER BY _date, billpkgnum',
576 };
577
578 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
579 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
580
581 my $conf = new FS::Conf;
582 my $money_char = $conf->config('money_char') || '$';
583
584 my $owed_sub = sub {
585   $money_char. shift->owed_recur; #_recur :/
586 };
587
588 my $payment_date_sub = sub {
589   #my $cust_bill_pkg = shift;
590   my @cust_pay = sort { $a->_date <=> $b->_date }
591                       map $_->cust_bill_pay->cust_pay,
592                           shift->cust_bill_pay_pkg('recur') #recur :/
593     or return '';
594   time2str('%b %d %Y', $cust_pay[-1]->_date );
595 };
596
597 </%init>