searching kingcon's idea of legacy customer numbers without remembering leading 0s
[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
13 @EXPORT_OK = qw( smart_search );
14
15 # 1 is mostly method/subroutine entry and options
16 # 2 traces progress of some operations
17 # 3 is even more information including possibly sensitive data
18 $DEBUG = 0;
19 $me = '[FS::cust_main::Search]';
20
21 @fuzzyfields = @FS::cust_main::fuzzyfields;
22
23 install_callback FS::UID sub { 
24   $conf = new FS::Conf;
25   #yes, need it for stuff below (prolly should be cached)
26 };
27
28 =head1 NAME
29
30 FS::cust_main::Search - Customer searching
31
32 =head1 SYNOPSIS
33
34   use FS::cust_main::Search;
35
36   FS::cust_main::Search::smart_search(%options);
37
38   FS::cust_main::Search::email_search(%options);
39
40   FS::cust_main::Search->search( \%options );
41   
42   FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
43
44 =head1 SUBROUTINES
45
46 =over 4
47
48 =item smart_search OPTION => VALUE ...
49
50 Accepts the following options: I<search>, the string to search for.  The string
51 will be searched for as a customer number, phone number, name or company name,
52 as an exact, or, in some cases, a substring or fuzzy match (see the source code
53 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
54 skip fuzzy matching when an exact match is found.
55
56 Any additional options are treated as an additional qualifier on the search
57 (i.e. I<agentnum>).
58
59 Returns a (possibly empty) array of FS::cust_main objects.
60
61 =cut
62
63 sub smart_search {
64   my %options = @_;
65
66   #here is the agent virtualization
67   my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
68
69   my @cust_main = ();
70
71   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
72   my $search = delete $options{'search'};
73   ( my $alphanum_search = $search ) =~ s/\W//g;
74   
75   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
76
77     #false laziness w/Record::ut_phone
78     my $phonen = "$1-$2-$3";
79     $phonen .= " x$4" if $4;
80
81     push @cust_main, qsearch( {
82       'table'   => 'cust_main',
83       'hashref' => { %options },
84       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
85                      ' ( '.
86                          join(' OR ', map "$_ = '$phonen'",
87                                           qw( daytime night fax
88                                               ship_daytime ship_night ship_fax )
89                              ).
90                      ' ) '.
91                      " AND $agentnums_sql", #agent virtualization
92     } );
93
94     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
95       #try looking for matches with extensions unless one was specified
96
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 "$_ LIKE '$phonen\%'",
103                                             qw( daytime night
104                                                 ship_daytime ship_night )
105                                ).
106                        ' ) '.
107                        " AND $agentnums_sql", #agent virtualization
108       } );
109
110     }
111
112   # custnum search (also try agent_custid), with some tweaking options if your
113   # legacy cust "numbers" have letters
114   } 
115   
116   
117   if ( $search =~ /@/ ) {
118       push @cust_main,
119           map $_->cust_main,
120               qsearch( {
121                          'table'     => 'cust_main_invoice',
122                          'hashref'   => { 'dest' => $search },
123                        }
124                      );
125   } elsif ( $search =~ /^\s*(\d+)\s*$/
126          || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
127               && $search =~ /^\s*(\w\w?\d+)\s*$/
128             )
129          || ( $conf->exists('address1-search' )
130               && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
131             )
132      )
133   {
134
135     my $num = $1;
136
137     if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
138       push @cust_main, qsearch( {
139         'table'     => 'cust_main',
140         'hashref'   => { 'custnum' => $num, %options },
141         'extra_sql' => " AND $agentnums_sql", #agent virtualization
142       } );
143     }
144
145     my $anum = $num;
146     if ( $conf->config('cust_main-agent_custid-format') =~ /^\\d\{(\d+)\}$/ ) {
147       $anum = sprintf("%0$1u", $num);
148     }
149
150     push @cust_main, qsearch( {
151       'table'     => 'cust_main',
152       'hashref'   => { 'agent_custid' => $anum, %options },
153       'extra_sql' => " AND $agentnums_sql", #agent virtualization
154     } );
155
156     if ( $conf->exists('address1-search') ) {
157       my $len = length($num);
158       $num = lc($num);
159       foreach my $prefix ( '', 'ship_' ) {
160         push @cust_main, qsearch( {
161           'table'     => 'cust_main',
162           'hashref'   => { %options, },
163           'extra_sql' => 
164             ( keys(%options) ? ' AND ' : ' WHERE ' ).
165             " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
166             " AND $agentnums_sql",
167         } );
168       }
169     }
170
171   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
172
173     my($company, $last, $first) = ( $1, $2, $3 );
174
175     # "Company (Last, First)"
176     #this is probably something a browser remembered,
177     #so just do an exact search (but case-insensitive, so USPS standardization
178     #doesn't throw a wrench in the works)
179
180     foreach my $prefix ( '', 'ship_' ) {
181       push @cust_main, qsearch( {
182         'table'     => 'cust_main',
183         'hashref'   => { %options },
184         'extra_sql' => 
185           ( keys(%options) ? ' AND ' : ' WHERE ' ).
186           join(' AND ',
187             " LOWER(${prefix}first)   = ". dbh->quote(lc($first)),
188             " LOWER(${prefix}last)    = ". dbh->quote(lc($last)),
189             " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
190             $agentnums_sql,
191           ),
192       } );
193     }
194
195   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
196                                               # try (ship_){last,company}
197
198     my $value = lc($1);
199
200     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
201     # # full strings the browser remembers won't work
202     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
203
204     use Lingua::EN::NameParse;
205     my $NameParse = new Lingua::EN::NameParse(
206              auto_clean     => 1,
207              allow_reversed => 1,
208     );
209
210     my($last, $first) = ( '', '' );
211     #maybe disable this too and just rely on NameParse?
212     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
213     
214       ($last, $first) = ( $1, $2 );
215     
216     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
217     } elsif ( ! $NameParse->parse($value) ) {
218
219       my %name = $NameParse->components;
220       $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
221       $last  = $name{'surname_1'};
222
223     }
224
225     if ( $first && $last ) {
226
227       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
228
229       #exact
230       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
231       $sql .= "
232         (     ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
233            OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
234         )";
235
236       push @cust_main, qsearch( {
237         'table'     => 'cust_main',
238         'hashref'   => \%options,
239         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
240       } );
241
242       # or it just be something that was typed in... (try that in a sec)
243
244     }
245
246     my $q_value = dbh->quote($value);
247
248     #exact
249     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
250     $sql .= " (    LOWER(last)          = $q_value
251                 OR LOWER(company)       = $q_value
252                 OR LOWER(ship_last)     = $q_value
253                 OR LOWER(ship_company)  = $q_value
254             ";
255     $sql .= "   OR LOWER(address1)      = $q_value
256                 OR LOWER(ship_address1) = $q_value
257             "
258       if $conf->exists('address1-search');
259     $sql .= " )";
260
261     push @cust_main, qsearch( {
262       'table'     => 'cust_main',
263       'hashref'   => \%options,
264       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
265     } );
266
267     #no exact match, trying substring/fuzzy
268     #always do substring & fuzzy (unless they're explicity config'ed off)
269     #getting complaints searches are not returning enough
270     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
271
272       #still some false laziness w/search (was search/cust_main.cgi)
273
274       #substring
275
276       my @hashrefs = (
277         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
278         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
279       );
280
281       if ( $first && $last ) {
282
283         push @hashrefs,
284           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
285             'last'         => { op=>'ILIKE', value=>"%$last%" },
286           },
287           { 'ship_first'   => { op=>'ILIKE', value=>"%$first%" },
288             'ship_last'    => { op=>'ILIKE', value=>"%$last%" },
289           },
290         ;
291
292       } else {
293
294         push @hashrefs,
295           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
296           { 'ship_last'    => { op=>'ILIKE', value=>"%$value%" }, },
297         ;
298       }
299
300       if ( $conf->exists('address1-search') ) {
301         push @hashrefs,
302           { 'address1'      => { op=>'ILIKE', value=>"%$value%" }, },
303           { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
304         ;
305       }
306
307       foreach my $hashref ( @hashrefs ) {
308
309         push @cust_main, qsearch( {
310           'table'     => 'cust_main',
311           'hashref'   => { %$hashref,
312                            %options,
313                          },
314           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
315         } );
316
317       }
318
319       #fuzzy
320       my @fuzopts = (
321         \%options,                #hashref
322         '',                       #select
323         " AND $agentnums_sql",    #extra_sql  #agent virtualization
324       );
325
326       if ( $first && $last ) {
327         push @cust_main, FS::cust_main::Search->fuzzy_search(
328           { 'last'   => $last,    #fuzzy hashref
329             'first'  => $first }, #
330           @fuzopts
331         );
332       }
333       foreach my $field ( 'last', 'company' ) {
334         push @cust_main,
335           FS::cust_main::Search->fuzzy_search( { $field => $value }, @fuzopts );
336       }
337       if ( $conf->exists('address1-search') ) {
338         push @cust_main,
339           FS::cust_main::Search->fuzzy_search( { 'address1' => $value }, @fuzopts );
340       }
341
342     }
343
344   }
345
346   #eliminate duplicates
347   my %saw = ();
348   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
349
350   @cust_main;
351
352 }
353
354 =item email_search
355
356 Accepts the following options: I<email>, the email address to search for.  The
357 email address will be searched for as an email invoice destination and as an
358 svc_acct account.
359
360 #Any additional options are treated as an additional qualifier on the search
361 #(i.e. I<agentnum>).
362
363 Returns a (possibly empty) array of FS::cust_main objects (but usually just
364 none or one).
365
366 =cut
367
368 sub email_search {
369   my %options = @_;
370
371   local($DEBUG) = 1;
372
373   my $email = delete $options{'email'};
374
375   #we're only being used by RT at the moment... no agent virtualization yet
376   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
377
378   my @cust_main = ();
379
380   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
381
382     my ( $user, $domain ) = ( $1, $2 );
383
384     warn "$me smart_search: searching for $user in domain $domain"
385       if $DEBUG;
386
387     push @cust_main,
388       map $_->cust_main,
389           qsearch( {
390                      'table'     => 'cust_main_invoice',
391                      'hashref'   => { 'dest' => $email },
392                    }
393                  );
394
395     push @cust_main,
396       map  $_->cust_main,
397       grep $_,
398       map  $_->cust_svc->cust_pkg,
399           qsearch( {
400                      'table'     => 'svc_acct',
401                      'hashref'   => { 'username' => $user, },
402                      'extra_sql' =>
403                        'AND ( SELECT domain FROM svc_domain
404                                 WHERE svc_acct.domsvc = svc_domain.svcnum
405                             ) = '. dbh->quote($domain),
406                    }
407                  );
408   }
409
410   my %saw = ();
411   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
412
413   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
414     if $DEBUG;
415
416   @cust_main;
417
418 }
419
420 =back
421
422 =head1 CLASS METHODS
423
424 =over 4
425
426 =item search HASHREF
427
428 (Class method)
429
430 Returns a qsearch hash expression to search for parameters specified in
431 HASHREF.  Valid parameters are
432
433 =over 4
434
435 =item agentnum
436
437 =item status
438
439 =item address
440
441 =item cancelled_pkgs
442
443 bool
444
445 =item signupdate
446
447 listref of start date, end date
448
449 =item payby
450
451 listref
452
453 =item paydate_year
454
455 =item paydate_month
456
457 =item current_balance
458
459 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
460
461 =item cust_fields
462
463 =item flattened_pkgs
464
465 bool
466
467 =back
468
469 =cut
470
471 sub search {
472   my ($class, $params) = @_;
473
474   my $dbh = dbh;
475
476   my @where = ();
477   my $orderby;
478
479   ##
480   # parse agent
481   ##
482
483   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
484     push @where,
485       "cust_main.agentnum = $1";
486   }
487
488   ##
489   # do the same for user
490   ##
491
492   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
493     push @where,
494       "cust_main.usernum = $1";
495   }
496
497   ##
498   # parse status
499   ##
500
501   #prospect ordered active inactive suspended cancelled
502   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
503     my $method = $params->{'status'}. '_sql';
504     #push @where, $class->$method();
505     push @where, FS::cust_main->$method();
506   }
507
508   ##
509   # address
510   ##
511   if ( $params->{'address'} =~ /\S/ ) {
512     my $address = dbh->quote('%'. lc($params->{'address'}). '%');
513     push @where, '('. join(' OR ',
514                              map "LOWER($_) LIKE $address",
515                                qw(address1 address2 ship_address1 ship_address2)
516                           ).
517                  ')';
518   }
519
520   ##
521   # parse cancelled package checkbox
522   ##
523
524   my $pkgwhere = "";
525
526   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
527     unless $params->{'cancelled_pkgs'};
528
529   ##
530   # parse without census tract checkbox
531   ##
532
533   push @where, "(censustract = '' or censustract is null)"
534     if $params->{'no_censustract'};
535
536   ##
537   # parse with hardcoded tax location checkbox
538   ##
539
540   push @where, "geocode is not null"
541     if $params->{'with_geocode'};
542
543   ##
544   # dates
545   ##
546
547   foreach my $field (qw( signupdate )) {
548
549     next unless exists($params->{$field});
550
551     my($beginning, $ending, $hour) = @{$params->{$field}};
552
553     push @where,
554       "cust_main.$field IS NOT NULL",
555       "cust_main.$field >= $beginning",
556       "cust_main.$field <= $ending";
557
558     if(defined $hour) {
559       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
560         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
561       }
562       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
563         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
564       }
565       else {
566         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
567       }
568     }
569
570     $orderby ||= "ORDER BY cust_main.$field";
571
572   }
573
574   ###
575   # classnum
576   ###
577
578   if ( $params->{'classnum'} ) {
579
580     my @classnum = ref( $params->{'classnum'} )
581                      ? @{ $params->{'classnum'} }
582                      :  ( $params->{'classnum'} );
583
584     @classnum = grep /^(\d*)$/, @classnum;
585
586     if ( @classnum ) {
587       push @where, '( '. join(' OR ', map {
588                                             $_ ? "cust_main.classnum = $_"
589                                                : "cust_main.classnum IS NULL"
590                                           }
591                                           @classnum
592                              ).
593                    ' )';
594     }
595
596   }
597
598   ###
599   # payby
600   ###
601
602   if ( $params->{'payby'} ) {
603
604     my @payby = ref( $params->{'payby'} )
605                   ? @{ $params->{'payby'} }
606                   :  ( $params->{'payby'} );
607
608     @payby = grep /^([A-Z]{4})$/, @payby;
609
610     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
611       if @payby;
612
613   }
614
615   ###
616   # paydate_year / paydate_month
617   ###
618
619   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
620     my $year = $1;
621     $params->{'paydate_month'} =~ /^(\d\d?)$/
622       or die "paydate_year without paydate_month?";
623     my $month = $1;
624
625     push @where,
626       'paydate IS NOT NULL',
627       "paydate != ''",
628       "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
629 ;
630   }
631
632   ###
633   # invoice terms
634   ###
635
636   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
637     my $terms = $1;
638     if ( $1 eq 'NULL' ) {
639       push @where,
640         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
641     } else {
642       push @where,
643         "cust_main.invoice_terms IS NOT NULL",
644         "cust_main.invoice_terms = '$1'";
645     }
646   }
647
648   ##
649   # amounts
650   ##
651
652   if ( $params->{'current_balance'} ) {
653
654     #my $balance_sql = $class->balance_sql();
655     my $balance_sql = FS::cust_main->balance_sql();
656
657     my @current_balance =
658       ref( $params->{'current_balance'} )
659       ? @{ $params->{'current_balance'} }
660       :  ( $params->{'current_balance'} );
661
662     push @where, map { s/current_balance/$balance_sql/; $_ }
663                      @current_balance;
664
665   }
666
667   ##
668   # custbatch
669   ##
670
671   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
672     push @where,
673       "cust_main.custbatch = '$1'";
674   }
675   
676   if ( $params->{'tagnum'} ) {
677     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
678
679     @tagnums = grep /^(\d+)$/, @tagnums;
680
681     if ( @tagnums ) {
682         my $tags_where = "0 < (select count(1) from cust_tag where " 
683                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
684                 . join(',', @tagnums) . "))";
685
686         push @where, $tags_where;
687     }
688   }
689
690
691   ##
692   # setup queries, subs, etc. for the search
693   ##
694
695   $orderby ||= 'ORDER BY custnum';
696
697   # here is the agent virtualization
698   push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
699
700   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
701
702   my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum  ) ';
703
704   my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
705
706   my @select = (
707                  'cust_main.custnum',
708                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
709                );
710
711   my(@extra_headers) = ();
712   my(@extra_fields)  = ();
713
714   if ($params->{'flattened_pkgs'}) {
715
716     if ($dbh->{Driver}->{Name} eq 'Pg') {
717
718       push @select, "array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
719
720     }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
721       push @select, "GROUP_CONCAT(pkg SEPARATOR '|') as magic";
722       $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
723     }else{
724       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
725            "omitting packing information from report.";
726     }
727
728     my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
729
730     my $sth = dbh->prepare($header_query) or die dbh->errstr;
731     $sth->execute() or die $sth->errstr;
732     my $headerrow = $sth->fetchrow_arrayref;
733     my $headercount = $headerrow ? $headerrow->[0] : 0;
734     while($headercount) {
735       unshift @extra_headers, "Package ". $headercount;
736       unshift @extra_fields, eval q!sub {my $c = shift;
737                                          my @a = split '\|', $c->magic;
738                                          my $p = $a[!.--$headercount. q!];
739                                          $p;
740                                         };!;
741     }
742
743   }
744
745   if ( $params->{'with_geocode'} ) {
746
747     unshift @extra_headers, 'Tax location override', 'Calculated tax location';
748     unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
749                            sub { my $c = shift;
750                                  $c->set('geocode', '');
751                                  $c->geocode('cch'); #XXX only cch right now
752                                };
753     push @select, 'geocode';
754     push @select, 'zip' unless grep { $_ eq 'zip' } @select;
755     push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
756   }
757
758   my $select = join(', ', @select);
759
760   my $sql_query = {
761     'table'         => 'cust_main',
762     'select'        => $select,
763     'hashref'       => {},
764     'extra_sql'     => $extra_sql,
765     'order_by'      => $orderby,
766     'count_query'   => $count_query,
767     'extra_headers' => \@extra_headers,
768     'extra_fields'  => \@extra_fields,
769   };
770
771 }
772
773 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
774
775 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
776 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
777 specified (the appropriate ship_ field is also searched).
778
779 Additional options are the same as FS::Record::qsearch
780
781 =cut
782
783 sub fuzzy_search {
784   my( $self, $fuzzy, $hash, @opt) = @_;
785   #$self
786   $hash ||= {};
787   my @cust_main = ();
788
789   check_and_rebuild_fuzzyfiles();
790   foreach my $field ( keys %$fuzzy ) {
791
792     my $all = $self->all_X($field);
793     next unless scalar(@$all);
794
795     my %match = ();
796     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
797
798     my @fcust = ();
799     foreach ( keys %match ) {
800       push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
801       push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
802     }
803     my %fsaw = ();
804     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
805   }
806
807   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
808   my %saw = ();
809   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
810
811   @cust_main;
812
813 }
814
815 =back
816
817 =head1 UTILITY SUBROUTINES
818
819 =over 4
820
821 =item check_and_rebuild_fuzzyfiles
822
823 =cut
824
825 sub check_and_rebuild_fuzzyfiles {
826   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
827   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
828 }
829
830 =item rebuild_fuzzyfiles
831
832 =cut
833
834 sub rebuild_fuzzyfiles {
835
836   use Fcntl qw(:flock);
837
838   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
839   mkdir $dir, 0700 unless -d $dir;
840
841   foreach my $fuzzy ( @fuzzyfields ) {
842
843     open(LOCK,">>$dir/cust_main.$fuzzy")
844       or die "can't open $dir/cust_main.$fuzzy: $!";
845     flock(LOCK,LOCK_EX)
846       or die "can't lock $dir/cust_main.$fuzzy: $!";
847
848     open (CACHE,">$dir/cust_main.$fuzzy.tmp")
849       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
850
851     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
852       my $sth = dbh->prepare("SELECT $field FROM cust_main".
853                              " WHERE $field != '' AND $field IS NOT NULL");
854       $sth->execute or die $sth->errstr;
855
856       while ( my $row = $sth->fetchrow_arrayref ) {
857         print CACHE $row->[0]. "\n";
858       }
859
860     } 
861
862     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
863   
864     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
865     close LOCK;
866   }
867
868 }
869
870 =item all_X
871
872 =cut
873
874 sub all_X {
875   my( $self, $field ) = @_;
876   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
877   open(CACHE,"<$dir/cust_main.$field")
878     or die "can't open $dir/cust_main.$field: $!";
879   my @array = map { chomp; $_; } <CACHE>;
880   close CACHE;
881   \@array;
882 }
883
884 =head1 BUGS
885
886 Bed bugs
887
888 =head1 SEE ALSO
889
890 L<FS::cust_main>, L<FS::Record>
891
892 =cut
893
894 1;
895