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