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;
16 $FS::svc_domain::whois_hack = 1;
18 @ISA = qw( Exporter );
19 @EXPORT_OK = qw( upgrade_schema upgrade_config upgrade upgrade_sqlradius );
25 FS::Upgrade - Database upgrade routines
33 Currently this module simply provides a place to store common subroutines for
48 my $conf = new FS::Conf;
50 $conf->touch('payment_receipt')
51 if $conf->exists('payment_receipt_email')
52 || $conf->config('payment_receipt_msgnum');
54 $conf->touch('geocode-require_nw_coordinates')
55 if $conf->exists('svc_broadband-require-nw-coordinates');
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');
63 $conf->set('echeck-country', 'US');
67 my @agents = qsearch('agent', {});
69 upgrade_overlimit_groups($conf);
70 map { upgrade_overlimit_groups($conf,$_->agentnum) } @agents;
72 upgrade_invoice_from($conf);
73 foreach my $agent (@agents) {
74 upgrade_invoice_from($conf,$agent->agentnum,1);
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 );
82 # change 'fslongtable' to 'longtable'
83 # in invoice and quotation main templates, and also in all secondary
86 qsearch('conf', { 'name' => {op=>'LIKE', value=>'%latex%'} });
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);
96 # if there's a USPS tools login, assume that's the standardization method
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');
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');
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');
114 You have FCC Form 477 package options enabled.
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.
120 If you need to continue using the old Form 477 report, turn on the
121 'old_fcc_report' configuration option.
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');
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');
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', '');
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') ;
154 if ( !$conf->config('password-generated-characters') ) {
156 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789()#.,' ;
157 $conf->set('password-generated-characters', $pw_set);
160 if ($conf->exists('unsuspendauto') && !$conf->config('unsuspend_balance')) {
161 $conf->set('unsuspend_balance','Zero');
162 $conf->delete('unsuspendauto');
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($_);
175 sub upgrade_overlimit_groups {
177 my $agentnum = shift;
178 my @groups = $conf->config('overlimit_groups',$agentnum);
179 if(scalar(@groups)) {
180 my $groups = join(',',@groups);
183 if ( $groups !~ /^[\d,]+$/ ) {
184 foreach my $groupname ( @groups ) {
185 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
187 $g = new FS::radius_group {
188 'groupname' => $groupname,
189 'description' => $groupname,
192 die $error if $error;
194 push @groupnums, $g->groupnum;
196 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
201 sub upgrade_invoice_from {
202 my ($conf, $agentnum, $agentonly) = @_;
204 (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) &&
205 ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
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 . '"';
218 $conf->set('invoice_from_name', $realname, $agentnum);
219 $conf->set('invoice_from', $realemail, $agentnum);
230 my $data = upgrade_data(%opt);
232 my $oldAutoCommit = $FS::UID::AutoCommit;
233 local $FS::UID::AutoCommit = 0;
234 local $FS::UID::AutoCommit = 0;
236 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
239 foreach my $table ( keys %$data ) {
241 my $class = "FS::$table";
245 if ( $class->can('_upgrade_data') ) {
246 warn "Upgrading $table...\n";
250 $class->_upgrade_data(%opt);
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
256 if ( $class->can('queueable_upgrade') ) {
257 my $jobname = $class . '::queueable_upgrade';
258 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
260 warn "$class upgrade already scheduled.\n";
262 if ( $opt{'queue'} ) {
263 warn "Scheduling $class upgrade.\n";
264 my $job = FS::queue->new({ job => $jobname });
265 $job->insert($class, %opt);
267 $class->queueable_upgrade(%opt);
272 if ( $oldAutoCommit ) {
273 warn " committing\n";
274 dbh->commit or die dbh->errstr;
277 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
278 warn " done in ". (time-$start). " seconds\n";
281 warn "WARNING: asked for upgrade of $table,".
282 " but FS::$table has no _upgrade_data method\n";
285 # my @records = @{ $data->{$table} };
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"
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;
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({
310 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
311 " AND LENGTH(payinfo) > 100",
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";
319 $object->payinfo($payinfo);
320 my $error = $object->replace;
321 die $error if $error;
334 tie my %hash, 'Tie::IxHash',
339 #fix whitespace - before cust_main
340 'cust_location' => [],
342 #remove bad source_paynum before cust_main
345 #cust_main (tokenizes cards, remove paycvv from history, locations, cust_payby, etc)
346 # (handles payinfo encryption/tokenization across all relevant tables)
352 #reason type and reasons
354 'cust_pkg_reason' => [],
356 #need part_pkg before cust_credit...
362 # fix some tax allocation records
363 'cust_bill_pkg_void' => [],
365 #duplicate history records
368 #populate cust_pay.otaker
371 #populate part_pkg_taxclass for starters
372 'part_pkg_taxclass' => [],
374 #remove bad pending records
375 'cust_pay_pending' => [],
377 #replace invnum and pkgnum with billpkgnum
378 'cust_bill_pkg_detail' => [],
380 #usage_classes if we have none
383 #phone_type if we have none
387 'access_right' => [],
389 #change recur_flat and enable_prorate
390 'part_pkg_option' => [],
392 #add weights to pkg_category
393 'pkg_category' => [],
399 'cust_attachment' => [],
400 #'cust_credit' => [],
402 'cust_main_note' => [],
404 'cust_pay_void' => [],
406 #'cust_pkg_reason' => [],
407 'cust_pkg_discount' => [],
408 #'cust_refund' => [],
412 'payment_gateway' => [],
414 #migrate to templates
415 'msg_template' => [],
417 #return unprovisioned numbers to availability
420 #insert scripcondition
421 'TicketSystem' => [],
423 #insert LATA data if not already present
426 #insert MSA data if not already present
429 # migrate to radius_group and groupnum instead of groupname
430 'radius_usergroup' => [],
434 #insert default tower_sector if not present
437 #repair improperly deleted services
441 'svc_broadband' => [],
443 #set up payment gateways if needed
446 #flag monthly tax exemptions
447 'cust_tax_exempt_pkg' => [],
449 #kick off tax location history upgrade
450 'cust_bill_pkg' => [],
452 #fix taxable line item links
453 'cust_bill_pkg_tax_location' => [],
455 #populate state FIPS codes if not already done
458 #set default locations on quoted packages
459 'quotation_pkg' => [],
461 #mark certain taxes as system-maintained,
463 'cust_main_county' => [],
465 #upgrade part_event_condition_option agentnum to a multiple hash value
466 'part_event_condition_option' =>[],
481 my $data = upgrade_schema_data(%opt);
483 my $oldAutoCommit = $FS::UID::AutoCommit;
484 local $FS::UID::AutoCommit = 0;
485 local $FS::UID::AutoCommit = 0;
487 foreach my $table ( keys %$data ) {
489 my $class = "FS::$table";
493 if ( $class->can('_upgrade_schema') ) {
494 warn "Upgrading $table schema...\n";
498 $class->_upgrade_schema(%opt);
500 if ( $oldAutoCommit ) {
501 warn " committing\n";
502 dbh->commit or die dbh->errstr;
505 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
506 warn " done in ". (time-$start). " seconds\n";
509 warn "WARNING: asked for schema upgrade of $table,".
510 " but FS::$table has no _upgrade_schema method\n";
517 =item upgrade_schema_data
521 sub upgrade_schema_data {
524 tie my %hash, 'Tie::IxHash',
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' => [],
539 sub upgrade_sqlradius {
542 my $conf = new FS::Conf;
544 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
546 foreach my $part_export ( @part_export ) {
548 my $errmsg = 'Error adding FreesideStatus to '.
549 $part_export->option('datasrc'). ': ';
551 my $dbh = FS::DBI->connect(
552 ( map $part_export->option($_), qw ( datasrc username password ) ),
553 { PrintError => 0, PrintWarn => 0 }
555 warn $errmsg.$FS::DBI::errstr;
559 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
560 my $group = "UserName";
562 if ref($part_export) =~ /withdomain/
563 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
565 my $sth_alter = $dbh->prepare(
566 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
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;
575 my $error = $sth_alter->errstr;
577 unless $error =~ /Duplicate column name/i #mysql
578 || $error =~ /already exists/i; #Pg
582 my $error = $dbh->errstr;
583 warn $errmsg.$error; #unless $error =~ /exists/i;
586 my $sth_index = $dbh->prepare(
587 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
590 unless ( $sth_index->execute ) {
591 my $error = $sth_index->errstr;
593 unless $error =~ /Duplicate key name/i #mysql
594 || $error =~ /already exists/i; #Pg
597 my $error = $dbh->errstr;
598 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
601 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
602 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
603 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
605 my $sth = $dbh->prepare("SELECT UserName,
607 $str2time max(AcctStartTime)),
608 $str2time max(AcctStopTime))
610 WHERE FreesideStatus = 'done'
614 or die $errmsg.$dbh->errstr;
615 $sth->execute() or die $errmsg.$sth->errstr;
617 while (my $row = $sth->fetchrow_arrayref ) {
618 my ($username, $realm, $start, $stop) = @$row;
620 $username = lc($username) unless $conf->exists('username-uppercase');
622 my $exportnum = $part_export->exportnum;
623 my $extra_sql = " AND exportnum = $exportnum ".
624 " AND exportsvcnum IS NOT NULL ";
626 if ( ref($part_export) =~ /withdomain/ ) {
627 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
628 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
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,
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);