4 use vars qw( @ISA @EXPORT_OK $DEBUG );
8 use FS::UID qw( dbh driver_name );
10 use FS::Record qw(qsearchs qsearch str2time_sql);
12 use FS::upgrade_journal;
15 $FS::svc_domain::whois_hack = 1;
17 @ISA = qw( Exporter );
18 @EXPORT_OK = qw( upgrade_schema upgrade_config upgrade upgrade_sqlradius );
24 FS::Upgrade - Database upgrade routines
32 Currently this module simply provides a place to store common subroutines for
47 my $conf = new FS::Conf;
49 $conf->touch('payment_receipt')
50 if $conf->exists('payment_receipt_email')
51 || $conf->config('payment_receipt_msgnum');
53 $conf->touch('geocode-require_nw_coordinates')
54 if $conf->exists('svc_broadband-require-nw-coordinates');
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');
62 $conf->set('echeck-country', 'US');
66 my @agents = qsearch('agent', {});
68 upgrade_overlimit_groups($conf);
69 map { upgrade_overlimit_groups($conf,$_->agentnum) } @agents;
71 upgrade_invoice_from($conf);
72 foreach my $agent (@agents) {
73 upgrade_invoice_from($conf,$agent->agentnum,1);
76 my $DIST_CONF = '/usr/local/etc/freeside/default_conf/';#DIST_CONF in Makefile
77 $conf->set($_, scalar(read_file( "$DIST_CONF/$_" )) )
78 foreach grep { ! $conf->exists($_) && -s "$DIST_CONF/$_" }
79 qw( quotation_html quotation_latex quotation_latexnotes );
81 # change 'fslongtable' to 'longtable'
82 # in invoice and quotation main templates, and also in all secondary
85 qsearch('conf', { 'name' => {op=>'LIKE', value=>'%latex%'} });
87 foreach my $c (@latex_confs) {
88 my $value = $c->value;
89 if (length($value) and $value =~ /fslongtable/) {
90 $value =~ s/fslongtable/longtable/g;
91 $conf->set($c->name, $value, $c->agentnum);
95 # if there's a USPS tools login, assume that's the standardization method
97 $conf->set('address_standardize_method', 'usps')
98 if $conf->exists('usps_webtools-userid')
99 && length($conf->config('usps_webtools-userid')) > 0
100 && ! $conf->exists('address_standardize_method');
102 # this option has been renamed/expanded
103 if ( $conf->exists('cust_main-enable_spouse_birthdate') ) {
104 $conf->touch('cust_main-enable_spouse');
105 $conf->delete('cust_main-enable_spouse_birthdate');
109 if ( $conf->exists('cust_pkg-show_fcc_voice_grade_equivalent') ) {
110 $conf->touch('part_pkg-show_fcc_options');
111 $conf->delete('cust_pkg-show_fcc_voice_grade_equivalent');
113 You have FCC Form 477 package options enabled.
115 Starting with the October 2014 filing date, the FCC has redesigned
116 Form 477 and introduced new service categories. See bin/convert-477-options
117 to update your package configuration for the new report.
119 If you need to continue using the old Form 477 report, turn on the
120 'old_fcc_report' configuration option.
124 # boolean invoice_sections_by_location option is now
125 # invoice_sections_method = 'location'
126 my @invoice_sections_confs =
127 qsearch('conf', { 'name' => { op=>'LIKE', value=>'%sections_by_location' } });
128 foreach my $c (@invoice_sections_confs) {
129 $c->name =~ /^(\w+)sections_by_location$/;
130 $conf->delete($c->name);
131 my $newname = $1.'sections_method';
132 $conf->set($newname, 'location');
135 # boolean tax-cust_exempt-groups-require_individual_nums is now -num_req all
136 if ( $conf->exists('tax-cust_exempt-groups-require_individual_nums') ) {
137 $conf->set('tax-cust_exempt-groups-num_req', 'all');
138 $conf->delete('tax-cust_exempt-groups-require_individual_nums');
143 sub upgrade_overlimit_groups {
145 my $agentnum = shift;
146 my @groups = $conf->config('overlimit_groups',$agentnum);
147 if(scalar(@groups)) {
148 my $groups = join(',',@groups);
151 if ( $groups !~ /^[\d,]+$/ ) {
152 foreach my $groupname ( @groups ) {
153 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
155 $g = new FS::radius_group {
156 'groupname' => $groupname,
157 'description' => $groupname,
160 die $error if $error;
162 push @groupnums, $g->groupnum;
164 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
169 sub upgrade_invoice_from {
170 my ($conf, $agentnum, $agentonly) = @_;
172 (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) &&
173 ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
176 $realemail =~ s/^\s*//; # remove leading spaces
177 $realemail =~ s/\s*$//; # remove trailing spaces
178 my $realname = $conf->config('invoice_from',$agentnum);
179 $realname =~ s/\<.*\>//; # remove email address
180 $realname =~ s/^\s*//; # remove leading spaces
181 $realname =~ s/\s*$//; # remove trailing spaces
182 # properly quote names that contain punctuation
183 if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
184 $realname = '"' . $realname . '"';
186 $conf->set('invoice_from_name', $realname, $agentnum);
187 $conf->set('invoice_from', $realemail, $agentnum);
198 my $data = upgrade_data(%opt);
200 my $oldAutoCommit = $FS::UID::AutoCommit;
201 local $FS::UID::AutoCommit = 0;
202 local $FS::UID::AutoCommit = 0;
204 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
207 foreach my $table ( keys %$data ) {
209 my $class = "FS::$table";
213 if ( $class->can('_upgrade_data') ) {
214 warn "Upgrading $table...\n";
218 $class->_upgrade_data(%opt);
220 # New interface for async upgrades: a class can declare a
221 # "queueable_upgrade" method, which will run as part of the normal
222 # upgrade, but if the -j option is passed, will instead be run from
224 if ( $class->can('queueable_upgrade') ) {
225 my $jobname = $class . '::queueable_upgrade';
226 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
228 warn "$class upgrade already scheduled.\n";
230 if ( $opt{'queue'} ) {
231 warn "Scheduling $class upgrade.\n";
232 my $job = FS::queue->new({ job => $jobname });
233 $job->insert($class, %opt);
235 $class->queueable_upgrade(%opt);
240 if ( $oldAutoCommit ) {
241 warn " committing\n";
242 dbh->commit or die dbh->errstr;
245 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
246 warn " done in ". (time-$start). " seconds\n";
249 warn "WARNING: asked for upgrade of $table,".
250 " but FS::$table has no _upgrade_data method\n";
253 # my @records = @{ $data->{$table} };
255 # foreach my $record ( @records ) {
256 # my $args = delete($record->{'_upgrade_args'}) || [];
257 # my $object = $class->new( $record );
258 # my $error = $object->insert( @$args );
259 # die "error inserting record into $table: $error\n"
265 local($FS::cust_main::ignore_expired_card) = 1;
266 local($FS::cust_main::ignore_illegal_zip) = 1;
267 local($FS::cust_main::ignore_banned_card) = 1;
268 local($FS::cust_main::skip_fuzzyfiles) = 1;
270 # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
271 # kind of a weird spot for this, but it's better than duplicating
272 # all this code in each class...
273 my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
274 foreach my $table ( @decrypt_tables ) {
275 my @objects = qsearch({
278 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
279 " AND LENGTH(payinfo) > 100",
281 foreach my $object ( @objects ) {
282 my $payinfo = $object->decrypt($object->payinfo);
283 die "error decrypting payinfo" if $payinfo eq $object->payinfo;
284 $object->payinfo($payinfo);
285 my $error = $object->replace;
286 die $error if $error;
299 tie my %hash, 'Tie::IxHash',
301 #cust_main (remove paycvv from history)
307 #reason type and reasons
309 'cust_pkg_reason' => [],
311 #need part_pkg before cust_credit...
317 #duplicate history records
320 #populate cust_pay.otaker
323 #populate part_pkg_taxclass for starters
324 'part_pkg_taxclass' => [],
326 #remove bad pending records
327 'cust_pay_pending' => [],
329 #replace invnum and pkgnum with billpkgnum
330 'cust_bill_pkg_detail' => [],
332 #usage_classes if we have none
335 #phone_type if we have none
339 'access_right' => [],
341 #change recur_flat and enable_prorate
342 'part_pkg_option' => [],
344 #add weights to pkg_category
345 'pkg_category' => [],
351 'cust_attachment' => [],
352 #'cust_credit' => [],
354 'cust_main_note' => [],
356 'cust_pay_void' => [],
358 #'cust_pkg_reason' => [],
359 'cust_pkg_discount' => [],
364 'payment_gateway' => [],
366 #migrate to templates
367 'msg_template' => [],
369 #return unprovisioned numbers to availability
372 #insert scripcondition
373 'TicketSystem' => [],
375 #insert LATA data if not already present
378 #insert MSA data if not already present
381 # migrate to radius_group and groupnum instead of groupname
382 'radius_usergroup' => [],
386 #insert default tower_sector if not present
389 #repair improperly deleted services
393 'svc_broadband' => [],
395 #set up payment gateways if needed
398 #flag monthly tax exemptions
399 'cust_tax_exempt_pkg' => [],
401 #kick off tax location history upgrade
402 'cust_bill_pkg' => [],
404 #fix taxable line item links
405 'cust_bill_pkg_tax_location' => [],
407 #populate state FIPS codes if not already done
410 #set default locations on quoted packages
411 'quotation_pkg' => [],
425 my $data = upgrade_schema_data(%opt);
427 my $oldAutoCommit = $FS::UID::AutoCommit;
428 local $FS::UID::AutoCommit = 0;
429 local $FS::UID::AutoCommit = 0;
431 foreach my $table ( keys %$data ) {
433 my $class = "FS::$table";
437 if ( $class->can('_upgrade_schema') ) {
438 warn "Upgrading $table schema...\n";
442 $class->_upgrade_schema(%opt);
444 if ( $oldAutoCommit ) {
445 warn " committing\n";
446 dbh->commit or die dbh->errstr;
449 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
450 warn " done in ". (time-$start). " seconds\n";
453 warn "WARNING: asked for schema upgrade of $table,".
454 " but FS::$table has no _upgrade_schema method\n";
461 =item upgrade_schema_data
465 sub upgrade_schema_data {
468 tie my %hash, 'Tie::IxHash',
470 #fix classnum character(1)
471 'cust_bill_pkg_detail' => [],
472 #add necessary columns to RT schema
473 'TicketSystem' => [],
481 sub upgrade_sqlradius {
484 my $conf = new FS::Conf;
486 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
488 foreach my $part_export ( @part_export ) {
490 my $errmsg = 'Error adding FreesideStatus to '.
491 $part_export->option('datasrc'). ': ';
493 my $dbh = DBI->connect(
494 ( map $part_export->option($_), qw ( datasrc username password ) ),
495 { PrintError => 0, PrintWarn => 0 }
497 warn $errmsg.$DBI::errstr;
501 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
502 my $group = "UserName";
504 if ref($part_export) =~ /withdomain/
505 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
507 my $sth_alter = $dbh->prepare(
508 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
511 if ( $sth_alter->execute ) {
512 my $sth_update = $dbh->prepare(
513 "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
514 ) or die $errmsg.$dbh->errstr;
515 $sth_update->execute or die $errmsg.$sth_update->errstr;
517 my $error = $sth_alter->errstr;
519 unless $error =~ /Duplicate column name/i #mysql
520 || $error =~ /already exists/i; #Pg
524 my $error = $dbh->errstr;
525 warn $errmsg.$error; #unless $error =~ /exists/i;
528 my $sth_index = $dbh->prepare(
529 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
532 unless ( $sth_index->execute ) {
533 my $error = $sth_index->errstr;
535 unless $error =~ /Duplicate key name/i #mysql
536 || $error =~ /already exists/i; #Pg
539 my $error = $dbh->errstr;
540 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
543 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
544 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
545 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
547 my $sth = $dbh->prepare("SELECT UserName,
549 $str2time max(AcctStartTime)),
550 $str2time max(AcctStopTime))
552 WHERE FreesideStatus = 'done'
556 or die $errmsg.$dbh->errstr;
557 $sth->execute() or die $errmsg.$sth->errstr;
559 while (my $row = $sth->fetchrow_arrayref ) {
560 my ($username, $realm, $start, $stop) = @$row;
562 $username = lc($username) unless $conf->exists('username-uppercase');
564 my $exportnum = $part_export->exportnum;
565 my $extra_sql = " AND exportnum = $exportnum ".
566 " AND exportsvcnum IS NOT NULL ";
568 if ( ref($part_export) =~ /withdomain/ ) {
569 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
570 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
573 my $svc_acct = qsearchs({
574 'select' => 'svc_acct.*',
575 'table' => 'svc_acct',
576 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
577 'LEFT JOIN export_svc USING ( svcpart )',
578 'hashref' => { 'username' => $username },
579 'extra_sql' => $extra_sql,
583 $svc_acct->last_login($start)
584 if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
585 $svc_acct->last_logout($stop)
586 if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);