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