add spouse name to customer records, #24919
[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::upgrade_journal;
12
13 use FS::svc_domain;
14 $FS::svc_domain::whois_hack = 1;
15
16 @ISA = qw( Exporter );
17 @EXPORT_OK = qw( upgrade_schema upgrade_config upgrade upgrade_sqlradius );
18
19 $DEBUG = 1;
20
21 =head1 NAME
22
23 FS::Upgrade - Database upgrade routines
24
25 =head1 SYNOPSIS
26
27   use FS::Upgrade;
28
29 =head1 DESCRIPTION
30
31 Currently this module simply provides a place to store common subroutines for
32 database upgrades.
33
34 =head1 SUBROUTINES
35
36 =over 4
37
38 =item upgrade_config
39
40 =cut
41
42 #config upgrades
43 sub upgrade_config {
44   my %opt = @_;
45
46   my $conf = new FS::Conf;
47
48   $conf->touch('payment_receipt')
49     if $conf->exists('payment_receipt_email')
50     || $conf->config('payment_receipt_msgnum');
51
52   $conf->touch('geocode-require_nw_coordinates')
53     if $conf->exists('svc_broadband-require-nw-coordinates');
54
55   unless ( $conf->config('echeck-country') ) {
56     if ( $conf->exists('cust_main-require-bank-branch') ) {
57       $conf->set('echeck-country', 'CA');
58     } elsif ( $conf->exists('echeck-nonus') ) {
59       $conf->set('echeck-country', 'XX');
60     } else {
61       $conf->set('echeck-country', 'US');
62     }
63   }
64
65   upgrade_overlimit_groups($conf);
66   map { upgrade_overlimit_groups($conf,$_->agentnum) } qsearch('agent', {});
67
68   my $DIST_CONF = '/usr/local/etc/freeside/default_conf/';#DIST_CONF in Makefile
69   $conf->set($_, scalar(read_file( "$DIST_CONF/$_" )) )
70     foreach grep { ! $conf->exists($_) && -s "$DIST_CONF/$_" }
71       qw( quotation_html quotation_latex quotation_latexnotes );
72
73   # change 'fslongtable' to 'longtable'
74   # in invoice and quotation main templates, and also in all secondary 
75   # invoice templates
76   my @latex_confs =
77     qsearch('conf', { 'name' => {op=>'LIKE', value=>'%latex%'} });
78
79   foreach my $c (@latex_confs) {
80     my $value = $c->value;
81     if (length($value) and $value =~ /fslongtable/) {
82       $value =~ s/fslongtable/longtable/g;
83       $conf->set($c->name, $value, $c->agentnum);
84     }
85   }
86
87   # if there's a USPS tools login, assume that's the standardization method
88   # you want to use
89   $conf->set('address_standardize_method', 'usps')
90     if $conf->exists('usps_webtools-userid')
91     && length($conf->config('usps_webtools-userid')) > 0
92     && ! $conf->exists('address_standardize_method');
93
94   # this option has been renamed/expanded
95   if ( $conf->exists('cust_main-enable_spouse_birthdate') ) {
96     $conf->touch('cust_main-enable_spouse');
97     $conf->delete('cust_main-enable_spouse_birthdate');
98   }
99 }
100
101 sub upgrade_overlimit_groups {
102     my $conf = shift;
103     my $agentnum = shift;
104     my @groups = $conf->config('overlimit_groups',$agentnum); 
105     if(scalar(@groups)) {
106         my $groups = join(',',@groups);
107         my @groupnums;
108         my $error = '';
109         if ( $groups !~ /^[\d,]+$/ ) {
110             foreach my $groupname ( @groups ) {
111                 my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
112                 unless ( $g ) {
113                     $g = new FS::radius_group {
114                                     'groupname' => $groupname,
115                                     'description' => $groupname,
116                                     };
117                     $error = $g->insert;
118                     die $error if $error;
119                 }
120                 push @groupnums, $g->groupnum;
121             }
122             $conf->set('overlimit_groups',join("\n",@groupnums),$agentnum);
123         }
124     }
125 }
126
127 =item upgrade
128
129 =cut
130
131 sub upgrade {
132   my %opt = @_;
133
134   my $data = upgrade_data(%opt);
135
136   my $oldAutoCommit = $FS::UID::AutoCommit;
137   local $FS::UID::AutoCommit = 0;
138   local $FS::UID::AutoCommit = 0;
139
140   local $FS::cust_pkg::upgrade = 1; #go away after setup+start dates cleaned up for old customers
141
142
143   foreach my $table ( keys %$data ) {
144
145     my $class = "FS::$table";
146     eval "use $class;";
147     die $@ if $@;
148
149     if ( $class->can('_upgrade_data') ) {
150       warn "Upgrading $table...\n";
151
152       my $start = time;
153
154       $class->_upgrade_data(%opt);
155
156       if ( $oldAutoCommit ) {
157         warn "  committing\n";
158         dbh->commit or die dbh->errstr;
159       }
160       
161       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
162       warn "  done in ". (time-$start). " seconds\n";
163
164     } else {
165       warn "WARNING: asked for upgrade of $table,".
166            " but FS::$table has no _upgrade_data method\n";
167     }
168
169 #    my @records = @{ $data->{$table} };
170 #
171 #    foreach my $record ( @records ) {
172 #      my $args = delete($record->{'_upgrade_args'}) || [];
173 #      my $object = $class->new( $record );
174 #      my $error = $object->insert( @$args );
175 #      die "error inserting record into $table: $error\n"
176 #        if $error;
177 #    }
178
179   }
180
181   local($FS::cust_main::ignore_expired_card) = 1;
182   local($FS::cust_main::ignore_illegal_zip) = 1;
183   local($FS::cust_main::ignore_banned_card) = 1;
184   local($FS::cust_main::skip_fuzzyfiles) = 1;
185
186   local($FS::cust_payby::ignore_expired_card) = 1;
187   local($FS::cust_payby::ignore_banned_card) = 1;
188
189   # decrypt inadvertantly-encrypted payinfo where payby != CARD,DCRD,CHEK,DCHK
190   # kind of a weird spot for this, but it's better than duplicating
191   # all this code in each class...
192   my @decrypt_tables = qw( cust_main cust_pay_void cust_pay cust_refund cust_pay_pending );
193   foreach my $table ( @decrypt_tables ) {
194       my @objects = qsearch({
195         'table'     => $table,
196         'hashref'   => {},
197         'extra_sql' => "WHERE payby NOT IN ( 'CARD', 'DCRD', 'CHEK', 'DCHK' ) ".
198                        " AND LENGTH(payinfo) > 100",
199       });
200       foreach my $object ( @objects ) {
201           my $payinfo = $object->decrypt($object->payinfo);
202           die "error decrypting payinfo" if $payinfo eq $object->payinfo;
203           $object->payinfo($payinfo);
204           my $error = $object->replace;
205           die $error if $error;
206       }
207   }
208
209 }
210
211 =item upgrade_data
212
213 =cut
214
215 sub upgrade_data {
216   my %opt = @_;
217
218   tie my %hash, 'Tie::IxHash', 
219
220     #cust_main (remove paycvv from history)
221     'cust_main' => [],
222
223     #msgcat
224     'msgcat' => [],
225
226     #reason type and reasons
227     'reason_type'     => [],
228     'cust_pkg_reason' => [],
229
230     #need part_pkg before cust_credit...
231     'part_pkg' => [],
232
233     #customer credits
234     'cust_credit' => [],
235
236     #duplicate history records
237     'h_cust_svc'  => [],
238
239     #populate cust_pay.otaker
240     'cust_pay'    => [],
241
242     #populate part_pkg_taxclass for starters
243     'part_pkg_taxclass' => [],
244
245     #remove bad pending records
246     'cust_pay_pending' => [],
247
248     #replace invnum and pkgnum with billpkgnum
249     'cust_bill_pkg_detail' => [],
250
251     #usage_classes if we have none
252     'usage_class' => [],
253
254     #phone_type if we have none
255     'phone_type' => [],
256
257     #fixup access rights
258     'access_right' => [],
259
260     #change recur_flat and enable_prorate
261     'part_pkg_option' => [],
262
263     #add weights to pkg_category
264     'pkg_category' => [],
265
266     #cdrbatch fixes
267     'cdr' => [],
268
269     #otaker->usernum
270     'cust_attachment' => [],
271     #'cust_credit' => [],
272     #'cust_main' => [],
273     'cust_main_note' => [],
274     #'cust_pay' => [],
275     'cust_pay_void' => [],
276     'cust_pkg' => [],
277     #'cust_pkg_reason' => [],
278     'cust_pkg_discount' => [],
279     'cust_refund' => [],
280     'banned_pay' => [],
281
282     #default namespace
283     'payment_gateway' => [],
284
285     #migrate to templates
286     'msg_template' => [],
287
288     #return unprovisioned numbers to availability
289     'phone_avail' => [],
290
291     #insert scripcondition
292     'TicketSystem' => [],
293     
294     #insert LATA data if not already present
295     'lata' => [],
296     
297     #insert MSA data if not already present
298     'msa' => [],
299
300     # migrate to radius_group and groupnum instead of groupname
301     'radius_usergroup' => [],
302     'part_svc'         => [],
303     'part_export'      => [],
304
305     #insert default tower_sector if not present
306     'tower' => [],
307
308     #repair improperly deleted services
309     'cust_svc' => [],
310
311     #routernum/blocknum
312     'svc_broadband' => [],
313
314     #set up payment gateways if needed
315     'pay_batch' => [],
316
317     #flag monthly tax exemptions
318     'cust_tax_exempt_pkg' => [],
319
320     #kick off tax location history upgrade
321     'cust_bill_pkg' => [],
322
323     #fix taxable line item links
324     'cust_bill_pkg_tax_location' => [],
325   ;
326
327   \%hash;
328
329 }
330
331 =item upgrade_schema
332
333 =cut
334
335 sub upgrade_schema {
336   my %opt = @_;
337
338   my $data = upgrade_schema_data(%opt);
339
340   my $oldAutoCommit = $FS::UID::AutoCommit;
341   local $FS::UID::AutoCommit = 0;
342   local $FS::UID::AutoCommit = 0;
343
344   foreach my $table ( keys %$data ) {
345
346     my $class = "FS::$table";
347     eval "use $class;";
348     die $@ if $@;
349
350     if ( $class->can('_upgrade_schema') ) {
351       warn "Upgrading $table schema...\n";
352
353       my $start = time;
354
355       $class->_upgrade_schema(%opt);
356
357       if ( $oldAutoCommit ) {
358         warn "  committing\n";
359         dbh->commit or die dbh->errstr;
360       }
361       
362       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
363       warn "  done in ". (time-$start). " seconds\n";
364
365     } else {
366       warn "WARNING: asked for schema upgrade of $table,".
367            " but FS::$table has no _upgrade_schema method\n";
368     }
369
370   }
371
372 }
373
374 =item upgrade_schema_data
375
376 =cut
377
378 sub upgrade_schema_data {
379   my %opt = @_;
380
381   tie my %hash, 'Tie::IxHash', 
382
383     #fix classnum character(1)
384     'cust_bill_pkg_detail' => [],
385     #add necessary columns to RT schema
386     'TicketSystem' => [],
387
388   ;
389
390   \%hash;
391
392 }
393
394 sub upgrade_sqlradius {
395   #my %opt = @_;
396
397   my $conf = new FS::Conf;
398
399   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
400
401   foreach my $part_export ( @part_export ) {
402
403     my $errmsg = 'Error adding FreesideStatus to '.
404                  $part_export->option('datasrc'). ': ';
405
406     my $dbh = DBI->connect(
407       ( map $part_export->option($_), qw ( datasrc username password ) ),
408       { PrintError => 0, PrintWarn => 0 }
409     ) or do {
410       warn $errmsg.$DBI::errstr;
411       next;
412     };
413
414     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
415     my $group = "UserName";
416     $group .= ",Realm"
417       if ref($part_export) =~ /withdomain/
418       || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
419
420     my $sth_alter = $dbh->prepare(
421       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
422     );
423     if ( $sth_alter ) {
424       if ( $sth_alter->execute ) {
425         my $sth_update = $dbh->prepare(
426          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
427         ) or die $errmsg.$dbh->errstr;
428         $sth_update->execute or die $errmsg.$sth_update->errstr;
429       } else {
430         my $error = $sth_alter->errstr;
431         warn $errmsg.$error
432           unless $error =~ /Duplicate column name/i  #mysql
433               || $error =~ /already exists/i;        #Pg
434 ;
435       }
436     } else {
437       my $error = $dbh->errstr;
438       warn $errmsg.$error; #unless $error =~ /exists/i;
439     }
440
441     my $sth_index = $dbh->prepare(
442       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
443     );
444     if ( $sth_index ) {
445       unless ( $sth_index->execute ) {
446         my $error = $sth_index->errstr;
447         warn $errmsg.$error
448           unless $error =~ /Duplicate key name/i #mysql
449               || $error =~ /already exists/i;    #Pg
450       }
451     } else {
452       my $error = $dbh->errstr;
453       warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
454     }
455
456     my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
457       ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
458       : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
459
460     my $sth = $dbh->prepare("SELECT UserName,
461                                     Realm,
462                                     $str2time max(AcctStartTime)),
463                                     $str2time max(AcctStopTime))
464                               FROM radacct
465                               WHERE FreesideStatus = 'done'
466                                 AND $times
467                               GROUP BY $group
468                             ")
469       or die $errmsg.$dbh->errstr;
470     $sth->execute() or die $errmsg.$sth->errstr;
471   
472     while (my $row = $sth->fetchrow_arrayref ) {
473       my ($username, $realm, $start, $stop) = @$row;
474   
475       $username = lc($username) unless $conf->exists('username-uppercase');
476
477       my $exportnum = $part_export->exportnum;
478       my $extra_sql = " AND exportnum = $exportnum ".
479                       " AND exportsvcnum IS NOT NULL ";
480
481       if ( ref($part_export) =~ /withdomain/ ) {
482         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
483                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
484       }
485   
486       my $svc_acct = qsearchs({
487         'select'    => 'svc_acct.*',
488         'table'     => 'svc_acct',
489         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
490                        'LEFT JOIN export_svc USING ( svcpart )',
491         'hashref'   => { 'username' => $username },
492         'extra_sql' => $extra_sql,
493       });
494
495       if ($svc_acct) {
496         $svc_acct->last_login($start)
497           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
498         $svc_acct->last_logout($stop)
499           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
500       }
501     }
502   }
503
504 }
505
506 =back
507
508 =head1 BUGS
509
510 Sure.
511
512 =head1 SEE ALSO
513
514 =cut
515
516 1;
517