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