RT#23598: Feature Request - Email notice to A/R Report Results
[freeside.git] / httemplate / search / elements / cust_main_dayranges.html
1 <%doc>
2
3 Example:
4
5   <& elements/cust_main_dayranges.html,
6                  'title'       => 'Accounts Receivable Aging Summary',
7                  'range_sub'   => $mysub,
8                  'email_link'  => 1,  #adds an action column with an email link if true
9   &>
10
11   my $mysub = sub {
12     my( $start, $end ) = @_;
13
14     "SQL EXPRESSION BASED ON $start AND $end";
15     # where $start and $end are unix timestamps
16   };
17
18 </%doc>
19 <& search.html,
20                  'name'        => 'customers',
21                  'query'       => $sql_query,
22                  'count_query' => $count_sql,
23                  'header'      => [
24                                     @cust_header,
25                                     '0-30',
26                                     '30-60',
27                                     '60-90',
28                                     '90+',
29                                     emt('Total'),
30                                     @pay_head,
31                                     @act_header,
32                                   ],
33                  'footer'      => [
34                                     'Total',
35                                     ( map '',( 1 .. $#cust_header ),),
36                                     sprintf( $money_char.'%.2f',
37                                              $row->{'rangecol_0_30'} ),
38                                     sprintf( $money_char.'%.2f',
39                                              $row->{'rangecol_30_60'} ),
40                                     sprintf( $money_char.'%.2f',
41                                              $row->{'rangecol_60_90'} ),
42                                     sprintf( $money_char.'%.2f',
43                                              $row->{'rangecol_90_0'} ),
44                                     sprintf( '<b>'.$money_char.'%.2f</b>',
45                                              $row->{'rangecol_0_0'} ),
46                                     ('') x @pay_labels,
47                                     @act_blank,
48                                   ],
49                  'fields'      => [
50                                     FS::UI::Web::cust_fields_subs(),
51                                     format_rangecol('0_30'),
52                                     format_rangecol('30_60'),
53                                     format_rangecol('60_90'),
54                                     format_rangecol('90_0'),
55                                     format_rangecol('0_0'),
56                                     @pay_labels,
57                                     @act_fields,
58                                   ],
59                  'links'       => [
60                                     ( map { $_ ne 'Cust. Status' ? $clink : '' }
61                                           @cust_header
62                                     ),
63                                     '',
64                                     '',
65                                     '',
66                                     '',
67                                     '',
68                                     @pay_links,
69                                     @act_blank,
70                                   ],
71                  'link_onclicks' => [ ( map '', @cust_header ),
72                                       '', '', '', '', '', 
73                                       ( map '', @pay_labels ),
74                                       @act_link_onclicks,
75                                     ],
76                  'align'       => FS::UI::Web::cust_aligns(). 
77                                    'rrrrr'.
78                                   ('c' x @pay_labels),
79                                   @act_align,
80                  'size'        => [ ( map '', @cust_header ),
81                                     #'-1', '', '', '', '',  '', ],
82                                     '', '', '', '', '',  '', 
83                                     ( map '', @pay_labels ),
84                                     @act_blank,
85                                     ],
86                  'style'       => [ FS::UI::Web::cust_styles(),
87                                     #'b', '', '', '', '', 'b', ],
88                                     '', '', '', '', 'b', 
89                                     ( map '', @pay_labels ),
90                                     @act_blank,
91                                     ],
92                  'xls_format'  => [ (map '', FS::UI::Web::cust_styles),
93                                     '', '', '', '', { bold => 1 },
94                                     @act_blank,
95                                   ],
96                  'color'       => [
97                                     FS::UI::Web::cust_colors(),
98                                     '',
99                                     '',
100                                     '',
101                                     '',
102                                     '',
103                                     '',
104                                     ( map '', @pay_labels ),
105                                     @act_blank,
106                                   ],
107                %opt,
108 &>
109 <%init>
110
111 my @cust_header = FS::UI::Web::cust_header($cgi->param('cust_fields'));
112 my %opt = @_;
113
114 #actually need to auto-generate other things too for a passed-in ranges to work
115 my $ranges = $opt{'ranges'} ? delete($opt{'ranges'}) : [
116   [  0, 30 ],
117   [ 30, 60 ],
118   [ 60, 90 ],
119   [ 90,  0 ],
120   [  0,  0 ],
121 ];
122
123 my $range_sub = delete($opt{'range_sub'}); #or die
124
125 my $as_of;
126 if($cgi->param('as_of')) {
127   $as_of = parse_datetime($cgi->param('as_of')) || '';
128   $opt{'title'} .= ' ('.$cgi->param('as_of').')' if $as_of;
129 }
130
131 my $range_cols = join(',', 
132   map call_range_sub($range_sub, @$_, 'as_of' => $as_of ), @$ranges );
133
134 my $select_count_pkgs = FS::cust_main->select_count_pkgs_sql;
135
136 my $active_sql    = FS::cust_pkg->active_sql;
137 my $inactive_sql  = FS::cust_pkg->inactive_sql;
138 my $suspended_sql = FS::cust_pkg->suspended_sql;
139 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
140
141 my $packages_cols = <<END;
142      ( $select_count_pkgs                    ) AS num_pkgs_sql,
143      ( $select_count_pkgs AND $active_sql    ) AS active_pkgs,
144      ( $select_count_pkgs AND $inactive_sql  ) AS inactive_pkgs,
145      ( $select_count_pkgs AND $suspended_sql ) AS suspended_pkgs,
146      ( $select_count_pkgs AND $cancelled_sql ) AS cancelled_pkgs
147 END
148
149 my @where = ();
150
151 unless ( $cgi->param('all_customers') ) {
152 # Exclude entire cust_main records where the balance is >0
153   my $days = 0;
154   if ( $cgi->param('days') =~ /^\s*(\d+)\s*$/ ) {
155     $days = $1;
156   }
157
158   # If this is set, allow cust_main records with nonzero balances
159   my $negative = $cgi->param('negative') || 0;
160
161   push @where,
162     call_range_sub($range_sub, $days, 0, 'as_of' => $as_of, 'no_as'=>1). 
163     ($negative ? ' != 0' : ' > 0');
164 }
165
166 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
167   my $agentnum = $1;
168   push @where, "agentnum = $agentnum";
169 }
170
171 #status (false laziness w/cust_main::search_sql
172
173 #prospect active inactive suspended cancelled
174 if ( grep { $cgi->param('status') eq $_ } FS::cust_main->statuses() ) {
175   my $method = $cgi->param('status'). '_sql';
176   push @where, FS::cust_main->$method();
177 }
178
179 # cust_classnum (false laziness w/prepaid_income.html, elements/cust_pay_or_refund.html, cust_bill_pay.html, cust_bill_pkg.html, cust_bill_pkg_referral.html, unearned_detail.html, cust_credit.html, cust_credit_refund.html, cust_main::Search::search_sql)
180 if ( grep { $_ eq 'cust_classnum' } $cgi->param ) {
181   my @classnums = grep /^\d*$/, $cgi->param('cust_classnum');
182   push @where, 'COALESCE( cust_main.classnum, 0) IN ( '.
183                    join(',', map { $_ || '0' } @classnums ).
184                ' )'
185     if @classnums;
186 }
187
188 #here is the agent virtualization
189 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
190
191 my $where = join(' AND ', @where);
192 $where = "WHERE $where" if $where;
193
194 my $count_sql = "select count(*) from cust_main $where";
195
196 my $sql_query = {
197   'table'     => 'cust_main',
198   'addl_from' => FS::UI::Web::join_cust_main('cust_main'),
199   'hashref'   => {},
200   'select'    => join(',',
201                    #'cust_main.*',
202                    'cust_main.custnum',
203                    $range_cols,
204                    $packages_cols,
205                    FS::UI::Web::cust_sql_fields(),
206                    'payby',
207                  ),
208   'extra_sql' => $where,
209   'order_by'  => "order by coalesce(lower(company), ''), lower(last)",
210 };
211
212 my $total_sql =
213   "SELECT ".
214       join(',', 
215         map call_range_sub( $range_sub, @$_, 'as_of' => $as_of, 'sum'=>1 ), 
216         @$ranges).
217     " FROM cust_main $where";
218
219 my $total_sth = dbh->prepare($total_sql) or die dbh->errstr;
220 $total_sth->execute or die "error executing $total_sql: ". $total_sth->errstr;
221 my $row = $total_sth->fetchrow_hashref();
222
223 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
224
225 my (@payby, @pay_head, @pay_labels, @pay_links);
226
227 my %payby = map {$_ => 1} $conf->config('payby');
228 if(%payby) {
229   push @payby, 'CARD' if ($payby{'CARD'} or $payby{'DCRD'});
230   push @payby, 'CHEK' if ($payby{'CHEK'} or $payby{'DCHK'});
231 }
232 else {
233   @payby = ('CARD','CHEK')
234 }
235
236 if($opt{'payment_links'} && $curuser->access_right('Process payment') && @payby) {
237   my %label = ( CARD => 'Card',
238                 CHEK => 'E-Check' );
239   push @pay_head, ({nodownload => 1}) foreach @payby;
240   $pay_head[0] = { label => 'Process',
241                    nodownload => 1,
242                    colspan => scalar(@payby) };
243
244   @pay_labels = (map { my $payby = $_; 
245                        my $label = $label{$payby};
246                        sub {($payby eq $_[0]->payby) ? "<b>".emt("$label (on file)")."</b>" : emt($label)}
247                      } @payby );
248
249   @pay_links = (map { [ "${p}misc/payment.cgi?payby=$_;custnum=", 'custnum' ] }
250                          @payby );
251 }
252
253 my (@act_header, @act_fields, @act_link_onclicks, @act_align, @act_blank);
254 if (delete($opt{'email_links'})) {
255   push @act_header, 'Actions';
256   push @act_fields, sub { 'send email' };
257   push @act_link_onclicks, sub {
258     my $row = shift;
259     my $custnum = $row->custnum;
260     return qq!window.open('${p}misc/email-customers.html?table=cust_main&custnum=$custnum','_blank')!;
261   };
262   push @act_align, 'l';
263   push @act_blank, '';
264 }
265
266 </%init>
267 <%once>
268
269 my $conf = new FS::Conf;
270 my $curuser = $FS::CurrentUser::CurrentUser;
271
272 my $money_char = $conf->config('money_char') || '$';
273
274 #Example:
275 #
276 # my $balance = balance(
277 #   $start, $end, 
278 #   'no_as'  => 1, #set to true when using in a WHERE clause (supress AS clause)
279 #                 #or 0 / omit when using in a SELECT clause as a column
280 #                 #  ("AS balance_$start_$end")
281 #   'sum'    => 1, #set to true to get a SUM() of the values, for totals
282 #
283 #   #obsolete? options for totals (passed to cust_main::balance_date_sql)
284 #   'total'  => 1, #set to true to remove all customer comparison clauses
285 #   'join'   => $join,   #JOIN clause
286 #   'where'  => \@where, #WHERE clause hashref (elements "AND"ed together)
287 # )
288
289 sub call_range_sub {
290   my($range_sub, $startdays, $enddays, %opt) = @_;
291
292   my $as = $opt{'no_as'} ? '' : " AS rangecol_${startdays}_$enddays";
293
294   my $as_of = $opt{'as_of'} || time;
295   my $cutoff = DateTime->from_epoch(epoch => $as_of, time_zone => 'local');
296   $cutoff->truncate(to => 'day'); # local midnight on the report day
297   $cutoff->add(days => 1); # the day after that
298   $cutoff->subtract(seconds => 1); # the last second of the report day
299
300   my $start = $cutoff->clone;
301   $start->subtract(days => $startdays);
302  
303   my $end = $cutoff->clone;
304   $end->subtract(days => $enddays);
305
306   #warn "cutoff ".$cutoff->epoch.", range $startdays-$enddays (".$start->epoch . '-' . ($enddays ? $end->epoch : '').")\n";
307   my $sql = &{$range_sub}( $start->epoch, 
308                            $enddays ? $end->epoch : '', 
309                            $cutoff->epoch ); #%opt?
310
311   $sql = "SUM($sql)" if $opt{'sum'};
312
313   $sql.$as;
314
315 }
316
317 sub format_rangecol { #closures help alot
318   my $range = shift;
319   sub { sprintf( $money_char.'%.2f', shift->get("rangecol_$range") ) };
320 }
321
322 </%once>