start of svc_acct events, #13202
[freeside.git] / FS / FS / cust_event.pm
1 package FS::cust_event;
2
3 use strict;
4 use base qw( FS::cust_main_Mixin FS::Record );
5 use vars qw( @ISA $DEBUG $me );
6 use Carp qw( croak confess );
7 use FS::Record qw( qsearch qsearchs dbdef );
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 use FS::svc_acct;
14
15 $DEBUG = 0;
16 $me = '[FS::cust_event]';
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 initial)])
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   $opt{'time'} = $self->_date
195       or die "test_conditions called without cust_event._date\n";
196     # this MUST be set, or all hell breaks loose in event conditions.
197     # it MUST be in the same time as in the cust_event object, or
198     # future time-dependent events will trigger incorrectly.
199
200   #no unsatisfied conditions
201   #! grep ! $_->condition( $object, %opt ), @conditions;
202   my @unsatisfied = grep ! $_->condition( $object, %opt ), @conditions;
203
204   if ( $opt{'stats_hashref'} ) {
205     foreach my $unsat (@unsatisfied) {
206       $opt{'stats_hashref'}->{$unsat->conditionname}++;
207     }
208   } 
209
210   ! @unsatisfied;
211 }
212
213 =item do_event
214
215 Runs the event action.
216
217 =cut
218
219 sub do_event {
220   my $self = shift;
221   my %opt = @_; # currently only 'time'
222   my $time = $opt{'time'} || time;
223
224   my $part_event = $self->part_event;
225
226   my $object = $self->cust_X;
227   my $obj_pkey = $object->primary_key;
228   my $for = "for ". $object->table. " ". $object->$obj_pkey();
229   warn "running cust_event ". $self->eventnum.
230        " (". $part_event->action. ") $for\n"
231     if $DEBUG;
232
233   my $error;
234   {
235     local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
236     $error = eval { $part_event->do_action($object, $self); };
237   }
238
239   my $status = '';
240   my $statustext = '';
241   if ( $@ ) {
242     $status = 'failed';
243     #$statustext = $@;
244     $statustext = "Error running ". $part_event->action. " action: $@";
245   } elsif ( $error ) {
246     $status = 'done';
247     $statustext = $error;
248   } else {
249     $status = 'done';
250   }
251
252   #replace or add myself
253   $self->_date($time);
254   $self->status($status);
255   $self->statustext($statustext);
256
257   $error = $self->eventnum ? $self->replace : $self->insert;
258   if ( $error ) {
259     #this is why we need that locked state...
260     my $e = 'WARNING: Event run but database not updated - '.
261             'error replacing or inserting cust_event '. $self->eventnum.
262             " $for: $error\n";
263     warn $e;
264     return $e;
265   }
266
267   '';
268
269 }
270
271 =item retry
272
273 Changes the status of this event from B<done> to B<failed>, allowing it to be
274 retried.
275
276 =cut
277
278 sub retry {
279   my $self = shift;
280   return '' unless $self->status eq 'done';
281   my $old = ref($self)->new( { $self->hash } );
282   $self->status('failed');
283   $self->replace($old);
284 }
285
286 #=item retryable
287 #
288 #Changes the statustext of this event to B<retriable>, rendering it 
289 #retriable (should retry be called).
290 #
291 #=cut
292
293 sub retriable {
294   confess "cust_event->retriable called";
295   my $self = shift;
296   return '' unless $self->status eq 'done';
297   my $old = ref($self)->new( { $self->hash } );
298   $self->statustext('retriable');
299   $self->replace($old);
300 }
301
302 =item join_sql
303
304 =cut
305
306 sub join_sql {
307   #my $class = shift;
308
309   "
310        JOIN part_event USING ( eventpart )
311   LEFT JOIN cust_bill ON ( eventtable = 'cust_bill' AND tablenum = invnum  )
312   LEFT JOIN cust_pkg  ON ( eventtable = 'cust_pkg'  AND tablenum = pkgnum  )
313
314   LEFT JOIN cust_svc  ON ( eventtable = 'svc_acct'  AND tablenum = svcnum  )
315   LEFT JOIN cust_pkg AS cust_pkg_for_svc ON ( cust_svc.pkgnum = cust_pkg_for_svc.pkgnum )
316   LEFT JOIN cust_main ON (    ( eventtable = 'cust_main' AND tablenum = cust_main.custnum )
317                            OR ( eventtable = 'cust_bill' AND cust_bill.custnum = cust_main.custnum )
318                            OR ( eventtable = 'cust_pkg'  AND cust_pkg.custnum  = cust_main.custnum )
319                            OR ( eventtable = 'svc_acct'  AND cust_pkg_for_svc.custnum  = cust_main.custnum )
320                          )
321   ";
322
323 }
324
325 =item search_sql_where HASHREF
326
327 Class method which returns an SQL WHERE fragment to search for parameters
328 specified in HASHREF.  Valid parameters are
329
330 =over 4
331
332 =item agentnum
333
334 =item custnum
335
336 =item invnum
337
338 =item pkgnum
339
340 =item svcnum
341
342 =item failed
343
344 =item beginning
345
346 =item ending
347
348 =item payby
349
350 =item 
351
352 =back
353
354 =cut
355
356 #Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
357 #sub 
358
359 sub search_sql_where {
360   my($class, $param) = @_;
361   if ( $DEBUG ) {
362     warn "$me search_sql_where called with params: \n".
363          join("\n", map { "  $_: ". $param->{$_} } keys %$param ). "\n";
364   }
365
366   my @search = $class->cust_search_sql($param);
367
368   #eventpart
369   my @eventpart = ref($param->{'eventpart'})
370                     ? @{ $param->{'eventpart'} }
371                     : split(',', $param->{'eventpart'});
372   @eventpart = grep /^(\d+)$/, @eventpart;
373   if ( @eventpart ) {
374     push @search, 'eventpart IN ('. join(',', @eventpart). ')';
375   }
376
377   if ( $param->{'beginning'} =~ /^(\d+)$/ ) {
378     push @search, "cust_event._date >= $1";
379   }
380   if ( $param->{'ending'} =~ /^(\d+)$/ ) {
381     push @search, "cust_event._date <= $1";
382   }
383
384   if ( $param->{'failed'} ) {
385     push @search, "statustext != ''",
386                   "statustext IS NOT NULL",
387                   "statustext != 'N/A'";
388   }
389
390   if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
391     push @search, "cust_main.custnum = '$1'";
392   }
393
394   if ( $param->{'invnum'} =~ /^(\d+)$/ ) {
395     push @search, "part_event.eventtable = 'cust_bill'",
396                   "tablenum = '$1'";
397   }
398
399   if ( $param->{'pkgnum'} =~ /^(\d+)$/ ) {
400     push @search, "part_event.eventtable = 'cust_pkg'",
401                   "tablenum = '$1'";
402   }
403
404   if ( $param->{'svcnum'} =~ /^(\d+)$/ ) {
405     push @search, "part_event.eventtable = 'svc_acct'",
406                   "tablenum = '$1'";
407   }
408
409   my $where = 'WHERE '. join(' AND ', @search );
410
411   join(' AND ', @search );
412
413 }
414
415 =back
416
417 =head1 SUBROUTINES
418
419 =over 4
420
421 =item reprint
422
423 =cut
424
425 sub process_reprint {
426   process_re_X('print', @_);
427 }
428
429 =item reemail
430
431 =cut
432
433 sub process_reemail {
434   process_re_X('email', @_);
435 }
436
437 =item refax
438
439 =cut
440
441 sub process_refax {
442   process_re_X('fax', @_);
443 }
444
445 use Storable qw(thaw);
446 use Data::Dumper;
447 use MIME::Base64;
448 sub process_re_X {
449   my( $method, $job ) = ( shift, shift );
450
451   my $param = thaw(decode_base64(shift));
452   warn Dumper($param) if $DEBUG;
453
454   re_X(
455     $method,
456     $param,
457     $job,
458   );
459
460 }
461
462 sub re_X {
463   my($method, $param, $job) = @_;
464
465   my $search_sql = FS::cust_event->search_sql_where($param);
466
467   #maybe not...?  we do want the "re-" action to match the search more closely
468   #            # yuck!  hardcoded *AND* sequential scans!
469   #my $where = " WHERE action LIKE 'cust_bill_send%' ".
470   #           ( $search_sql ? " AND $search_sql" : "" );
471
472   my $where = ( $search_sql ? " WHERE $search_sql" : "" );
473
474   my @cust_event = qsearch({
475     'table'     => 'cust_event',
476     'addl_from' => FS::cust_event->join_sql(),
477     'hashref'   => {},
478     'extra_sql' => $where,
479   });
480
481   warn "$me re_X found ". scalar(@cust_event). " events\n"
482     if $DEBUG;
483
484   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
485   foreach my $cust_event ( @cust_event ) {
486
487     my $cust_X = $cust_event->cust_X; # cust_bill
488     next unless $cust_X->can($method);
489
490     $cust_X->$method( $cust_event->part_event->templatename
491                       || $cust_X->agent_template
492                     );
493
494     if ( $job ) { #progressbar foo
495       $num++;
496       if ( time - $min_sec > $last ) {
497         my $error = $job->update_statustext(
498           int( 100 * $num / scalar(@cust_event) )
499         );
500         die $error if $error;
501         $last = time;
502       }
503     }
504
505   }
506
507   #this doesn't work, but it would be nice
508   #if ( $job ) { #progressbar foo
509   #  my $error = $job->update_statustext(
510   #    scalar(@cust_event). " invoices re-${method}ed"
511   #  );
512   #  die $error if $error;
513   #}
514
515 }
516
517 =back
518
519 =head1 SEE ALSO
520
521 L<FS::part_event>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
522 base documentation.
523
524 =cut
525
526 1;
527