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