event refactor, landing on HEAD!
[freeside.git] / FS / FS / cust_event.pm
1 package FS::cust_event;
2
3 use strict;
4 use vars qw( @ISA $DEBUG );
5 use Carp qw( croak confess );
6 use FS::Record qw( qsearch qsearchs dbdef );
7 use FS::cust_main_Mixin;
8 use FS::part_event;
9 #for cust_X
10 use FS::cust_main;
11 use FS::cust_pkg;
12 use FS::cust_bill;
13
14 @ISA = qw(FS::cust_main_Mixin FS::Record);
15
16 $DEBUG = 0;
17
18 =head1 NAME
19
20 FS::cust_event - Object methods for cust_event records
21
22 =head1 SYNOPSIS
23
24   use FS::cust_event;
25
26   $record = new FS::cust_event \%hash;
27   $record = new FS::cust_event { 'column' => 'value' };
28
29   $error = $record->insert;
30
31   $error = $new_record->replace($old_record);
32
33   $error = $record->delete;
34
35   $error = $record->check;
36
37 =head1 DESCRIPTION
38
39 An FS::cust_event object represents an completed event.  FS::cust_event
40 inherits from FS::Record.  The following fields are currently supported:
41
42 =over 4
43
44 =item eventnum - primary key
45
46 =item eventpart - event definition (see L<FS::part_event>)
47
48 =item tablenum - customer, package or invoice, depending on the value of part_event.eventtable (see L<FS::cust_main>, L<FS::cust_pkg>, and L<FS::cust_bill>)
49
50 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
51 L<Time::Local> and L<Date::Parse> for conversion functions.
52
53 =item status - event status: B<new>, B<locked>, B<done> or B<failed>.  Note: B<done> indicates the event is complete and should not be retried (statustext may still be set to an optional message), while B<failed> indicates the event failed and should be retried.
54
55 =item statustext - additional status detail (i.e. error or progress message)
56
57 =back
58
59 =head1 METHODS
60
61 =over 4
62
63 =item new HASHREF
64
65 Creates a new completed invoice event.  To add the compelted invoice event to
66 the database, see L<"insert">.
67
68 Note that this stores the hash reference, not a distinct copy of the hash it
69 points to.  You can ask the object for a copy with the I<hash> method.
70
71 =cut
72
73 # the new method can be inherited from FS::Record, if a table method is defined
74
75 sub table { 'cust_event'; }
76
77 sub cust_linked { $_[0]->cust_main_custnum; } 
78 sub cust_unlinked_msg {
79   my $self = shift;
80   "WARNING: can't find cust_main.custnum ". $self->custnum;
81   #' (cust_bill.invnum '. $self->invnum. ')';
82 }
83 sub custnum {
84   my $self = shift;
85   $self->cust_main_custnum(@_) || $self->SUPER::custnum(@_);
86 }
87
88 =item insert
89
90 Adds this record to the database.  If there is an error, returns the error,
91 otherwise returns false.
92
93 =cut
94
95 # the insert method can be inherited from FS::Record
96
97 =item delete
98
99 Delete this record from the database.
100
101 =cut
102
103 # the delete method can be inherited from FS::Record
104
105 =item replace OLD_RECORD
106
107 Replaces the OLD_RECORD with this one in the database.  If there is an error,
108 returns the error, otherwise returns false.
109
110 =cut
111
112 # the replace method can be inherited from FS::Record
113
114 =item check
115
116 Checks all fields to make sure this is a valid completed invoice event.  If
117 there is an error, returns the error, otherwise returns false.  Called by the
118 insert and replace methods.
119
120 =cut
121
122 # the check method should currently be supplied - FS::Record contains some
123 # data checking routines
124
125 sub check {
126   my $self = shift;
127
128   my $error = $self->ut_numbern('eventnum')
129     || $self->ut_foreign_key('eventpart', 'part_event', 'eventpart')
130   ;
131   return $error if $error;
132
133   my $eventtable = $self->part_event->eventtable;
134   my $dbdef_eventtable = dbdef->table( $eventtable );
135
136   $error = 
137        $self->ut_foreign_key( 'tablenum',
138                               $eventtable,
139                               $dbdef_eventtable->primary_key
140                             )
141     || $self->ut_number('_date')
142     || $self->ut_enum('status', [qw( new locked done failed )])
143     || $self->ut_textn('statustext')
144   ;
145   return $error if $error;
146
147   $self->SUPER::check;
148 }
149
150 =item part_event
151
152 Returns the event definition (see L<FS::part_event>) for this completed event.
153
154 =cut
155
156 sub part_event {
157   my $self = shift;
158   qsearchs( 'part_event', { 'eventpart' => $self->eventpart } );
159 }
160
161 =item cust_X
162
163 Returns the customer, package, invoice or batched payment (see
164 L<FS::cust_main>, L<FS::cust_pkg>, L<FS::cust_bill> or L<FS::cust_pay_batch>)
165 for this completed invoice event.
166
167 =cut
168
169 sub cust_bill {
170   croak "FS::cust_event::cust_bill called";
171 }
172
173 sub cust_X {
174   my $self = shift;
175   my $eventtable = $self->part_event->eventtable;
176   my $dbdef_table = dbdef->table( $eventtable );
177   my $primary_key = $dbdef_table->primary_key;
178   qsearchs( $eventtable, { $primary_key => $self->tablenum } );
179 }
180
181 =item test_conditions [ OPTION => VALUE ... ]
182
183 Tests conditions for this event, returns true if all conditions are satisfied,
184 false otherwise.
185
186 =cut
187
188 sub test_conditions {
189   my( $self, %opt ) = @_;
190   my $part_event = $self->part_event;
191   my $object = $self->cust_X;
192   my @conditions = $part_event->part_event_condition;
193
194   #no unsatisfied conditions
195   #! grep ! $_->condition( $object, %opt ), @conditions;
196   my @unsatisfied = grep ! $_->condition( $object, %opt ), @conditions;
197
198   if ( $opt{'stats_hashref'} ) {
199     foreach my $unsat (@unsatisfied) {
200       $opt{'stats_hashref'}->{$unsat->conditionname}++;
201     }
202   } 
203
204   ! @unsatisfied;
205 }
206
207 =item do_event
208
209 Runs the event action.
210
211 =cut
212
213 sub do_event {
214   my $self = shift;
215
216   my $part_event = $self->part_event;
217
218   my $object = $self->cust_X;
219   my $obj_pkey = $object->primary_key;
220   my $for = "for ". $object->table. " ". $object->$obj_pkey();
221   warn "running cust_event ". $self->eventnum.
222        " (". $part_event->action. ") $for\n"
223     if $DEBUG;
224
225   my $oldAutoCommit = $FS::UID::AutoCommit;
226   local $FS::UID::AutoCommit = 0;
227
228   my $error;
229   {
230     local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
231     $error = eval { $part_event->do_action($object); };
232   }
233
234   my $status = '';
235   my $statustext = '';
236   if ( $@ ) {
237     $status = 'failed';
238     #$statustext = $@;
239     $statustext = "Error running ". $part_event->action. " action: $@";
240   } elsif ( $error ) {
241     $status = 'done';
242     $statustext = $error;
243   } else {
244     $status = 'done';
245   }
246
247   #replace or add myself
248   $self->_date(time);
249   $self->status($status);
250   $self->statustext($statustext);
251
252   $error = $self->eventnum ? $self->replace : $self->insert;
253   if ( $error ) {
254     #this is why we need that locked state...
255     my $e = 'WARNING: Event run but database not updated - '.
256             'error replacing or inserting cust_event '. $self->eventnum.
257             " $for: $error\n";
258     warn $e;
259     return $e;
260   }
261
262   '';
263
264 }
265
266 =item retry
267
268 Changes the status of this event from B<done> to B<failed>, allowing it to be
269 retried.
270
271 =cut
272
273 sub retry {
274   my $self = shift;
275   return '' unless $self->status eq 'done';
276   my $old = ref($self)->new( { $self->hash } );
277   $self->status('failed');
278   $self->replace($old);
279 }
280
281 #=item retryable
282 #
283 #Changes the statustext of this event to B<retriable>, rendering it 
284 #retriable (should retry be called).
285 #
286 #=cut
287
288 sub retriable {
289   confess "cust_event->retriable called";
290   my $self = shift;
291   return '' unless $self->status eq 'done';
292   my $old = ref($self)->new( { $self->hash } );
293   $self->statustext('retriable');
294   $self->replace($old);
295 }
296
297 =back
298
299 =head1 SUBROUTINES
300
301 =over 4
302
303 =item reprint
304
305 =cut
306
307 sub process_reprint {
308   process_re_X('print', @_);
309 }
310
311 =item reemail
312
313 =cut
314
315 sub process_reemail {
316   process_re_X('email', @_);
317 }
318
319 =item refax
320
321 =cut
322
323 sub process_refax {
324   process_re_X('fax', @_);
325 }
326
327 use Storable qw(thaw);
328 use Data::Dumper;
329 use MIME::Base64;
330 sub process_re_X {
331   my( $method, $job ) = ( shift, shift );
332
333   my $param = thaw(decode_base64(shift));
334   warn Dumper($param) if $DEBUG;
335
336   re_X(
337     $method,
338     $param->{'beginning'},
339     $param->{'ending'},
340     $param->{'failed'},
341     $job,
342   );
343
344 }
345
346 sub re_X {
347   my($method, $beginning, $ending, $failed, $job) = @_;
348
349   my $from = 'LEFT JOIN part_event USING ( eventpart )';
350
351               # yuck!  hardcoed *AND* sequential scans!
352   my $where = " WHERE action LIKE 'cust_bill_send%'".
353               "   AND cust_event._date >= $beginning".
354               "   AND cust_event._date <= $ending";
355   $where .= " AND statustext != '' AND statustext IS NOT NULL"
356     if $failed;
357
358   my @cust_event = qsearch({
359     'table'     => 'cust_event',
360     'addl_from' => $from,
361     'hashref'   => {},
362     'extra_sql' => $where,
363   });
364
365   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
366   foreach my $cust_event ( @cust_event ) {
367
368     # XXX 
369     $cust_event->cust_bill->$method(
370       $cust_event->part_event->templatename
371       || $cust_event->cust_main->agent_template
372     );
373
374     if ( $job ) { #progressbar foo
375       $num++;
376       if ( time - $min_sec > $last ) {
377         my $error = $job->update_statustext(
378           int( 100 * $num / scalar(@cust_event) )
379         );
380         die $error if $error;
381         $last = time;
382       }
383     }
384
385   }
386
387   #this doesn't work, but it would be nice
388   #if ( $job ) { #progressbar foo
389   #  my $error = $job->update_statustext(
390   #    scalar(@cust_event). " invoices re-${method}ed"
391   #  );
392   #  die $error if $error;
393   #}
394
395 }
396
397 =back
398
399 =head1 SEE ALSO
400
401 L<FS::part_event>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
402 base documentation.
403
404 =cut
405
406 1;
407