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