doh!
[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_anything('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   $opt{'cust_event'} = $self;
194
195   #no unsatisfied conditions
196   #! grep ! $_->condition( $object, %opt ), @conditions;
197   my @unsatisfied = grep ! $_->condition( $object, %opt ), @conditions;
198
199   if ( $opt{'stats_hashref'} ) {
200     foreach my $unsat (@unsatisfied) {
201       $opt{'stats_hashref'}->{$unsat->conditionname}++;
202     }
203   } 
204
205   ! @unsatisfied;
206 }
207
208 =item do_event
209
210 Runs the event action.
211
212 =cut
213
214 sub do_event {
215   my $self = shift;
216
217   my $part_event = $self->part_event;
218
219   my $object = $self->cust_X;
220   my $obj_pkey = $object->primary_key;
221   my $for = "for ". $object->table. " ". $object->$obj_pkey();
222   warn "running cust_event ". $self->eventnum.
223        " (". $part_event->action. ") $for\n"
224     if $DEBUG;
225
226   my $oldAutoCommit = $FS::UID::AutoCommit;
227   local $FS::UID::AutoCommit = 0;
228
229   my $error;
230   {
231     local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
232     $error = eval { $part_event->do_action($object); };
233   }
234
235   my $status = '';
236   my $statustext = '';
237   if ( $@ ) {
238     $status = 'failed';
239     #$statustext = $@;
240     $statustext = "Error running ". $part_event->action. " action: $@";
241   } elsif ( $error ) {
242     $status = 'done';
243     $statustext = $error;
244   } else {
245     $status = 'done';
246   }
247
248   #replace or add myself
249   $self->_date(time);
250   $self->status($status);
251   $self->statustext($statustext);
252
253   $error = $self->eventnum ? $self->replace : $self->insert;
254   if ( $error ) {
255     #this is why we need that locked state...
256     my $e = 'WARNING: Event run but database not updated - '.
257             'error replacing or inserting cust_event '. $self->eventnum.
258             " $for: $error\n";
259     warn $e;
260     return $e;
261   }
262
263   '';
264
265 }
266
267 =item retry
268
269 Changes the status of this event from B<done> to B<failed>, allowing it to be
270 retried.
271
272 =cut
273
274 sub retry {
275   my $self = shift;
276   return '' unless $self->status eq 'done';
277   my $old = ref($self)->new( { $self->hash } );
278   $self->status('failed');
279   $self->replace($old);
280 }
281
282 #=item retryable
283 #
284 #Changes the statustext of this event to B<retriable>, rendering it 
285 #retriable (should retry be called).
286 #
287 #=cut
288
289 sub retriable {
290   confess "cust_event->retriable called";
291   my $self = shift;
292   return '' unless $self->status eq 'done';
293   my $old = ref($self)->new( { $self->hash } );
294   $self->statustext('retriable');
295   $self->replace($old);
296 }
297
298 =back
299
300 =head1 SUBROUTINES
301
302 =over 4
303
304 =item reprint
305
306 =cut
307
308 sub process_reprint {
309   process_re_X('print', @_);
310 }
311
312 =item reemail
313
314 =cut
315
316 sub process_reemail {
317   process_re_X('email', @_);
318 }
319
320 =item refax
321
322 =cut
323
324 sub process_refax {
325   process_re_X('fax', @_);
326 }
327
328 use Storable qw(thaw);
329 use Data::Dumper;
330 use MIME::Base64;
331 sub process_re_X {
332   my( $method, $job ) = ( shift, shift );
333
334   my $param = thaw(decode_base64(shift));
335   warn Dumper($param) if $DEBUG;
336
337   re_X(
338     $method,
339     $param->{'beginning'},
340     $param->{'ending'},
341     $param->{'failed'},
342     $job,
343   );
344
345 }
346
347 sub re_X {
348   my($method, $beginning, $ending, $failed, $job) = @_;
349
350   my $from = 'LEFT JOIN part_event USING ( eventpart )';
351
352               # yuck!  hardcoed *AND* sequential scans!
353   my $where = " WHERE action LIKE 'cust_bill_send%'".
354               "   AND cust_event._date >= $beginning".
355               "   AND cust_event._date <= $ending";
356   $where .= " AND statustext != '' AND statustext IS NOT NULL"
357     if $failed;
358
359   my @cust_event = qsearch({
360     'table'     => 'cust_event',
361     'addl_from' => $from,
362     'hashref'   => {},
363     'extra_sql' => $where,
364   });
365
366   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
367   foreach my $cust_event ( @cust_event ) {
368
369     # XXX 
370     $cust_event->cust_bill->$method(
371       $cust_event->part_event->templatename
372       || $cust_event->cust_main->agent_template
373     );
374
375     if ( $job ) { #progressbar foo
376       $num++;
377       if ( time - $min_sec > $last ) {
378         my $error = $job->update_statustext(
379           int( 100 * $num / scalar(@cust_event) )
380         );
381         die $error if $error;
382         $last = time;
383       }
384     }
385
386   }
387
388   #this doesn't work, but it would be nice
389   #if ( $job ) { #progressbar foo
390   #  my $error = $job->update_statustext(
391   #    scalar(@cust_event). " invoices re-${method}ed"
392   #  );
393   #  die $error if $error;
394   #}
395
396 }
397
398 =back
399
400 =head1 SEE ALSO
401
402 L<FS::part_event>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
403 base documentation.
404
405 =cut
406
407 1;
408