1 package FS::cust_main::Search;
4 use base qw( Exporter );
5 use vars qw( @EXPORT_OK $DEBUG $me $conf @fuzzyfields );
6 use String::Approx qw(amatch);
8 use FS::Record qw( qsearch );
10 use FS::cust_main_invoice;
12 use FS::payinfo_Mixin;
14 @EXPORT_OK = qw( smart_search );
16 # 1 is mostly method/subroutine entry and options
17 # 2 traces progress of some operations
18 # 3 is even more information including possibly sensitive data
20 $me = '[FS::cust_main::Search]';
23 'cust_main.first', 'cust_main.last', 'cust_main.company',
24 'cust_location.address1',
25 'contact.first', 'contact.last',
28 install_callback FS::UID sub {
30 #yes, need it for stuff below (prolly should be cached)
35 FS::cust_main::Search - Customer searching
39 use FS::cust_main::Search;
41 FS::cust_main::Search::smart_search(%options);
43 FS::cust_main::Search::email_search(%options);
45 FS::cust_main::Search->search( \%options );
47 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
53 =item smart_search OPTION => VALUE ...
55 Accepts the following options: I<search>, the string to search for. The string
56 will be searched for as a customer number, phone number, name or company name,
57 address (if address1-search is on), invoicing email address, or credit card
60 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
61 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
63 skip fuzzy matching when an exact match is found.
65 Any additional options are treated as an additional qualifier on the search
68 Returns a (possibly empty) array of FS::cust_main objects.
75 #here is the agent virtualization
77 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
78 my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
82 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
83 my $search = delete $options{'search'};
84 ( my $alphanum_search = $search ) =~ s/\W//g;
86 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
88 #false laziness w/Record::ut_phone
89 my $phonen = "$1-$2-$3";
90 $phonen .= " x$4" if $4;
92 my $phonenum = "$1$2$3";
95 #cust_main phone numbers
96 push @cust_main, qsearch( {
97 'table' => 'cust_main',
98 'hashref' => { %options },
99 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
101 join(' OR ', map "$_ = '$phonen'",
102 qw( daytime night mobile fax )
105 " AND $agentnums_sql", #agent virtualization
108 #contact phone numbers
110 grep $agentnums_href->{$_->agentnum}, #agent virt
111 grep $_, #skip contacts that don't have cust_main records
112 map $_->contact->cust_main,
114 'table' => 'contact_phone',
115 'hashref' => { 'phonenum' => $phonenum },
118 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
119 #try looking for matches with extensions unless one was specified
121 push @cust_main, qsearch( {
122 'table' => 'cust_main',
123 'hashref' => { %options },
124 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
126 join(' OR ', map "$_ LIKE '$phonen\%'",
130 " AND $agentnums_sql", #agent virtualization
138 if ( $search =~ /@/ ) { #email address
140 # invoicing email address
142 grep $agentnums_href->{$_->agentnum}, #agent virt
145 'table' => 'cust_main_invoice',
146 'hashref' => { 'dest' => $search },
150 # contact email address
152 grep $agentnums_href->{$_->agentnum}, #agent virt
153 grep $_, #skip contacts that don't have cust_main records
154 map $_->contact->cust_main,
156 'table' => 'contact_email',
157 'hashref' => { 'emailaddress' => $search },
161 # custnum search (also try agent_custid), with some tweaking options if your
162 # legacy cust "numbers" have letters
163 } elsif ( $search =~ /^\s*(\d+)\s*$/
164 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
165 && $search =~ /^\s*(\w\w?\d+)\s*$/
167 || ( $conf->config('cust_main-custnum-display_special')
168 # it's not currently possible for special prefixes to contain
169 # digits, so just strip off any alphabetic prefix and match
170 # the rest to custnum
171 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
173 || ( $conf->exists('address1-search' )
174 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
181 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
182 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
183 ? ' AND agent_custid IS NULL ' : '';
184 push @cust_main, qsearch( {
185 'table' => 'cust_main',
186 'hashref' => { 'custnum' => $num, %options },
187 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
191 # for all agents this user can see, if any of them have custnum prefixes
192 # that match the search string, include customers that match the rest
193 # of the custnum and belong to that agent
194 foreach my $agentnum ( keys %$agentnums_href ) {
195 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
197 if ( $p eq substr($num, 0, length($p)) ) {
198 push @cust_main, qsearch( {
199 'table' => 'cust_main',
200 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
201 'agentnum' => $agentnum,
208 push @cust_main, qsearch( {
209 'table' => 'cust_main',
210 'hashref' => { 'agent_custid' => $num, %options },
211 'extra_sql' => " AND $agentnums_sql", #agent virtualization
214 if ( $conf->exists('address1-search') ) {
215 my $len = length($num);
217 # probably the Right Thing: return customers that have any associated
218 # locations matching the string, not just bill/ship location
219 push @cust_main, qsearch( {
220 'table' => 'cust_main',
221 'addl_from' => ' JOIN cust_location USING (custnum) ',
222 'hashref' => { %options, },
224 ( keys(%options) ? ' AND ' : ' WHERE ' ).
225 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
226 " AND $agentnums_sql",
230 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
232 my($company, $last, $first) = ( $1, $2, $3 );
234 # "Company (Last, First)"
235 #this is probably something a browser remembered,
236 #so just do an exact search (but case-insensitive, so USPS standardization
237 #doesn't throw a wrench in the works)
239 push @cust_main, qsearch( {
240 'table' => 'cust_main',
241 'hashref' => { %options },
243 ( keys(%options) ? ' AND ' : ' WHERE ' ).
245 " LOWER(first) = ". dbh->quote(lc($first)),
246 " LOWER(last) = ". dbh->quote(lc($last)),
247 " LOWER(company) = ". dbh->quote(lc($company)),
253 # probably not necessary for the "something a browser remembered" case
255 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
256 # try {first,last,company}
260 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
261 # # full strings the browser remembers won't work
262 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
264 use Lingua::EN::NameParse;
265 my $NameParse = new Lingua::EN::NameParse(
270 my($last, $first) = ( '', '' );
271 #maybe disable this too and just rely on NameParse?
272 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
274 ($last, $first) = ( $1, $2 );
276 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
277 } elsif ( ! $NameParse->parse($value) ) {
279 my %name = $NameParse->components;
280 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
281 $last = $name{'surname_1'};
285 if ( $first && $last ) {
287 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
290 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
291 $sql .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
294 push @cust_main, qsearch( {
295 'table' => 'cust_main',
296 'hashref' => \%options,
297 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
302 grep $agentnums_href->{$_->agentnum}, #agent virt
303 grep $_, #skip contacts that don't have cust_main records
306 'table' => 'contact',
307 'hashref' => { 'first' => $first,
313 # or it just be something that was typed in... (try that in a sec)
317 my $q_value = dbh->quote($value);
320 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
321 $sql .= " ( LOWER(cust_main.first) = $q_value
322 OR LOWER(cust_main.last) = $q_value
323 OR LOWER(cust_main.company) = $q_value
326 #address1 (yes, it's a kludge)
327 $sql .= " OR EXISTS (
328 SELECT 1 FROM cust_location
329 WHERE LOWER(cust_location.address1) = $q_value
330 AND cust_location.custnum = cust_main.custnum
332 if $conf->exists('address1-search');
334 #contacts (look, another kludge)
335 $sql .= " OR EXISTS ( SELECT 1 FROM contact
336 WHERE ( LOWER(contact.first) = $q_value
337 OR LOWER(contact.last) = $q_value
339 AND contact.custnum IS NOT NULL
340 AND contact.custnum = cust_main.custnum
344 push @cust_main, qsearch( {
345 'table' => 'cust_main',
346 'hashref' => \%options,
347 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
350 #no exact match, trying substring/fuzzy
351 #always do substring & fuzzy (unless they're explicity config'ed off)
352 #getting complaints searches are not returning enough
353 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
355 #still some false laziness w/search (was search/cust_main.cgi)
360 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
363 if ( $first && $last ) {
366 { 'first' => { op=>'ILIKE', value=>"%$first%" },
367 'last' => { op=>'ILIKE', value=>"%$last%" },
374 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
375 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
379 foreach my $hashref ( @hashrefs ) {
381 push @cust_main, qsearch( {
382 'table' => 'cust_main',
383 'hashref' => { %$hashref,
386 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
391 if ( $conf->exists('address1-search') ) {
393 push @cust_main, qsearch( {
394 table => 'cust_main',
395 addl_from => 'JOIN cust_location USING (custnum)',
396 extra_sql => 'WHERE '.
397 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
398 " AND $agentnums_sql", #agent virtualizaiton
405 shift @hashrefs; #no company column in contact table
407 foreach my $hashref ( @hashrefs ) {
410 grep $agentnums_href->{$_->agentnum}, #agent virt
411 grep $_, #skip contacts that don't have cust_main records
414 'table' => 'contact',
415 'hashref' => { %$hashref,
418 #'extra_sql' => " AND $agentnums_sql", #agent virt
425 'hashref' => \%options,
427 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
430 if ( $first && $last ) {
431 push @cust_main, FS::cust_main::Search->fuzzy_search(
432 { 'last' => $last, #fuzzy hashref
433 'first' => $first }, #
437 foreach my $field ( 'first', 'last', 'company' ) {
439 FS::cust_main::Search->fuzzy_search( { $field => $value }, %fuzopts );
441 if ( $conf->exists('address1-search') ) {
443 FS::cust_main::Search->fuzzy_search(
444 { 'cust_location.address1' => $value }, %fuzopts );
451 ( my $nospace_search = $search ) =~ s/\s//g;
452 ( my $card_search = $nospace_search ) =~ s/\-//g;
453 $card_search =~ s/[x\*\.\_]/x/gi;
455 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
457 ( my $like_search = $card_search ) =~ s/x/_/g;
458 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
460 push @cust_main, qsearch({
461 'table' => 'cust_main',
463 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
464 OR paymask = '$mask_search'
466 " AND payby IN ('CARD','DCRD') ".
467 " AND $agentnums_sql", #agent virtulization
473 #eliminate duplicates
475 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
483 Accepts the following options: I<email>, the email address to search for. The
484 email address will be searched for as an email invoice destination and as an
487 #Any additional options are treated as an additional qualifier on the search
490 Returns a (possibly empty) array of FS::cust_main objects (but usually just
500 my $email = delete $options{'email'};
502 #we're only being used by RT at the moment... no agent virtualization yet
503 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
507 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
509 my ( $user, $domain ) = ( $1, $2 );
511 warn "$me smart_search: searching for $user in domain $domain"
517 'table' => 'cust_main_invoice',
518 'hashref' => { 'dest' => $email },
525 map $_->cust_svc->cust_pkg,
527 'table' => 'svc_acct',
528 'hashref' => { 'username' => $user, },
530 'AND ( SELECT domain FROM svc_domain
531 WHERE svc_acct.domsvc = svc_domain.svcnum
532 ) = '. dbh->quote($domain),
538 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
540 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
557 Returns a qsearch hash expression to search for parameters specified in
558 HASHREF. Valid parameters are
578 listref of start date, end date
582 listref of start date, end date
584 =item spouse_birthdate
586 listref of start date, end date
588 =item anniversary_date
590 listref of start date, end date
600 =item current_balance
602 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
615 my ($class, $params) = @_;
622 # initialize these to prevent warnings
630 'paydate_year' => '',
631 'invoice_terms' => '',
637 # explicit custnum(s)
640 if ( $params->{'custnum'} ) {
641 my @custnums = ref($params->{'custnum'}) ?
642 @{ $params->{'custnum'} } :
643 $params->{'custnum'};
645 'cust_main.custnum IN (' .
646 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
647 ')' if scalar(@custnums) > 0;
654 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
656 "cust_main.agentnum = $1";
663 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
664 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
665 : 'cust_main.salesnum IS NULL';
672 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
674 "cust_main.usernum = $1";
681 #prospect ordered active inactive suspended cancelled
682 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
683 my $method = $params->{'status'}. '_sql';
684 #push @where, $class->$method();
685 push @where, FS::cust_main->$method();
691 if ( $params->{'address'} ) {
692 # allow this to be an arrayref
693 my @values = ($params->{'address'});
694 @values = @{$values[0]} if ref($values[0]);
696 foreach (grep /\S/, @values) {
697 my $address = dbh->quote('%'. lc($_). '%');
699 "LOWER(cust_location.address1) LIKE $address",
700 "LOWER(cust_location.address2) LIKE $address";
703 push @where, "EXISTS(
704 SELECT 1 FROM cust_location
705 WHERE cust_location.custnum = cust_main.custnum
706 AND (".join(' OR ',@orwhere).")
714 if ( $params->{'zip'} =~ /\S/ ) {
715 my $zip = dbh->quote($params->{'zip'} . '%');
716 push @where, "EXISTS(
717 SELECT 1 FROM cust_location
718 WHERE cust_location.custnum = cust_main.custnum
719 AND cust_location.zip LIKE $zip
726 if ( $params->{'refnum'} ) {
728 my @refnum = ref( $params->{'refnum'} )
729 ? @{ $params->{'refnum'} }
730 : ( $params->{'refnum'} );
732 @refnum = grep /^(\d*)$/, @refnum;
734 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
740 # parse cancelled package checkbox
745 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
746 unless $params->{'cancelled_pkgs'};
749 # "with email address(es)" checkbox
753 'EXISTS ( SELECT 1 FROM cust_main_invoice
754 WHERE cust_main_invoice.custnum = cust_main.custnum
756 )' # AND dest LIKE '%@%'
757 if $params->{'with_email'};
760 # "with postal mail invoices" checkbox
764 "EXISTS ( SELECT 1 FROM cust_main_invoice
765 WHERE cust_main_invoice.custnum = cust_main.custnum
767 if $params->{'POST'};
770 # "without postal mail invoices" checkbox
774 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
775 WHERE cust_main_invoice.custnum = cust_main.custnum
777 if $params->{'no_POST'};
783 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
785 next unless exists($params->{$field});
787 my($beginning, $ending, $hour) = @{$params->{$field}};
790 "cust_main.$field IS NOT NULL",
791 "cust_main.$field >= $beginning",
792 "cust_main.$field <= $ending";
794 if($field eq 'signupdate' && defined $hour) {
795 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
796 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
798 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
799 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
802 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
806 $orderby ||= "ORDER BY cust_main.$field";
814 if ( $params->{'classnum'} ) {
816 my @classnum = ref( $params->{'classnum'} )
817 ? @{ $params->{'classnum'} }
818 : ( $params->{'classnum'} );
820 @classnum = grep /^(\d*)$/, @classnum;
823 push @where, '( '. join(' OR ', map {
824 $_ ? "cust_main.classnum = $_"
825 : "cust_main.classnum IS NULL"
838 if ( $params->{'payby'} ) {
840 my @payby = ref( $params->{'payby'} )
841 ? @{ $params->{'payby'} }
842 : ( $params->{'payby'} );
844 @payby = grep /^([A-Z]{4})$/, @payby;
846 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
852 # paydate_year / paydate_month
855 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
857 $params->{'paydate_month'} =~ /^(\d\d?)$/
858 or die "paydate_year without paydate_month?";
862 'paydate IS NOT NULL',
864 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
872 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
874 if ( $1 eq 'NULL' ) {
876 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
879 "cust_main.invoice_terms IS NOT NULL",
880 "cust_main.invoice_terms = '$1'";
888 if ( $params->{'current_balance'} ) {
890 #my $balance_sql = $class->balance_sql();
891 my $balance_sql = FS::cust_main->balance_sql();
893 my @current_balance =
894 ref( $params->{'current_balance'} )
895 ? @{ $params->{'current_balance'} }
896 : ( $params->{'current_balance'} );
898 push @where, map { s/current_balance/$balance_sql/; $_ }
907 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
909 "cust_main.custbatch = '$1'";
912 if ( $params->{'tagnum'} ) {
913 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
915 @tagnums = grep /^(\d+)$/, @tagnums;
918 if ( $params->{'all_tags'} ) {
919 foreach ( @tagnums ) {
920 push @where, 'exists(select 1 from cust_tag where '.
921 'cust_tag.custnum = cust_main.custnum and tagnum = '.
924 } else { # matching any tag, not all
925 my $tags_where = "0 < (select count(1) from cust_tag where "
926 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
927 . join(',', @tagnums) . "))";
929 push @where, $tags_where;
936 # setup queries, subs, etc. for the search
939 $orderby ||= 'ORDER BY custnum';
941 # here is the agent virtualization
943 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
945 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
948 # always make address fields available in results
949 for my $pre ('bill_', 'ship_') {
951 'LEFT JOIN cust_location AS '.$pre.'location '.
952 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
955 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
959 # there's a good chance that we'll need these
960 'cust_main.bill_locationnum',
961 'cust_main.ship_locationnum',
962 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
965 my(@extra_headers) = ();
966 my(@extra_fields) = ();
968 if ($params->{'flattened_pkgs'}) {
972 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
974 if ($dbh->{Driver}->{Name} eq 'Pg') {
979 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
980 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
985 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
986 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
987 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
988 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
990 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
991 "omitting package information from report.";
995 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
996 FROM cust_main $addl_from $extra_sql $pkgwhere
997 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1000 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1001 $sth->execute() or die $sth->errstr;
1002 my $headerrow = $sth->fetchrow_arrayref;
1003 my $headercount = $headerrow ? $headerrow->[0] : 0;
1004 while($headercount) {
1005 unshift @extra_headers, "Package ". $headercount;
1006 unshift @extra_fields, eval q!sub {my $c = shift;
1007 my @a = split '\|', $c->magic;
1008 my $p = $a[!.--$headercount. q!];
1015 my $select = join(', ', @select);
1018 'table' => 'cust_main',
1019 'select' => $select,
1020 'addl_from' => $addl_from,
1022 'extra_sql' => $extra_sql,
1023 'order_by' => $orderby,
1024 'count_query' => $count_query,
1025 'extra_headers' => \@extra_headers,
1026 'extra_fields' => \@extra_fields,
1028 #warn Data::Dumper::Dumper($sql_query);
1033 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1035 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1036 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1039 Additional options are the same as FS::Record::qsearch
1046 # sensible defaults, then merge in any passed options
1048 'table' => 'cust_main',
1057 my @fuzzy_mod = 'i';
1058 my $conf = new FS::Conf;
1059 my $fuzziness = $conf->config('fuzzy-fuzziness');
1060 push @fuzzy_mod, $fuzziness if $fuzziness;
1062 check_and_rebuild_fuzzyfiles();
1063 foreach my $field ( keys %$fuzzy ) {
1065 my $all = $self->all_X($field);
1066 next unless scalar(@$all);
1069 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1070 next if !keys(%match);
1072 my $in_matches = 'IN (' .
1073 join(',', map { dbh->quote($_) } keys %match) .
1076 my $extra_sql = $fuzopts{extra_sql};
1077 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1078 $extra_sql .= ' AND ';
1080 $extra_sql .= 'WHERE ';
1082 $extra_sql .= "$field $in_matches";
1084 my $addl_from = $fuzopts{addl_from};
1085 if ( $field =~ /^cust_location\./ ) {
1086 $addl_from .= ' JOIN cust_location USING (custnum)';
1087 } elsif ( $field =~ /^contact\./ ) {
1088 $addl_from .= ' JOIN contact USING (custnum)';
1091 push @cust_main, qsearch({
1093 'addl_from' => $addl_from,
1094 'extra_sql' => $extra_sql,
1098 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1100 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1108 =head1 UTILITY SUBROUTINES
1112 =item check_and_rebuild_fuzzyfiles
1116 sub check_and_rebuild_fuzzyfiles {
1117 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1118 rebuild_fuzzyfiles()
1119 if grep { ! -e "$dir/$_" }
1121 my ($field, $table) = reverse split('\.', $_);
1122 $table ||= 'cust_main';
1128 =item rebuild_fuzzyfiles
1132 sub rebuild_fuzzyfiles {
1134 use Fcntl qw(:flock);
1136 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1137 mkdir $dir, 0700 unless -d $dir;
1139 foreach my $fuzzy ( @fuzzyfields ) {
1141 my ($field, $table) = reverse split('\.', $fuzzy);
1142 $table ||= 'cust_main';
1144 open(LOCK,">>$dir/$table.$field")
1145 or die "can't open $dir/$table.$field: $!";
1147 or die "can't lock $dir/$table.$field: $!";
1149 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1150 or die "can't open $dir/$table.$field.tmp: $!";
1152 my $sth = dbh->prepare(
1153 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1155 $sth->execute or die $sth->errstr;
1157 while ( my $row = $sth->fetchrow_arrayref ) {
1158 print CACHE $row->[0]. "\n";
1161 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1163 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1169 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1173 sub append_fuzzyfiles {
1174 #my( $first, $last, $company ) = @_;
1176 check_and_rebuild_fuzzyfiles();
1178 #foreach my $fuzzy (@fuzzyfields) {
1179 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1180 'cust_location.address1',
1183 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1190 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1192 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1196 use Fcntl qw(:flock);
1197 sub append_fuzzyfiles_fuzzyfield {
1198 my( $fuzzyfield, $value ) = @_;
1200 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1203 my ($field, $table) = reverse split('\.', $fuzzyfield);
1204 $table ||= 'cust_main';
1206 return unless length($value);
1208 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1209 or die "can't open $dir/$table.$field: $!";
1210 flock(CACHE,LOCK_EX)
1211 or die "can't lock $dir/$table.$field: $!";
1213 print CACHE "$value\n";
1215 flock(CACHE,LOCK_UN)
1216 or die "can't unlock $dir/$table.$field: $!";
1226 my( $self, $fuzzy ) = @_;
1227 my ($field, $table) = reverse split('\.', $fuzzy);
1228 $table ||= 'cust_main';
1230 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1231 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1232 or die "can't open $dir/$table.$field: $!";
1233 my @array = map { chomp; $_; } <CACHE>;
1244 L<FS::cust_main>, L<FS::Record>