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 if ($conf->config('invoice_from') =~ /\<(.*)\>/) {
51 $realemail =~ s/^\s*//; # remove leading spaces
52 $realemail =~ s/\s*$//; # remove trailing spaces
53 my $realname = $conf->config('invoice_from');
54 $realname =~ s/\<.*\>//; # remove email address
55 $realname =~ s/^\s*//; # remove leading spaces
56 $realname =~ s/\s*$//; # remove trailing spaces
57 # properly quote names that contain punctuation
58 if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
59 $realname = '"' . $realname . '"';
61 $conf->set('invoice_from_name', $realname);
62 $conf->set('invoice_from', $realemail);
65 $conf->touch('payment_receipt')
66 if $conf->exists('payment_receipt_email')
67 || $conf->config('payment_receipt_msgnum');
69 $conf->touch('geocode-require_nw_coordinates')
70 if $conf->exists('svc_broadband-require-nw-coordinates');
72 unless ( $conf->config('echeck-country') ) {
73 if ( $conf->exists('cust_main-require-bank-branch') ) {
74 $conf->set('echeck-country', 'CA');
75 } elsif ( $conf->exists('echeck-nonus') ) {
76 $conf->set('echeck-country', 'XX');
78 $conf->set('echeck-country', 'US');
82 upgrade_overlimit_groups($conf);
83 map { upgrade_overlimit_groups($conf,$_->agentnum) } qsearch('agent', {});
85 my $DIST_CONF = '/usr/local/etc/freeside/default_conf/';#DIST_CONF in Makefile
86 $conf->set($_, scalar(read_file( "$DIST_CONF/$_" )) )
87 foreach grep { ! $conf->exists($_) && -s "$DIST_CONF/$_" }
88 qw( quotation_html quotation_latex quotation_latexnotes );
90 # change 'fslongtable' to 'longtable'
91 # in invoice and quotation main templates, and also in all secondary
94 qsearch('conf', { 'name' => {op=>'LIKE', value=>'%latex%'} });
96 foreach my $c (@latex_confs) {
97 my $value = $c->value;
98 if (length($value) and $value =~ /fslongtable/) {
99 $value =~ s/fslongtable/longtable/g;
100 $conf->set($c->name, $value, $c->agentnum);
104 # if there's a USPS tools login, assume that's the standardization method
106 $conf->set('address_standardize_method', 'usps')
107 if $conf->exists('usps_webtools-userid')
108 && length($conf->config('usps_webtools-userid')) > 0
109 && ! $conf->exists('address_standardize_method');
111 # this option has been renamed/expanded
112 if ( $conf->exists('cust_main-enable_spouse_birthdate') ) {
113 $conf->touch('cust_main-enable_spouse');
114 $conf->delete('cust_main-enable_spouse_birthdate');
118 if ( $conf->exists('cust_pkg-show_fcc_voice_grade_equivalent') ) {
119 $conf->touch('part_pkg-show_fcc_options');
120 $conf->delete('cust_pkg-show_fcc_voice_grade_equivalent');
122 You have FCC Form 477 package options enabled.
124 Starting with the October 2014 filing date, the FCC has redesigned
125 Form 477 and introduced new service categories. See bin/convert-477-options
126 to update your package configuration for the new report.
128 If you need to continue using the old Form 477 report, turn on the
129 'old_fcc_report' configuration option.
133 # boolean invoice_sections_by_location option is now
134 # invoice_sections_method = 'location'
135 my @invoice_sections_confs =
136 qsearch('conf', { 'name' => { op=>'LIKE', value=>'%sections_by_location' } });
137 foreach my $c (@invoice_sections_confs) {
138 $c->name =~ /^(\w+)sections_by_location$/;
139 $conf->delete($c->name);
140 my $newname = $1.'sections_method';
141 $conf->set($newname, 'location');
144 # boolean tax-cust_exempt-groups-require_individual_nums is now -num_req all
145 if ( $conf->exists('tax-cust_exempt-groups-require_individual_nums') ) {
146 $conf->set('tax-cust_exempt-groups-num_req', 'all');
147 $conf->delete('tax-cust_exempt-groups-require_individual_nums');
152 sub upgrade_overlimit_groups {
154 my $agentnum = shift;
155 my @groups = $conf->config('overlimit_groups',$agentnum);
156 if(scalar(@groups)) {
157 my $groups = join(',',@groups);
160 if ( $groups !~ /^[\d,]+$/ ) {
161 foreach my $groupname ( @groups ) {
162 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
164 $g = new FS::radius_group {
165 'groupname' => $groupname,
166 'description' => $groupname,
169 die $error if $error;
171 push @groupnums, $g->groupnum;
173 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
185 my $data = upgrade_data(%opt);
187 my $oldAutoCommit = $FS::UID::AutoCommit;
188 local $FS::UID::AutoCommit = 0;
189 local $FS::UID::AutoCommit = 0;
191 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
194 foreach my $table ( keys %$data ) {
196 my $class = "FS::$table";
200 if ( $class->can('_upgrade_data') ) {
201 warn "Upgrading $table...\n";
205 $class->_upgrade_data(%opt);
207 # New interface for async upgrades: a class can declare a
208 # "queueable_upgrade" method, which will run as part of the normal
209 # upgrade, but if the -j option is passed, will instead be run from
211 if ( $class->can('queueable_upgrade') ) {
212 my $jobname = $class . '::queueable_upgrade';
213 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
215 warn "$class upgrade already scheduled.\n";
217 if ( $opt{'queue'} ) {
218 warn "Scheduling $class upgrade.\n";
219 my $job = FS::queue->new({ job => $jobname });
220 $job->insert($class, %opt);
222 $class->queueable_upgrade(%opt);
227 if ( $oldAutoCommit ) {
228 warn " committing\n";
229 dbh->commit or die dbh->errstr;
232 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
233 warn " done in ". (time-$start). " seconds\n";
236 warn "WARNING: asked for upgrade of $table,".
237 " but FS::$table has no _upgrade_data method\n";
240 # my @records = @{ $data->{$table} };
242 # foreach my $record ( @records ) {
243 # my $args = delete($record->{'_upgrade_args'}) || [];
244 # my $object = $class->new( $record );
245 # my $error = $object->insert( @$args );
246 # die "error inserting record into $table: $error\n"
252 local($FS::cust_main::ignore_expired_card) = 1;
253 local($FS::cust_main::ignore_illegal_zip) = 1;
254 local($FS::cust_main::ignore_banned_card) = 1;
255 local($FS::cust_main::skip_fuzzyfiles) = 1;
257 # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
258 # kind of a weird spot for this, but it's better than duplicating
259 # all this code in each class...
260 my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
261 foreach my $table ( @decrypt_tables ) {
262 my @objects = qsearch({
265 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
266 " AND LENGTH(payinfo) > 100",
268 foreach my $object ( @objects ) {
269 my $payinfo = $object->decrypt($object->payinfo);
270 die "error decrypting payinfo" if $payinfo eq $object->payinfo;
271 $object->payinfo($payinfo);
272 my $error = $object->replace;
273 die $error if $error;
286 tie my %hash, 'Tie::IxHash',
288 #cust_main (remove paycvv from history)
294 #reason type and reasons
296 'cust_pkg_reason' => [],
298 #need part_pkg before cust_credit...
304 #duplicate history records
307 #populate cust_pay.otaker
310 #populate part_pkg_taxclass for starters
311 'part_pkg_taxclass' => [],
313 #remove bad pending records
314 'cust_pay_pending' => [],
316 #replace invnum and pkgnum with billpkgnum
317 'cust_bill_pkg_detail' => [],
319 #usage_classes if we have none
322 #phone_type if we have none
326 'access_right' => [],
328 #change recur_flat and enable_prorate
329 'part_pkg_option' => [],
331 #add weights to pkg_category
332 'pkg_category' => [],
338 'cust_attachment' => [],
339 #'cust_credit' => [],
341 'cust_main_note' => [],
343 'cust_pay_void' => [],
345 #'cust_pkg_reason' => [],
346 'cust_pkg_discount' => [],
351 'payment_gateway' => [],
353 #migrate to templates
354 'msg_template' => [],
356 #return unprovisioned numbers to availability
359 #insert scripcondition
360 'TicketSystem' => [],
362 #insert LATA data if not already present
365 #insert MSA data if not already present
368 # migrate to radius_group and groupnum instead of groupname
369 'radius_usergroup' => [],
373 #insert default tower_sector if not present
376 #repair improperly deleted services
380 'svc_broadband' => [],
382 #set up payment gateways if needed
385 #flag monthly tax exemptions
386 'cust_tax_exempt_pkg' => [],
388 #kick off tax location history upgrade
389 'cust_bill_pkg' => [],
391 #fix taxable line item links
392 'cust_bill_pkg_tax_location' => [],
394 #populate state FIPS codes if not already done
409 my $data = upgrade_schema_data(%opt);
411 my $oldAutoCommit = $FS::UID::AutoCommit;
412 local $FS::UID::AutoCommit = 0;
413 local $FS::UID::AutoCommit = 0;
415 foreach my $table ( keys %$data ) {
417 my $class = "FS::$table";
421 if ( $class->can('_upgrade_schema') ) {
422 warn "Upgrading $table schema...\n";
426 $class->_upgrade_schema(%opt);
428 if ( $oldAutoCommit ) {
429 warn " committing\n";
430 dbh->commit or die dbh->errstr;
433 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
434 warn " done in ". (time-$start). " seconds\n";
437 warn "WARNING: asked for schema upgrade of $table,".
438 " but FS::$table has no _upgrade_schema method\n";
445 =item upgrade_schema_data
449 sub upgrade_schema_data {
452 tie my %hash, 'Tie::IxHash',
454 #fix classnum character(1)
455 'cust_bill_pkg_detail' => [],
456 #add necessary columns to RT schema
457 'TicketSystem' => [],
465 sub upgrade_sqlradius {
468 my $conf = new FS::Conf;
470 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
472 foreach my $part_export ( @part_export ) {
474 my $errmsg = 'Error adding FreesideStatus to '.
475 $part_export->option('datasrc'). ': ';
477 my $dbh = DBI->connect(
478 ( map $part_export->option($_), qw ( datasrc username password ) ),
479 { PrintError => 0, PrintWarn => 0 }
481 warn $errmsg.$DBI::errstr;
485 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
486 my $group = "UserName";
488 if ref($part_export) =~ /withdomain/
489 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
491 my $sth_alter = $dbh->prepare(
492 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
495 if ( $sth_alter->execute ) {
496 my $sth_update = $dbh->prepare(
497 "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
498 ) or die $errmsg.$dbh->errstr;
499 $sth_update->execute or die $errmsg.$sth_update->errstr;
501 my $error = $sth_alter->errstr;
503 unless $error =~ /Duplicate column name/i #mysql
504 || $error =~ /already exists/i; #Pg
508 my $error = $dbh->errstr;
509 warn $errmsg.$error; #unless $error =~ /exists/i;
512 my $sth_index = $dbh->prepare(
513 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
516 unless ( $sth_index->execute ) {
517 my $error = $sth_index->errstr;
519 unless $error =~ /Duplicate key name/i #mysql
520 || $error =~ /already exists/i; #Pg
523 my $error = $dbh->errstr;
524 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
527 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
528 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
529 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
531 my $sth = $dbh->prepare("SELECT UserName,
533 $str2time max(AcctStartTime)),
534 $str2time max(AcctStopTime))
536 WHERE FreesideStatus = 'done'
540 or die $errmsg.$dbh->errstr;
541 $sth->execute() or die $errmsg.$sth->errstr;
543 while (my $row = $sth->fetchrow_arrayref ) {
544 my ($username, $realm, $start, $stop) = @$row;
546 $username = lc($username) unless $conf->exists('username-uppercase');
548 my $exportnum = $part_export->exportnum;
549 my $extra_sql = " AND exportnum = $exportnum ".
550 " AND exportsvcnum IS NOT NULL ";
552 if ( ref($part_export) =~ /withdomain/ ) {
553 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
554 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
557 my $svc_acct = qsearchs({
558 'select' => 'svc_acct.*',
559 'table' => 'svc_acct',
560 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
561 'LEFT JOIN export_svc USING ( svcpart )',
562 'hashref' => { 'username' => $username },
563 'extra_sql' => $extra_sql,
567 $svc_acct->last_login($start)
568 if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
569 $svc_acct->last_logout($stop)
570 if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);