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