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 my $tax_prefix = FS::Conf->new->exists('tax-ship_location') ? 'ship_'
673 push @where, "${tax_prefix}location.geocode is not null"
674 if $params->{'with_geocode'};
677 # "with email address(es)" checkbox
681 'EXISTS ( SELECT 1 FROM cust_main_invoice
682 WHERE cust_main_invoice.custnum = cust_main.custnum
684 )' # AND dest LIKE '%@%'
685 if $params->{'with_email'};
688 # "with postal mail invoices" checkbox
692 "EXISTS ( SELECT 1 FROM cust_main_invoice
693 WHERE cust_main_invoice.custnum = cust_main.custnum
695 if $params->{'POST'};
698 # "without postal mail invoices" checkbox
702 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
703 WHERE cust_main_invoice.custnum = cust_main.custnum
705 if $params->{'no_POST'};
711 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
713 next unless exists($params->{$field});
715 my($beginning, $ending, $hour) = @{$params->{$field}};
718 "cust_main.$field IS NOT NULL",
719 "cust_main.$field >= $beginning",
720 "cust_main.$field <= $ending";
722 if($field eq 'signupdate' && defined $hour) {
723 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
724 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
726 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
727 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
730 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
734 $orderby ||= "ORDER BY cust_main.$field";
742 if ( $params->{'classnum'} ) {
744 my @classnum = ref( $params->{'classnum'} )
745 ? @{ $params->{'classnum'} }
746 : ( $params->{'classnum'} );
748 @classnum = grep /^(\d*)$/, @classnum;
751 push @where, '( '. join(' OR ', map {
752 $_ ? "cust_main.classnum = $_"
753 : "cust_main.classnum IS NULL"
766 if ( $params->{'payby'} ) {
768 my @payby = ref( $params->{'payby'} )
769 ? @{ $params->{'payby'} }
770 : ( $params->{'payby'} );
772 @payby = grep /^([A-Z]{4})$/, @payby;
774 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
780 # paydate_year / paydate_month
783 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
785 $params->{'paydate_month'} =~ /^(\d\d?)$/
786 or die "paydate_year without paydate_month?";
790 'paydate IS NOT NULL',
792 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
800 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
802 if ( $1 eq 'NULL' ) {
804 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
807 "cust_main.invoice_terms IS NOT NULL",
808 "cust_main.invoice_terms = '$1'";
816 if ( $params->{'current_balance'} ) {
818 #my $balance_sql = $class->balance_sql();
819 my $balance_sql = FS::cust_main->balance_sql();
821 my @current_balance =
822 ref( $params->{'current_balance'} )
823 ? @{ $params->{'current_balance'} }
824 : ( $params->{'current_balance'} );
826 push @where, map { s/current_balance/$balance_sql/; $_ }
835 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
837 "cust_main.custbatch = '$1'";
840 if ( $params->{'tagnum'} ) {
841 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
843 @tagnums = grep /^(\d+)$/, @tagnums;
846 if ( $params->{'all_tags'} ) {
847 foreach ( @tagnums ) {
848 push @where, 'exists(select 1 from cust_tag where '.
849 'cust_tag.custnum = cust_main.custnum and tagnum = '.
852 } else { # matching any tag, not all
853 my $tags_where = "0 < (select count(1) from cust_tag where "
854 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
855 . join(',', @tagnums) . "))";
857 push @where, $tags_where;
864 # setup queries, subs, etc. for the search
867 $orderby ||= 'ORDER BY custnum';
869 # here is the agent virtualization
871 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
873 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
876 # always make address fields available in results
877 for my $pre ('bill_', 'ship_') {
879 'LEFT JOIN cust_location AS '.$pre.'location '.
880 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
883 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
887 # there's a good chance that we'll need these
888 'cust_main.bill_locationnum',
889 'cust_main.ship_locationnum',
890 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
893 my(@extra_headers) = ();
894 my(@extra_fields) = ();
896 if ($params->{'flattened_pkgs'}) {
900 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
902 if ($dbh->{Driver}->{Name} eq 'Pg') {
907 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
908 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
913 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
914 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
915 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
916 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
918 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
919 "omitting package information from report.";
923 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
924 FROM cust_main $addl_from $extra_sql $pkgwhere
925 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
928 my $sth = dbh->prepare($header_query) or die dbh->errstr;
929 $sth->execute() or die $sth->errstr;
930 my $headerrow = $sth->fetchrow_arrayref;
931 my $headercount = $headerrow ? $headerrow->[0] : 0;
932 while($headercount) {
933 unshift @extra_headers, "Package ". $headercount;
934 unshift @extra_fields, eval q!sub {my $c = shift;
935 my @a = split '\|', $c->magic;
936 my $p = $a[!.--$headercount. q!];
943 if ( $params->{'with_geocode'} ) {
945 unshift @extra_headers, 'Tax location override', 'Calculated tax location';
946 unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
948 $c->set('geocode', '');
949 $c->geocode('cch'); #XXX only cch right now
951 push @select, 'geocode';
952 push @select, 'zip' unless grep { $_ eq 'zip' } @select;
953 push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
956 my $select = join(', ', @select);
959 'table' => 'cust_main',
961 'addl_from' => $addl_from,
963 'extra_sql' => $extra_sql,
964 'order_by' => $orderby,
965 'count_query' => $count_query,
966 'extra_headers' => \@extra_headers,
967 'extra_fields' => \@extra_fields,
969 warn Data::Dumper::Dumper($sql_query);
974 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
976 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
977 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
980 Additional options are the same as FS::Record::qsearch
987 # sensible defaults, then merge in any passed options
989 'table' => 'cust_main',
999 my $conf = new FS::Conf;
1000 my $fuzziness = $conf->config('fuzzy-fuzziness');
1001 push @fuzzy_mod, $fuzziness if $fuzziness;
1003 check_and_rebuild_fuzzyfiles();
1004 foreach my $field ( keys %$fuzzy ) {
1006 my $all = $self->all_X($field);
1007 next unless scalar(@$all);
1010 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1011 next if !keys(%match);
1013 my $in_matches = 'IN (' .
1014 join(',', map { dbh->quote($_) } keys %match) .
1017 my $extra_sql = $fuzopts{extra_sql};
1018 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1019 $extra_sql .= ' AND ';
1021 $extra_sql .= 'WHERE ';
1023 $extra_sql .= "$field $in_matches";
1025 my $addl_from = $fuzopts{addl_from};
1026 if ( $field =~ /^cust_location/ ) {
1027 $addl_from .= ' JOIN cust_location USING (custnum)';
1030 push @cust_main, qsearch({
1032 'addl_from' => $addl_from,
1033 'extra_sql' => $extra_sql,
1037 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1039 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1047 =head1 UTILITY SUBROUTINES
1051 =item check_and_rebuild_fuzzyfiles
1055 sub check_and_rebuild_fuzzyfiles {
1056 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1057 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
1060 =item rebuild_fuzzyfiles
1064 sub rebuild_fuzzyfiles {
1066 use Fcntl qw(:flock);
1068 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1069 mkdir $dir, 0700 unless -d $dir;
1071 foreach my $fuzzy ( @fuzzyfields ) {
1073 my ($field, $table) = reverse split('\.', $fuzzy);
1074 $table ||= 'cust_main';
1076 open(LOCK,">>$dir/$table.$field")
1077 or die "can't open $dir/$table.$field: $!";
1079 or die "can't lock $dir/$table.$field: $!";
1081 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1082 or die "can't open $dir/$table.$field.tmp: $!";
1084 my $sth = dbh->prepare(
1085 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1087 $sth->execute or die $sth->errstr;
1089 while ( my $row = $sth->fetchrow_arrayref ) {
1090 print CACHE $row->[0]. "\n";
1093 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1095 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1101 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1105 sub append_fuzzyfiles {
1106 #my( $first, $last, $company ) = @_;
1108 check_and_rebuild_fuzzyfiles();
1110 use Fcntl qw(:flock);
1112 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1114 foreach my $fuzzy (@fuzzyfields) {
1116 my ($field, $table) = reverse split('\.', $fuzzy);
1117 $table ||= 'cust_main';
1123 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1124 or die "can't open $dir/$table.$field: $!";
1125 flock(CACHE,LOCK_EX)
1126 or die "can't lock $dir/$table.$field: $!";
1128 print CACHE "$value\n";
1130 flock(CACHE,LOCK_UN)
1131 or die "can't unlock $dir/$table.$field: $!";
1145 my( $self, $fuzzy ) = @_;
1146 my ($field, $table) = reverse split('\.', $fuzzy);
1147 $table ||= 'cust_main';
1149 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1150 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1151 or die "can't open $dir/$table.$field: $!";
1152 my @array = map { chomp; $_; } <CACHE>;
1163 L<FS::cust_main>, L<FS::Record>