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