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
97 push @cust_main, qsearch( {
98 'table' => 'cust_main',
99 'hashref' => { %options },
100 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
102 join(' OR ', map "$_ = '$phonen'",
103 qw( daytime night mobile fax )
106 " AND $agentnums_sql", #agent virtualization
109 #contact phone numbers
111 grep $agentnums_href->{$_->agentnum}, #agent virt
112 grep $_, #skip contacts that don't have cust_main records
113 map $_->contact->cust_main,
115 'table' => 'contact_phone',
116 'hashref' => { 'phonenum' => $phonenum },
119 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
120 #try looking for matches with extensions unless one was specified
122 push @cust_main, qsearch( {
123 'table' => 'cust_main',
124 'hashref' => { %options },
125 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
127 join(' OR ', map "$_ LIKE '$phonen\%'",
131 " AND $agentnums_sql", #agent virtualization
139 if ( $search =~ /@/ ) { #email address
141 # invoicing email address
143 grep $agentnums_href->{$_->agentnum}, #agent virt
146 'table' => 'cust_main_invoice',
147 'hashref' => { 'dest' => $search },
151 # contact email address
153 grep $agentnums_href->{$_->agentnum}, #agent virt
154 grep $_, #skip contacts that don't have cust_main records
155 map $_->contact->cust_main,
157 'table' => 'contact_email',
158 'hashref' => { 'emailaddress' => $search },
162 # custnum search (also try agent_custid), with some tweaking options if your
163 # legacy cust "numbers" have letters
164 } elsif ( $search =~ /^\s*(\d+)\s*$/
165 or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
166 && $search =~ /^\s*(\w\w?\d+)\s*$/
168 or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
169 && $search =~ /^\s*(\d+-\w)\s*$/
171 or ( $conf->config('cust_main-custnum-display_special')
172 # it's not currently possible for special prefixes to contain
173 # digits, so just strip off any alphabetic prefix and match
174 # the rest to custnum
175 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
177 or ( $conf->exists('address1-search' )
178 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
185 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
186 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
187 ? ' AND agent_custid IS NULL ' : '';
188 push @cust_main, qsearch( {
189 'table' => 'cust_main',
190 'hashref' => { 'custnum' => $num, %options },
191 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
195 # for all agents this user can see, if any of them have custnum prefixes
196 # that match the search string, include customers that match the rest
197 # of the custnum and belong to that agent
198 foreach my $agentnum ( keys %$agentnums_href ) {
199 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
201 if ( $p eq substr($num, 0, length($p)) ) {
202 push @cust_main, qsearch( {
203 'table' => 'cust_main',
204 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
205 'agentnum' => $agentnum,
212 push @cust_main, qsearch( {
213 'table' => 'cust_main',
214 'hashref' => { 'agent_custid' => $num, %options },
215 'extra_sql' => " AND $agentnums_sql", #agent virtualization
218 if ( $conf->exists('address1-search') ) {
219 my $len = length($num);
221 # probably the Right Thing: return customers that have any associated
222 # locations matching the string, not just bill/ship location
223 push @cust_main, qsearch( {
224 'select' => 'cust_main.*',
225 'table' => 'cust_main',
226 'addl_from' => ' JOIN cust_location USING (custnum) ',
227 'hashref' => { %options, },
229 ( keys(%options) ? ' AND ' : ' WHERE ' ).
230 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
231 " AND $agentnums_sql",
235 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
237 my($company, $last, $first) = ( $1, $2, $3 );
239 # "Company (Last, First)"
240 #this is probably something a browser remembered,
241 #so just do an exact search (but case-insensitive, so USPS standardization
242 #doesn't throw a wrench in the works)
244 push @cust_main, qsearch( {
245 'table' => 'cust_main',
246 'hashref' => { %options },
248 ( keys(%options) ? ' AND ' : ' WHERE ' ).
250 " LOWER(first) = ". dbh->quote(lc($first)),
251 " LOWER(last) = ". dbh->quote(lc($last)),
252 " LOWER(company) = ". dbh->quote(lc($company)),
258 # probably not necessary for the "something a browser remembered" case
260 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
261 # try {first,last,company}
265 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
266 # # full strings the browser remembers won't work
267 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
269 use Lingua::EN::NameParse;
270 my $NameParse = new Lingua::EN::NameParse(
275 my($last, $first) = ( '', '' );
276 #maybe disable this too and just rely on NameParse?
277 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
279 ($last, $first) = ( $1, $2 );
281 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
282 } elsif ( ! $NameParse->parse($value) ) {
284 my %name = $NameParse->components;
285 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
286 $last = $name{'surname_1'};
290 if ( $first && $last ) {
292 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
295 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
296 $sql .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
299 push @cust_main, qsearch( {
300 'table' => 'cust_main',
301 'hashref' => \%options,
302 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
307 grep $agentnums_href->{$_->agentnum}, #agent virt
308 grep $_, #skip contacts that don't have cust_main records
311 'table' => 'contact',
312 'hashref' => { 'first' => $first,
318 # or it just be something that was typed in... (try that in a sec)
322 my $q_value = dbh->quote($value);
325 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
326 $sql .= " ( LOWER(cust_main.first) = $q_value
327 OR LOWER(cust_main.last) = $q_value
328 OR LOWER(cust_main.company) = $q_value
329 OR LOWER(cust_main.ship_company) = $q_value
332 #address1 (yes, it's a kludge)
333 $sql .= " OR EXISTS (
334 SELECT 1 FROM cust_location
335 WHERE LOWER(cust_location.address1) = $q_value
336 AND cust_location.custnum = cust_main.custnum
338 if $conf->exists('address1-search');
340 #contacts (look, another kludge)
341 $sql .= " OR EXISTS ( SELECT 1 FROM contact
342 WHERE ( LOWER(contact.first) = $q_value
343 OR LOWER(contact.last) = $q_value
345 AND contact.custnum IS NOT NULL
346 AND contact.custnum = cust_main.custnum
350 push @cust_main, qsearch( {
351 'table' => 'cust_main',
352 'hashref' => \%options,
353 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
356 #no exact match, trying substring/fuzzy
357 #always do substring & fuzzy (unless they're explicity config'ed off)
358 #getting complaints searches are not returning enough
359 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
361 #still some false laziness w/search (was search/cust_main.cgi)
364 $FS::CurrentUser::CurrentUser->access_right('List all customers')
369 my @company_hashrefs = ();
370 if ( length($value) >= $min_len ) {
371 @company_hashrefs = (
372 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
373 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
378 if ( $first && $last ) {
381 { 'first' => { op=>'ILIKE', value=>"%$first%" },
382 'last' => { op=>'ILIKE', value=>"%$last%" },
386 } elsif ( length($value) >= $min_len ) {
389 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
390 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
395 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
397 push @cust_main, qsearch( {
398 'table' => 'cust_main',
399 'hashref' => { %$hashref,
402 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
407 if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
409 push @cust_main, qsearch( {
410 table => 'cust_main',
411 addl_from => 'JOIN cust_location USING (custnum)',
412 extra_sql => 'WHERE '.
413 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
414 " AND $agentnums_sql", #agent virtualizaiton
421 foreach my $hashref ( @hashrefs ) {
424 grep $agentnums_href->{$_->agentnum}, #agent virt
425 grep $_, #skip contacts that don't have cust_main records
428 'table' => 'contact',
429 'hashref' => { %$hashref,
432 #'extra_sql' => " AND $agentnums_sql", #agent virt
439 'hashref' => \%options,
441 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
444 if ( $first && $last ) {
445 push @cust_main, FS::cust_main::Search->fuzzy_search(
446 { 'last' => $last, #fuzzy hashref
447 'first' => $first }, #
450 push @cust_main, FS::cust_main::Search->fuzzy_search(
451 { 'contact.last' => $last, #fuzzy hashref
452 'contact.first' => $first }, #
457 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
458 push @cust_main, FS::cust_main::Search->fuzzy_search(
459 { $field => $value },
463 foreach my $field ( 'first', 'last' ) {
464 push @cust_main, FS::cust_main::Search->fuzzy_search(
465 { "contact.$field" => $value },
469 if ( $conf->exists('address1-search') ) {
471 FS::cust_main::Search->fuzzy_search(
472 { 'cust_location.address1' => $value },
481 ( my $nospace_search = $search ) =~ s/\s//g;
482 ( my $card_search = $nospace_search ) =~ s/\-//g;
483 $card_search =~ s/[x\*\.\_]/x/gi;
485 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
487 ( my $like_search = $card_search ) =~ s/x/_/g;
488 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
490 push @cust_main, qsearch({
491 'table' => 'cust_main',
493 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
494 OR paymask = '$mask_search'
496 " AND payby IN ('CARD','DCRD') ".
497 " AND $agentnums_sql", #agent virtulization
503 #eliminate duplicates
505 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
513 Accepts the following options: I<email>, the email address to search for. The
514 email address will be searched for as an email invoice destination and as an
517 #Any additional options are treated as an additional qualifier on the search
520 Returns a (possibly empty) array of FS::cust_main objects (but usually just
528 my $email = delete $options{'email'};
530 #no agent virtualization yet
531 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
535 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
537 my ( $user, $domain ) = ( $1, $2 );
539 warn "$me smart_search: searching for $user in domain $domain"
545 'table' => 'cust_main_invoice',
546 'hashref' => { 'dest' => $email },
553 map $_->cust_svc->cust_pkg,
555 'table' => 'svc_acct',
556 'hashref' => { 'username' => $user, },
558 'AND ( SELECT domain FROM svc_domain
559 WHERE svc_acct.domsvc = svc_domain.svcnum
560 ) = '. dbh->quote($domain),
566 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
568 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
585 Returns a qsearch hash expression to search for parameters specified in
586 HASHREF. Valid parameters are
606 listref of start date, end date
610 listref of start date, end date
612 =item spouse_birthdate
614 listref of start date, end date
616 =item anniversary_date
618 listref of start date, end date
628 =item current_balance
630 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
643 my ($class, $params) = @_;
650 # initialize these to prevent warnings
658 'paydate_year' => '',
659 'invoice_terms' => '',
665 # explicit custnum(s)
668 if ( $params->{'custnum'} ) {
669 my @custnums = ref($params->{'custnum'}) ?
670 @{ $params->{'custnum'} } :
671 $params->{'custnum'};
673 'cust_main.custnum IN (' .
674 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
675 ')' if scalar(@custnums) > 0;
682 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
684 "cust_main.agentnum = $1";
691 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
692 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
693 : 'cust_main.salesnum IS NULL';
700 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
702 "cust_main.usernum = $1";
709 #prospect ordered active inactive suspended cancelled
710 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
711 my $method = $params->{'status'}. '_sql';
712 #push @where, $class->$method();
713 push @where, FS::cust_main->$method();
717 unless ( $params->{location_history} ) {
719 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
720 cust_main.ship_locationnum
722 OR cust_location.locationnum IN (
723 SELECT locationnum FROM cust_pkg
724 WHERE cust_pkg.custnum = cust_main.custnum
725 AND locationnum IS NOT NULL
726 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
734 if ( $params->{'address'} ) {
735 # allow this to be an arrayref
736 my @values = ($params->{'address'});
737 @values = @{$values[0]} if ref($values[0]);
739 foreach (grep /\S/, @values) {
740 my $address = dbh->quote('%'. lc($_). '%');
742 "LOWER(cust_location.address1) LIKE $address",
743 "LOWER(cust_location.address2) LIKE $address";
746 push @where, "EXISTS(
747 SELECT 1 FROM cust_location
748 WHERE cust_location.custnum = cust_main.custnum
749 AND (".join(' OR ',@orwhere).")
758 if ( $params->{'city'} =~ /\S/ ) {
759 my $city = dbh->quote($params->{'city'});
760 push @where, "EXISTS(
761 SELECT 1 FROM cust_location
762 WHERE cust_location.custnum = cust_main.custnum
763 AND cust_location.city = $city
771 if ( $params->{'county'} =~ /\S/ ) {
772 my $county = dbh->quote($params->{'county'});
773 push @where, "EXISTS(
774 SELECT 1 FROM cust_location
775 WHERE cust_location.custnum = cust_main.custnum
776 AND cust_location.county = $county
784 if ( $params->{'state'} =~ /\S/ ) {
785 my $state = dbh->quote($params->{'state'});
786 push @where, "EXISTS(
787 SELECT 1 FROM cust_location
788 WHERE cust_location.custnum = cust_main.custnum
789 AND cust_location.state = $state
797 if ( $params->{'zip'} =~ /\S/ ) {
798 my $zip = dbh->quote($params->{'zip'} . '%');
799 push @where, "EXISTS(
800 SELECT 1 FROM cust_location
801 WHERE cust_location.custnum = cust_main.custnum
802 AND cust_location.zip LIKE $zip
810 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
811 my $country = uc($1);
812 push @where, "EXISTS(
813 SELECT 1 FROM cust_location
814 WHERE cust_location.custnum = cust_main.custnum
815 AND cust_location.country = '$country'
823 if ( $params->{'refnum'} ) {
825 my @refnum = ref( $params->{'refnum'} )
826 ? @{ $params->{'refnum'} }
827 : ( $params->{'refnum'} );
829 @refnum = grep /^(\d*)$/, @refnum;
831 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
837 # parse cancelled package checkbox
842 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
843 unless $params->{'cancelled_pkgs'};
846 # "with email address(es)" checkbox
850 'EXISTS ( SELECT 1 FROM cust_main_invoice
851 WHERE cust_main_invoice.custnum = cust_main.custnum
853 )' # AND dest LIKE '%@%'
854 if $params->{'with_email'};
857 # "with postal mail invoices" checkbox
861 "EXISTS ( SELECT 1 FROM cust_main_invoice
862 WHERE cust_main_invoice.custnum = cust_main.custnum
864 if $params->{'POST'};
867 # "without postal mail invoices" checkbox
871 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
872 WHERE cust_main_invoice.custnum = cust_main.custnum
874 if $params->{'no_POST'};
877 # "tax exempt" checkbox
879 push @where, "cust_main.tax = 'Y'"
883 # "not tax exempt" checkbox
885 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
886 if $params->{'no_tax'};
891 if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
897 if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
898 my $method = $params->{referral_status}. '_sql';
899 $and_status = ' AND '. FS::cust_main->$method();
900 $and_status =~ s/ cust_main\./ referred_cust_main./g;
904 " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
905 WHERE cust_main.custnum = referred_cust_main.referral_custnum
915 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
917 next unless exists($params->{$field});
919 my($beginning, $ending, $hour) = @{$params->{$field}};
922 "cust_main.$field IS NOT NULL",
923 "cust_main.$field >= $beginning",
924 "cust_main.$field <= $ending";
926 if($field eq 'signupdate' && defined $hour) {
927 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
928 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
930 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
931 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
934 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
938 $orderby ||= "ORDER BY cust_main.$field";
946 if ( $params->{'classnum'} ) {
948 my @classnum = ref( $params->{'classnum'} )
949 ? @{ $params->{'classnum'} }
950 : ( $params->{'classnum'} );
952 @classnum = grep /^(\d*)$/, @classnum;
955 push @where, '( '. join(' OR ', map {
956 $_ ? "cust_main.classnum = $_"
957 : "cust_main.classnum IS NULL"
970 if ( $params->{'payby'} ) {
972 my @payby = ref( $params->{'payby'} )
973 ? @{ $params->{'payby'} }
974 : ( $params->{'payby'} );
976 @payby = grep /^([A-Z]{4})$/, @payby;
978 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
984 # paydate_year / paydate_month
987 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
989 $params->{'paydate_month'} =~ /^(\d\d?)$/
990 or die "paydate_year without paydate_month?";
994 'paydate IS NOT NULL',
996 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
1004 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
1006 if ( $1 eq 'NULL' ) {
1008 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
1011 "cust_main.invoice_terms IS NOT NULL",
1012 "cust_main.invoice_terms = '$1'";
1020 if ( $params->{'current_balance'} ) {
1022 #my $balance_sql = $class->balance_sql();
1023 my $balance_sql = FS::cust_main->balance_sql();
1025 my @current_balance =
1026 ref( $params->{'current_balance'} )
1027 ? @{ $params->{'current_balance'} }
1028 : ( $params->{'current_balance'} );
1030 push @where, map { s/current_balance/$balance_sql/; $_ }
1039 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
1041 "cust_main.custbatch = '$1'";
1044 if ( $params->{'tagnum'} ) {
1045 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1047 @tagnums = grep /^(\d+)$/, @tagnums;
1050 if ( $params->{'all_tags'} ) {
1051 foreach ( @tagnums ) {
1052 push @where, 'exists(select 1 from cust_tag where '.
1053 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1056 } else { # matching any tag, not all
1057 my $tags_where = "0 < (select count(1) from cust_tag where "
1058 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1059 . join(',', @tagnums) . "))";
1061 push @where, $tags_where;
1069 if ( $params->{'pkg_classnum'} ) {
1070 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1071 @{ $params->{'pkg_classnum'} } :
1072 $params->{'pkg_classnum'};
1073 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1075 if ( @pkg_classnums ) {
1078 if ( $params->{'all_pkg_classnums'} ) {
1079 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1082 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1084 foreach (@pkg_where) {
1086 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1087 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1088 if ( not $params->{'any_pkg_status'} ) {
1089 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1091 push @where, "EXISTS($select_pkg)";
1097 # setup queries, subs, etc. for the search
1100 $orderby ||= 'ORDER BY custnum';
1102 # here is the agent virtualization
1104 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1106 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1109 # always make address fields available in results
1110 for my $pre ('bill_', 'ship_') {
1112 'LEFT JOIN cust_location AS '.$pre.'location '.
1113 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1116 # always make referral available in results
1117 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1118 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1120 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1123 'cust_main.custnum',
1124 'cust_main.salesnum',
1125 # there's a good chance that we'll need these
1126 'cust_main.bill_locationnum',
1127 'cust_main.ship_locationnum',
1128 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1131 my @extra_headers = ();
1132 my @extra_fields = ();
1133 my @extra_sort_fields = ();
1135 if ($params->{'flattened_pkgs'}) {
1139 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1141 if ($dbh->{Driver}->{Name} eq 'Pg') {
1146 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1147 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1152 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1153 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1154 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1155 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1157 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1158 "omitting package information from report.";
1161 my $header_query = "
1162 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1163 FROM cust_main $addl_from $extra_sql $pkgwhere
1164 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1167 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1168 $sth->execute() or die $sth->errstr;
1169 my $headerrow = $sth->fetchrow_arrayref;
1170 my $headercount = $headerrow ? $headerrow->[0] : 0;
1171 while($headercount) {
1172 unshift @extra_headers, "Package ". $headercount;
1173 unshift @extra_fields, eval q!sub {my $c = shift;
1174 my @a = split '\|', $c->magic;
1175 my $p = $a[!.--$headercount. q!];
1178 unshift @extra_sort_fields, '';
1183 if ( $params->{'with_referrals'} ) {
1185 #XXX next: num for each customer status
1188 '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1189 WHERE cust_main.custnum = referred_cust_main.referral_custnum
1190 ) AS num_referrals';
1192 unshift @extra_headers, 'Referrals';
1193 unshift @extra_fields, 'num_referrals';
1194 unshift @extra_sort_fields, 'num_referrals';
1198 my $select = join(', ', @select);
1201 'table' => 'cust_main',
1202 'select' => $select,
1203 'addl_from' => $addl_from,
1205 'extra_sql' => $extra_sql,
1206 'order_by' => $orderby,
1207 'count_query' => $count_query,
1208 'extra_headers' => \@extra_headers,
1209 'extra_fields' => \@extra_fields,
1210 'extra_sort_fields' => \@extra_sort_fields,
1212 #warn Data::Dumper::Dumper($sql_query);
1217 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1219 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1220 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1223 Additional options are the same as FS::Record::qsearch
1230 # sensible defaults, then merge in any passed options
1232 'table' => 'cust_main',
1241 my @fuzzy_mod = 'i';
1242 my $conf = new FS::Conf;
1243 my $fuzziness = $conf->config('fuzzy-fuzziness');
1244 push @fuzzy_mod, $fuzziness if $fuzziness;
1246 check_and_rebuild_fuzzyfiles();
1247 foreach my $field ( keys %$fuzzy ) {
1249 my $all = $self->all_X($field);
1250 next unless scalar(@$all);
1253 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1254 next if !keys(%match);
1256 my $in_matches = 'IN (' .
1257 join(',', map { dbh->quote($_) } keys %match) .
1260 my $extra_sql = $fuzopts{extra_sql};
1261 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1262 $extra_sql .= ' AND ';
1264 $extra_sql .= 'WHERE ';
1266 $extra_sql .= "$field $in_matches";
1268 my $addl_from = $fuzopts{addl_from};
1269 if ( $field =~ /^cust_location\./ ) {
1270 $addl_from .= ' JOIN cust_location USING (custnum)';
1271 } elsif ( $field =~ /^contact\./ ) {
1272 $addl_from .= ' JOIN contact USING (custnum)';
1275 push @cust_main, qsearch({
1277 'addl_from' => $addl_from,
1278 'extra_sql' => $extra_sql,
1282 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1284 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1292 =head1 UTILITY SUBROUTINES
1296 =item check_and_rebuild_fuzzyfiles
1300 sub check_and_rebuild_fuzzyfiles {
1301 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1302 rebuild_fuzzyfiles()
1303 if grep { ! -e "$dir/$_" }
1305 my ($field, $table) = reverse split('\.', $_);
1306 $table ||= 'cust_main';
1312 =item rebuild_fuzzyfiles
1316 sub rebuild_fuzzyfiles {
1318 use Fcntl qw(:flock);
1320 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1321 mkdir $dir, 0700 unless -d $dir;
1323 foreach my $fuzzy ( @fuzzyfields ) {
1325 my ($field, $table) = reverse split('\.', $fuzzy);
1326 $table ||= 'cust_main';
1328 open(LOCK,">>$dir/$table.$field")
1329 or die "can't open $dir/$table.$field: $!";
1331 or die "can't lock $dir/$table.$field: $!";
1333 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1334 or die "can't open $dir/$table.$field.tmp: $!";
1336 my $sth = dbh->prepare(
1337 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1339 $sth->execute or die $sth->errstr;
1341 while ( my $row = $sth->fetchrow_arrayref ) {
1342 print CACHE $row->[0]. "\n";
1345 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1347 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1353 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1357 sub append_fuzzyfiles {
1358 #my( $first, $last, $company ) = @_;
1360 check_and_rebuild_fuzzyfiles();
1362 #foreach my $fuzzy (@fuzzyfields) {
1363 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1364 'cust_location.address1',
1365 'cust_main.ship_company',
1368 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1375 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1377 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1381 use Fcntl qw(:flock);
1382 sub append_fuzzyfiles_fuzzyfield {
1383 my( $fuzzyfield, $value ) = @_;
1385 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1388 my ($field, $table) = reverse split('\.', $fuzzyfield);
1389 $table ||= 'cust_main';
1391 return unless length($value);
1393 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1394 or die "can't open $dir/$table.$field: $!";
1395 flock(CACHE,LOCK_EX)
1396 or die "can't lock $dir/$table.$field: $!";
1398 print CACHE "$value\n";
1400 flock(CACHE,LOCK_UN)
1401 or die "can't unlock $dir/$table.$field: $!";
1411 my( $self, $fuzzy ) = @_;
1412 my ($field, $table) = reverse split('\.', $fuzzy);
1413 $table ||= 'cust_main';
1415 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1416 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1417 or die "can't open $dir/$table.$field: $!";
1418 my @array = map { chomp; $_; } <CACHE>;
1429 L<FS::cust_main>, L<FS::Record>