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