Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
363         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
364       );
365
366       my @hashrefs = ();
367
368       if ( $first && $last ) {
369
370         @hashrefs = (
371           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
372             'last'         => { op=>'ILIKE', value=>"%$last%" },
373           },
374         );
375
376       } else {
377
378         @hashrefs = (
379           { 'first'        => { op=>'ILIKE', value=>"%$value%" }, },
380           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
381         );
382       }
383
384       foreach my $hashref ( @company_hashrefs, @hashrefs ) {
385
386         push @cust_main, qsearch( {
387           'table'     => 'cust_main',
388           'hashref'   => { %$hashref,
389                            %options,
390                          },
391           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
392         } );
393
394       }
395
396       if ( $conf->exists('address1-search') ) {
397
398         push @cust_main, qsearch( {
399           table     => 'cust_main',
400           addl_from => 'JOIN cust_location USING (custnum)',
401           extra_sql => 'WHERE '.
402                         ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
403                         " AND $agentnums_sql", #agent virtualizaiton
404         } );
405
406       }
407
408       #contact substring
409
410       foreach my $hashref ( @hashrefs ) {
411
412         push @cust_main,
413           grep $agentnums_href->{$_->agentnum}, #agent virt
414             grep $_, #skip contacts that don't have cust_main records
415               map $_->cust_main,
416                 qsearch({
417                           'table'     => 'contact',
418                           'hashref'   => { %$hashref,
419                                            #%options,
420                                          },
421                           #'extra_sql' => " AND $agentnums_sql", #agent virt
422                        });
423
424       }
425
426       #fuzzy
427       my %fuzopts = (
428         'hashref'   => \%options,
429         'select'    => '',
430         'extra_sql' => "WHERE $agentnums_sql",    #agent virtualization
431       );
432
433       if ( $first && $last ) {
434         push @cust_main, FS::cust_main::Search->fuzzy_search(
435           { 'last'   => $last,    #fuzzy hashref
436             'first'  => $first }, #
437           %fuzopts
438         );
439         push @cust_main, FS::cust_main::Search->fuzzy_search(
440           { 'contact.last'   => $last,    #fuzzy hashref
441             'contact.first'  => $first }, #
442           %fuzopts
443         );
444      }
445       foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
446         push @cust_main, FS::cust_main::Search->fuzzy_search(
447           { $field => $value },
448           %fuzopts
449         );
450       }
451       foreach my $field ( 'first', 'last' ) {
452         push @cust_main, FS::cust_main::Search->fuzzy_search(
453           { "contact.$field" => $value },
454           %fuzopts
455         );
456       }
457       if ( $conf->exists('address1-search') ) {
458         push @cust_main,
459           FS::cust_main::Search->fuzzy_search(
460             { 'cust_location.address1' => $value },
461             %fuzopts
462         );
463       }
464
465     }
466
467   }
468
469   ( my $nospace_search = $search ) =~ s/\s//g;
470   ( my $card_search = $nospace_search ) =~ s/\-//g;
471   $card_search =~ s/[x\*\.\_]/x/gi;
472   
473   if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
474
475     ( my $like_search = $card_search ) =~ s/x/_/g;
476     my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
477
478     push @cust_main, qsearch({
479       'table'     => 'cust_main',
480       'addl_from' => ' JOIN cust_payby USING (custnum)',
481       'hashref'   => {},
482       'extra_sql' => " WHERE (    cust_payby.payinfo LIKE '$like_search'
483                                OR cust_payby.paymask =    '$mask_search'
484                              ) ".
485                      " AND cust_payby.payby IN ('CARD','DCRD') ".
486                      " AND $agentnums_sql", #agent virtulization
487     });
488
489   }
490   
491
492   #eliminate duplicates
493   my %saw = ();
494   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
495
496   @cust_main;
497
498 }
499
500 =item email_search
501
502 Accepts the following options: I<email>, the email address to search for.  The
503 email address will be searched for as an email invoice destination and as an
504 svc_acct account.
505
506 #Any additional options are treated as an additional qualifier on the search
507 #(i.e. I<agentnum>).
508
509 Returns a (possibly empty) array of FS::cust_main objects (but usually just
510 none or one).
511
512 =cut
513
514 sub email_search {
515   my %options = @_;
516
517   my $email = delete $options{'email'};
518
519   #no agent virtualization yet
520   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
521
522   my @cust_main = ();
523
524   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
525
526     my ( $user, $domain ) = ( $1, $2 );
527
528     warn "$me smart_search: searching for $user in domain $domain"
529       if $DEBUG;
530
531     push @cust_main,
532       map { $_->cust_main }
533       map { $_->cust_contact }
534       map { $_->contact }
535           qsearch( {
536                      'table'     => 'contact_email',
537                      'hashref'   => { 'emailaddress' => $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 current_balance
612
613 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
614
615 =item cust_fields
616
617 =item flattened_pkgs
618
619 bool
620
621 =back
622
623 =cut
624
625 sub search {
626   my ($class, $params) = @_;
627
628   my $dbh = dbh;
629
630   my @where = ();
631   my $orderby;
632
633   # initialize these to prevent warnings
634   $params = {
635     'custnum'       => '',
636     'agentnum'      => '',
637     'usernum'       => '',
638     'status'        => '',
639     'address'       => '',
640     'zip'           => '',
641     'invoice_terms' => '',
642     'custbatch'     => '',
643     %$params
644   };
645
646   ##
647   # explicit custnum(s)
648   ##
649
650   if ( $params->{'custnum'} ) {
651     my @custnums = ref($params->{'custnum'}) ? 
652                       @{ $params->{'custnum'} } : 
653                       $params->{'custnum'};
654     push @where, 
655       'cust_main.custnum IN (' . 
656       join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
657       ')' if scalar(@custnums) > 0;
658   }
659
660   ##
661   # parse agent
662   ##
663
664   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
665     push @where,
666       "cust_main.agentnum = $1";
667   }
668
669   ##
670   # parse sales person
671   ##
672
673   if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
674     push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
675                            : 'cust_main.salesnum IS NULL';
676   }
677
678   ##
679   # parse usernum
680   ##
681
682   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
683     push @where,
684       "cust_main.usernum = $1";
685   }
686
687   ##
688   # parse status
689   ##
690
691   #prospect ordered active inactive suspended cancelled
692   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
693     my $method = $params->{'status'}. '_sql';
694     #push @where, $class->$method();
695     push @where, FS::cust_main->$method();
696   }
697
698   my $current = '';
699   unless ( $params->{location_history} ) {
700     $current = '
701       AND (    cust_location.locationnum IN ( cust_main.bill_locationnum,
702                                               cust_main.ship_locationnum
703                                             )
704             OR cust_location.locationnum IN (
705                  SELECT locationnum FROM cust_pkg
706                   WHERE cust_pkg.custnum = cust_main.custnum
707                     AND locationnum IS NOT NULL
708                     AND '. FS::cust_pkg->ncancelled_recurring_sql.'
709                )
710           )';
711   }
712
713   ##
714   # address
715   ##
716   if ( $params->{'address'} ) {
717     # allow this to be an arrayref
718     my @values = ($params->{'address'});
719     @values = @{$values[0]} if ref($values[0]);
720     my @orwhere;
721     foreach (grep /\S/, @values) {
722       my $address = dbh->quote('%'. lc($_). '%');
723       push @orwhere,
724         "LOWER(cust_location.address1) LIKE $address",
725         "LOWER(cust_location.address2) LIKE $address";
726     }
727     if (@orwhere) {
728       push @where, "EXISTS(
729         SELECT 1 FROM cust_location 
730         WHERE cust_location.custnum = cust_main.custnum
731           AND (".join(' OR ',@orwhere).")
732           $current
733         )";
734     }
735   }
736
737   ##
738   # city
739   ##
740   if ( $params->{'city'} =~ /\S/ ) {
741     my $city = dbh->quote($params->{'city'});
742     push @where, "EXISTS(
743       SELECT 1 FROM cust_location
744       WHERE cust_location.custnum = cust_main.custnum
745         AND cust_location.city = $city
746         $current
747     )";
748   }
749
750   ##
751   # county
752   ##
753   if ( $params->{'county'} =~ /\S/ ) {
754     my $county = dbh->quote($params->{'county'});
755     push @where, "EXISTS(
756       SELECT 1 FROM cust_location
757       WHERE cust_location.custnum = cust_main.custnum
758         AND cust_location.county = $county
759         $current
760     )";
761   }
762
763   ##
764   # state
765   ##
766   if ( $params->{'state'} =~ /\S/ ) {
767     my $state = dbh->quote($params->{'state'});
768     push @where, "EXISTS(
769       SELECT 1 FROM cust_location
770       WHERE cust_location.custnum = cust_main.custnum
771         AND cust_location.state = $state
772         $current
773     )";
774   }
775
776   ##
777   # zipcode
778   ##
779   if ( $params->{'zip'} =~ /\S/ ) {
780     my $zip = dbh->quote($params->{'zip'} . '%');
781     push @where, "EXISTS(
782       SELECT 1 FROM cust_location
783       WHERE cust_location.custnum = cust_main.custnum
784         AND cust_location.zip LIKE $zip
785         $current
786     )";
787   }
788
789   ##
790   # country
791   ##
792   if ( $params->{'country'} =~ /^(\w\w)$/ ) {
793     my $country = uc($1);
794     push @where, "EXISTS(
795       SELECT 1 FROM cust_location
796       WHERE cust_location.custnum = cust_main.custnum
797         AND cust_location.country = '$country'
798         $current
799     )";
800   }
801
802   ###
803   # refnum
804   ###
805   if ( $params->{'refnum'}  ) {
806
807     my @refnum = ref( $params->{'refnum'} )
808                    ? @{ $params->{'refnum'} }
809                    :  ( $params->{'refnum'} );
810
811     @refnum = grep /^(\d*)$/, @refnum;
812
813     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
814       if @refnum;
815
816   }
817
818   ##
819   # parse cancelled package checkbox
820   ##
821
822   my $pkgwhere = "";
823
824   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
825     unless $params->{'cancelled_pkgs'};
826
827   ##
828   # "with email address(es)" checkbox
829   ##
830
831   push @where,
832     'EXISTS ( SELECT 1 FROM contact_email
833                 JOIN cust_contact USING (contactnum)
834                 WHERE cust_contact.custnum = cust_main.custnum
835             )'
836     if $params->{'with_email'};
837
838   ##
839   # "with postal mail invoices" checkbox
840   ##
841
842   push @where, "cust_main.postal_invoice = 'Y'"
843     if $params->{'POST'};
844
845   ##
846   # "without postal mail invoices" checkbox
847   ##
848
849   push @where, "cust_main.postal_invoice IS NULL"
850     if $params->{'no_POST'};
851
852   ##
853   # "tax exempt" checkbox
854   ##
855   push @where, "cust_main.tax = 'Y'"
856     if $params->{'tax'};
857
858   ##
859   # "not tax exempt" checkbox
860   ##
861   push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
862     if $params->{'no_tax'};
863
864   ##
865   # dates
866   ##
867
868   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
869
870     next unless exists($params->{$field});
871
872     my($beginning, $ending, $hour) = @{$params->{$field}};
873
874     push @where,
875       "cust_main.$field IS NOT NULL",
876       "cust_main.$field >= $beginning",
877       "cust_main.$field <= $ending";
878
879     if($field eq 'signupdate' && defined $hour) {
880       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
881         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
882       }
883       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
884         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
885       }
886       else {
887         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
888       }
889     }
890
891     $orderby ||= "ORDER BY cust_main.$field";
892
893   }
894
895   ###
896   # classnum
897   ###
898
899   if ( $params->{'classnum'} ) {
900
901     my @classnum = ref( $params->{'classnum'} )
902                      ? @{ $params->{'classnum'} }
903                      :  ( $params->{'classnum'} );
904
905     @classnum = grep /^(\d*)$/, @classnum;
906
907     if ( @classnum ) {
908       push @where, '( '. join(' OR ', map {
909                                             $_ ? "cust_main.classnum = $_"
910                                                : "cust_main.classnum IS NULL"
911                                           }
912                                           @classnum
913                              ).
914                    ' )';
915     }
916
917   }
918
919   ###
920   # invoice terms
921   ###
922
923   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
924     my $terms = $1;
925     if ( $1 eq 'NULL' ) {
926       push @where,
927         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
928     } else {
929       push @where,
930         "cust_main.invoice_terms IS NOT NULL",
931         "cust_main.invoice_terms = '$1'";
932     }
933   }
934
935   ##
936   # amounts
937   ##
938
939   if ( $params->{'current_balance'} ) {
940
941     #my $balance_sql = $class->balance_sql();
942     my $balance_sql = FS::cust_main->balance_sql();
943
944     my @current_balance =
945       ref( $params->{'current_balance'} )
946       ? @{ $params->{'current_balance'} }
947       :  ( $params->{'current_balance'} );
948
949     push @where, map { s/current_balance/$balance_sql/; $_ }
950                      @current_balance;
951
952   }
953
954   ##
955   # custbatch
956   ##
957
958   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
959     push @where,
960       "cust_main.custbatch = '$1'";
961   }
962   
963   if ( $params->{'tagnum'} ) {
964     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
965
966     @tagnums = grep /^(\d+)$/, @tagnums;
967
968     if ( @tagnums ) {
969       if ( $params->{'all_tags'} ) {
970         foreach ( @tagnums ) {
971           push @where, 'exists(select 1 from cust_tag where '.
972                        'cust_tag.custnum = cust_main.custnum and tagnum = '.
973                        $_ . ')';
974         }
975       } else { # matching any tag, not all
976         my $tags_where = "0 < (select count(1) from cust_tag where " 
977                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
978                 . join(',', @tagnums) . "))";
979
980         push @where, $tags_where;
981       }
982     }
983   }
984
985   # pkg_classnum
986   #   all_pkg_classnums
987   #   any_pkg_status
988   if ( $params->{'pkg_classnum'} ) {
989     my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
990                           @{ $params->{'pkg_classnum'} } :
991                              $params->{'pkg_classnum'};
992     @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
993
994     if ( @pkg_classnums ) {
995
996       my @pkg_where;
997       if ( $params->{'all_pkg_classnums'} ) {
998         push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
999       } else {
1000         push @pkg_where,
1001           'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1002       }
1003       foreach (@pkg_where) {
1004         my $select_pkg = 
1005           "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1006           "cust_pkg.custnum = cust_main.custnum AND $_ ";
1007         if ( not $params->{'any_pkg_status'} ) {
1008           $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1009         }
1010         push @where, "EXISTS($select_pkg)";
1011       }
1012     }
1013   }
1014
1015   ##
1016   # setup queries, subs, etc. for the search
1017   ##
1018
1019   $orderby ||= 'ORDER BY custnum';
1020
1021   # here is the agent virtualization
1022   push @where,
1023     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1024
1025   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1026
1027   my $addl_from = '';
1028   # always make address fields available in results
1029   for my $pre ('bill_', 'ship_') {
1030     $addl_from .= 
1031       'LEFT JOIN cust_location AS '.$pre.'location '.
1032       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1033   }
1034
1035   # always make referral available in results
1036   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
1037   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1038
1039   my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1040
1041   my @select = (
1042                  'cust_main.custnum',
1043                  'cust_main.salesnum',
1044                  # there's a good chance that we'll need these
1045                  'cust_main.bill_locationnum',
1046                  'cust_main.ship_locationnum',
1047                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1048                );
1049
1050   my(@extra_headers) = ();
1051   my(@extra_fields)  = ();
1052
1053   if ($params->{'flattened_pkgs'}) {
1054
1055     #my $pkg_join = '';
1056     $addl_from .=
1057       ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1058
1059     if ($dbh->{Driver}->{Name} eq 'Pg') {
1060
1061       push @select, "
1062         ARRAY_TO_STRING(
1063           ARRAY(
1064             SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1065               WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1066           ), '|'
1067         ) AS magic
1068       ";
1069
1070     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1071       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1072       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1073       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1074     } else {
1075       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
1076            "omitting package information from report.";
1077     }
1078
1079     my $header_query = "
1080       SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1081         FROM cust_main $addl_from $extra_sql $pkgwhere
1082           GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1083     ";
1084
1085     my $sth = dbh->prepare($header_query) or die dbh->errstr;
1086     $sth->execute() or die $sth->errstr;
1087     my $headerrow = $sth->fetchrow_arrayref;
1088     my $headercount = $headerrow ? $headerrow->[0] : 0;
1089     while($headercount) {
1090       unshift @extra_headers, "Package ". $headercount;
1091       unshift @extra_fields, eval q!sub {my $c = shift;
1092                                          my @a = split '\|', $c->magic;
1093                                          my $p = $a[!.--$headercount. q!];
1094                                          $p;
1095                                         };!;
1096     }
1097
1098   }
1099
1100   my $select = join(', ', @select);
1101
1102   my $sql_query = {
1103     'table'         => 'cust_main',
1104     'select'        => $select,
1105     'addl_from'     => $addl_from,
1106     'hashref'       => {},
1107     'extra_sql'     => $extra_sql,
1108     'order_by'      => $orderby,
1109     'count_query'   => $count_query,
1110     'extra_headers' => \@extra_headers,
1111     'extra_fields'  => \@extra_fields,
1112   };
1113   $sql_query;
1114
1115 }
1116
1117 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1118
1119 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1120 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1121 specified.
1122
1123 Additional options are the same as FS::Record::qsearch
1124
1125 =cut
1126
1127 sub fuzzy_search {
1128   my $self = shift;
1129   my $fuzzy = shift;
1130   # sensible defaults, then merge in any passed options
1131   my %fuzopts = (
1132     'table'     => 'cust_main',
1133     'addl_from' => '',
1134     'extra_sql' => '',
1135     'hashref'   => {},
1136     @_
1137   );
1138
1139   my @cust_main = ();
1140
1141   my @fuzzy_mod = 'i';
1142   my $conf = new FS::Conf;
1143   my $fuzziness = $conf->config('fuzzy-fuzziness');
1144   push @fuzzy_mod, $fuzziness if $fuzziness;
1145
1146   check_and_rebuild_fuzzyfiles();
1147   foreach my $field ( keys %$fuzzy ) {
1148
1149     my $all = $self->all_X($field);
1150     next unless scalar(@$all);
1151
1152     my %match = ();
1153     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1154     next if !keys(%match);
1155
1156     my $in_matches = 'IN (' .
1157                      join(',', map { dbh->quote($_) } keys %match) .
1158                      ')';
1159
1160     my $extra_sql = $fuzopts{extra_sql};
1161     if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1162       $extra_sql .= ' AND ';
1163     } else {
1164       $extra_sql .= 'WHERE ';
1165     }
1166     $extra_sql .= "$field $in_matches";
1167
1168     my $addl_from = $fuzopts{addl_from};
1169     if ( $field =~ /^cust_location\./ ) {
1170       $addl_from .= ' JOIN cust_location USING (custnum)';
1171     } elsif ( $field =~ /^contact\./ ) {
1172       $addl_from .= ' JOIN contact USING (custnum)';
1173     }
1174
1175     push @cust_main, qsearch({
1176       %fuzopts,
1177       'addl_from' => $addl_from,
1178       'extra_sql' => $extra_sql,
1179     });
1180   }
1181
1182   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1183   my %saw = ();
1184   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1185
1186   @cust_main;
1187
1188 }
1189
1190 =back
1191
1192 =head1 UTILITY SUBROUTINES
1193
1194 =over 4
1195
1196 =item check_and_rebuild_fuzzyfiles
1197
1198 =cut
1199
1200 sub check_and_rebuild_fuzzyfiles {
1201   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1202   rebuild_fuzzyfiles()
1203     if grep { ! -e "$dir/$_" }
1204          map {
1205                my ($field, $table) = reverse split('\.', $_);
1206                $table ||= 'cust_main';
1207                "$table.$field"
1208              }
1209            @fuzzyfields;
1210 }
1211
1212 =item rebuild_fuzzyfiles
1213
1214 =cut
1215
1216 sub rebuild_fuzzyfiles {
1217
1218   use Fcntl qw(:flock);
1219
1220   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1221   mkdir $dir, 0700 unless -d $dir;
1222
1223   foreach my $fuzzy ( @fuzzyfields ) {
1224
1225     my ($field, $table) = reverse split('\.', $fuzzy);
1226     $table ||= 'cust_main';
1227
1228     open(LOCK,">>$dir/$table.$field")
1229       or die "can't open $dir/$table.$field: $!";
1230     flock(LOCK,LOCK_EX)
1231       or die "can't lock $dir/$table.$field: $!";
1232
1233     open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1234       or die "can't open $dir/$table.$field.tmp: $!";
1235
1236     my $sth = dbh->prepare(
1237       "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1238     );
1239     $sth->execute or die $sth->errstr;
1240
1241     while ( my $row = $sth->fetchrow_arrayref ) {
1242       print CACHE $row->[0]. "\n";
1243     }
1244
1245     close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1246   
1247     rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1248     close LOCK;
1249   }
1250
1251 }
1252
1253 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1254
1255 =cut
1256
1257 sub append_fuzzyfiles {
1258   #my( $first, $last, $company ) = @_;
1259
1260   check_and_rebuild_fuzzyfiles();
1261
1262   #foreach my $fuzzy (@fuzzyfields) {
1263   foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company', 
1264                       'cust_location.address1',
1265                       'cust_main.ship_company',
1266                     ) {
1267
1268     append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1269
1270   }
1271
1272   1;
1273 }
1274
1275 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1276
1277 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1278
1279 =cut
1280
1281 use Fcntl qw(:flock);
1282 sub append_fuzzyfiles_fuzzyfield {
1283   my( $fuzzyfield, $value ) = @_;
1284
1285   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1286
1287
1288   my ($field, $table) = reverse split('\.', $fuzzyfield);
1289   $table ||= 'cust_main';
1290
1291   return unless defined($value) && length($value);
1292
1293   open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1294     or die "can't open $dir/$table.$field: $!";
1295   flock(CACHE,LOCK_EX)
1296     or die "can't lock $dir/$table.$field: $!";
1297
1298   print CACHE "$value\n";
1299
1300   flock(CACHE,LOCK_UN)
1301     or die "can't unlock $dir/$table.$field: $!";
1302   close CACHE;
1303
1304 }
1305
1306 =item all_X
1307
1308 =cut
1309
1310 sub all_X {
1311   my( $self, $fuzzy ) = @_;
1312   my ($field, $table) = reverse split('\.', $fuzzy);
1313   $table ||= 'cust_main';
1314
1315   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1316   open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1317     or die "can't open $dir/$table.$field: $!";
1318   my @array = map { chomp; $_; } <CACHE>;
1319   close CACHE;
1320   \@array;
1321 }
1322
1323 =head1 BUGS
1324
1325 Bed bugs
1326
1327 =head1 SEE ALSO
1328
1329 L<FS::cust_main>, L<FS::Record>
1330
1331 =cut
1332
1333 1;
1334