further optimize condition_sql for "Invoice eligible for automatic collection" condit...
[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                      disable_empty => 1,
19                      hashref => { disabled => '' },
20                    },
21     'run_delay' => { label=>'Delay', type=>'freq', value=>'1',  },
22   );
23 }
24
25 # Specification:
26 # Given an event B that has this condition, where the "eventpart"
27 # option is set to event A, and the "run_delay" option is set to 
28 # X days.
29 # This condition is TRUE if:
30 # - Event A last ran X or more days in the past,
31 # AND
32 # - Event B has not run since the most recent occurrence of event A.
33
34 sub condition {
35   # similar to "once_every", but with a different eventpart
36   my($self, $object, %opt) = @_;
37
38   my $obj_pkey = $object->primary_key;
39   my $tablenum = $object->$obj_pkey();
40
41   my $before = $self->option_age_from('run_delay',$opt{'time'});
42   my $eventpart = $self->option('eventpart');
43
44   my %hash = (
45     'eventpart' => $eventpart,
46     'tablenum'  => $tablenum,
47     'status'    => { op => '!=', value => 'failed' },
48   );
49
50   my $most_recent_other = qsearchs( {
51     'table'     => 'cust_event',
52     'hashref'   => \%hash,
53     'order_by'  => " ORDER BY _date DESC LIMIT 1",
54   } )
55     or return 0; # if it hasn't run at all, return false
56   
57   return 0 if $most_recent_other->_date > $before; # we're still in the delay
58
59   # now see if there's been an instance of this event since the one we're
60   # following...
61   $hash{'eventpart'} = $self->eventpart;
62   if ( $opt{'cust_event'} and $opt{'cust_event'}->eventnum =~ /^(\d+)$/ ) {
63     $hash{'eventnum'} = { op => '!=', value => $1 };
64   }
65
66   my $most_recent_self = qsearchs( {
67     'table'     => 'cust_event',
68     'hashref'   => \%hash,
69     'order_by'  => " ORDER BY _date DESC LIMIT 1",
70   } );
71
72   return 0 if defined($most_recent_self) 
73           and $most_recent_self->_date >= $most_recent_other->_date;
74   # the follower has already run
75   
76   1;
77 }
78
79 # condition_sql, maybe someday
80
81 1;