+sub upgrade_sqlradius {
+ #my %opt = @_;
+
+ my $conf = new FS::Conf;
+
+ my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
+
+ foreach my $part_export ( @part_export ) {
+
+ my $errmsg = 'Error adding FreesideStatus to '.
+ $part_export->option('datasrc'). ': ';
+
+ my $dbh = DBI->connect(
+ ( map $part_export->option($_), qw ( datasrc username password ) ),
+ { PrintError => 0, PrintWarn => 0 }
+ ) or do {
+ warn $errmsg.$DBI::errstr;
+ next;
+ };
+
+ my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
+ my $group = "UserName";
+ $group .= ",Realm"
+ if ( ref($part_export) =~ /withdomain/ );
+
+ my $sth_alter = $dbh->prepare(
+ "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
+ );
+ if ( $sth_alter ) {
+ if ( $sth_alter->execute ) {
+ my $sth_update = $dbh->prepare(
+ "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
+ ) or die $errmsg.$dbh->errstr;
+ $sth_update->execute or die $errmsg.$sth_update->errstr;
+ } else {
+ my $error = $sth_alter->errstr;
+ warn $errmsg.$error unless $error =~ /Duplicate column name/i;
+ }
+ } else {
+ my $error = $dbh->errstr;
+ warn $errmsg.$error; #unless $error =~ /exists/i;
+ }
+
+ my $sth_index = $dbh->prepare(
+ "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
+ );
+ if ( $sth_index ) {
+ unless ( $sth_index->execute ) {
+ my $error = $sth_index->errstr;
+ warn $errmsg.$error unless $error =~ /Duplicate key name/i;
+ }
+ } else {
+ my $error = $dbh->errstr;
+ warn $errmsg.$error; #unless $error =~ /exists/i;
+ }
+
+ my $sth = $dbh->prepare("SELECT UserName,
+ Realm,
+ $str2time max(AcctStartTime)),
+ $str2time max(AcctStopTime))
+ FROM radacct
+ WHERE FreesideStatus = 'done'
+ AND AcctStartTime != 0
+ AND AcctStopTime != 0
+ GROUP BY $group
+ ")
+ or die $errmsg.$dbh->errstr;
+ $sth->execute() or die $errmsg.$sth->errstr;
+
+ while (my $row = $sth->fetchrow_arrayref ) {
+ my ($username, $realm, $start, $stop) = @$row;
+
+ $username = lc($username) unless $conf->exists('username-uppercase');
+
+ my $exportnum = $part_export->exportnum;
+ my $extra_sql = " AND exportnum = $exportnum ".
+ " AND exportsvcnum IS NOT NULL ";
+
+ if ( ref($part_export) =~ /withdomain/ ) {
+ $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
+ WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
+ }
+
+ my $svc_acct = qsearchs({
+ 'select' => 'svc_acct.*',
+ 'table' => 'svc_acct',
+ 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
+ 'LEFT JOIN export_svc USING ( svcpart )',
+ 'hashref' => { 'username' => $username },
+ 'extra_sql' => $extra_sql,
+ });
+
+ if ($svc_acct) {
+ $svc_acct->last_login($start)
+ if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
+ $svc_acct->last_logout($stop)
+ if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
+ }
+ }
+ }
+
+}