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
67 my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
71 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
72 my $search = delete $options{'search'};
73 ( my $alphanum_search = $search ) =~ s/\W//g;
75 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
77 #false laziness w/Record::ut_phone
78 my $phonen = "$1-$2-$3";
79 $phonen .= " x$4" if $4;
81 push @cust_main, qsearch( {
82 'table' => 'cust_main',
83 'hashref' => { %options },
84 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
86 join(' OR ', map "$_ = '$phonen'",
88 ship_daytime ship_night ship_fax )
91 " AND $agentnums_sql", #agent virtualization
94 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
95 #try looking for matches with extensions unless one was specified
97 push @cust_main, qsearch( {
98 'table' => 'cust_main',
99 'hashref' => { %options },
100 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
102 join(' OR ', map "$_ LIKE '$phonen\%'",
104 ship_daytime ship_night )
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->exists('address1-search' )
130 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
137 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
138 push @cust_main, qsearch( {
139 'table' => 'cust_main',
140 'hashref' => { 'custnum' => $num, %options },
141 'extra_sql' => " AND $agentnums_sql", #agent virtualization
145 #if this becomes agent-virt need to get a list of all prefixes the current
146 #user can see (via their agents)
147 my $prefix = $conf->config('cust_main-custnum-display_prefix');
148 if ( $prefix && $prefix eq substr($num, 0, length($prefix)) ) {
149 push @cust_main, qsearch( {
150 'table' => 'cust_main',
151 'hashref' => { 'custnum' => 0 + substr($num, length($prefix)),
154 'extra_sql' => " AND $agentnums_sql", #agent virtualization
158 push @cust_main, qsearch( {
159 'table' => 'cust_main',
160 'hashref' => { 'agent_custid' => $num, %options },
161 'extra_sql' => " AND $agentnums_sql", #agent virtualization
164 if ( $conf->exists('address1-search') ) {
165 my $len = length($num);
167 foreach my $prefix ( '', 'ship_' ) {
168 push @cust_main, qsearch( {
169 'table' => 'cust_main',
170 'hashref' => { %options, },
172 ( keys(%options) ? ' AND ' : ' WHERE ' ).
173 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
174 " AND $agentnums_sql",
179 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
181 my($company, $last, $first) = ( $1, $2, $3 );
183 # "Company (Last, First)"
184 #this is probably something a browser remembered,
185 #so just do an exact search (but case-insensitive, so USPS standardization
186 #doesn't throw a wrench in the works)
188 foreach my $prefix ( '', 'ship_' ) {
189 push @cust_main, qsearch( {
190 'table' => 'cust_main',
191 'hashref' => { %options },
193 ( keys(%options) ? ' AND ' : ' WHERE ' ).
195 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
196 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
197 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
203 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
204 # try (ship_){last,company}
208 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
209 # # full strings the browser remembers won't work
210 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
212 use Lingua::EN::NameParse;
213 my $NameParse = new Lingua::EN::NameParse(
218 my($last, $first) = ( '', '' );
219 #maybe disable this too and just rely on NameParse?
220 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
222 ($last, $first) = ( $1, $2 );
224 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
225 } elsif ( ! $NameParse->parse($value) ) {
227 my %name = $NameParse->components;
228 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
229 $last = $name{'surname_1'};
233 if ( $first && $last ) {
235 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
238 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
240 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
241 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
244 push @cust_main, qsearch( {
245 'table' => 'cust_main',
246 'hashref' => \%options,
247 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
250 # or it just be something that was typed in... (try that in a sec)
254 my $q_value = dbh->quote($value);
257 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
258 $sql .= " ( LOWER(last) = $q_value
259 OR LOWER(company) = $q_value
260 OR LOWER(ship_last) = $q_value
261 OR LOWER(ship_company) = $q_value
263 $sql .= " OR LOWER(address1) = $q_value
264 OR LOWER(ship_address1) = $q_value
266 if $conf->exists('address1-search');
269 push @cust_main, qsearch( {
270 'table' => 'cust_main',
271 'hashref' => \%options,
272 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
275 #no exact match, trying substring/fuzzy
276 #always do substring & fuzzy (unless they're explicity config'ed off)
277 #getting complaints searches are not returning enough
278 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
280 #still some false laziness w/search (was search/cust_main.cgi)
285 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
286 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
289 if ( $first && $last ) {
292 { 'first' => { op=>'ILIKE', value=>"%$first%" },
293 'last' => { op=>'ILIKE', value=>"%$last%" },
295 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
296 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
303 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
304 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
308 if ( $conf->exists('address1-search') ) {
310 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
311 { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
315 foreach my $hashref ( @hashrefs ) {
317 push @cust_main, qsearch( {
318 'table' => 'cust_main',
319 'hashref' => { %$hashref,
322 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
331 " AND $agentnums_sql", #extra_sql #agent virtualization
334 if ( $first && $last ) {
335 push @cust_main, FS::cust_main::Search->fuzzy_search(
336 { 'last' => $last, #fuzzy hashref
337 'first' => $first }, #
341 foreach my $field ( 'last', 'company' ) {
343 FS::cust_main::Search->fuzzy_search( { $field => $value }, @fuzopts );
345 if ( $conf->exists('address1-search') ) {
347 FS::cust_main::Search->fuzzy_search( { 'address1' => $value }, @fuzopts );
354 #eliminate duplicates
356 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
364 Accepts the following options: I<email>, the email address to search for. The
365 email address will be searched for as an email invoice destination and as an
368 #Any additional options are treated as an additional qualifier on the search
371 Returns a (possibly empty) array of FS::cust_main objects (but usually just
381 my $email = delete $options{'email'};
383 #we're only being used by RT at the moment... no agent virtualization yet
384 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
388 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
390 my ( $user, $domain ) = ( $1, $2 );
392 warn "$me smart_search: searching for $user in domain $domain"
398 'table' => 'cust_main_invoice',
399 'hashref' => { 'dest' => $email },
406 map $_->cust_svc->cust_pkg,
408 'table' => 'svc_acct',
409 'hashref' => { 'username' => $user, },
411 'AND ( SELECT domain FROM svc_domain
412 WHERE svc_acct.domsvc = svc_domain.svcnum
413 ) = '. dbh->quote($domain),
419 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
421 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
438 Returns a qsearch hash expression to search for parameters specified in
439 HASHREF. Valid parameters are
455 listref of start date, end date
465 =item current_balance
467 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
480 my ($class, $params) = @_;
487 # initialize these to prevent warnings
494 'paydate_year' => '',
495 'invoice_terms' => '',
501 # explicit custnum(s)
504 if ( $params->{'custnum'} ) {
505 my @custnums = ref($params->{'custnum'}) ?
506 @{ $params->{'custnum'} } :
507 $params->{'custnum'};
509 'cust_main.custnum IN (' .
510 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
511 ')' if scalar(@custnums) > 0;
518 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
520 "cust_main.agentnum = $1";
524 # do the same for user
527 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
529 "cust_main.usernum = $1";
536 #prospect ordered active inactive suspended cancelled
537 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
538 my $method = $params->{'status'}. '_sql';
539 #push @where, $class->$method();
540 push @where, FS::cust_main->$method();
546 if ( $params->{'address'} =~ /\S/ ) {
547 my $address = dbh->quote('%'. lc($params->{'address'}). '%');
548 push @where, '('. join(' OR ',
549 map "LOWER($_) LIKE $address",
550 qw(address1 address2 ship_address1 ship_address2)
556 # parse cancelled package checkbox
561 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
562 unless $params->{'cancelled_pkgs'};
565 # parse without census tract checkbox
568 push @where, "(censustract = '' or censustract is null)"
569 if $params->{'no_censustract'};
572 # parse with hardcoded tax location checkbox
575 push @where, "geocode is not null"
576 if $params->{'with_geocode'};
582 foreach my $field (qw( signupdate )) {
584 next unless exists($params->{$field});
586 my($beginning, $ending, $hour) = @{$params->{$field}};
589 "cust_main.$field IS NOT NULL",
590 "cust_main.$field >= $beginning",
591 "cust_main.$field <= $ending";
594 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
595 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
597 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
598 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
601 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
605 $orderby ||= "ORDER BY cust_main.$field";
613 if ( $params->{'classnum'} ) {
615 my @classnum = ref( $params->{'classnum'} )
616 ? @{ $params->{'classnum'} }
617 : ( $params->{'classnum'} );
619 @classnum = grep /^(\d*)$/, @classnum;
622 push @where, '( '. join(' OR ', map {
623 $_ ? "cust_main.classnum = $_"
624 : "cust_main.classnum IS NULL"
637 if ( $params->{'payby'} ) {
639 my @payby = ref( $params->{'payby'} )
640 ? @{ $params->{'payby'} }
641 : ( $params->{'payby'} );
643 @payby = grep /^([A-Z]{4})$/, @payby;
645 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
651 # paydate_year / paydate_month
654 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
656 $params->{'paydate_month'} =~ /^(\d\d?)$/
657 or die "paydate_year without paydate_month?";
661 'paydate IS NOT NULL',
663 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
671 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
673 if ( $1 eq 'NULL' ) {
675 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
678 "cust_main.invoice_terms IS NOT NULL",
679 "cust_main.invoice_terms = '$1'";
687 if ( $params->{'current_balance'} ) {
689 #my $balance_sql = $class->balance_sql();
690 my $balance_sql = FS::cust_main->balance_sql();
692 my @current_balance =
693 ref( $params->{'current_balance'} )
694 ? @{ $params->{'current_balance'} }
695 : ( $params->{'current_balance'} );
697 push @where, map { s/current_balance/$balance_sql/; $_ }
706 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
708 "cust_main.custbatch = '$1'";
711 if ( $params->{'tagnum'} ) {
712 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
714 @tagnums = grep /^(\d+)$/, @tagnums;
717 my $tags_where = "0 < (select count(1) from cust_tag where "
718 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
719 . join(',', @tagnums) . "))";
721 push @where, $tags_where;
727 # setup queries, subs, etc. for the search
730 $orderby ||= 'ORDER BY custnum';
732 # here is the agent virtualization
733 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
735 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
737 my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum ) ';
739 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
743 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
746 my(@extra_headers) = ();
747 my(@extra_fields) = ();
749 if ($params->{'flattened_pkgs'}) {
751 if ($dbh->{Driver}->{Name} eq 'Pg') {
753 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";
755 }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
756 push @select, "GROUP_CONCAT(pkg SEPARATOR '|') as magic";
757 $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
759 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
760 "omitting packing information from report.";
763 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";
765 my $sth = dbh->prepare($header_query) or die dbh->errstr;
766 $sth->execute() or die $sth->errstr;
767 my $headerrow = $sth->fetchrow_arrayref;
768 my $headercount = $headerrow ? $headerrow->[0] : 0;
769 while($headercount) {
770 unshift @extra_headers, "Package ". $headercount;
771 unshift @extra_fields, eval q!sub {my $c = shift;
772 my @a = split '\|', $c->magic;
773 my $p = $a[!.--$headercount. q!];
780 if ( $params->{'with_geocode'} ) {
782 unshift @extra_headers, 'Tax location override', 'Calculated tax location';
783 unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
785 $c->set('geocode', '');
786 $c->geocode('cch'); #XXX only cch right now
788 push @select, 'geocode';
789 push @select, 'zip' unless grep { $_ eq 'zip' } @select;
790 push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
793 my $select = join(', ', @select);
796 'table' => 'cust_main',
799 'extra_sql' => $extra_sql,
800 'order_by' => $orderby,
801 'count_query' => $count_query,
802 'extra_headers' => \@extra_headers,
803 'extra_fields' => \@extra_fields,
808 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
810 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
811 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
812 specified (the appropriate ship_ field is also searched).
814 Additional options are the same as FS::Record::qsearch
819 my( $self, $fuzzy, $hash, @opt) = @_;
824 check_and_rebuild_fuzzyfiles();
825 foreach my $field ( keys %$fuzzy ) {
827 my $all = $self->all_X($field);
828 next unless scalar(@$all);
831 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
834 foreach ( keys %match ) {
835 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
836 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
839 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
842 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
844 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
852 =head1 UTILITY SUBROUTINES
856 =item check_and_rebuild_fuzzyfiles
860 sub check_and_rebuild_fuzzyfiles {
861 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
862 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
865 =item rebuild_fuzzyfiles
869 sub rebuild_fuzzyfiles {
871 use Fcntl qw(:flock);
873 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
874 mkdir $dir, 0700 unless -d $dir;
876 foreach my $fuzzy ( @fuzzyfields ) {
878 open(LOCK,">>$dir/cust_main.$fuzzy")
879 or die "can't open $dir/cust_main.$fuzzy: $!";
881 or die "can't lock $dir/cust_main.$fuzzy: $!";
883 open (CACHE,">$dir/cust_main.$fuzzy.tmp")
884 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
886 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
887 my $sth = dbh->prepare("SELECT $field FROM cust_main".
888 " WHERE $field != '' AND $field IS NOT NULL");
889 $sth->execute or die $sth->errstr;
891 while ( my $row = $sth->fetchrow_arrayref ) {
892 print CACHE $row->[0]. "\n";
897 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
899 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
905 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
909 sub append_fuzzyfiles {
910 #my( $first, $last, $company ) = @_;
912 check_and_rebuild_fuzzyfiles();
914 use Fcntl qw(:flock);
916 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
918 foreach my $field (@fuzzyfields) {
923 open(CACHE,">>$dir/cust_main.$field")
924 or die "can't open $dir/cust_main.$field: $!";
926 or die "can't lock $dir/cust_main.$field: $!";
928 print CACHE "$value\n";
931 or die "can't unlock $dir/cust_main.$field: $!";
945 my( $self, $field ) = @_;
946 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
947 open(CACHE,"<$dir/cust_main.$field")
948 or die "can't open $dir/cust_main.$field: $!";
949 my @array = map { chomp; $_; } <CACHE>;
960 L<FS::cust_main>, L<FS::Record>