1 package FS::cust_main::Search;
4 use base qw( Exporter );
5 use vars qw( @EXPORT_OK $DEBUG $me $conf @fuzzyfields );
6 use String::Approx qw(amatch);
8 use FS::Record qw( qsearch );
10 use FS::cust_main_invoice;
12 use FS::payinfo_Mixin;
14 @EXPORT_OK = qw( smart_search );
16 # 1 is mostly method/subroutine entry and options
17 # 2 traces progress of some operations
18 # 3 is even more information including possibly sensitive data
20 $me = '[FS::cust_main::Search]';
23 'cust_main.first', 'cust_main.last', 'cust_main.company',
24 'cust_location.address1',
25 'contact.first', 'contact.last',
28 install_callback FS::UID sub {
30 #yes, need it for stuff below (prolly should be cached)
35 FS::cust_main::Search - Customer searching
39 use FS::cust_main::Search;
41 FS::cust_main::Search::smart_search(%options);
43 FS::cust_main::Search::email_search(%options);
45 FS::cust_main::Search->search( \%options );
47 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
53 =item smart_search OPTION => VALUE ...
55 Accepts the following options: I<search>, the string to search for. The string
56 will be searched for as a customer number, phone number, name or company name,
57 address (if address1-search is on), invoicing email address, or credit card
60 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
61 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
63 skip fuzzy matching when an exact match is found.
65 Any additional options are treated as an additional qualifier on the search
68 Returns a (possibly empty) array of FS::cust_main objects.
75 #here is the agent virtualization
77 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
78 my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
82 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
83 my $search = delete $options{'search'};
84 ( my $alphanum_search = $search ) =~ s/\W//g;
86 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
88 #false laziness w/Record::ut_phone
89 my $phonen = "$1-$2-$3";
90 $phonen .= " x$4" if $4;
92 my $phonenum = "$1$2$3";
95 #cust_main phone numbers
96 push @cust_main, qsearch( {
97 'table' => 'cust_main',
98 'hashref' => { %options },
99 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
101 join(' OR ', map "$_ = '$phonen'",
102 qw( daytime night mobile fax )
105 " AND $agentnums_sql", #agent virtualization
108 #contact phone numbers
110 grep $agentnums_href->{$_->agentnum}, #agent virt
111 grep $_, #skip contacts that don't have cust_main records
112 map $_->contact->cust_main,
114 'table' => 'contact_phone',
115 'hashref' => { 'phonenum' => $phonenum },
118 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
119 #try looking for matches with extensions unless one was specified
121 push @cust_main, qsearch( {
122 'table' => 'cust_main',
123 'hashref' => { %options },
124 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
126 join(' OR ', map "$_ LIKE '$phonen\%'",
130 " AND $agentnums_sql", #agent virtualization
138 if ( $search =~ /@/ ) { #email address
140 # invoicing email address
142 grep $agentnums_href->{$_->agentnum}, #agent virt
145 'table' => 'cust_main_invoice',
146 'hashref' => { 'dest' => $search },
150 # contact email address
152 grep $agentnums_href->{$_->agentnum}, #agent virt
153 grep $_, #skip contacts that don't have cust_main records
154 map $_->contact->cust_main,
156 'table' => 'contact_email',
157 'hashref' => { 'emailaddress' => $search },
161 # custnum search (also try agent_custid), with some tweaking options if your
162 # legacy cust "numbers" have letters
163 } elsif ( $search =~ /^\s*(\d+)\s*$/
164 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
165 && $search =~ /^\s*(\w\w?\d+)\s*$/
167 || ( $conf->config('cust_main-custnum-display_special')
168 # it's not currently possible for special prefixes to contain
169 # digits, so just strip off any alphabetic prefix and match
170 # the rest to custnum
171 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
173 || ( $conf->exists('address1-search' )
174 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
181 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
182 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
183 ? ' AND agent_custid IS NULL ' : '';
184 push @cust_main, qsearch( {
185 'table' => 'cust_main',
186 'hashref' => { 'custnum' => $num, %options },
187 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
191 # for all agents this user can see, if any of them have custnum prefixes
192 # that match the search string, include customers that match the rest
193 # of the custnum and belong to that agent
194 foreach my $agentnum ( keys %$agentnums_href ) {
195 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
197 if ( $p eq substr($num, 0, length($p)) ) {
198 push @cust_main, qsearch( {
199 'table' => 'cust_main',
200 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
201 'agentnum' => $agentnum,
208 push @cust_main, qsearch( {
209 'table' => 'cust_main',
210 'hashref' => { 'agent_custid' => $num, %options },
211 'extra_sql' => " AND $agentnums_sql", #agent virtualization
214 if ( $conf->exists('address1-search') ) {
215 my $len = length($num);
217 # probably the Right Thing: return customers that have any associated
218 # locations matching the string, not just bill/ship location
219 push @cust_main, qsearch( {
220 'table' => 'cust_main',
221 'addl_from' => ' JOIN cust_location USING (custnum) ',
222 'hashref' => { %options, },
224 ( keys(%options) ? ' AND ' : ' WHERE ' ).
225 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
226 " AND $agentnums_sql",
230 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
232 my($company, $last, $first) = ( $1, $2, $3 );
234 # "Company (Last, First)"
235 #this is probably something a browser remembered,
236 #so just do an exact search (but case-insensitive, so USPS standardization
237 #doesn't throw a wrench in the works)
239 push @cust_main, qsearch( {
240 'table' => 'cust_main',
241 'hashref' => { %options },
243 ( keys(%options) ? ' AND ' : ' WHERE ' ).
245 " LOWER(first) = ". dbh->quote(lc($first)),
246 " LOWER(last) = ". dbh->quote(lc($last)),
247 " LOWER(company) = ". dbh->quote(lc($company)),
253 # probably not necessary for the "something a browser remembered" case
255 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
256 # try {first,last,company}
260 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
261 # # full strings the browser remembers won't work
262 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
264 use Lingua::EN::NameParse;
265 my $NameParse = new Lingua::EN::NameParse(
270 my($last, $first) = ( '', '' );
271 #maybe disable this too and just rely on NameParse?
272 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
274 ($last, $first) = ( $1, $2 );
276 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
277 } elsif ( ! $NameParse->parse($value) ) {
279 my %name = $NameParse->components;
280 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
281 $last = $name{'surname_1'};
285 if ( $first && $last ) {
287 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
290 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
291 $sql .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
294 push @cust_main, qsearch( {
295 'table' => 'cust_main',
296 'hashref' => \%options,
297 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
302 grep $agentnums_href->{$_->agentnum}, #agent virt
303 grep $_, #skip contacts that don't have cust_main records
306 'table' => 'contact',
307 'hashref' => { 'first' => $first,
313 # or it just be something that was typed in... (try that in a sec)
317 my $q_value = dbh->quote($value);
320 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
321 $sql .= " ( LOWER(cust_main.first) = $q_value
322 OR LOWER(cust_main.last) = $q_value
323 OR LOWER(cust_main.company) = $q_value
326 #address1 (yes, it's a kludge)
327 $sql .= " OR EXISTS (
328 SELECT 1 FROM cust_location
329 WHERE LOWER(cust_location.address1) = $q_value
330 AND cust_location.custnum = cust_main.custnum
332 if $conf->exists('address1-search');
334 #contacts (look, another kludge)
335 $sql .= " OR EXISTS ( SELECT 1 FROM contact
336 WHERE ( LOWER(contact.first) = $q_value
337 OR LOWER(contact.last) = $q_value
339 AND contact.custnum IS NOT NULL
340 AND contact.custnum = cust_main.custnum
344 push @cust_main, qsearch( {
345 'table' => 'cust_main',
346 'hashref' => \%options,
347 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
350 #no exact match, trying substring/fuzzy
351 #always do substring & fuzzy (unless they're explicity config'ed off)
352 #getting complaints searches are not returning enough
353 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
355 #still some false laziness w/search (was search/cust_main.cgi)
360 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
363 if ( $first && $last ) {
366 { 'first' => { op=>'ILIKE', value=>"%$first%" },
367 'last' => { op=>'ILIKE', value=>"%$last%" },
374 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
375 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
379 foreach my $hashref ( @hashrefs ) {
381 push @cust_main, qsearch( {
382 'table' => 'cust_main',
383 'hashref' => { %$hashref,
386 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
391 if ( $conf->exists('address1-search') ) {
393 push @cust_main, qsearch( {
394 table => 'cust_main',
395 addl_from => 'JOIN cust_location USING (custnum)',
396 extra_sql => 'WHERE '.
397 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
398 " AND $agentnums_sql", #agent virtualizaiton
405 shift @hashrefs; #no company column in contact table
407 foreach my $hashref ( @hashrefs ) {
410 grep $agentnums_href->{$_->agentnum}, #agent virt
411 grep $_, #skip contacts that don't have cust_main records
414 'table' => 'contact',
415 'hashref' => { %$hashref,
418 #'extra_sql' => " AND $agentnums_sql", #agent virt
425 'hashref' => \%options,
427 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
430 if ( $first && $last ) {
431 push @cust_main, FS::cust_main::Search->fuzzy_search(
432 { 'last' => $last, #fuzzy hashref
433 'first' => $first }, #
436 push @cust_main, FS::cust_main::Search->fuzzy_search(
437 { 'contact.last' => $last, #fuzzy hashref
438 'contact.first' => $first }, #
442 foreach my $field ( 'first', 'last', 'company' ) {
443 push @cust_main, FS::cust_main::Search->fuzzy_search(
444 { $field => $value },
448 foreach my $field ( 'first', 'last' ) {
449 push @cust_main, FS::cust_main::Search->fuzzy_search(
450 { "contact.$field" => $value },
454 if ( $conf->exists('address1-search') ) {
456 FS::cust_main::Search->fuzzy_search(
457 { 'cust_location.address1' => $value },
466 ( my $nospace_search = $search ) =~ s/\s//g;
467 ( my $card_search = $nospace_search ) =~ s/\-//g;
468 $card_search =~ s/[x\*\.\_]/x/gi;
470 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
472 ( my $like_search = $card_search ) =~ s/x/_/g;
473 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
475 push @cust_main, qsearch({
476 'table' => 'cust_main',
478 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
479 OR paymask = '$mask_search'
481 " AND payby IN ('CARD','DCRD') ".
482 " AND $agentnums_sql", #agent virtulization
488 #eliminate duplicates
490 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
498 Accepts the following options: I<email>, the email address to search for. The
499 email address will be searched for as an email invoice destination and as an
502 #Any additional options are treated as an additional qualifier on the search
505 Returns a (possibly empty) array of FS::cust_main objects (but usually just
515 my $email = delete $options{'email'};
517 #we're only being used by RT at the moment... no agent virtualization yet
518 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
522 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
524 my ( $user, $domain ) = ( $1, $2 );
526 warn "$me smart_search: searching for $user in domain $domain"
532 'table' => 'cust_main_invoice',
533 'hashref' => { 'dest' => $email },
540 map $_->cust_svc->cust_pkg,
542 'table' => 'svc_acct',
543 'hashref' => { 'username' => $user, },
545 'AND ( SELECT domain FROM svc_domain
546 WHERE svc_acct.domsvc = svc_domain.svcnum
547 ) = '. dbh->quote($domain),
553 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
555 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
572 Returns a qsearch hash expression to search for parameters specified in
573 HASHREF. Valid parameters are
593 listref of start date, end date
597 listref of start date, end date
599 =item spouse_birthdate
601 listref of start date, end date
603 =item anniversary_date
605 listref of start date, end date
615 =item current_balance
617 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
630 my ($class, $params) = @_;
637 # initialize these to prevent warnings
645 'paydate_year' => '',
646 'invoice_terms' => '',
652 # explicit custnum(s)
655 if ( $params->{'custnum'} ) {
656 my @custnums = ref($params->{'custnum'}) ?
657 @{ $params->{'custnum'} } :
658 $params->{'custnum'};
660 'cust_main.custnum IN (' .
661 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
662 ')' if scalar(@custnums) > 0;
669 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
671 "cust_main.agentnum = $1";
678 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
679 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
680 : 'cust_main.salesnum IS NULL';
687 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
689 "cust_main.usernum = $1";
696 #prospect ordered active inactive suspended cancelled
697 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
698 my $method = $params->{'status'}. '_sql';
699 #push @where, $class->$method();
700 push @where, FS::cust_main->$method();
706 if ( $params->{'address'} ) {
707 # allow this to be an arrayref
708 my @values = ($params->{'address'});
709 @values = @{$values[0]} if ref($values[0]);
711 foreach (grep /\S/, @values) {
712 my $address = dbh->quote('%'. lc($_). '%');
714 "LOWER(cust_location.address1) LIKE $address",
715 "LOWER(cust_location.address2) LIKE $address";
718 push @where, "EXISTS(
719 SELECT 1 FROM cust_location
720 WHERE cust_location.custnum = cust_main.custnum
721 AND (".join(' OR ',@orwhere).")
729 if ( $params->{'zip'} =~ /\S/ ) {
730 my $zip = dbh->quote($params->{'zip'} . '%');
731 push @where, "EXISTS(
732 SELECT 1 FROM cust_location
733 WHERE cust_location.custnum = cust_main.custnum
734 AND cust_location.zip LIKE $zip
741 if ( $params->{'refnum'} ) {
743 my @refnum = ref( $params->{'refnum'} )
744 ? @{ $params->{'refnum'} }
745 : ( $params->{'refnum'} );
747 @refnum = grep /^(\d*)$/, @refnum;
749 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
755 # parse cancelled package checkbox
760 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
761 unless $params->{'cancelled_pkgs'};
764 # "with email address(es)" checkbox
768 'EXISTS ( SELECT 1 FROM cust_main_invoice
769 WHERE cust_main_invoice.custnum = cust_main.custnum
771 )' # AND dest LIKE '%@%'
772 if $params->{'with_email'};
775 # "with postal mail invoices" checkbox
779 "EXISTS ( SELECT 1 FROM cust_main_invoice
780 WHERE cust_main_invoice.custnum = cust_main.custnum
782 if $params->{'POST'};
785 # "without postal mail invoices" checkbox
789 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
790 WHERE cust_main_invoice.custnum = cust_main.custnum
792 if $params->{'no_POST'};
798 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
800 next unless exists($params->{$field});
802 my($beginning, $ending, $hour) = @{$params->{$field}};
805 "cust_main.$field IS NOT NULL",
806 "cust_main.$field >= $beginning",
807 "cust_main.$field <= $ending";
809 if($field eq 'signupdate' && defined $hour) {
810 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
811 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
813 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
814 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
817 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
821 $orderby ||= "ORDER BY cust_main.$field";
829 if ( $params->{'classnum'} ) {
831 my @classnum = ref( $params->{'classnum'} )
832 ? @{ $params->{'classnum'} }
833 : ( $params->{'classnum'} );
835 @classnum = grep /^(\d*)$/, @classnum;
838 push @where, '( '. join(' OR ', map {
839 $_ ? "cust_main.classnum = $_"
840 : "cust_main.classnum IS NULL"
853 if ( $params->{'payby'} ) {
855 my @payby = ref( $params->{'payby'} )
856 ? @{ $params->{'payby'} }
857 : ( $params->{'payby'} );
859 @payby = grep /^([A-Z]{4})$/, @payby;
861 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
867 # paydate_year / paydate_month
870 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
872 $params->{'paydate_month'} =~ /^(\d\d?)$/
873 or die "paydate_year without paydate_month?";
877 'paydate IS NOT NULL',
879 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
887 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
889 if ( $1 eq 'NULL' ) {
891 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
894 "cust_main.invoice_terms IS NOT NULL",
895 "cust_main.invoice_terms = '$1'";
903 if ( $params->{'current_balance'} ) {
905 #my $balance_sql = $class->balance_sql();
906 my $balance_sql = FS::cust_main->balance_sql();
908 my @current_balance =
909 ref( $params->{'current_balance'} )
910 ? @{ $params->{'current_balance'} }
911 : ( $params->{'current_balance'} );
913 push @where, map { s/current_balance/$balance_sql/; $_ }
922 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
924 "cust_main.custbatch = '$1'";
927 if ( $params->{'tagnum'} ) {
928 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
930 @tagnums = grep /^(\d+)$/, @tagnums;
933 if ( $params->{'all_tags'} ) {
934 foreach ( @tagnums ) {
935 push @where, 'exists(select 1 from cust_tag where '.
936 'cust_tag.custnum = cust_main.custnum and tagnum = '.
939 } else { # matching any tag, not all
940 my $tags_where = "0 < (select count(1) from cust_tag where "
941 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
942 . join(',', @tagnums) . "))";
944 push @where, $tags_where;
951 # setup queries, subs, etc. for the search
954 $orderby ||= 'ORDER BY custnum';
956 # here is the agent virtualization
958 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
960 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
963 # always make address fields available in results
964 for my $pre ('bill_', 'ship_') {
966 'LEFT JOIN cust_location AS '.$pre.'location '.
967 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
970 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
974 # there's a good chance that we'll need these
975 'cust_main.bill_locationnum',
976 'cust_main.ship_locationnum',
977 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
980 my(@extra_headers) = ();
981 my(@extra_fields) = ();
983 if ($params->{'flattened_pkgs'}) {
987 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
989 if ($dbh->{Driver}->{Name} eq 'Pg') {
994 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
995 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1000 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1001 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1002 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1003 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1005 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1006 "omitting package information from report.";
1009 my $header_query = "
1010 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1011 FROM cust_main $addl_from $extra_sql $pkgwhere
1012 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1015 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1016 $sth->execute() or die $sth->errstr;
1017 my $headerrow = $sth->fetchrow_arrayref;
1018 my $headercount = $headerrow ? $headerrow->[0] : 0;
1019 while($headercount) {
1020 unshift @extra_headers, "Package ". $headercount;
1021 unshift @extra_fields, eval q!sub {my $c = shift;
1022 my @a = split '\|', $c->magic;
1023 my $p = $a[!.--$headercount. q!];
1030 my $select = join(', ', @select);
1033 'table' => 'cust_main',
1034 'select' => $select,
1035 'addl_from' => $addl_from,
1037 'extra_sql' => $extra_sql,
1038 'order_by' => $orderby,
1039 'count_query' => $count_query,
1040 'extra_headers' => \@extra_headers,
1041 'extra_fields' => \@extra_fields,
1043 #warn Data::Dumper::Dumper($sql_query);
1048 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1050 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1051 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1054 Additional options are the same as FS::Record::qsearch
1061 # sensible defaults, then merge in any passed options
1063 'table' => 'cust_main',
1072 my @fuzzy_mod = 'i';
1073 my $conf = new FS::Conf;
1074 my $fuzziness = $conf->config('fuzzy-fuzziness');
1075 push @fuzzy_mod, $fuzziness if $fuzziness;
1077 check_and_rebuild_fuzzyfiles();
1078 foreach my $field ( keys %$fuzzy ) {
1080 my $all = $self->all_X($field);
1081 next unless scalar(@$all);
1084 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1085 next if !keys(%match);
1087 my $in_matches = 'IN (' .
1088 join(',', map { dbh->quote($_) } keys %match) .
1091 my $extra_sql = $fuzopts{extra_sql};
1092 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1093 $extra_sql .= ' AND ';
1095 $extra_sql .= 'WHERE ';
1097 $extra_sql .= "$field $in_matches";
1099 my $addl_from = $fuzopts{addl_from};
1100 if ( $field =~ /^cust_location\./ ) {
1101 $addl_from .= ' JOIN cust_location USING (custnum)';
1102 } elsif ( $field =~ /^contact\./ ) {
1103 $addl_from .= ' JOIN contact USING (custnum)';
1106 push @cust_main, qsearch({
1108 'addl_from' => $addl_from,
1109 'extra_sql' => $extra_sql,
1113 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1115 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1123 =head1 UTILITY SUBROUTINES
1127 =item check_and_rebuild_fuzzyfiles
1131 sub check_and_rebuild_fuzzyfiles {
1132 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1133 rebuild_fuzzyfiles()
1134 if grep { ! -e "$dir/$_" }
1136 my ($field, $table) = reverse split('\.', $_);
1137 $table ||= 'cust_main';
1143 =item rebuild_fuzzyfiles
1147 sub rebuild_fuzzyfiles {
1149 use Fcntl qw(:flock);
1151 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1152 mkdir $dir, 0700 unless -d $dir;
1154 foreach my $fuzzy ( @fuzzyfields ) {
1156 my ($field, $table) = reverse split('\.', $fuzzy);
1157 $table ||= 'cust_main';
1159 open(LOCK,">>$dir/$table.$field")
1160 or die "can't open $dir/$table.$field: $!";
1162 or die "can't lock $dir/$table.$field: $!";
1164 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1165 or die "can't open $dir/$table.$field.tmp: $!";
1167 my $sth = dbh->prepare(
1168 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1170 $sth->execute or die $sth->errstr;
1172 while ( my $row = $sth->fetchrow_arrayref ) {
1173 print CACHE $row->[0]. "\n";
1176 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1178 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1184 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1188 sub append_fuzzyfiles {
1189 #my( $first, $last, $company ) = @_;
1191 check_and_rebuild_fuzzyfiles();
1193 #foreach my $fuzzy (@fuzzyfields) {
1194 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1195 'cust_location.address1',
1198 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1205 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1207 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1211 use Fcntl qw(:flock);
1212 sub append_fuzzyfiles_fuzzyfield {
1213 my( $fuzzyfield, $value ) = @_;
1215 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1218 my ($field, $table) = reverse split('\.', $fuzzyfield);
1219 $table ||= 'cust_main';
1221 return unless length($value);
1223 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1224 or die "can't open $dir/$table.$field: $!";
1225 flock(CACHE,LOCK_EX)
1226 or die "can't lock $dir/$table.$field: $!";
1228 print CACHE "$value\n";
1230 flock(CACHE,LOCK_UN)
1231 or die "can't unlock $dir/$table.$field: $!";
1241 my( $self, $fuzzy ) = @_;
1242 my ($field, $table) = reverse split('\.', $fuzzy);
1243 $table ||= 'cust_main';
1245 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1246 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1247 or die "can't open $dir/$table.$field: $!";
1248 my @array = map { chomp; $_; } <CACHE>;
1259 L<FS::cust_main>, L<FS::Record>