eliminate some false laziness in FS::Misc::send_email vs. msg_template/email.pm send_...
[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::cust_pay;
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 =item no_action - 'Y' if the event action wasn't performed. Some actions
58 contain an internal check to see if the action is going to be impossible (for
59 example, emailing a notice to a customer who has no email address), and if so,
60 won't attempt the action. It shouldn't be reported as a failure because
61 there's no need to retry it. However, the action should set no_action = 'Y'
62 so that there's a record.
63
64 =back
65
66 =head1 METHODS
67
68 =over 4
69
70 =item new HASHREF
71
72 Creates a new completed invoice event.  To add the compelted invoice event to
73 the database, see L<"insert">.
74
75 Note that this stores the hash reference, not a distinct copy of the hash it
76 points to.  You can ask the object for a copy with the I<hash> method.
77
78 =cut
79
80 # the new method can be inherited from FS::Record, if a table method is defined
81
82 sub table { 'cust_event'; }
83
84 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum } 
85 sub cust_unlinked_msg {
86   my $self = shift;
87   "WARNING: can't find cust_main.custnum ". $self->custnum;
88   #' (cust_bill.invnum '. $self->invnum. ')';
89 }
90 sub custnum {
91   my $self = shift;
92   $self->cust_main_custnum(@_) || $self->SUPER::custnum(@_);
93 }
94
95 =item insert
96
97 Adds this record to the database.  If there is an error, returns the error,
98 otherwise returns false.
99
100 =cut
101
102 # the insert method can be inherited from FS::Record
103
104 =item delete
105
106 Delete this record from the database.
107
108 =cut
109
110 # the delete method can be inherited from FS::Record
111
112 =item replace OLD_RECORD
113
114 Replaces the OLD_RECORD with this one in the database.  If there is an error,
115 returns the error, otherwise returns false.
116
117 =cut
118
119 # the replace method can be inherited from FS::Record
120
121 =item check
122
123 Checks all fields to make sure this is a valid completed invoice event.  If
124 there is an error, returns the error, otherwise returns false.  Called by the
125 insert and replace methods.
126
127 =cut
128
129 # the check method should currently be supplied - FS::Record contains some
130 # data checking routines
131
132 sub check {
133   my $self = shift;
134
135   my $error = $self->ut_numbern('eventnum')
136     || $self->ut_foreign_key('eventpart', 'part_event', 'eventpart')
137   ;
138   return $error if $error;
139
140   my $eventtable = $self->part_event->eventtable;
141   my $dbdef_eventtable = dbdef->table( $eventtable );
142
143   $error = 
144        $self->ut_foreign_key( 'tablenum',
145                               $eventtable,
146                               $dbdef_eventtable->primary_key
147                             )
148     || $self->ut_number('_date')
149     || $self->ut_enum('status', [qw( new locked done failed initial)])
150     || $self->ut_anything('statustext')
151     || $self->ut_flag('no_action')
152   ;
153   return $error if $error;
154
155   $self->SUPER::check;
156 }
157
158 =item part_event
159
160 Returns the event definition (see L<FS::part_event>) for this completed event.
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   $opt{'time'} = $self->_date
196       or die "test_conditions called without cust_event._date\n";
197     # this MUST be set, or all hell breaks loose in event conditions.
198     # it MUST be in the same time as in the cust_event object, or
199     # future time-dependent events will trigger incorrectly.
200
201   #no unsatisfied conditions
202   #! grep ! $_->condition( $object, %opt ), @conditions;
203   my @unsatisfied = grep ! $_->condition( $object, %opt ), @conditions;
204
205   if ( $opt{'stats_hashref'} ) {
206     foreach my $unsat (@unsatisfied) {
207       $opt{'stats_hashref'}->{$unsat->conditionname}++;
208     }
209   } 
210
211   ! @unsatisfied;
212 }
213
214 =item do_event
215
216 Runs the event action.
217
218 =cut
219
220 sub do_event {
221   my $self = shift;
222   my %opt = @_; # currently only 'time'
223   my $time = $opt{'time'} || time;
224
225   my $part_event = $self->part_event;
226
227   my $object = $self->cust_X;
228   my $obj_pkey = $object->primary_key;
229   my $for = "for ". $object->table. " ". $object->$obj_pkey();
230   warn "running cust_event ". $self->eventnum.
231        " (". $part_event->action. ") $for\n"
232     if $DEBUG;
233
234   my $error;
235   {
236     local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
237     $error = eval { $part_event->do_action($object, $self); };
238   }
239
240   my $status = '';
241   my $statustext = '';
242   if ( $@ ) {
243     $status = 'failed';
244     #$statustext = $@;
245     $statustext = "Error running ". $part_event->action. " action: $@";
246   } elsif ( $error ) {
247     $status = 'done';
248     if ( $error eq 'N/A' ) {
249       # archaic way to indicate no-op completion of spool_csv (and maybe
250       # other events)?
251       $self->no_action('Y');
252     } else {
253       $statustext = $error;
254     }
255   } else {
256     $status = 'done';
257   }
258
259   #replace or add myself
260   $self->_date($time);
261   $self->status($status);
262   $self->statustext($statustext);
263
264   $error = $self->eventnum ? $self->replace : $self->insert;
265   if ( $error ) {
266     #this is why we need that locked state...
267     my $e = 'WARNING: Event run but database not updated - '.
268             'error replacing or inserting cust_event '. $self->eventnum.
269             " $for: $error\n";
270     warn $e;
271     return $e;
272   }
273
274   '';
275
276 }
277
278 =item retry
279
280 Changes the status of this event from B<done> to B<failed>, allowing it to be
281 retried.
282
283 =cut
284
285 sub retry {
286   my $self = shift;
287   return '' unless $self->status eq 'done';
288   my $old = ref($self)->new( { $self->hash } );
289   $self->status('failed');
290   $self->replace($old);
291 }
292
293 #=item retryable
294 #
295 #Changes the statustext of this event to B<retriable>, rendering it 
296 #retriable (should retry be called).
297 #
298 #=cut
299
300 sub retriable {
301   confess "cust_event->retriable called";
302   my $self = shift;
303   return '' unless $self->status eq 'done';
304   my $old = ref($self)->new( { $self->hash } );
305   $self->statustext('retriable');
306   $self->replace($old);
307 }
308
309 =item join_sql
310
311 =cut
312
313 sub join_sql {
314   #my $class = shift;
315
316   "
317        JOIN part_event USING ( eventpart )
318
319   LEFT JOIN cust_bill ON ( eventtable = 'cust_bill' AND tablenum = cust_bill.invnum  )
320   LEFT JOIN cust_pkg  ON ( eventtable = 'cust_pkg'  AND tablenum = cust_pkg.pkgnum  )
321   LEFT JOIN cust_pay  ON ( eventtable = 'cust_pay'  AND tablenum = cust_pay.paynum  )
322   LEFT JOIN cust_pay_batch ON ( eventtable = 'cust_pay_batch' AND tablenum = cust_pay_batch.paybatchnum )
323   LEFT JOIN cust_statement ON ( eventtable = 'cust_statement' AND tablenum = cust_statement.statementnum )
324
325   LEFT JOIN cust_svc  ON ( eventtable = 'svc_acct'  AND tablenum = cust_svc.svcnum  )
326   LEFT JOIN cust_pkg AS cust_pkg_for_svc ON ( cust_svc.pkgnum = cust_pkg_for_svc.pkgnum )
327
328   LEFT JOIN cust_main ON (
329        ( eventtable = 'cust_main' AND tablenum = cust_main.custnum )
330     OR ( eventtable = 'cust_bill' AND cust_bill.custnum = cust_main.custnum )
331     OR ( eventtable = 'cust_pkg'  AND cust_pkg.custnum  = cust_main.custnum )
332     OR ( eventtable = 'cust_pay'  AND cust_pay.custnum  = cust_main.custnum )
333     OR ( eventtable = 'svc_acct'  AND cust_pkg_for_svc.custnum  = cust_main.custnum )
334   )
335   ";
336
337 }
338
339 =item search_sql_where HASHREF
340
341 Class method which returns an SQL WHERE fragment to search for parameters
342 specified in HASHREF.  Valid parameters are
343
344 =over 4
345
346 =item agentnum
347
348 =item custnum
349
350 =item invnum
351
352 =item pkgnum
353
354 =item svcnum
355
356 =item failed
357
358 =item beginning
359
360 =item ending
361
362 =back
363
364 =cut
365
366 #Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
367 #sub 
368
369 sub search_sql_where {
370   my($class, $param) = @_;
371   if ( $DEBUG ) {
372     warn "$me search_sql_where called with params: \n".
373          join("\n", map { "  $_: ". $param->{$_} } keys %$param ). "\n";
374   }
375
376   my @search = $class->cust_search_sql($param);
377
378   #eventpart
379   my @eventpart = ref($param->{'eventpart'})
380                     ? @{ $param->{'eventpart'} }
381                     : split(',', $param->{'eventpart'});
382   @eventpart = grep /^(\d+)$/, @eventpart;
383   if ( @eventpart ) {
384     push @search, 'eventpart IN ('. join(',', @eventpart). ')';
385   }
386
387   if ( $param->{'beginning'} =~ /^(\d+)$/ ) {
388     push @search, "cust_event._date >= $1";
389   }
390   if ( $param->{'ending'} =~ /^(\d+)$/ ) {
391     push @search, "cust_event._date <= $1";
392   }
393
394   #if ( $param->{'failed'} ) {
395   #  push @search, "statustext != ''",
396   #                "statustext IS NOT NULL",
397   #                "statustext != 'N/A'";
398   #}
399   # huh?
400
401   my @event_status = ref($param->{'event_status'})
402                     ? @{ $param->{'event_status'} }
403                     : split(',', $param->{'event_status'});
404   if ( @event_status ) {
405     my @status;
406
407     my ($done_Y, $done_N, $done_S);
408     # done_Y: action was taken
409     # done_N: action was not taken
410     # done_S: status message returned
411     foreach (@event_status) {
412       if ($_ eq 'done_Y') {
413         $done_Y = 1;
414       } elsif ( $_ eq 'done_N' ) {
415         $done_N = 1;
416       } elsif ( $_ eq 'done_S' ) {
417         $done_S = 1;
418       } else {
419         push @status, $_;
420       }
421     }
422     if ( $done_Y or $done_N or $done_S ) {
423       push @status, 'done';
424     }
425     if ( @status ) {
426       push @search, "cust_event.status IN(" .
427                     join(',', map "'$_'", @status) .
428                     ')';
429     }
430
431     # done_S status should include only those where statustext is not null,
432     # and done_Y should include only those where it is.
433     if ( $done_Y and $done_N and $done_S ) {
434       # then not necessary
435     } else {
436       my @done_status;
437       if ( $done_Y ) {
438         push @done_status, "(cust_event.no_action IS NULL AND cust_event.statustext IS NULL)";
439       }
440       if ( $done_N ) {
441         push @done_status, "(cust_event.no_action = 'Y')";
442       }
443       if ( $done_S ) {
444         push @done_status, "(cust_event.no_action IS NULL AND cust_event.statustext IS NOT NULL)";
445       }
446       push @search, join(' OR ', @done_status) if @done_status;
447     }
448
449   } # event_status
450
451   # always hide initialization
452   push @search, 'cust_event.status != \'initial\'';
453
454   if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
455     push @search, "cust_main.custnum = '$1'";
456   }
457
458   if ( $param->{'invnum'} =~ /^(\d+)$/ ) {
459     push @search, "part_event.eventtable = 'cust_bill'",
460                   "tablenum = '$1'";
461   }
462
463   if ( $param->{'pkgnum'} =~ /^(\d+)$/ ) {
464     push @search, "part_event.eventtable = 'cust_pkg'",
465                   "tablenum = '$1'";
466   }
467
468   if ( $param->{'paynum'} =~ /^(\d+)$/ ) {
469     push @search, "part_event.eventtable = 'cust_pay'",
470                   "tablenum = '$1'";
471   }
472
473   if ( $param->{'svcnum'} =~ /^(\d+)$/ ) {
474     push @search, "part_event.eventtable = 'svc_acct'",
475                   "tablenum = '$1'";
476   }
477
478   my $where = 'WHERE '. join(' AND ', @search );
479
480   join(' AND ', @search );
481
482 }
483
484 =back
485
486 =head1 SUBROUTINES
487
488 =over 4
489
490 =item reprint
491
492 =cut
493
494 sub process_reprint {
495   process_re_X('print', @_);
496 }
497
498 =item reemail
499
500 =cut
501
502 sub process_reemail {
503   process_re_X('email', @_);
504 }
505
506 =item refax
507
508 =cut
509
510 sub process_refax {
511   process_re_X('fax', @_);
512 }
513
514 use Data::Dumper;
515 sub process_re_X {
516   my( $method, $job, $param ) = @_;
517   warn Dumper($param) if $DEBUG;
518
519   re_X(
520     $method,
521     $param,
522     $job,
523   );
524
525 }
526
527 sub re_X {
528   my($method, $param, $job) = @_;
529
530   my $search_sql = FS::cust_event->search_sql_where($param);
531
532   #maybe not...?  we do want the "re-" action to match the search more closely
533   #            # yuck!  hardcoded *AND* sequential scans!
534   #my $where = " WHERE action LIKE 'cust_bill_send%' ".
535   #           ( $search_sql ? " AND $search_sql" : "" );
536
537   my $where = ( $search_sql ? " WHERE $search_sql" : "" );
538
539   my @cust_event = qsearch({
540     'table'     => 'cust_event',
541     'addl_from' => FS::cust_event->join_sql(),
542     'hashref'   => {},
543     'extra_sql' => $where,
544   });
545
546   warn "$me re_X found ". scalar(@cust_event). " events\n"
547     if $DEBUG;
548
549   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
550   foreach my $cust_event ( @cust_event ) {
551
552     my $cust_X = $cust_event->cust_X; # cust_bill
553     next unless $cust_X->can($method);
554
555     my $part_event = $cust_event->part_event;
556     my $template = $part_event->templatename
557                    || $cust_X->agent_template;
558     my $modenum = $part_event->option('modenum') || '';
559     my $invoice_from = $part_event->option('agent_invoice_from') || '';
560     $cust_X->set('mode' => $modenum);
561     $cust_X->$method( { template => $template,
562                         modenum  => $modenum,
563                         from     => $invoice_from,
564                     } );
565
566     if ( $job ) { #progressbar foo
567       $num++;
568       if ( time - $min_sec > $last ) {
569         my $error = $job->update_statustext(
570           int( 100 * $num / scalar(@cust_event) )
571         );
572         die $error if $error;
573         $last = time;
574       }
575     }
576
577   }
578
579   #this doesn't work, but it would be nice
580   #if ( $job ) { #progressbar foo
581   #  my $error = $job->update_statustext(
582   #    scalar(@cust_event). " invoices re-${method}ed"
583   #  );
584   #  die $error if $error;
585   #}
586
587 }
588
589 =back
590
591 =head1 SEE ALSO
592
593 L<FS::part_event>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
594 base documentation.
595
596 =cut
597
598 1;
599