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