adding export to read mailbox status information, RT#15987
[freeside.git] / httemplate / search / cust_credit_bill_pkg.html
1 <% include( 'elements/search.html',
2               'title'       => 'Tax credits', #well, actually application of
3               'name'        => 'tax credits', # credit to line item
4               'query'       => $query,
5               'count_query' => $count_query,
6                  'count_addl'  => [ $money_char. '%.2f total', ],
7                  'header'      => [
8                    #'#',
9
10                    'Amount',
11
12                    #credit
13                    'Date',
14                    'By',
15                    'Reason',
16
17                    # line item
18                    'Description',
19
20                    #invoice
21                    'Invoice',
22                    'Date',
23                    FS::UI::Web::cust_header(),
24                  ],
25                  'fields'      => [
26                    #'creditbillpkgnum',
27                    sub { sprintf($money_char.'%.2f', shift->amount ) },
28
29                    sub { time2str('%b %d %Y', shift->get('cust_credit_date') ) },
30                    sub { shift->cust_credit_bill->cust_credit->otaker },
31                    sub { shift->cust_credit_bill->cust_credit->reason },
32
33                    sub { $_[0]->pkgnum > 0
34                            ? $_[0]->get('pkg')      # possibly use override.pkg
35                            : $_[0]->get('itemdesc') # but i think this correct
36                        },
37                    'invnum',
38                    sub { time2str('%b %d %Y', shift->_date ) },
39                    \&FS::UI::Web::cust_fields,
40                  ],
41                  'sort_fields' => [
42                    'amount',
43                    'cust_credit_date',
44                    '', #'otaker',
45                    '', #reason
46                    '', #line item description
47                    'invnum',
48                    '_date',
49                    #cust fields
50                  ],
51                  'links'       => [
52                    '',
53                    '',
54                    '',
55                    '',
56                    '',
57                    $ilink,
58                    $ilink,
59                    ( map { $_ ne 'Cust. Status' ? $clink : '' }
60                          FS::UI::Web::cust_header()
61                    ),
62                  ],
63                  'align' => 'rrlllrr'.FS::UI::Web::cust_aligns(),
64                  'color' => [ 
65                               '',
66                               '',
67                               '',
68                               '',
69                               '',
70                               '',
71                               '',
72                               FS::UI::Web::cust_colors(),
73                             ],
74                  'style' => [ 
75                               '',
76                               '',
77                               '',
78                               '',
79                               '',
80                               '',
81                               '',
82                               FS::UI::Web::cust_styles(),
83                             ],
84            )
85 %>
86 <%init>
87
88 #LOTS of false laziness below w/cust_bill_pkg.cgi
89
90 die "access denied"
91   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
92
93 my $conf = new FS::Conf;
94
95 #here is the agent virtualization
96 my $agentnums_sql =
97   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
98
99 my @where = ( $agentnums_sql );
100
101 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
102 push @where, "cust_bill._date >= $beginning",
103              "cust_bill._date <= $ending";
104
105 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
106   push @where, "cust_main.agentnum = $1";
107 }
108
109 #classnum
110 # not specified: all classes
111 # 0: empty class
112 # N: classnum
113 my $use_override = $cgi->param('use_override');
114 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
115   my $comparison = '';
116   if ( $1 == 0 ) {
117     $comparison = "IS NULL";
118   } else {
119     $comparison = "= $1";
120   }
121
122   if ( $use_override ) {
123     push @where, "(
124       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
125       override.classnum $comparison AND pkgpart_override IS NOT NULL
126     )";
127   } else {
128     push @where, "part_pkg.classnum $comparison";
129   }
130 }
131
132 if ( $cgi->param('taxclass')
133      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
134                                 #(should we save a taxclass or a link to taxnum
135                                 # in cust_bill_pkg or something like
136                                 # cust_bill_pkg_tax_location?)
137    )
138 {
139
140   #override taxclass when use_override is specified?  probably
141   #if ( $use_override ) {
142   #
143   #  push @where,
144   #    ' ( '. join(' OR ',
145   #                  map {
146   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
147   #                        '      AND pkgpart_override IS NULL '.
148   #                        '   OR '.
149   #                        '      override.taxclass = '. dbh->quote($_).
150   #                        '      AND pkgpart_override IS NOT NULL '.
151   #                        ' ) '
152   #                      }
153   #                      $cgi->param('taxclass')
154   #               ).
155   #    ' ) ';
156   #
157   #} else {
158
159     push @where,
160       ' ( '. join(' OR ',
161                     map ' part_pkg.taxclass = '.dbh->quote($_),
162                         $cgi->param('taxclass')
163                  ).
164       ' ) ';
165
166   #}
167
168 }
169
170 my @loc_param = qw( city county state country );
171
172 if ( $cgi->param('out') ) {
173
174   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
175   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
176     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
177   }
178
179   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
180     if $cgi->param('istax');
181
182   push @where, "
183     0 = (
184           SELECT COUNT(*) FROM cust_main_county
185            WHERE cust_main_county.tax > 0
186              AND $loc_sql
187         )
188   ";
189
190   #not linked to by anything, but useful for debugging "out of taxable region"
191   if ( grep $cgi->param($_), @loc_param ) {
192
193     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
194
195     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
196     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
197       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
198     }
199
200     push @where, $loc_sql;
201
202   }
203
204 } elsif ( $cgi->param('country') ) {
205
206   my @counties = $cgi->param('county');
207    
208   if ( scalar(@counties) > 1 ) {
209
210     #hacky, could be more efficient.  care if it is ever used for more than the
211     # tax-report_groups filtering kludge
212
213     my $locs_sql =
214       ' ( '. join(' OR ', map {
215
216           my %ph = ( 'county' => dbh->quote($_),
217                      map { $_ => dbh->quote( $cgi->param($_) ) }
218                        qw( city state country )
219                    );
220
221           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
222           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
223             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
224           }
225
226           $loc_sql;
227
228         } @counties
229
230       ). ' ) ';
231
232     push @where, $locs_sql;
233
234   } else {
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   my($title, $name);
248   if ( $cgi->param('istax') ) {
249     $title = 'Tax credits';
250     $name  = 'tax credits';
251     if ( $cgi->param('taxname') ) {
252       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
253     #} elsif ( $cgi->param('taxnameNULL') {
254     } else {
255       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
256     }
257   } elsif ( $cgi->param('nottax') ) {
258     $title = 'Credit applications to line items';
259     $name  = 'applications';
260     #what can we usefully do with "taxname" ????  look up a class???
261   } else {
262     $title = 'Credit applications to line items';
263     $name  = 'applications';
264     #warn "neither nottax nor istax parameters specified";
265   }
266
267   if ( $cgi->param('taxclassNULL')
268        && ! $cgi->param('istax')  #no taxclass in this case
269      )
270   {
271
272     my %hash = ( 'country' => scalar($cgi->param('country')) );
273     foreach (qw( state county )) {
274       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
275     }
276     my $cust_main_county = qsearchs('cust_main_county', \%hash);
277     die "unknown base region for empty taxclass" unless $cust_main_county;
278
279     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
280     push @where, $same_sql if $same_sql;
281
282   }
283
284 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
285
286   # this should really be shoved out to FS::cust_pkg->location_sql or something
287   # along with the code in report_newtax.cgi
288
289   my %pn = (
290    'county'        => 'tax_rate_location.county',
291    'state'         => 'tax_rate_location.state',
292    'city'          => 'tax_rate_location.city',
293    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
294   );
295
296   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
297            qw( city county state locationtaxid );
298
299   push @where,
300     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
301                    keys %ph
302     );
303
304 }
305
306 if ( $cgi->param('itemdesc') ) {
307   if ( $cgi->param('itemdesc') eq 'Tax' ) {
308     push @where, "(itemdesc='Tax' OR itemdesc is null)";
309   } else {
310     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
311   }
312 }
313
314 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
315   my ( $group_op, $group_value ) = ( $1, $2 );
316   if ( $group_op eq '=' ) {
317     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
318     push @where, 'itemdesc = '. dbh->quote($group_value);
319   } elsif ( $group_op eq '!=' ) {
320     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
321   } else {
322     die "guru meditation #00de: group_op $group_op\n";
323   }
324   
325 }
326
327 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
328 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
329
330 if ( $cgi->param('cust_tax') ) {
331   #false laziness -ish w/report_tax.cgi
332   my $cust_exempt;
333   if ( $cgi->param('taxname') ) {
334     my $q_taxname = dbh->quote($cgi->param('taxname'));
335     $cust_exempt =
336       "( tax = 'Y'
337          OR EXISTS ( SELECT 1 FROM cust_main_exemption
338                        WHERE cust_main_exemption.custnum = cust_main.custnum
339                          AND cust_main_exemption.taxname = $q_taxname )
340        )
341       ";
342   } else {
343     $cust_exempt = " tax = 'Y' ";
344   }
345
346   push @where, $cust_exempt;
347 }
348
349 my $count_query = "SELECT COUNT(DISTINCT billpkgnum),
350                           SUM(cust_credit_bill_pkg.amount)";
351
352 my $join_cust =
353   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum ) 
354     LEFT JOIN cust_main ON ( cust_bill.custnum = cust_main.custnum ) ';
355
356
357 my $join_pkg;
358
359 my $join_cust_bill_pkg = 'LEFT JOIN cust_bill_pkg USING ( billpkgnum )';
360
361 if ( $cgi->param('nottax') ) {
362
363   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
364                  LEFT JOIN part_pkg USING ( pkgpart )
365                  LEFT JOIN part_pkg AS override
366                    ON pkgpart_override = override.pkgpart ';
367   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
368     if $conf->exists('tax-pkg_address');
369
370 } elsif ( $cgi->param('istax') ) {
371
372   #false laziness w/report_tax.cgi $taxfromwhere
373   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
374             $cgi->param('iscredit') eq 'rate') {
375
376     $join_pkg .=
377       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ';
378     if ( $cgi->param('iscredit') eq 'rate' ) {
379       $join_pkg .= ', billpkgtaxratelocationnum )';
380     } elsif ( $conf->exists('tax-pkg_address') ) {
381       $join_pkg .= ', billpkgtaxlocationnum )';
382       push @where, "billpkgtaxratelocationnum IS NULL";
383     } else {
384       $join_pkg .= ' )';
385       push @where, "billpkgtaxratelocationnum IS NULL";
386     }
387
388     $join_pkg .= ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
389
390   } elsif ( $conf->exists('tax-pkg_address') ) {
391
392     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
393                    LEFT JOIN cust_location              USING ( locationnum ) ';
394
395     #quelle kludge, somewhat false laziness w/report_tax.cgi
396     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
397   }
398
399 } else { 
400
401   #die?
402   warn "neiether nottax nor istax parameters specified";
403   #same as before?
404   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
405                  LEFT JOIN part_pkg USING ( pkgpart ) ';
406
407 }
408
409 my $where = ' WHERE '. join(' AND ', @where);
410
411 my $join_credit = ' LEFT JOIN cust_credit_bill USING ( creditbillnum )
412                     LEFT JOIN cust_credit      USING ( crednum ) ';
413
414 $count_query .= " FROM cust_credit_bill_pkg
415                          $join_pkg
416                          $join_cust_bill_pkg
417                          $join_credit
418                          $join_cust
419                        $where";
420
421 my @select = ( 'cust_credit_bill_pkg.*',
422                'cust_bill_pkg.*',
423                'cust_credit.otaker',
424                'cust_credit._date AS cust_credit_date',
425                'cust_bill._date',
426              );
427 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
428 push @select, 'cust_main.custnum',
429               FS::UI::Web::cust_sql_fields();
430
431 my $query = {
432   'table'     => 'cust_credit_bill_pkg',
433   'addl_from' => "$join_pkg
434                   $join_cust_bill_pkg
435                   $join_credit
436                   $join_cust",
437   'hashref'   => {},
438   'select'    => join(', ', @select ),
439   'extra_sql' => $where,
440   'order_by'  => 'ORDER BY creditbillpkgnum', #cust_bill. or cust_credit._date?
441 };
442
443 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
444 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
445
446 my $conf = new FS::Conf;
447 my $money_char = $conf->config('money_char') || '$';
448
449 </%init>