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