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'} =~ /\S/ ) {
614 my $address = dbh->quote('%'. lc($params->{'address'}). '%');
615 push @where, "EXISTS(
616 SELECT 1 FROM cust_location
617 WHERE cust_location.custnum = cust_main.custnum
618 AND (LOWER(cust_location.address1) LIKE $address OR
619 LOWER(cust_location.address2) LIKE $address)
626 if ( $params->{'zip'} =~ /\S/ ) {
627 my $zip = dbh->quote($params->{'zip'} . '%');
628 push @where, "EXISTS(
629 SELECT 1 FROM cust_location
630 WHERE cust_location.custnum = cust_main.custnum
631 AND cust_location.zip LIKE $zip
638 if ( $params->{'refnum'} ) {
640 my @refnum = ref( $params->{'refnum'} )
641 ? @{ $params->{'refnum'} }
642 : ( $params->{'refnum'} );
644 @refnum = grep /^(\d*)$/, @refnum;
646 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
652 # parse cancelled package checkbox
657 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
658 unless $params->{'cancelled_pkgs'};
661 # parse without census tract checkbox
664 push @where, "(ship_location.censustract = '' or ship_location.censustract is null)"
665 if $params->{'no_censustract'};
668 # parse with hardcoded tax location checkbox
671 push @where, "ship_location.geocode is not null"
672 if $params->{'with_geocode'};
675 # "with email address(es)" checkbox
679 'EXISTS ( SELECT 1 FROM cust_main_invoice
680 WHERE cust_main_invoice.custnum = cust_main.custnum
682 )' # AND dest LIKE '%@%'
683 if $params->{'with_email'};
686 # "with postal mail invoices" checkbox
690 "EXISTS ( SELECT 1 FROM cust_main_invoice
691 WHERE cust_main_invoice.custnum = cust_main.custnum
693 if $params->{'POST'};
696 # "without postal mail invoices" checkbox
700 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
701 WHERE cust_main_invoice.custnum = cust_main.custnum
703 if $params->{'no_POST'};
709 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
711 next unless exists($params->{$field});
713 my($beginning, $ending, $hour) = @{$params->{$field}};
716 "cust_main.$field IS NOT NULL",
717 "cust_main.$field >= $beginning",
718 "cust_main.$field <= $ending";
720 if($field eq 'signupdate' && defined $hour) {
721 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
722 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
724 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
725 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
728 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
732 $orderby ||= "ORDER BY cust_main.$field";
740 if ( $params->{'classnum'} ) {
742 my @classnum = ref( $params->{'classnum'} )
743 ? @{ $params->{'classnum'} }
744 : ( $params->{'classnum'} );
746 @classnum = grep /^(\d*)$/, @classnum;
749 push @where, '( '. join(' OR ', map {
750 $_ ? "cust_main.classnum = $_"
751 : "cust_main.classnum IS NULL"
764 if ( $params->{'payby'} ) {
766 my @payby = ref( $params->{'payby'} )
767 ? @{ $params->{'payby'} }
768 : ( $params->{'payby'} );
770 @payby = grep /^([A-Z]{4})$/, @payby;
772 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
778 # paydate_year / paydate_month
781 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
783 $params->{'paydate_month'} =~ /^(\d\d?)$/
784 or die "paydate_year without paydate_month?";
788 'paydate IS NOT NULL',
790 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
798 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
800 if ( $1 eq 'NULL' ) {
802 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
805 "cust_main.invoice_terms IS NOT NULL",
806 "cust_main.invoice_terms = '$1'";
814 if ( $params->{'current_balance'} ) {
816 #my $balance_sql = $class->balance_sql();
817 my $balance_sql = FS::cust_main->balance_sql();
819 my @current_balance =
820 ref( $params->{'current_balance'} )
821 ? @{ $params->{'current_balance'} }
822 : ( $params->{'current_balance'} );
824 push @where, map { s/current_balance/$balance_sql/; $_ }
833 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
835 "cust_main.custbatch = '$1'";
838 if ( $params->{'tagnum'} ) {
839 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
841 @tagnums = grep /^(\d+)$/, @tagnums;
844 if ( $params->{'all_tags'} ) {
845 foreach ( @tagnums ) {
846 push @where, 'exists(select 1 from cust_tag where '.
847 'cust_tag.custnum = cust_main.custnum and tagnum = '.
850 } else { # matching any tag, not all
851 my $tags_where = "0 < (select count(1) from cust_tag where "
852 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
853 . join(',', @tagnums) . "))";
855 push @where, $tags_where;
862 # setup queries, subs, etc. for the search
865 $orderby ||= 'ORDER BY custnum';
867 # here is the agent virtualization
869 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
871 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
874 # always make address fields available in results
875 for my $pre ('bill_', 'ship_') {
877 'LEFT JOIN cust_location AS '.$pre.'location '.
878 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
881 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
885 # there's a good chance that we'll need these
886 'cust_main.bill_locationnum',
887 'cust_main.ship_locationnum',
888 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
891 my(@extra_headers) = ();
892 my(@extra_fields) = ();
894 if ($params->{'flattened_pkgs'}) {
898 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
900 if ($dbh->{Driver}->{Name} eq 'Pg') {
905 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
906 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
911 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
912 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
913 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
914 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
916 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
917 "omitting package information from report.";
921 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
922 FROM cust_main $addl_from $extra_sql $pkgwhere
923 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
926 my $sth = dbh->prepare($header_query) or die dbh->errstr;
927 $sth->execute() or die $sth->errstr;
928 my $headerrow = $sth->fetchrow_arrayref;
929 my $headercount = $headerrow ? $headerrow->[0] : 0;
930 while($headercount) {
931 unshift @extra_headers, "Package ". $headercount;
932 unshift @extra_fields, eval q!sub {my $c = shift;
933 my @a = split '\|', $c->magic;
934 my $p = $a[!.--$headercount. q!];
941 if ( $params->{'with_geocode'} ) {
943 unshift @extra_headers, 'Tax location override', 'Calculated tax location';
944 unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
946 $c->set('geocode', '');
947 $c->geocode('cch'); #XXX only cch right now
949 push @select, 'geocode';
950 push @select, 'zip' unless grep { $_ eq 'zip' } @select;
951 push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
954 my $select = join(', ', @select);
957 'table' => 'cust_main',
959 'addl_from' => $addl_from,
961 'extra_sql' => $extra_sql,
962 'order_by' => $orderby,
963 'count_query' => $count_query,
964 'extra_headers' => \@extra_headers,
965 'extra_fields' => \@extra_fields,
967 warn Data::Dumper::Dumper($sql_query);
972 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
974 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
975 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
978 Additional options are the same as FS::Record::qsearch
985 # sensible defaults, then merge in any passed options
987 'table' => 'cust_main',
997 my $conf = new FS::Conf;
998 my $fuzziness = $conf->config('fuzzy-fuzziness');
999 push @fuzzy_mod, $fuzziness if $fuzziness;
1001 check_and_rebuild_fuzzyfiles();
1002 foreach my $field ( keys %$fuzzy ) {
1004 my $all = $self->all_X($field);
1005 next unless scalar(@$all);
1008 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1009 next if !keys(%match);
1011 my $in_matches = 'IN (' .
1012 join(',', map { dbh->quote($_) } keys %match) .
1015 my $extra_sql = $fuzopts{extra_sql};
1016 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1017 $extra_sql .= ' AND ';
1019 $extra_sql .= 'WHERE ';
1021 $extra_sql .= "$field $in_matches";
1023 my $addl_from = $fuzopts{addl_from};
1024 if ( $field =~ /^cust_location/ ) {
1025 $addl_from .= ' JOIN cust_location USING (custnum)';
1028 push @cust_main, qsearch({
1030 'addl_from' => $addl_from,
1031 'extra_sql' => $extra_sql,
1035 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1037 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1045 =head1 UTILITY SUBROUTINES
1049 =item check_and_rebuild_fuzzyfiles
1053 sub check_and_rebuild_fuzzyfiles {
1054 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1055 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
1058 =item rebuild_fuzzyfiles
1062 sub rebuild_fuzzyfiles {
1064 use Fcntl qw(:flock);
1066 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1067 mkdir $dir, 0700 unless -d $dir;
1069 foreach my $fuzzy ( @fuzzyfields ) {
1071 my ($field, $table) = reverse split('\.', $fuzzy);
1072 $table ||= 'cust_main';
1074 open(LOCK,">>$dir/$table.$field")
1075 or die "can't open $dir/$table.$field: $!";
1077 or die "can't lock $dir/$table.$field: $!";
1079 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1080 or die "can't open $dir/$table.$field.tmp: $!";
1082 my $sth = dbh->prepare(
1083 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1085 $sth->execute or die $sth->errstr;
1087 while ( my $row = $sth->fetchrow_arrayref ) {
1088 print CACHE $row->[0]. "\n";
1091 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1093 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1099 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1103 sub append_fuzzyfiles {
1104 #my( $first, $last, $company ) = @_;
1106 check_and_rebuild_fuzzyfiles();
1108 use Fcntl qw(:flock);
1110 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1112 foreach my $fuzzy (@fuzzyfields) {
1114 my ($field, $table) = reverse split('\.', $fuzzy);
1115 $table ||= 'cust_main';
1121 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1122 or die "can't open $dir/$table.$field: $!";
1123 flock(CACHE,LOCK_EX)
1124 or die "can't lock $dir/$table.$field: $!";
1126 print CACHE "$value\n";
1128 flock(CACHE,LOCK_UN)
1129 or die "can't unlock $dir/$table.$field: $!";
1143 my( $self, $fuzzy ) = @_;
1144 my ($field, $table) = reverse split('\.', $fuzzy);
1145 $table ||= 'cust_main';
1147 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1148 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1149 or die "can't open $dir/$table.$field: $!";
1150 my @array = map { chomp; $_; } <CACHE>;
1161 L<FS::cust_main>, L<FS::Record>