RT# 82942 Replace DBI->connect() with FS::DBI->connect()
[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 use FS::DBI;
14
15 use FS::svc_domain;
16 $FS::svc_domain::whois_hack = 1;
17
18 @ISA = qw( Exporter );
19 @EXPORT_OK = qw( upgrade_schema upgrade_config upgrade upgrade_sqlradius );
20
21 $DEBUG = 1;
22
23 =head1 NAME
24
25 FS::Upgrade - Database upgrade routines
26
27 =head1 SYNOPSIS
28
29   use FS::Upgrade;
30
31 =head1 DESCRIPTION
32
33 Currently this module simply provides a place to store common subroutines for
34 database upgrades.
35
36 =head1 SUBROUTINES
37
38 =over 4
39
40 =item upgrade_config
41
42 =cut
43
44 #config upgrades
45 sub upgrade_config {
46   my %opt = @_;
47
48   my $conf = new FS::Conf;
49
50   $conf->touch('payment_receipt')
51     if $conf->exists('payment_receipt_email')
52     || $conf->config('payment_receipt_msgnum');
53
54   $conf->touch('geocode-require_nw_coordinates')
55     if $conf->exists('svc_broadband-require-nw-coordinates');
56
57   unless ( $conf->config('echeck-country') ) {
58     if ( $conf->exists('cust_main-require-bank-branch') ) {
59       $conf->set('echeck-country', 'CA');
60     } elsif ( $conf->exists('echeck-nonus') ) {
61       $conf->set('echeck-country', 'XX');
62     } else {
63       $conf->set('echeck-country', 'US');
64     }
65   }
66
67   my @agents = qsearch('agent', {});
68
69   upgrade_overlimit_groups($conf);
70   map { upgrade_overlimit_groups($conf,$_->agentnum) } @agents;
71
72   upgrade_invoice_from($conf);
73   foreach my $agent (@agents) {
74     upgrade_invoice_from($conf,$agent->agentnum,1);
75   }
76
77   my $DIST_CONF = '/usr/local/etc/freeside/default_conf/';#DIST_CONF in Makefile
78   $conf->set($_, scalar(read_file( "$DIST_CONF/$_" )) )
79     foreach grep { ! $conf->exists($_) && -s "$DIST_CONF/$_" }
80       qw( quotation_html quotation_latex quotation_latexnotes );
81
82   # change 'fslongtable' to 'longtable'
83   # in invoice and quotation main templates, and also in all secondary 
84   # invoice templates
85   my @latex_confs =
86     qsearch('conf', { 'name' => {op=>'LIKE', value=>'%latex%'} });
87
88   foreach my $c (@latex_confs) {
89     my $value = $c->value;
90     if (length($value) and $value =~ /fslongtable/) {
91       $value =~ s/fslongtable/longtable/g;
92       $conf->set($c->name, $value, $c->agentnum);
93     }
94   }
95
96   # if there's a USPS tools login, assume that's the standardization method
97   # you want to use
98   $conf->set('address_standardize_method', 'usps')
99     if $conf->exists('usps_webtools-userid')
100     && length($conf->config('usps_webtools-userid')) > 0
101     && ! $conf->exists('address_standardize_method');
102
103   # this option has been renamed/expanded
104   if ( $conf->exists('cust_main-enable_spouse_birthdate') ) {
105     $conf->touch('cust_main-enable_spouse');
106     $conf->delete('cust_main-enable_spouse_birthdate');
107   }
108
109   # renamed/repurposed
110   if ( $conf->exists('cust_pkg-show_fcc_voice_grade_equivalent') ) {
111     $conf->touch('part_pkg-show_fcc_options');
112     $conf->delete('cust_pkg-show_fcc_voice_grade_equivalent');
113     warn "
114 You have FCC Form 477 package options enabled.
115
116 Starting with the October 2014 filing date, the FCC has redesigned 
117 Form 477 and introduced new service categories.  See bin/convert-477-options
118 to update your package configuration for the new report.
119
120 If you need to continue using the old Form 477 report, turn on the
121 'old_fcc_report' configuration option.
122 ";
123   }
124
125   # boolean invoice_sections_by_location option is now
126   # invoice_sections_method = 'location'
127   my @invoice_sections_confs =
128     qsearch('conf', { 'name' => { op=>'LIKE', value=>'%sections_by_location' } });
129   foreach my $c (@invoice_sections_confs) {
130     $c->name =~ /^(\w+)sections_by_location$/;
131     $conf->delete($c->name);
132     my $newname = $1.'sections_method';
133     $conf->set($newname, 'location');
134   }
135
136   # boolean tax-cust_exempt-groups-require_individual_nums is now -num_req all
137   if ( $conf->exists('tax-cust_exempt-groups-require_individual_nums') ) {
138     $conf->set('tax-cust_exempt-groups-num_req', 'all');
139     $conf->delete('tax-cust_exempt-groups-require_individual_nums');
140   }
141
142   # boolean+text previous_balance-exclude_from_total is now two separate options
143   my $total_new_charges = $conf->config('previous_balance-exclude_from_total');
144   if (length($total_new_charges) > 0) {
145     $conf->set('previous_balance-text-total_new_charges', $total_new_charges);
146     $conf->set('previous_balance-exclude_from_total', '');
147   }
148
149   if ( $conf->exists('voip-cust_email_csv_cdr') ) {
150     $conf->set('voip_cdr_email_attach', 'csv');
151     $conf->delete('voip-cust_email_csv_cdr') ;
152   }
153
154   if ( !$conf->config('password-generated-characters') ) {
155     my $pw_set = 
156       'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789()#.,' ;
157     $conf->set('password-generated-characters', $pw_set);
158   }
159
160   if ($conf->exists('unsuspendauto') && !$conf->config('unsuspend_balance')) {
161     $conf->set('unsuspend_balance','Zero');
162     $conf->delete('unsuspendauto');
163   }
164
165   # if translate-auto-insert is enabled for a locale, ensure that invoice
166   # terms are in the msgcat (is there a better place for this?)
167   if (my $auto_locale = $conf->config('translate-auto-insert')) {
168     my $lh = FS::L10N->get_handle($auto_locale);
169     foreach (@FS::Conf::invoice_terms) {
170       $lh->maketext($_) if length($_);
171     }
172   }
173 }
174
175 sub upgrade_overlimit_groups {
176     my $conf = shift;
177     my $agentnum = shift;
178     my @groups = $conf->config('overlimit_groups',$agentnum); 
179     if(scalar(@groups)) {
180         my $groups = join(',',@groups);
181         my @groupnums;
182         my $error = '';
183         if ( $groups !~ /^[\d,]+$/ ) {
184             foreach my $groupname ( @groups ) {
185                 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
186                 unless ( $g ) {
187                     $g = new FS::radius_group {
188                                     'groupname' => $groupname,
189                                     'description' => $groupname,
190                                     };
191                     $error = $g->insert;
192                     die $error if $error;
193                 }
194                 push @groupnums, $g->groupnum;
195             }
196             $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
197         }
198     }
199 }
200
201 sub upgrade_invoice_from {
202   my ($conf, $agentnum, $agentonly) = @_;
203   if (
204       (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) && 
205       ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
206   ) {
207     my $realemail = $1;
208     $realemail =~ s/^\s*//; # remove leading spaces
209     $realemail =~ s/\s*$//; # remove trailing spaces
210     my $realname = $conf->config('invoice_from',$agentnum);
211     $realname =~ s/\<.*\>//; # remove email address
212     $realname =~ s/^\s*//; # remove leading spaces
213     $realname =~ s/\s*$//; # remove trailing spaces
214     # properly quote names that contain punctuation
215     if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
216       $realname = '"' . $realname . '"';
217     }
218     $conf->set('invoice_from_name', $realname, $agentnum);
219     $conf->set('invoice_from', $realemail, $agentnum);
220   }
221 }
222
223 =item upgrade
224
225 =cut
226
227 sub upgrade {
228   my %opt = @_;
229
230   my $data = upgrade_data(%opt);
231
232   my $oldAutoCommit = $FS::UID::AutoCommit;
233   local $FS::UID::AutoCommit = 0;
234   local $FS::UID::AutoCommit = 0;
235
236   local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
237
238
239   foreach my $table ( keys %$data ) {
240
241     my $class = "FS::$table";
242     eval "use $class;";
243     die $@ if $@;
244
245     if ( $class->can('_upgrade_data') ) {
246       warn "Upgrading $table...\n";
247
248       my $start = time;
249
250       $class->_upgrade_data(%opt);
251
252       # New interface for async upgrades: a class can declare a 
253       # "queueable_upgrade" method, which will run as part of the normal 
254       # upgrade, but if the -j option is passed, will instead be run from 
255       # the job queue.
256       if ( $class->can('queueable_upgrade') ) {
257         my $jobname = $class . '::queueable_upgrade';
258         my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
259         if ($num_jobs > 0) {
260           warn "$class upgrade already scheduled.\n";
261         } else {
262           if ( $opt{'queue'} ) {
263             warn "Scheduling $class upgrade.\n";
264             my $job = FS::queue->new({ job => $jobname });
265             $job->insert($class, %opt);
266           } else {
267             $class->queueable_upgrade(%opt);
268           }
269         } #$num_jobs == 0
270       }
271
272       if ( $oldAutoCommit ) {
273         warn "  committing\n";
274         dbh->commit or die dbh->errstr;
275       }
276       
277       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
278       warn "  done in ". (time-$start). " seconds\n";
279
280     } else {
281       warn "WARNING: asked for upgrade of $table,".
282            " but FS::$table has no _upgrade_data method\n";
283     }
284
285 #    my @records = @{ $data->{$table} };
286 #
287 #    foreach my $record ( @records ) {
288 #      my $args = delete($record->{'_upgrade_args'}) || [];
289 #      my $object = $class->new( $record );
290 #      my $error = $object->insert( @$args );
291 #      die "error inserting record into $table: $error\n"
292 #        if $error;
293 #    }
294
295   }
296
297   local($FS::cust_main::ignore_expired_card) = 1;
298   local($FS::cust_main::ignore_illegal_zip) = 1;
299   local($FS::cust_main::ignore_banned_card) = 1;
300   local($FS::cust_main::skip_fuzzyfiles) = 1;
301
302   # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
303   # kind of a weird spot for this, but it's better than duplicating
304   # all this code in each class...
305   my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
306   foreach my $table ( @decrypt_tables ) {
307       my @objects = qsearch({
308         'table'     => $table,
309         'hashref'   => {},
310         'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
311                        " AND LENGTH(payinfo) > 100",
312       });
313       foreach my $object ( @objects ) {
314           my $payinfo = $object->decrypt($object->payinfo);
315           if ( $payinfo eq $object->payinfo ) {
316             warn "error decrypting payinfo for $table: $payinfo\n";
317             next;
318           }
319           $object->payinfo($payinfo);
320           my $error = $object->replace;
321           die $error if $error;
322       }
323   }
324
325 }
326
327 =item upgrade_data
328
329 =cut
330
331 sub upgrade_data {
332   my %opt = @_;
333
334   tie my %hash, 'Tie::IxHash', 
335
336     #remap log levels
337     'log' => [],
338
339     #fix whitespace - before cust_main
340     'cust_location' => [],
341
342     #remove bad source_paynum before cust_main
343     'cust_refund' => [],
344
345     #cust_main (tokenizes cards, remove paycvv from history, locations, cust_payby, etc)
346     # (handles payinfo encryption/tokenization across all relevant tables)
347     'cust_main' => [],
348
349     #msgcat
350     'msgcat' => [],
351
352     #reason type and reasons
353     'reason_type'     => [],
354     'cust_pkg_reason' => [],
355
356     #need part_pkg before cust_credit...
357     'part_pkg' => [],
358
359     #customer credits
360     'cust_credit' => [],
361
362     # fix some tax allocation records
363     'cust_bill_pkg_void' => [],
364
365     #duplicate history records
366     'h_cust_svc'  => [],
367
368     #populate cust_pay.otaker
369     'cust_pay'    => [],
370
371     #populate part_pkg_taxclass for starters
372     'part_pkg_taxclass' => [],
373
374     #remove bad pending records
375     'cust_pay_pending' => [],
376
377     #replace invnum and pkgnum with billpkgnum
378     'cust_bill_pkg_detail' => [],
379
380     #usage_classes if we have none
381     'usage_class' => [],
382
383     #phone_type if we have none
384     'phone_type' => [],
385
386     #fixup access rights
387     'access_right' => [],
388
389     #change recur_flat and enable_prorate
390     'part_pkg_option' => [],
391
392     #add weights to pkg_category
393     'pkg_category' => [],
394
395     #cdrbatch fixes
396     'cdr' => [],
397
398     #otaker->usernum
399     'cust_attachment' => [],
400     #'cust_credit' => [],
401     #'cust_main' => [],
402     'cust_main_note' => [],
403     #'cust_pay' => [],
404     'cust_pay_void' => [],
405     'cust_pkg' => [],
406     #'cust_pkg_reason' => [],
407     'cust_pkg_discount' => [],
408     #'cust_refund' => [],
409     'banned_pay' => [],
410
411     #default namespace
412     'payment_gateway' => [],
413
414     #migrate to templates
415     'msg_template' => [],
416
417     #return unprovisioned numbers to availability
418     'phone_avail' => [],
419
420     #insert scripcondition
421     'TicketSystem' => [],
422     
423     #insert LATA data if not already present
424     'lata' => [],
425     
426     #insert MSA data if not already present
427     'msa' => [],
428
429     # migrate to radius_group and groupnum instead of groupname
430     'radius_usergroup' => [],
431     'part_svc'         => [],
432     'part_export'      => [],
433
434     #insert default tower_sector if not present
435     'tower' => [],
436
437     #repair improperly deleted services
438     'cust_svc' => [],
439
440     #routernum/blocknum
441     'svc_broadband' => [],
442
443     #set up payment gateways if needed
444     'pay_batch' => [],
445
446     #flag monthly tax exemptions
447     'cust_tax_exempt_pkg' => [],
448
449     #kick off tax location history upgrade
450     'cust_bill_pkg' => [],
451
452     #fix taxable line item links
453     'cust_bill_pkg_tax_location' => [],
454
455     #populate state FIPS codes if not already done
456     'state' => [],
457
458     #set default locations on quoted packages
459     'quotation_pkg' => [],
460
461     #mark certain taxes as system-maintained,
462     # and fix whitespace
463     'cust_main_county' => [],
464
465     #upgrade part_event_condition_option agentnum to a multiple hash value
466     'part_event_condition_option' =>[],
467
468   ;
469
470   \%hash;
471
472 }
473
474 =item upgrade_schema
475
476 =cut
477
478 sub upgrade_schema {
479   my %opt = @_;
480
481   my $data = upgrade_schema_data(%opt);
482
483   my $oldAutoCommit = $FS::UID::AutoCommit;
484   local $FS::UID::AutoCommit = 0;
485   local $FS::UID::AutoCommit = 0;
486
487   foreach my $table ( keys %$data ) {
488
489     my $class = "FS::$table";
490     eval "use $class;";
491     die $@ if $@;
492
493     if ( $class->can('_upgrade_schema') ) {
494       warn "Upgrading $table schema...\n";
495
496       my $start = time;
497
498       $class->_upgrade_schema(%opt);
499
500       if ( $oldAutoCommit ) {
501         warn "  committing\n";
502         dbh->commit or die dbh->errstr;
503       }
504       
505       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
506       warn "  done in ". (time-$start). " seconds\n";
507
508     } else {
509       warn "WARNING: asked for schema upgrade of $table,".
510            " but FS::$table has no _upgrade_schema method\n";
511     }
512
513   }
514
515 }
516
517 =item upgrade_schema_data
518
519 =cut
520
521 sub upgrade_schema_data {
522   my %opt = @_;
523
524   tie my %hash, 'Tie::IxHash', 
525
526     #fix classnum character(1)
527     'cust_bill_pkg_detail' => [],
528     #add necessary columns to RT schema
529     'TicketSystem' => [],
530     #remove possible dangling records
531     'password_history' => [],
532     'cust_pay_pending' => [],
533   ;
534
535   \%hash;
536
537 }
538
539 sub upgrade_sqlradius {
540   #my %opt = @_;
541
542   my $conf = new FS::Conf;
543
544   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
545
546   foreach my $part_export ( @part_export ) {
547
548     my $errmsg = 'Error adding FreesideStatus to '.
549                  $part_export->option('datasrc'). ': ';
550
551     my $dbh = FS::DBI->connect(
552       ( map $part_export->option($_), qw ( datasrc username password ) ),
553       { PrintError => 0, PrintWarn => 0 }
554     ) or do {
555       warn $errmsg.$FS::DBI::errstr;
556       next;
557     };
558
559     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
560     my $group = "UserName";
561     $group .= ",Realm"
562       if ref($part_export) =~ /withdomain/
563       || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
564
565     my $sth_alter = $dbh->prepare(
566       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
567     );
568     if ( $sth_alter ) {
569       if ( $sth_alter->execute ) {
570         my $sth_update = $dbh->prepare(
571          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
572         ) or die $errmsg.$dbh->errstr;
573         $sth_update->execute or die $errmsg.$sth_update->errstr;
574       } else {
575         my $error = $sth_alter->errstr;
576         warn $errmsg.$error
577           unless $error =~ /Duplicate column name/i  #mysql
578               || $error =~ /already exists/i;        #Pg
579 ;
580       }
581     } else {
582       my $error = $dbh->errstr;
583       warn $errmsg.$error; #unless $error =~ /exists/i;
584     }
585
586     my $sth_index = $dbh->prepare(
587       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
588     );
589     if ( $sth_index ) {
590       unless ( $sth_index->execute ) {
591         my $error = $sth_index->errstr;
592         warn $errmsg.$error
593           unless $error =~ /Duplicate key name/i #mysql
594               || $error =~ /already exists/i;    #Pg
595       }
596     } else {
597       my $error = $dbh->errstr;
598       warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
599     }
600
601     my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
602       ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
603       : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
604
605     my $sth = $dbh->prepare("SELECT UserName,
606                                     Realm,
607                                     $str2time max(AcctStartTime)),
608                                     $str2time max(AcctStopTime))
609                               FROM radacct
610                               WHERE FreesideStatus = 'done'
611                                 AND $times
612                               GROUP BY $group
613                             ")
614       or die $errmsg.$dbh->errstr;
615     $sth->execute() or die $errmsg.$sth->errstr;
616   
617     while (my $row = $sth->fetchrow_arrayref ) {
618       my ($username, $realm, $start, $stop) = @$row;
619   
620       $username = lc($username) unless $conf->exists('username-uppercase');
621
622       my $exportnum = $part_export->exportnum;
623       my $extra_sql = " AND exportnum = $exportnum ".
624                       " AND exportsvcnum IS NOT NULL ";
625
626       if ( ref($part_export) =~ /withdomain/ ) {
627         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
628                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
629       }
630   
631       my $svc_acct = qsearchs({
632         'select'    => 'svc_acct.*',
633         'table'     => 'svc_acct',
634         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
635                        'LEFT JOIN export_svc USING ( svcpart )',
636         'hashref'   => { 'username' => $username },
637         'extra_sql' => $extra_sql,
638       });
639
640       if ($svc_acct) {
641         $svc_acct->last_login($start)
642           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
643         $svc_acct->last_logout($stop)
644           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
645       }
646     }
647   }
648
649 }
650
651 =back
652
653 =head1 BUGS
654
655 Sure.
656
657 =head1 SEE ALSO
658
659 =cut
660
661 1;
662