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