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