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->exists('address1-search' )
131 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
138 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
139 push @cust_main, qsearch( {
140 'table' => 'cust_main',
141 'hashref' => { 'custnum' => $num, %options },
142 'extra_sql' => " AND $agentnums_sql", #agent virtualization
146 #if this becomes agent-virt need to get a list of all prefixes the current
147 #user can see (via their agents)
148 my $prefix = $conf->config('cust_main-custnum-display_prefix');
149 if ( $prefix && $prefix eq substr($num, 0, length($prefix)) ) {
150 push @cust_main, qsearch( {
151 'table' => 'cust_main',
152 'hashref' => { 'custnum' => 0 + substr($num, length($prefix)),
155 'extra_sql' => " AND $agentnums_sql", #agent virtualization
159 push @cust_main, qsearch( {
160 'table' => 'cust_main',
161 'hashref' => { 'agent_custid' => $num, %options },
162 'extra_sql' => " AND $agentnums_sql", #agent virtualization
165 if ( $conf->exists('address1-search') ) {
166 my $len = length($num);
168 foreach my $prefix ( '', 'ship_' ) {
169 push @cust_main, qsearch( {
170 'table' => 'cust_main',
171 'hashref' => { %options, },
173 ( keys(%options) ? ' AND ' : ' WHERE ' ).
174 " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
175 " AND $agentnums_sql",
180 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
182 my($company, $last, $first) = ( $1, $2, $3 );
184 # "Company (Last, First)"
185 #this is probably something a browser remembered,
186 #so just do an exact search (but case-insensitive, so USPS standardization
187 #doesn't throw a wrench in the works)
189 foreach my $prefix ( '', 'ship_' ) {
190 push @cust_main, qsearch( {
191 'table' => 'cust_main',
192 'hashref' => { %options },
194 ( keys(%options) ? ' AND ' : ' WHERE ' ).
196 " LOWER(${prefix}first) = ". dbh->quote(lc($first)),
197 " LOWER(${prefix}last) = ". dbh->quote(lc($last)),
198 " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
204 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
205 # try (ship_){last,company}
209 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
210 # # full strings the browser remembers won't work
211 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
213 use Lingua::EN::NameParse;
214 my $NameParse = new Lingua::EN::NameParse(
219 my($last, $first) = ( '', '' );
220 #maybe disable this too and just rely on NameParse?
221 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
223 ($last, $first) = ( $1, $2 );
225 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
226 } elsif ( ! $NameParse->parse($value) ) {
228 my %name = $NameParse->components;
229 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
230 $last = $name{'surname_1'};
234 if ( $first && $last ) {
236 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
239 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
241 ( ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
242 OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
245 push @cust_main, qsearch( {
246 'table' => 'cust_main',
247 'hashref' => \%options,
248 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
251 # or it just be something that was typed in... (try that in a sec)
255 my $q_value = dbh->quote($value);
258 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
259 $sql .= " ( LOWER(last) = $q_value
260 OR LOWER(company) = $q_value
261 OR LOWER(ship_last) = $q_value
262 OR LOWER(ship_company) = $q_value
264 $sql .= " OR LOWER(address1) = $q_value
265 OR LOWER(ship_address1) = $q_value
267 if $conf->exists('address1-search');
270 push @cust_main, qsearch( {
271 'table' => 'cust_main',
272 'hashref' => \%options,
273 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
276 #no exact match, trying substring/fuzzy
277 #always do substring & fuzzy (unless they're explicity config'ed off)
278 #getting complaints searches are not returning enough
279 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
281 #still some false laziness w/search (was search/cust_main.cgi)
286 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
287 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
290 if ( $first && $last ) {
293 { 'first' => { op=>'ILIKE', value=>"%$first%" },
294 'last' => { op=>'ILIKE', value=>"%$last%" },
296 { 'ship_first' => { op=>'ILIKE', value=>"%$first%" },
297 'ship_last' => { op=>'ILIKE', value=>"%$last%" },
304 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
305 { 'ship_last' => { op=>'ILIKE', value=>"%$value%" }, },
309 if ( $conf->exists('address1-search') ) {
311 { 'address1' => { op=>'ILIKE', value=>"%$value%" }, },
312 { 'ship_address1' => { 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
332 " AND $agentnums_sql", #extra_sql #agent virtualization
335 if ( $first && $last ) {
336 push @cust_main, FS::cust_main::Search->fuzzy_search(
337 { 'last' => $last, #fuzzy hashref
338 'first' => $first }, #
342 foreach my $field ( 'last', 'company' ) {
344 FS::cust_main::Search->fuzzy_search( { $field => $value }, @fuzopts );
346 if ( $conf->exists('address1-search') ) {
348 FS::cust_main::Search->fuzzy_search( { 'address1' => $value }, @fuzopts );
355 #eliminate duplicates
357 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
365 Accepts the following options: I<email>, the email address to search for. The
366 email address will be searched for as an email invoice destination and as an
369 #Any additional options are treated as an additional qualifier on the search
372 Returns a (possibly empty) array of FS::cust_main objects (but usually just
382 my $email = delete $options{'email'};
384 #we're only being used by RT at the moment... no agent virtualization yet
385 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
389 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
391 my ( $user, $domain ) = ( $1, $2 );
393 warn "$me smart_search: searching for $user in domain $domain"
399 'table' => 'cust_main_invoice',
400 'hashref' => { 'dest' => $email },
407 map $_->cust_svc->cust_pkg,
409 'table' => 'svc_acct',
410 'hashref' => { 'username' => $user, },
412 'AND ( SELECT domain FROM svc_domain
413 WHERE svc_acct.domsvc = svc_domain.svcnum
414 ) = '. dbh->quote($domain),
420 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
422 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
439 Returns a qsearch hash expression to search for parameters specified in
440 HASHREF. Valid parameters are
456 listref of start date, end date
466 =item current_balance
468 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
481 my ($class, $params) = @_;
488 # initialize these to prevent warnings
495 'paydate_year' => '',
496 'invoice_terms' => '',
502 # explicit custnum(s)
505 if ( $params->{'custnum'} ) {
506 my @custnums = ref($params->{'custnum'}) ?
507 @{ $params->{'custnum'} } :
508 $params->{'custnum'};
510 'cust_main.custnum IN (' .
511 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
512 ')' if scalar(@custnums) > 0;
519 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
521 "cust_main.agentnum = $1";
525 # do the same for user
528 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
530 "cust_main.usernum = $1";
537 #prospect ordered active inactive suspended cancelled
538 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
539 my $method = $params->{'status'}. '_sql';
540 #push @where, $class->$method();
541 push @where, FS::cust_main->$method();
547 if ( $params->{'address'} =~ /\S/ ) {
548 my $address = dbh->quote('%'. lc($params->{'address'}). '%');
549 push @where, '('. join(' OR ',
550 map "LOWER($_) LIKE $address",
551 qw(address1 address2 ship_address1 ship_address2)
557 # parse cancelled package checkbox
562 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
563 unless $params->{'cancelled_pkgs'};
566 # parse without census tract checkbox
569 push @where, "(censustract = '' or censustract is null)"
570 if $params->{'no_censustract'};
573 # parse with hardcoded tax location checkbox
576 push @where, "geocode is not null"
577 if $params->{'with_geocode'};
583 foreach my $field (qw( signupdate )) {
585 next unless exists($params->{$field});
587 my($beginning, $ending, $hour) = @{$params->{$field}};
590 "cust_main.$field IS NOT NULL",
591 "cust_main.$field >= $beginning",
592 "cust_main.$field <= $ending";
595 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
596 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
598 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
599 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
602 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
606 $orderby ||= "ORDER BY cust_main.$field";
614 if ( $params->{'classnum'} ) {
616 my @classnum = ref( $params->{'classnum'} )
617 ? @{ $params->{'classnum'} }
618 : ( $params->{'classnum'} );
620 @classnum = grep /^(\d*)$/, @classnum;
623 push @where, '( '. join(' OR ', map {
624 $_ ? "cust_main.classnum = $_"
625 : "cust_main.classnum IS NULL"
638 if ( $params->{'payby'} ) {
640 my @payby = ref( $params->{'payby'} )
641 ? @{ $params->{'payby'} }
642 : ( $params->{'payby'} );
644 @payby = grep /^([A-Z]{4})$/, @payby;
646 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
652 # paydate_year / paydate_month
655 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
657 $params->{'paydate_month'} =~ /^(\d\d?)$/
658 or die "paydate_year without paydate_month?";
662 'paydate IS NOT NULL',
664 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
672 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
674 if ( $1 eq 'NULL' ) {
676 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
679 "cust_main.invoice_terms IS NOT NULL",
680 "cust_main.invoice_terms = '$1'";
688 if ( $params->{'current_balance'} ) {
690 #my $balance_sql = $class->balance_sql();
691 my $balance_sql = FS::cust_main->balance_sql();
693 my @current_balance =
694 ref( $params->{'current_balance'} )
695 ? @{ $params->{'current_balance'} }
696 : ( $params->{'current_balance'} );
698 push @where, map { s/current_balance/$balance_sql/; $_ }
707 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
709 "cust_main.custbatch = '$1'";
712 if ( $params->{'tagnum'} ) {
713 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
715 @tagnums = grep /^(\d+)$/, @tagnums;
718 my $tags_where = "0 < (select count(1) from cust_tag where "
719 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
720 . join(',', @tagnums) . "))";
722 push @where, $tags_where;
728 # setup queries, subs, etc. for the search
731 $orderby ||= 'ORDER BY custnum';
733 # here is the agent virtualization
735 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
737 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
741 my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
745 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
748 my(@extra_headers) = ();
749 my(@extra_fields) = ();
751 if ($params->{'flattened_pkgs'}) {
755 if ($dbh->{Driver}->{Name} eq 'Pg') {
757 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";
759 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
760 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
761 $addl_from .= ' LEFT JOIN cust_pkg USING ( custnum ) '; #Pg too w/flatpkg?
762 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
763 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
765 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
766 "omitting packing information from report.";
769 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";
771 my $sth = dbh->prepare($header_query) or die dbh->errstr;
772 $sth->execute() or die $sth->errstr;
773 my $headerrow = $sth->fetchrow_arrayref;
774 my $headercount = $headerrow ? $headerrow->[0] : 0;
775 while($headercount) {
776 unshift @extra_headers, "Package ". $headercount;
777 unshift @extra_fields, eval q!sub {my $c = shift;
778 my @a = split '\|', $c->magic;
779 my $p = $a[!.--$headercount. q!];
786 if ( $params->{'with_geocode'} ) {
788 unshift @extra_headers, 'Tax location override', 'Calculated tax location';
789 unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
791 $c->set('geocode', '');
792 $c->geocode('cch'); #XXX only cch right now
794 push @select, 'geocode';
795 push @select, 'zip' unless grep { $_ eq 'zip' } @select;
796 push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
799 my $select = join(', ', @select);
802 'table' => 'cust_main',
804 'addl_from' => $addl_from,
806 'extra_sql' => $extra_sql,
807 'order_by' => $orderby,
808 'count_query' => $count_query,
809 'extra_headers' => \@extra_headers,
810 'extra_fields' => \@extra_fields,
815 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
817 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
818 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
819 specified (the appropriate ship_ field is also searched).
821 Additional options are the same as FS::Record::qsearch
826 my( $self, $fuzzy, $hash, @opt) = @_;
831 check_and_rebuild_fuzzyfiles();
832 foreach my $field ( keys %$fuzzy ) {
834 my $all = $self->all_X($field);
835 next unless scalar(@$all);
838 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
841 foreach ( keys %match ) {
842 push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
843 push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
846 push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
849 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
851 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
859 =head1 UTILITY SUBROUTINES
863 =item check_and_rebuild_fuzzyfiles
867 sub check_and_rebuild_fuzzyfiles {
868 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
869 rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
872 =item rebuild_fuzzyfiles
876 sub rebuild_fuzzyfiles {
878 use Fcntl qw(:flock);
880 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
881 mkdir $dir, 0700 unless -d $dir;
883 foreach my $fuzzy ( @fuzzyfields ) {
885 open(LOCK,">>$dir/cust_main.$fuzzy")
886 or die "can't open $dir/cust_main.$fuzzy: $!";
888 or die "can't lock $dir/cust_main.$fuzzy: $!";
890 open (CACHE, '>:encoding(UTF-8)', "$dir/cust_main.$fuzzy.tmp")
891 or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
893 foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
894 my $sth = dbh->prepare("SELECT $field FROM cust_main".
895 " WHERE $field != '' AND $field IS NOT NULL");
896 $sth->execute or die $sth->errstr;
898 while ( my $row = $sth->fetchrow_arrayref ) {
899 print CACHE $row->[0]. "\n";
904 close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
906 rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
912 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
916 sub append_fuzzyfiles {
917 #my( $first, $last, $company ) = @_;
919 check_and_rebuild_fuzzyfiles();
921 use Fcntl qw(:flock);
923 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
925 foreach my $field (@fuzzyfields) {
930 open(CACHE, '>>:encoding(UTF-8)', "$dir/cust_main.$field" )
931 or die "can't open $dir/cust_main.$field: $!";
933 or die "can't lock $dir/cust_main.$field: $!";
935 print CACHE "$value\n";
938 or die "can't unlock $dir/cust_main.$field: $!";
952 my( $self, $field ) = @_;
953 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
954 open(CACHE, '<:encoding(UTF-8)', "$dir/cust_main.$field")
955 or die "can't open $dir/cust_main.$field: $!";
956 my @array = map { chomp; $_; } <CACHE>;
967 L<FS::cust_main>, L<FS::Record>