non-blocking upgrade for part_pkg, #29155
[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   # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
208   # kind of a weird spot for this, but it's better than duplicating
209   # all this code in each class...
210   my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
211   foreach my $table ( @decrypt_tables ) {
212       my @objects = qsearch({
213         'table'     => $table,
214         'hashref'   => {},
215         'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
216                        " AND LENGTH(payinfo) > 100",
217       });
218       foreach my $object ( @objects ) {
219           my $payinfo = $object->decrypt($object->payinfo);
220           die "error decrypting payinfo" if $payinfo eq $object->payinfo;
221           $object->payinfo($payinfo);
222           my $error = $object->replace;
223           die $error if $error;
224       }
225   }
226
227 }
228
229 =item upgrade_data
230
231 =cut
232
233 sub upgrade_data {
234   my %opt = @_;
235
236   tie my %hash, 'Tie::IxHash', 
237
238     #cust_main (remove paycvv from history)
239     'cust_main' => [],
240
241     #msgcat
242     'msgcat' => [],
243
244     #reason type and reasons
245     'reason_type'     => [],
246     'cust_pkg_reason' => [],
247
248     #need part_pkg before cust_credit...
249     'part_pkg' => [],
250
251     #customer credits
252     'cust_credit' => [],
253
254     #duplicate history records
255     'h_cust_svc'  => [],
256
257     #populate cust_pay.otaker
258     'cust_pay'    => [],
259
260     #populate part_pkg_taxclass for starters
261     'part_pkg_taxclass' => [],
262
263     #remove bad pending records
264     'cust_pay_pending' => [],
265
266     #replace invnum and pkgnum with billpkgnum
267     'cust_bill_pkg_detail' => [],
268
269     #usage_classes if we have none
270     'usage_class' => [],
271
272     #phone_type if we have none
273     'phone_type' => [],
274
275     #fixup access rights
276     'access_right' => [],
277
278     #change recur_flat and enable_prorate
279     'part_pkg_option' => [],
280
281     #add weights to pkg_category
282     'pkg_category' => [],
283
284     #cdrbatch fixes
285     'cdr' => [],
286
287     #otaker->usernum
288     'cust_attachment' => [],
289     #'cust_credit' => [],
290     #'cust_main' => [],
291     'cust_main_note' => [],
292     #'cust_pay' => [],
293     'cust_pay_void' => [],
294     'cust_pkg' => [],
295     #'cust_pkg_reason' => [],
296     'cust_pkg_discount' => [],
297     'cust_refund' => [],
298     'banned_pay' => [],
299
300     #default namespace
301     'payment_gateway' => [],
302
303     #migrate to templates
304     'msg_template' => [],
305
306     #return unprovisioned numbers to availability
307     'phone_avail' => [],
308
309     #insert scripcondition
310     'TicketSystem' => [],
311     
312     #insert LATA data if not already present
313     'lata' => [],
314     
315     #insert MSA data if not already present
316     'msa' => [],
317
318     # migrate to radius_group and groupnum instead of groupname
319     'radius_usergroup' => [],
320     'part_svc'         => [],
321     'part_export'      => [],
322
323     #insert default tower_sector if not present
324     'tower' => [],
325
326     #repair improperly deleted services
327     'cust_svc' => [],
328
329     #routernum/blocknum
330     'svc_broadband' => [],
331
332     #set up payment gateways if needed
333     'pay_batch' => [],
334
335     #flag monthly tax exemptions
336     'cust_tax_exempt_pkg' => [],
337
338     #kick off tax location history upgrade
339     'cust_bill_pkg' => [],
340
341     #fix taxable line item links
342     'cust_bill_pkg_tax_location' => [],
343   ;
344
345   \%hash;
346
347 }
348
349 =item upgrade_schema
350
351 =cut
352
353 sub upgrade_schema {
354   my %opt = @_;
355
356   my $data = upgrade_schema_data(%opt);
357
358   my $oldAutoCommit = $FS::UID::AutoCommit;
359   local $FS::UID::AutoCommit = 0;
360   local $FS::UID::AutoCommit = 0;
361
362   foreach my $table ( keys %$data ) {
363
364     my $class = "FS::$table";
365     eval "use $class;";
366     die $@ if $@;
367
368     if ( $class->can('_upgrade_schema') ) {
369       warn "Upgrading $table schema...\n";
370
371       my $start = time;
372
373       $class->_upgrade_schema(%opt);
374
375       if ( $oldAutoCommit ) {
376         warn "  committing\n";
377         dbh->commit or die dbh->errstr;
378       }
379       
380       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
381       warn "  done in ". (time-$start). " seconds\n";
382
383     } else {
384       warn "WARNING: asked for schema upgrade of $table,".
385            " but FS::$table has no _upgrade_schema method\n";
386     }
387
388   }
389
390 }
391
392 =item upgrade_schema_data
393
394 =cut
395
396 sub upgrade_schema_data {
397   my %opt = @_;
398
399   tie my %hash, 'Tie::IxHash', 
400
401     #fix classnum character(1)
402     'cust_bill_pkg_detail' => [],
403     #add necessary columns to RT schema
404     'TicketSystem' => [],
405
406   ;
407
408   \%hash;
409
410 }
411
412 sub upgrade_sqlradius {
413   #my %opt = @_;
414
415   my $conf = new FS::Conf;
416
417   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
418
419   foreach my $part_export ( @part_export ) {
420
421     my $errmsg = 'Error adding FreesideStatus to '.
422                  $part_export->option('datasrc'). ': ';
423
424     my $dbh = DBI->connect(
425       ( map $part_export->option($_), qw ( datasrc username password ) ),
426       { PrintError => 0, PrintWarn => 0 }
427     ) or do {
428       warn $errmsg.$DBI::errstr;
429       next;
430     };
431
432     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
433     my $group = "UserName";
434     $group .= ",Realm"
435       if ref($part_export) =~ /withdomain/
436       || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
437
438     my $sth_alter = $dbh->prepare(
439       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
440     );
441     if ( $sth_alter ) {
442       if ( $sth_alter->execute ) {
443         my $sth_update = $dbh->prepare(
444          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
445         ) or die $errmsg.$dbh->errstr;
446         $sth_update->execute or die $errmsg.$sth_update->errstr;
447       } else {
448         my $error = $sth_alter->errstr;
449         warn $errmsg.$error
450           unless $error =~ /Duplicate column name/i  #mysql
451               || $error =~ /already exists/i;        #Pg
452 ;
453       }
454     } else {
455       my $error = $dbh->errstr;
456       warn $errmsg.$error; #unless $error =~ /exists/i;
457     }
458
459     my $sth_index = $dbh->prepare(
460       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
461     );
462     if ( $sth_index ) {
463       unless ( $sth_index->execute ) {
464         my $error = $sth_index->errstr;
465         warn $errmsg.$error
466           unless $error =~ /Duplicate key name/i #mysql
467               || $error =~ /already exists/i;    #Pg
468       }
469     } else {
470       my $error = $dbh->errstr;
471       warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
472     }
473
474     my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
475       ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
476       : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
477
478     my $sth = $dbh->prepare("SELECT UserName,
479                                     Realm,
480                                     $str2time max(AcctStartTime)),
481                                     $str2time max(AcctStopTime))
482                               FROM radacct
483                               WHERE FreesideStatus = 'done'
484                                 AND $times
485                               GROUP BY $group
486                             ")
487       or die $errmsg.$dbh->errstr;
488     $sth->execute() or die $errmsg.$sth->errstr;
489   
490     while (my $row = $sth->fetchrow_arrayref ) {
491       my ($username, $realm, $start, $stop) = @$row;
492   
493       $username = lc($username) unless $conf->exists('username-uppercase');
494
495       my $exportnum = $part_export->exportnum;
496       my $extra_sql = " AND exportnum = $exportnum ".
497                       " AND exportsvcnum IS NOT NULL ";
498
499       if ( ref($part_export) =~ /withdomain/ ) {
500         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
501                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
502       }
503   
504       my $svc_acct = qsearchs({
505         'select'    => 'svc_acct.*',
506         'table'     => 'svc_acct',
507         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
508                        'LEFT JOIN export_svc USING ( svcpart )',
509         'hashref'   => { 'username' => $username },
510         'extra_sql' => $extra_sql,
511       });
512
513       if ($svc_acct) {
514         $svc_acct->last_login($start)
515           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
516         $svc_acct->last_logout($stop)
517           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
518       }
519     }
520   }
521
522 }
523
524 =back
525
526 =head1 BUGS
527
528 Sure.
529
530 =head1 SEE ALSO
531
532 =cut
533
534 1;
535