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