import torrus 1.0.9
[freeside.git] / FS / FS / part_event / Condition / once_perinv.pm
1 package FS::part_event::Condition::once_perinv;
2
3 use strict;
4 use FS::Record qw( qsearch );
5 use FS::part_event;
6 use FS::cust_event;
7
8 use base qw( FS::part_event::Condition );
9
10 sub description { "Run only once for each time the package has been billed"; }
11
12 # Run the event, at most, a number of times equal to the number of 
13 # distinct invoices that contain line items from this package.
14
15 sub eventtable_hashref {
16     { 'cust_main' => 0,
17       'cust_bill' => 0,
18       'cust_pkg'  => 1,
19     };
20 }
21
22 sub condition {
23   my($self, $cust_pkg, %opt) = @_;
24
25   my %invnum;
26   $invnum{$_->invnum} = 1 
27     foreach ( qsearch('cust_bill_pkg', { 'pkgnum' => $cust_pkg->pkgnum }) );
28   my @events = qsearch( {
29       'table'     => 'cust_event', 
30       'hashref'   => { 'eventpart' => $self->eventpart,
31                        'status'    => { op=>'!=', value=>'failed' },
32                        'tablenum'  => $cust_pkg->pkgnum,
33                      },
34       'extra_sql' => ( $opt{'cust_event'}->eventnum =~ /^(\d+)$/
35                        ? " AND eventnum != $1 " : '' ),
36   } );
37   scalar(@events) < scalar(keys %invnum);
38 }
39
40 sub condition_sql {
41   my( $self, $table ) = @_;
42
43   "( 
44     ( SELECT COUNT(distinct(invnum)) 
45       FROM cust_bill_pkg
46       WHERE cust_bill_pkg.pkgnum = cust_pkg.pkgnum )
47     >
48     ( SELECT COUNT(*)
49       FROM cust_event
50       WHERE cust_event.eventpart = part_event.eventpart
51         AND cust_event.tablenum = cust_pkg.pkgnum
52         AND status != 'failed' )
53   )"
54
55 }
56
57 1;