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 upgrade_overlimit_groups($conf);
67 map { upgrade_overlimit_groups($conf,$_->agentnum) } qsearch('agent', {});
69 my $DIST_CONF = '/usr/local/etc/freeside/default_conf/';#DIST_CONF in Makefile
70 $conf->set($_, scalar(read_file( "$DIST_CONF/$_" )) )
71 foreach grep { ! $conf->exists($_) && -s "$DIST_CONF/$_" }
72 qw( quotation_html quotation_latex quotation_latexnotes );
74 # change 'fslongtable' to 'longtable'
75 # in invoice and quotation main templates, and also in all secondary
78 qsearch('conf', { 'name' => {op=>'LIKE', value=>'%latex%'} });
80 foreach my $c (@latex_confs) {
81 my $value = $c->value;
82 if (length($value) and $value =~ /fslongtable/) {
83 $value =~ s/fslongtable/longtable/g;
84 $conf->set($c->name, $value, $c->agentnum);
88 # if there's a USPS tools login, assume that's the standardization method
90 $conf->set('address_standardize_method', 'usps')
91 if $conf->exists('usps_webtools-userid')
92 && length($conf->config('usps_webtools-userid')) > 0
93 && ! $conf->exists('address_standardize_method');
95 # this option has been renamed/expanded
96 if ( $conf->exists('cust_main-enable_spouse_birthdate') ) {
97 $conf->touch('cust_main-enable_spouse');
98 $conf->delete('cust_main-enable_spouse_birthdate');
102 sub upgrade_overlimit_groups {
104 my $agentnum = shift;
105 my @groups = $conf->config('overlimit_groups',$agentnum);
106 if(scalar(@groups)) {
107 my $groups = join(',',@groups);
110 if ( $groups !~ /^[\d,]+$/ ) {
111 foreach my $groupname ( @groups ) {
112 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
114 $g = new FS::radius_group {
115 'groupname' => $groupname,
116 'description' => $groupname,
119 die $error if $error;
121 push @groupnums, $g->groupnum;
123 $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
135 my $data = upgrade_data(%opt);
137 my $oldAutoCommit = $FS::UID::AutoCommit;
138 local $FS::UID::AutoCommit = 0;
139 local $FS::UID::AutoCommit = 0;
141 local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
144 foreach my $table ( keys %$data ) {
146 my $class = "FS::$table";
150 if ( $class->can('_upgrade_data') ) {
151 warn "Upgrading $table...\n";
155 $class->_upgrade_data(%opt);
157 # New interface for async upgrades: a class can declare a
158 # "queueable_upgrade" method, which will run as part of the normal
159 # upgrade, but if the -j option is passed, will instead be run from
161 if ( $class->can('queueable_upgrade') ) {
162 my $jobname = $class . '::queueable_upgrade';
163 my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
165 warn "$class upgrade already scheduled.\n";
167 if ( $opt{'queue'} ) {
168 warn "Scheduling $class upgrade.\n";
169 my $job = FS::queue->new({ job => $jobname });
170 $job->insert($class, %opt);
172 $class->queueable_upgrade(%opt);
177 if ( $oldAutoCommit ) {
178 warn " committing\n";
179 dbh->commit or die dbh->errstr;
182 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
183 warn " done in ". (time-$start). " seconds\n";
186 warn "WARNING: asked for upgrade of $table,".
187 " but FS::$table has no _upgrade_data method\n";
190 # my @records = @{ $data->{$table} };
192 # foreach my $record ( @records ) {
193 # my $args = delete($record->{'_upgrade_args'}) || [];
194 # my $object = $class->new( $record );
195 # my $error = $object->insert( @$args );
196 # die "error inserting record into $table: $error\n"
202 local($FS::cust_main::ignore_expired_card) = 1;
203 local($FS::cust_main::ignore_illegal_zip) = 1;
204 local($FS::cust_main::ignore_banned_card) = 1;
205 local($FS::cust_main::skip_fuzzyfiles) = 1;
207 # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
208 # kind of a weird spot for this, but it's better than duplicating
209 # all this code in each class...
210 my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
211 foreach my $table ( @decrypt_tables ) {
212 my @objects = qsearch({
215 'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
216 " AND LENGTH(payinfo) > 100",
218 foreach my $object ( @objects ) {
219 my $payinfo = $object->decrypt($object->payinfo);
220 die "error decrypting payinfo" if $payinfo eq $object->payinfo;
221 $object->payinfo($payinfo);
222 my $error = $object->replace;
223 die $error if $error;
236 tie my %hash, 'Tie::IxHash',
238 #cust_main (remove paycvv from history)
244 #reason type and reasons
246 'cust_pkg_reason' => [],
248 #need part_pkg before cust_credit...
254 #duplicate history records
257 #populate cust_pay.otaker
260 #populate part_pkg_taxclass for starters
261 'part_pkg_taxclass' => [],
263 #remove bad pending records
264 'cust_pay_pending' => [],
266 #replace invnum and pkgnum with billpkgnum
267 'cust_bill_pkg_detail' => [],
269 #usage_classes if we have none
272 #phone_type if we have none
276 'access_right' => [],
278 #change recur_flat and enable_prorate
279 'part_pkg_option' => [],
281 #add weights to pkg_category
282 'pkg_category' => [],
288 'cust_attachment' => [],
289 #'cust_credit' => [],
291 'cust_main_note' => [],
293 'cust_pay_void' => [],
295 #'cust_pkg_reason' => [],
296 'cust_pkg_discount' => [],
301 'payment_gateway' => [],
303 #migrate to templates
304 'msg_template' => [],
306 #return unprovisioned numbers to availability
309 #insert scripcondition
310 'TicketSystem' => [],
312 #insert LATA data if not already present
315 #insert MSA data if not already present
318 # migrate to radius_group and groupnum instead of groupname
319 'radius_usergroup' => [],
323 #insert default tower_sector if not present
326 #repair improperly deleted services
330 'svc_broadband' => [],
332 #set up payment gateways if needed
335 #flag monthly tax exemptions
336 'cust_tax_exempt_pkg' => [],
338 #kick off tax location history upgrade
339 'cust_bill_pkg' => [],
341 #fix taxable line item links
342 'cust_bill_pkg_tax_location' => [],
356 my $data = upgrade_schema_data(%opt);
358 my $oldAutoCommit = $FS::UID::AutoCommit;
359 local $FS::UID::AutoCommit = 0;
360 local $FS::UID::AutoCommit = 0;
362 foreach my $table ( keys %$data ) {
364 my $class = "FS::$table";
368 if ( $class->can('_upgrade_schema') ) {
369 warn "Upgrading $table schema...\n";
373 $class->_upgrade_schema(%opt);
375 if ( $oldAutoCommit ) {
376 warn " committing\n";
377 dbh->commit or die dbh->errstr;
380 #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
381 warn " done in ". (time-$start). " seconds\n";
384 warn "WARNING: asked for schema upgrade of $table,".
385 " but FS::$table has no _upgrade_schema method\n";
392 =item upgrade_schema_data
396 sub upgrade_schema_data {
399 tie my %hash, 'Tie::IxHash',
401 #fix classnum character(1)
402 'cust_bill_pkg_detail' => [],
403 #add necessary columns to RT schema
404 'TicketSystem' => [],
412 sub upgrade_sqlradius {
415 my $conf = new FS::Conf;
417 my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
419 foreach my $part_export ( @part_export ) {
421 my $errmsg = 'Error adding FreesideStatus to '.
422 $part_export->option('datasrc'). ': ';
424 my $dbh = DBI->connect(
425 ( map $part_export->option($_), qw ( datasrc username password ) ),
426 { PrintError => 0, PrintWarn => 0 }
428 warn $errmsg.$DBI::errstr;
432 my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
433 my $group = "UserName";
435 if ref($part_export) =~ /withdomain/
436 || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
438 my $sth_alter = $dbh->prepare(
439 "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
442 if ( $sth_alter->execute ) {
443 my $sth_update = $dbh->prepare(
444 "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
445 ) or die $errmsg.$dbh->errstr;
446 $sth_update->execute or die $errmsg.$sth_update->errstr;
448 my $error = $sth_alter->errstr;
450 unless $error =~ /Duplicate column name/i #mysql
451 || $error =~ /already exists/i; #Pg
455 my $error = $dbh->errstr;
456 warn $errmsg.$error; #unless $error =~ /exists/i;
459 my $sth_index = $dbh->prepare(
460 "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
463 unless ( $sth_index->execute ) {
464 my $error = $sth_index->errstr;
466 unless $error =~ /Duplicate key name/i #mysql
467 || $error =~ /already exists/i; #Pg
470 my $error = $dbh->errstr;
471 warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
474 my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
475 ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
476 : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
478 my $sth = $dbh->prepare("SELECT UserName,
480 $str2time max(AcctStartTime)),
481 $str2time max(AcctStopTime))
483 WHERE FreesideStatus = 'done'
487 or die $errmsg.$dbh->errstr;
488 $sth->execute() or die $errmsg.$sth->errstr;
490 while (my $row = $sth->fetchrow_arrayref ) {
491 my ($username, $realm, $start, $stop) = @$row;
493 $username = lc($username) unless $conf->exists('username-uppercase');
495 my $exportnum = $part_export->exportnum;
496 my $extra_sql = " AND exportnum = $exportnum ".
497 " AND exportsvcnum IS NOT NULL ";
499 if ( ref($part_export) =~ /withdomain/ ) {
500 $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
501 WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
504 my $svc_acct = qsearchs({
505 'select' => 'svc_acct.*',
506 'table' => 'svc_acct',
507 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum )'.
508 'LEFT JOIN export_svc USING ( svcpart )',
509 'hashref' => { 'username' => $username },
510 'extra_sql' => $extra_sql,
514 $svc_acct->last_login($start)
515 if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
516 $svc_acct->last_logout($stop)
517 if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);