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