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]';
22 @fuzzyfields = ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
23 'cust_location.address1' );
25 install_callback FS::UID sub {
27 #yes, need it for stuff below (prolly should be cached)
32 FS::cust_main::Search - Customer searching
36 use FS::cust_main::Search;
38 FS::cust_main::Search::smart_search(%options);
40 FS::cust_main::Search::email_search(%options);
42 FS::cust_main::Search->search( \%options );
44 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
50 =item smart_search OPTION => VALUE ...
52 Accepts the following options: I<search>, the string to search for. The string
53 will be searched for as a customer number, phone number, name or company name,
54 address (if address1-search is on), invoicing email address, or credit card
57 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
58 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
60 skip fuzzy matching when an exact match is found.
62 Any additional options are treated as an additional qualifier on the search
65 Returns a (possibly empty) array of FS::cust_main objects.
72 #here is the agent virtualization
74 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
78 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
79 my $search = delete $options{'search'};
80 ( my $alphanum_search = $search ) =~ s/\W//g;
82 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
84 #false laziness w/Record::ut_phone
85 my $phonen = "$1-$2-$3";
86 $phonen .= " x$4" if $4;
88 push @cust_main, qsearch( {
89 'table' => 'cust_main',
90 'hashref' => { %options },
91 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
93 join(' OR ', map "$_ = '$phonen'",
94 qw( daytime night mobile fax )
97 " AND $agentnums_sql", #agent virtualization
100 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
101 #try looking for matches with extensions unless one was specified
103 push @cust_main, qsearch( {
104 'table' => 'cust_main',
105 'hashref' => { %options },
106 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
108 join(' OR ', map "$_ LIKE '$phonen\%'",
112 " AND $agentnums_sql", #agent virtualization
120 if ( $search =~ /@/ ) { #invoicing email address
124 'table' => 'cust_main_invoice',
125 'hashref' => { 'dest' => $search },
129 # custnum search (also try agent_custid), with some tweaking options if your
130 # legacy cust "numbers" have letters
131 } elsif ( $search =~ /^\s*(\d+)\s*$/
132 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
133 && $search =~ /^\s*(\w\w?\d+)\s*$/
135 || ( $conf->config('cust_main-custnum-display_special')
136 # it's not currently possible for special prefixes to contain
137 # digits, so just strip off any alphabetic prefix and match
138 # the rest to custnum
139 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
141 || ( $conf->exists('address1-search' )
142 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
149 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
150 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
151 ? ' AND agent_custid IS NULL ' : '';
152 push @cust_main, qsearch( {
153 'table' => 'cust_main',
154 'hashref' => { 'custnum' => $num, %options },
155 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
159 # for all agents this user can see, if any of them have custnum prefixes
160 # that match the search string, include customers that match the rest
161 # of the custnum and belong to that agent
162 foreach my $agentnum ( $FS::CurrentUser::CurrentUser->agentnums ) {
163 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
165 if ( $p eq substr($num, 0, length($p)) ) {
166 push @cust_main, qsearch( {
167 'table' => 'cust_main',
168 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
169 'agentnum' => $agentnum,
176 push @cust_main, qsearch( {
177 'table' => 'cust_main',
178 'hashref' => { 'agent_custid' => $num, %options },
179 'extra_sql' => " AND $agentnums_sql", #agent virtualization
182 if ( $conf->exists('address1-search') ) {
183 my $len = length($num);
185 # probably the Right Thing: return customers that have any associated
186 # locations matching the string, not just bill/ship location
187 push @cust_main, qsearch( {
188 'table' => 'cust_main',
189 'addl_from' => ' JOIN cust_location USING (custnum) ',
190 'hashref' => { %options, },
192 ( keys(%options) ? ' AND ' : ' WHERE ' ).
193 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
194 " AND $agentnums_sql",
198 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
200 my($company, $last, $first) = ( $1, $2, $3 );
202 # "Company (Last, First)"
203 #this is probably something a browser remembered,
204 #so just do an exact search (but case-insensitive, so USPS standardization
205 #doesn't throw a wrench in the works)
207 push @cust_main, qsearch( {
208 'table' => 'cust_main',
209 'hashref' => { %options },
211 ( keys(%options) ? ' AND ' : ' WHERE ' ).
213 " LOWER(first) = ". dbh->quote(lc($first)),
214 " LOWER(last) = ". dbh->quote(lc($last)),
215 " LOWER(company) = ". dbh->quote(lc($company)),
221 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
222 # try (ship_){last,company}
226 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
227 # # full strings the browser remembers won't work
228 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
230 use Lingua::EN::NameParse;
231 my $NameParse = new Lingua::EN::NameParse(
236 my($last, $first) = ( '', '' );
237 #maybe disable this too and just rely on NameParse?
238 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
240 ($last, $first) = ( $1, $2 );
242 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
243 } elsif ( ! $NameParse->parse($value) ) {
245 my %name = $NameParse->components;
246 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
247 $last = $name{'surname_1'};
251 if ( $first && $last ) {
253 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
256 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
257 $sql .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
259 push @cust_main, qsearch( {
260 'table' => 'cust_main',
261 'hashref' => \%options,
262 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
266 # or it just be something that was typed in... (try that in a sec)
270 my $q_value = dbh->quote($value);
273 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
274 $sql .= " ( LOWER(last) = $q_value
275 OR LOWER(company) = $q_value
279 SELECT 1 FROM cust_location
280 WHERE LOWER(cust_location.address1) = $q_value
281 AND cust_location.custnum = cust_main.custnum
284 if $conf->exists('address1-search');
287 push @cust_main, qsearch( {
288 'table' => 'cust_main',
289 'hashref' => \%options,
290 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
293 #no exact match, trying substring/fuzzy
294 #always do substring & fuzzy (unless they're explicity config'ed off)
295 #getting complaints searches are not returning enough
296 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
298 #still some false laziness w/search (was search/cust_main.cgi)
303 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
306 if ( $first && $last ) {
307 #contacts? ship_first/ship_last are gone
310 { 'first' => { op=>'ILIKE', value=>"%$first%" },
311 'last' => { op=>'ILIKE', value=>"%$last%" },
318 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
322 foreach my $hashref ( @hashrefs ) {
324 push @cust_main, qsearch( {
325 'table' => 'cust_main',
326 'hashref' => { %$hashref,
329 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
334 if ( $conf->exists('address1-search') ) {
336 push @cust_main, qsearch( {
337 'table' => 'cust_main',
338 'addl_from' => 'JOIN cust_location USING (custnum)',
339 'extra_sql' => 'WHERE cust_location.address1 ILIKE '.
340 dbh->quote("%$value%"),
347 'hashref' => \%options,
349 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
352 if ( $first && $last ) {
353 push @cust_main, FS::cust_main::Search->fuzzy_search(
354 { 'last' => $last, #fuzzy hashref
355 'first' => $first }, #
359 foreach my $field ( 'last', 'company' ) {
361 FS::cust_main::Search->fuzzy_search( { $field => $value }, %fuzopts );
363 if ( $conf->exists('address1-search') ) {
365 FS::cust_main::Search->fuzzy_search(
366 { 'cust_location.address1' => $value }, %fuzopts );
373 ( my $nospace_search = $search ) =~ s/\s//g;
374 ( my $card_search = $nospace_search ) =~ s/\-//g;
375 $card_search =~ s/[x\*\.\_]/x/gi;
377 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
379 ( my $like_search = $card_search ) =~ s/x/_/g;
380 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
382 push @cust_main, qsearch({
383 'table' => 'cust_main',
385 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
386 OR paymask = '$mask_search'
388 " AND payby IN ('CARD','DCRD') ".
389 " AND $agentnums_sql", #agent virtulization
395 #eliminate duplicates
397 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
405 Accepts the following options: I<email>, the email address to search for. The
406 email address will be searched for as an email invoice destination and as an
409 #Any additional options are treated as an additional qualifier on the search
412 Returns a (possibly empty) array of FS::cust_main objects (but usually just
422 my $email = delete $options{'email'};
424 #we're only being used by RT at the moment... no agent virtualization yet
425 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
429 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
431 my ( $user, $domain ) = ( $1, $2 );
433 warn "$me smart_search: searching for $user in domain $domain"
439 'table' => 'cust_main_invoice',
440 'hashref' => { 'dest' => $email },
447 map $_->cust_svc->cust_pkg,
449 'table' => 'svc_acct',
450 'hashref' => { 'username' => $user, },
452 'AND ( SELECT domain FROM svc_domain
453 WHERE svc_acct.domsvc = svc_domain.svcnum
454 ) = '. dbh->quote($domain),
460 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
462 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
479 Returns a qsearch hash expression to search for parameters specified in
480 HASHREF. Valid parameters are
500 listref of start date, end date
504 listref of start date, end date
506 =item spouse_birthdate
508 listref of start date, end date
510 =item anniversary_date
512 listref of start date, end date
522 =item current_balance
524 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
537 my ($class, $params) = @_;
544 # initialize these to prevent warnings
552 'paydate_year' => '',
553 'invoice_terms' => '',
559 # explicit custnum(s)
562 if ( $params->{'custnum'} ) {
563 my @custnums = ref($params->{'custnum'}) ?
564 @{ $params->{'custnum'} } :
565 $params->{'custnum'};
567 'cust_main.custnum IN (' .
568 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
569 ')' if scalar(@custnums) > 0;
576 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
578 "cust_main.agentnum = $1";
585 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
586 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
587 : 'cust_main.salesnum IS NULL';
594 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
596 "cust_main.usernum = $1";
603 #prospect ordered active inactive suspended cancelled
604 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
605 my $method = $params->{'status'}. '_sql';
606 #push @where, $class->$method();
607 push @where, FS::cust_main->$method();
613 if ( $params->{'address'} ) {
614 # allow this to be an arrayref
615 my @values = ($params->{'address'});
616 @values = @{$values[0]} if ref($values[0]);
618 foreach (grep /\S/, @values) {
619 my $address = dbh->quote('%'. lc($_). '%');
621 "LOWER(cust_location.address1) LIKE $address",
622 "LOWER(cust_location.address2) LIKE $address";
625 push @where, "EXISTS(
626 SELECT 1 FROM cust_location
627 WHERE cust_location.custnum = cust_main.custnum
628 AND (".join(' OR ',@orwhere).")
636 if ( $params->{'zip'} =~ /\S/ ) {
637 my $zip = dbh->quote($params->{'zip'} . '%');
638 push @where, "EXISTS(
639 SELECT 1 FROM cust_location
640 WHERE cust_location.custnum = cust_main.custnum
641 AND cust_location.zip LIKE $zip
648 if ( $params->{'refnum'} ) {
650 my @refnum = ref( $params->{'refnum'} )
651 ? @{ $params->{'refnum'} }
652 : ( $params->{'refnum'} );
654 @refnum = grep /^(\d*)$/, @refnum;
656 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
662 # parse cancelled package checkbox
667 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
668 unless $params->{'cancelled_pkgs'};
671 # parse without census tract checkbox
674 push @where, "(ship_location.censustract = '' or ship_location.censustract is null)"
675 if $params->{'no_censustract'};
678 # parse with hardcoded tax location checkbox
681 my $tax_prefix = FS::Conf->new->exists('tax-ship_location') ? 'ship_'
683 push @where, "${tax_prefix}location.geocode is not null"
684 if $params->{'with_geocode'};
687 # "with email address(es)" checkbox
691 'EXISTS ( SELECT 1 FROM cust_main_invoice
692 WHERE cust_main_invoice.custnum = cust_main.custnum
694 )' # AND dest LIKE '%@%'
695 if $params->{'with_email'};
698 # "with postal mail invoices" checkbox
702 "EXISTS ( SELECT 1 FROM cust_main_invoice
703 WHERE cust_main_invoice.custnum = cust_main.custnum
705 if $params->{'POST'};
708 # "without postal mail invoices" checkbox
712 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
713 WHERE cust_main_invoice.custnum = cust_main.custnum
715 if $params->{'no_POST'};
721 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
723 next unless exists($params->{$field});
725 my($beginning, $ending, $hour) = @{$params->{$field}};
728 "cust_main.$field IS NOT NULL",
729 "cust_main.$field >= $beginning",
730 "cust_main.$field <= $ending";
732 if($field eq 'signupdate' && defined $hour) {
733 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
734 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
736 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
737 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
740 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
744 $orderby ||= "ORDER BY cust_main.$field";
752 if ( $params->{'classnum'} ) {
754 my @classnum = ref( $params->{'classnum'} )
755 ? @{ $params->{'classnum'} }
756 : ( $params->{'classnum'} );
758 @classnum = grep /^(\d*)$/, @classnum;
761 push @where, '( '. join(' OR ', map {
762 $_ ? "cust_main.classnum = $_"
763 : "cust_main.classnum IS NULL"
776 if ( $params->{'payby'} ) {
778 my @payby = ref( $params->{'payby'} )
779 ? @{ $params->{'payby'} }
780 : ( $params->{'payby'} );
782 @payby = grep /^([A-Z]{4})$/, @payby;
784 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
790 # paydate_year / paydate_month
793 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
795 $params->{'paydate_month'} =~ /^(\d\d?)$/
796 or die "paydate_year without paydate_month?";
800 'paydate IS NOT NULL',
802 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
810 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
812 if ( $1 eq 'NULL' ) {
814 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
817 "cust_main.invoice_terms IS NOT NULL",
818 "cust_main.invoice_terms = '$1'";
826 if ( $params->{'current_balance'} ) {
828 #my $balance_sql = $class->balance_sql();
829 my $balance_sql = FS::cust_main->balance_sql();
831 my @current_balance =
832 ref( $params->{'current_balance'} )
833 ? @{ $params->{'current_balance'} }
834 : ( $params->{'current_balance'} );
836 push @where, map { s/current_balance/$balance_sql/; $_ }
845 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
847 "cust_main.custbatch = '$1'";
850 if ( $params->{'tagnum'} ) {
851 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
853 @tagnums = grep /^(\d+)$/, @tagnums;
856 if ( $params->{'all_tags'} ) {
857 foreach ( @tagnums ) {
858 push @where, 'exists(select 1 from cust_tag where '.
859 'cust_tag.custnum = cust_main.custnum and tagnum = '.
862 } else { # matching any tag, not all
863 my $tags_where = "0 < (select count(1) from cust_tag where "
864 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
865 . join(',', @tagnums) . "))";
867 push @where, $tags_where;
874 # setup queries, subs, etc. for the search
877 $orderby ||= 'ORDER BY custnum';
879 # here is the agent virtualization
881 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
883 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
886 # always make address fields available in results
887 for my $pre ('bill_', 'ship_') {
889 'LEFT JOIN cust_location AS '.$pre.'location '.
890 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
893 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
897 # there's a good chance that we'll need these
898 'cust_main.bill_locationnum',
899 'cust_main.ship_locationnum',
900 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
903 my(@extra_headers) = ();
904 my(@extra_fields) = ();
906 if ($params->{'flattened_pkgs'}) {
910 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
912 if ($dbh->{Driver}->{Name} eq 'Pg') {
917 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
918 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
923 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
924 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
925 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
926 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
928 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
929 "omitting package information from report.";
933 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
934 FROM cust_main $addl_from $extra_sql $pkgwhere
935 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
938 my $sth = dbh->prepare($header_query) or die dbh->errstr;
939 $sth->execute() or die $sth->errstr;
940 my $headerrow = $sth->fetchrow_arrayref;
941 my $headercount = $headerrow ? $headerrow->[0] : 0;
942 while($headercount) {
943 unshift @extra_headers, "Package ". $headercount;
944 unshift @extra_fields, eval q!sub {my $c = shift;
945 my @a = split '\|', $c->magic;
946 my $p = $a[!.--$headercount. q!];
953 if ( $params->{'with_geocode'} ) {
955 unshift @extra_headers, 'Tax location override', 'Calculated tax location';
956 unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
958 $c->set('geocode', '');
959 $c->geocode('cch'); #XXX only cch right now
961 push @select, 'geocode';
962 push @select, 'zip' unless grep { $_ eq 'zip' } @select;
963 push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
966 my $select = join(', ', @select);
969 'table' => 'cust_main',
971 'addl_from' => $addl_from,
973 'extra_sql' => $extra_sql,
974 'order_by' => $orderby,
975 'count_query' => $count_query,
976 'extra_headers' => \@extra_headers,
977 'extra_fields' => \@extra_fields,
979 warn Data::Dumper::Dumper($sql_query);
984 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
986 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
987 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
990 Additional options are the same as FS::Record::qsearch
997 # sensible defaults, then merge in any passed options
999 'table' => 'cust_main',
1008 my @fuzzy_mod = 'i';
1009 my $conf = new FS::Conf;
1010 my $fuzziness = $conf->config('fuzzy-fuzziness');
1011 push @fuzzy_mod, $fuzziness if $fuzziness;
1013 check_and_rebuild_fuzzyfiles();
1014 foreach my $field ( keys %$fuzzy ) {
1016 my $all = $self->all_X($field);
1017 next unless scalar(@$all);
1020 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1021 next if !keys(%match);
1023 my $in_matches = 'IN (' .
1024 join(',', map { dbh->quote($_) } keys %match) .
1027 my $extra_sql = $fuzopts{extra_sql};
1028 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1029 $extra_sql .= ' AND ';
1031 $extra_sql .= 'WHERE ';
1033 $extra_sql .= "$field $in_matches";
1035 my $addl_from = $fuzopts{addl_from};
1036 if ( $field =~ /^cust_location/ ) {
1037 $addl_from .= ' JOIN cust_location USING (custnum)';
1040 push @cust_main, qsearch({
1042 'addl_from' => $addl_from,
1043 'extra_sql' => $extra_sql,
1047 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1049 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1057 =head1 UTILITY SUBROUTINES
1061 =item check_and_rebuild_fuzzyfiles
1065 sub check_and_rebuild_fuzzyfiles {
1066 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1067 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
1070 =item rebuild_fuzzyfiles
1074 sub rebuild_fuzzyfiles {
1076 use Fcntl qw(:flock);
1078 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1079 mkdir $dir, 0700 unless -d $dir;
1081 foreach my $fuzzy ( @fuzzyfields ) {
1083 my ($field, $table) = reverse split('\.', $fuzzy);
1084 $table ||= 'cust_main';
1086 open(LOCK,">>$dir/$table.$field")
1087 or die "can't open $dir/$table.$field: $!";
1089 or die "can't lock $dir/$table.$field: $!";
1091 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1092 or die "can't open $dir/$table.$field.tmp: $!";
1094 my $sth = dbh->prepare(
1095 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1097 $sth->execute or die $sth->errstr;
1099 while ( my $row = $sth->fetchrow_arrayref ) {
1100 print CACHE $row->[0]. "\n";
1103 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1105 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1111 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1115 sub append_fuzzyfiles {
1116 #my( $first, $last, $company ) = @_;
1118 check_and_rebuild_fuzzyfiles();
1120 use Fcntl qw(:flock);
1122 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1124 foreach my $fuzzy (@fuzzyfields) {
1126 my ($field, $table) = reverse split('\.', $fuzzy);
1127 $table ||= 'cust_main';
1133 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1134 or die "can't open $dir/$table.$field: $!";
1135 flock(CACHE,LOCK_EX)
1136 or die "can't lock $dir/$table.$field: $!";
1138 print CACHE "$value\n";
1140 flock(CACHE,LOCK_UN)
1141 or die "can't unlock $dir/$table.$field: $!";
1155 my( $self, $fuzzy ) = @_;
1156 my ($field, $table) = reverse split('\.', $fuzzy);
1157 $table ||= 'cust_main';
1159 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1160 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1161 or die "can't open $dir/$table.$field: $!";
1162 my @array = map { chomp; $_; } <CACHE>;
1173 L<FS::cust_main>, L<FS::Record>