column upgrade for tax_rate RT#4903)
[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 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 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
37
38 =cut
39
40 sub upgrade {
41   my %opt = @_;
42
43   my $data = upgrade_data(%opt);
44
45   foreach my $table ( keys %$data ) {
46
47     my $class = "FS::$table";
48     eval "use $class;";
49     die $@ if $@;
50
51     if ( $class->can('_upgrade_data') ) {
52       warn "Upgrading $table...\n";
53
54       my $start = time;
55
56       my $oldAutoCommit = $FS::UID::AutoCommit;
57       local $FS::UID::AutoCommit = 0;
58       $FS::UID::AutoCommit = 0;
59
60       $class->_upgrade_data(%opt);
61
62       if ( $oldAutoCommit ) {
63         dbh->commit or die dbh->errstr;
64       }
65       
66       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
67       warn "  done in ". (time-$start). " seconds\n";
68
69     } else {
70       warn "WARNING: asked for upgrade of $table,".
71            " but FS::$table has no _upgrade_data method\n";
72     }
73
74 #    my @records = @{ $data->{$table} };
75 #
76 #    foreach my $record ( @records ) {
77 #      my $args = delete($record->{'_upgrade_args'}) || [];
78 #      my $object = $class->new( $record );
79 #      my $error = $object->insert( @$args );
80 #      die "error inserting record into $table: $error\n"
81 #        if $error;
82 #    }
83
84   }
85
86 }
87
88
89 sub upgrade_data {
90   my %opt = @_;
91
92   tie my %hash, 'Tie::IxHash', 
93
94     #msgcat
95     'msgcat' => [],
96
97     #reason type and reasons
98     'reason_type'     => [],
99     'reason'          => [],
100     'cust_pkg_reason' => [],
101
102     #need part_pkg before cust_credit...
103     'part_pkg' => [],
104
105     #customer credits
106     'cust_credit' => [],
107
108     #duplicate history records
109     'h_cust_svc'  => [],
110
111     #populate cust_pay.otaker
112     'cust_pay'    => [],
113
114     #populate part_pkg_taxclass for starters
115     'part_pkg_taxclass' => [],
116
117     #remove bad pending records
118     'cust_pay_pending' => [],
119
120     #replace invnum and pkgnum with billpkgnum
121     'cust_bill_pkg_detail' => [],
122
123     #usage_classes if we have none
124     'usage_class' => [],
125
126     #fixup access rights
127     'access_right' => [],
128
129     #change tax_rate column types
130     'tax_rate' => [],
131
132   ;
133
134   \%hash;
135
136 }
137
138 sub upgrade_sqlradius {
139   #my %opt = @_;
140
141   my $conf = new FS::Conf;
142
143   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
144
145   foreach my $part_export ( @part_export ) {
146
147     my $errmsg = 'Error adding FreesideStatus to '.
148                  $part_export->option('datasrc'). ': ';
149
150     my $dbh = DBI->connect(
151       ( map $part_export->option($_), qw ( datasrc username password ) ),
152       { PrintError => 0, PrintWarn => 0 }
153     ) or do {
154       warn $errmsg.$DBI::errstr;
155       next;
156     };
157
158     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
159     my $group = "UserName";
160     $group .= ",Realm"
161       if ( ref($part_export) =~ /withdomain/ );
162
163     my $sth_alter = $dbh->prepare(
164       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
165     );
166     if ( $sth_alter ) {
167       if ( $sth_alter->execute ) {
168         my $sth_update = $dbh->prepare(
169          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
170         ) or die $errmsg.$dbh->errstr;
171         $sth_update->execute or die $errmsg.$sth_update->errstr;
172       } else {
173         my $error = $sth_alter->errstr;
174         warn $errmsg.$error unless $error =~ /Duplicate column name/i;
175       }
176     } else {
177       my $error = $dbh->errstr;
178       warn $errmsg.$error; #unless $error =~ /exists/i;
179     }
180
181     my $sth_index = $dbh->prepare(
182       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
183     );
184     if ( $sth_index ) {
185       unless ( $sth_index->execute ) {
186         my $error = $sth_index->errstr;
187         warn $errmsg.$error unless $error =~ /Duplicate key name/i;
188       }
189     } else {
190       my $error = $dbh->errstr;
191       warn $errmsg.$error; #unless $error =~ /exists/i;
192     }
193
194     my $sth = $dbh->prepare("SELECT UserName,
195                                     Realm,
196                                     $str2time max(AcctStartTime)),
197                                     $str2time max(AcctStopTime))
198                               FROM radacct
199                               WHERE FreesideStatus = 'done'
200                                 AND AcctStartTime != 0
201                                 AND AcctStopTime  != 0
202                               GROUP BY $group
203                             ")
204       or die $errmsg.$dbh->errstr;
205     $sth->execute() or die $errmsg.$sth->errstr;
206   
207     while (my $row = $sth->fetchrow_arrayref ) {
208       my ($username, $realm, $start, $stop) = @$row;
209   
210       $username = lc($username) unless $conf->exists('username-uppercase');
211
212       my $exportnum = $part_export->exportnum;
213       my $extra_sql = " AND exportnum = $exportnum ".
214                       " AND exportsvcnum IS NOT NULL ";
215
216       if ( ref($part_export) =~ /withdomain/ ) {
217         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
218                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
219       }
220   
221       my $svc_acct = qsearchs({
222         'select'    => 'svc_acct.*',
223         'table'     => 'svc_acct',
224         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
225                        'LEFT JOIN export_svc USING ( svcpart )',
226         'hashref'   => { 'username' => $username },
227         'extra_sql' => $extra_sql,
228       });
229
230       if ($svc_acct) {
231         $svc_acct->last_login($start)
232           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
233         $svc_acct->last_logout($stop)
234           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
235       }
236     }
237   }
238
239 }
240
241 =back
242
243 =head1 BUGS
244
245 Sure.
246
247 =head1 SEE ALSO
248
249 =cut
250
251 1;
252