further optimize condition_sql for "Invoice eligible for automatic collection" condit...
[freeside.git] / FS / FS / part_event / Condition / times_percust.pm
1 package FS::part_event::Condition::times_percust;
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 this event the specified number of times per customer"; }
11
12 sub option_fields {
13   (
14     'run_times'  => { label=>'Number of times', type=>'text', value=>'1', },
15   );
16 }
17
18 sub eventtable_hashref {
19     { 'cust_main' => 0,
20       'cust_bill' => 1,
21       'cust_pkg'  => 1,
22     };
23 }
24
25 sub condition {
26   my($self, $object, %opt) = @_;
27
28   my $obj_pkey = $object->primary_key;
29   my $obj_table = $object->table;
30   my $custnum = $object->custnum;
31
32   my @where = (
33     "tablenum IN ( SELECT $obj_pkey FROM $obj_table WHERE custnum = $custnum )"
34   );
35   if ( $opt{'cust_event'}->eventnum =~ /^(\d+)$/ ) {
36     push @where, " eventnum != $1 ";
37   }
38   my $extra_sql = ' AND '. join(' AND ', @where);
39  
40   my @existing = qsearch( {
41     'table'     => 'cust_event',
42     'hashref'   => {
43                      'eventpart' => $self->eventpart,
44                      #'tablenum'  => $tablenum,
45                      'status'    => { op=>'!=', value=>'failed' },
46                    },
47     'extra_sql' => $extra_sql,
48   } );
49
50   scalar(@existing) < $self->option('run_times');
51
52 }
53
54 sub condition_sql {
55   my( $class, $table, %opt ) = @_;
56
57   my %pkey = %{ FS::part_event->eventtable_pkey };
58
59   my $run_times =
60     $class->condition_sql_option_integer('run_times', $opt{'driver_name'});
61
62   my $pkey = $pkey{$table};
63
64   my $existing = "( SELECT COUNT(*) FROM cust_event
65                       WHERE cust_event.eventpart = part_event.eventpart
66                         AND cust_event.tablenum IN (
67                           SELECT $pkey FROM $table AS times_percust
68                             WHERE times_percust.custnum = cust_main.custnum )
69                         AND status != 'failed'
70                   )";
71
72   "$existing < $run_times";
73
74 }
75
76 1;