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