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