1 package FS::cust_main::Search;
5 use base qw( Exporter );
6 use vars qw( @EXPORT_OK $DEBUG $me $conf @fuzzyfields );
7 use String::Approx qw(amatch);
9 use FS::Record qw( qsearch );
11 use FS::cust_main_invoice;
13 use FS::payinfo_Mixin;
15 @EXPORT_OK = qw( smart_search );
17 # 1 is mostly method/subroutine entry and options
18 # 2 traces progress of some operations
19 # 3 is even more information including possibly sensitive data
21 $me = '[FS::cust_main::Search]';
24 'cust_main.first', 'cust_main.last', 'cust_main.company',
25 'cust_main.ship_company', # if you're using it
26 'cust_location.address1',
27 'contact.first', 'contact.last',
30 install_callback FS::UID sub {
32 #yes, need it for stuff below (prolly should be cached)
37 FS::cust_main::Search - Customer searching
41 use FS::cust_main::Search;
43 FS::cust_main::Search::smart_search(%options);
45 FS::cust_main::Search::email_search(%options);
47 FS::cust_main::Search->search( \%options );
49 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
55 =item smart_search OPTION => VALUE ...
57 Accepts the following options: I<search>, the string to search for. The string
58 will be searched for as a customer number, phone number, name or company name,
59 address (if address1-search is on), invoicing email address, or credit card
62 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
63 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
65 skip fuzzy matching when an exact match is found.
67 Any additional options are treated as an additional qualifier on the search
70 Returns a (possibly empty) array of FS::cust_main objects.
77 #here is the agent virtualization
79 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
80 my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
84 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
85 my $search = delete $options{'search'};
86 ( my $alphanum_search = $search ) =~ s/\W//g;
88 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
90 #false laziness w/Record::ut_phone
91 my $phonen = "$1-$2-$3";
92 $phonen .= " x$4" if $4;
94 my $phonenum = "$1$2$3";
97 #cust_main phone numbers and contact phone number
98 push @cust_main, qsearch( {
99 'table' => 'cust_main',
100 'hashref' => { %options },
101 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
103 join(' OR ', map "$_ = '$phonen'",
104 qw( daytime night mobile fax )
106 " OR phonenum = '$phonenum' ".
108 " AND $agentnums_sql", #agent virtualization
109 'addl_from' => ' left join cust_contact using (custnum) left join contact_phone using (contactnum) ',
112 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
113 #try looking for matches with extensions unless one was specified
115 push @cust_main, qsearch( {
116 'table' => 'cust_main',
117 'hashref' => { %options },
118 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
120 join(' OR ', map "$_ LIKE '$phonen\%'",
124 " AND $agentnums_sql", #agent virtualization
132 if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
134 push @cust_main, qsearch( {
135 'table' => 'cust_main',
136 'hashref' => { %options },
137 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
139 join(' OR ', map "$_ = '$search'",
140 qw( dest emailaddress )
143 " AND $agentnums_sql", #agent virtualization
144 'addl_from' => ' left join cust_main_invoice using (custnum) left join cust_contact using (custnum) left join contact_email using (contactnum) ',
147 # custnum search (also try agent_custid), with some tweaking options if your
148 # legacy cust "numbers" have letters
149 } elsif ( $search =~ /^\s*(\d+)\s*$/
150 or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
151 && $search =~ /^\s*(\w\w?\d+)\s*$/
153 or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
154 && $search =~ /^\s*(\d+-\w)\s*$/
156 or ( $conf->config('cust_main-custnum-display_special')
157 # it's not currently possible for special prefixes to contain
158 # digits, so just strip off any alphabetic prefix and match
159 # the rest to custnum
160 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
162 or ( $conf->exists('address1-search' )
163 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
170 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
171 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
172 ? ' AND agent_custid IS NULL ' : '';
173 push @cust_main, qsearch( {
174 'table' => 'cust_main',
175 'hashref' => { 'custnum' => $num, %options },
176 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
180 # for all agents this user can see, if any of them have custnum prefixes
181 # that match the search string, include customers that match the rest
182 # of the custnum and belong to that agent
183 foreach my $agentnum ( keys %$agentnums_href ) {
184 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
186 if ( $p eq substr($num, 0, length($p)) ) {
187 push @cust_main, qsearch( {
188 'table' => 'cust_main',
189 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
190 'agentnum' => $agentnum,
197 push @cust_main, qsearch( {
198 'table' => 'cust_main',
199 'hashref' => { 'agent_custid' => $num, %options },
200 'extra_sql' => " AND $agentnums_sql", #agent virtualization
203 if ( $conf->exists('address1-search') ) {
204 my $len = length($num);
206 # probably the Right Thing: return customers that have any associated
207 # locations matching the string, not just bill/ship location
208 push @cust_main, qsearch( {
209 'table' => 'cust_main',
210 'addl_from' => ' JOIN cust_location USING (custnum) ',
211 'hashref' => { %options, },
213 ( keys(%options) ? ' AND ' : ' WHERE ' ).
214 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
215 " AND $agentnums_sql",
219 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
221 my($company, $last, $first) = ( $1, $2, $3 );
223 # "Company (Last, First)"
224 #this is probably something a browser remembered,
225 #so just do an exact search (but case-insensitive, so USPS standardization
226 #doesn't throw a wrench in the works)
228 push @cust_main, qsearch( {
229 'table' => 'cust_main',
230 'hashref' => { %options },
232 ( keys(%options) ? ' AND ' : ' WHERE ' ).
234 " LOWER(first) = ". dbh->quote(lc($first)),
235 " LOWER(last) = ". dbh->quote(lc($last)),
236 " LOWER(company) = ". dbh->quote(lc($company)),
242 # probably not necessary for the "something a browser remembered" case
244 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
245 # try {first,last,company}
249 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
250 # # full strings the browser remembers won't work
251 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
253 use Lingua::EN::NameParse;
254 my $NameParse = new Lingua::EN::NameParse(
259 my($last, $first) = ( '', '' );
260 #maybe disable this too and just rely on NameParse?
261 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
263 ($last, $first) = ( $1, $2 );
265 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
266 } elsif ( ! $NameParse->parse($value) ) {
268 my %name = $NameParse->components;
269 $first = lc($name{'given_name_1'}) || $name{'initials_1'}; #wtf NameParse, Ed?
270 $last = lc($name{'surname_1'});
274 if ( $first && $last ) {
276 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
279 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
280 $sql .= "( (LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first)
281 OR (LOWER(contact.last) = $q_last AND LOWER(contact.first) = $q_first) )";
283 #cust_main and contacts
284 push @cust_main, qsearch( {
285 'table' => 'cust_main',
286 'select' => 'cust_main.*, cust_contact.*, contact.contactnum, contact.last as contact_last, contact.first as contact_first, contact.title',
287 'hashref' => { %options },
288 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
289 'addl_from' => ' left join cust_contact on cust_main.custnum = cust_contact.custnum left join contact using (contactnum) ',
292 # or it just be something that was typed in... (try that in a sec)
296 my $q_value = dbh->quote($value);
299 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
300 $sql .= " ( LOWER(cust_main.first) = $q_value
301 OR LOWER(cust_main.last) = $q_value
302 OR LOWER(cust_main.company) = $q_value
303 OR LOWER(cust_main.ship_company) = $q_value
304 OR LOWER(contact.first) = $q_value
305 OR LOWER(contact.last) = $q_value
308 #address1 (yes, it's a kludge)
309 $sql .= " OR EXISTS (
310 SELECT 1 FROM cust_location
311 WHERE LOWER(cust_location.address1) = $q_value
312 AND cust_location.custnum = cust_main.custnum
314 if $conf->exists('address1-search');
316 push @cust_main, qsearch( {
317 'table' => 'cust_main',
318 'select' => 'cust_main.*, cust_contact.*, contact.contactnum, contact.last as contact_last, contact.first as contact_first, contact.title',
319 'hashref' => { %options },
320 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
321 'addl_from' => 'left join cust_contact on cust_main.custnum = cust_contact.custnum left join contact using (contactnum) ',
324 #no exact match, trying substring/fuzzy
325 #always do substring & fuzzy (unless they're explicity config'ed off)
326 #getting complaints searches are not returning enough
327 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
329 #still some false laziness w/search (was search/cust_main.cgi)
332 $FS::CurrentUser::CurrentUser->access_right('List all customers')
337 my @company_hashrefs = ();
338 if ( length($value) >= $min_len ) {
339 @company_hashrefs = (
340 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
341 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
346 if ( $first && $last ) {
349 { 'first' => { op=>'ILIKE', value=>"%$first%" },
350 'last' => { op=>'ILIKE', value=>"%$last%" },
354 } elsif ( length($value) >= $min_len ) {
357 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
358 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
363 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
365 push @cust_main, qsearch( {
366 'table' => 'cust_main',
367 'hashref' => { %$hashref,
370 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
375 if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
377 push @cust_main, qsearch( {
378 table => 'cust_main',
379 addl_from => 'JOIN cust_location USING (custnum)',
380 extra_sql => 'WHERE '.
381 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
382 " AND $agentnums_sql", #agent virtualizaiton
389 foreach my $hashref ( @hashrefs ) {
392 grep $agentnums_href->{$_->agentnum}, #agent virt
393 grep $_, #skip contacts that don't have cust_main records
396 'table' => 'contact',
397 'hashref' => { %$hashref,
400 #'extra_sql' => " AND $agentnums_sql", #agent virt
407 'hashref' => \%options,
409 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
412 if ( $first && $last ) {
413 push @cust_main, FS::cust_main::Search->fuzzy_search(
414 { 'last' => $last, #fuzzy hashref
415 'first' => $first }, #
418 push @cust_main, FS::cust_main::Search->fuzzy_search(
419 { 'contact.last' => $last, #fuzzy hashref
420 'contact.first' => $first }, #
425 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
426 push @cust_main, FS::cust_main::Search->fuzzy_search(
427 { $field => $value },
431 foreach my $field ( 'first', 'last' ) {
432 push @cust_main, FS::cust_main::Search->fuzzy_search(
433 { "contact.$field" => $value },
437 if ( $conf->exists('address1-search') ) {
439 FS::cust_main::Search->fuzzy_search(
440 { 'cust_location.address1' => $value },
449 ( my $nospace_search = $search ) =~ s/\s//g;
450 ( my $card_search = $nospace_search ) =~ s/\-//g;
451 $card_search =~ s/[x\*\.\_]/x/gi;
453 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
455 ( my $like_search = $card_search ) =~ s/x/_/g;
456 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
458 push @cust_main, qsearch({
459 'table' => 'cust_main',
460 'addl_from' => ' JOIN cust_payby USING (custnum)',
462 'extra_sql' => " WHERE ( cust_payby.payinfo LIKE '$like_search'
463 OR cust_payby.paymask = '$mask_search'
465 " AND cust_payby.payby IN ('CARD','DCRD') ".
466 " AND $agentnums_sql", #agent virtulization
472 #eliminate duplicates
474 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
482 Accepts the following options: I<email>, the email address to search for. The
483 email address will be searched for as an email invoice destination and as an
486 #Any additional options are treated as an additional qualifier on the search
489 Returns a (possibly empty) array of FS::cust_main objects (but usually just
497 my $email = delete $options{'email'};
499 #no agent virtualization yet
500 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
504 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
506 my ( $user, $domain ) = ( $1, $2 );
508 warn "$me smart_search: searching for $user in domain $domain"
512 map { $_->cust_main }
513 map { $_->cust_contact }
516 'table' => 'contact_email',
517 'hashref' => { 'emailaddress' => $email },
524 map $_->cust_svc->cust_pkg,
526 'table' => 'svc_acct',
527 'hashref' => { 'username' => $user, },
529 'AND ( SELECT domain FROM svc_domain
530 WHERE svc_acct.domsvc = svc_domain.svcnum
531 ) = '. dbh->quote($domain),
537 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
539 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
556 Returns a qsearch hash expression to search for parameters specified in
557 HASHREF. Valid parameters are
577 listref of start date, end date
581 listref of start date, end date
583 =item spouse_birthdate
585 listref of start date, end date
587 =item anniversary_date
589 listref of start date, end date
591 =item current_balance
593 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
606 my ($class, $params) = @_;
613 # initialize these to prevent warnings
621 'invoice_terms' => '',
627 # explicit custnum(s)
630 if ( $params->{'custnum'} ) {
631 my @custnums = ref($params->{'custnum'}) ?
632 @{ $params->{'custnum'} } :
633 $params->{'custnum'};
635 'cust_main.custnum IN (' .
636 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
637 ')' if scalar(@custnums) > 0;
644 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
646 "cust_main.agentnum = $1";
653 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
654 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
655 : 'cust_main.salesnum IS NULL';
662 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
664 "cust_main.usernum = $1";
671 #prospect ordered active inactive suspended cancelled
672 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
673 my $method = $params->{'status'}. '_sql';
674 #push @where, $class->$method();
675 push @where, FS::cust_main->$method();
679 unless ( $params->{location_history} ) {
681 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
682 cust_main.ship_locationnum
684 OR cust_location.locationnum IN (
685 SELECT locationnum FROM cust_pkg
686 WHERE cust_pkg.custnum = cust_main.custnum
687 AND locationnum IS NOT NULL
688 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
696 if ( $params->{'address'} ) {
697 # allow this to be an arrayref
698 my @values = ($params->{'address'});
699 @values = @{$values[0]} if ref($values[0]);
701 foreach (grep /\S/, @values) {
702 my $address = dbh->quote('%'. lc($_). '%');
704 "LOWER(cust_location.address1) LIKE $address",
705 "LOWER(cust_location.address2) LIKE $address";
708 push @where, "EXISTS(
709 SELECT 1 FROM cust_location
710 WHERE cust_location.custnum = cust_main.custnum
711 AND (".join(' OR ',@orwhere).")
720 if ( $params->{'city'} =~ /\S/ ) {
721 my $city = dbh->quote($params->{'city'});
722 push @where, "EXISTS(
723 SELECT 1 FROM cust_location
724 WHERE cust_location.custnum = cust_main.custnum
725 AND cust_location.city = $city
733 if ( $params->{'county'} =~ /\S/ ) {
734 my $county = dbh->quote($params->{'county'});
735 push @where, "EXISTS(
736 SELECT 1 FROM cust_location
737 WHERE cust_location.custnum = cust_main.custnum
738 AND cust_location.county = $county
746 if ( $params->{'state'} =~ /\S/ ) {
747 my $state = dbh->quote($params->{'state'});
748 push @where, "EXISTS(
749 SELECT 1 FROM cust_location
750 WHERE cust_location.custnum = cust_main.custnum
751 AND cust_location.state = $state
759 if ( $params->{'zip'} =~ /\S/ ) {
760 my $zip = dbh->quote($params->{'zip'} . '%');
761 push @where, "EXISTS(
762 SELECT 1 FROM cust_location
763 WHERE cust_location.custnum = cust_main.custnum
764 AND cust_location.zip LIKE $zip
772 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
773 my $country = uc($1);
774 push @where, "EXISTS(
775 SELECT 1 FROM cust_location
776 WHERE cust_location.custnum = cust_main.custnum
777 AND cust_location.country = '$country'
785 if ( $params->{'refnum'} ) {
787 my @refnum = ref( $params->{'refnum'} )
788 ? @{ $params->{'refnum'} }
789 : ( $params->{'refnum'} );
791 @refnum = grep /^(\d*)$/, @refnum;
793 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
799 # parse cancelled package checkbox
804 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
805 unless $params->{'cancelled_pkgs'};
808 # "with email address(es)" checkbox,
809 # also optionally: with_email_dest and with_contact_type
812 if ($params->{with_email}) {
815 my $contact_type_sql;
817 if ($params->{with_email_dest}) {
818 croak unless ref $params->{with_email_dest} eq 'ARRAY';
820 @email_dest = @{$params->{with_email_dest}};
823 join(' OR ',map(" cust_contact.${_}_dest IS NOT NULL ", @email_dest)).
825 # Can't use message_dist = 'Y' because single quotes are escaped later
827 if ($params->{with_contact_type}) {
828 croak unless ref $params->{with_contact_type} eq 'ARRAY';
830 my @contact_type = grep {/^\d+$/ && $_ > 0} @{$params->{with_contact_type}};
831 my $has_null_type = 0;
832 $has_null_type = 1 if grep { $_ eq 0 } @{$params->{with_contact_type}};
834 if ($has_null_type) {
835 $hnt_sql = ' OR ' if @contact_type;
836 $hnt_sql .= ' cust_contact.classnum IS NULL ';
841 join(' OR ', map(" cust_contact.classnum = $_ ", @contact_type)).
846 "EXISTS ( SELECT 1 FROM contact_email
847 JOIN cust_contact USING (contactnum)
848 WHERE cust_contact.custnum = cust_main.custnum
855 # "with postal mail invoices" checkbox
858 push @where, "cust_main.postal_invoice = 'Y'"
859 if $params->{'POST'};
862 # "without postal mail invoices" checkbox
865 push @where, "cust_main.postal_invoice IS NULL"
866 if $params->{'no_POST'};
869 # "tax exempt" checkbox
871 push @where, "cust_main.tax = 'Y'"
875 # "not tax exempt" checkbox
877 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
878 if $params->{'no_tax'};
883 if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
889 if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
890 my $method = $params->{referral_status}. '_sql';
891 $and_status = ' AND '. FS::cust_main->$method();
892 $and_status =~ s/ cust_main\./ referred_cust_main./g;
896 " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
897 WHERE cust_main.custnum = referred_cust_main.referral_custnum
907 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
909 next unless exists($params->{$field});
911 my($beginning, $ending, $hour) = @{$params->{$field}};
914 "cust_main.$field IS NOT NULL",
915 "cust_main.$field >= $beginning",
916 "cust_main.$field <= $ending";
918 if($field eq 'signupdate' && defined $hour) {
919 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
920 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
922 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
923 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
926 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
930 $orderby ||= "ORDER BY cust_main.$field";
938 if ( $params->{'classnum'} ) {
940 my @classnum = ref( $params->{'classnum'} )
941 ? @{ $params->{'classnum'} }
942 : ( $params->{'classnum'} );
944 @classnum = grep /^(\d*)$/, @classnum;
947 push @where, '( '. join(' OR ', map {
948 $_ ? "cust_main.classnum = $_"
949 : "cust_main.classnum IS NULL"
962 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
964 if ( $1 eq 'NULL' ) {
966 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
969 "cust_main.invoice_terms IS NOT NULL",
970 "cust_main.invoice_terms = '$1'";
978 if ( $params->{'current_balance'} ) {
980 #my $balance_sql = $class->balance_sql();
981 my $balance_sql = FS::cust_main->balance_sql();
983 my @current_balance =
984 ref( $params->{'current_balance'} )
985 ? @{ $params->{'current_balance'} }
986 : ( $params->{'current_balance'} );
988 push @where, map { s/current_balance/$balance_sql/; $_ }
997 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
999 "cust_main.custbatch = '$1'";
1002 if ( $params->{'tagnum'} ) {
1003 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1005 @tagnums = grep /^(\d+)$/, @tagnums;
1008 if ( $params->{'all_tags'} ) {
1009 foreach ( @tagnums ) {
1010 push @where, 'exists(select 1 from cust_tag where '.
1011 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1014 } else { # matching any tag, not all
1015 my $tags_where = "0 < (select count(1) from cust_tag where "
1016 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1017 . join(',', @tagnums) . "))";
1019 push @where, $tags_where;
1027 if ( $params->{'pkg_classnum'} ) {
1028 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1029 @{ $params->{'pkg_classnum'} } :
1030 $params->{'pkg_classnum'};
1031 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1033 if ( @pkg_classnums ) {
1036 if ( $params->{'all_pkg_classnums'} ) {
1037 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1040 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1042 foreach (@pkg_where) {
1044 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1045 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1046 if ( not $params->{'any_pkg_status'} ) {
1047 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1049 push @where, "EXISTS($select_pkg)";
1055 # setup queries, subs, etc. for the search
1058 $orderby ||= 'ORDER BY custnum';
1060 # here is the agent virtualization
1062 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1064 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1067 # always make address fields available in results
1068 for my $pre ('bill_', 'ship_') {
1070 'LEFT JOIN cust_location AS '.$pre.'location '.
1071 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1074 # always make referral available in results
1075 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1076 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1078 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1081 'cust_main.custnum',
1082 'cust_main.salesnum',
1083 # there's a good chance that we'll need these
1084 'cust_main.bill_locationnum',
1085 'cust_main.ship_locationnum',
1086 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1089 my @extra_headers = ();
1090 my @extra_fields = ();
1091 my @extra_sort_fields = ();
1094 if ($params->{'contacts'}) {
1095 my $contact_params = $params->{'contacts'};
1098 ' LEFT JOIN cust_contact ON ( cust_main.custnum = cust_contact.custnum ) ';
1100 if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
1101 $addl_from .= ' LEFT JOIN contact ON ( cust_contact.contactnum = contact.contactnum ) ';
1102 my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
1103 unless !$contact_params->{'contacts_firstname'};
1104 my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
1105 unless !$contact_params->{'contacts_lastname'};
1106 $extra_sql .= " AND ( '1' $first_query $last_query )";
1109 if ($contact_params->{'contacts_email'}) {
1110 $addl_from .= ' LEFT JOIN contact_email ON ( cust_contact.contactnum = contact_email.contactnum ) ';
1111 $extra_sql .= " AND ( contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "' )";
1114 if ($contact_params->{'contacts_homephone'} || $contact_params->{'contacts_workphone'} || $contact_params->{'contacts_mobilephone'}) {
1115 $addl_from .= ' LEFT JOIN contact_phone ON ( cust_contact.contactnum = contact_phone.contactnum ) ';
1116 my $contacts_mobilephone;
1117 foreach my $phone (qw( contacts_homephone contacts_workphone contacts_mobilephone )) {
1118 (my $num = $contact_params->{$phone}) =~ s/\W//g;
1119 if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
1121 my $home_query = " AND ( contact_phone.phonetypenum = '2' AND contact_phone.phonenum = '" . $contact_params->{'contacts_homephone'} . "' )"
1122 unless !$contact_params->{'contacts_homephone'};
1123 my $work_query = " AND ( contact_phone.phonetypenum = '1' AND contact_phone.phonenum = '" . $contact_params->{'contacts_workphone'} . "' )"
1124 unless !$contact_params->{'contacts_workphone'};
1125 my $mobile_query = " AND ( contact_phone.phonetypenum = '3' AND contact_phone.phonenum = '" . $contact_params->{'contacts_mobilephone'} . "' )"
1126 unless !$contact_params->{'contacts_mobilephone'};
1127 $extra_sql .= " AND ( '1' $home_query $work_query $mobile_query )";
1132 if ($params->{'flattened_pkgs'}) {
1136 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1138 if ($dbh->{Driver}->{Name} eq 'Pg') {
1143 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1144 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1149 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1150 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1151 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1152 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1154 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1155 "omitting package information from report.";
1158 my $header_query = "
1159 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1160 FROM cust_main $addl_from $extra_sql $pkgwhere
1161 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1164 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1165 $sth->execute() or die $sth->errstr;
1166 my $headerrow = $sth->fetchrow_arrayref;
1167 my $headercount = $headerrow ? $headerrow->[0] : 0;
1168 while($headercount) {
1169 unshift @extra_headers, "Package ". $headercount;
1170 unshift @extra_fields, eval q!sub {my $c = shift;
1171 my @a = split '\|', $c->magic;
1172 my $p = $a[!.--$headercount. q!];
1175 unshift @extra_sort_fields, '';
1180 if ( $params->{'with_referrals'} ) {
1182 #XXX next: num for each customer status
1185 '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1186 WHERE cust_main.custnum = referred_cust_main.referral_custnum
1187 ) AS num_referrals';
1189 unshift @extra_headers, 'Referrals';
1190 unshift @extra_fields, 'num_referrals';
1191 unshift @extra_sort_fields, 'num_referrals';
1195 my $select = join(', ', @select);
1198 'table' => 'cust_main',
1199 'select' => $select,
1200 'addl_from' => $addl_from,
1202 'extra_sql' => $extra_sql,
1203 'order_by' => $orderby,
1204 'count_query' => $count_query,
1205 'extra_headers' => \@extra_headers,
1206 'extra_fields' => \@extra_fields,
1207 'extra_sort_fields' => \@extra_sort_fields,
1213 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1215 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1216 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1219 Additional options are the same as FS::Record::qsearch
1226 # sensible defaults, then merge in any passed options
1228 'table' => 'cust_main',
1237 my @fuzzy_mod = 'i';
1238 my $conf = new FS::Conf;
1239 my $fuzziness = $conf->config('fuzzy-fuzziness');
1240 push @fuzzy_mod, $fuzziness if $fuzziness;
1242 check_and_rebuild_fuzzyfiles();
1243 foreach my $field ( keys %$fuzzy ) {
1245 my $all = $self->all_X($field);
1246 next unless scalar(@$all);
1249 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1250 next if !keys(%match);
1252 my $in_matches = 'IN (' .
1253 join(',', map { dbh->quote($_) } keys %match) .
1256 my $extra_sql = $fuzopts{extra_sql};
1257 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1258 $extra_sql .= ' AND ';
1260 $extra_sql .= 'WHERE ';
1262 $extra_sql .= "$field $in_matches";
1264 my $addl_from = $fuzopts{addl_from};
1265 if ( $field =~ /^cust_location\./ ) {
1266 $addl_from .= ' JOIN cust_location USING (custnum)';
1267 } elsif ( $field =~ /^contact\./ ) {
1268 $addl_from .= ' JOIN contact USING (custnum)';
1271 push @cust_main, qsearch({
1273 'addl_from' => $addl_from,
1274 'extra_sql' => $extra_sql,
1278 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1280 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1288 =head1 UTILITY SUBROUTINES
1292 =item check_and_rebuild_fuzzyfiles
1296 sub check_and_rebuild_fuzzyfiles {
1297 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1298 rebuild_fuzzyfiles()
1299 if grep { ! -e "$dir/$_" }
1301 my ($field, $table) = reverse split('\.', $_);
1302 $table ||= 'cust_main';
1308 =item rebuild_fuzzyfiles
1312 sub rebuild_fuzzyfiles {
1314 use Fcntl qw(:flock);
1316 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1317 mkdir $dir, 0700 unless -d $dir;
1319 foreach my $fuzzy ( @fuzzyfields ) {
1321 my ($field, $table) = reverse split('\.', $fuzzy);
1322 $table ||= 'cust_main';
1324 open(LOCK,">>$dir/$table.$field")
1325 or die "can't open $dir/$table.$field: $!";
1327 or die "can't lock $dir/$table.$field: $!";
1329 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1330 or die "can't open $dir/$table.$field.tmp: $!";
1332 my $sth = dbh->prepare(
1333 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1335 $sth->execute or die $sth->errstr;
1337 while ( my $row = $sth->fetchrow_arrayref ) {
1338 print CACHE $row->[0]. "\n";
1341 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1343 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1349 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1353 sub append_fuzzyfiles {
1354 #my( $first, $last, $company ) = @_;
1356 check_and_rebuild_fuzzyfiles();
1358 #foreach my $fuzzy (@fuzzyfields) {
1359 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1360 'cust_location.address1',
1361 'cust_main.ship_company',
1364 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1371 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1373 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1377 use Fcntl qw(:flock);
1378 sub append_fuzzyfiles_fuzzyfield {
1379 my( $fuzzyfield, $value ) = @_;
1381 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1384 my ($field, $table) = reverse split('\.', $fuzzyfield);
1385 $table ||= 'cust_main';
1387 return unless defined($value) && length($value);
1389 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1390 or die "can't open $dir/$table.$field: $!";
1391 flock(CACHE,LOCK_EX)
1392 or die "can't lock $dir/$table.$field: $!";
1394 print CACHE "$value\n";
1396 flock(CACHE,LOCK_UN)
1397 or die "can't unlock $dir/$table.$field: $!";
1407 my( $self, $fuzzy ) = @_;
1408 my ($field, $table) = reverse split('\.', $fuzzy);
1409 $table ||= 'cust_main';
1411 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1412 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1413 or die "can't open $dir/$table.$field: $!";
1414 my @array = map { chomp; $_; } <CACHE>;
1425 L<FS::cust_main>, L<FS::Record>