007ce4548d09c67d4a7aea436023d93d58c59f96
[freeside.git] / FS / FS / part_event / Condition / has_referral_custnum.pm
1 package FS::part_event::Condition::has_referral_custnum;
2
3 use strict;
4 use FS::cust_main;
5
6 use base qw( FS::part_event::Condition );
7
8 sub description { 'Customer has a referring customer'; }
9
10 sub option_fields {
11   (
12     'active' => { 'label' => 'Referring customer is active',
13                   'type'  => 'checkbox',
14                   'value' => 'Y',
15                 },
16     'check_bal' => { 'label' => 'Check referring customer balance',
17                      'type'  => 'checkbox',
18                      'value' => 'Y',
19                    },
20     'balance' => { 'label'      => 'Referring customer balance under (or equal to)',
21                    'type'       => 'money',
22                    'value'      => '0.00', #default
23                  },
24     'age'     => { 'label'      => 'Referring customer balance age',
25                    'type'       => 'freq',
26                  },
27   );
28 }
29
30 sub condition {
31   my($self, $object, %opt) = @_;
32
33   my $cust_main = $self->cust_main($object);
34   return 0 unless $cust_main; #sanity check
35   return 0 unless $cust_main->referral_custnum;
36
37   my $referring_cust_main = $cust_main->referral_custnum_cust_main;
38   return 0 unless $referring_cust_main; #sanity check;
39
40   #referring customer must sign up before referred customer
41   return 0 unless $cust_main->signupdate > $referring_cust_main->signupdate;
42
43   if ( $self->option('active') ) {
44     #check for no cust_main for referral_custnum? (deleted?)
45     return 0 unless $referring_cust_main->status eq 'active';
46   }
47
48   return 1 unless $self->option('check_bal');
49
50   #false laziness w/ balance_age_under
51   my $under = $self->option('balance');
52   $under = 0 unless length($under);
53
54   my $age = $self->option_age_from('age', $opt{'time'} );
55
56   $referring_cust_main->balance_date($age) <= $under;
57
58 }
59
60 sub condition_sql {
61   my( $class, $table, %opt ) = @_;
62
63   my $age = $class->condition_sql_option_age_from('age', $opt{'time'});
64   my $balance_sql      = FS::cust_main->balance_sql( $age );
65   my $balance_date_sql = FS::cust_main->balance_date_sql;
66   my $active_sql       = FS::cust_main->active_sql;
67   $balance_sql      =~ s/cust_main.custnum/cust_main.referral_custnum/;
68   $balance_date_sql =~ s/cust_main.custnum/cust_main.referral_custnum/;
69   $active_sql       =~ s/cust_main.custnum/cust_main.referral_custnum/;
70
71   my $sql = "cust_main.referral_custnum IS NOT NULL".
72     " AND (".$class->condition_sql_option('active')." IS NULL OR $active_sql)".
73     " AND ($balance_date_sql <= $balance_sql)";
74
75   return $sql;
76 }
77
78 1;