Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / FS / FS / part_event / Condition / pkg_age_Common.pm
1 package FS::part_event::Condition::pkg_age_Common;
2 use base qw( FS::part_event::Condition );
3
4 use strict;
5 use Tie::IxHash;
6
7 tie our %dates, 'Tie::IxHash',
8   'setup'        => 'Setup date',
9   'last_bill'    => 'Last bill date',
10   'bill'         => 'Next bill date',
11   'adjourn'      => 'Adjournment date',
12   'susp'         => 'Suspension date',
13   'expire'       => 'Expiration date',
14   'cancel'       => 'Cancellation date',
15   'contract_end' => 'Contract end date',
16 ;
17
18 sub eventtable_hashref {
19     { 'cust_main' => 0,
20       'cust_bill' => 0,
21       'cust_pkg'  => 1,
22     };
23 }
24
25 #something like this
26 sub option_fields {
27   my $class = shift;
28   (
29     'age'  =>  { 'label'   => $class->pkg_age_label,
30                  'type'    => 'freq',
31                },
32     'field' => { 'label'   => 'Compare date',
33                  'type'    => 'select',
34                  'options' => [ keys %dates ],
35                  'labels'  => \%dates,
36                },
37   );
38 }
39
40 sub condition {
41   my( $self, $cust_pkg, %opt ) = @_;
42
43   my $age = $self->pkg_age_age( $cust_pkg, %opt );
44
45   my $pkg_date = $cust_pkg->get( $self->option('field') );
46
47   $pkg_date && $self->pkg_age_compare( $pkg_date, $age );
48
49 }
50
51 sub pkg_age_age {
52   my( $self, $cust_pkg, %opt ) = @_;
53   $self->option_age_from('age', $opt{'time'} );
54 }
55
56 #doesn't work if you override pkg_age_age,
57 # so if you do, override this with at least a stub that returns 'true'
58 sub condition_sql {
59   my( $class, $table, %opt ) = @_;
60   my $age   = $class->condition_sql_option_age_from('age', $opt{'time'});
61   my $field = $class->condition_sql_option('field');
62   my $op    = $class->pkg_age_operator;
63
64   #amazingly, this is actually faster 
65   my $sql = '( CASE';
66   foreach ( keys %dates ) {
67     $sql .= " WHEN $field = '$_' THEN ".
68             "  (cust_pkg.$_ IS NOT NULL AND cust_pkg.$_ $op $age)";
69   }
70   $sql .= ' END )';
71   return $sql;
72 }
73
74 1;
75