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');
141 # boolean+text previous_balance-exclude_from_total is now two separate options
142 my $total_new_charges = $conf->config('previous_balance-exclude_from_total');
143 if (length($total_new_charges) > 0) {
144 $conf->set('previous_balance-text-total_new_charges', $total_new_charges);
145 $conf->set('previous_balance-exclude_from_total', '');
148 if ( $conf->exists('voip-cust_email_csv_cdr') ) {
149 $conf->set('voip_cdr_email_attach', 'csv');
150 $conf->delete('voip-cust_email_csv_cdr') ;
153 if ( !$conf->config('password-generated-characters') ) {
155 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789()#.,' ;
156 $conf->set('password-generated-characters', $pw_set);
159 if ($conf->exists('unsuspendauto') && !$conf->config('unsuspend_balance')) {
160 $conf->set('unsuspend_balance','Zero');
161 $conf->delete('unsuspendauto');
164 # if translate-auto-insert is enabled for a locale, ensure that invoice
165 # terms are in the msgcat (is there a better place for this?)
166 if (my $auto_locale = $conf->config('translate-auto-insert')) {
167 my $lh = FS::L10N->get_handle($auto_locale);
168 foreach (@FS::Conf::invoice_terms) {
169 $lh->maketext($_) if length($_);
174 sub upgrade_overlimit_groups {
176 my $agentnum = shift;
177 my @groups = $conf->config('overlimit_groups',$agentnum);
178 if(scalar(@groups)) {
179 my $groups = join(',',@groups);
182 if ( $groups !~ /^[\d,]+$/ ) {
183 foreach my $groupname ( @groups ) {
184 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
186 $g = new FS::radius_group {
187 'groupname' => $groupname,
188 'description' => $groupname,
191 die $error if $error;
193 push @groupnums, $g->groupnum;
195 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
200 sub upgrade_invoice_from {
201 my ($conf, $agentnum, $agentonly) = @_;
203 (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) &&
204 ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
207 $realemail =~ s/^\s*//; # remove leading spaces
208 $realemail =~ s/\s*$//; # remove trailing spaces
209 my $realname = $conf->config('invoice_from',$agentnum);
210 $realname =~ s/\<.*\>//; # remove email address
211 $realname =~ s/^\s*//; # remove leading spaces
212 $realname =~ s/\s*$//; # remove trailing spaces
213 # properly quote names that contain punctuation
214 if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
215 $realname = '"' . $realname . '"';
217 $conf->set('invoice_from_name', $realname, $agentnum);
218 $conf->set('invoice_from', $realemail, $agentnum);
229 my $data = upgrade_data(%opt);
231 my $oldAutoCommit = $FS::UID::AutoCommit;
232 local $FS::UID::AutoCommit = 0;
233 local $FS::UID::AutoCommit = 0;
235 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
238 foreach my $table ( keys %$data ) {
240 my $class = "FS::$table";
244 if ( $class->can('_upgrade_data') ) {
245 warn "Upgrading $table...\n";
249 $class->_upgrade_data(%opt);
251 # New interface for async upgrades: a class can declare a
252 # "queueable_upgrade" method, which will run as part of the normal
253 # upgrade, but if the -j option is passed, will instead be run from
255 if ( $class->can('queueable_upgrade') ) {
256 my $jobname = $class . '::queueable_upgrade';
257 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
259 warn "$class upgrade already scheduled.\n";
261 if ( $opt{'queue'} ) {
262 warn "Scheduling $class upgrade.\n";
263 my $job = FS::queue->new({ job => $jobname });
264 $job->insert($class, %opt);
266 $class->queueable_upgrade(%opt);
271 if ( $oldAutoCommit ) {
272 warn " committing\n";
273 dbh->commit or die dbh->errstr;
276 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
277 warn " done in ". (time-$start). " seconds\n";
280 warn "WARNING: asked for upgrade of $table,".
281 " but FS::$table has no _upgrade_data method\n";
284 # my @records = @{ $data->{$table} };
286 # foreach my $record ( @records ) {
287 # my $args = delete($record->{'_upgrade_args'}) || [];
288 # my $object = $class->new( $record );
289 # my $error = $object->insert( @$args );
290 # die "error inserting record into $table: $error\n"
296 local($FS::cust_main::ignore_expired_card) = 1;
297 local($FS::cust_main::ignore_illegal_zip) = 1;
298 local($FS::cust_main::ignore_banned_card) = 1;
299 local($FS::cust_main::skip_fuzzyfiles) = 1;
301 # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
302 # kind of a weird spot for this, but it's better than duplicating
303 # all this code in each class...
304 my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
305 foreach my $table ( @decrypt_tables ) {
306 my @objects = qsearch({
309 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
310 " AND LENGTH(payinfo) > 100",
312 foreach my $object ( @objects ) {
313 my $payinfo = $object->decrypt($object->payinfo);
314 die "error decrypting payinfo" if $payinfo eq $object->payinfo;
315 $object->payinfo($payinfo);
316 my $error = $object->replace;
317 die $error if $error;
330 tie my %hash, 'Tie::IxHash',
332 #fix whitespace - before cust_main
333 'cust_location' => [],
335 #cust_main (tokenizes cards, remove paycvv from history, locations, cust_payby, etc)
336 # (handles payinfo encryption/tokenization across all relevant tables)
342 #reason type and reasons
344 'cust_pkg_reason' => [],
346 #need part_pkg before cust_credit...
352 # fix some tax allocation records
353 'cust_bill_pkg_void' => [],
355 #duplicate history records
358 #populate cust_pay.otaker
361 #populate part_pkg_taxclass for starters
362 'part_pkg_taxclass' => [],
364 #remove bad pending records
365 'cust_pay_pending' => [],
367 #replace invnum and pkgnum with billpkgnum
368 'cust_bill_pkg_detail' => [],
370 #usage_classes if we have none
373 #phone_type if we have none
377 'access_right' => [],
379 #change recur_flat and enable_prorate
380 'part_pkg_option' => [],
382 #add weights to pkg_category
383 'pkg_category' => [],
389 'cust_attachment' => [],
390 #'cust_credit' => [],
392 'cust_main_note' => [],
394 'cust_pay_void' => [],
396 #'cust_pkg_reason' => [],
397 'cust_pkg_discount' => [],
402 'payment_gateway' => [],
404 #migrate to templates
405 'msg_template' => [],
407 #return unprovisioned numbers to availability
410 #insert scripcondition
411 'TicketSystem' => [],
413 #insert LATA data if not already present
416 #insert MSA data if not already present
419 # migrate to radius_group and groupnum instead of groupname
420 'radius_usergroup' => [],
424 #insert default tower_sector if not present
427 #repair improperly deleted services
431 'svc_broadband' => [],
433 #set up payment gateways if needed
436 #flag monthly tax exemptions
437 'cust_tax_exempt_pkg' => [],
439 #kick off tax location history upgrade
440 'cust_bill_pkg' => [],
442 #fix taxable line item links
443 'cust_bill_pkg_tax_location' => [],
445 #populate state FIPS codes if not already done
448 #set default locations on quoted packages
449 'quotation_pkg' => [],
451 #mark certain taxes as system-maintained,
453 'cust_main_county' => [],
467 my $data = upgrade_schema_data(%opt);
469 my $oldAutoCommit = $FS::UID::AutoCommit;
470 local $FS::UID::AutoCommit = 0;
471 local $FS::UID::AutoCommit = 0;
473 foreach my $table ( keys %$data ) {
475 my $class = "FS::$table";
479 if ( $class->can('_upgrade_schema') ) {
480 warn "Upgrading $table schema...\n";
484 $class->_upgrade_schema(%opt);
486 if ( $oldAutoCommit ) {
487 warn " committing\n";
488 dbh->commit or die dbh->errstr;
491 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
492 warn " done in ". (time-$start). " seconds\n";
495 warn "WARNING: asked for schema upgrade of $table,".
496 " but FS::$table has no _upgrade_schema method\n";
503 =item upgrade_schema_data
507 sub upgrade_schema_data {
510 tie my %hash, 'Tie::IxHash',
512 #fix classnum character(1)
513 'cust_bill_pkg_detail' => [],
514 #add necessary columns to RT schema
515 'TicketSystem' => [],
516 #remove possible dangling records
517 'password_history' => [],
518 'cust_pay_pending' => [],
525 sub upgrade_sqlradius {
528 my $conf = new FS::Conf;
530 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
532 foreach my $part_export ( @part_export ) {
534 my $errmsg = 'Error adding FreesideStatus to '.
535 $part_export->option('datasrc'). ': ';
537 my $dbh = DBI->connect(
538 ( map $part_export->option($_), qw ( datasrc username password ) ),
539 { PrintError => 0, PrintWarn => 0 }
541 warn $errmsg.$DBI::errstr;
545 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
546 my $group = "UserName";
548 if ref($part_export) =~ /withdomain/
549 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
551 my $sth_alter = $dbh->prepare(
552 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
555 if ( $sth_alter->execute ) {
556 my $sth_update = $dbh->prepare(
557 "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
558 ) or die $errmsg.$dbh->errstr;
559 $sth_update->execute or die $errmsg.$sth_update->errstr;
561 my $error = $sth_alter->errstr;
563 unless $error =~ /Duplicate column name/i #mysql
564 || $error =~ /already exists/i; #Pg
568 my $error = $dbh->errstr;
569 warn $errmsg.$error; #unless $error =~ /exists/i;
572 my $sth_index = $dbh->prepare(
573 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
576 unless ( $sth_index->execute ) {
577 my $error = $sth_index->errstr;
579 unless $error =~ /Duplicate key name/i #mysql
580 || $error =~ /already exists/i; #Pg
583 my $error = $dbh->errstr;
584 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
587 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
588 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
589 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
591 my $sth = $dbh->prepare("SELECT UserName,
593 $str2time max(AcctStartTime)),
594 $str2time max(AcctStopTime))
596 WHERE FreesideStatus = 'done'
600 or die $errmsg.$dbh->errstr;
601 $sth->execute() or die $errmsg.$sth->errstr;
603 while (my $row = $sth->fetchrow_arrayref ) {
604 my ($username, $realm, $start, $stop) = @$row;
606 $username = lc($username) unless $conf->exists('username-uppercase');
608 my $exportnum = $part_export->exportnum;
609 my $extra_sql = " AND exportnum = $exportnum ".
610 " AND exportsvcnum IS NOT NULL ";
612 if ( ref($part_export) =~ /withdomain/ ) {
613 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
614 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
617 my $svc_acct = qsearchs({
618 'select' => 'svc_acct.*',
619 'table' => 'svc_acct',
620 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
621 'LEFT JOIN export_svc USING ( svcpart )',
622 'hashref' => { 'username' => $username },
623 'extra_sql' => $extra_sql,
627 $svc_acct->last_login($start)
628 if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
629 $svc_acct->last_logout($stop)
630 if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);