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