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