default to a session cookie instead of setting an explicit timeout, weird timezone...
[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   'orig_setup'   => 'Original setup date',
17 ;
18
19 sub eventtable_hashref {
20     { 'cust_main' => 0,
21       'cust_bill' => 0,
22       'cust_pkg'  => 1,
23     };
24 }
25
26 #something like this
27 sub option_fields {
28   my $class = shift;
29   (
30     'age'  =>  { 'label'   => $class->pkg_age_label,
31                  'type'    => 'freq',
32                },
33     'field' => { 'label'   => 'Compare date',
34                  'type'    => 'select',
35                  'options' => [ keys %dates ],
36                  'labels'  => \%dates,
37                },
38   );
39 }
40
41 sub condition {
42   my( $self, $cust_pkg, %opt ) = @_;
43
44   my $age = $self->pkg_age_age( $cust_pkg, %opt );
45
46   my $field = $self->option('field');
47   if ( $field =~ /^orig_(\w+)$/ ) {
48     # then find the package's oldest ancestor and compare to that
49     $field = $1;
50     while ($cust_pkg->change_pkgnum) {
51       $cust_pkg = $cust_pkg->old_cust_pkg;
52     }
53   }
54
55   my $pkg_date = $cust_pkg->get( $field );
56
57   $pkg_date && $self->pkg_age_compare( $pkg_date, $age );
58
59 }
60
61 sub pkg_age_age {
62   my( $self, $cust_pkg, %opt ) = @_;
63   $self->option_age_from('age', $opt{'time'} );
64 }
65
66 #doesn't work if you override pkg_age_age,
67 # so if you do, override this with at least a stub that returns 'true'
68 sub condition_sql {
69   my( $class, $table, %opt ) = @_;
70   my $age   = $class->condition_sql_option_age_from('age', $opt{'time'});
71   my $field = $class->condition_sql_option('field');
72   my $op    = $class->pkg_age_operator;
73
74   #amazingly, this is actually faster 
75   my $sql = '( CASE';
76   foreach ( keys %dates ) {
77     $sql .= " WHEN $field = '$_' THEN ";
78     # don't even try to handle orig_setup in here.  it's not worth it.
79     if ($_ =~ /^orig_/) {
80       $sql .= 'TRUE';
81     } else {
82       $sql .= "  (cust_pkg.$_ IS NOT NULL AND cust_pkg.$_ $op $age)";
83     }
84   }
85   $sql .= ' END )';
86   return $sql;
87 }
88
89 1;
90