RT#37908: Convert existing email-sending code to use common interface [removals and...
[freeside.git] / FS / FS / Upgrade.pm
1 package FS::Upgrade;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $DEBUG );
5 use Exporter;
6 use Tie::IxHash;
7 use File::Slurp;
8 use FS::UID qw( dbh driver_name );
9 use FS::Conf;
10 use FS::Record qw(qsearchs qsearch str2time_sql);
11 use FS::queue;
12 use FS::upgrade_journal;
13 use FS::Setup qw( enable_banned_pay_pad );
14
15 use FS::svc_domain;
16 $FS::svc_domain::whois_hack = 1;
17
18 @ISA = qw( Exporter );
19 @EXPORT_OK = qw( upgrade_schema upgrade_config upgrade upgrade_sqlradius );
20
21 $DEBUG = 1;
22
23 =head1 NAME
24
25 FS::Upgrade - Database upgrade routines
26
27 =head1 SYNOPSIS
28
29   use FS::Upgrade;
30
31 =head1 DESCRIPTION
32
33 Currently this module simply provides a place to store common subroutines for
34 database upgrades.
35
36 =head1 SUBROUTINES
37
38 =over 4
39
40 =item upgrade_config
41
42 =cut
43
44 #config upgrades
45 sub upgrade_config {
46   my %opt = @_;
47
48   my $conf = new FS::Conf;
49
50   $conf->touch('payment_receipt')
51     if $conf->exists('payment_receipt_email')
52     || $conf->config('payment_receipt_msgnum');
53
54   $conf->touch('geocode-require_nw_coordinates')
55     if $conf->exists('svc_broadband-require-nw-coordinates');
56
57   unless ( $conf->config('echeck-country') ) {
58     if ( $conf->exists('cust_main-require-bank-branch') ) {
59       $conf->set('echeck-country', 'CA');
60     } elsif ( $conf->exists('echeck-nonus') ) {
61       $conf->set('echeck-country', 'XX');
62     } else {
63       $conf->set('echeck-country', 'US');
64     }
65   }
66
67   my @agents = qsearch('agent', {});
68
69   upgrade_overlimit_groups($conf);
70   map { upgrade_overlimit_groups($conf,$_->agentnum) } @agents;
71
72   upgrade_invoice_from($conf);
73   foreach my $agent (@agents) {
74     upgrade_invoice_from($conf,$agent->agentnum,1);
75   }
76
77   my $DIST_CONF = '/usr/local/etc/freeside/default_conf/';#DIST_CONF in Makefile
78   $conf->set($_, scalar(read_file( "$DIST_CONF/$_" )) )
79     foreach grep { ! $conf->exists($_) && -s "$DIST_CONF/$_" }
80       qw( quotation_html quotation_latex quotation_latexnotes );
81
82   # change 'fslongtable' to 'longtable'
83   # in invoice and quotation main templates, and also in all secondary 
84   # invoice templates
85   my @latex_confs =
86     qsearch('conf', { 'name' => {op=>'LIKE', value=>'%latex%'} });
87
88   foreach my $c (@latex_confs) {
89     my $value = $c->value;
90     if (length($value) and $value =~ /fslongtable/) {
91       $value =~ s/fslongtable/longtable/g;
92       $conf->set($c->name, $value, $c->agentnum);
93     }
94   }
95
96   # if there's a USPS tools login, assume that's the standardization method
97   # you want to use
98   $conf->set('address_standardize_method', 'usps')
99     if $conf->exists('usps_webtools-userid')
100     && length($conf->config('usps_webtools-userid')) > 0
101     && ! $conf->exists('address_standardize_method');
102
103   # this option has been renamed/expanded
104   if ( $conf->exists('cust_main-enable_spouse_birthdate') ) {
105     $conf->touch('cust_main-enable_spouse');
106     $conf->delete('cust_main-enable_spouse_birthdate');
107   }
108
109   # renamed/repurposed
110   if ( $conf->exists('cust_pkg-show_fcc_voice_grade_equivalent') ) {
111     $conf->touch('part_pkg-show_fcc_options');
112     $conf->delete('cust_pkg-show_fcc_voice_grade_equivalent');
113     warn "
114 You have FCC Form 477 package options enabled.
115
116 Starting with the October 2014 filing date, the FCC has redesigned 
117 Form 477 and introduced new service categories.  See bin/convert-477-options
118 to update your package configuration for the new report.
119
120 If you need to continue using the old Form 477 report, turn on the
121 'old_fcc_report' configuration option.
122 ";
123   }
124
125   # boolean invoice_sections_by_location option is now
126   # invoice_sections_method = 'location'
127   my @invoice_sections_confs =
128     qsearch('conf', { 'name' => { op=>'LIKE', value=>'%sections_by_location' } });
129   foreach my $c (@invoice_sections_confs) {
130     $c->name =~ /^(\w+)sections_by_location$/;
131     $conf->delete($c->name);
132     my $newname = $1.'sections_method';
133     $conf->set($newname, 'location');
134   }
135
136   # boolean enable_taxproducts is now tax_data_vendor = 'cch'
137   if ( $conf->exists('enable_taxproducts') ) {
138
139     $conf->delete('enable_taxproducts');
140     $conf->set('tax_data_vendor', 'cch');
141
142   }
143
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');
148   }
149
150   # boolean+text previous_balance-exclude_from_total is now two separate options
151   my $total_new_charges = $conf->config('previous_balance-exclude_from_total');
152   if (length($total_new_charges) > 0) {
153     $conf->set('previous_balance-text-total_new_charges', $total_new_charges);
154     $conf->set('previous_balance-exclude_from_total', '');
155   }
156
157   # switch from specifying an email address to boolean check
158   if ( $conf->exists('batch-errors_to') ) {
159     $conf->touch('batch-errors_not_fatal');
160     $conf->delete('batch-errors_to');
161   }
162
163   enable_banned_pay_pad() unless length($conf->config('banned_pay-pad'));
164
165 }
166
167 sub upgrade_overlimit_groups {
168     my $conf = shift;
169     my $agentnum = shift;
170     my @groups = $conf->config('overlimit_groups',$agentnum); 
171     if(scalar(@groups)) {
172         my $groups = join(',',@groups);
173         my @groupnums;
174         my $error = '';
175         if ( $groups !~ /^[\d,]+$/ ) {
176             foreach my $groupname ( @groups ) {
177                 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
178                 unless ( $g ) {
179                     $g = new FS::radius_group {
180                                     'groupname' => $groupname,
181                                     'description' => $groupname,
182                                     };
183                     $error = $g->insert;
184                     die $error if $error;
185                 }
186                 push @groupnums, $g->groupnum;
187             }
188             $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
189         }
190     }
191 }
192
193 sub upgrade_invoice_from {
194   my ($conf, $agentnum, $agentonly) = @_;
195   if (
196       (!$conf->exists('invoice_from_name',$agentnum,$agentonly)) && 
197       ($conf->config('invoice_from',$agentnum,$agentonly) =~ /\<(.*)\>/)
198   ) {
199     my $realemail = $1;
200     $realemail =~ s/^\s*//; # remove leading spaces
201     $realemail =~ s/\s*$//; # remove trailing spaces
202     my $realname = $conf->config('invoice_from',$agentnum);
203     $realname =~ s/\<.*\>//; # remove email address
204     $realname =~ s/^\s*//; # remove leading spaces
205     $realname =~ s/\s*$//; # remove trailing spaces
206     # properly quote names that contain punctuation
207     if (($realname =~ /[^[:alnum:][:space:]]/) && ($realname !~ /^\".*\"$/)) {
208       $realname = '"' . $realname . '"';
209     }
210     $conf->set('invoice_from_name', $realname, $agentnum);
211     $conf->set('invoice_from', $realemail, $agentnum);
212   }
213 }
214
215 =item upgrade
216
217 =cut
218
219 sub upgrade {
220   my %opt = @_;
221
222   my $data = upgrade_data(%opt);
223
224   my $oldAutoCommit = $FS::UID::AutoCommit;
225   local $FS::UID::AutoCommit = 0;
226   local $FS::UID::AutoCommit = 0;
227
228   local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
229
230
231   foreach my $table ( keys %$data ) {
232
233     my $class = "FS::$table";
234     eval "use $class;";
235     die $@ if $@;
236
237     if ( $class->can('_upgrade_data') ) {
238       warn "Upgrading $table...\n";
239
240       my $start = time;
241
242       $class->_upgrade_data(%opt);
243
244       # New interface for async upgrades: a class can declare a 
245       # "queueable_upgrade" method, which will run as part of the normal 
246       # upgrade, but if the -j option is passed, will instead be run from 
247       # the job queue.
248       if ( $class->can('queueable_upgrade') ) {
249         my $jobname = $class . '::queueable_upgrade';
250         my $num_jobs = FS::queue->count("job = '$jobname' and status != 'failed'");
251         if ($num_jobs > 0) {
252           warn "$class upgrade already scheduled.\n";
253         } else {
254           if ( $opt{'queue'} ) {
255             warn "Scheduling $class upgrade.\n";
256             my $job = FS::queue->new({ job => $jobname });
257             $job->insert($class, %opt);
258           } else {
259             $class->queueable_upgrade(%opt);
260           }
261         } #$num_jobs == 0
262       }
263
264       if ( $oldAutoCommit ) {
265         warn "  committing\n";
266         dbh->commit or die dbh->errstr;
267       }
268       
269       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
270       warn "  done in ". (time-$start). " seconds\n";
271
272     } else {
273       warn "WARNING: asked for upgrade of $table,".
274            " but FS::$table has no _upgrade_data method\n";
275     }
276
277 #    my @records = @{ $data->{$table} };
278 #
279 #    foreach my $record ( @records ) {
280 #      my $args = delete($record->{'_upgrade_args'}) || [];
281 #      my $object = $class->new( $record );
282 #      my $error = $object->insert( @$args );
283 #      die "error inserting record into $table: $error\n"
284 #        if $error;
285 #    }
286
287   }
288
289   local($FS::cust_main::ignore_expired_card) = 1;
290   #this is long-gone... would need to set an equivalent in cust_location #local($FS::cust_main::ignore_illegal_zip) = 1;
291   local($FS::cust_main::ignore_banned_card) = 1;
292   local($FS::cust_main::skip_fuzzyfiles) = 1;
293
294   local($FS::cust_payby::ignore_expired_card) = 1;
295   local($FS::cust_payby::ignore_banned_card) = 1;
296
297   # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
298   # kind of a weird spot for this, but it's better than duplicating
299   # all this code in each class...
300   my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
301   foreach my $table ( @decrypt_tables ) {
302       my @objects = qsearch({
303         'table'     => $table,
304         'hashref'   => {},
305         'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
306                        " AND LENGTH(payinfo) > 100",
307       });
308       foreach my $object ( @objects ) {
309           my $payinfo = $object->decrypt($object->payinfo);
310           die "error decrypting payinfo" if $payinfo eq $object->payinfo;
311           $object->payinfo($payinfo);
312           my $error = $object->replace;
313           die $error if $error;
314       }
315   }
316
317 }
318
319 =item upgrade_data
320
321 =cut
322
323 sub upgrade_data {
324   my %opt = @_;
325
326   tie my %hash, 'Tie::IxHash', 
327
328     #payby conditions to new ones
329     'part_event_condition' => [],
330
331     #payby actions to new ones
332     'part_event' => [],
333
334     #cust_main (remove paycvv from history, locations, cust_payby, etc)
335     'cust_main' => [],
336
337     #contact -> cust_contact / prospect_contact
338     'contact' => [],
339
340     #msgcat
341     'msgcat' => [],
342
343     #reason type and reasons
344     'reason_type'     => [],
345     'cust_pkg_reason' => [],
346
347     #need part_pkg before cust_credit...
348     'part_pkg' => [],
349
350     #customer credits
351     'cust_credit' => [],
352
353     #duplicate history records
354     'h_cust_svc'  => [],
355
356     #populate cust_pay.otaker
357     'cust_pay'    => [],
358
359     #populate part_pkg_taxclass for starters
360     'part_pkg_taxclass' => [],
361
362     #remove bad pending records
363     'cust_pay_pending' => [],
364
365     #replace invnum and pkgnum with billpkgnum
366     'cust_bill_pkg_detail' => [],
367
368     #usage_classes if we have none
369     'usage_class' => [],
370
371     #phone_type if we have none
372     'phone_type' => [],
373
374     #fixup access rights
375     'access_right' => [],
376
377     #change recur_flat and enable_prorate
378     'part_pkg_option' => [],
379
380     #add weights to pkg_category
381     'pkg_category' => [],
382
383     #cdrbatch fixes
384     'cdr' => [],
385
386     #otaker->usernum
387     'cust_attachment' => [],
388     #'cust_credit' => [],
389     #'cust_main' => [],
390     'cust_main_note' => [],
391     #'cust_pay' => [],
392     'cust_pay_void' => [],
393     'cust_pkg' => [],
394     #'cust_pkg_reason' => [],
395     'cust_pkg_discount' => [],
396     'cust_refund' => [],
397     'banned_pay' => [],
398
399     #default namespace
400     'payment_gateway' => [],
401
402     #migrate to templates
403     'msg_template' => [],
404
405     #return unprovisioned numbers to availability
406     'phone_avail' => [],
407
408     #insert scripcondition
409     'TicketSystem' => [],
410     
411     #insert LATA data if not already present
412     'lata' => [],
413     
414     #insert MSA data if not already present
415     'msa' => [],
416
417     # migrate to radius_group and groupnum instead of groupname
418     'radius_usergroup' => [],
419     'part_svc'         => [],
420     'part_export'      => [],
421
422     #insert default tower_sector if not present
423     'tower' => [],
424
425     #repair improperly deleted services
426     'cust_svc' => [],
427
428     #routernum/blocknum
429     'svc_broadband' => [],
430
431     #set up payment gateways if needed
432     'pay_batch' => [],
433
434     #flag monthly tax exemptions
435     'cust_tax_exempt_pkg' => [],
436
437     #kick off tax location history upgrade
438     'cust_bill_pkg' => [],
439
440     #fix taxable line item links
441     'cust_bill_pkg_tax_location' => [],
442
443     #populate state FIPS codes if not already done
444     'state' => [],
445
446     #set default locations on quoted packages
447     'quotation_pkg' => [],
448
449     #populate tax statuses
450     'tax_status' => [],
451   ;
452
453   \%hash;
454
455 }
456
457 =item upgrade_schema
458
459 =cut
460
461 sub upgrade_schema {
462   my %opt = @_;
463
464   my $data = upgrade_schema_data(%opt);
465
466   my $oldAutoCommit = $FS::UID::AutoCommit;
467   local $FS::UID::AutoCommit = 0;
468   local $FS::UID::AutoCommit = 0;
469
470   foreach my $table ( keys %$data ) {
471
472     my $class = "FS::$table";
473     eval "use $class;";
474     die $@ if $@;
475
476     if ( $class->can('_upgrade_schema') ) {
477       warn "Upgrading $table schema...\n";
478
479       my $start = time;
480
481       $class->_upgrade_schema(%opt);
482
483       if ( $oldAutoCommit ) {
484         warn "  committing\n";
485         dbh->commit or die dbh->errstr;
486       }
487       
488       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
489       warn "  done in ". (time-$start). " seconds\n";
490
491     } else {
492       warn "WARNING: asked for schema upgrade of $table,".
493            " but FS::$table has no _upgrade_schema method\n";
494     }
495
496   }
497
498 }
499
500 =item upgrade_schema_data
501
502 =cut
503
504 sub upgrade_schema_data {
505   my %opt = @_;
506
507   tie my %hash, 'Tie::IxHash', 
508
509     #fix classnum character(1)
510     'cust_bill_pkg_detail' => [],
511     #add necessary columns to RT schema
512     'TicketSystem' => [],
513
514   ;
515
516   \%hash;
517
518 }
519
520 sub upgrade_sqlradius {
521   #my %opt = @_;
522
523   my $conf = new FS::Conf;
524
525   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
526
527   foreach my $part_export ( @part_export ) {
528
529     my $errmsg = 'Error adding FreesideStatus to '.
530                  $part_export->option('datasrc'). ': ';
531
532     my $dbh = DBI->connect(
533       ( map $part_export->option($_), qw ( datasrc username password ) ),
534       { PrintError => 0, PrintWarn => 0 }
535     ) or do {
536       warn $errmsg.$DBI::errstr;
537       next;
538     };
539
540     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
541     my $group = "UserName";
542     $group .= ",Realm"
543       if ref($part_export) =~ /withdomain/
544       || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
545
546     my $sth_alter = $dbh->prepare(
547       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
548     );
549     if ( $sth_alter ) {
550       if ( $sth_alter->execute ) {
551         my $sth_update = $dbh->prepare(
552          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
553         ) or die $errmsg.$dbh->errstr;
554         $sth_update->execute or die $errmsg.$sth_update->errstr;
555       } else {
556         my $error = $sth_alter->errstr;
557         warn $errmsg.$error
558           unless $error =~ /Duplicate column name/i  #mysql
559               || $error =~ /already exists/i;        #Pg
560 ;
561       }
562     } else {
563       my $error = $dbh->errstr;
564       warn $errmsg.$error; #unless $error =~ /exists/i;
565     }
566
567     my $sth_index = $dbh->prepare(
568       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
569     );
570     if ( $sth_index ) {
571       unless ( $sth_index->execute ) {
572         my $error = $sth_index->errstr;
573         warn $errmsg.$error
574           unless $error =~ /Duplicate key name/i #mysql
575               || $error =~ /already exists/i;    #Pg
576       }
577     } else {
578       my $error = $dbh->errstr;
579       warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
580     }
581
582     my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
583       ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
584       : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
585
586     my $sth = $dbh->prepare("SELECT UserName,
587                                     Realm,
588                                     $str2time max(AcctStartTime)),
589                                     $str2time max(AcctStopTime))
590                               FROM radacct
591                               WHERE FreesideStatus = 'done'
592                                 AND $times
593                               GROUP BY $group
594                             ")
595       or die $errmsg.$dbh->errstr;
596     $sth->execute() or die $errmsg.$sth->errstr;
597   
598     while (my $row = $sth->fetchrow_arrayref ) {
599       my ($username, $realm, $start, $stop) = @$row;
600   
601       $username = lc($username) unless $conf->exists('username-uppercase');
602
603       my $exportnum = $part_export->exportnum;
604       my $extra_sql = " AND exportnum = $exportnum ".
605                       " AND exportsvcnum IS NOT NULL ";
606
607       if ( ref($part_export) =~ /withdomain/ ) {
608         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
609                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
610       }
611   
612       my $svc_acct = qsearchs({
613         'select'    => 'svc_acct.*',
614         'table'     => 'svc_acct',
615         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
616                        'LEFT JOIN export_svc USING ( svcpart )',
617         'hashref'   => { 'username' => $username },
618         'extra_sql' => $extra_sql,
619       });
620
621       if ($svc_acct) {
622         $svc_acct->last_login($start)
623           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
624         $svc_acct->last_logout($stop)
625           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
626       }
627     }
628   }
629
630 }
631
632 =back
633
634 =head1 BUGS
635
636 Sure.
637
638 =head1 SEE ALSO
639
640 =cut
641
642 1;
643