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') ;
155 sub upgrade_overlimit_groups {
157 my $agentnum = shift;
158 my @groups = $conf->config('overlimit_groups',$agentnum);
159 if(scalar(@groups)) {
160 my $groups = join(',',@groups);
163 if ( $groups !~ /^[\d,]+$/ ) {
164 foreach my $groupname ( @groups ) {
165 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
167 $g = new FS::radius_group {
168 'groupname' => $groupname,
169 'description' => $groupname,
172 die $error if $error;
174 push @groupnums, $g->groupnum;
176 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
181 sub upgrade_invoice_from {
182 my ($conf, $agentnum, $agentonly) = @_;
184 (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) &&
185 ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
188 $realemail =~ s/^\s*//; # remove leading spaces
189 $realemail =~ s/\s*$//; # remove trailing spaces
190 my $realname = $conf->config('invoice_from',$agentnum);
191 $realname =~ s/\<.*\>//; # remove email address
192 $realname =~ s/^\s*//; # remove leading spaces
193 $realname =~ s/\s*$//; # remove trailing spaces
194 # properly quote names that contain punctuation
195 if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
196 $realname = '"' . $realname . '"';
198 $conf->set('invoice_from_name', $realname, $agentnum);
199 $conf->set('invoice_from', $realemail, $agentnum);
210 my $data = upgrade_data(%opt);
212 my $oldAutoCommit = $FS::UID::AutoCommit;
213 local $FS::UID::AutoCommit = 0;
214 local $FS::UID::AutoCommit = 0;
216 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
219 foreach my $table ( keys %$data ) {
221 my $class = "FS::$table";
225 if ( $class->can('_upgrade_data') ) {
226 warn "Upgrading $table...\n";
230 $class->_upgrade_data(%opt);
232 # New interface for async upgrades: a class can declare a
233 # "queueable_upgrade" method, which will run as part of the normal
234 # upgrade, but if the -j option is passed, will instead be run from
236 if ( $class->can('queueable_upgrade') ) {
237 my $jobname = $class . '::queueable_upgrade';
238 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
240 warn "$class upgrade already scheduled.\n";
242 if ( $opt{'queue'} ) {
243 warn "Scheduling $class upgrade.\n";
244 my $job = FS::queue->new({ job => $jobname });
245 $job->insert($class, %opt);
247 $class->queueable_upgrade(%opt);
252 if ( $oldAutoCommit ) {
253 warn " committing\n";
254 dbh->commit or die dbh->errstr;
257 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
258 warn " done in ". (time-$start). " seconds\n";
261 warn "WARNING: asked for upgrade of $table,".
262 " but FS::$table has no _upgrade_data method\n";
265 # my @records = @{ $data->{$table} };
267 # foreach my $record ( @records ) {
268 # my $args = delete($record->{'_upgrade_args'}) || [];
269 # my $object = $class->new( $record );
270 # my $error = $object->insert( @$args );
271 # die "error inserting record into $table: $error\n"
277 local($FS::cust_main::ignore_expired_card) = 1;
278 local($FS::cust_main::ignore_illegal_zip) = 1;
279 local($FS::cust_main::ignore_banned_card) = 1;
280 local($FS::cust_main::skip_fuzzyfiles) = 1;
282 # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
283 # kind of a weird spot for this, but it's better than duplicating
284 # all this code in each class...
285 my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
286 foreach my $table ( @decrypt_tables ) {
287 my @objects = qsearch({
290 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
291 " AND LENGTH(payinfo) > 100",
293 foreach my $object ( @objects ) {
294 my $payinfo = $object->decrypt($object->payinfo);
295 die "error decrypting payinfo" if $payinfo eq $object->payinfo;
296 $object->payinfo($payinfo);
297 my $error = $object->replace;
298 die $error if $error;
311 tie my %hash, 'Tie::IxHash',
313 #cust_main (remove paycvv from history)
319 #reason type and reasons
321 'cust_pkg_reason' => [],
323 #need part_pkg before cust_credit...
329 #duplicate history records
332 #populate cust_pay.otaker
335 #populate part_pkg_taxclass for starters
336 'part_pkg_taxclass' => [],
338 #remove bad pending records
339 'cust_pay_pending' => [],
341 #replace invnum and pkgnum with billpkgnum
342 'cust_bill_pkg_detail' => [],
344 #usage_classes if we have none
347 #phone_type if we have none
351 'access_right' => [],
353 #change recur_flat and enable_prorate
354 'part_pkg_option' => [],
356 #add weights to pkg_category
357 'pkg_category' => [],
363 'cust_attachment' => [],
364 #'cust_credit' => [],
366 'cust_main_note' => [],
368 'cust_pay_void' => [],
370 #'cust_pkg_reason' => [],
371 'cust_pkg_discount' => [],
376 'payment_gateway' => [],
378 #migrate to templates
379 'msg_template' => [],
381 #return unprovisioned numbers to availability
384 #insert scripcondition
385 'TicketSystem' => [],
387 #insert LATA data if not already present
390 #insert MSA data if not already present
393 # migrate to radius_group and groupnum instead of groupname
394 'radius_usergroup' => [],
398 #insert default tower_sector if not present
401 #repair improperly deleted services
405 'svc_broadband' => [],
407 #set up payment gateways if needed
410 #flag monthly tax exemptions
411 'cust_tax_exempt_pkg' => [],
413 #kick off tax location history upgrade
414 'cust_bill_pkg' => [],
416 #fix taxable line item links
417 'cust_bill_pkg_tax_location' => [],
419 #populate state FIPS codes if not already done
422 #set default locations on quoted packages
423 'quotation_pkg' => [],
437 my $data = upgrade_schema_data(%opt);
439 my $oldAutoCommit = $FS::UID::AutoCommit;
440 local $FS::UID::AutoCommit = 0;
441 local $FS::UID::AutoCommit = 0;
443 foreach my $table ( keys %$data ) {
445 my $class = "FS::$table";
449 if ( $class->can('_upgrade_schema') ) {
450 warn "Upgrading $table schema...\n";
454 $class->_upgrade_schema(%opt);
456 if ( $oldAutoCommit ) {
457 warn " committing\n";
458 dbh->commit or die dbh->errstr;
461 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
462 warn " done in ". (time-$start). " seconds\n";
465 warn "WARNING: asked for schema upgrade of $table,".
466 " but FS::$table has no _upgrade_schema method\n";
473 =item upgrade_schema_data
477 sub upgrade_schema_data {
480 tie my %hash, 'Tie::IxHash',
482 #fix classnum character(1)
483 'cust_bill_pkg_detail' => [],
484 #add necessary columns to RT schema
485 'TicketSystem' => [],
493 sub upgrade_sqlradius {
496 my $conf = new FS::Conf;
498 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
500 foreach my $part_export ( @part_export ) {
502 my $errmsg = 'Error adding FreesideStatus to '.
503 $part_export->option('datasrc'). ': ';
505 my $dbh = DBI->connect(
506 ( map $part_export->option($_), qw ( datasrc username password ) ),
507 { PrintError => 0, PrintWarn => 0 }
509 warn $errmsg.$DBI::errstr;
513 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
514 my $group = "UserName";
516 if ref($part_export) =~ /withdomain/
517 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
519 my $sth_alter = $dbh->prepare(
520 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
523 if ( $sth_alter->execute ) {
524 my $sth_update = $dbh->prepare(
525 "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
526 ) or die $errmsg.$dbh->errstr;
527 $sth_update->execute or die $errmsg.$sth_update->errstr;
529 my $error = $sth_alter->errstr;
531 unless $error =~ /Duplicate column name/i #mysql
532 || $error =~ /already exists/i; #Pg
536 my $error = $dbh->errstr;
537 warn $errmsg.$error; #unless $error =~ /exists/i;
540 my $sth_index = $dbh->prepare(
541 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
544 unless ( $sth_index->execute ) {
545 my $error = $sth_index->errstr;
547 unless $error =~ /Duplicate key name/i #mysql
548 || $error =~ /already exists/i; #Pg
551 my $error = $dbh->errstr;
552 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
555 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
556 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
557 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
559 my $sth = $dbh->prepare("SELECT UserName,
561 $str2time max(AcctStartTime)),
562 $str2time max(AcctStopTime))
564 WHERE FreesideStatus = 'done'
568 or die $errmsg.$dbh->errstr;
569 $sth->execute() or die $errmsg.$sth->errstr;
571 while (my $row = $sth->fetchrow_arrayref ) {
572 my ($username, $realm, $start, $stop) = @$row;
574 $username = lc($username) unless $conf->exists('username-uppercase');
576 my $exportnum = $part_export->exportnum;
577 my $extra_sql = " AND exportnum = $exportnum ".
578 " AND exportsvcnum IS NOT NULL ";
580 if ( ref($part_export) =~ /withdomain/ ) {
581 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
582 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
585 my $svc_acct = qsearchs({
586 'select' => 'svc_acct.*',
587 'table' => 'svc_acct',
588 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
589 'LEFT JOIN export_svc USING ( svcpart )',
590 'hashref' => { 'username' => $username },
591 'extra_sql' => $extra_sql,
595 $svc_acct->last_login($start)
596 if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
597 $svc_acct->last_logout($stop)
598 if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);