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