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