communigate provisioning phase 2: add svc_domain.trailer -> communigate TrailerText...
[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
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; } 
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 )])
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 =cut
154
155 sub part_event {
156   my $self = shift;
157   qsearchs( 'part_event', { 'eventpart' => $self->eventpart } );
158 }
159
160 =item cust_X
161
162 Returns the customer, package, invoice or batched payment (see
163 L<FS::cust_main>, L<FS::cust_pkg>, L<FS::cust_bill> or L<FS::cust_pay_batch>)
164 for this completed invoice event.
165
166 =cut
167
168 sub cust_bill {
169   croak "FS::cust_event::cust_bill called";
170 }
171
172 sub cust_X {
173   my $self = shift;
174   my $eventtable = $self->part_event->eventtable;
175   my $dbdef_table = dbdef->table( $eventtable );
176   my $primary_key = $dbdef_table->primary_key;
177   qsearchs( $eventtable, { $primary_key => $self->tablenum } );
178 }
179
180 =item test_conditions [ OPTION => VALUE ... ]
181
182 Tests conditions for this event, returns true if all conditions are satisfied,
183 false otherwise.
184
185 =cut
186
187 sub test_conditions {
188   my( $self, %opt ) = @_;
189   my $part_event = $self->part_event;
190   my $object = $self->cust_X;
191   my @conditions = $part_event->part_event_condition;
192   $opt{'cust_event'} = $self;
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, $self); };
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 =item join_cust_sql
298
299 =cut
300
301 sub join_sql {
302   #my $class = shift;
303
304   "
305        JOIN part_event USING ( eventpart )
306   LEFT JOIN cust_bill ON ( eventtable = 'cust_bill' AND tablenum = invnum  )
307   LEFT JOIN cust_pkg  ON ( eventtable = 'cust_pkg'  AND tablenum = 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                          )
312   ";
313
314 }
315
316 =item search_sql_where HASHREF
317
318 Class method which returns an SQL WHERE fragment to search for parameters
319 specified in HASHREF.  Valid parameters are
320
321 =over 4
322
323 =item agentnum
324
325 =item custnum
326
327 =item invnum
328
329 =item pkgnum
330
331 =item failed
332
333 =item beginning
334
335 =item ending
336
337 =item payby
338
339 =item 
340
341 =back
342
343 =cut
344
345 #Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
346 #sub 
347
348 sub search_sql_where {
349   my($class, $param) = @_;
350   if ( $DEBUG ) {
351     warn "$me search_sql_where called with params: \n".
352          join("\n", map { "  $_: ". $param->{$_} } keys %$param ). "\n";
353   }
354
355   my @search = $class->cust_search_sql($param);
356
357   #eventpart
358   my @eventpart = ref($param->{'eventpart'})
359                     ? @{ $param->{'eventpart'} }
360                     : split(',', $param->{'eventpart'});
361   @eventpart = grep /^(\d+)$/, @eventpart;
362   if ( @eventpart ) {
363     push @search, 'eventpart IN ('. join(',', @eventpart). ')';
364   }
365
366   if ( $param->{'beginning'} =~ /^(\d+)$/ ) {
367     push @search, "cust_event._date >= $1";
368   }
369   if ( $param->{'ending'} =~ /^(\d+)$/ ) {
370     push @search, "cust_event._date <= $1";
371   }
372
373   if ( $param->{'failed'} ) {
374     push @search, "statustext != ''",
375                   "statustext IS NOT NULL",
376                   "statustext != 'N/A'";
377   }
378
379   if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
380     push @search, "cust_main.custnum = '$1'";
381   }
382
383   if ( $param->{'invnum'} =~ /^(\d+)$/ ) {
384     push @search, "part_event.eventtable = 'cust_bill'",
385                   "tablenum = '$1'";
386   }
387
388   if ( $param->{'pkgnum'} =~ /^(\d+)$/ ) {
389     push @search, "part_event.eventtable = 'cust_pkg'",
390                   "tablenum = '$1'";
391   }
392
393   my $where = 'WHERE '. join(' AND ', @search );
394
395   join(' AND ', @search );
396
397 }
398
399 =back
400
401 =head1 SUBROUTINES
402
403 =over 4
404
405 =item reprint
406
407 =cut
408
409 sub process_reprint {
410   process_re_X('print', @_);
411 }
412
413 =item reemail
414
415 =cut
416
417 sub process_reemail {
418   process_re_X('email', @_);
419 }
420
421 =item refax
422
423 =cut
424
425 sub process_refax {
426   process_re_X('fax', @_);
427 }
428
429 use Storable qw(thaw);
430 use Data::Dumper;
431 use MIME::Base64;
432 sub process_re_X {
433   my( $method, $job ) = ( shift, shift );
434
435   my $param = thaw(decode_base64(shift));
436   warn Dumper($param) if $DEBUG;
437
438   re_X(
439     $method,
440     $param,
441     $job,
442   );
443
444 }
445
446 sub re_X {
447   my($method, $param, $job) = @_;
448
449   my $search_sql = FS::cust_event->search_sql_where($param);
450
451   #maybe not...?  we do want the "re-" action to match the search more closely
452   #            # yuck!  hardcoded *AND* sequential scans!
453   #my $where = " WHERE action LIKE 'cust_bill_send%' ".
454   #           ( $search_sql ? " AND $search_sql" : "" );
455
456   my $where = ( $search_sql ? " WHERE $search_sql" : "" );
457
458   my @cust_event = qsearch({
459     'table'     => 'cust_event',
460     'addl_from' => FS::cust_event->join_sql(),
461     'hashref'   => {},
462     'extra_sql' => $where,
463   });
464
465   warn "$me re_X found ". scalar(@cust_event). " events\n"
466     if $DEBUG;
467
468   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
469   foreach my $cust_event ( @cust_event ) {
470
471     my $cust_X = $cust_event->cust_X; # cust_bill
472     next unless $cust_X->can($method);
473
474     $cust_X->$method( $cust_event->part_event->templatename
475                       || $cust_X->agent_template
476                     );
477
478     if ( $job ) { #progressbar foo
479       $num++;
480       if ( time - $min_sec > $last ) {
481         my $error = $job->update_statustext(
482           int( 100 * $num / scalar(@cust_event) )
483         );
484         die $error if $error;
485         $last = time;
486       }
487     }
488
489   }
490
491   #this doesn't work, but it would be nice
492   #if ( $job ) { #progressbar foo
493   #  my $error = $job->update_statustext(
494   #    scalar(@cust_event). " invoices re-${method}ed"
495   #  );
496   #  die $error if $error;
497   #}
498
499 }
500
501 =back
502
503 =head1 SEE ALSO
504
505 L<FS::part_event>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
506 base documentation.
507
508 =cut
509
510 1;
511