c59d84748c4e980d0041c25858ad95e46a1bc4c8
[freeside.git] / FS / FS / part_event / Condition / after_event.pm
1 package FS::part_event::Condition::after_event;
2
3 use strict;
4 use FS::Record qw( qsearchs );
5 use FS::part_event;
6 use FS::cust_event;
7
8 use base qw( FS::part_event::Condition );
9
10 sub description { "After running another event" }
11
12 # Runs the event at least X days after the most recent time another event
13 # ran on the same object.
14
15 sub option_fields {
16   (
17     'eventpart' => { label=>'Event', type=>'select-part_event', },
18     'run_delay' => { label=>'Delay', type=>'freq', value=>'1',  },
19   );
20 }
21
22 # Specification:
23 # Given an event B that has this condition, where the "eventpart"
24 # option is set to event A, and the "run_delay" option is set to 
25 # X days.
26 # This condition is TRUE if:
27 # - Event A last ran X or more days in the past,
28 # AND
29 # - Event B has not run since the most recent occurrence of event A.
30
31 sub condition {
32   # similar to "once_every", but with a different eventpart
33   my($self, $object, %opt) = @_;
34
35   my $obj_pkey = $object->primary_key;
36   my $tablenum = $object->$obj_pkey();
37
38   my $before = $self->option_age_from('run_delay',$opt{'time'});
39   my $eventpart = $self->option('eventpart');
40
41   my %hash = (
42     'eventpart' => $eventpart,
43     'tablenum'  => $tablenum,
44     'status'    => { op => '!=', value => 'failed' },
45   );
46
47   my $most_recent_other = qsearchs( {
48     'table'     => 'cust_event',
49     'hashref'   => \%hash,
50     'order_by'  => " ORDER BY _date DESC LIMIT 1",
51   } )
52     or return 0; # if it hasn't run at all, return false
53   
54   return 0 if $most_recent_other->_date > $before; # we're still in the delay
55
56   # now see if there's been an instance of this event since the one we're
57   # following...
58   $hash{'eventpart'} = $self->eventpart;
59   if ( $opt{'cust_event'} and $opt{'cust_event'}->eventnum =~ /^(\d+)$/ ) {
60     $hash{'eventnum'} = { op => '!=', value => $1 };
61   }
62
63   my $most_recent_self = qsearchs( {
64     'table'     => 'cust_event',
65     'hashref'   => \%hash,
66     'order_by'  => " ORDER BY _date DESC LIMIT 1",
67   } );
68
69   return 0 if defined($most_recent_self) 
70           and $most_recent_self->_date >= $most_recent_other->_date;
71   # the follower has already run
72   
73   1;
74 }
75
76 # condition_sql, maybe someday
77
78 1;