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