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