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