event refactor, landing on HEAD!
[freeside.git] / FS / FS / part_event / Condition / balance_age.pm
1 package FS::part_event::Condition::balance_age;
2
3 require 5.006;
4 use strict;
5 use Time::Local qw(timelocal_nocheck);
6
7 use base qw( FS::part_event::Condition );
8
9 sub description { 'Customer balance age'; }
10
11 sub option_fields {
12   (
13     'balance' => { 'label'      => 'Balance over',
14                    'type'       => 'money',
15                    'value'      => '0.00', #default
16                  },
17     'age'     => { 'label'      => 'Age',
18                    'type'       => 'freq',
19                  },
20   );
21 }
22
23 sub condition {
24   my($self, $object, %opt) = @_;
25
26   my $cust_main = $self->cust_main($object);
27
28   my $over = $self->option('balance');
29   $over = 0 unless length($over);
30
31   #false laziness w/cust_bill_age
32   my $time = $opt{'time'};
33   my $age = $self->option('age');
34   $age = '0m' unless length($age);
35
36   my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($time) )[0,1,2,3,4,5];
37   if ( $age =~ /^(\d+)m$/i ) {
38     $mon -= $1;
39     until ( $mon >= 0 ) { $mon += 12; $year--; }
40   } elsif ( $age =~ /^(\d+)y$/i ) {
41     $year -= $1;
42   } elsif ( $age =~ /^(\d+)w$/i ) {
43     $mday -= $1 * 7;
44   } elsif ( $age =~ /^(\d+)d$/i ) {
45     $mday -= $1;
46   } elsif ( $age =~ /^(\d+)h$/i ) {
47     $hour -= $hour;
48   } else {
49     die "unparsable age: $age";
50   }
51   my $age_date = timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
52
53   $cust_main->balance_date($age_date) > $over;
54 }
55
56 sub condition_sql {
57   my( $class, $table, %opt ) = @_;
58
59   my $time = $opt{'time'};
60
61   my $over = $class->condition_sql_option('balance');
62   my $age = $class->condition_sql_option('age');
63   my $age_sql =
64     "$time - EXTRACT( EPOCH FROM REPLACE( $age, 'm', 'mon')::interval )";
65
66   my $balance_sql = FS::cust_main->balance_date_sql( $age_sql );
67
68   "$balance_sql > $over";
69
70 }
71
72 sub order_sql {
73   my( $class ) = @_;
74
75   my $age = $class->condition_sql_option('age');
76   "EXTRACT( EPOCH FROM REPLACE( $age, 'm', 'mon')::interval )";
77 }
78
79 sub order_sql_weight {
80   10;
81 }
82
83 1;