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