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