make address fields work in customer search results, #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 mobile 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       my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
144                                 ? ' AND agent_custid IS NULL ' : '';
145       push @cust_main, qsearch( {
146         'table'     => 'cust_main',
147         'hashref'   => { 'custnum' => $num, %options },
148         'extra_sql' => " AND $agentnums_sql $agent_custid_null",
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       # probably the Right Thing: return customers that have any associated
179       # locations matching the string, not just bill/ship location
180       push @cust_main, qsearch( {
181         'table'     => 'cust_main',
182         'addl_from' => ' JOIN cust_location USING (custnum) ',
183         'hashref'   => { %options, },
184         'extra_sql' => 
185           ( keys(%options) ? ' AND ' : ' WHERE ' ).
186           " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
187           " AND $agentnums_sql",
188       } );
189     }
190
191   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
192
193     my($company, $last, $first) = ( $1, $2, $3 );
194
195     # "Company (Last, First)"
196     #this is probably something a browser remembered,
197     #so just do an exact search (but case-insensitive, so USPS standardization
198     #doesn't throw a wrench in the works)
199
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(first)   = ". dbh->quote(lc($first)),
207           " LOWER(last)    = ". dbh->quote(lc($last)),
208           " LOWER(company) = ". dbh->quote(lc($company)),
209           $agentnums_sql,
210         ),
211       } ),
212     #contacts?
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 .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
251
252       push @cust_main, qsearch( {
253         'table'     => 'cust_main',
254         'hashref'   => \%options,
255         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
256       } );
257       #contacts?
258
259       # or it just be something that was typed in... (try that in a sec)
260
261     }
262
263     my $q_value = dbh->quote($value);
264
265     #exact
266     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
267     $sql .= " (    LOWER(last)          = $q_value
268                 OR LOWER(company)       = $q_value
269             ";
270     #yes, it's a kludge
271     $sql .= "   OR EXISTS( 
272                 SELECT 1 FROM cust_location 
273                 WHERE LOWER(cust_location.address1) = $q_value
274                   AND cust_location.custnum = cust_main.custnum
275             )
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       );
298
299       if ( $first && $last ) {
300         #contacts? ship_first/ship_last are gone
301
302         push @hashrefs,
303           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
304             'last'         => { op=>'ILIKE', value=>"%$last%" },
305           },
306         ;
307
308       } else {
309
310         push @hashrefs,
311           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
312         ;
313       }
314
315       foreach my $hashref ( @hashrefs ) {
316
317         push @cust_main, qsearch( {
318           'table'     => 'cust_main',
319           'hashref'   => { %$hashref,
320                            %options,
321                          },
322           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
323         } );
324
325       }
326
327       if ( $conf->exists('address1-search') ) {
328
329         push @cust_main, qsearch( {
330           'table'     => 'cust_main',
331           'addl_from' => 'JOIN cust_location USING (custnum)',
332           'extra_sql' => 'WHERE cust_location.address1 ILIKE '.
333                           dbh->quote("%$value%"),
334         } );
335
336       }
337
338       #fuzzy
339       my %fuzopts = (
340         'hashref'   => \%options,
341         'select'    => '',
342         'extra_sql' => " AND $agentnums_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 zip
461
462 =item refnum
463
464 =item cancelled_pkgs
465
466 bool
467
468 =item signupdate
469
470 listref of start date, end date
471
472 =item birthdate
473
474 listref of start date, end date
475
476 =item spouse_birthdate
477
478 listref of start date, end date
479
480 =item anniversary_date
481
482 listref of start date, end date
483
484 =item payby
485
486 listref
487
488 =item paydate_year
489
490 =item paydate_month
491
492 =item current_balance
493
494 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
495
496 =item cust_fields
497
498 =item flattened_pkgs
499
500 bool
501
502 =back
503
504 =cut
505
506 sub search {
507   my ($class, $params) = @_;
508
509   my $dbh = dbh;
510
511   my @where = ();
512   my $orderby;
513
514   # initialize these to prevent warnings
515   $params = {
516     'custnum'       => '',
517     'agentnum'      => '',
518     'usernum'       => '',
519     'status'        => '',
520     'address'       => '',
521     'zip'           => '',
522     'paydate_year'  => '',
523     'invoice_terms' => '',
524     'custbatch'     => '',
525     %$params
526   };
527
528   ##
529   # explicit custnum(s)
530   ##
531
532   if ( $params->{'custnum'} ) {
533     my @custnums = ref($params->{'custnum'}) ? 
534                       @{ $params->{'custnum'} } : 
535                       $params->{'custnum'};
536     push @where, 
537       'cust_main.custnum IN (' . 
538       join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
539       ')' if scalar(@custnums) > 0;
540   }
541
542   ##
543   # parse agent
544   ##
545
546   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
547     push @where,
548       "cust_main.agentnum = $1";
549   }
550
551   ##
552   # do the same for user
553   ##
554
555   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
556     push @where,
557       "cust_main.usernum = $1";
558   }
559
560   ##
561   # parse status
562   ##
563
564   #prospect ordered active inactive suspended cancelled
565   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
566     my $method = $params->{'status'}. '_sql';
567     #push @where, $class->$method();
568     push @where, FS::cust_main->$method();
569   }
570
571   ##
572   # address
573   ##
574   if ( $params->{'address'} =~ /\S/ ) {
575     my $address = dbh->quote('%'. lc($params->{'address'}). '%');
576     push @where, "EXISTS(
577       SELECT 1 FROM cust_location 
578       WHERE cust_location.custnum = cust_main.custnum
579         AND (LOWER(cust_location.address1) LIKE $address OR
580              LOWER(cust_location.address2) LIKE $address)
581     )";
582   }
583
584   ##
585   # zipcode
586   ##
587   if ( $params->{'zip'} =~ /\S/ ) {
588     my $zip = dbh->quote($params->{'zip'} . '%');
589     push @where, "EXISTS(
590       SELECT 1 FROM cust_location
591       WHERE cust_location.custnum = cust_main.custnum
592         AND cust_location.zip LIKE $zip
593     )";
594   }
595
596   ###
597   # refnum
598   ###
599   if ( $params->{'refnum'}  ) {
600
601     my @refnum = ref( $params->{'refnum'} )
602                    ? @{ $params->{'refnum'} }
603                    :  ( $params->{'refnum'} );
604
605     @refnum = grep /^(\d*)$/, @refnum;
606
607     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
608       if @refnum;
609
610   }
611
612   ##
613   # parse cancelled package checkbox
614   ##
615
616   my $pkgwhere = "";
617
618   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
619     unless $params->{'cancelled_pkgs'};
620
621   ##
622   # parse without census tract checkbox
623   ##
624
625   push @where, "(censustract = '' or censustract is null)"
626     if $params->{'no_censustract'};
627
628   ##
629   # parse with hardcoded tax location checkbox
630   ##
631
632   push @where, "geocode is not null"
633     if $params->{'with_geocode'};
634
635   ##
636   # dates
637   ##
638
639   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
640
641     next unless exists($params->{$field});
642
643     my($beginning, $ending, $hour) = @{$params->{$field}};
644
645     push @where,
646       "cust_main.$field IS NOT NULL",
647       "cust_main.$field >= $beginning",
648       "cust_main.$field <= $ending";
649
650     if($field eq 'signupdate' && defined $hour) {
651       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
652         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
653       }
654       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
655         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
656       }
657       else {
658         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
659       }
660     }
661
662     $orderby ||= "ORDER BY cust_main.$field";
663
664   }
665
666   ###
667   # classnum
668   ###
669
670   if ( $params->{'classnum'} ) {
671
672     my @classnum = ref( $params->{'classnum'} )
673                      ? @{ $params->{'classnum'} }
674                      :  ( $params->{'classnum'} );
675
676     @classnum = grep /^(\d*)$/, @classnum;
677
678     if ( @classnum ) {
679       push @where, '( '. join(' OR ', map {
680                                             $_ ? "cust_main.classnum = $_"
681                                                : "cust_main.classnum IS NULL"
682                                           }
683                                           @classnum
684                              ).
685                    ' )';
686     }
687
688   }
689
690   ###
691   # payby
692   ###
693
694   if ( $params->{'payby'} ) {
695
696     my @payby = ref( $params->{'payby'} )
697                   ? @{ $params->{'payby'} }
698                   :  ( $params->{'payby'} );
699
700     @payby = grep /^([A-Z]{4})$/, @payby;
701
702     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
703       if @payby;
704
705   }
706
707   ###
708   # paydate_year / paydate_month
709   ###
710
711   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
712     my $year = $1;
713     $params->{'paydate_month'} =~ /^(\d\d?)$/
714       or die "paydate_year without paydate_month?";
715     my $month = $1;
716
717     push @where,
718       'paydate IS NOT NULL',
719       "paydate != ''",
720       "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
721 ;
722   }
723
724   ###
725   # invoice terms
726   ###
727
728   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
729     my $terms = $1;
730     if ( $1 eq 'NULL' ) {
731       push @where,
732         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
733     } else {
734       push @where,
735         "cust_main.invoice_terms IS NOT NULL",
736         "cust_main.invoice_terms = '$1'";
737     }
738   }
739
740   ##
741   # amounts
742   ##
743
744   if ( $params->{'current_balance'} ) {
745
746     #my $balance_sql = $class->balance_sql();
747     my $balance_sql = FS::cust_main->balance_sql();
748
749     my @current_balance =
750       ref( $params->{'current_balance'} )
751       ? @{ $params->{'current_balance'} }
752       :  ( $params->{'current_balance'} );
753
754     push @where, map { s/current_balance/$balance_sql/; $_ }
755                      @current_balance;
756
757   }
758
759   ##
760   # custbatch
761   ##
762
763   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
764     push @where,
765       "cust_main.custbatch = '$1'";
766   }
767   
768   if ( $params->{'tagnum'} ) {
769     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
770
771     @tagnums = grep /^(\d+)$/, @tagnums;
772
773     if ( @tagnums ) {
774         my $tags_where = "0 < (select count(1) from cust_tag where " 
775                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
776                 . join(',', @tagnums) . "))";
777
778         push @where, $tags_where;
779     }
780   }
781
782
783   ##
784   # setup queries, subs, etc. for the search
785   ##
786
787   $orderby ||= 'ORDER BY custnum';
788
789   # here is the agent virtualization
790   push @where,
791     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
792
793   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
794
795   my $addl_from = '';
796
797   my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
798
799   my @select = (
800                  'cust_main.custnum',
801                  # there's a good chance that we'll need these
802                  'cust_main.bill_locationnum',
803                  'cust_main.ship_locationnum',
804                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
805                );
806
807   my(@extra_headers) = ();
808   my(@extra_fields)  = ();
809
810   if ($params->{'flattened_pkgs'}) {
811
812     #my $pkg_join = '';
813     $addl_from .= ' LEFT JOIN cust_pkg USING ( custnum ) ';
814
815     if ($dbh->{Driver}->{Name} eq 'Pg') {
816
817       push @select, "
818         ARRAY_TO_STRING(
819           ARRAY(
820             SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
821               WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
822           ), '|'
823         ) AS magic
824       ";
825
826     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
827       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
828       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
829       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
830     } else {
831       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
832            "omitting package information from report.";
833     }
834
835     my $header_query = "
836       SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
837         FROM cust_main $addl_from $extra_sql $pkgwhere
838           GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
839     ";
840
841     my $sth = dbh->prepare($header_query) or die dbh->errstr;
842     $sth->execute() or die $sth->errstr;
843     my $headerrow = $sth->fetchrow_arrayref;
844     my $headercount = $headerrow ? $headerrow->[0] : 0;
845     while($headercount) {
846       unshift @extra_headers, "Package ". $headercount;
847       unshift @extra_fields, eval q!sub {my $c = shift;
848                                          my @a = split '\|', $c->magic;
849                                          my $p = $a[!.--$headercount. q!];
850                                          $p;
851                                         };!;
852     }
853
854   }
855
856   if ( $params->{'with_geocode'} ) {
857
858     unshift @extra_headers, 'Tax location override', 'Calculated tax location';
859     unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
860                            sub { my $c = shift;
861                                  $c->set('geocode', '');
862                                  $c->geocode('cch'); #XXX only cch right now
863                                };
864     push @select, 'geocode';
865     push @select, 'zip' unless grep { $_ eq 'zip' } @select;
866     push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
867   }
868
869   my $select = join(', ', @select);
870
871   my $sql_query = {
872     'table'         => 'cust_main',
873     'select'        => $select,
874     'addl_from'     => $addl_from,
875     'hashref'       => {},
876     'extra_sql'     => $extra_sql,
877     'order_by'      => $orderby,
878     'count_query'   => $count_query,
879     'extra_headers' => \@extra_headers,
880     'extra_fields'  => \@extra_fields,
881   };
882
883 }
884
885 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
886
887 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
888 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
889 specified.
890
891 Additional options are the same as FS::Record::qsearch
892
893 =cut
894
895 sub fuzzy_search {
896   my( $self, $fuzzy ) = @_;
897   # sensible defaults, then merge in any passed options
898   my %fuzopts = (
899     'table'     => 'cust_main',
900     'addl_from' => '',
901     'extra_sql' => '',
902     'hashref'   => {},
903     @_
904   );
905
906   my @cust_main = ();
907
908   check_and_rebuild_fuzzyfiles();
909   foreach my $field ( keys %$fuzzy ) {
910
911     my $all = $self->all_X($field);
912     next unless scalar(@$all);
913
914     my %match = ();
915     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
916
917     my @fcust = ();
918     foreach ( keys %match ) {
919       if ( $field eq 'address1' ) {
920         #because it lives outside the table
921         my $addl_from = $fuzopts{addl_from} .
922                         'JOIN cust_location USING (custnum)';
923         my $extra_sql = $fuzopts{extra_sql} .
924                         " AND cust_location.address1 = ".dbh->quote($_);
925         push @fcust, qsearch({
926             %fuzopts,
927             'addl_from' => $addl_from,
928             'extra_sql' => $extra_sql,
929         });
930       } else {
931         my $hash = $fuzopts{hashref};
932         $hash->{$field} = $_;
933         push @fcust, qsearch({
934             %fuzopts,
935             'hashref' => $hash
936         });
937       }
938     }
939     my %fsaw = ();
940     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
941   }
942
943   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
944   my %saw = ();
945   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
946
947   @cust_main;
948
949 }
950
951 =back
952
953 =head1 UTILITY SUBROUTINES
954
955 =over 4
956
957 =item check_and_rebuild_fuzzyfiles
958
959 =cut
960
961 sub check_and_rebuild_fuzzyfiles {
962   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
963   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
964 }
965
966 =item rebuild_fuzzyfiles
967
968 =cut
969
970 sub rebuild_fuzzyfiles {
971
972   use Fcntl qw(:flock);
973
974   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
975   mkdir $dir, 0700 unless -d $dir;
976
977   foreach my $fuzzy ( @fuzzyfields ) {
978
979     open(LOCK,">>$dir/cust_main.$fuzzy")
980       or die "can't open $dir/cust_main.$fuzzy: $!";
981     flock(LOCK,LOCK_EX)
982       or die "can't lock $dir/cust_main.$fuzzy: $!";
983
984     open (CACHE, '>:encoding(UTF-8)', "$dir/cust_main.$fuzzy.tmp")
985       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
986
987     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
988       my $sth = dbh->prepare("SELECT $field FROM cust_main".
989                              " WHERE $field != '' AND $field IS NOT NULL");
990       $sth->execute or die $sth->errstr;
991
992       while ( my $row = $sth->fetchrow_arrayref ) {
993         print CACHE $row->[0]. "\n";
994       }
995
996     } 
997
998     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
999   
1000     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
1001     close LOCK;
1002   }
1003
1004 }
1005
1006 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1007
1008 =cut
1009
1010 sub append_fuzzyfiles {
1011   #my( $first, $last, $company ) = @_;
1012
1013   check_and_rebuild_fuzzyfiles();
1014
1015   use Fcntl qw(:flock);
1016
1017   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1018
1019   foreach my $field (@fuzzyfields) {
1020     my $value = shift;
1021
1022     if ( $value ) {
1023
1024       open(CACHE, '>>:encoding(UTF-8)', "$dir/cust_main.$field" )
1025         or die "can't open $dir/cust_main.$field: $!";
1026       flock(CACHE,LOCK_EX)
1027         or die "can't lock $dir/cust_main.$field: $!";
1028
1029       print CACHE "$value\n";
1030
1031       flock(CACHE,LOCK_UN)
1032         or die "can't unlock $dir/cust_main.$field: $!";
1033       close CACHE;
1034     }
1035
1036   }
1037
1038   1;
1039 }
1040
1041 =item all_X
1042
1043 =cut
1044
1045 sub all_X {
1046   my( $self, $field ) = @_;
1047   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1048   open(CACHE, '<:encoding(UTF-8)', "$dir/cust_main.$field")
1049     or die "can't open $dir/cust_main.$field: $!";
1050   my @array = map { chomp; $_; } <CACHE>;
1051   close CACHE;
1052   \@array;
1053 }
1054
1055 =head1 BUGS
1056
1057 Bed bugs
1058
1059 =head1 SEE ALSO
1060
1061 L<FS::cust_main>, L<FS::Record>
1062
1063 =cut
1064
1065 1;
1066