add taxclass and paid/credit columns to line item reports, clickthrough to credit...
[freeside.git] / httemplate / search / cust_credit_bill_pkg.html
1 <% include( 'elements/search.html',
2               'title'         => 'Credit application detail', #to line item
3               'name_singular' => 'credit application',
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 if ( $cgi->param('billpkgnum') =~ /^(\d+)$/ ) {
110   push @where, "billpkgnum = $1";
111 }
112
113 #classnum
114 # not specified: all classes
115 # 0: empty class
116 # N: classnum
117 my $use_override = $cgi->param('use_override');
118 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
119   my $comparison = '';
120   if ( $1 == 0 ) {
121     $comparison = "IS NULL";
122   } else {
123     $comparison = "= $1";
124   }
125
126   if ( $use_override ) {
127     push @where, "(
128       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
129       override.classnum $comparison AND pkgpart_override IS NOT NULL
130     )";
131   } else {
132     push @where, "part_pkg.classnum $comparison";
133   }
134 }
135
136 if ( $cgi->param('taxclass')
137      && ! $cgi->param('istax')  #no part_pkg.taxclass in this case
138                                 #(should we save a taxclass or a link to taxnum
139                                 # in cust_bill_pkg or something like
140                                 # cust_bill_pkg_tax_location?)
141    )
142 {
143
144   #override taxclass when use_override is specified?  probably
145   #if ( $use_override ) {
146   #
147   #  push @where,
148   #    ' ( '. join(' OR ',
149   #                  map {
150   #                        ' (    part_pkg.taxclass = '. dbh->quote($_).
151   #                        '      AND pkgpart_override IS NULL '.
152   #                        '   OR '.
153   #                        '      override.taxclass = '. dbh->quote($_).
154   #                        '      AND pkgpart_override IS NOT NULL '.
155   #                        ' ) '
156   #                      }
157   #                      $cgi->param('taxclass')
158   #               ).
159   #    ' ) ';
160   #
161   #} else {
162
163     push @where,
164       ' ( '. join(' OR ',
165                     map ' part_pkg.taxclass = '.dbh->quote($_),
166                         $cgi->param('taxclass')
167                  ).
168       ' ) ';
169
170   #}
171
172 }
173
174 my @loc_param = qw( district city county state country );
175
176 if ( $cgi->param('out') ) {
177
178   my ( $loc_sql, @param ) = FS::cust_pkg->location_sql( 'ornull' => 1 );
179   while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
180     $loc_sql =~ s/\?/'cust_main_county.'.shift(@param)/e;
181   }
182
183   $loc_sql =~ s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g
184     if $cgi->param('istax');
185
186   push @where, "
187     0 = (
188           SELECT COUNT(*) FROM cust_main_county
189            WHERE cust_main_county.tax > 0
190              AND $loc_sql
191         )
192   ";
193
194   #not linked to by anything, but useful for debugging "out of taxable region"
195   if ( grep $cgi->param($_), @loc_param ) {
196
197     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
198
199     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
200     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
201       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
202     }
203
204     push @where, $loc_sql;
205
206   }
207
208 } elsif ( $cgi->param('country') ) {
209
210   my @counties = $cgi->param('county');
211    
212   if ( scalar(@counties) > 1 ) {
213
214     #hacky, could be more efficient.  care if it is ever used for more than the
215     # tax-report_groups filtering kludge
216
217     my $locs_sql =
218       ' ( '. join(' OR ', map {
219
220           my %ph = ( 'county' => dbh->quote($_),
221                      map { $_ => dbh->quote( $cgi->param($_) ) }
222                        qw( district city state country )
223                    );
224
225           my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
226           while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
227             $loc_sql =~ s/\?/$ph{shift(@param)}/e;
228           }
229
230           $loc_sql;
231
232         } @counties
233
234       ). ' ) ';
235
236     push @where, $locs_sql;
237
238   } else {
239
240     my %ph = map { $_ => dbh->quote( scalar($cgi->param($_)) ) } @loc_param;
241
242     my ( $loc_sql, @param ) = FS::cust_pkg->location_sql;
243     while ( $loc_sql =~ /\?/ ) { #easier to do our own substitution
244       $loc_sql =~ s/\?/$ph{shift(@param)}/e;
245     }
246
247     push @where, $loc_sql;
248
249   }
250    
251   my($title, $name);
252   if ( $cgi->param('istax') ) {
253     $title = 'Tax credits';
254     $name  = 'tax credits';
255     if ( $cgi->param('taxname') ) {
256       push @where, 'itemdesc = '. dbh->quote( $cgi->param('taxname') );
257     #} elsif ( $cgi->param('taxnameNULL') {
258     } else {
259       push @where, "( itemdesc IS NULL OR itemdesc = '' OR itemdesc = 'Tax' )";
260     }
261   } elsif ( $cgi->param('nottax') ) {
262     $title = 'Credit applications to line items';
263     $name  = 'applications';
264     #what can we usefully do with "taxname" ????  look up a class???
265   } else {
266     $title = 'Credit applications to line items';
267     $name  = 'applications';
268     #warn "neither nottax nor istax parameters specified";
269   }
270
271   if ( $cgi->param('taxclassNULL')
272        && ! $cgi->param('istax')  #no taxclass in this case
273      )
274   {
275
276     my %hash = ( 'country' => scalar($cgi->param('country')) );
277     foreach (qw( state county )) {
278       $hash{$_} = scalar($cgi->param($_)) if $cgi->param($_);
279     }
280     my $cust_main_county = qsearchs('cust_main_county', \%hash);
281     die "unknown base region for empty taxclass" unless $cust_main_county;
282
283     my $same_sql = $cust_main_county->sql_taxclass_sameregion;
284     push @where, $same_sql if $same_sql;
285
286   }
287
288 } elsif ( scalar( grep( /locationtaxid/, $cgi->param ) ) ) {
289
290   # this should really be shoved out to FS::cust_pkg->location_sql or something
291   # along with the code in report_newtax.cgi
292
293   my %pn = (
294    'county'        => 'tax_rate_location.county',
295    'state'         => 'tax_rate_location.state',
296    'city'          => 'tax_rate_location.city',
297    'locationtaxid' => 'cust_bill_pkg_tax_rate_location.locationtaxid',
298   );
299
300   my %ph = map { ( $pn{$_} => dbh->quote( $cgi->param($_) || '' ) ) }
301            qw( city county state locationtaxid );
302
303   push @where,
304     join( ' AND ', map { "( $_ = $ph{$_} OR $ph{$_} = '' AND $_ IS NULL)" }
305                    keys %ph
306     );
307
308 }
309
310 if ( $cgi->param('itemdesc') ) {
311   if ( $cgi->param('itemdesc') eq 'Tax' ) {
312     push @where, "(itemdesc='Tax' OR itemdesc is null)";
313   } else {
314     push @where, 'itemdesc='. dbh->quote($cgi->param('itemdesc'));
315   }
316 }
317
318 if ( $cgi->param('report_group') =~ /^(=|!=) (.*)$/ && $cgi->param('istax') ) {
319   my ( $group_op, $group_value ) = ( $1, $2 );
320   if ( $group_op eq '=' ) {
321     #push @where, 'itemdesc LIKE '. dbh->quote($group_value.'%');
322     push @where, 'itemdesc = '. dbh->quote($group_value);
323   } elsif ( $group_op eq '!=' ) {
324     push @where, '( itemdesc != '. dbh->quote($group_value) .' OR itemdesc IS NULL )';
325   } else {
326     die "guru meditation #00de: group_op $group_op\n";
327   }
328   
329 }
330
331 push @where, 'cust_bill_pkg.pkgnum != 0' if $cgi->param('nottax');
332 push @where, 'cust_bill_pkg.pkgnum  = 0' if $cgi->param('istax');
333
334 if ( $cgi->param('cust_tax') ) {
335   #false laziness -ish w/report_tax.cgi
336   my $cust_exempt;
337   if ( $cgi->param('taxname') ) {
338     my $q_taxname = dbh->quote($cgi->param('taxname'));
339     $cust_exempt =
340       "( tax = 'Y'
341          OR EXISTS ( SELECT 1 FROM cust_main_exemption
342                        WHERE cust_main_exemption.custnum = cust_main.custnum
343                          AND cust_main_exemption.taxname = $q_taxname )
344        )
345       ";
346   } else {
347     $cust_exempt = " tax = 'Y' ";
348   }
349
350   push @where, $cust_exempt;
351 }
352
353 my $count_query = "SELECT COUNT(DISTINCT creditbillpkgnum),
354                           SUM(cust_credit_bill_pkg.amount)";
355
356 my $join_cust =
357   '      JOIN cust_bill ON ( cust_bill_pkg.invnum = cust_bill.invnum ) 
358     LEFT JOIN cust_main ON ( cust_bill.custnum = cust_main.custnum ) ';
359
360
361 my $join_pkg;
362
363 my $join_cust_bill_pkg = 'LEFT JOIN cust_bill_pkg USING ( billpkgnum )';
364
365 if ( $cgi->param('nottax') ) {
366
367   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
368                  LEFT JOIN part_pkg USING ( pkgpart )
369                  LEFT JOIN part_pkg AS override
370                    ON pkgpart_override = override.pkgpart ';
371   $join_pkg .= ' LEFT JOIN cust_location USING ( locationnum ) '
372     if $conf->exists('tax-pkg_address');
373
374 } elsif ( $cgi->param('istax') ) {
375
376   #false laziness w/report_tax.cgi $taxfromwhere
377   if ( scalar( grep( /locationtaxid/, $cgi->param ) ) ||
378             $cgi->param('iscredit') eq 'rate') {
379
380     $join_pkg .=
381       ' LEFT JOIN cust_bill_pkg_tax_rate_location USING ( billpkgnum ';
382     if ( $cgi->param('iscredit') eq 'rate' ) {
383       $join_pkg .= ', billpkgtaxratelocationnum )';
384     } elsif ( $conf->exists('tax-pkg_address') ) {
385       $join_pkg .= ', billpkgtaxlocationnum )';
386       push @where, "billpkgtaxratelocationnum IS NULL";
387     } else {
388       $join_pkg .= ' )';
389       push @where, "billpkgtaxratelocationnum IS NULL";
390     }
391
392     $join_pkg .= ' LEFT JOIN tax_rate_location USING ( taxratelocationnum ) ';
393
394   } elsif ( $conf->exists('tax-pkg_address') ) {
395
396     $join_pkg .= ' LEFT JOIN cust_bill_pkg_tax_location USING ( billpkgnum )
397                    LEFT JOIN cust_location              USING ( locationnum ) ';
398
399     #quelle kludge, somewhat false laziness w/report_tax.cgi
400     s/cust_pkg\.locationnum/cust_bill_pkg_tax_location.locationnum/g for @where;
401   }
402
403 } else { 
404
405   #die?
406   warn "neiether nottax nor istax parameters specified";
407   #same as before?
408   $join_pkg =  ' LEFT JOIN cust_pkg USING ( pkgnum )
409                  LEFT JOIN part_pkg USING ( pkgpart ) ';
410
411 }
412
413 my $where = ' WHERE '. join(' AND ', @where);
414
415 my $join_credit = ' LEFT JOIN cust_credit_bill USING ( creditbillnum )
416                     LEFT JOIN cust_credit      USING ( crednum ) ';
417
418 $count_query .= " FROM cust_credit_bill_pkg
419                          $join_cust_bill_pkg
420                          $join_pkg
421                          $join_credit
422                          $join_cust
423                        $where";
424
425 my @select = ( 'cust_credit_bill_pkg.*',
426                'cust_bill_pkg.*',
427                'cust_credit.otaker',
428                'cust_credit._date AS cust_credit_date',
429                'cust_bill._date',
430              );
431 push @select, 'part_pkg.pkg' unless $cgi->param('istax');
432 push @select, 'cust_main.custnum',
433               FS::UI::Web::cust_sql_fields();
434
435 my $query = {
436   'table'     => 'cust_credit_bill_pkg',
437   'addl_from' => "$join_cust_bill_pkg
438                   $join_pkg
439                   $join_credit
440                   $join_cust",
441   'hashref'   => {},
442   'select'    => join(', ', @select ),
443   'extra_sql' => $where,
444   'order_by'  => 'ORDER BY creditbillpkgnum', #cust_bill. or cust_credit._date?
445 };
446
447 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
448 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
449
450 my $conf = new FS::Conf;
451 my $money_char = $conf->config('money_char') || '$';
452
453 </%init>