backport fix for too much payment receiptery, RT#9723 / RT#9856
[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_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 }
51
52 =item upgrade
53
54 =cut
55
56 sub upgrade {
57   my %opt = @_;
58
59   my $data = upgrade_data(%opt);
60
61   my $oldAutoCommit = $FS::UID::AutoCommit;
62   local $FS::UID::AutoCommit = 0;
63   local $FS::UID::AutoCommit = 0;
64
65   foreach my $table ( keys %$data ) {
66
67     my $class = "FS::$table";
68     eval "use $class;";
69     die $@ if $@;
70
71     if ( $class->can('_upgrade_data') ) {
72       warn "Upgrading $table...\n";
73
74       my $start = time;
75
76       $class->_upgrade_data(%opt);
77
78       if ( $oldAutoCommit ) {
79         warn "  committing\n";
80         dbh->commit or die dbh->errstr;
81       }
82       
83       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
84       warn "  done in ". (time-$start). " seconds\n";
85
86     } else {
87       warn "WARNING: asked for upgrade of $table,".
88            " but FS::$table has no _upgrade_data method\n";
89     }
90
91 #    my @records = @{ $data->{$table} };
92 #
93 #    foreach my $record ( @records ) {
94 #      my $args = delete($record->{'_upgrade_args'}) || [];
95 #      my $object = $class->new( $record );
96 #      my $error = $object->insert( @$args );
97 #      die "error inserting record into $table: $error\n"
98 #        if $error;
99 #    }
100
101   }
102
103 }
104
105 =item upgrade_data
106
107 =cut
108
109 sub upgrade_data {
110   my %opt = @_;
111
112   tie my %hash, 'Tie::IxHash', 
113
114     #cust_main (remove paycvv from history)
115     'cust_main' => [],
116
117     #msgcat
118     'msgcat' => [],
119
120     #reason type and reasons
121     'reason_type'     => [],
122     'cust_pkg_reason' => [],
123
124     #need part_pkg before cust_credit...
125     'part_pkg' => [],
126
127     #customer credits
128     'cust_credit' => [],
129
130     #duplicate history records
131     'h_cust_svc'  => [],
132
133     #populate cust_pay.otaker
134     'cust_pay'    => [],
135
136     #populate part_pkg_taxclass for starters
137     'part_pkg_taxclass' => [],
138
139     #remove bad pending records
140     'cust_pay_pending' => [],
141
142     #replace invnum and pkgnum with billpkgnum
143     'cust_bill_pkg_detail' => [],
144
145     #usage_classes if we have none
146     'usage_class' => [],
147
148     #fixup access rights
149     'access_right' => [],
150
151     #change recur_flat and enable_prorate
152     'part_pkg_option' => [],
153
154     #add weights to pkg_category
155     'pkg_category' => [],
156
157     #cdrbatch fixes
158     'cdr' => [],
159
160     #default namespace
161     'payment_gateway' => [],
162
163   ;
164
165   \%hash;
166
167 }
168
169 =item upgrade_schema
170
171 =cut
172
173 sub upgrade_schema {
174   my %opt = @_;
175
176   my $data = upgrade_schema_data(%opt);
177
178   my $oldAutoCommit = $FS::UID::AutoCommit;
179   local $FS::UID::AutoCommit = 0;
180   local $FS::UID::AutoCommit = 0;
181
182   foreach my $table ( keys %$data ) {
183
184     my $class = "FS::$table";
185     eval "use $class;";
186     die $@ if $@;
187
188     if ( $class->can('_upgrade_schema') ) {
189       warn "Upgrading $table schema...\n";
190
191       my $start = time;
192
193       $class->_upgrade_schema(%opt);
194
195       if ( $oldAutoCommit ) {
196         warn "  committing\n";
197         dbh->commit or die dbh->errstr;
198       }
199       
200       #warn "\e[1K\rUpgrading $table... done in ". (time-$start). " seconds\n";
201       warn "  done in ". (time-$start). " seconds\n";
202
203     } else {
204       warn "WARNING: asked for schema upgrade of $table,".
205            " but FS::$table has no _upgrade_schema method\n";
206     }
207
208   }
209
210 }
211
212 =item upgrade_schema_data
213
214 =cut
215
216 sub upgrade_schema_data {
217   my %opt = @_;
218
219   tie my %hash, 'Tie::IxHash', 
220
221     #fix classnum character(1)
222     'cust_bill_pkg_detail' => [],
223
224   ;
225
226   \%hash;
227
228 }
229
230 sub upgrade_sqlradius {
231   #my %opt = @_;
232
233   my $conf = new FS::Conf;
234
235   my @part_export = FS::part_export::sqlradius->all_sqlradius_withaccounting();
236
237   foreach my $part_export ( @part_export ) {
238
239     my $errmsg = 'Error adding FreesideStatus to '.
240                  $part_export->option('datasrc'). ': ';
241
242     my $dbh = DBI->connect(
243       ( map $part_export->option($_), qw ( datasrc username password ) ),
244       { PrintError => 0, PrintWarn => 0 }
245     ) or do {
246       warn $errmsg.$DBI::errstr;
247       next;
248     };
249
250     my $str2time = str2time_sql( $dbh->{Driver}->{Name} );
251     my $group = "UserName";
252     $group .= ",Realm"
253       if ref($part_export) =~ /withdomain/
254       || $dbh->{Driver}->{Name} =~ /^Pg/; #hmm
255
256     my $sth_alter = $dbh->prepare(
257       "ALTER TABLE radacct ADD COLUMN FreesideStatus varchar(32) NULL"
258     );
259     if ( $sth_alter ) {
260       if ( $sth_alter->execute ) {
261         my $sth_update = $dbh->prepare(
262          "UPDATE radacct SET FreesideStatus = 'done' WHERE FreesideStatus IS NULL"
263         ) or die $errmsg.$dbh->errstr;
264         $sth_update->execute or die $errmsg.$sth_update->errstr;
265       } else {
266         my $error = $sth_alter->errstr;
267         warn $errmsg.$error
268           unless $error =~ /Duplicate column name/i  #mysql
269               || $error =~ /already exists/i;        #Pg
270 ;
271       }
272     } else {
273       my $error = $dbh->errstr;
274       warn $errmsg.$error; #unless $error =~ /exists/i;
275     }
276
277     my $sth_index = $dbh->prepare(
278       "CREATE INDEX FreesideStatus ON radacct ( FreesideStatus )"
279     );
280     if ( $sth_index ) {
281       unless ( $sth_index->execute ) {
282         my $error = $sth_index->errstr;
283         warn $errmsg.$error
284           unless $error =~ /Duplicate key name/i #mysql
285               || $error =~ /already exists/i;    #Pg
286       }
287     } else {
288       my $error = $dbh->errstr;
289       warn $errmsg.$error. ' (preparing statement)';#unless $error =~ /exists/i;
290     }
291
292     my $times = ($dbh->{Driver}->{Name} =~ /^mysql/)
293       ? ' AcctStartTime != 0 AND AcctStopTime != 0 '
294       : ' AcctStartTime IS NOT NULL AND AcctStopTime IS NOT NULL ';
295
296     my $sth = $dbh->prepare("SELECT UserName,
297                                     Realm,
298                                     $str2time max(AcctStartTime)),
299                                     $str2time max(AcctStopTime))
300                               FROM radacct
301                               WHERE FreesideStatus = 'done'
302                                 AND $times
303                               GROUP BY $group
304                             ")
305       or die $errmsg.$dbh->errstr;
306     $sth->execute() or die $errmsg.$sth->errstr;
307   
308     while (my $row = $sth->fetchrow_arrayref ) {
309       my ($username, $realm, $start, $stop) = @$row;
310   
311       $username = lc($username) unless $conf->exists('username-uppercase');
312
313       my $exportnum = $part_export->exportnum;
314       my $extra_sql = " AND exportnum = $exportnum ".
315                       " AND exportsvcnum IS NOT NULL ";
316
317       if ( ref($part_export) =~ /withdomain/ ) {
318         $extra_sql = " AND '$realm' = ( SELECT domain FROM svc_domain
319                          WHERE svc_domain.svcnum = svc_acct.domsvc ) ";
320       }
321   
322       my $svc_acct = qsearchs({
323         'select'    => 'svc_acct.*',
324         'table'     => 'svc_acct',
325         'addl_from' => 'LEFT JOIN cust_svc   USING ( svcnum )'.
326                        'LEFT JOIN export_svc USING ( svcpart )',
327         'hashref'   => { 'username' => $username },
328         'extra_sql' => $extra_sql,
329       });
330
331       if ($svc_acct) {
332         $svc_acct->last_login($start)
333           if $start && (!$svc_acct->last_login || $start > $svc_acct->last_login);
334         $svc_acct->last_logout($stop)
335           if $stop && (!$svc_acct->last_logout || $stop > $svc_acct->last_logout);
336       }
337     }
338   }
339
340 }
341
342 =back
343
344 =head1 BUGS
345
346 Sure.
347
348 =head1 SEE ALSO
349
350 =cut
351
352 1;
353