yet more timestamping improvements and corrections to reasons based on history records
[freeside.git] / FS / FS / cust_pkg_reason.pm
1 package FS::cust_pkg_reason;
2
3 use strict;
4 use vars qw( @ISA );
5 use FS::Record qw( qsearch qsearchs );
6
7 @ISA = qw(FS::Record);
8
9 =head1 NAME
10
11 FS::cust_pkg_reason - Object methods for cust_pkg_reason records
12
13 =head1 SYNOPSIS
14
15   use FS::cust_pkg_reason;
16
17   $record = new FS::cust_pkg_reason \%hash;
18   $record = new FS::cust_pkg_reason { 'column' => 'value' };
19
20   $error = $record->insert;
21
22   $error = $new_record->replace($old_record);
23
24   $error = $record->delete;
25
26   $error = $record->check;
27
28 =head1 DESCRIPTION
29
30 An FS::cust_pkg_reason object represents a relationship between a cust_pkg
31 and a reason, for example cancellation or suspension reasons. 
32 FS::cust_pkg_reason inherits from FS::Record.  The following fields are
33 currently supported:
34
35 =over 4
36
37 =item num - primary key
38
39 =item pkgnum - 
40
41 =item reasonnum - 
42
43 =item otaker - 
44
45 =item date - 
46
47
48 =back
49
50 =head1 METHODS
51
52 =over 4
53
54 =item new HASHREF
55
56 Creates a new cust_pkg_reason.  To add the example to the database, see
57 L<"insert">.
58
59 Note that this stores the hash reference, not a distinct copy of the hash it
60 points to.  You can ask the object for a copy with the I<hash> method.
61
62 =cut
63
64 sub table { 'cust_pkg_reason'; }
65
66 =item insert
67
68 Adds this record to the database.  If there is an error, returns the error,
69 otherwise returns false.
70
71 =cut
72
73 =item delete
74
75 Delete this record from the database.
76
77 =cut
78
79 =item replace OLD_RECORD
80
81 Replaces the OLD_RECORD with this one in the database.  If there is an error,
82 returns the error, otherwise returns false.
83
84 =cut
85
86 =item check
87
88 Checks all fields to make sure this is a valid cust_pkg_reason.  If there is
89 an error, returns the error, otherwise returns false.  Called by the insert
90 and replace methods.
91
92 =cut
93
94 sub check {
95   my $self = shift;
96
97   my $error = 
98     $self->ut_numbern('num')
99     || $self->ut_number('pkgnum')
100     || $self->ut_number('reasonnum')
101     || $self->ut_enum('action', [ 'A', 'C', 'E', 'S' ])
102     || $self->ut_text('otaker')
103     || $self->ut_numbern('date')
104   ;
105   return $error if $error;
106
107   $self->SUPER::check;
108 }
109
110 =item reason
111
112 Returns the reason (see L<FS::reason>) associated with this cust_pkg_reason.
113
114 =cut
115
116 sub reason {
117   my $self = shift;
118   qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
119 }
120
121 =item reasontext
122
123 Returns the text of the reason (see L<FS::reason>) associated with this
124 cust_pkg_reason.
125
126 =cut
127
128 sub reasontext {
129   my $reason = shift->reason;
130   $reason ? $reason->reason : '';
131 }
132
133 # _upgrade_data
134 #
135 # Used by FS::Upgrade to migrate to a new database.
136
137 sub _upgrade_data { # class method
138   my ($class, %opts) = @_;
139
140   my $test_cust_pkg_reason = new FS::cust_pkg_reason;
141   return '' unless $test_cust_pkg_reason->dbdef_table->column('action');
142
143   my $count = 0;
144   my @unmigrated = qsearch('cust_pkg_reason', { 'action' => '' } ); 
145   foreach ( @unmigrated ) {
146     # we could create h_cust_pkg_reason and h_cust_pkg_reason packages
147     @FS::h_cust_pkg::ISA = qw( FS::h_Common FS::cust_pkg );
148     sub FS::h_cust_pkg::table { 'h_cust_pkg' };
149     @FS::h_cust_pkg_reason::ISA = qw( FS::h_Common FS::cust_pkg_reason );
150     sub FS::h_cust_pkg_reason::table { 'h_cust_pkg_reason' };
151
152     my @history_cust_pkg_reason = qsearch( 'h_cust_pkg_reason', { $_->hash } );
153     
154     next unless scalar(@history_cust_pkg_reason) == 1;
155
156     my %action_value = ( op    => 'LIKE',
157                          value => 'replace_%',
158                        );
159     my $hashref = { pkgnum => $_->pkgnum,
160                     history_date   => $history_cust_pkg_reason[0]->history_date,
161                     history_action => { %action_value },
162                   };
163
164     my @history = qsearch({ table    => 'h_cust_pkg',
165                             hashref  => $hashref,
166                             order_by => 'ORDER BY history_action',
167                          });
168
169     my $fuzz = 0;
170     while (scalar(@history) < 2 && $fuzz < 3) {
171       $hashref->{history_date}++;
172       $hashref->{history_action} = { %action_value }; # qsearch distorts this!
173       $fuzz++;
174       push @history, qsearch({ table    => 'h_cust_pkg',
175                                hashref  => $hashref,
176                                order_by => 'ORDER BY history_action',
177                             });
178     }
179
180     next unless scalar(@history) == 2;
181
182     my @new = grep { $_->history_action eq 'replace_new' } @history;
183     my @old = grep { $_->history_action eq 'replace_old' } @history;
184     
185     next if (scalar(@new) == 2 || scalar(@old) == 2);
186
187     if ( !$old[0]->get('cancel') && $new[0]->get('cancel') ) {
188       $_->action('C');
189     }elsif( !$old[0]->susp && $new[0]->susp ){
190       $_->action('S');
191     }elsif( $new[0]->expire &&
192             (!$old[0]->expire || !$old[0]->expire != $new[0]->expire )
193           ){
194       $_->action('E');
195       $_->date($new[0]->expire);
196     }elsif( $new[0]->adjourn &&
197             (!$old[0]->adjourn || $old[0]->adjourn != $new[0]->adjourn )
198           ){
199       $_->action('A');
200       $_->date($new[0]->adjourn);
201     }
202
203     my $error = $_->replace
204       if $_->modified;
205
206     die $error if $error;
207
208     $count++;
209   }
210
211   #remove nullability if scalar(@migrated) - $count == 0 && ->column('action');
212   
213   #seek expirations/adjourns without reason
214   foreach my $field qw( expire adjourn cancel susp ) {
215     my $addl_from =
216       "LEFT JOIN h_cust_pkg ON ".
217       "(cust_pkg_reason.pkgnum = h_cust_pkg.pkgnum AND".
218       " cust_pkg_reason.date = h_cust_pkg.$field AND".
219       " history_action = 'replace_new')";
220
221     my $extra_sql = 'AND h_cust_pkg.pkgnum IS NULL';
222
223     my @unmigrated = qsearch({ table   => 'cust_pkg_reason',
224                                hashref => { action => uc(substr($field,0,1)) },
225                                addl_from => $addl_from,
226                                select    => 'cust_pkg_reason.*',
227                                extra_sql => $extra_sql,
228                             }); 
229     foreach ( @unmigrated ) {
230       # we could create h_cust_pkg_reason and h_cust_pkg_reason packages
231       @FS::h_cust_pkg::ISA = qw( FS::h_Common FS::cust_pkg );
232       sub FS::h_cust_pkg::table { 'h_cust_pkg' };
233
234       my %action_value = ( op    => 'LIKE',
235                            value => 'replace_%',
236                          );
237       my $hashref = { pkgnum => $_->pkgnum,
238                       history_date   => $_->date,
239                       history_action => { %action_value },
240                     };
241
242       my @history = qsearch({ table    => 'h_cust_pkg',
243                               hashref  => $hashref,
244                               order_by => 'ORDER BY history_action',
245                            });
246
247       my $fuzz = 0;
248       while (scalar(@history) < 2 && $fuzz < 3) {
249         $hashref->{history_date}++;
250         $hashref->{history_action} = { %action_value }; # qsearch distorts this!
251         $fuzz++;
252         push @history, qsearch({ table    => 'h_cust_pkg',
253                                  hashref  => $hashref,
254                                  order_by => 'ORDER BY history_action',
255                               });
256       }
257
258       next unless scalar(@history) == 2;
259
260       my @new = grep { $_->history_action eq 'replace_new' } @history;
261       my @old = grep { $_->history_action eq 'replace_old' } @history;
262     
263       next if (scalar(@new) == 2 || scalar(@old) == 2);
264
265       $_->date($new[0]->get($field))
266         if ( $new[0]->get($field) &&
267              ( !$old[0]->get($field) ||
268                 $old[0]->get($field) != $new[0]->get($field)
269              )
270            );
271
272       my $error = $_->replace
273         if $_->modified;
274
275       die $error if $error;
276     }
277   }
278
279   #seek cancels/suspends without reason, but with expire/adjourn reason
280   foreach my $field qw( cancel susp ) {
281
282     my %precursor_map = ( 'cancel' => 'expire', 'susp' => 'adjourn' );
283     my $precursor = $precursor_map{$field};
284     my $preaction = uc(substr($precursor,0,1));
285     my $action    = uc(substr($field,0,1));
286     my $addl_from =
287       "LEFT JOIN cust_pkg_reason ON ".
288       "(cust_pkg.pkgnum = cust_pkg_reason.pkgnum AND".
289       " cust_pkg.$precursor = cust_pkg_reason.date AND".
290       " cust_pkg_reason.action = '$preaction') ".
291       "LEFT JOIN cust_pkg_reason AS target ON ".
292       "(cust_pkg.pkgnum = target.pkgnum AND".
293       " cust_pkg.$field = target.date AND".
294       " target.action = '$action')"
295     ;
296
297     my $extra_sql = "WHERE target.pkgnum IS NULL AND ".
298                     "cust_pkg.$field IS NOT NULL AND ".
299                     "cust_pkg.$field < cust_pkg.$precursor + 86400 AND ".
300                     "cust_pkg_reason.action = '$preaction'";
301
302     my @unmigrated = qsearch({ table     => 'cust_pkg',
303                                hashref   => { },
304                                select    => 'cust_pkg.*',
305                                addl_from => $addl_from,
306                                extra_sql => $extra_sql,
307                             }); 
308     foreach ( @unmigrated ) {
309       my $cpr = new FS::cust_pkg_reason { $_->last_cust_pkg_reason($precursor)->hash, 'num' => '' };
310       $cpr->date($_->get($field));
311       $cpr->action($action);
312
313       my $error = $cpr->insert;
314       die $error if $error;
315     }
316   }
317
318   '';
319
320 }
321
322 =back
323
324 =head1 BUGS
325
326 Here be termites.  Don't use on wooden computers.
327
328 =head1 SEE ALSO
329
330 L<FS::Record>, schema.html from the base documentation.
331
332 =cut
333
334 1;
335