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_main.ship_company', # if you're using it
25 'cust_location.address1',
26 'contact.first', 'contact.last',
29 install_callback FS::UID sub {
31 #yes, need it for stuff below (prolly should be cached)
36 FS::cust_main::Search - Customer searching
40 use FS::cust_main::Search;
42 FS::cust_main::Search::smart_search(%options);
44 FS::cust_main::Search::email_search(%options);
46 FS::cust_main::Search->search( \%options );
48 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
54 =item smart_search OPTION => VALUE ...
56 Accepts the following options: I<search>, the string to search for. The string
57 will be searched for as a customer number, phone number, name or company name,
58 address (if address1-search is on), invoicing email address, or credit card
61 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
62 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
64 skip fuzzy matching when an exact match is found.
66 Any additional options are treated as an additional qualifier on the search
69 Returns a (possibly empty) array of FS::cust_main objects.
76 #here is the agent virtualization
78 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
79 my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
83 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
84 my $search = delete $options{'search'};
85 ( my $alphanum_search = $search ) =~ s/\W//g;
87 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
89 #false laziness w/Record::ut_phone
90 my $phonen = "$1-$2-$3";
91 $phonen .= " x$4" if $4;
93 my $phonenum = "$1$2$3";
96 #cust_main phone numbers and contact phone number
97 push @cust_main, qsearch( {
98 'select' => 'cust_main.*',
99 'table' => 'cust_main',
100 'addl_from' => ' left join contact using (custnum) '.
101 ' left join contact_phone using (contactnum) ',
102 'hashref' => { %options },
103 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
105 join(' OR ', map "$_ = '$phonen'",
106 qw( daytime night mobile fax )
108 " OR phonenum = '$phonenum' ".
110 " AND $agentnums_sql", #agent virtualization
113 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
114 #try looking for matches with extensions unless one was specified
116 push @cust_main, qsearch( {
117 'table' => 'cust_main',
118 'hashref' => { %options },
119 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
121 join(' OR ', map "$_ LIKE '$phonen\%'",
125 " AND $agentnums_sql", #agent virtualization
133 if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
135 push @cust_main, qsearch( {
136 'select' => 'cust_main.*',
137 'table' => 'cust_main',
138 'addl_from' => ' left join cust_main_invoice using (custnum) '.
139 ' left join contact using (custnum) '.
140 ' left join contact_email using (contactnum) ',
141 'hashref' => { %options },
142 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
144 join(' OR ', map "$_ = '$search'",
145 qw( dest emailaddress )
148 " AND $agentnums_sql", #agent virtualization
151 # custnum search (also try agent_custid), with some tweaking options if your
152 # legacy cust "numbers" have letters
153 } elsif ( $search =~ /^\s*(\d+)\s*$/
154 or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
155 && $search =~ /^\s*(\w\w?\d+)\s*$/
157 or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
158 && $search =~ /^\s*(\d+-\w)\s*$/
160 or ( $conf->config('cust_main-custnum-display_special')
161 # it's not currently possible for special prefixes to contain
162 # digits, so just strip off any alphabetic prefix and match
163 # the rest to custnum
164 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
166 or ( $conf->exists('address1-search' )
167 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
174 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
175 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
176 ? ' AND agent_custid IS NULL ' : '';
177 push @cust_main, qsearch( {
178 'table' => 'cust_main',
179 'hashref' => { 'custnum' => $num, %options },
180 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
184 # for all agents this user can see, if any of them have custnum prefixes
185 # that match the search string, include customers that match the rest
186 # of the custnum and belong to that agent
187 foreach my $agentnum ( keys %$agentnums_href ) {
188 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
190 if ( $p eq substr($num, 0, length($p)) ) {
191 push @cust_main, qsearch( {
192 'table' => 'cust_main',
193 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
194 'agentnum' => $agentnum,
201 push @cust_main, qsearch( {
202 'table' => 'cust_main',
203 'hashref' => { 'agent_custid' => $num, %options },
204 'extra_sql' => " AND $agentnums_sql", #agent virtualization
207 if ( $conf->exists('address1-search') ) {
208 my $len = length($num);
210 # probably the Right Thing: return customers that have any associated
211 # locations matching the string, not just bill/ship location
212 push @cust_main, qsearch( {
213 'select' => 'cust_main.*',
214 'table' => 'cust_main',
215 'addl_from' => ' JOIN cust_location USING (custnum) ',
216 'hashref' => { %options, },
218 ( keys(%options) ? ' AND ' : ' WHERE ' ).
219 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
220 " AND $agentnums_sql",
224 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
226 my($company, $last, $first) = ( $1, $2, $3 );
228 # "Company (Last, First)"
229 #this is probably something a browser remembered,
230 #so just do an exact search (but case-insensitive, so USPS standardization
231 #doesn't throw a wrench in the works)
233 push @cust_main, qsearch( {
234 'table' => 'cust_main',
235 'hashref' => { %options },
237 ( keys(%options) ? ' AND ' : ' WHERE ' ).
239 " LOWER(first) = ". dbh->quote(lc($first)),
240 " LOWER(last) = ". dbh->quote(lc($last)),
241 " LOWER(company) = ". dbh->quote(lc($company)),
247 # probably not necessary for the "something a browser remembered" case
249 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
250 # try {first,last,company}
254 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
255 # # full strings the browser remembers won't work
256 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
258 use Lingua::EN::NameParse;
259 my $NameParse = new Lingua::EN::NameParse(
264 my($last, $first) = ( '', '' );
265 #maybe disable this too and just rely on NameParse?
266 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
268 ($last, $first) = ( $1, $2 );
270 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
271 } elsif ( ! $NameParse->parse($value) ) {
273 my %name = $NameParse->components;
274 $first = lc($name{'given_name_1'}) || $name{'initials_1'}; #wtf NameParse, Ed?
275 $last = lc($name{'surname_1'});
279 if ( $first && $last ) {
281 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
284 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
285 $sql .= "( (LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first)
286 OR (LOWER(contact.last) = $q_last AND LOWER(contact.first) = $q_first) )";
288 #cust_main and contacts
289 push @cust_main, qsearch( {
290 'select' => 'cust_main.*',
291 'table' => 'cust_main',
292 'addl_from' => ' left join contact using (custnum) ',
293 'hashref' => { %options },
294 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
297 # or it just be something that was typed in... (try that in a sec)
301 my $q_value = dbh->quote($value);
304 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
305 $sql .= " ( LOWER(cust_main.first) = $q_value
306 OR LOWER(cust_main.last) = $q_value
307 OR LOWER(cust_main.company) = $q_value
308 OR LOWER(cust_main.ship_company) = $q_value
309 OR LOWER(contact.first) = $q_value
310 OR LOWER(contact.last) = $q_value
313 #address1 (yes, it's a kludge)
314 $sql .= " OR EXISTS (
315 SELECT 1 FROM cust_location
316 WHERE LOWER(cust_location.address1) = $q_value
317 AND cust_location.custnum = cust_main.custnum
319 if $conf->exists('address1-search');
321 push @cust_main, qsearch( {
322 'select' => 'cust_main.*',
323 'table' => 'cust_main',
324 'addl_from' => ' left join contact using (custnum) ',
325 'hashref' => { %options },
326 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
329 #no exact match, trying substring/fuzzy
330 #always do substring & fuzzy (unless they're explicity config'ed off)
331 #getting complaints searches are not returning enough
332 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
334 #still some false laziness w/search (was search/cust_main.cgi)
337 $FS::CurrentUser::CurrentUser->access_right('List all customers')
342 my @company_hashrefs = ();
343 if ( length($value) >= $min_len ) {
344 @company_hashrefs = (
345 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
346 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
351 if ( $first && $last ) {
354 { 'first' => { op=>'ILIKE', value=>"%$first%" },
355 'last' => { op=>'ILIKE', value=>"%$last%" },
359 } elsif ( length($value) >= $min_len ) {
362 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
363 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
368 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
370 push @cust_main, qsearch( {
371 'table' => 'cust_main',
372 'hashref' => { %$hashref,
375 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
380 if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
382 push @cust_main, qsearch( {
383 select => 'cust_main.*',
384 table => 'cust_main',
385 addl_from => 'JOIN cust_location USING (custnum)',
386 extra_sql => 'WHERE '.
387 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
388 " AND $agentnums_sql", #agent virtualizaiton
395 foreach my $hashref ( @hashrefs ) {
398 grep $agentnums_href->{$_->agentnum}, #agent virt
399 grep $_, #skip contacts that don't have cust_main records
402 'table' => 'contact',
403 'hashref' => { %$hashref,
406 #'extra_sql' => " AND $agentnums_sql", #agent virt
413 'hashref' => \%options,
415 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
418 if ( $first && $last ) {
419 push @cust_main, FS::cust_main::Search->fuzzy_search(
420 { 'last' => $last, #fuzzy hashref
421 'first' => $first }, #
424 push @cust_main, FS::cust_main::Search->fuzzy_search(
425 { 'contact.last' => $last, #fuzzy hashref
426 'contact.first' => $first }, #
431 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
432 push @cust_main, FS::cust_main::Search->fuzzy_search(
433 { $field => $value },
437 foreach my $field ( 'first', 'last' ) {
438 push @cust_main, FS::cust_main::Search->fuzzy_search(
439 { "contact.$field" => $value },
443 if ( $conf->exists('address1-search') ) {
445 FS::cust_main::Search->fuzzy_search(
446 { 'cust_location.address1' => $value },
455 ( my $nospace_search = $search ) =~ s/\s//g;
456 ( my $card_search = $nospace_search ) =~ s/\-//g;
457 $card_search =~ s/[x\*\.\_]/x/gi;
459 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
461 ( my $like_search = $card_search ) =~ s/x/_/g;
462 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
464 push @cust_main, qsearch({
465 'table' => 'cust_main',
467 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
468 OR paymask = '$mask_search'
470 " AND payby IN ('CARD','DCRD') ".
471 " AND $agentnums_sql", #agent virtulization
477 #eliminate duplicates
479 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
487 Accepts the following options: I<email>, the email address to search for. The
488 email address will be searched for as an email invoice destination and as an
491 #Any additional options are treated as an additional qualifier on the search
494 Returns a (possibly empty) array of FS::cust_main objects (but usually just
502 my $email = delete $options{'email'};
504 #no agent virtualization yet
505 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
509 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
511 my ( $user, $domain ) = ( $1, $2 );
513 warn "$me smart_search: searching for $user in domain $domain"
519 'table' => 'cust_main_invoice',
520 'hashref' => { 'dest' => $email },
527 map $_->cust_svc->cust_pkg,
529 'table' => 'svc_acct',
530 'hashref' => { 'username' => $user, },
532 'AND ( SELECT domain FROM svc_domain
533 WHERE svc_acct.domsvc = svc_domain.svcnum
534 ) = '. dbh->quote($domain),
540 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
542 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
559 Returns a qsearch hash expression to search for parameters specified in
560 HASHREF. Valid parameters are
580 listref of start date, end date
584 listref of start date, end date
586 =item spouse_birthdate
588 listref of start date, end date
590 =item anniversary_date
592 listref of start date, end date
602 =item current_balance
604 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
617 my ($class, $params) = @_;
624 # initialize these to prevent warnings
632 'paydate_year' => '',
633 'invoice_terms' => '',
639 # explicit custnum(s)
642 if ( $params->{'custnum'} ) {
643 my @custnums = ref($params->{'custnum'}) ?
644 @{ $params->{'custnum'} } :
645 $params->{'custnum'};
647 'cust_main.custnum IN (' .
648 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
649 ')' if scalar(@custnums) > 0;
656 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
658 "cust_main.agentnum = $1";
665 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
666 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
667 : 'cust_main.salesnum IS NULL';
674 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
676 "cust_main.usernum = $1";
683 #prospect ordered active inactive suspended cancelled
684 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
685 my $method = $params->{'status'}. '_sql';
686 #push @where, $class->$method();
687 push @where, FS::cust_main->$method();
691 unless ( $params->{location_history} ) {
693 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
694 cust_main.ship_locationnum
696 OR cust_location.locationnum IN (
697 SELECT locationnum FROM cust_pkg
698 WHERE cust_pkg.custnum = cust_main.custnum
699 AND locationnum IS NOT NULL
700 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
708 if ( $params->{'address'} ) {
709 # allow this to be an arrayref
710 my @values = ($params->{'address'});
711 @values = @{$values[0]} if ref($values[0]);
713 foreach (grep /\S/, @values) {
714 my $address = dbh->quote('%'. lc($_). '%');
716 "LOWER(cust_location.address1) LIKE $address",
717 "LOWER(cust_location.address2) LIKE $address";
720 push @where, "EXISTS(
721 SELECT 1 FROM cust_location
722 WHERE cust_location.custnum = cust_main.custnum
723 AND (".join(' OR ',@orwhere).")
732 if ( $params->{'city'} =~ /\S/ ) {
733 my $city = dbh->quote($params->{'city'});
734 push @where, "EXISTS(
735 SELECT 1 FROM cust_location
736 WHERE cust_location.custnum = cust_main.custnum
737 AND cust_location.city = $city
745 if ( $params->{'county'} =~ /\S/ ) {
746 my $county = dbh->quote($params->{'county'});
747 push @where, "EXISTS(
748 SELECT 1 FROM cust_location
749 WHERE cust_location.custnum = cust_main.custnum
750 AND cust_location.county = $county
758 if ( $params->{'state'} =~ /\S/ ) {
759 my $state = dbh->quote($params->{'state'});
760 push @where, "EXISTS(
761 SELECT 1 FROM cust_location
762 WHERE cust_location.custnum = cust_main.custnum
763 AND cust_location.state = $state
771 if ( $params->{'zip'} =~ /\S/ ) {
772 my $zip = dbh->quote($params->{'zip'} . '%');
773 push @where, "EXISTS(
774 SELECT 1 FROM cust_location
775 WHERE cust_location.custnum = cust_main.custnum
776 AND cust_location.zip LIKE $zip
784 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
785 my $country = uc($1);
786 push @where, "EXISTS(
787 SELECT 1 FROM cust_location
788 WHERE cust_location.custnum = cust_main.custnum
789 AND cust_location.country = '$country'
797 if ( $params->{'refnum'} ) {
799 my @refnum = ref( $params->{'refnum'} )
800 ? @{ $params->{'refnum'} }
801 : ( $params->{'refnum'} );
803 @refnum = grep /^(\d*)$/, @refnum;
805 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
811 # parse cancelled package checkbox
816 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
817 unless $params->{'cancelled_pkgs'};
820 # "with email address(es)" checkbox
824 'EXISTS ( SELECT 1 FROM cust_main_invoice
825 WHERE cust_main_invoice.custnum = cust_main.custnum
827 )' # AND dest LIKE '%@%'
828 if $params->{'with_email'};
831 # "with postal mail invoices" checkbox
835 "EXISTS ( SELECT 1 FROM cust_main_invoice
836 WHERE cust_main_invoice.custnum = cust_main.custnum
838 if $params->{'POST'};
841 # "without postal mail invoices" checkbox
845 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
846 WHERE cust_main_invoice.custnum = cust_main.custnum
848 if $params->{'no_POST'};
851 # "tax exempt" checkbox
853 push @where, "cust_main.tax = 'Y'"
857 # "not tax exempt" checkbox
859 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
860 if $params->{'no_tax'};
865 if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
871 if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
872 my $method = $params->{referral_status}. '_sql';
873 $and_status = ' AND '. FS::cust_main->$method();
874 $and_status =~ s/ cust_main\./ referred_cust_main./g;
878 " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
879 WHERE cust_main.custnum = referred_cust_main.referral_custnum
889 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
891 next unless exists($params->{$field});
893 my($beginning, $ending, $hour) = @{$params->{$field}};
896 "cust_main.$field IS NOT NULL",
897 "cust_main.$field >= $beginning",
898 "cust_main.$field <= $ending";
900 if($field eq 'signupdate' && defined $hour) {
901 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
902 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
904 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
905 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
908 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
912 $orderby ||= "ORDER BY cust_main.$field";
920 if ( $params->{'classnum'} ) {
922 my @classnum = ref( $params->{'classnum'} )
923 ? @{ $params->{'classnum'} }
924 : ( $params->{'classnum'} );
926 @classnum = grep /^(\d*)$/, @classnum;
929 push @where, '( '. join(' OR ', map {
930 $_ ? "cust_main.classnum = $_"
931 : "cust_main.classnum IS NULL"
944 if ( $params->{'payby'} ) {
946 my @payby = ref( $params->{'payby'} )
947 ? @{ $params->{'payby'} }
948 : ( $params->{'payby'} );
950 @payby = grep /^([A-Z]{4})$/, @payby;
952 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
958 # paydate_year / paydate_month
961 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
963 $params->{'paydate_month'} =~ /^(\d\d?)$/
964 or die "paydate_year without paydate_month?";
968 'paydate IS NOT NULL',
970 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
978 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
980 if ( $1 eq 'NULL' ) {
982 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
985 "cust_main.invoice_terms IS NOT NULL",
986 "cust_main.invoice_terms = '$1'";
994 if ( $params->{'current_balance'} ) {
996 #my $balance_sql = $class->balance_sql();
997 my $balance_sql = FS::cust_main->balance_sql();
999 my @current_balance =
1000 ref( $params->{'current_balance'} )
1001 ? @{ $params->{'current_balance'} }
1002 : ( $params->{'current_balance'} );
1004 push @where, map { s/current_balance/$balance_sql/; $_ }
1013 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
1015 "cust_main.custbatch = '$1'";
1018 if ( $params->{'tagnum'} ) {
1019 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1021 @tagnums = grep /^(\d+)$/, @tagnums;
1024 if ( $params->{'all_tags'} ) {
1025 my $exists = $params->{'all_tags'} eq 'all' ? 'exists' : 'not exists';
1026 foreach ( @tagnums ) {
1027 push @where, $exists.'(select 1 from cust_tag where '.
1028 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1031 } else { # matching any tag, not all
1032 my $tags_where = "0 < (select count(1) from cust_tag where "
1033 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1034 . join(',', @tagnums) . "))";
1036 push @where, $tags_where;
1044 if ( $params->{'pkg_classnum'} ) {
1045 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1046 @{ $params->{'pkg_classnum'} } :
1047 $params->{'pkg_classnum'};
1048 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1050 if ( @pkg_classnums ) {
1053 if ( $params->{'all_pkg_classnums'} ) {
1054 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1057 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1059 foreach (@pkg_where) {
1061 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1062 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1063 if ( not $params->{'any_pkg_status'} ) {
1064 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1066 push @where, "EXISTS($select_pkg)";
1074 if (keys %{ $params->{'contacts'} }) {
1075 my $contact_params = $params->{'contacts'};
1077 if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
1078 my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
1079 unless !$contact_params->{'contacts_firstname'};
1080 my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
1081 unless !$contact_params->{'contacts_lastname'};
1083 "EXISTS ( SELECT 1 FROM contact
1084 WHERE contact.custnum = cust_main.custnum
1085 $first_query $last_query
1089 if ($contact_params->{'contacts_email'}) {
1091 "EXISTS ( SELECT 1 FROM contact_email
1092 JOIN contact USING (contactnum)
1093 WHERE contact.custnum = cust_main.custnum
1094 AND contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "'
1098 if ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
1100 foreach my $phone ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
1101 $phone =~ /^contacts_phonetypenum(\d+)$/ or die "No phone type num $1 from $phone";
1102 my $phonetypenum = $1;
1103 (my $num = $contact_params->{$phone}) =~ s/\W//g;
1104 if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
1105 $phone_query .= " AND ( contact_phone.phonetypenum = '".$phonetypenum."' AND contact_phone.phonenum = '" . $contact_params->{$phone} . "' )"
1106 unless !$contact_params->{$phone};
1109 "EXISTS ( SELECT 1 FROM contact_phone
1110 JOIN contact USING (contactnum)
1111 WHERE contact.custnum = cust_main.custnum
1119 # setup queries, subs, etc. for the search
1122 $orderby ||= 'ORDER BY cust_main.custnum';
1124 # here is the agent virtualization
1126 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1128 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1131 # always make address fields available in results
1132 for my $pre ('bill_', 'ship_') {
1134 'LEFT JOIN cust_location AS '.$pre.'location '.
1135 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1138 # always make referral available in results
1139 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1140 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1143 'cust_main.custnum',
1144 'cust_main.salesnum',
1145 # there's a good chance that we'll need these
1146 'cust_main.bill_locationnum',
1147 'cust_main.ship_locationnum',
1148 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1151 my @extra_headers = ();
1152 my @extra_fields = ();
1153 my @extra_sort_fields = ();
1155 my $count_query = "SELECT COUNT(DISTINCT cust_main.custnum) FROM cust_main $addl_from $extra_sql";
1157 if ($params->{'flattened_pkgs'}) {
1161 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1163 if ($dbh->{Driver}->{Name} eq 'Pg') {
1168 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1169 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1174 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1175 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1176 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1177 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1179 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1180 "omitting package information from report.";
1183 my $header_query = "
1184 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1185 FROM cust_main $addl_from $extra_sql $pkgwhere
1186 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1189 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1190 $sth->execute() or die $sth->errstr;
1191 my $headerrow = $sth->fetchrow_arrayref;
1192 my $headercount = $headerrow ? $headerrow->[0] : 0;
1193 while($headercount) {
1194 unshift @extra_headers, "Package ". $headercount;
1195 unshift @extra_fields, eval q!sub {my $c = shift;
1196 my @a = split '\|', $c->magic;
1197 my $p = $a[!.--$headercount. q!];
1200 unshift @extra_sort_fields, '';
1205 if ( $params->{'with_referrals'} ) {
1207 #XXX next: num for each customer status
1210 '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1211 WHERE cust_main.custnum = referred_cust_main.referral_custnum
1212 ) AS num_referrals';
1214 unshift @extra_headers, 'Referrals';
1215 unshift @extra_fields, 'num_referrals';
1216 unshift @extra_sort_fields, 'num_referrals';
1220 my $select = join(', ', @select);
1223 'table' => 'cust_main',
1224 'select' => $select,
1225 'addl_from' => $addl_from,
1227 'extra_sql' => $extra_sql,
1228 'order_by' => $orderby,
1229 'count_query' => $count_query,
1230 'extra_headers' => \@extra_headers,
1231 'extra_fields' => \@extra_fields,
1232 'extra_sort_fields' => \@extra_sort_fields,
1234 #warn Data::Dumper::Dumper($sql_query);
1239 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1241 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1242 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1245 Additional options are the same as FS::Record::qsearch
1252 # sensible defaults, then merge in any passed options
1254 'table' => 'cust_main',
1263 my @fuzzy_mod = 'i';
1264 my $conf = new FS::Conf;
1265 my $fuzziness = $conf->config('fuzzy-fuzziness');
1266 push @fuzzy_mod, $fuzziness if $fuzziness;
1268 check_and_rebuild_fuzzyfiles();
1269 foreach my $field ( keys %$fuzzy ) {
1271 my $all = $self->all_X($field);
1272 next unless scalar(@$all);
1275 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1276 next if !keys(%match);
1278 my $in_matches = 'IN (' .
1279 join(',', map { dbh->quote($_) } keys %match) .
1282 my $extra_sql = $fuzopts{extra_sql};
1283 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1284 $extra_sql .= ' AND ';
1286 $extra_sql .= 'WHERE ';
1288 $extra_sql .= "$field $in_matches";
1290 my $addl_from = $fuzopts{addl_from};
1291 if ( $field =~ /^cust_location\./ ) {
1292 $addl_from .= ' JOIN cust_location USING (custnum)';
1293 } elsif ( $field =~ /^contact\./ ) {
1294 $addl_from .= ' JOIN contact USING (custnum)';
1297 push @cust_main, qsearch({
1299 'addl_from' => $addl_from,
1300 'extra_sql' => $extra_sql,
1304 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1306 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1314 =head1 UTILITY SUBROUTINES
1318 =item check_and_rebuild_fuzzyfiles
1322 sub check_and_rebuild_fuzzyfiles {
1323 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1324 rebuild_fuzzyfiles()
1325 if grep { ! -e "$dir/$_" }
1327 my ($field, $table) = reverse split('\.', $_);
1328 $table ||= 'cust_main';
1334 =item rebuild_fuzzyfiles
1338 sub rebuild_fuzzyfiles {
1340 use Fcntl qw(:flock);
1342 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1343 mkdir $dir, 0700 unless -d $dir;
1345 foreach my $fuzzy ( @fuzzyfields ) {
1347 my ($field, $table) = reverse split('\.', $fuzzy);
1348 $table ||= 'cust_main';
1350 open(LOCK,">>$dir/$table.$field")
1351 or die "can't open $dir/$table.$field: $!";
1353 or die "can't lock $dir/$table.$field: $!";
1355 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1356 or die "can't open $dir/$table.$field.tmp: $!";
1358 my $sth = dbh->prepare(
1359 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1361 $sth->execute or die $sth->errstr;
1363 while ( my $row = $sth->fetchrow_arrayref ) {
1364 print CACHE $row->[0]. "\n";
1367 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1369 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1375 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1379 sub append_fuzzyfiles {
1380 #my( $first, $last, $company ) = @_;
1382 check_and_rebuild_fuzzyfiles();
1384 #foreach my $fuzzy (@fuzzyfields) {
1385 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1386 'cust_location.address1',
1387 'cust_main.ship_company',
1390 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1397 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1399 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1403 use Fcntl qw(:flock);
1404 sub append_fuzzyfiles_fuzzyfield {
1405 my( $fuzzyfield, $value ) = @_;
1407 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1410 my ($field, $table) = reverse split('\.', $fuzzyfield);
1411 $table ||= 'cust_main';
1413 return unless length($value);
1415 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1416 or die "can't open $dir/$table.$field: $!";
1417 flock(CACHE,LOCK_EX)
1418 or die "can't lock $dir/$table.$field: $!";
1420 print CACHE "$value\n";
1422 flock(CACHE,LOCK_UN)
1423 or die "can't unlock $dir/$table.$field: $!";
1433 my( $self, $fuzzy ) = @_;
1434 my ($field, $table) = reverse split('\.', $fuzzy);
1435 $table ||= 'cust_main';
1437 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1438 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1439 or die "can't open $dir/$table.$field: $!";
1440 my @array = map { chomp; $_; } <CACHE>;
1451 L<FS::cust_main>, L<FS::Record>