fix searches for cust_pay events, RT#35167
[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 =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 || $_[0]->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 =item cust_X
155
156 Returns the customer, package, invoice or batched payment (see
157 L<FS::cust_main>, L<FS::cust_pkg>, L<FS::cust_bill> or L<FS::cust_pay_batch>)
158 for this completed invoice event.
159
160 =cut
161
162 sub cust_bill {
163   croak "FS::cust_event::cust_bill called";
164 }
165
166 sub cust_X {
167   my $self = shift;
168   my $eventtable = $self->part_event->eventtable;
169   my $dbdef_table = dbdef->table( $eventtable );
170   my $primary_key = $dbdef_table->primary_key;
171   qsearchs( $eventtable, { $primary_key => $self->tablenum } );
172 }
173
174 =item test_conditions [ OPTION => VALUE ... ]
175
176 Tests conditions for this event, returns true if all conditions are satisfied,
177 false otherwise.
178
179 =cut
180
181 sub test_conditions {
182   my( $self, %opt ) = @_;
183   my $part_event = $self->part_event;
184   my $object = $self->cust_X;
185   my @conditions = $part_event->part_event_condition;
186   $opt{'cust_event'} = $self;
187   $opt{'time'} = $self->_date
188       or die "test_conditions called without cust_event._date\n";
189     # this MUST be set, or all hell breaks loose in event conditions.
190     # it MUST be in the same time as in the cust_event object, or
191     # future time-dependent events will trigger incorrectly.
192
193   #no unsatisfied conditions
194   #! grep ! $_->condition( $object, %opt ), @conditions;
195   my @unsatisfied = grep ! $_->condition( $object, %opt ), @conditions;
196
197   if ( $opt{'stats_hashref'} ) {
198     foreach my $unsat (@unsatisfied) {
199       $opt{'stats_hashref'}->{$unsat->conditionname}++;
200     }
201   } 
202
203   ! @unsatisfied;
204 }
205
206 =item do_event
207
208 Runs the event action.
209
210 =cut
211
212 sub do_event {
213   my $self = shift;
214   my %opt = @_; # currently only 'time'
215   my $time = $opt{'time'} || time;
216
217   my $part_event = $self->part_event;
218
219   my $object = $self->cust_X;
220   my $obj_pkey = $object->primary_key;
221   my $for = "for ". $object->table. " ". $object->$obj_pkey();
222   warn "running cust_event ". $self->eventnum.
223        " (". $part_event->action. ") $for\n"
224     if $DEBUG;
225
226   my $error;
227   {
228     local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
229     $error = eval { $part_event->do_action($object, $self); };
230   }
231
232   my $status = '';
233   my $statustext = '';
234   if ( $@ ) {
235     $status = 'failed';
236     #$statustext = $@;
237     $statustext = "Error running ". $part_event->action. " action: $@";
238   } elsif ( $error ) {
239     $status = 'done';
240     $statustext = $error;
241   } else {
242     $status = 'done';
243   }
244
245   #replace or add myself
246   $self->_date($time);
247   $self->status($status);
248   $self->statustext($statustext);
249
250   $error = $self->eventnum ? $self->replace : $self->insert;
251   if ( $error ) {
252     #this is why we need that locked state...
253     my $e = 'WARNING: Event run but database not updated - '.
254             'error replacing or inserting cust_event '. $self->eventnum.
255             " $for: $error\n";
256     warn $e;
257     return $e;
258   }
259
260   '';
261
262 }
263
264 =item retry
265
266 Changes the status of this event from B<done> to B<failed>, allowing it to be
267 retried.
268
269 =cut
270
271 sub retry {
272   my $self = shift;
273   return '' unless $self->status eq 'done';
274   my $old = ref($self)->new( { $self->hash } );
275   $self->status('failed');
276   $self->replace($old);
277 }
278
279 #=item retryable
280 #
281 #Changes the statustext of this event to B<retriable>, rendering it 
282 #retriable (should retry be called).
283 #
284 #=cut
285
286 sub retriable {
287   confess "cust_event->retriable called";
288   my $self = shift;
289   return '' unless $self->status eq 'done';
290   my $old = ref($self)->new( { $self->hash } );
291   $self->statustext('retriable');
292   $self->replace($old);
293 }
294
295 =item join_sql
296
297 =cut
298
299 sub join_sql {
300   #my $class = shift;
301
302   "
303        JOIN part_event USING ( eventpart )
304   LEFT JOIN cust_bill ON ( eventtable = 'cust_bill' AND tablenum = invnum  )
305   LEFT JOIN cust_pkg  ON ( eventtable = 'cust_pkg'  AND tablenum = pkgnum  )
306   LEFT JOIN cust_pay  ON ( eventtable = 'cust_pay'  AND tablenum = paynum  )
307   LEFT JOIN cust_svc  ON ( eventtable = 'svc_acct'  AND tablenum = svcnum  )
308   LEFT JOIN cust_pkg AS cust_pkg_for_svc ON ( cust_svc.pkgnum = cust_pkg_for_svc.pkgnum )
309   LEFT JOIN cust_main ON (
310        ( 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     OR ( eventtable = 'cust_pay'  AND cust_pay.custnum  = cust_main.custnum )
314     OR ( eventtable = 'svc_acct'  AND cust_pkg_for_svc.custnum  = cust_main.custnum )
315   )
316   ";
317
318 }
319
320 =item search_sql_where HASHREF
321
322 Class method which returns an SQL WHERE fragment to search for parameters
323 specified in HASHREF.  Valid parameters are
324
325 =over 4
326
327 =item agentnum
328
329 =item custnum
330
331 =item invnum
332
333 =item pkgnum
334
335 =item svcnum
336
337 =item failed
338
339 =item beginning
340
341 =item ending
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_where {
351   my($class, $param) = @_;
352   if ( $DEBUG ) {
353     warn "$me search_sql_where 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   if ( $param->{'paynum'} =~ /^(\d+)$/ ) {
396     push @search, "part_event.eventtable = 'cust_pay'",
397                   "tablenum = '$1'";
398   }
399
400   if ( $param->{'svcnum'} =~ /^(\d+)$/ ) {
401     push @search, "part_event.eventtable = 'svc_acct'",
402                   "tablenum = '$1'";
403   }
404
405   my $where = 'WHERE '. join(' AND ', @search );
406
407   join(' AND ', @search );
408
409 }
410
411 =back
412
413 =head1 SUBROUTINES
414
415 =over 4
416
417 =item reprint
418
419 =cut
420
421 sub process_reprint {
422   process_re_X('print', @_);
423 }
424
425 =item reemail
426
427 =cut
428
429 sub process_reemail {
430   process_re_X('email', @_);
431 }
432
433 =item refax
434
435 =cut
436
437 sub process_refax {
438   process_re_X('fax', @_);
439 }
440
441 use Data::Dumper;
442 sub process_re_X {
443   my( $method, $job, $param ) = @_;
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                         from     => $invoice_from,
491                     } );
492
493     if ( $job ) { #progressbar foo
494       $num++;
495       if ( time - $min_sec > $last ) {
496         my $error = $job->update_statustext(
497           int( 100 * $num / scalar(@cust_event) )
498         );
499         die $error if $error;
500         $last = time;
501       }
502     }
503
504   }
505
506   #this doesn't work, but it would be nice
507   #if ( $job ) { #progressbar foo
508   #  my $error = $job->update_statustext(
509   #    scalar(@cust_event). " invoices re-${method}ed"
510   #  );
511   #  die $error if $error;
512   #}
513
514 }
515
516 =back
517
518 =head1 SEE ALSO
519
520 L<FS::part_event>, L<FS::cust_bill>, L<FS::Record>, schema.html from the
521 base documentation.
522
523 =cut
524
525 1;
526