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;
13 @EXPORT_OK = qw( smart_search );
15 # 1 is mostly method/subroutine entry and options
16 # 2 traces progress of some operations
17 # 3 is even more information including possibly sensitive data
19 $me = '[FS::cust_main::Search]';
21 @fuzzyfields = ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
22 'cust_location.address1' );
24 install_callback FS::UID sub {
26 #yes, need it for stuff below (prolly should be cached)
31 FS::cust_main::Search - Customer searching
35 use FS::cust_main::Search;
37 FS::cust_main::Search::smart_search(%options);
39 FS::cust_main::Search::email_search(%options);
41 FS::cust_main::Search->search( \%options );
43 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
49 =item smart_search OPTION => VALUE ...
51 Accepts the following options: I<search>, the string to search for. The string
52 will be searched for as a customer number, phone number, name or company name,
53 as an exact, or, in some cases, a substring or fuzzy match (see the source code
54 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
55 skip fuzzy matching when an exact match is found.
57 Any additional options are treated as an additional qualifier on the search
60 Returns a (possibly empty) array of FS::cust_main objects.
67 #here is the agent virtualization
69 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
73 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
74 my $search = delete $options{'search'};
75 ( my $alphanum_search = $search ) =~ s/\W//g;
77 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
79 #false laziness w/Record::ut_phone
80 my $phonen = "$1-$2-$3";
81 $phonen .= " x$4" if $4;
83 push @cust_main, qsearch( {
84 'table' => 'cust_main',
85 'hashref' => { %options },
86 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
88 join(' OR ', map "$_ = '$phonen'",
89 qw( daytime night mobile fax )
92 " AND $agentnums_sql", #agent virtualization
95 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
96 #try looking for matches with extensions unless one was specified
98 push @cust_main, qsearch( {
99 'table' => 'cust_main',
100 'hashref' => { %options },
101 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
103 join(' OR ', map "$_ LIKE '$phonen\%'",
107 " AND $agentnums_sql", #agent virtualization
112 # custnum search (also try agent_custid), with some tweaking options if your
113 # legacy cust "numbers" have letters
117 if ( $search =~ /@/ ) {
121 'table' => 'cust_main_invoice',
122 'hashref' => { 'dest' => $search },
125 } elsif ( $search =~ /^\s*(\d+)\s*$/
126 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
127 && $search =~ /^\s*(\w\w?\d+)\s*$/
129 || ( $conf->config('cust_main-custnum-display_special')
130 # it's not currently possible for special prefixes to contain
131 # digits, so just strip off any alphabetic prefix and match
132 # the rest to custnum
133 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
135 || ( $conf->exists('address1-search' )
136 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
143 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
144 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
145 ? ' AND agent_custid IS NULL ' : '';
146 push @cust_main, qsearch( {
147 'table' => 'cust_main',
148 'hashref' => { 'custnum' => $num, %options },
149 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
153 # for all agents this user can see, if any of them have custnum prefixes
154 # that match the search string, include customers that match the rest
155 # of the custnum and belong to that agent
156 foreach my $agentnum ( $FS::CurrentUser::CurrentUser->agentnums ) {
157 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
159 if ( $p eq substr($num, 0, length($p)) ) {
160 push @cust_main, qsearch( {
161 'table' => 'cust_main',
162 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
163 'agentnum' => $agentnum,
170 push @cust_main, qsearch( {
171 'table' => 'cust_main',
172 'hashref' => { 'agent_custid' => $num, %options },
173 'extra_sql' => " AND $agentnums_sql", #agent virtualization
176 if ( $conf->exists('address1-search') ) {
177 my $len = length($num);
179 # probably the Right Thing: return customers that have any associated
180 # locations matching the string, not just bill/ship location
181 push @cust_main, qsearch( {
182 'table' => 'cust_main',
183 'addl_from' => ' JOIN cust_location USING (custnum) ',
184 'hashref' => { %options, },
186 ( keys(%options) ? ' AND ' : ' WHERE ' ).
187 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
188 " AND $agentnums_sql",
192 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
194 my($company, $last, $first) = ( $1, $2, $3 );
196 # "Company (Last, First)"
197 #this is probably something a browser remembered,
198 #so just do an exact search (but case-insensitive, so USPS standardization
199 #doesn't throw a wrench in the works)
201 push @cust_main, qsearch( {
202 'table' => 'cust_main',
203 'hashref' => { %options },
205 ( keys(%options) ? ' AND ' : ' WHERE ' ).
207 " LOWER(first) = ". dbh->quote(lc($first)),
208 " LOWER(last) = ". dbh->quote(lc($last)),
209 " LOWER(company) = ". dbh->quote(lc($company)),
215 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
216 # try (ship_){last,company}
220 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
221 # # full strings the browser remembers won't work
222 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
224 use Lingua::EN::NameParse;
225 my $NameParse = new Lingua::EN::NameParse(
230 my($last, $first) = ( '', '' );
231 #maybe disable this too and just rely on NameParse?
232 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
234 ($last, $first) = ( $1, $2 );
236 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
237 } elsif ( ! $NameParse->parse($value) ) {
239 my %name = $NameParse->components;
240 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
241 $last = $name{'surname_1'};
245 if ( $first && $last ) {
247 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
250 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
251 $sql .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
253 push @cust_main, qsearch( {
254 'table' => 'cust_main',
255 'hashref' => \%options,
256 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
260 # or it just be something that was typed in... (try that in a sec)
264 my $q_value = dbh->quote($value);
267 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
268 $sql .= " ( LOWER(last) = $q_value
269 OR LOWER(company) = $q_value
273 SELECT 1 FROM cust_location
274 WHERE LOWER(cust_location.address1) = $q_value
275 AND cust_location.custnum = cust_main.custnum
278 if $conf->exists('address1-search');
281 push @cust_main, qsearch( {
282 'table' => 'cust_main',
283 'hashref' => \%options,
284 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
287 #no exact match, trying substring/fuzzy
288 #always do substring & fuzzy (unless they're explicity config'ed off)
289 #getting complaints searches are not returning enough
290 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
292 #still some false laziness w/search (was search/cust_main.cgi)
297 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
300 if ( $first && $last ) {
301 #contacts? ship_first/ship_last are gone
304 { 'first' => { op=>'ILIKE', value=>"%$first%" },
305 'last' => { op=>'ILIKE', value=>"%$last%" },
312 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
316 foreach my $hashref ( @hashrefs ) {
318 push @cust_main, qsearch( {
319 'table' => 'cust_main',
320 'hashref' => { %$hashref,
323 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
328 if ( $conf->exists('address1-search') ) {
330 push @cust_main, qsearch( {
331 'table' => 'cust_main',
332 'addl_from' => 'JOIN cust_location USING (custnum)',
333 'extra_sql' => 'WHERE cust_location.address1 ILIKE '.
334 dbh->quote("%$value%"),
341 'hashref' => \%options,
343 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
346 if ( $first && $last ) {
347 push @cust_main, FS::cust_main::Search->fuzzy_search(
348 { 'last' => $last, #fuzzy hashref
349 'first' => $first }, #
353 foreach my $field ( 'last', 'company' ) {
355 FS::cust_main::Search->fuzzy_search( { $field => $value }, %fuzopts );
357 if ( $conf->exists('address1-search') ) {
359 FS::cust_main::Search->fuzzy_search(
360 { 'cust_location.address1' => $value }, %fuzopts );
367 #eliminate duplicates
369 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
377 Accepts the following options: I<email>, the email address to search for. The
378 email address will be searched for as an email invoice destination and as an
381 #Any additional options are treated as an additional qualifier on the search
384 Returns a (possibly empty) array of FS::cust_main objects (but usually just
394 my $email = delete $options{'email'};
396 #we're only being used by RT at the moment... no agent virtualization yet
397 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
401 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
403 my ( $user, $domain ) = ( $1, $2 );
405 warn "$me smart_search: searching for $user in domain $domain"
411 'table' => 'cust_main_invoice',
412 'hashref' => { 'dest' => $email },
419 map $_->cust_svc->cust_pkg,
421 'table' => 'svc_acct',
422 'hashref' => { 'username' => $user, },
424 'AND ( SELECT domain FROM svc_domain
425 WHERE svc_acct.domsvc = svc_domain.svcnum
426 ) = '. dbh->quote($domain),
432 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
434 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
451 Returns a qsearch hash expression to search for parameters specified in
452 HASHREF. Valid parameters are
472 listref of start date, end date
476 listref of start date, end date
478 =item spouse_birthdate
480 listref of start date, end date
482 =item anniversary_date
484 listref of start date, end date
494 =item current_balance
496 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
509 my ($class, $params) = @_;
516 # initialize these to prevent warnings
524 'paydate_year' => '',
525 'invoice_terms' => '',
531 # explicit custnum(s)
534 if ( $params->{'custnum'} ) {
535 my @custnums = ref($params->{'custnum'}) ?
536 @{ $params->{'custnum'} } :
537 $params->{'custnum'};
539 'cust_main.custnum IN (' .
540 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
541 ')' if scalar(@custnums) > 0;
548 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
550 "cust_main.agentnum = $1";
554 # do the same for user
557 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
559 "cust_main.usernum = $1";
566 #prospect ordered active inactive suspended cancelled
567 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
568 my $method = $params->{'status'}. '_sql';
569 #push @where, $class->$method();
570 push @where, FS::cust_main->$method();
576 if ( $params->{'address'} =~ /\S/ ) {
577 my $address = dbh->quote('%'. lc($params->{'address'}). '%');
578 push @where, "EXISTS(
579 SELECT 1 FROM cust_location
580 WHERE cust_location.custnum = cust_main.custnum
581 AND (LOWER(cust_location.address1) LIKE $address OR
582 LOWER(cust_location.address2) LIKE $address)
589 if ( $params->{'zip'} =~ /\S/ ) {
590 my $zip = dbh->quote($params->{'zip'} . '%');
591 push @where, "EXISTS(
592 SELECT 1 FROM cust_location
593 WHERE cust_location.custnum = cust_main.custnum
594 AND cust_location.zip LIKE $zip
601 if ( $params->{'refnum'} ) {
603 my @refnum = ref( $params->{'refnum'} )
604 ? @{ $params->{'refnum'} }
605 : ( $params->{'refnum'} );
607 @refnum = grep /^(\d*)$/, @refnum;
609 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
615 # parse cancelled package checkbox
620 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
621 unless $params->{'cancelled_pkgs'};
624 # parse without census tract checkbox
627 push @where, "(ship_location.censustract = '' or ship_location.censustract is null)"
628 if $params->{'no_censustract'};
631 # parse with hardcoded tax location checkbox
634 push @where, "ship_location.geocode is not null"
635 if $params->{'with_geocode'};
638 # "with email address(es)" checkbox
642 'EXISTS ( SELECT 1 FROM cust_main_invoice
643 WHERE cust_main_invoice.custnum = cust_main.custnum
645 )' # AND dest LIKE '%@%'
646 if $params->{'with_email'};
649 # "with postal mail invoices" checkbox
653 "EXISTS ( SELECT 1 FROM cust_main_invoice
654 WHERE cust_main_invoice.custnum = cust_main.custnum
656 if $params->{'POST'};
659 # "without postal mail invoices" checkbox
663 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
664 WHERE cust_main_invoice.custnum = cust_main.custnum
666 if $params->{'no_POST'};
672 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
674 next unless exists($params->{$field});
676 my($beginning, $ending, $hour) = @{$params->{$field}};
679 "cust_main.$field IS NOT NULL",
680 "cust_main.$field >= $beginning",
681 "cust_main.$field <= $ending";
683 if($field eq 'signupdate' && defined $hour) {
684 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
685 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
687 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
688 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
691 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
695 $orderby ||= "ORDER BY cust_main.$field";
703 if ( $params->{'classnum'} ) {
705 my @classnum = ref( $params->{'classnum'} )
706 ? @{ $params->{'classnum'} }
707 : ( $params->{'classnum'} );
709 @classnum = grep /^(\d*)$/, @classnum;
712 push @where, '( '. join(' OR ', map {
713 $_ ? "cust_main.classnum = $_"
714 : "cust_main.classnum IS NULL"
727 if ( $params->{'payby'} ) {
729 my @payby = ref( $params->{'payby'} )
730 ? @{ $params->{'payby'} }
731 : ( $params->{'payby'} );
733 @payby = grep /^([A-Z]{4})$/, @payby;
735 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
741 # paydate_year / paydate_month
744 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
746 $params->{'paydate_month'} =~ /^(\d\d?)$/
747 or die "paydate_year without paydate_month?";
751 'paydate IS NOT NULL',
753 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
761 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
763 if ( $1 eq 'NULL' ) {
765 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
768 "cust_main.invoice_terms IS NOT NULL",
769 "cust_main.invoice_terms = '$1'";
777 if ( $params->{'current_balance'} ) {
779 #my $balance_sql = $class->balance_sql();
780 my $balance_sql = FS::cust_main->balance_sql();
782 my @current_balance =
783 ref( $params->{'current_balance'} )
784 ? @{ $params->{'current_balance'} }
785 : ( $params->{'current_balance'} );
787 push @where, map { s/current_balance/$balance_sql/; $_ }
796 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
798 "cust_main.custbatch = '$1'";
801 if ( $params->{'tagnum'} ) {
802 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
804 @tagnums = grep /^(\d+)$/, @tagnums;
807 if ( $params->{'all_tags'} ) {
808 foreach ( @tagnums ) {
809 push @where, 'exists(select 1 from cust_tag where '.
810 'cust_tag.custnum = cust_main.custnum and tagnum = '.
813 } else { # matching any tag, not all
814 my $tags_where = "0 < (select count(1) from cust_tag where "
815 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
816 . join(',', @tagnums) . "))";
818 push @where, $tags_where;
825 # setup queries, subs, etc. for the search
828 $orderby ||= 'ORDER BY custnum';
830 # here is the agent virtualization
832 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
834 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
837 # always make address fields available in results
838 for my $pre ('bill_', 'ship_') {
840 'LEFT JOIN cust_location AS '.$pre.'location '.
841 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
844 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
848 # there's a good chance that we'll need these
849 'cust_main.bill_locationnum',
850 'cust_main.ship_locationnum',
851 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
854 my(@extra_headers) = ();
855 my(@extra_fields) = ();
857 if ($params->{'flattened_pkgs'}) {
861 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
863 if ($dbh->{Driver}->{Name} eq 'Pg') {
868 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
869 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
874 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
875 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
876 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
877 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
879 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
880 "omitting package information from report.";
884 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
885 FROM cust_main $addl_from $extra_sql $pkgwhere
886 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
889 my $sth = dbh->prepare($header_query) or die dbh->errstr;
890 $sth->execute() or die $sth->errstr;
891 my $headerrow = $sth->fetchrow_arrayref;
892 my $headercount = $headerrow ? $headerrow->[0] : 0;
893 while($headercount) {
894 unshift @extra_headers, "Package ". $headercount;
895 unshift @extra_fields, eval q!sub {my $c = shift;
896 my @a = split '\|', $c->magic;
897 my $p = $a[!.--$headercount. q!];
904 if ( $params->{'with_geocode'} ) {
906 unshift @extra_headers, 'Tax location override', 'Calculated tax location';
907 unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
909 $c->set('geocode', '');
910 $c->geocode('cch'); #XXX only cch right now
912 push @select, 'geocode';
913 push @select, 'zip' unless grep { $_ eq 'zip' } @select;
914 push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
917 my $select = join(', ', @select);
920 'table' => 'cust_main',
922 'addl_from' => $addl_from,
924 'extra_sql' => $extra_sql,
925 'order_by' => $orderby,
926 'count_query' => $count_query,
927 'extra_headers' => \@extra_headers,
928 'extra_fields' => \@extra_fields,
930 warn Data::Dumper::Dumper($sql_query);
935 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
937 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
938 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
941 Additional options are the same as FS::Record::qsearch
948 # sensible defaults, then merge in any passed options
950 'table' => 'cust_main',
960 my $conf = new FS::Conf;
961 my $fuzziness = $conf->config('fuzzy-fuzziness');
962 push @fuzzy_mod, $fuzziness if $fuzziness;
964 check_and_rebuild_fuzzyfiles();
965 foreach my $field ( keys %$fuzzy ) {
967 my $all = $self->all_X($field);
968 next unless scalar(@$all);
971 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
972 next if !keys(%match);
974 my $in_matches = 'IN (' .
975 join(',', map { dbh->quote($_) } keys %match) .
978 my $extra_sql = $fuzopts{extra_sql};
979 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
980 $extra_sql .= ' AND ';
982 $extra_sql .= 'WHERE ';
984 $extra_sql .= "$field $in_matches";
986 my $addl_from = $fuzopts{addl_from};
987 if ( $field =~ /^cust_location/ ) {
988 $addl_from .= ' JOIN cust_location USING (custnum)';
991 push @cust_main, qsearch({
993 'addl_from' => $addl_from,
994 'extra_sql' => $extra_sql,
998 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1000 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1008 =head1 UTILITY SUBROUTINES
1012 =item check_and_rebuild_fuzzyfiles
1016 sub check_and_rebuild_fuzzyfiles {
1017 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1018 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
1021 =item rebuild_fuzzyfiles
1025 sub rebuild_fuzzyfiles {
1027 use Fcntl qw(:flock);
1029 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1030 mkdir $dir, 0700 unless -d $dir;
1032 foreach my $fuzzy ( @fuzzyfields ) {
1034 my ($field, $table) = reverse split('\.', $fuzzy);
1035 $table ||= 'cust_main';
1037 open(LOCK,">>$dir/$table.$field")
1038 or die "can't open $dir/$table.$field: $!";
1040 or die "can't lock $dir/$table.$field: $!";
1042 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1043 or die "can't open $dir/$table.$field.tmp: $!";
1045 my $sth = dbh->prepare(
1046 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1048 $sth->execute or die $sth->errstr;
1050 while ( my $row = $sth->fetchrow_arrayref ) {
1051 print CACHE $row->[0]. "\n";
1054 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1056 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1062 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1066 sub append_fuzzyfiles {
1067 #my( $first, $last, $company ) = @_;
1069 check_and_rebuild_fuzzyfiles();
1071 use Fcntl qw(:flock);
1073 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1075 foreach my $fuzzy (@fuzzyfields) {
1077 my ($field, $table) = reverse split('\.', $fuzzy);
1078 $table ||= 'cust_main';
1084 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1085 or die "can't open $dir/$table.$field: $!";
1086 flock(CACHE,LOCK_EX)
1087 or die "can't lock $dir/$table.$field: $!";
1089 print CACHE "$value\n";
1091 flock(CACHE,LOCK_UN)
1092 or die "can't unlock $dir/$table.$field: $!";
1106 my( $self, $fuzzy ) = @_;
1107 my ($field, $table) = reverse split('\.', $fuzzy);
1108 $table ||= 'cust_main';
1110 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1111 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1112 or die "can't open $dir/$table.$field: $!";
1113 my @array = map { chomp; $_; } <CACHE>;
1124 L<FS::cust_main>, L<FS::Record>