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