fix account search by time remaining to deal with situations w/o a recurring amount
[freeside.git] / httemplate / search / svc_acct.cgi
1 <% include( 'elements/search.html',
2                  'title'       => 'Account Search Results',
3                  'name'        => 'accounts',
4                  'query'       => $sql_query,
5                  'count_query' => $count_query,
6                  'redirect'    => $link,
7                  'header'      => \@header,
8                  'fields'      => \@fields,
9                  'links'       => \@links,
10                  'align'       => $align,
11                  'color'       => \@color,
12                  'style'       => \@style,
13              )
14 %>
15 <%once>
16
17 #false laziness w/ClientAPI/MyAccount.pm
18 sub format_time { 
19   my $support = shift;
20   (($support < 0) ? '-' : '' ). int(abs($support)/3600)."h".sprintf("%02d",(abs($support)%3600)/60)."m";
21 }
22
23 sub timelast {
24   my( $svc_acct, $last, $permonth ) = @_;
25
26   my $sql = "
27     SELECT SUM(support) FROM acct_rt_transaction
28       LEFT JOIN Transactions
29         ON Transactions.Id = acct_rt_transaction.transaction_id
30     WHERE svcnum = ? 
31       AND Transactions.Created >= ?
32   ";
33
34   my $sth = dbh->prepare($sql) or die dbh->errstr;
35   $sth->execute( $svc_acct->svcnum,
36                  time2str('%Y-%m-%d %X', time - $last*86400 ) 
37                )
38     or die $sth->errstr;
39
40   my $seconds = $sth->fetchrow_arrayref->[0];
41
42   my $return = (($seconds < 0) ? '-' : '') . concise(duration($seconds));
43
44   $return .= sprintf(' (%.2fx)', $seconds / $permonth ) if $permonth;
45
46   $return;
47
48 }
49
50 </%once>
51 <%init>
52
53 die "access denied"
54   unless $FS::CurrentUser::CurrentUser->access_right('List services');
55
56 my $link      = [ "${p}view/svc_acct.cgi?",   'svcnum'  ];
57 my $link_cust = sub {
58   my $svc_acct = shift;
59   if ( $svc_acct->custnum ) {
60     [ "${p}view/cust_main.cgi?", 'custnum' ];
61   } else {
62     '';
63   }
64 };
65
66 my @extra_sql = ();
67
68 my @header = ( '#', 'Service', 'Account', 'UID', 'Last Login' );
69 my @fields = ( 'svcnum', 'svc', 'email', 'uid', 'last_login_text' );
70 my @links = ( $link, $link, $link, $link, $link );
71 my $align = 'rlllr';
72 my @color = ( '', '', '', '', '' );
73 my @style = ( '', '', '', '', '' );
74
75 if ( $cgi->param('domain') ) { 
76   my $svc_domain =
77     qsearchs('svc_domain', { 'domain' => $cgi->param('domain') } );
78   unless ( $svc_domain ) {
79     #it would be nice if this looked more like the other "not found"
80     #errors, but this will do for now.
81     errorpage("Domain ". $cgi->param('domain'). " not found at all");
82   } else {
83     push @extra_sql, 'domsvc = '. $svc_domain->svcnum;
84   }
85 }
86
87 my $timepermonth = '';
88
89 my $orderby = 'ORDER BY svcnum';
90 if ( $cgi->param('magic') =~ /^(all|unlinked)$/ ) {
91
92   push @extra_sql, 'pkgnum IS NULL'
93     if $cgi->param('magic') eq 'unlinked';
94
95   my $sortby = '';
96   if ( $cgi->param('sortby') =~ /^(\w+)$/ ) {
97     $sortby = $1;
98     $sortby = "LOWER($sortby)"
99       if $sortby eq 'username';
100     push @extra_sql, "$sortby IS NOT NULL"
101       if $sortby eq 'uid' || $sortby eq 'seconds' || $sortby eq 'last_login';
102     $orderby = "ORDER BY $sortby";
103   }
104
105   if ( $sortby eq 'seconds' ) {
106     #push @header, 'Time remaining';
107     push @header, 'Time';
108     push @fields, sub { my $svc_acct = shift; format_time($svc_acct->seconds) };
109     push @links, '';
110     $align .= 'r';
111     push @color, '';
112     push @style, '';
113
114     my $conf = new FS::Conf;
115     if ( $conf->exists('svc_acct-display_paid_time_remaining') ) {
116       push @header, 'Paid time', 'Last 30', 'Last 60', 'Last 90';
117       push @fields,
118         sub {
119           my $svc_acct = shift;
120           my $seconds = $svc_acct->seconds;
121           my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
122           my $part_pkg = $cust_pkg->part_pkg;
123
124           #my $timepermonth = $part_pkg->option('seconds');
125           $timepermonth = $part_pkg->option('seconds');
126           $timepermonth = $timepermonth / $part_pkg->freq
127             if $part_pkg->freq =~ /^\d+$/ && $part_pkg->freq != 0;
128
129           #my $recur = $part_pkg->calc_recur($cust_pkg);
130           my $recur = $part_pkg->base_recur($cust_pkg);
131
132           return format_time($seconds) unless $timepermonth && $recur;
133
134           my $balance = $cust_pkg->cust_main->balance;
135           my $months_unpaid = $balance / $recur;
136           my $time_unpaid = $months_unpaid * $timepermonth;
137           format_time($seconds-$time_unpaid).
138             sprintf(' (%.2fx monthly)', ( $seconds-$time_unpaid ) / $timepermonth );
139         },
140         sub { timelast( shift, 30, $timepermonth ); },
141         sub { timelast( shift, 60, $timepermonth ); },
142         sub { timelast( shift, 90, $timepermonth ); },
143       ;
144       push @links, '', '', '', '';
145       $align .= 'rrrr';
146       push @color, '', '', '', '';
147       push @style, '', '', '', '';
148     }
149
150   }
151
152 } elsif ( $cgi->param('magic') =~ /^nologin$/ ) {
153
154   if ( $cgi->param('sortby') =~ /^(\w+)$/ ) {
155     my $sortby = $1;
156     $sortby = "LOWER($sortby)"
157       if $sortby eq 'username';
158     push @extra_sql, "last_login IS NULL";
159     $orderby = "ORDER BY $sortby";
160   }
161
162 } elsif ( $cgi->param('magic') =~ /^advanced$/ ) {
163   $orderby = "";
164
165   if ( $cgi->param('agentnum') =~ /^(\d+)$/ and $1 ) {
166     push @extra_sql, "agentnum = $1";
167   }
168
169   my $pkgpart = join (' OR cust_pkg.pkgpart=',
170                       grep {$_} map { /^(\d+)$/; } ($cgi->param('pkgpart')));
171   push @extra_sql,  '(cust_pkg.pkgpart=' . $pkgpart . ')' if $pkgpart;
172                       
173   foreach my $field (qw( last_login last_logout )) {
174
175     my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi, $field);
176
177     next if $beginning == 0 && $ending == 4294967295;
178
179     if ($cgi->param($field."_invert")) {
180       push @extra_sql,
181         "(svc_acct.$field IS NULL OR ".
182         "svc_acct.$field < $beginning AND ".
183         "svc_acct.$field > $ending)";
184     } else {
185       push @extra_sql,
186         "svc_acct.$field IS NOT NULL",
187         "svc_acct.$field >= $beginning",
188         "svc_acct.$field <= $ending";
189     }
190   
191     $orderby ||= "ORDER BY svc_acct.$field" .
192       ($cgi->param($field."_invert") ? ' DESC' : '');
193
194   }
195
196   $orderby ||= "ORDER BY svcnum";
197
198 } elsif ( $cgi->param('popnum') =~ /^(\d+)$/ ) {
199   push @extra_sql, "popnum = $1";
200   $orderby = "ORDER BY LOWER(username)";
201 } elsif ( $cgi->param('svcpart') =~ /^(\d+)$/ ) {
202   push @extra_sql, "svcpart = $1";
203   $orderby = "ORDER BY uid";
204   #$orderby = "ORDER BY svcnum";
205 } else {
206   $orderby = "ORDER BY uid";
207
208   my @username_sql;
209
210   my %username_type;
211   foreach ( $cgi->param('username_type') ) {
212     $username_type{$_}++;
213   }
214
215   $cgi->param('username') =~ /^([\w\-\.\&]+)$/; #untaint username_text
216   my $username = $1;
217
218   push @username_sql, "username ILIKE '$username'"
219     if $username_type{'Exact'}
220     || $username_type{'Fuzzy'};
221
222   push @username_sql, "username ILIKE '\%$username\%'"
223     if $username_type{'Substring'}
224     || $username_type{'All'};
225
226   if ( $username_type{'Fuzzy'} || $username_type{'All'} ) {
227     &FS::svc_acct::check_and_rebuild_fuzzyfiles;
228     my $all_username = &FS::svc_acct::all_username;
229
230     my %username;
231     if ( $username_type{'Fuzzy'} || $username_type{'All'} ) { 
232       foreach ( amatch($username, [ qw(i) ], @$all_username) ) {
233         $username{$_}++; 
234       }
235     }
236
237     #if ($username_type{'Sound-alike'}) {
238     #}
239
240     push @username_sql, "username = '$_'"
241       foreach (keys %username);
242
243   }
244
245   push @extra_sql, '( '. join( ' OR ', @username_sql). ' )';
246
247 }
248
249 push @header, FS::UI::Web::cust_header($cgi->param('cust_fields'));
250 push @fields, \&FS::UI::Web::cust_fields,
251 push @links, map { $_ ne 'Cust. Status' ? $link_cust : '' }
252                  FS::UI::Web::cust_header($cgi->param('cust_fields'));
253 $align .= FS::UI::Web::cust_aligns();
254 push @color, FS::UI::Web::cust_colors();
255 push @style, FS::UI::Web::cust_styles();
256
257 my $addl_from = ' LEFT JOIN cust_svc  USING ( svcnum  ) '.
258                 ' LEFT JOIN part_svc  USING ( svcpart ) '.
259                 ' LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
260                 ' LEFT JOIN cust_main USING ( custnum ) ';
261
262 #here is the agent virtualization
263 push @extra_sql, $FS::CurrentUser::CurrentUser->agentnums_sql( 
264                    'null_right' => 'View/link unlinked services'
265                  );
266
267 my $extra_sql = 
268   scalar(@extra_sql)
269     ? ' WHERE '. join(' AND ', @extra_sql )
270     : '';
271
272 my $count_query = "SELECT COUNT(*) FROM svc_acct $addl_from $extra_sql";
273 #if ( keys %svc_acct ) {
274 #  $count_query .= ' WHERE '.
275 #                    join(' AND ', map "$_ = ". dbh->quote($svc_acct{$_}),
276 #                                      keys %svc_acct
277 #                        );
278 #}
279
280 my $sql_query = {
281   'table' => 'svc_acct',
282   'hashref'   => {}, # \%svc_acct,
283   'select'    => join(', ',
284                     'svc_acct.*',
285                     'part_svc.svc',
286                     'cust_main.custnum',
287                     FS::UI::Web::cust_sql_fields(),
288                   ),
289   'extra_sql' => "$extra_sql $orderby",
290   'addl_from' => $addl_from,
291 };
292
293 </%init>