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