spacing, and order like sql, RT#77532
[freeside.git] / FS / FS / cust_main / Search.pm
1 package FS::cust_main::Search;
2
3 use strict;
4 use base qw( Exporter );
5 use vars qw( @EXPORT_OK $DEBUG $me $conf @fuzzyfields );
6 use String::Approx qw(amatch);
7 use FS::UID qw( dbh );
8 use FS::Record qw( qsearch );
9 use FS::cust_main;
10 use FS::cust_main_invoice;
11 use FS::svc_acct;
12 use FS::payinfo_Mixin;
13
14 @EXPORT_OK = qw( smart_search );
15
16 # 1 is mostly method/subroutine entry and options
17 # 2 traces progress of some operations
18 # 3 is even more information including possibly sensitive data
19 $DEBUG = 0;
20 $me = '[FS::cust_main::Search]';
21
22 @fuzzyfields = (
23   'cust_main.first', 'cust_main.last', 'cust_main.company', 
24   'cust_main.ship_company', # if you're using it
25   'cust_location.address1',
26   'contact.first',   'contact.last',
27 );
28
29 install_callback FS::UID sub { 
30   $conf = new FS::Conf;
31   #yes, need it for stuff below (prolly should be cached)
32 };
33
34 =head1 NAME
35
36 FS::cust_main::Search - Customer searching
37
38 =head1 SYNOPSIS
39
40   use FS::cust_main::Search;
41
42   FS::cust_main::Search::smart_search(%options);
43
44   FS::cust_main::Search::email_search(%options);
45
46   FS::cust_main::Search->search( \%options );
47   
48   FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
49
50 =head1 SUBROUTINES
51
52 =over 4
53
54 =item smart_search OPTION => VALUE ...
55
56 Accepts the following options: I<search>, the string to search for.  The string
57 will be searched for as a customer number, phone number, name or company name,
58 address (if address1-search is on), invoicing email address, or credit card
59 number.
60
61 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
62 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
63 smart_search to
64 skip fuzzy matching when an exact match is found.
65
66 Any additional options are treated as an additional qualifier on the search
67 (i.e. I<agentnum>).
68
69 Returns a (possibly empty) array of FS::cust_main objects.
70
71 =cut
72
73 sub smart_search {
74   my %options = @_;
75
76   #here is the agent virtualization
77   my $agentnums_sql = 
78     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
79   my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
80
81   my @cust_main = ();
82
83   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
84   my $search = delete $options{'search'};
85   ( my $alphanum_search = $search ) =~ s/\W//g;
86   
87   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
88
89     #false laziness w/Record::ut_phone
90     my $phonen = "$1-$2-$3";
91     $phonen .= " x$4" if $4;
92
93     my $phonenum = "$1$2$3";
94     #my $extension = $4;
95
96     #cust_main phone numbers and contact phone number
97     push @cust_main, qsearch( {
98       'select'    => 'cust_main.*',
99       'table'     => 'cust_main',
100       'addl_from' => ' left join cust_contact  using (custnum) '.
101                      ' left join contact_phone using (contactnum) ',
102       'hashref'   => { %options },
103       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
104                      ' ( '.
105                          join(' OR ', map "$_ = '$phonen'",
106                                           qw( daytime night mobile fax )
107                              ).
108                           " OR phonenum = '$phonenum' ".
109                      ' ) '.
110                      " AND $agentnums_sql", #agent virtualization
111     } );
112
113     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
114       #try looking for matches with extensions unless one was specified
115
116       push @cust_main, qsearch( {
117         'table'     => 'cust_main',
118         'hashref'   => { %options },
119         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
120                        ' ( '.
121                            join(' OR ', map "$_ LIKE '$phonen\%'",
122                                             qw( daytime night )
123                                ).
124                        ' ) '.
125                        " AND $agentnums_sql", #agent virtualization
126       } );
127
128     }
129
130   } 
131   
132   
133   if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
134
135     push @cust_main, qsearch( {
136       'select'    => 'cust_main.*',
137       'table'     => 'cust_main',
138       'addl_from' => ' left join cust_main_invoice using (custnum) '.
139                      ' left join cust_contact      using (custnum) '.
140                      ' left join contact_email     using (contactnum) ',
141       'hashref'   => { %options },
142       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
143                      ' ( '.
144                          join(' OR ', map "$_ = '$search'",
145                                           qw( dest emailaddress )
146                              ).
147                      ' ) '.
148                      " AND $agentnums_sql", #agent virtualization
149     } );
150
151   # custnum search (also try agent_custid), with some tweaking options if your
152   # legacy cust "numbers" have letters
153   } elsif (    $search =~ /^\s*(\d+)\s*$/
154             or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
155                  && $search =~ /^\s*(\w\w?\d+)\s*$/
156                )
157             or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
158                  && $search =~ /^\s*(\d+-\w)\s*$/
159                )
160             or ( $conf->config('cust_main-custnum-display_special')
161                  # it's not currently possible for special prefixes to contain
162                  # digits, so just strip off any alphabetic prefix and match 
163                  # the rest to custnum
164                  && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
165                )
166             or ( $conf->exists('address1-search' )
167                  && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
168                )
169           )
170   {
171
172     my $num = $1;
173
174     if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
175       my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
176                                 ? ' AND agent_custid IS NULL ' : '';
177       push @cust_main, qsearch( {
178         'table'     => 'cust_main',
179         'hashref'   => { 'custnum' => $num, %options },
180         'extra_sql' => " AND $agentnums_sql $agent_custid_null",
181       } );
182     }
183
184     # for all agents this user can see, if any of them have custnum prefixes 
185     # that match the search string, include customers that match the rest 
186     # of the custnum and belong to that agent
187     foreach my $agentnum ( keys %$agentnums_href ) {
188       my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
189       next if !$p;
190       if ( $p eq substr($num, 0, length($p)) ) {
191         push @cust_main, qsearch( {
192           'table'   => 'cust_main',
193           'hashref' => { 'custnum' => 0 + substr($num, length($p)),
194                          'agentnum' => $agentnum,
195                           %options,
196                        },
197         } );
198       }
199     }
200
201     push @cust_main, qsearch( {
202         'table'     => 'cust_main',
203         'hashref'   => { 'agent_custid' => $num, %options },
204         'extra_sql' => " AND $agentnums_sql", #agent virtualization
205     } );
206
207     if ( $conf->exists('address1-search') ) {
208       my $len = length($num);
209       $num = lc($num);
210       # probably the Right Thing: return customers that have any associated
211       # locations matching the string, not just bill/ship location
212       push @cust_main, qsearch( {
213         'table'     => 'cust_main',
214         'addl_from' => ' JOIN cust_location USING (custnum) ',
215         'hashref'   => { %options, },
216         'extra_sql' => 
217           ( keys(%options) ? ' AND ' : ' WHERE ' ).
218           " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
219           " AND $agentnums_sql",
220       } );
221     }
222
223   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
224
225     my($company, $last, $first) = ( $1, $2, $3 );
226
227     # "Company (Last, First)"
228     #this is probably something a browser remembered,
229     #so just do an exact search (but case-insensitive, so USPS standardization
230     #doesn't throw a wrench in the works)
231
232     push @cust_main, qsearch( {
233         'table'     => 'cust_main',
234         'hashref'   => { %options },
235         'extra_sql' => 
236         ( keys(%options) ? ' AND ' : ' WHERE ' ).
237         join(' AND ',
238           " LOWER(first)   = ". dbh->quote(lc($first)),
239           " LOWER(last)    = ". dbh->quote(lc($last)),
240           " LOWER(company) = ". dbh->quote(lc($company)),
241           $agentnums_sql,
242         ),
243       } ),
244
245     #contacts?
246     # probably not necessary for the "something a browser remembered" case
247
248   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
249                                               # try {first,last,company}
250
251     my $value = lc($1);
252
253     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
254     # # full strings the browser remembers won't work
255     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
256
257     use Lingua::EN::NameParse;
258     my $NameParse = new Lingua::EN::NameParse(
259              auto_clean     => 1,
260              allow_reversed => 1,
261     );
262
263     my($last, $first) = ( '', '' );
264     #maybe disable this too and just rely on NameParse?
265     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
266     
267       ($last, $first) = ( $1, $2 );
268     
269     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
270     } elsif ( ! $NameParse->parse($value) ) {
271
272       my %name = $NameParse->components;
273       $first = lc($name{'given_name_1'}) || $name{'initials_1'}; #wtf NameParse, Ed?
274       $last  = lc($name{'surname_1'});
275
276     }
277
278     if ( $first && $last ) {
279
280       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
281
282       #exact
283       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
284       $sql .= "( (LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first)
285                  OR (LOWER(contact.last) = $q_last AND LOWER(contact.first) = $q_first) )";
286
287       #cust_main and contacts
288       push @cust_main, qsearch( {
289         'select'    => 'cust_main.*',
290         'table'     => 'cust_main',
291         'addl_from' => ' left join cust_contact using (custnum) '.
292                        ' left join contact using (contactnum) ',
293         'hashref'   => { %options },
294         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
295       } );
296
297       # or it just be something that was typed in... (try that in a sec)
298
299     }
300
301     my $q_value = dbh->quote($value);
302
303     #exact
304     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
305     $sql .= " (    LOWER(cust_main.first)         = $q_value
306                 OR LOWER(cust_main.last)          = $q_value
307                 OR LOWER(cust_main.company)       = $q_value
308                 OR LOWER(cust_main.ship_company)  = $q_value
309                 OR LOWER(contact.first)           = $q_value
310                 OR LOWER(contact.last)            = $q_value
311             )";
312
313     #address1 (yes, it's a kludge)
314     $sql .= "   OR EXISTS ( 
315                             SELECT 1 FROM cust_location 
316                               WHERE LOWER(cust_location.address1) = $q_value
317                                 AND cust_location.custnum = cust_main.custnum
318                           )"
319       if $conf->exists('address1-search');
320
321     push @cust_main, qsearch( {
322       'select'    => 'cust_main.*',
323       'table'     => 'cust_main',
324       'addl_from' => ' left join cust_contact using (custnum) '.
325                      ' left join contact using (contactnum) ',
326       'hashref'   => { %options },
327       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
328     } );
329
330     #no exact match, trying substring/fuzzy
331     #always do substring & fuzzy (unless they're explicity config'ed off)
332     #getting complaints searches are not returning enough
333     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
334
335       #still some false laziness w/search (was search/cust_main.cgi)
336
337       my $min_len =
338         $FS::CurrentUser::CurrentUser->access_right('List all customers')
339         ? 3 : 4;
340
341       #substring
342
343       my @company_hashrefs = ();
344       if ( length($value) >= $min_len ) {
345         @company_hashrefs = (
346           { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
347           { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
348         );
349       }
350
351       my @hashrefs = ();
352       if ( $first && $last ) {
353
354         @hashrefs = (
355           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
356             'last'         => { op=>'ILIKE', value=>"%$last%" },
357           },
358         );
359
360       } elsif ( length($value) >= $min_len ) {
361
362         @hashrefs = (
363           { 'first'        => { op=>'ILIKE', value=>"%$value%" }, },
364           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
365         );
366
367       }
368
369       foreach my $hashref ( @company_hashrefs, @hashrefs ) {
370
371         push @cust_main, qsearch( {
372           'table'     => 'cust_main',
373           'hashref'   => { %$hashref,
374                            %options,
375                          },
376           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
377         } );
378
379       }
380
381       if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
382
383         push @cust_main, qsearch( {
384           table     => 'cust_main',
385           addl_from => 'JOIN cust_location USING (custnum)',
386           extra_sql => 'WHERE '.
387                         ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
388                         " AND $agentnums_sql", #agent virtualizaiton
389         } );
390
391       }
392
393       #contact substring
394
395       foreach my $hashref ( @hashrefs ) {
396
397         push @cust_main,
398           grep $agentnums_href->{$_->agentnum}, #agent virt
399             grep $_, #skip contacts that don't have cust_main records
400               map $_->cust_main,
401                 qsearch({
402                           'table'     => 'contact',
403                           'hashref'   => { %$hashref,
404                                            #%options,
405                                          },
406                           #'extra_sql' => " AND $agentnums_sql", #agent virt
407                        });
408
409       }
410
411       #fuzzy
412       my %fuzopts = (
413         'hashref'   => \%options,
414         'select'    => '',
415         'extra_sql' => "WHERE $agentnums_sql",    #agent virtualization
416       );
417
418       if ( $first && $last ) {
419         push @cust_main, FS::cust_main::Search->fuzzy_search(
420           { 'last'   => $last,    #fuzzy hashref
421             'first'  => $first }, #
422           %fuzopts
423         );
424         push @cust_main, FS::cust_main::Search->fuzzy_search(
425           { 'contact.last'   => $last,    #fuzzy hashref
426             'contact.first'  => $first }, #
427           %fuzopts
428         );
429       }
430
431       foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
432         push @cust_main, FS::cust_main::Search->fuzzy_search(
433           { $field => $value },
434           %fuzopts
435         );
436       }
437       foreach my $field ( 'first', 'last' ) {
438         push @cust_main, FS::cust_main::Search->fuzzy_search(
439           { "contact.$field" => $value },
440           %fuzopts
441         );
442       }
443       if ( $conf->exists('address1-search') ) {
444         push @cust_main,
445           FS::cust_main::Search->fuzzy_search(
446             { 'cust_location.address1' => $value },
447             %fuzopts
448         );
449       }
450
451     }
452
453   }
454
455   ( my $nospace_search = $search ) =~ s/\s//g;
456   ( my $card_search = $nospace_search ) =~ s/\-//g;
457   $card_search =~ s/[x\*\.\_]/x/gi;
458   
459   if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
460
461     ( my $like_search = $card_search ) =~ s/x/_/g;
462     my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
463
464     push @cust_main, qsearch({
465       'table'     => 'cust_main',
466       'addl_from' => ' JOIN cust_payby USING (custnum)',
467       'hashref'   => {},
468       'extra_sql' => " WHERE (    cust_payby.payinfo LIKE '$like_search'
469                                OR cust_payby.paymask =    '$mask_search'
470                              ) ".
471                      " AND cust_payby.payby IN ('CARD','DCRD') ".
472                      " AND $agentnums_sql", #agent virtulization
473     });
474
475   }
476   
477
478   #eliminate duplicates
479   my %saw = ();
480   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
481
482   @cust_main;
483
484 }
485
486 =item email_search
487
488 Accepts the following options: I<email>, the email address to search for.  The
489 email address will be searched for as an email invoice destination and as an
490 svc_acct account.
491
492 #Any additional options are treated as an additional qualifier on the search
493 #(i.e. I<agentnum>).
494
495 Returns a (possibly empty) array of FS::cust_main objects (but usually just
496 none or one).
497
498 =cut
499
500 sub email_search {
501   my %options = @_;
502
503   my $email = delete $options{'email'};
504
505   #no agent virtualization yet
506   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
507
508   my @cust_main = ();
509
510   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
511
512     my ( $user, $domain ) = ( $1, $2 );
513
514     warn "$me smart_search: searching for $user in domain $domain"
515       if $DEBUG;
516
517     push @cust_main,
518       map { $_->cust_main }
519       map { $_->cust_contact }
520       map { $_->contact }
521           qsearch( {
522                      'table'     => 'contact_email',
523                      'hashref'   => { 'emailaddress' => $email },
524                    }
525                  );
526
527     push @cust_main,
528       map  $_->cust_main,
529       grep $_,
530       map  $_->cust_svc->cust_pkg,
531           qsearch( {
532                      'table'     => 'svc_acct',
533                      'hashref'   => { 'username' => $user, },
534                      'extra_sql' =>
535                        'AND ( SELECT domain FROM svc_domain
536                                 WHERE svc_acct.domsvc = svc_domain.svcnum
537                             ) = '. dbh->quote($domain),
538                    }
539                  );
540   }
541
542   my %saw = ();
543   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
544
545   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
546     if $DEBUG;
547
548   @cust_main;
549
550 }
551
552 =back
553
554 =head1 CLASS METHODS
555
556 =over 4
557
558 =item search HASHREF
559
560 (Class method)
561
562 Returns a qsearch hash expression to search for parameters specified in
563 HASHREF.  Valid parameters are
564
565 =over 4
566
567 =item agentnum
568
569 =item status
570
571 =item address
572
573 =item zip
574
575 =item refnum
576
577 =item cancelled_pkgs
578
579 bool
580
581 =item signupdate
582
583 listref of start date, end date
584
585 =item birthdate
586
587 listref of start date, end date
588
589 =item spouse_birthdate
590
591 listref of start date, end date
592
593 =item anniversary_date
594
595 listref of start date, end date
596
597 =item current_balance
598
599 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
600
601 =item cust_fields
602
603 =item flattened_pkgs
604
605 bool
606
607 =back
608
609 =cut
610
611 sub search {
612   my ($class, $params) = @_;
613
614   my $dbh = dbh;
615
616   my @where = ();
617   my $orderby;
618
619   # initialize these to prevent warnings
620   $params = {
621     'custnum'       => '',
622     'agentnum'      => '',
623     'usernum'       => '',
624     'status'        => '',
625     'address'       => '',
626     'zip'           => '',
627     'invoice_terms' => '',
628     'custbatch'     => '',
629     %$params
630   };
631
632   ##
633   # explicit custnum(s)
634   ##
635
636   if ( $params->{'custnum'} ) {
637     my @custnums = ref($params->{'custnum'}) ? 
638                       @{ $params->{'custnum'} } : 
639                       $params->{'custnum'};
640     push @where, 
641       'cust_main.custnum IN (' . 
642       join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
643       ')' if scalar(@custnums) > 0;
644   }
645
646   ##
647   # parse agent
648   ##
649
650   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
651     push @where,
652       "cust_main.agentnum = $1";
653   }
654
655   ##
656   # parse sales person
657   ##
658
659   if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
660     push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
661                            : 'cust_main.salesnum IS NULL';
662   }
663
664   ##
665   # parse usernum
666   ##
667
668   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
669     push @where,
670       "cust_main.usernum = $1";
671   }
672
673   ##
674   # parse status
675   ##
676
677   #prospect ordered active inactive suspended cancelled
678   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
679     my $method = $params->{'status'}. '_sql';
680     #push @where, $class->$method();
681     push @where, FS::cust_main->$method();
682   }
683
684   my $current = '';
685   unless ( $params->{location_history} ) {
686     $current = '
687       AND (    cust_location.locationnum IN ( cust_main.bill_locationnum,
688                                               cust_main.ship_locationnum
689                                             )
690             OR cust_location.locationnum IN (
691                  SELECT locationnum FROM cust_pkg
692                   WHERE cust_pkg.custnum = cust_main.custnum
693                     AND locationnum IS NOT NULL
694                     AND '. FS::cust_pkg->ncancelled_recurring_sql.'
695                )
696           )';
697   }
698
699   ##
700   # address
701   ##
702   if ( $params->{'address'} ) {
703     # allow this to be an arrayref
704     my @values = ($params->{'address'});
705     @values = @{$values[0]} if ref($values[0]);
706     my @orwhere;
707     foreach (grep /\S/, @values) {
708       my $address = dbh->quote('%'. lc($_). '%');
709       push @orwhere,
710         "LOWER(cust_location.address1) LIKE $address",
711         "LOWER(cust_location.address2) LIKE $address";
712     }
713     if (@orwhere) {
714       push @where, "EXISTS(
715         SELECT 1 FROM cust_location 
716         WHERE cust_location.custnum = cust_main.custnum
717           AND (".join(' OR ',@orwhere).")
718           $current
719         )";
720     }
721   }
722
723   ##
724   # city
725   ##
726   if ( $params->{'city'} =~ /\S/ ) {
727     my $city = dbh->quote($params->{'city'});
728     push @where, "EXISTS(
729       SELECT 1 FROM cust_location
730       WHERE cust_location.custnum = cust_main.custnum
731         AND cust_location.city = $city
732         $current
733     )";
734   }
735
736   ##
737   # county
738   ##
739   if ( $params->{'county'} =~ /\S/ ) {
740     my $county = dbh->quote($params->{'county'});
741     push @where, "EXISTS(
742       SELECT 1 FROM cust_location
743       WHERE cust_location.custnum = cust_main.custnum
744         AND cust_location.county = $county
745         $current
746     )";
747   }
748
749   ##
750   # state
751   ##
752   if ( $params->{'state'} =~ /\S/ ) {
753     my $state = dbh->quote($params->{'state'});
754     push @where, "EXISTS(
755       SELECT 1 FROM cust_location
756       WHERE cust_location.custnum = cust_main.custnum
757         AND cust_location.state = $state
758         $current
759     )";
760   }
761
762   ##
763   # zipcode
764   ##
765   if ( $params->{'zip'} =~ /\S/ ) {
766     my $zip = dbh->quote($params->{'zip'} . '%');
767     push @where, "EXISTS(
768       SELECT 1 FROM cust_location
769       WHERE cust_location.custnum = cust_main.custnum
770         AND cust_location.zip LIKE $zip
771         $current
772     )";
773   }
774
775   ##
776   # country
777   ##
778   if ( $params->{'country'} =~ /^(\w\w)$/ ) {
779     my $country = uc($1);
780     push @where, "EXISTS(
781       SELECT 1 FROM cust_location
782       WHERE cust_location.custnum = cust_main.custnum
783         AND cust_location.country = '$country'
784         $current
785     )";
786   }
787
788   ###
789   # refnum
790   ###
791   if ( $params->{'refnum'}  ) {
792
793     my @refnum = ref( $params->{'refnum'} )
794                    ? @{ $params->{'refnum'} }
795                    :  ( $params->{'refnum'} );
796
797     @refnum = grep /^(\d*)$/, @refnum;
798
799     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
800       if @refnum;
801
802   }
803
804   ##
805   # parse cancelled package checkbox
806   ##
807
808   my $pkgwhere = "";
809
810   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
811     unless $params->{'cancelled_pkgs'};
812
813   ##
814   # "with email address(es)" checkbox
815   ##
816
817   push @where,
818     'EXISTS ( SELECT 1 FROM contact_email
819                 JOIN cust_contact USING (contactnum)
820                 WHERE cust_contact.custnum = cust_main.custnum
821             )'
822     if $params->{'with_email'};
823
824   ##
825   # "with postal mail invoices" checkbox
826   ##
827
828   push @where, "cust_main.postal_invoice = 'Y'"
829     if $params->{'POST'};
830
831   ##
832   # "without postal mail invoices" checkbox
833   ##
834
835   push @where, "cust_main.postal_invoice IS NULL"
836     if $params->{'no_POST'};
837
838   ##
839   # "tax exempt" checkbox
840   ##
841   push @where, "cust_main.tax = 'Y'"
842     if $params->{'tax'};
843
844   ##
845   # "not tax exempt" checkbox
846   ##
847   push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
848     if $params->{'no_tax'};
849
850   ##
851   # with referrals
852   ##
853   if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
854
855     my $n = $1;
856   
857     # referral status
858     my $and_status = '';
859     if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
860       my $method = $params->{referral_status}. '_sql';
861       $and_status = ' AND '. FS::cust_main->$method();
862       $and_status =~ s/ cust_main\./ referred_cust_main./g;
863     }
864
865     push @where,
866       " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
867                   WHERE cust_main.custnum = referred_cust_main.referral_custnum
868                     $and_status
869               )";
870
871   }
872
873   ##
874   # dates
875   ##
876
877   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
878
879     next unless exists($params->{$field});
880
881     my($beginning, $ending, $hour) = @{$params->{$field}};
882
883     push @where,
884       "cust_main.$field IS NOT NULL",
885       "cust_main.$field >= $beginning",
886       "cust_main.$field <= $ending";
887
888     if($field eq 'signupdate' && defined $hour) {
889       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
890         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
891       }
892       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
893         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
894       }
895       else {
896         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
897       }
898     }
899
900     $orderby ||= "ORDER BY cust_main.$field";
901
902   }
903
904   ###
905   # classnum
906   ###
907
908   if ( $params->{'classnum'} ) {
909
910     my @classnum = ref( $params->{'classnum'} )
911                      ? @{ $params->{'classnum'} }
912                      :  ( $params->{'classnum'} );
913
914     @classnum = grep /^(\d*)$/, @classnum;
915
916     if ( @classnum ) {
917       push @where, '( '. join(' OR ', map {
918                                             $_ ? "cust_main.classnum = $_"
919                                                : "cust_main.classnum IS NULL"
920                                           }
921                                           @classnum
922                              ).
923                    ' )';
924     }
925
926   }
927
928   ###
929   # invoice terms
930   ###
931
932   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
933     my $terms = $1;
934     if ( $1 eq 'NULL' ) {
935       push @where,
936         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
937     } else {
938       push @where,
939         "cust_main.invoice_terms IS NOT NULL",
940         "cust_main.invoice_terms = '$1'";
941     }
942   }
943
944   ##
945   # amounts
946   ##
947
948   if ( $params->{'current_balance'} ) {
949
950     #my $balance_sql = $class->balance_sql();
951     my $balance_sql = FS::cust_main->balance_sql();
952
953     my @current_balance =
954       ref( $params->{'current_balance'} )
955       ? @{ $params->{'current_balance'} }
956       :  ( $params->{'current_balance'} );
957
958     push @where, map { s/current_balance/$balance_sql/; $_ }
959                      @current_balance;
960
961   }
962
963   ##
964   # custbatch
965   ##
966
967   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
968     push @where,
969       "cust_main.custbatch = '$1'";
970   }
971   
972   if ( $params->{'tagnum'} ) {
973     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
974
975     @tagnums = grep /^(\d+)$/, @tagnums;
976
977     if ( @tagnums ) {
978       if ( $params->{'all_tags'} ) {
979         foreach ( @tagnums ) {
980           push @where, 'exists(select 1 from cust_tag where '.
981                        'cust_tag.custnum = cust_main.custnum and tagnum = '.
982                        $_ . ')';
983         }
984       } else { # matching any tag, not all
985         my $tags_where = "0 < (select count(1) from cust_tag where " 
986                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
987                 . join(',', @tagnums) . "))";
988
989         push @where, $tags_where;
990       }
991     }
992   }
993
994   # pkg_classnum
995   #   all_pkg_classnums
996   #   any_pkg_status
997   if ( $params->{'pkg_classnum'} ) {
998     my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
999                           @{ $params->{'pkg_classnum'} } :
1000                              $params->{'pkg_classnum'};
1001     @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1002
1003     if ( @pkg_classnums ) {
1004
1005       my @pkg_where;
1006       if ( $params->{'all_pkg_classnums'} ) {
1007         push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1008       } else {
1009         push @pkg_where,
1010           'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1011       }
1012       foreach (@pkg_where) {
1013         my $select_pkg = 
1014           "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1015           "cust_pkg.custnum = cust_main.custnum AND $_ ";
1016         if ( not $params->{'any_pkg_status'} ) {
1017           $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1018         }
1019         push @where, "EXISTS($select_pkg)";
1020       }
1021     }
1022   }
1023
1024   ##
1025   # setup queries, subs, etc. for the search
1026   ##
1027
1028   $orderby ||= 'ORDER BY custnum';
1029
1030   # here is the agent virtualization
1031   push @where,
1032     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1033
1034   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1035
1036   my $addl_from = '';
1037   # always make address fields available in results
1038   for my $pre ('bill_', 'ship_') {
1039     $addl_from .= 
1040       'LEFT JOIN cust_location AS '.$pre.'location '.
1041       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1042   }
1043
1044   # always make referral available in results
1045   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
1046   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1047
1048   my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1049
1050   my @select = (
1051                  'cust_main.custnum',
1052                  'cust_main.salesnum',
1053                  # there's a good chance that we'll need these
1054                  'cust_main.bill_locationnum',
1055                  'cust_main.ship_locationnum',
1056                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1057                );
1058
1059   my @extra_headers     = ();
1060   my @extra_fields      = ();
1061   my @extra_sort_fields = ();
1062
1063   ## search contacts
1064   if ($params->{'contacts'}) {
1065     my $contact_params = $params->{'contacts'};
1066
1067     $addl_from .=
1068       ' LEFT JOIN cust_contact ON ( cust_main.custnum = cust_contact.custnum ) ';
1069
1070     if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
1071       $addl_from .= ' LEFT JOIN contact ON ( cust_contact.contactnum = contact.contactnum ) ';
1072       my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
1073         unless !$contact_params->{'contacts_firstname'};
1074       my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
1075         unless !$contact_params->{'contacts_lastname'};
1076       $extra_sql .= " AND ( '1' $first_query $last_query )";
1077     }
1078
1079     if ($contact_params->{'contacts_email'}) {
1080       $addl_from .= ' LEFT JOIN contact_email ON ( cust_contact.contactnum = contact_email.contactnum ) ';
1081       $extra_sql .= " AND ( contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "' )";
1082     }
1083
1084     if ($contact_params->{'contacts_homephone'} || $contact_params->{'contacts_workphone'} || $contact_params->{'contacts_mobilephone'}) {
1085       $addl_from .= ' LEFT JOIN contact_phone ON ( cust_contact.contactnum = contact_phone.contactnum ) ';
1086       my $contacts_mobilephone;
1087       foreach my $phone (qw( contacts_homephone contacts_workphone contacts_mobilephone )) {
1088         (my $num = $contact_params->{$phone}) =~ s/\W//g;
1089         if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
1090       }
1091       my $home_query = " AND ( contact_phone.phonetypenum = '2' AND contact_phone.phonenum = '" . $contact_params->{'contacts_homephone'} . "' )"
1092         unless !$contact_params->{'contacts_homephone'};
1093       my $work_query = " AND ( contact_phone.phonetypenum = '1' AND contact_phone.phonenum = '" . $contact_params->{'contacts_workphone'} . "' )"
1094         unless !$contact_params->{'contacts_workphone'};
1095       my $mobile_query = " AND ( contact_phone.phonetypenum = '3' AND contact_phone.phonenum = '" . $contact_params->{'contacts_mobilephone'} . "' )"
1096         unless !$contact_params->{'contacts_mobilephone'};
1097       $extra_sql .= " AND ( '1' $home_query $work_query $mobile_query )";
1098     }
1099
1100   }
1101
1102   if ($params->{'flattened_pkgs'}) {
1103
1104     #my $pkg_join = '';
1105     $addl_from .=
1106       ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1107
1108     if ($dbh->{Driver}->{Name} eq 'Pg') {
1109
1110       push @select, "
1111         ARRAY_TO_STRING(
1112           ARRAY(
1113             SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1114               WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1115           ), '|'
1116         ) AS magic
1117       ";
1118
1119     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1120       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1121       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1122       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1123     } else {
1124       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
1125            "omitting package information from report.";
1126     }
1127
1128     my $header_query = "
1129       SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1130         FROM cust_main $addl_from $extra_sql $pkgwhere
1131           GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1132     ";
1133
1134     my $sth = dbh->prepare($header_query) or die dbh->errstr;
1135     $sth->execute() or die $sth->errstr;
1136     my $headerrow = $sth->fetchrow_arrayref;
1137     my $headercount = $headerrow ? $headerrow->[0] : 0;
1138     while($headercount) {
1139       unshift @extra_headers, "Package ". $headercount;
1140       unshift @extra_fields, eval q!sub {my $c = shift;
1141                                          my @a = split '\|', $c->magic;
1142                                          my $p = $a[!.--$headercount. q!];
1143                                          $p;
1144                                         };!;
1145       unshift @extra_sort_fields, '';
1146     }
1147
1148   }
1149
1150   if ( $params->{'with_referrals'} ) {
1151
1152     #XXX next: num for each customer status
1153      
1154     push @select,
1155       '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1156            WHERE cust_main.custnum = referred_cust_main.referral_custnum
1157        ) AS num_referrals';
1158
1159     unshift @extra_headers, 'Referrals';
1160     unshift @extra_fields, 'num_referrals';
1161     unshift @extra_sort_fields, 'num_referrals';
1162
1163   }
1164
1165   my $select = join(', ', @select);
1166
1167   my $sql_query = {
1168     'table'             => 'cust_main',
1169     'select'            => $select,
1170     'addl_from'         => $addl_from,
1171     'hashref'           => {},
1172     'extra_sql'         => $extra_sql,
1173     'order_by'          => $orderby,
1174     'count_query'       => $count_query,
1175     'extra_headers'     => \@extra_headers,
1176     'extra_fields'      => \@extra_fields,
1177     'extra_sort_fields' => \@extra_sort_fields,
1178   };
1179   $sql_query;
1180
1181 }
1182
1183 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1184
1185 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1186 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1187 specified.
1188
1189 Additional options are the same as FS::Record::qsearch
1190
1191 =cut
1192
1193 sub fuzzy_search {
1194   my $self = shift;
1195   my $fuzzy = shift;
1196   # sensible defaults, then merge in any passed options
1197   my %fuzopts = (
1198     'table'     => 'cust_main',
1199     'addl_from' => '',
1200     'extra_sql' => '',
1201     'hashref'   => {},
1202     @_
1203   );
1204
1205   my @cust_main = ();
1206
1207   my @fuzzy_mod = 'i';
1208   my $conf = new FS::Conf;
1209   my $fuzziness = $conf->config('fuzzy-fuzziness');
1210   push @fuzzy_mod, $fuzziness if $fuzziness;
1211
1212   check_and_rebuild_fuzzyfiles();
1213   foreach my $field ( keys %$fuzzy ) {
1214
1215     my $all = $self->all_X($field);
1216     next unless scalar(@$all);
1217
1218     my %match = ();
1219     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1220     next if !keys(%match);
1221
1222     my $in_matches = 'IN (' .
1223                      join(',', map { dbh->quote($_) } keys %match) .
1224                      ')';
1225
1226     my $extra_sql = $fuzopts{extra_sql};
1227     if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1228       $extra_sql .= ' AND ';
1229     } else {
1230       $extra_sql .= 'WHERE ';
1231     }
1232     $extra_sql .= "$field $in_matches";
1233
1234     my $addl_from = $fuzopts{addl_from};
1235     if ( $field =~ /^cust_location\./ ) {
1236       $addl_from .= ' JOIN cust_location USING (custnum)';
1237     } elsif ( $field =~ /^contact\./ ) {
1238       $addl_from .= ' JOIN contact USING (custnum)';
1239     }
1240
1241     push @cust_main, qsearch({
1242       %fuzopts,
1243       'addl_from' => $addl_from,
1244       'extra_sql' => $extra_sql,
1245     });
1246   }
1247
1248   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1249   my %saw = ();
1250   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1251
1252   @cust_main;
1253
1254 }
1255
1256 =back
1257
1258 =head1 UTILITY SUBROUTINES
1259
1260 =over 4
1261
1262 =item check_and_rebuild_fuzzyfiles
1263
1264 =cut
1265
1266 sub check_and_rebuild_fuzzyfiles {
1267   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1268   rebuild_fuzzyfiles()
1269     if grep { ! -e "$dir/$_" }
1270          map {
1271                my ($field, $table) = reverse split('\.', $_);
1272                $table ||= 'cust_main';
1273                "$table.$field"
1274              }
1275            @fuzzyfields;
1276 }
1277
1278 =item rebuild_fuzzyfiles
1279
1280 =cut
1281
1282 sub rebuild_fuzzyfiles {
1283
1284   use Fcntl qw(:flock);
1285
1286   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1287   mkdir $dir, 0700 unless -d $dir;
1288
1289   foreach my $fuzzy ( @fuzzyfields ) {
1290
1291     my ($field, $table) = reverse split('\.', $fuzzy);
1292     $table ||= 'cust_main';
1293
1294     open(LOCK,">>$dir/$table.$field")
1295       or die "can't open $dir/$table.$field: $!";
1296     flock(LOCK,LOCK_EX)
1297       or die "can't lock $dir/$table.$field: $!";
1298
1299     open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1300       or die "can't open $dir/$table.$field.tmp: $!";
1301
1302     my $sth = dbh->prepare(
1303       "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1304     );
1305     $sth->execute or die $sth->errstr;
1306
1307     while ( my $row = $sth->fetchrow_arrayref ) {
1308       print CACHE $row->[0]. "\n";
1309     }
1310
1311     close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1312   
1313     rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1314     close LOCK;
1315   }
1316
1317 }
1318
1319 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1320
1321 =cut
1322
1323 sub append_fuzzyfiles {
1324   #my( $first, $last, $company ) = @_;
1325
1326   check_and_rebuild_fuzzyfiles();
1327
1328   #foreach my $fuzzy (@fuzzyfields) {
1329   foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company', 
1330                       'cust_location.address1',
1331                       'cust_main.ship_company',
1332                     ) {
1333
1334     append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1335
1336   }
1337
1338   1;
1339 }
1340
1341 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1342
1343 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1344
1345 =cut
1346
1347 use Fcntl qw(:flock);
1348 sub append_fuzzyfiles_fuzzyfield {
1349   my( $fuzzyfield, $value ) = @_;
1350
1351   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1352
1353
1354   my ($field, $table) = reverse split('\.', $fuzzyfield);
1355   $table ||= 'cust_main';
1356
1357   return unless defined($value) && length($value);
1358
1359   open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1360     or die "can't open $dir/$table.$field: $!";
1361   flock(CACHE,LOCK_EX)
1362     or die "can't lock $dir/$table.$field: $!";
1363
1364   print CACHE "$value\n";
1365
1366   flock(CACHE,LOCK_UN)
1367     or die "can't unlock $dir/$table.$field: $!";
1368   close CACHE;
1369
1370 }
1371
1372 =item all_X
1373
1374 =cut
1375
1376 sub all_X {
1377   my( $self, $fuzzy ) = @_;
1378   my ($field, $table) = reverse split('\.', $fuzzy);
1379   $table ||= 'cust_main';
1380
1381   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1382   open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1383     or die "can't open $dir/$table.$field: $!";
1384   my @array = map { chomp; $_; } <CACHE>;
1385   close CACHE;
1386   \@array;
1387 }
1388
1389 =head1 BUGS
1390
1391 Bed bugs
1392
1393 =head1 SEE ALSO
1394
1395 L<FS::cust_main>, L<FS::Record>
1396
1397 =cut
1398
1399 1;
1400