optimize billing for customers with lots of existing packages and invoices, RT#30238
[freeside.git] / FS / FS / part_event / Condition / once.pm
index 8c24e83..f164582 100644 (file)
@@ -7,7 +7,7 @@ use FS::cust_event;
 
 use base qw( FS::part_event::Condition );
 
-sub description { "Don't run this event again after it has completed sucessfully"; }
+sub description { "Don't run this event again after it has completed successfully"; }
 
 sub implicit_flag { 10; }
 
@@ -16,15 +16,22 @@ sub remove_warning {
 }
 
 sub condition {
-  my($self, $object) = @_;
+  my($self, $object, %opt) = @_;
 
   my $obj_pkey = $object->primary_key;
   my $tablenum = $object->$obj_pkey();
-  
-  my @existing = qsearch( 'cust_event', {
-    'eventpart' => $self->eventpart,
-    'tablenum'  => $tablenum,
-    'status'    => { op=>'!=', value=>'failed' },
+  my @existing = qsearch( {
+    'table'     => 'cust_event',
+    'hashref'   => {
+                     'eventpart' => $self->eventpart,
+                     'tablenum'  => $tablenum,
+                     'status'    => { op=>'!=', value=>'failed' },
+                   },
+    'extra_sql' => ( $opt{'cust_event'}->eventnum =~ /^(\d+)$/
+                       ? " AND eventnum != $1 "
+                       : ''
+                   ),
   } );
 
   ! scalar(@existing);
@@ -36,11 +43,12 @@ sub condition_sql {
 
   my %tablenum = %{ FS::part_event->eventtable_pkey_sql };
 
-  "0 = ( SELECT COUNT(*) FROM cust_event
-           WHERE cust_event.eventpart = part_event.eventpart
-             AND cust_event.tablenum = $tablenum{$table}
-             AND status != 'failed'
-       )
+  "NOT EXISTS ( SELECT 1 FROM cust_event
+                  WHERE cust_event.eventpart = part_event.eventpart
+                    AND cust_event.tablenum = $tablenum{$table}
+                    AND status != 'failed'
+                  LIMIT 1
+              )
   ";
 
 }