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