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