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