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