Added option for Credit Report to include Voided Credits RT#73200
[freeside.git] / httemplate / search / cust_credit.html
1 <& elements/search.html,
2                  'title'       => $title,
3                  'name'        => emt('credits'),
4                  'query'       => $sql_query,
5                  'count_query' => $count_query,
6                  'count_addl'  => \@count_addl,
7                  'header'      => \@header,
8                  'fields'      => \@fields,
9                  'sort_fields' => \@sort_fields,
10                  'align' => $align,
11                  'links' => \@links,
12                  'color' => \@color,
13                  'style' => \@style,
14                  'classname_from_column' => 1,
15 &>
16 <%init>
17
18 die "access denied"
19   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
20
21 my $conf = new FS::Conf;
22
23 my $money_char = $conf->config('money_char') || '$';
24
25 my $title = emt('Credit Search Results');
26
27 my $unapplied = $cgi->param('unapplied');
28 $title = emt("Unapplied $title") if $unapplied;
29 my $clink = sub {
30   my $cust_bill = shift;
31   $cust_bill->cust_main_custnum
32     ? [ "${p}view/cust_main.cgi?", 'custnum' ]
33     : '';
34 };
35
36 # form selectbox for show_voided_credits:
37 # - value='': use default from $conf
38 # - value="0" : override default, do not show voided credits
39 # - value="1" : override default, show voided credits
40 my $show_voided_credits;
41 $show_voided_credits = $conf->config('show_voided_credits');
42 $show_voided_credits = $cgi->param('show_voided_credits')
43   if $cgi->param('show_voided_credits') =~ /^(\d)$/;
44
45 my (@header, @fields, @sort_fields, $align, @links, @color, @style);
46 $align = '';
47
48 # Report Column: Amount
49 push @header, emt('Amount');
50 push @fields, sub { $money_char .sprintf('%.2f', shift->amount) };
51 push @sort_fields, 'amount';
52 $align .= 'r';
53 push @links, '';
54 push @color, '';
55 push @style, '';
56
57 # Report Column: Unapplied Amount
58 if ($unapplied) {
59   push @header, emt('Unapplied');
60   push @fields, sub { $money_char .sprintf('%.2f', shift->unapplied_amount) };
61   push @sort_fields, '';
62   $align .= 'r';
63   push @links, '';
64   push @color, '';
65   push @style, '';
66 }
67
68 # Report Columns: Date, By, Reason, Info
69 push @header, emt('Date'),
70               emt('By'),
71               emt('Reason'),
72               emt('Info'),
73               ;
74 push @fields, sub { time2str('%b %d %Y', shift->_date ) },
75               'otaker',
76               'reason_only',
77               'addlinfo',
78               ;
79 push @sort_fields, '_date', 'otaker', 'reasonnum', 'addlinfo';
80 $align .= 'rlll';
81 push @links,  '',
82               '',
83               '',
84               '',
85               ;
86 push @color,  '',
87               '',
88               '',
89               '',
90               ;
91 push @style,  '',
92               '',
93               '',
94               '',
95               ;
96
97 # insert customer email after 'Reason' if this is a commission report
98 if ( $cgi->param('commission_salesnum') or $cgi->param('commission_agentnum') ) {
99   my $sub_customer_email = sub {
100     my $cust_credit = shift;
101     my $cust_event = $cust_credit->cust_event or return '';
102     my $cust_X = $cust_event->cust_X or return '';
103     my $cust_main = $cust_X->cust_main or return '';
104     my ($email) = $cust_main->invoicing_list_emailonly;
105     return encode_entities("<$email>") if length($email);
106     '';
107   };
108   push @header, '';
109   push @fields, $sub_customer_email;
110   push @sort_fields, '';
111   $align .= 'l';
112   push @links, '';
113   push @color, '';
114   push @style, '';
115 }
116
117 # cust fields
118 push @header, FS::UI::Web::cust_header();
119 push @fields, \&FS::UI::Web::cust_fields;
120 push @sort_fields, FS::UI::Web::cust_sort_fields;
121 $align .= FS::UI::Web::cust_aligns();
122 push @links, map { $_ ne 'Cust. Status' ? $clink : '' }
123                          FS::UI::Web::cust_header();
124 push @color, FS::UI::Web::cust_colors();
125 push @style, FS::UI::Web::cust_styles();
126
127 if ( $show_voided_credits ) {
128
129   # Report Column: Void By:
130   push @header, emt('Void By');
131   push @fields, sub {
132     my $rec = shift;
133     return $rec->void_username
134       if $rec->isa('FS::cust_credit_void');
135     return '';
136   };
137   push @sort_fields, '';
138   $align .= 'l';
139   push @links, '';
140   push @color, '';
141   push @style, '';
142
143   # Report Column: Void Date:
144   push @header, emt('Void Date');
145   push @fields, sub {
146     my $rec = shift;
147     return time2str('%b %d %Y', $rec->void_date )
148       if $rec->isa('FS::cust_credit_void');
149     return '';
150   };
151   push @sort_fields, '';
152   $align .= 'l';
153   push @links, '';
154   push @color, '';
155   push @style, '';
156
157   # Report Column: Void Reason:
158   push @header, emt('Void Reason');
159   push @fields, sub {
160     my $rec = shift;
161     return $rec->void_reason_text
162       if $rec->isa('FS::cust_credit_void');
163     return '';
164   };
165   push @sort_fields, '';
166   $align .= 'l';
167   push @links, '';
168   push @color, '';
169   push @style, '';
170 }
171
172
173 my @search = ();
174 my $addl_from = '';
175
176 if ( $cgi->param('usernum') =~ /^(\d+)$/ ) {
177   push @search, "cust_credit.usernum = $1";
178 }
179
180 if ( $cgi->param('agentnum') && $cgi->param('agentnum') =~ /^(\d+)$/ ) {
181   push @search, "agentnum = $1";
182   my $agent = qsearchs('agent', { 'agentnum' => $1 } );
183   die "unknown agentnum $1" unless $agent;
184   $title = $agent->agent. " $title";
185 }
186
187 if ( $cgi->param('credbatch') =~ /^([\w\-\/\.\:]+)$/ ) {
188   push @search, "cust_credit.credbatch = '$1'";
189 }
190
191 # commission_salesnum
192 if ( $cgi->param('commission_salesnum') =~ /^(\d+)$/ ) {
193   push @search, "commission_salesnum = $1";
194 }
195
196 # commission agentnum
197 if ( $cgi->param('commission_agentnum') =~ /^(\d+)$/ ) {
198   push @search, "commission_agentnum = $1";
199 }
200
201 # commission_classnum
202 if ( grep { $_ eq 'commission_classnum' } $cgi->param ) {
203   $cgi->param('commission_classnum') =~ /^(\d*)$/ or die 'guru meditation #13';
204   my $classnum = $1;
205   push @search, "part_pkg.classnum ". ( $classnum ? " = $classnum"
206                                                  : " IS NULL "    );
207
208   $addl_from .=
209     ' LEFT JOIN cust_pkg ON ( commission_pkgnum = cust_pkg.pkgnum ) '.
210     ' LEFT JOIN part_pkg USING ( pkgpart ) ';
211 }
212
213 if ( $cgi->param('refnum') && $cgi->param('refnum') =~ /^(\d+)$/ ) {
214   push @search, "refnum = $1";
215   my $part_referral = qsearchs('part_referral', { 'refnum' => $1 } );
216   die "unknown refnum $1" unless $part_referral;
217   $title = $part_referral->referral. " $title";
218 }
219
220
221 # cust_classnum (false laziness w/ elements/cust_main_dayranges.html, elements/cust_pay_or_refund.html, prepaid_income.html, cust_bill_pay.html, cust_bill_pkg.html, cust_bill_pkg_referral.html, unearned_detail.html, cust_credit_refund.html, cust_main::Search::search_sql)
222 if ( grep { $_ eq 'cust_classnum' } $cgi->param ) {
223   my @classnums = grep /^\d*$/, $cgi->param('cust_classnum');
224   push @search, 'COALESCE( cust_main.classnum, 0) IN ( '.
225                     join(',', map { $_ || '0' } @classnums ).
226                 ' )'
227     if @classnums;
228 }
229
230 if ( $unapplied ) {
231   push @search, FS::cust_credit->unapplied_sql . ' > 0';
232 }
233
234 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
235 push @search, "_date >= $beginning ",
236               "_date <= $ending";
237
238 push @search, FS::UI::Web::parse_lt_gt($cgi, 'amount' );
239
240 # Agent virtualization
241 push @search, $FS::CurrentUser::CurrentUser->agentnums_sql(table=>'cust_main');
242
243 my @select = (
244   "'cust_credit' as __classname",
245   qw(cust_credit.crednum
246      cust_credit.custnum
247      cust_credit._date
248      cust_credit.amount
249      cust_credit.currency
250      cust_credit.otaker
251      cust_credit.usernum
252      cust_credit.reason
253      cust_credit.reasonnum
254      cust_credit.addlinfo
255      cust_credit.closed
256      cust_credit.pkgnum
257      cust_credit.eventnum
258      cust_credit.commission_agentnum
259      cust_credit.commission_salesnum
260      cust_credit.commission_pkgnum
261      cust_credit.commission_invnum
262      cust_credit.credbatch
263      ),
264   'Null as void_date',
265   'Null as void_usernum',
266   'Null as void_reasonnum',
267   'Null as void_reason',
268   'Null as void_reason_text',
269   'Null as void_username',
270   'cust_main.custnum as cust_main_custnum',
271   FS::UI::Web::cust_sql_fields(),
272 );
273 my @select_void = (
274   "'cust_credit_void' as __classname",
275   qw(cust_credit_void.crednum
276      cust_credit_void.custnum
277      cust_credit_void._date
278      cust_credit_void.amount
279      cust_credit_void.currency
280      cust_credit_void.otaker
281      cust_credit_void.usernum
282      cust_credit_void.reason
283      cust_credit_void.reasonnum
284      cust_credit_void.addlinfo
285      cust_credit_void.closed
286      cust_credit_void.pkgnum
287      cust_credit_void.eventnum
288      cust_credit_void.commission_agentnum
289      cust_credit_void.commission_salesnum
290      cust_credit_void.commission_pkgnum
291      cust_credit_void.commission_invnum
292      ),
293   'Null as credbatch',
294   qw(cust_credit_void.void_date
295      cust_credit_void.void_usernum
296      cust_credit_void.void_reasonnum
297      cust_credit_void.void_reason
298   ),
299   'reason.reason as void_reason_text',
300   'vusers.username as void_username',
301   'cust_main.custnum as cust_main_custnum',
302   FS::UI::Web::cust_sql_fields(),
303 );
304
305 if ( $unapplied ) {
306   push @select, '('.FS::cust_credit->unapplied_sql .') AS unapplied_amount';
307   push @search, FS::cust_credit->unapplied_sql .' > 0';
308 }
309
310 my $where = 'WHERE '. join(' AND ', @search);
311
312 my $count_query = 'SELECT COUNT(*), SUM(amount) ';
313 $count_query .= ', SUM(' . FS::cust_credit->unapplied_sql . ') ' if $unapplied;
314 $count_query .= 'FROM cust_credit'.
315                   $addl_from. FS::UI::Web::join_cust_main('cust_credit').
316                   $where;
317
318 my @count_addl = ( $money_char.'%.2f total credited (gross)' );
319 push @count_addl, $money_char.'%.2f unapplied' if $unapplied;
320
321 my $sql_query   = {
322   'table'     => 'cust_credit',
323   'select'    => join(', ',@select),
324   'hashref'   => {},
325   'extra_sql' => $where,
326   'addl_from' => $addl_from. FS::UI::Web::join_cust_main('cust_credit')
327 };
328
329 # Join to get reason text and void username to avoid two extra query per row
330 my $addl_from_void = join(' ',
331   $addl_from,
332   FS::UI::Web::join_cust_main('cust_credit_void'),
333   ' LEFT JOIN reason ON (reason.reasonnum = cust_credit_void.void_reasonnum) ',
334   ' LEFT JOIN access_user as vusers '.
335     'on (vusers.usernum = cust_credit_void.void_usernum) ',
336 );
337
338 my $where_void = $where;
339 $where_void =~ s/cust_credit/cust_credit_void/g;
340
341 my $sql_query_void = {
342   'table'     => 'cust_credit_void',
343   'select'    => join(', ',@select_void),
344   'hashref'   => {},
345   'extra_sql' => $where_void,
346   'addl_from' => $addl_from_void,
347 };
348
349 if ($show_voided_credits) {
350
351   $sql_query = [$sql_query, $sql_query_void];
352
353   my $count_cust_credit;
354   my $count_cust_credit_void;
355   my $count_sum;
356
357   # Expected fields for count query are count, sum
358   # Get those totals here, and send a fake count query
359   my $count_row = qsearchs({
360     table => 'cust_credit',
361     select => 'count(*), sum(amount)',
362     extra_sql => $where,
363     addl_from => $addl_from . FS::UI::Web::join_cust_main('cust_credit'),
364   });
365   $count_cust_credit = $count_row->count || 0;
366   $count_sum = $count_row->sum || 0;
367
368   $count_row = qsearchs({
369     table => 'cust_credit_void',
370     select => 'count(*)',
371     extra_sql => $where_void,
372     addl_from => $addl_from_void,
373   });
374   $count_cust_credit_void = $count_row->count || 0;
375
376   my $count_combined = $count_cust_credit + $count_cust_credit_void;
377
378   # Fake count query providing needed values
379   $count_query = "SELECT $count_combined as count, $count_sum as sum";
380 }
381
382 </%init>