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