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 = ( 'first', 'last', 'company', 'address1' );
23 install_callback FS::UID sub {
25 #yes, need it for stuff below (prolly should be cached)
30 FS::cust_main::Search - Customer searching
34 use FS::cust_main::Search;
36 FS::cust_main::Search::smart_search(%options);
38 FS::cust_main::Search::email_search(%options);
40 FS::cust_main::Search->search( \%options );
42 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
48 =item smart_search OPTION => VALUE ...
50 Accepts the following options: I<search>, the string to search for. The string
51 will be searched for as a customer number, phone number, name or company name,
52 as an exact, or, in some cases, a substring or fuzzy match (see the source code
53 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
54 skip fuzzy matching when an exact match is found.
56 Any additional options are treated as an additional qualifier on the search
59 Returns a (possibly empty) array of FS::cust_main objects.
66 #here is the agent virtualization
68 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
72 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
73 my $search = delete $options{'search'};
74 ( my $alphanum_search = $search ) =~ s/\W//g;
76 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
78 #false laziness w/Record::ut_phone
79 my $phonen = "$1-$2-$3";
80 $phonen .= " x$4" if $4;
82 push @cust_main, qsearch( {
83 'table' => 'cust_main',
84 'hashref' => { %options },
85 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
87 join(' OR ', map "$_ = '$phonen'",
89 ship_daytime ship_night ship_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\%'",
105 ship_daytime ship_night )
108 " AND $agentnums_sql", #agent virtualization
113 # custnum search (also try agent_custid), with some tweaking options if your
114 # legacy cust "numbers" have letters
118 if ( $search =~ /@/ ) {
122 'table' => 'cust_main_invoice',
123 'hashref' => { 'dest' => $search },
126 } elsif ( $search =~ /^\s*(\d+)\s*$/
127 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
128 && $search =~ /^\s*(\w\w?\d+)\s*$/
130 || ( $conf->config('cust_main-custnum-display_special')
131 # it's not currently possible for special prefixes to contain
132 # digits, so just strip off any alphabetic prefix and match
133 # the rest to custnum
134 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
136 || ( $conf->exists('address1-search' )
137 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
144 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
145 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
146 ? ' AND agent_custid IS NULL ' : '';
147 push @cust_main, qsearch( {
148 'table' => 'cust_main',
149 'hashref' => { 'custnum' => $num, %options },
150 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
154 # for all agents this user can see, if any of them have custnum prefixes
155 # that match the search string, include customers that match the rest
156 # of the custnum and belong to that agent
157 foreach my $agentnum ( $FS::CurrentUser::CurrentUser->agentnums ) {
158 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
160 if ( $p eq substr($num, 0, length($p)) ) {
161 push @cust_main, qsearch( {
162 'table' => 'cust_main',
163 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
164 'agentnum' => $agentnum,
171 push @cust_main, qsearch( {
172 'table' => 'cust_main',
173 'hashref' => { 'agent_custid' => $num, %options },
174 'extra_sql' => " AND $agentnums_sql", #agent virtualization
177 if ( $conf->exists('address1-search') ) {
178 my $len = length($num);
180 foreach my $prefix ( '', 'ship_' ) {
181 push @cust_main, qsearch( {
182 'table' => 'cust_main',
183 'hashref' => { %options, },
185 ( keys(%options) ? ' AND ' : ' WHERE ' ).
186 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
187 " 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 foreach my $prefix ( '', 'ship_' ) {
202 push @cust_main, qsearch( {
203 'table' => 'cust_main',
204 'hashref' => { %options },
206 ( keys(%options) ? ' AND ' : ' WHERE ' ).
208 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
209 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
210 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
216 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
217 # try (ship_){last,company}
221 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
222 # # full strings the browser remembers won't work
223 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
225 use Lingua::EN::NameParse;
226 my $NameParse = new Lingua::EN::NameParse(
231 my($last, $first) = ( '', '' );
232 #maybe disable this too and just rely on NameParse?
233 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
235 ($last, $first) = ( $1, $2 );
237 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
238 } elsif ( ! $NameParse->parse($value) ) {
240 my %name = $NameParse->components;
241 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
242 $last = $name{'surname_1'};
246 if ( $first && $last ) {
248 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
251 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
253 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
254 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
257 push @cust_main, qsearch( {
258 'table' => 'cust_main',
259 'hashref' => \%options,
260 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
263 # or it just be something that was typed in... (try that in a sec)
267 my $q_value = dbh->quote($value);
270 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
271 $sql .= " ( LOWER(last) = $q_value
272 OR LOWER(company) = $q_value
273 OR LOWER(ship_last) = $q_value
274 OR LOWER(ship_company) = $q_value
276 $sql .= " OR LOWER(address1) = $q_value
277 OR LOWER(ship_address1) = $q_value
279 if $conf->exists('address1-search');
282 push @cust_main, qsearch( {
283 'table' => 'cust_main',
284 'hashref' => \%options,
285 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
288 #no exact match, trying substring/fuzzy
289 #always do substring & fuzzy (unless they're explicity config'ed off)
290 #getting complaints searches are not returning enough
291 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
293 #still some false laziness w/search (was search/cust_main.cgi)
298 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
299 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
302 if ( $first && $last ) {
305 { 'first' => { op=>'ILIKE', value=>"%$first%" },
306 'last' => { op=>'ILIKE', value=>"%$last%" },
308 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
309 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
316 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
317 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
321 if ( $conf->exists('address1-search') ) {
323 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
324 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
328 foreach my $hashref ( @hashrefs ) {
330 push @cust_main, qsearch( {
331 'table' => 'cust_main',
332 'hashref' => { %$hashref,
335 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
344 " AND $agentnums_sql", #extra_sql #agent virtualization
347 if ( $first && $last ) {
348 push @cust_main, FS::cust_main::Search->fuzzy_search(
349 { 'last' => $last, #fuzzy hashref
350 'first' => $first }, #
354 foreach my $field ( 'last', 'company' ) {
356 FS::cust_main::Search->fuzzy_search( { $field => $value }, @fuzopts );
358 if ( $conf->exists('address1-search') ) {
360 FS::cust_main::Search->fuzzy_search( { '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
470 listref of start date, end date
474 listref of start date, end date
476 =item spouse_birthdate
478 listref of start date, end date
488 =item current_balance
490 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
503 my ($class, $params) = @_;
510 # initialize these to prevent warnings
517 'paydate_year' => '',
518 'invoice_terms' => '',
524 # explicit custnum(s)
527 if ( $params->{'custnum'} ) {
528 my @custnums = ref($params->{'custnum'}) ?
529 @{ $params->{'custnum'} } :
530 $params->{'custnum'};
532 'cust_main.custnum IN (' .
533 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
534 ')' if scalar(@custnums) > 0;
541 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
543 "cust_main.agentnum = $1";
547 # do the same for user
550 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
552 "cust_main.usernum = $1";
559 #prospect ordered active inactive suspended cancelled
560 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
561 my $method = $params->{'status'}. '_sql';
562 #push @where, $class->$method();
563 push @where, FS::cust_main->$method();
569 if ( $params->{'address'} =~ /\S/ ) {
570 my $address = dbh->quote('%'. lc($params->{'address'}). '%');
571 push @where, '('. join(' OR ',
572 map "LOWER($_) LIKE $address",
573 qw(address1 address2 ship_address1 ship_address2)
581 if ( $params->{'refnum'} =~ /^(\d+)$/ ) {
582 push @where, "refnum = $1";
586 # parse cancelled package checkbox
591 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
592 unless $params->{'cancelled_pkgs'};
595 # parse without census tract checkbox
598 push @where, "(censustract = '' or censustract is null)"
599 if $params->{'no_censustract'};
602 # parse with hardcoded tax location checkbox
605 push @where, "geocode is not null"
606 if $params->{'with_geocode'};
612 foreach my $field (qw( signupdate birthdate spouse_birthdate )) {
614 next unless exists($params->{$field});
616 my($beginning, $ending, $hour) = @{$params->{$field}};
619 "cust_main.$field IS NOT NULL",
620 "cust_main.$field >= $beginning",
621 "cust_main.$field <= $ending";
623 if($field eq 'signupdate' && defined $hour) {
624 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
625 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
627 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
628 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
631 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
635 $orderby ||= "ORDER BY cust_main.$field";
643 if ( $params->{'classnum'} ) {
645 my @classnum = ref( $params->{'classnum'} )
646 ? @{ $params->{'classnum'} }
647 : ( $params->{'classnum'} );
649 @classnum = grep /^(\d*)$/, @classnum;
652 push @where, '( '. join(' OR ', map {
653 $_ ? "cust_main.classnum = $_"
654 : "cust_main.classnum IS NULL"
667 if ( $params->{'payby'} ) {
669 my @payby = ref( $params->{'payby'} )
670 ? @{ $params->{'payby'} }
671 : ( $params->{'payby'} );
673 @payby = grep /^([A-Z]{4})$/, @payby;
675 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
681 # paydate_year / paydate_month
684 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
686 $params->{'paydate_month'} =~ /^(\d\d?)$/
687 or die "paydate_year without paydate_month?";
691 'paydate IS NOT NULL',
693 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
701 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
703 if ( $1 eq 'NULL' ) {
705 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
708 "cust_main.invoice_terms IS NOT NULL",
709 "cust_main.invoice_terms = '$1'";
717 if ( $params->{'current_balance'} ) {
719 #my $balance_sql = $class->balance_sql();
720 my $balance_sql = FS::cust_main->balance_sql();
722 my @current_balance =
723 ref( $params->{'current_balance'} )
724 ? @{ $params->{'current_balance'} }
725 : ( $params->{'current_balance'} );
727 push @where, map { s/current_balance/$balance_sql/; $_ }
736 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
738 "cust_main.custbatch = '$1'";
741 if ( $params->{'tagnum'} ) {
742 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
744 @tagnums = grep /^(\d+)$/, @tagnums;
747 my $tags_where = "0 < (select count(1) from cust_tag where "
748 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
749 . join(',', @tagnums) . "))";
751 push @where, $tags_where;
757 # setup queries, subs, etc. for the search
760 $orderby ||= 'ORDER BY custnum';
762 # here is the agent virtualization
764 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
766 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
770 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
774 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
777 my(@extra_headers) = ();
778 my(@extra_fields) = ();
780 if ($params->{'flattened_pkgs'}) {
783 $addl_from .= ' LEFT JOIN cust_pkg USING ( custnum ) ';
785 if ($dbh->{Driver}->{Name} eq 'Pg') {
787 push @select, "array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
789 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
790 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
791 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
792 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
794 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
795 "omitting package information from report.";
798 my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
800 my $sth = dbh->prepare($header_query) or die dbh->errstr;
801 $sth->execute() or die $sth->errstr;
802 my $headerrow = $sth->fetchrow_arrayref;
803 my $headercount = $headerrow ? $headerrow->[0] : 0;
804 while($headercount) {
805 unshift @extra_headers, "Package ". $headercount;
806 unshift @extra_fields, eval q!sub {my $c = shift;
807 my @a = split '\|', $c->magic;
808 my $p = $a[!.--$headercount. q!];
815 if ( $params->{'with_geocode'} ) {
817 unshift @extra_headers, 'Tax location override', 'Calculated tax location';
818 unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
820 $c->set('geocode', '');
821 $c->geocode('cch'); #XXX only cch right now
823 push @select, 'geocode';
824 push @select, 'zip' unless grep { $_ eq 'zip' } @select;
825 push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
828 my $select = join(', ', @select);
831 'table' => 'cust_main',
833 'addl_from' => $addl_from,
835 'extra_sql' => $extra_sql,
836 'order_by' => $orderby,
837 'count_query' => $count_query,
838 'extra_headers' => \@extra_headers,
839 'extra_fields' => \@extra_fields,
844 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
846 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
847 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
848 specified (the appropriate ship_ field is also searched).
850 Additional options are the same as FS::Record::qsearch
855 my( $self, $fuzzy, $hash, @opt) = @_;
860 check_and_rebuild_fuzzyfiles();
861 foreach my $field ( keys %$fuzzy ) {
863 my $all = $self->all_X($field);
864 next unless scalar(@$all);
867 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
870 foreach ( keys %match ) {
871 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
872 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
875 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
878 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
880 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
888 =head1 UTILITY SUBROUTINES
892 =item check_and_rebuild_fuzzyfiles
896 sub check_and_rebuild_fuzzyfiles {
897 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
898 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
901 =item rebuild_fuzzyfiles
905 sub rebuild_fuzzyfiles {
907 use Fcntl qw(:flock);
909 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
910 mkdir $dir, 0700 unless -d $dir;
912 foreach my $fuzzy ( @fuzzyfields ) {
914 open(LOCK,">>$dir/cust_main.$fuzzy")
915 or die "can't open $dir/cust_main.$fuzzy: $!";
917 or die "can't lock $dir/cust_main.$fuzzy: $!";
919 open (CACHE, '>:encoding(UTF-8)', "$dir/cust_main.$fuzzy.tmp")
920 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
922 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
923 my $sth = dbh->prepare("SELECT $field FROM cust_main".
924 " WHERE $field != '' AND $field IS NOT NULL");
925 $sth->execute or die $sth->errstr;
927 while ( my $row = $sth->fetchrow_arrayref ) {
928 print CACHE $row->[0]. "\n";
933 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
935 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
941 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
945 sub append_fuzzyfiles {
946 #my( $first, $last, $company ) = @_;
948 check_and_rebuild_fuzzyfiles();
950 use Fcntl qw(:flock);
952 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
954 foreach my $field (@fuzzyfields) {
959 open(CACHE, '>>:encoding(UTF-8)', "$dir/cust_main.$field" )
960 or die "can't open $dir/cust_main.$field: $!";
962 or die "can't lock $dir/cust_main.$field: $!";
964 print CACHE "$value\n";
967 or die "can't unlock $dir/cust_main.$field: $!";
981 my( $self, $field ) = @_;
982 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
983 open(CACHE, '<:encoding(UTF-8)', "$dir/cust_main.$field")
984 or die "can't open $dir/cust_main.$field: $!";
985 my @array = map { chomp; $_; } <CACHE>;
996 L<FS::cust_main>, L<FS::Record>