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', '');
150 sub upgrade_overlimit_groups {
152 my $agentnum = shift;
153 my @groups = $conf->config('overlimit_groups',$agentnum);
154 if(scalar(@groups)) {
155 my $groups = join(',',@groups);
158 if ( $groups !~ /^[\d,]+$/ ) {
159 foreach my $groupname ( @groups ) {
160 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
162 $g = new FS::radius_group {
163 'groupname' => $groupname,
164 'description' => $groupname,
167 die $error if $error;
169 push @groupnums, $g->groupnum;
171 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
176 sub upgrade_invoice_from {
177 my ($conf, $agentnum, $agentonly) = @_;
179 (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) &&
180 ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
183 $realemail =~ s/^\s*//; # remove leading spaces
184 $realemail =~ s/\s*$//; # remove trailing spaces
185 my $realname = $conf->config('invoice_from',$agentnum);
186 $realname =~ s/\<.*\>//; # remove email address
187 $realname =~ s/^\s*//; # remove leading spaces
188 $realname =~ s/\s*$//; # remove trailing spaces
189 # properly quote names that contain punctuation
190 if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
191 $realname = '"' . $realname . '"';
193 $conf->set('invoice_from_name', $realname, $agentnum);
194 $conf->set('invoice_from', $realemail, $agentnum);
205 my $data = upgrade_data(%opt);
207 my $oldAutoCommit = $FS::UID::AutoCommit;
208 local $FS::UID::AutoCommit = 0;
209 local $FS::UID::AutoCommit = 0;
211 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
214 foreach my $table ( keys %$data ) {
216 my $class = "FS::$table";
220 if ( $class->can('_upgrade_data') ) {
221 warn "Upgrading $table...\n";
225 $class->_upgrade_data(%opt);
227 # New interface for async upgrades: a class can declare a
228 # "queueable_upgrade" method, which will run as part of the normal
229 # upgrade, but if the -j option is passed, will instead be run from
231 if ( $class->can('queueable_upgrade') ) {
232 my $jobname = $class . '::queueable_upgrade';
233 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
235 warn "$class upgrade already scheduled.\n";
237 if ( $opt{'queue'} ) {
238 warn "Scheduling $class upgrade.\n";
239 my $job = FS::queue->new({ job => $jobname });
240 $job->insert($class, %opt);
242 $class->queueable_upgrade(%opt);
247 if ( $oldAutoCommit ) {
248 warn " committing\n";
249 dbh->commit or die dbh->errstr;
252 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
253 warn " done in ". (time-$start). " seconds\n";
256 warn "WARNING: asked for upgrade of $table,".
257 " but FS::$table has no _upgrade_data method\n";
260 # my @records = @{ $data->{$table} };
262 # foreach my $record ( @records ) {
263 # my $args = delete($record->{'_upgrade_args'}) || [];
264 # my $object = $class->new( $record );
265 # my $error = $object->insert( @$args );
266 # die "error inserting record into $table: $error\n"
272 local($FS::cust_main::ignore_expired_card) = 1;
273 local($FS::cust_main::ignore_illegal_zip) = 1;
274 local($FS::cust_main::ignore_banned_card) = 1;
275 local($FS::cust_main::skip_fuzzyfiles) = 1;
277 # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
278 # kind of a weird spot for this, but it's better than duplicating
279 # all this code in each class...
280 my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
281 foreach my $table ( @decrypt_tables ) {
282 my @objects = qsearch({
285 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
286 " AND LENGTH(payinfo) > 100",
288 foreach my $object ( @objects ) {
289 my $payinfo = $object->decrypt($object->payinfo);
290 die "error decrypting payinfo" if $payinfo eq $object->payinfo;
291 $object->payinfo($payinfo);
292 my $error = $object->replace;
293 die $error if $error;
306 tie my %hash, 'Tie::IxHash',
308 #cust_main (remove paycvv from history)
314 #reason type and reasons
316 'cust_pkg_reason' => [],
318 #need part_pkg before cust_credit...
324 #duplicate history records
327 #populate cust_pay.otaker
330 #populate part_pkg_taxclass for starters
331 'part_pkg_taxclass' => [],
333 #remove bad pending records
334 'cust_pay_pending' => [],
336 #replace invnum and pkgnum with billpkgnum
337 'cust_bill_pkg_detail' => [],
339 #usage_classes if we have none
342 #phone_type if we have none
346 'access_right' => [],
348 #change recur_flat and enable_prorate
349 'part_pkg_option' => [],
351 #add weights to pkg_category
352 'pkg_category' => [],
358 'cust_attachment' => [],
359 #'cust_credit' => [],
361 'cust_main_note' => [],
363 'cust_pay_void' => [],
365 #'cust_pkg_reason' => [],
366 'cust_pkg_discount' => [],
371 'payment_gateway' => [],
373 #migrate to templates
374 'msg_template' => [],
376 #return unprovisioned numbers to availability
379 #insert scripcondition
380 'TicketSystem' => [],
382 #insert LATA data if not already present
385 #insert MSA data if not already present
388 # migrate to radius_group and groupnum instead of groupname
389 'radius_usergroup' => [],
393 #insert default tower_sector if not present
396 #repair improperly deleted services
400 'svc_broadband' => [],
402 #set up payment gateways if needed
405 #flag monthly tax exemptions
406 'cust_tax_exempt_pkg' => [],
408 #kick off tax location history upgrade
409 'cust_bill_pkg' => [],
411 #fix taxable line item links
412 'cust_bill_pkg_tax_location' => [],
414 #populate state FIPS codes if not already done
417 #set default locations on quoted packages
418 'quotation_pkg' => [],
432 my $data = upgrade_schema_data(%opt);
434 my $oldAutoCommit = $FS::UID::AutoCommit;
435 local $FS::UID::AutoCommit = 0;
436 local $FS::UID::AutoCommit = 0;
438 foreach my $table ( keys %$data ) {
440 my $class = "FS::$table";
444 if ( $class->can('_upgrade_schema') ) {
445 warn "Upgrading $table schema...\n";
449 $class->_upgrade_schema(%opt);
451 if ( $oldAutoCommit ) {
452 warn " committing\n";
453 dbh->commit or die dbh->errstr;
456 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
457 warn " done in ". (time-$start). " seconds\n";
460 warn "WARNING: asked for schema upgrade of $table,".
461 " but FS::$table has no _upgrade_schema method\n";
468 =item upgrade_schema_data
472 sub upgrade_schema_data {
475 tie my %hash, 'Tie::IxHash',
477 #fix classnum character(1)
478 'cust_bill_pkg_detail' => [],
479 #add necessary columns to RT schema
480 'TicketSystem' => [],
488 sub upgrade_sqlradius {
491 my $conf = new FS::Conf;
493 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
495 foreach my $part_export ( @part_export ) {
497 my $errmsg = 'Error adding FreesideStatus to '.
498 $part_export->option('datasrc'). ': ';
500 my $dbh = DBI->connect(
501 ( map $part_export->option($_), qw ( datasrc username password ) ),
502 { PrintError => 0, PrintWarn => 0 }
504 warn $errmsg.$DBI::errstr;
508 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
509 my $group = "UserName";
511 if ref($part_export) =~ /withdomain/
512 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
514 my $sth_alter = $dbh->prepare(
515 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
518 if ( $sth_alter->execute ) {
519 my $sth_update = $dbh->prepare(
520 "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
521 ) or die $errmsg.$dbh->errstr;
522 $sth_update->execute or die $errmsg.$sth_update->errstr;
524 my $error = $sth_alter->errstr;
526 unless $error =~ /Duplicate column name/i #mysql
527 || $error =~ /already exists/i; #Pg
531 my $error = $dbh->errstr;
532 warn $errmsg.$error; #unless $error =~ /exists/i;
535 my $sth_index = $dbh->prepare(
536 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
539 unless ( $sth_index->execute ) {
540 my $error = $sth_index->errstr;
542 unless $error =~ /Duplicate key name/i #mysql
543 || $error =~ /already exists/i; #Pg
546 my $error = $dbh->errstr;
547 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
550 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
551 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
552 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
554 my $sth = $dbh->prepare("SELECT UserName,
556 $str2time max(AcctStartTime)),
557 $str2time max(AcctStopTime))
559 WHERE FreesideStatus = 'done'
563 or die $errmsg.$dbh->errstr;
564 $sth->execute() or die $errmsg.$sth->errstr;
566 while (my $row = $sth->fetchrow_arrayref ) {
567 my ($username, $realm, $start, $stop) = @$row;
569 $username = lc($username) unless $conf->exists('username-uppercase');
571 my $exportnum = $part_export->exportnum;
572 my $extra_sql = " AND exportnum = $exportnum ".
573 " AND exportsvcnum IS NOT NULL ";
575 if ( ref($part_export) =~ /withdomain/ ) {
576 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
577 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
580 my $svc_acct = qsearchs({
581 'select' => 'svc_acct.*',
582 'table' => 'svc_acct',
583 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
584 'LEFT JOIN export_svc USING ( svcpart )',
585 'hashref' => { 'username' => $username },
586 'extra_sql' => $extra_sql,
590 $svc_acct->last_login($start)
591 if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
592 $svc_acct->last_logout($stop)
593 if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);