fix unnecessary warnings on upgrade of remote Pg RADIUS db, RT#9178
[freeside.git] / FS / FS / Upgrade.pm
1 package FS::Upgrade;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $DEBUG );
5 use Exporter;
6 use Tie::IxHash;
7 use FS::UID qw( dbh driver_name );
8 use FS::Conf;
9 use FS::Record qw(qsearchs str2time_sql);
10
11 use FS::svc_domain;
12 $FS::svc_domain::whois_hack = 1;
13
14 @ISA = qw( Exporter );
15 @EXPORT_OK = qw( upgrade upgrade_sqlradius );
16
17 $DEBUG = 1;
18
19 =head1 NAME
20
21 FS::Upgrade - Database upgrade routines
22
23 =head1 SYNOPSIS
24
25   use FS::Upgrade;
26
27 =head1 DESCRIPTION
28
29 Currently this module simply provides a place to store common subroutines for
30 database upgrades.
31
32 =head1 SUBROUTINES
33
34 =over 4
35
36 =item
37
38 =cut
39
40 sub upgrade {
41   my %opt = @_;
42
43   my $data = upgrade_data(%opt);
44
45   my $oldAutoCommit = $FS::UID::AutoCommit;
46   local $FS::UID::AutoCommit = 0;
47   local $FS::UID::AutoCommit = 0;
48
49   foreach my $table ( keys %$data ) {
50
51     my $class = "FS::$table";
52     eval "use $class;";
53     die $@ if $@;
54
55     if ( $class->can('_upgrade_data') ) {
56       warn "Upgrading $table...\n";
57
58       my $start = time;
59
60       $class->_upgrade_data(%opt);
61
62       if ( $oldAutoCommit ) {
63         warn "  committing\n";
64         dbh->commit or die dbh->errstr;
65       }
66       
67       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
68       warn "  done in ". (time-$start). " seconds\n";
69
70     } else {
71       warn "WARNING: asked for upgrade of $table,".
72            " but FS::$table has no _upgrade_data method\n";
73     }
74
75 #    my @records = @{ $data->{$table} };
76 #
77 #    foreach my $record ( @records ) {
78 #      my $args = delete($record->{'_upgrade_args'}) || [];
79 #      my $object = $class->new( $record );
80 #      my $error = $object->insert( @$args );
81 #      die "error inserting record into $table: $error\n"
82 #        if $error;
83 #    }
84
85   }
86
87 }
88
89
90 sub upgrade_data {
91   my %opt = @_;
92
93   tie my %hash, 'Tie::IxHash', 
94
95     #cust_main (remove paycvv from history)
96     'cust_main' => [],
97
98     #msgcat
99     'msgcat' => [],
100
101     #reason type and reasons
102     'reason_type'     => [],
103     'cust_pkg_reason' => [],
104
105     #need part_pkg before cust_credit...
106     'part_pkg' => [],
107
108     #customer credits
109     'cust_credit' => [],
110
111     #duplicate history records
112     'h_cust_svc'  => [],
113
114     #populate cust_pay.otaker
115     'cust_pay'    => [],
116
117     #populate part_pkg_taxclass for starters
118     'part_pkg_taxclass' => [],
119
120     #remove bad pending records
121     'cust_pay_pending' => [],
122
123     #replace invnum and pkgnum with billpkgnum
124     'cust_bill_pkg_detail' => [],
125
126     #usage_classes if we have none
127     'usage_class' => [],
128
129     #phone_type if we have none
130     'phone_type' => [],
131
132     #fixup access rights
133     'access_right' => [],
134
135     #change recur_flat and enable_prorate
136     'part_pkg_option' => [],
137
138     #add weights to pkg_category
139     'pkg_category' => [],
140
141     #cdrbatch fixes
142     'cdr' => [],
143
144     #otaker->usernum
145     'cust_attachment' => [],
146     #'cust_credit' => [],
147     #'cust_main' => [],
148     'cust_main_note' => [],
149     #'cust_pay' => [],
150     'cust_pay_void' => [],
151     'cust_pkg' => [],
152     #'cust_pkg_reason' => [],
153     'cust_pkg_discount' => [],
154     'cust_refund' => [],
155     'banned_pay' => [],
156
157     #default namespace
158     'payment_gateway' => [],
159
160   ;
161
162   \%hash;
163
164 }
165
166 sub upgrade_sqlradius {
167   #my %opt = @_;
168
169   my $conf = new FS::Conf;
170
171   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
172
173   foreach my $part_export ( @part_export ) {
174
175     my $errmsg = 'Error adding FreesideStatus to '.
176                  $part_export->option('datasrc'). ': ';
177
178     my $dbh = DBI->connect(
179       ( map $part_export->option($_), qw ( datasrc username password ) ),
180       { PrintError => 0, PrintWarn => 0 }
181     ) or do {
182       warn $errmsg.$DBI::errstr;
183       next;
184     };
185
186     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
187     my $group = "UserName";
188     $group .= ",Realm"
189       if ( ref($part_export) =~ /withdomain/ );
190
191     my $sth_alter = $dbh->prepare(
192       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
193     );
194     if ( $sth_alter ) {
195       if ( $sth_alter->execute ) {
196         my $sth_update = $dbh->prepare(
197          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
198         ) or die $errmsg.$dbh->errstr;
199         $sth_update->execute or die $errmsg.$sth_update->errstr;
200       } else {
201         my $error = $sth_alter->errstr;
202         warn $errmsg.$error unless $error =~ /Duplicate column name/i;
203       }
204     } else {
205       my $error = $dbh->errstr;
206       warn $errmsg.$error; #unless $error =~ /exists/i;
207     }
208
209     my $sth_index = $dbh->prepare(
210       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
211     );
212     if ( $sth_index ) {
213       unless ( $sth_index->execute ) {
214         my $error = $sth_index->errstr;
215         warn $errmsg.$error
216           unless $error =~ /Duplicate key name/i                        #mysql
217               || $error =~ /relation "freesidestatus" already exists/i; #Pg
218       }
219     } else {
220       my $error = $dbh->errstr;
221       warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
222     }
223
224     my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
225       ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
226       : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
227
228     my $sth = $dbh->prepare("SELECT UserName,
229                                     Realm,
230                                     $str2time max(AcctStartTime)),
231                                     $str2time max(AcctStopTime))
232                               FROM radacct
233                               WHERE FreesideStatus = 'done'
234                                 AND $times
235                               GROUP BY $group
236                             ")
237       or die $errmsg.$dbh->errstr;
238     $sth->execute() or die $errmsg.$sth->errstr;
239   
240     while (my $row = $sth->fetchrow_arrayref ) {
241       my ($username, $realm, $start, $stop) = @$row;
242   
243       $username = lc($username) unless $conf->exists('username-uppercase');
244
245       my $exportnum = $part_export->exportnum;
246       my $extra_sql = " AND exportnum = $exportnum ".
247                       " AND exportsvcnum IS NOT NULL ";
248
249       if ( ref($part_export) =~ /withdomain/ ) {
250         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
251                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
252       }
253   
254       my $svc_acct = qsearchs({
255         'select'    => 'svc_acct.*',
256         'table'     => 'svc_acct',
257         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
258                        'LEFT JOIN export_svc USING ( svcpart )',
259         'hashref'   => { 'username' => $username },
260         'extra_sql' => $extra_sql,
261       });
262
263       if ($svc_acct) {
264         $svc_acct->last_login($start)
265           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
266         $svc_acct->last_logout($stop)
267           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
268       }
269     }
270   }
271
272 }
273
274 =back
275
276 =head1 BUGS
277
278 Sure.
279
280 =head1 SEE ALSO
281
282 =cut
283
284 1;
285