further optimize condition_sql for "Invoice eligible for automatic collection" condit...
[freeside.git] / FS / FS / part_event / Condition / svc_acct_threshold.pm
1 package FS::part_event::Condition::svc_acct_threshold;
2
3 use strict;
4 use FS::svc_acct;
5
6 use base qw( FS::part_event::Condition );
7
8 sub description { 'Service is over its usage warning threshold' };
9
10 sub eventtable_hashref {
11   { 'svc_acct' => 1 }
12 }
13
14 tie my %usage_types, 'Tie::IxHash', (
15   'seconds'   => 'Time',
16   'upbytes'   => 'Upload',
17   'downbytes' => 'Download',
18   'totalbytes'=> 'Total transfer',
19 );
20
21 sub option_fields {
22   (
23     'usage_types' => {
24       type          => 'checkbox-multiple',
25       options       => [ keys %usage_types ],
26       option_labels => \%usage_types,
27     },
28   );
29 }
30
31 sub condition {
32   my($self, $svc_acct) = @_;
33
34   my $types = $self->option('usage_types') || {};
35   foreach my $column (keys %$types) {
36     # don't trigger if this type of usage isn't tracked on the service
37     next if $svc_acct->$column eq '';
38     my $threshold;
39     my $method = $column.'_threshold';
40     $threshold = $svc_acct->$method;
41     # don't trigger if seconds = 0 and seconds_threshold is null
42     next if $threshold eq '';
43
44     return 1 if ( $svc_acct->$column <= $threshold );
45   }
46   return 0;
47 }
48
49 sub condition_sql {
50   my($self) = @_;
51
52   # not an exact condition_sql--ignores the usage_types option
53   '(' . join(' OR ',
54     map {
55       my $threshold = $_.'_threshold';
56       "( svc_acct.$_ IS NOT NULL AND svc_acct.$threshold IS NOT NULL AND ".
57       "svc_acct.$_ <= svc_acct.$threshold )"
58     } keys %usage_types
59   ) . ')'
60
61
62 1;
63