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