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 enable_taxproducts is now enable_taxproducts = 'cch'
136 if ( $conf->exists('enable_taxproducts') and
137 $conf->config('enable_taxproducts') eq '' ) {
139 $conf->set('enable_taxproducts', 'cch');
143 # boolean tax-cust_exempt-groups-require_individual_nums is now -num_req all
144 if ( $conf->exists('tax-cust_exempt-groups-require_individual_nums') ) {
145 $conf->set('tax-cust_exempt-groups-num_req', 'all');
146 $conf->delete('tax-cust_exempt-groups-require_individual_nums');
151 sub upgrade_overlimit_groups {
153 my $agentnum = shift;
154 my @groups = $conf->config('overlimit_groups',$agentnum);
155 if(scalar(@groups)) {
156 my $groups = join(',',@groups);
159 if ( $groups !~ /^[\d,]+$/ ) {
160 foreach my $groupname ( @groups ) {
161 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
163 $g = new FS::radius_group {
164 'groupname' => $groupname,
165 'description' => $groupname,
168 die $error if $error;
170 push @groupnums, $g->groupnum;
172 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
177 sub upgrade_invoice_from {
178 my ($conf, $agentnum, $agentonly) = @_;
180 (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) &&
181 ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
184 $realemail =~ s/^\s*//; # remove leading spaces
185 $realemail =~ s/\s*$//; # remove trailing spaces
186 my $realname = $conf->config('invoice_from',$agentnum);
187 $realname =~ s/\<.*\>//; # remove email address
188 $realname =~ s/^\s*//; # remove leading spaces
189 $realname =~ s/\s*$//; # remove trailing spaces
190 # properly quote names that contain punctuation
191 if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
192 $realname = '"' . $realname . '"';
194 $conf->set('invoice_from_name', $realname, $agentnum);
195 $conf->set('invoice_from', $realemail, $agentnum);
206 my $data = upgrade_data(%opt);
208 my $oldAutoCommit = $FS::UID::AutoCommit;
209 local $FS::UID::AutoCommit = 0;
210 local $FS::UID::AutoCommit = 0;
212 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
215 foreach my $table ( keys %$data ) {
217 my $class = "FS::$table";
221 if ( $class->can('_upgrade_data') ) {
222 warn "Upgrading $table...\n";
226 $class->_upgrade_data(%opt);
228 # New interface for async upgrades: a class can declare a
229 # "queueable_upgrade" method, which will run as part of the normal
230 # upgrade, but if the -j option is passed, will instead be run from
232 if ( $class->can('queueable_upgrade') ) {
233 my $jobname = $class . '::queueable_upgrade';
234 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
236 warn "$class upgrade already scheduled.\n";
238 if ( $opt{'queue'} ) {
239 warn "Scheduling $class upgrade.\n";
240 my $job = FS::queue->new({ job => $jobname });
241 $job->insert($class, %opt);
243 $class->queueable_upgrade(%opt);
248 if ( $oldAutoCommit ) {
249 warn " committing\n";
250 dbh->commit or die dbh->errstr;
253 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
254 warn " done in ". (time-$start). " seconds\n";
257 warn "WARNING: asked for upgrade of $table,".
258 " but FS::$table has no _upgrade_data method\n";
261 # my @records = @{ $data->{$table} };
263 # foreach my $record ( @records ) {
264 # my $args = delete($record->{'_upgrade_args'}) || [];
265 # my $object = $class->new( $record );
266 # my $error = $object->insert( @$args );
267 # die "error inserting record into $table: $error\n"
273 local($FS::cust_main::ignore_expired_card) = 1;
274 #this is long-gone... would need to set an equivalent in cust_location #local($FS::cust_main::ignore_illegal_zip) = 1;
275 local($FS::cust_main::ignore_banned_card) = 1;
276 local($FS::cust_main::skip_fuzzyfiles) = 1;
278 local($FS::cust_payby::ignore_expired_card) = 1;
279 local($FS::cust_payby::ignore_banned_card) = 1;
281 # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
282 # kind of a weird spot for this, but it's better than duplicating
283 # all this code in each class...
284 my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
285 foreach my $table ( @decrypt_tables ) {
286 my @objects = qsearch({
289 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
290 " AND LENGTH(payinfo) > 100",
292 foreach my $object ( @objects ) {
293 my $payinfo = $object->decrypt($object->payinfo);
294 die "error decrypting payinfo" if $payinfo eq $object->payinfo;
295 $object->payinfo($payinfo);
296 my $error = $object->replace;
297 die $error if $error;
310 tie my %hash, 'Tie::IxHash',
312 #payby conditions to new ones
313 'part_event_condition' => [],
315 #payby actions to new ones
318 #cust_main (remove paycvv from history, locations, cust_payby, etc)
321 #contact -> cust_contact / prospect_contact
327 #reason type and reasons
329 'cust_pkg_reason' => [],
331 #need part_pkg before cust_credit...
337 #duplicate history records
340 #populate cust_pay.otaker
343 #populate part_pkg_taxclass for starters
344 'part_pkg_taxclass' => [],
346 #remove bad pending records
347 'cust_pay_pending' => [],
349 #replace invnum and pkgnum with billpkgnum
350 'cust_bill_pkg_detail' => [],
352 #usage_classes if we have none
355 #phone_type if we have none
359 'access_right' => [],
361 #change recur_flat and enable_prorate
362 'part_pkg_option' => [],
364 #add weights to pkg_category
365 'pkg_category' => [],
371 'cust_attachment' => [],
372 #'cust_credit' => [],
374 'cust_main_note' => [],
376 'cust_pay_void' => [],
378 #'cust_pkg_reason' => [],
379 'cust_pkg_discount' => [],
384 'payment_gateway' => [],
386 #migrate to templates
387 'msg_template' => [],
389 #return unprovisioned numbers to availability
392 #insert scripcondition
393 'TicketSystem' => [],
395 #insert LATA data if not already present
398 #insert MSA data if not already present
401 # migrate to radius_group and groupnum instead of groupname
402 'radius_usergroup' => [],
406 #insert default tower_sector if not present
409 #repair improperly deleted services
413 'svc_broadband' => [],
415 #set up payment gateways if needed
418 #flag monthly tax exemptions
419 'cust_tax_exempt_pkg' => [],
421 #kick off tax location history upgrade
422 'cust_bill_pkg' => [],
424 #fix taxable line item links
425 'cust_bill_pkg_tax_location' => [],
427 #populate state FIPS codes if not already done
430 #populate tax statuses
445 my $data = upgrade_schema_data(%opt);
447 my $oldAutoCommit = $FS::UID::AutoCommit;
448 local $FS::UID::AutoCommit = 0;
449 local $FS::UID::AutoCommit = 0;
451 foreach my $table ( keys %$data ) {
453 my $class = "FS::$table";
457 if ( $class->can('_upgrade_schema') ) {
458 warn "Upgrading $table schema...\n";
462 $class->_upgrade_schema(%opt);
464 if ( $oldAutoCommit ) {
465 warn " committing\n";
466 dbh->commit or die dbh->errstr;
469 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
470 warn " done in ". (time-$start). " seconds\n";
473 warn "WARNING: asked for schema upgrade of $table,".
474 " but FS::$table has no _upgrade_schema method\n";
481 =item upgrade_schema_data
485 sub upgrade_schema_data {
488 tie my %hash, 'Tie::IxHash',
490 #fix classnum character(1)
491 'cust_bill_pkg_detail' => [],
492 #add necessary columns to RT schema
493 'TicketSystem' => [],
501 sub upgrade_sqlradius {
504 my $conf = new FS::Conf;
506 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
508 foreach my $part_export ( @part_export ) {
510 my $errmsg = 'Error adding FreesideStatus to '.
511 $part_export->option('datasrc'). ': ';
513 my $dbh = DBI->connect(
514 ( map $part_export->option($_), qw ( datasrc username password ) ),
515 { PrintError => 0, PrintWarn => 0 }
517 warn $errmsg.$DBI::errstr;
521 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
522 my $group = "UserName";
524 if ref($part_export) =~ /withdomain/
525 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
527 my $sth_alter = $dbh->prepare(
528 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
531 if ( $sth_alter->execute ) {
532 my $sth_update = $dbh->prepare(
533 "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
534 ) or die $errmsg.$dbh->errstr;
535 $sth_update->execute or die $errmsg.$sth_update->errstr;
537 my $error = $sth_alter->errstr;
539 unless $error =~ /Duplicate column name/i #mysql
540 || $error =~ /already exists/i; #Pg
544 my $error = $dbh->errstr;
545 warn $errmsg.$error; #unless $error =~ /exists/i;
548 my $sth_index = $dbh->prepare(
549 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
552 unless ( $sth_index->execute ) {
553 my $error = $sth_index->errstr;
555 unless $error =~ /Duplicate key name/i #mysql
556 || $error =~ /already exists/i; #Pg
559 my $error = $dbh->errstr;
560 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
563 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
564 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
565 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
567 my $sth = $dbh->prepare("SELECT UserName,
569 $str2time max(AcctStartTime)),
570 $str2time max(AcctStopTime))
572 WHERE FreesideStatus = 'done'
576 or die $errmsg.$dbh->errstr;
577 $sth->execute() or die $errmsg.$sth->errstr;
579 while (my $row = $sth->fetchrow_arrayref ) {
580 my ($username, $realm, $start, $stop) = @$row;
582 $username = lc($username) unless $conf->exists('username-uppercase');
584 my $exportnum = $part_export->exportnum;
585 my $extra_sql = " AND exportnum = $exportnum ".
586 " AND exportsvcnum IS NOT NULL ";
588 if ( ref($part_export) =~ /withdomain/ ) {
589 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
590 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
593 my $svc_acct = qsearchs({
594 'select' => 'svc_acct.*',
595 'table' => 'svc_acct',
596 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
597 'LEFT JOIN export_svc USING ( svcpart )',
598 'hashref' => { 'username' => $username },
599 'extra_sql' => $extra_sql,
603 $svc_acct->last_login($start)
604 if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
605 $svc_acct->last_logout($stop)
606 if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);