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