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