per-customer RADIUS data usage report, #42310
[freeside.git] / httemplate / search / sqlradius_usage.html
1 % if ( @include_agents ) {
2 %   # jumbo report
3 <& /elements/header.html, $title &>
4 %   foreach my $agent ( @include_agents ) {
5 % $cgi->param('agentnum', $agent->agentnum); #for download links
6 <DIV WIDTH="100%" STYLE="page-break-after: always">
7 <FONT SIZE=6><% $agent->agent %></FONT><BR><BR>
8   <& sqlradius_usage.html, 
9       export            => $export,
10       agentnum          => $agent->agentnum,
11       nohtmlheader      => 1,
12       usage_by_username => \%usage_by_username,
13       download_label    => 'Download this section',
14       &>
15 </DIV>
16 <BR><BR>
17 %  }
18 <& /elements/footer.html &>
19 % } else {
20 <& elements/search.html,
21   'title'       => $title,
22   'name'        => 'services',
23   'query'       => $sql_query,
24   'count_query' => $sql_query->{'count_query'},
25   'header'      => [ #FS::UI::Web::cust_header(),
26                      '#',
27                      'Customer',
28                      'Package',
29                      @svc_header,
30                      'Upload (GB)',
31                      'Download (GB)',
32                      'Total (GB)',
33                    ],
34   'footer'      => \@footer,
35   'fields'      => [ #\&FS::UI::Web::cust_fields,
36                      'display_custnum',
37                      'name',
38                      'pkg',
39                      @svc_fields,
40                      @svc_usage,
41                    ],
42   'links'       => [ #( map { $_ ne 'Cust. Status' ? $link_cust : '' }
43                      #  FS::UI::Web::cust_header() ),
44                      $link_cust,
45                      $link_cust,
46                      '', #package
47                      ( map { $link_svc } @svc_header ),
48                      '',
49                      '',
50                      '',
51                    ],
52   'align'       => #FS::UI::Web::cust_aligns() .
53                    'rlc' . ('l' x scalar(@svc_header)) . 'rrr' ,
54   'nohtmlheader'    => ($opt{'nohtmlheader'} || 0),
55   'download_label'  => $opt{'download_label'},
56 &>
57 % }
58 <%init>
59
60 my %opt = @_;
61
62 my $curuser = $FS::CurrentUser::CurrentUser;
63 die "access denied" unless $curuser->access_right('List services');
64
65 my $title = 'Data Usage Report - '; 
66 my $agentnum;
67 my @include_agents;
68
69 if ( $opt{'agentnum'} ) {
70   $agentnum = $opt{'agentnum'};
71 } elsif ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
72   $agentnum = $1;
73 }
74
75 if ( $agentnum ) {
76   my $agent = FS::agent->by_key($agentnum);
77   $title = $agent->agent." $title";
78 } else {
79   @include_agents = qsearch('agent', {});
80 }
81
82 # usage query params
83 my( $beginning, $ending ) = FS::UI::Web::parse_beginning_ending($cgi);
84
85 if ( $beginning ) {
86   $title .= time2str('%h %o %Y ', $beginning);
87 }
88 $title .= 'through ';
89 if ( $ending == 4294967295 ) {
90   $title .= 'now';
91 } else {
92   $title .= time2str('%h %o %Y', $ending);
93 }
94
95 # can also show a specific customer / service. the main query will handle
96 # agent restrictions, but we need a list of the services to ask the export
97 # for usage data.
98 my ($cust_main, @svc_x);
99 if ( $cgi->param('custnum') =~ /^(\d+)$/ ) {
100   $cust_main = qsearchs( {
101     'table'     => 'cust_main',
102     'hashref'   => { 'custnum' => $1 },
103     'extra_sql' => ' AND '. $curuser->agentnums_sql,
104   });
105   die "Customer not found!" unless $cust_main;
106   # then only report on this agent
107   $agentnum = $cust_main->agentnum;
108   @include_agents = ();
109   # and announce that we're doing it
110   $title .= ' - ' . $cust_main->name_short;
111
112   # yes, we'll query the database once for each service the customer has,
113   # even non-radacct'd services. probably less bad than a single query that
114   # pulls records for every service for every customer.
115   foreach my $cust_pkg ($cust_main->all_pkgs) {
116     foreach my $cust_svc ($cust_pkg->cust_svc) {
117       push @svc_x, $cust_svc->svc_x;
118     }
119   }
120 }
121 foreach ($cgi->param('svcnum')) {
122   if (/^(\d+)$/) {
123     my $cust_svc = FS::cust_svc->by_key($1)
124       or die "service #$1 not found."; # or continue?
125     push @svc_x, $cust_svc->svc_x;
126   }
127 }
128
129 my $export;
130 my %usage_by_username;
131 if ( exists($opt{usage_by_username}) ) {
132   # There's no agent separation in the radacct data.  So in the jumbo report
133   # do this procedure once, and pass the hash into all the per-agent sections.
134   %usage_by_username = %{ $opt{usage_by_username} };
135   $export  = $opt{export};
136 } else {
137
138   $cgi->param('exportnum') =~ /^(\d+)$/
139     or die "illegal export: '".$cgi->param('exportnum')."'";
140   $export = FS::part_export->by_key($1)
141     or die "exportnum $1 not found";
142   $export->exporttype =~ /sqlradius/
143     or die "exportnum ".$export->exportnum." is type ".$export->exporttype.
144            ", not sqlradius";
145
146   my %usage_param = (
147       stoptime_start  => $beginning,
148       stoptime_end    => $ending,
149       summarize       => 1
150   );
151   # usage_sessions() returns an arrayref of hashrefs of
152   # (username, acctsessiontime, acctinputoctets, acctoutputoctets)
153   # (XXX needs to include 'realm' for sqlradius_withdomain)
154   my $usage;
155   if ( @svc_x ) {
156     # then query once per service
157     $usage = [];
158     foreach my $svc ( @svc_x ) {
159       $usage_param{'svc'} = $svc;
160       push @$usage, @{ $export->usage_sessions(\%usage_param) };
161     }
162   } else {
163     # one query, get everyone's data
164     my $usage = $export->usage_sessions(\%usage_param);
165   }
166
167   # rearrange to be indexed by username.
168   foreach (@$usage) {
169     my $username = $_->{'username'};
170     my @row = (
171       $_->{'acctinputoctets'},
172       $_->{'acctoutputoctets'},
173       $_->{'acctinputoctets'} + $_->{'acctoutputoctets'}
174     );
175     $usage_by_username{$username} = \@row;
176   }
177 }
178
179 #warn Dumper(\%usage_by_username);
180 my @total_usage = (0, 0, 0, 0); # session time, input, output, input + output
181 my @svc_usage = map {
182   my $i = $_;
183   sub {
184     my $username = $export->export_username(shift);
185     return '' if !exists($usage_by_username{$username});
186     my $value = $usage_by_username{ $username }->[$i];
187     $total_usage[$i] += $value;
188     # for now, always show in GB, rounded to 3 digits
189     bytes_to_gb($value);
190   }
191 } (0,1,2);
192
193 # set up svcdb-specific stuff
194 my $export_username = sub {
195   $export->export_username(shift); # countrycode + phone, formatted MAC, etc.
196 };
197
198 my %svc_header = (
199   svc_acct      => [ 'Username' ],
200   svc_broadband => [ 'MAC address', 'IP address' ],
201 #  svc_phone     => [ 'Phone' ], #not yet supported, no search method
202                                  # (not sure input/output octets is relevant)
203 );
204 my %svc_fields = (
205   svc_acct      => [ $export_username ],
206   svc_broadband => [ $export_username, 'ip_addr' ],
207 #  svc_phone     => [ $export_username ],
208 );
209
210 # what kind of service we're operating on
211 my $svcdb = FS::part_export::export_info()->{$export->exporttype}->{'svc'};
212 my $class = "FS::$svcdb";
213 my @svc_header = @{ $svc_header{$svcdb} };
214 my @svc_fields = @{ $svc_fields{$svcdb} };
215
216 # svc_x search params
217 my %search_hash = ( 'agentnum' => $agentnum,
218                     'exportnum' => $export->exportnum );
219
220 if ($cust_main) {
221   $search_hash{'custnum'} = $cust_main->custnum;
222 }
223 if (@svc_x) {
224   $search_hash{'svcnum'} = [ map { $_->get('svcnum') } @svc_x ];
225 }
226
227 my $sql_query = $class->search(\%search_hash);
228 $sql_query->{'select'}    .= ', part_pkg.pkg';
229 $sql_query->{'addl_from'} .= ' LEFT JOIN part_pkg USING (pkgpart)';
230
231 if ( @svc_x ) {
232   my $svcnums = join(',', map { $_->get('svcnum') } @svc_x);
233   $sql_query->{'extra_sql'} .= ' AND svcnum IN('.$svcnums.')';
234 }
235
236 my $link_svc = [ $p.'view/cust_svc.cgi?', 'svcnum' ];
237
238 my $link_cust = [ $p.'view/cust_main.cgi?', 'custnum' ];
239
240 # columns between the customer name and the usage fields
241 my $skip_cols = 1 + scalar(@svc_header);
242
243 my $num_rows = FS::Record->scalar_sql($sql_query->{count_query});
244 my @footer = (
245   '',
246   emt('[quant,_1,service]', $num_rows), 
247   ('') x $skip_cols,
248   map {
249     my $i = $_;
250     sub { # defer this until the rows have been processed
251       bytes_to_gb($total_usage[$i])
252     }
253   } (0,1,2)
254 );
255
256 sub bytes_to_gb {
257   $_[0] ?  sprintf('%.3f', $_[0] / (1024*1024*1024.0)) : '';
258 }
259
260 warn Dumper \%usage_by_username;
261
262
263 </%init>