re-write RADIUS groups, RT13274
[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_schema upgrade_config 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 upgrade_config
37
38 =cut
39
40 #config upgrades
41 sub upgrade_config {
42   my %opt = @_;
43
44   my $conf = new FS::Conf;
45
46   $conf->touch('payment_receipt')
47     if $conf->exists('payment_receipt_email')
48     || $conf->config('payment_receipt_msgnum');
49
50 }
51
52 =item upgrade
53
54 =cut
55
56 sub upgrade {
57   my %opt = @_;
58
59   my $data = upgrade_data(%opt);
60
61   my $oldAutoCommit = $FS::UID::AutoCommit;
62   local $FS::UID::AutoCommit = 0;
63   local $FS::UID::AutoCommit = 0;
64
65   foreach my $table ( keys %$data ) {
66
67     my $class = "FS::$table";
68     eval "use $class;";
69     die $@ if $@;
70
71     if ( $class->can('_upgrade_data') ) {
72       warn "Upgrading $table...\n";
73
74       my $start = time;
75
76       $class->_upgrade_data(%opt);
77
78       if ( $oldAutoCommit ) {
79         warn "  committing\n";
80         dbh->commit or die dbh->errstr;
81       }
82       
83       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
84       warn "  done in ". (time-$start). " seconds\n";
85
86     } else {
87       warn "WARNING: asked for upgrade of $table,".
88            " but FS::$table has no _upgrade_data method\n";
89     }
90
91 #    my @records = @{ $data->{$table} };
92 #
93 #    foreach my $record ( @records ) {
94 #      my $args = delete($record->{'_upgrade_args'}) || [];
95 #      my $object = $class->new( $record );
96 #      my $error = $object->insert( @$args );
97 #      die "error inserting record into $table: $error\n"
98 #        if $error;
99 #    }
100
101   }
102
103 }
104
105 =item upgrade_data
106
107 =cut
108
109 sub upgrade_data {
110   my %opt = @_;
111
112   tie my %hash, 'Tie::IxHash', 
113
114     #cust_main (remove paycvv from history)
115     'cust_main' => [],
116
117     #msgcat
118     'msgcat' => [],
119
120     #reason type and reasons
121     'reason_type'     => [],
122     'cust_pkg_reason' => [],
123
124     #need part_pkg before cust_credit...
125     'part_pkg' => [],
126
127     #customer credits
128     'cust_credit' => [],
129
130     #duplicate history records
131     'h_cust_svc'  => [],
132
133     #populate cust_pay.otaker
134     'cust_pay'    => [],
135
136     #populate part_pkg_taxclass for starters
137     'part_pkg_taxclass' => [],
138
139     #remove bad pending records
140     'cust_pay_pending' => [],
141
142     #replace invnum and pkgnum with billpkgnum
143     'cust_bill_pkg_detail' => [],
144
145     #usage_classes if we have none
146     'usage_class' => [],
147
148     #phone_type if we have none
149     'phone_type' => [],
150
151     #fixup access rights
152     'access_right' => [],
153
154     #change recur_flat and enable_prorate
155     'part_pkg_option' => [],
156
157     #add weights to pkg_category
158     'pkg_category' => [],
159
160     #cdrbatch fixes
161     'cdr' => [],
162
163     #otaker->usernum
164     'cust_attachment' => [],
165     #'cust_credit' => [],
166     #'cust_main' => [],
167     'cust_main_note' => [],
168     #'cust_pay' => [],
169     'cust_pay_void' => [],
170     'cust_pkg' => [],
171     #'cust_pkg_reason' => [],
172     'cust_pkg_discount' => [],
173     'cust_refund' => [],
174     'banned_pay' => [],
175
176     #default namespace
177     'payment_gateway' => [],
178
179     #migrate to templates
180     'msg_template' => [],
181
182     #return unprovisioned numbers to availability
183     'phone_avail' => [],
184
185     #insert scripcondition
186     'TicketSystem' => [],
187     
188     #insert LATA data if not already present
189     'lata' => [],
190     
191     #insert MSA data if not already present
192     'msa' => [],
193
194     # migrate to radius_group and groupnum instead of groupname
195     'radius_usergroup' => [],
196
197   ;
198
199   \%hash;
200
201 }
202
203 =item upgrade_schema
204
205 =cut
206
207 sub upgrade_schema {
208   my %opt = @_;
209
210   my $data = upgrade_schema_data(%opt);
211
212   my $oldAutoCommit = $FS::UID::AutoCommit;
213   local $FS::UID::AutoCommit = 0;
214   local $FS::UID::AutoCommit = 0;
215
216   foreach my $table ( keys %$data ) {
217
218     my $class = "FS::$table";
219     eval "use $class;";
220     die $@ if $@;
221
222     if ( $class->can('_upgrade_schema') ) {
223       warn "Upgrading $table schema...\n";
224
225       my $start = time;
226
227       $class->_upgrade_schema(%opt);
228
229       if ( $oldAutoCommit ) {
230         warn "  committing\n";
231         dbh->commit or die dbh->errstr;
232       }
233       
234       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
235       warn "  done in ". (time-$start). " seconds\n";
236
237     } else {
238       warn "WARNING: asked for schema upgrade of $table,".
239            " but FS::$table has no _upgrade_schema method\n";
240     }
241
242   }
243
244 }
245
246 =item upgrade_schema_data
247
248 =cut
249
250 sub upgrade_schema_data {
251   my %opt = @_;
252
253   tie my %hash, 'Tie::IxHash', 
254
255     #fix classnum character(1)
256     'cust_bill_pkg_detail' => [],
257
258   ;
259
260   \%hash;
261
262 }
263
264 sub upgrade_sqlradius {
265   #my %opt = @_;
266
267   my $conf = new FS::Conf;
268
269   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
270
271   foreach my $part_export ( @part_export ) {
272
273     my $errmsg = 'Error adding FreesideStatus to '.
274                  $part_export->option('datasrc'). ': ';
275
276     my $dbh = DBI->connect(
277       ( map $part_export->option($_), qw ( datasrc username password ) ),
278       { PrintError => 0, PrintWarn => 0 }
279     ) or do {
280       warn $errmsg.$DBI::errstr;
281       next;
282     };
283
284     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
285     my $group = "UserName";
286     $group .= ",Realm"
287       if ref($part_export) =~ /withdomain/
288       || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
289
290     my $sth_alter = $dbh->prepare(
291       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
292     );
293     if ( $sth_alter ) {
294       if ( $sth_alter->execute ) {
295         my $sth_update = $dbh->prepare(
296          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
297         ) or die $errmsg.$dbh->errstr;
298         $sth_update->execute or die $errmsg.$sth_update->errstr;
299       } else {
300         my $error = $sth_alter->errstr;
301         warn $errmsg.$error
302           unless $error =~ /Duplicate column name/i  #mysql
303               || $error =~ /already exists/i;        #Pg
304 ;
305       }
306     } else {
307       my $error = $dbh->errstr;
308       warn $errmsg.$error; #unless $error =~ /exists/i;
309     }
310
311     my $sth_index = $dbh->prepare(
312       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
313     );
314     if ( $sth_index ) {
315       unless ( $sth_index->execute ) {
316         my $error = $sth_index->errstr;
317         warn $errmsg.$error
318           unless $error =~ /Duplicate key name/i #mysql
319               || $error =~ /already exists/i;    #Pg
320       }
321     } else {
322       my $error = $dbh->errstr;
323       warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
324     }
325
326     my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
327       ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
328       : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
329
330     my $sth = $dbh->prepare("SELECT UserName,
331                                     Realm,
332                                     $str2time max(AcctStartTime)),
333                                     $str2time max(AcctStopTime))
334                               FROM radacct
335                               WHERE FreesideStatus = 'done'
336                                 AND $times
337                               GROUP BY $group
338                             ")
339       or die $errmsg.$dbh->errstr;
340     $sth->execute() or die $errmsg.$sth->errstr;
341   
342     while (my $row = $sth->fetchrow_arrayref ) {
343       my ($username, $realm, $start, $stop) = @$row;
344   
345       $username = lc($username) unless $conf->exists('username-uppercase');
346
347       my $exportnum = $part_export->exportnum;
348       my $extra_sql = " AND exportnum = $exportnum ".
349                       " AND exportsvcnum IS NOT NULL ";
350
351       if ( ref($part_export) =~ /withdomain/ ) {
352         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
353                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
354       }
355   
356       my $svc_acct = qsearchs({
357         'select'    => 'svc_acct.*',
358         'table'     => 'svc_acct',
359         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
360                        'LEFT JOIN export_svc USING ( svcpart )',
361         'hashref'   => { 'username' => $username },
362         'extra_sql' => $extra_sql,
363       });
364
365       if ($svc_acct) {
366         $svc_acct->last_login($start)
367           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
368         $svc_acct->last_logout($stop)
369           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
370       }
371     }
372   }
373
374 }
375
376 =back
377
378 =head1 BUGS
379
380 Sure.
381
382 =head1 SEE ALSO
383
384 =cut
385
386 1;
387