referral status search, RT#75757
[freeside.git] / FS / FS / cust_main / Search.pm
index 0eb0020..4eab474 100644 (file)
@@ -356,10 +356,14 @@ sub smart_search {
 
       #still some false laziness w/search (was search/cust_main.cgi)
 
+      my $min_len =
+        $FS::CurrentUser::CurrentUser->access_right('List all customers')
+        ? 3 : 4;
+
       #substring
 
       my @company_hashrefs = ();
-      if ( length($value) >= 4 ) {
+      if ( length($value) >= $min_len ) {
         @company_hashrefs = (
           { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
           { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
@@ -375,7 +379,7 @@ sub smart_search {
           },
         );
 
-      } elsif ( length($value) >= 4 ) {
+      } elsif ( length($value) >= $min_len ) {
 
         @hashrefs = (
           { 'first'        => { op=>'ILIKE', value=>"%$value%" }, },
@@ -396,7 +400,7 @@ sub smart_search {
 
       }
 
-      if ( $conf->exists('address1-search') && length($value) >= 4 ) {
+      if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
 
         push @cust_main, qsearch( {
           table     => 'cust_main',
@@ -868,10 +872,24 @@ sub search {
   ##
   # with referrals
   ##
-  if ( $params->{'with_referrals'} ) {
+  if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
+
+    my $n = $1;
+  
+    # referral status
+    my $and_status = '';
+    if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
+      my $method = $params->{referral_status}. '_sql';
+      $and_status = ' AND '. FS::cust_main->$method();
+      $and_status =~ s/ cust_main\./ referred_cust_main./g;
+    }
+
     push @where,
-      ' EXISTS ( SELECT 1 FROM cust_main AS referred_cust_main
-                   WHERE cust_main.custnum = referred_cust_main.referral_custnum )';
+      " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
+                  WHERE cust_main.custnum = referred_cust_main.referral_custnum
+                    $and_status
+              )";
+
   }
 
   ##