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