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