Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / FS / FS / part_event / Condition / referred_cust_base_recur.pm
1 package FS::part_event::Condition::referred_cust_base_recur;
2 use base qw( FS::part_event::Condition );
3
4 use List::Util qw( sum );
5
6 sub description { 'Referred customers recurring per month'; }
7
8 sub option_fields {
9   (
10     'recur_times'  => { label => 'Base recurring per month of referred customers is at least this many times base recurring per month of referring customer',
11                         type  => 'text',
12                         value => '1',
13                       },
14     'if_pkg_class' => { label    => 'Only considering package of class',
15                         type     => 'select-pkg_class',
16                         multiple => 1,
17                       },
18   );
19 }
20
21 sub condition {
22   my($self, $object, %opt) = @_;
23
24   my $cust_main = $self->cust_main($object);
25   my @cust_pkg = $cust_main->billing_pkgs;
26
27   my @referral_cust_main = $cust_main->referral_cust_main;
28   my @referral_cust_pkg = map $_->billing_pkgs, @referral_cust_main;
29
30   my $if_pkg_class = $self->option('if_pkg_class') || {};
31   if ( keys %$if_pkg_class ) {
32     @cust_pkg          = grep $_->part_pkg->classnum, @cust_pkg;
33     @referral_cust_pkg = grep $_->part_pkg->classnum, @referral_cust_pkg;
34   }
35
36   return 0 unless @cust_pkg && @referral_cust_pkg;
37
38   my $recur     = sum map $_->part_pkg->base_recur_permonth, @cust_pkg;
39   my $ref_recur = sum map $_->part_pkg->base_recur_permonth, @referral_cust_pkg;
40
41   $ref_recur >= $self->option('recur_times') * $recur;
42 }
43
44 #sub condition_sql {
45 #  my( $class, $table ) = @_;
46 #
47 #  #XXX TODO: this optimization
48 #}
49
50 1;
51