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 select => 'cust_main.*',
411 table => 'cust_main',
412 addl_from => 'JOIN cust_location USING (custnum)',
413 extra_sql => 'WHERE '.
414 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
415 " AND $agentnums_sql", #agent virtualizaiton
422 foreach my $hashref ( @hashrefs ) {
425 grep $agentnums_href->{$_->agentnum}, #agent virt
426 grep $_, #skip contacts that don't have cust_main records
429 'table' => 'contact',
430 'hashref' => { %$hashref,
433 #'extra_sql' => " AND $agentnums_sql", #agent virt
440 'hashref' => \%options,
442 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
445 if ( $first && $last ) {
446 push @cust_main, FS::cust_main::Search->fuzzy_search(
447 { 'last' => $last, #fuzzy hashref
448 'first' => $first }, #
451 push @cust_main, FS::cust_main::Search->fuzzy_search(
452 { 'contact.last' => $last, #fuzzy hashref
453 'contact.first' => $first }, #
458 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
459 push @cust_main, FS::cust_main::Search->fuzzy_search(
460 { $field => $value },
464 foreach my $field ( 'first', 'last' ) {
465 push @cust_main, FS::cust_main::Search->fuzzy_search(
466 { "contact.$field" => $value },
470 if ( $conf->exists('address1-search') ) {
472 FS::cust_main::Search->fuzzy_search(
473 { 'cust_location.address1' => $value },
482 ( my $nospace_search = $search ) =~ s/\s//g;
483 ( my $card_search = $nospace_search ) =~ s/\-//g;
484 $card_search =~ s/[x\*\.\_]/x/gi;
486 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
488 ( my $like_search = $card_search ) =~ s/x/_/g;
489 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
491 push @cust_main, qsearch({
492 'table' => 'cust_main',
494 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
495 OR paymask = '$mask_search'
497 " AND payby IN ('CARD','DCRD') ".
498 " AND $agentnums_sql", #agent virtulization
504 #eliminate duplicates
506 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
514 Accepts the following options: I<email>, the email address to search for. The
515 email address will be searched for as an email invoice destination and as an
518 #Any additional options are treated as an additional qualifier on the search
521 Returns a (possibly empty) array of FS::cust_main objects (but usually just
529 my $email = delete $options{'email'};
531 #no agent virtualization yet
532 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
536 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
538 my ( $user, $domain ) = ( $1, $2 );
540 warn "$me smart_search: searching for $user in domain $domain"
546 'table' => 'cust_main_invoice',
547 'hashref' => { 'dest' => $email },
554 map $_->cust_svc->cust_pkg,
556 'table' => 'svc_acct',
557 'hashref' => { 'username' => $user, },
559 'AND ( SELECT domain FROM svc_domain
560 WHERE svc_acct.domsvc = svc_domain.svcnum
561 ) = '. dbh->quote($domain),
567 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
569 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
586 Returns a qsearch hash expression to search for parameters specified in
587 HASHREF. Valid parameters are
607 listref of start date, end date
611 listref of start date, end date
613 =item spouse_birthdate
615 listref of start date, end date
617 =item anniversary_date
619 listref of start date, end date
629 =item current_balance
631 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
644 my ($class, $params) = @_;
651 # initialize these to prevent warnings
659 'paydate_year' => '',
660 'invoice_terms' => '',
666 # explicit custnum(s)
669 if ( $params->{'custnum'} ) {
670 my @custnums = ref($params->{'custnum'}) ?
671 @{ $params->{'custnum'} } :
672 $params->{'custnum'};
674 'cust_main.custnum IN (' .
675 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
676 ')' if scalar(@custnums) > 0;
683 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
685 "cust_main.agentnum = $1";
692 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
693 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
694 : 'cust_main.salesnum IS NULL';
701 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
703 "cust_main.usernum = $1";
710 #prospect ordered active inactive suspended cancelled
711 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
712 my $method = $params->{'status'}. '_sql';
713 #push @where, $class->$method();
714 push @where, FS::cust_main->$method();
718 unless ( $params->{location_history} ) {
720 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
721 cust_main.ship_locationnum
723 OR cust_location.locationnum IN (
724 SELECT locationnum FROM cust_pkg
725 WHERE cust_pkg.custnum = cust_main.custnum
726 AND locationnum IS NOT NULL
727 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
735 if ( $params->{'address'} ) {
736 # allow this to be an arrayref
737 my @values = ($params->{'address'});
738 @values = @{$values[0]} if ref($values[0]);
740 foreach (grep /\S/, @values) {
741 my $address = dbh->quote('%'. lc($_). '%');
743 "LOWER(cust_location.address1) LIKE $address",
744 "LOWER(cust_location.address2) LIKE $address";
747 push @where, "EXISTS(
748 SELECT 1 FROM cust_location
749 WHERE cust_location.custnum = cust_main.custnum
750 AND (".join(' OR ',@orwhere).")
759 if ( $params->{'city'} =~ /\S/ ) {
760 my $city = dbh->quote($params->{'city'});
761 push @where, "EXISTS(
762 SELECT 1 FROM cust_location
763 WHERE cust_location.custnum = cust_main.custnum
764 AND cust_location.city = $city
772 if ( $params->{'county'} =~ /\S/ ) {
773 my $county = dbh->quote($params->{'county'});
774 push @where, "EXISTS(
775 SELECT 1 FROM cust_location
776 WHERE cust_location.custnum = cust_main.custnum
777 AND cust_location.county = $county
785 if ( $params->{'state'} =~ /\S/ ) {
786 my $state = dbh->quote($params->{'state'});
787 push @where, "EXISTS(
788 SELECT 1 FROM cust_location
789 WHERE cust_location.custnum = cust_main.custnum
790 AND cust_location.state = $state
798 if ( $params->{'zip'} =~ /\S/ ) {
799 my $zip = dbh->quote($params->{'zip'} . '%');
800 push @where, "EXISTS(
801 SELECT 1 FROM cust_location
802 WHERE cust_location.custnum = cust_main.custnum
803 AND cust_location.zip LIKE $zip
811 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
812 my $country = uc($1);
813 push @where, "EXISTS(
814 SELECT 1 FROM cust_location
815 WHERE cust_location.custnum = cust_main.custnum
816 AND cust_location.country = '$country'
824 if ( $params->{'refnum'} ) {
826 my @refnum = ref( $params->{'refnum'} )
827 ? @{ $params->{'refnum'} }
828 : ( $params->{'refnum'} );
830 @refnum = grep /^(\d*)$/, @refnum;
832 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
838 # parse cancelled package checkbox
843 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
844 unless $params->{'cancelled_pkgs'};
847 # "with email address(es)" checkbox
851 'EXISTS ( SELECT 1 FROM cust_main_invoice
852 WHERE cust_main_invoice.custnum = cust_main.custnum
854 )' # AND dest LIKE '%@%'
855 if $params->{'with_email'};
858 # "with postal mail invoices" checkbox
862 "EXISTS ( SELECT 1 FROM cust_main_invoice
863 WHERE cust_main_invoice.custnum = cust_main.custnum
865 if $params->{'POST'};
868 # "without postal mail invoices" checkbox
872 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
873 WHERE cust_main_invoice.custnum = cust_main.custnum
875 if $params->{'no_POST'};
878 # "tax exempt" checkbox
880 push @where, "cust_main.tax = 'Y'"
884 # "not tax exempt" checkbox
886 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
887 if $params->{'no_tax'};
892 if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
898 if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
899 my $method = $params->{referral_status}. '_sql';
900 $and_status = ' AND '. FS::cust_main->$method();
901 $and_status =~ s/ cust_main\./ referred_cust_main./g;
905 " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
906 WHERE cust_main.custnum = referred_cust_main.referral_custnum
916 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
918 next unless exists($params->{$field});
920 my($beginning, $ending, $hour) = @{$params->{$field}};
923 "cust_main.$field IS NOT NULL",
924 "cust_main.$field >= $beginning",
925 "cust_main.$field <= $ending";
927 if($field eq 'signupdate' && defined $hour) {
928 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
929 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
931 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
932 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
935 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
939 $orderby ||= "ORDER BY cust_main.$field";
947 if ( $params->{'classnum'} ) {
949 my @classnum = ref( $params->{'classnum'} )
950 ? @{ $params->{'classnum'} }
951 : ( $params->{'classnum'} );
953 @classnum = grep /^(\d*)$/, @classnum;
956 push @where, '( '. join(' OR ', map {
957 $_ ? "cust_main.classnum = $_"
958 : "cust_main.classnum IS NULL"
971 if ( $params->{'payby'} ) {
973 my @payby = ref( $params->{'payby'} )
974 ? @{ $params->{'payby'} }
975 : ( $params->{'payby'} );
977 @payby = grep /^([A-Z]{4})$/, @payby;
979 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
985 # paydate_year / paydate_month
988 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
990 $params->{'paydate_month'} =~ /^(\d\d?)$/
991 or die "paydate_year without paydate_month?";
995 'paydate IS NOT NULL',
997 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
1005 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
1007 if ( $1 eq 'NULL' ) {
1009 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
1012 "cust_main.invoice_terms IS NOT NULL",
1013 "cust_main.invoice_terms = '$1'";
1021 if ( $params->{'current_balance'} ) {
1023 #my $balance_sql = $class->balance_sql();
1024 my $balance_sql = FS::cust_main->balance_sql();
1026 my @current_balance =
1027 ref( $params->{'current_balance'} )
1028 ? @{ $params->{'current_balance'} }
1029 : ( $params->{'current_balance'} );
1031 push @where, map { s/current_balance/$balance_sql/; $_ }
1040 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
1042 "cust_main.custbatch = '$1'";
1045 if ( $params->{'tagnum'} ) {
1046 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1048 @tagnums = grep /^(\d+)$/, @tagnums;
1051 if ( $params->{'all_tags'} ) {
1052 my $exists = $params->{'all_tags'} eq 'all' ? 'exists' : 'not exists';
1053 foreach ( @tagnums ) {
1054 push @where, $exists.'(select 1 from cust_tag where '.
1055 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1058 } else { # matching any tag, not all
1059 my $tags_where = "0 < (select count(1) from cust_tag where "
1060 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1061 . join(',', @tagnums) . "))";
1063 push @where, $tags_where;
1071 if ( $params->{'pkg_classnum'} ) {
1072 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1073 @{ $params->{'pkg_classnum'} } :
1074 $params->{'pkg_classnum'};
1075 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1077 if ( @pkg_classnums ) {
1080 if ( $params->{'all_pkg_classnums'} ) {
1081 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1084 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1086 foreach (@pkg_where) {
1088 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1089 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1090 if ( not $params->{'any_pkg_status'} ) {
1091 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1093 push @where, "EXISTS($select_pkg)";
1099 # setup queries, subs, etc. for the search
1102 $orderby ||= 'ORDER BY custnum';
1104 # here is the agent virtualization
1106 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1108 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1111 # always make address fields available in results
1112 for my $pre ('bill_', 'ship_') {
1114 'LEFT JOIN cust_location AS '.$pre.'location '.
1115 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1118 # always make referral available in results
1119 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1120 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1122 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1125 'cust_main.custnum',
1126 'cust_main.salesnum',
1127 # there's a good chance that we'll need these
1128 'cust_main.bill_locationnum',
1129 'cust_main.ship_locationnum',
1130 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1133 my @extra_headers = ();
1134 my @extra_fields = ();
1135 my @extra_sort_fields = ();
1137 if ($params->{'flattened_pkgs'}) {
1141 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1143 if ($dbh->{Driver}->{Name} eq 'Pg') {
1148 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1149 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1154 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1155 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1156 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1157 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1159 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1160 "omitting package information from report.";
1163 my $header_query = "
1164 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1165 FROM cust_main $addl_from $extra_sql $pkgwhere
1166 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1169 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1170 $sth->execute() or die $sth->errstr;
1171 my $headerrow = $sth->fetchrow_arrayref;
1172 my $headercount = $headerrow ? $headerrow->[0] : 0;
1173 while($headercount) {
1174 unshift @extra_headers, "Package ". $headercount;
1175 unshift @extra_fields, eval q!sub {my $c = shift;
1176 my @a = split '\|', $c->magic;
1177 my $p = $a[!.--$headercount. q!];
1180 unshift @extra_sort_fields, '';
1185 if ( $params->{'with_referrals'} ) {
1187 #XXX next: num for each customer status
1190 '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1191 WHERE cust_main.custnum = referred_cust_main.referral_custnum
1192 ) AS num_referrals';
1194 unshift @extra_headers, 'Referrals';
1195 unshift @extra_fields, 'num_referrals';
1196 unshift @extra_sort_fields, 'num_referrals';
1200 my $select = join(', ', @select);
1203 'table' => 'cust_main',
1204 'select' => $select,
1205 'addl_from' => $addl_from,
1207 'extra_sql' => $extra_sql,
1208 'order_by' => $orderby,
1209 'count_query' => $count_query,
1210 'extra_headers' => \@extra_headers,
1211 'extra_fields' => \@extra_fields,
1212 'extra_sort_fields' => \@extra_sort_fields,
1214 #warn Data::Dumper::Dumper($sql_query);
1219 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1221 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1222 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1225 Additional options are the same as FS::Record::qsearch
1232 # sensible defaults, then merge in any passed options
1234 'table' => 'cust_main',
1243 my @fuzzy_mod = 'i';
1244 my $conf = new FS::Conf;
1245 my $fuzziness = $conf->config('fuzzy-fuzziness');
1246 push @fuzzy_mod, $fuzziness if $fuzziness;
1248 check_and_rebuild_fuzzyfiles();
1249 foreach my $field ( keys %$fuzzy ) {
1251 my $all = $self->all_X($field);
1252 next unless scalar(@$all);
1255 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1256 next if !keys(%match);
1258 my $in_matches = 'IN (' .
1259 join(',', map { dbh->quote($_) } keys %match) .
1262 my $extra_sql = $fuzopts{extra_sql};
1263 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1264 $extra_sql .= ' AND ';
1266 $extra_sql .= 'WHERE ';
1268 $extra_sql .= "$field $in_matches";
1270 my $addl_from = $fuzopts{addl_from};
1271 if ( $field =~ /^cust_location\./ ) {
1272 $addl_from .= ' JOIN cust_location USING (custnum)';
1273 } elsif ( $field =~ /^contact\./ ) {
1274 $addl_from .= ' JOIN contact USING (custnum)';
1277 push @cust_main, qsearch({
1279 'addl_from' => $addl_from,
1280 'extra_sql' => $extra_sql,
1284 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1286 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1294 =head1 UTILITY SUBROUTINES
1298 =item check_and_rebuild_fuzzyfiles
1302 sub check_and_rebuild_fuzzyfiles {
1303 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1304 rebuild_fuzzyfiles()
1305 if grep { ! -e "$dir/$_" }
1307 my ($field, $table) = reverse split('\.', $_);
1308 $table ||= 'cust_main';
1314 =item rebuild_fuzzyfiles
1318 sub rebuild_fuzzyfiles {
1320 use Fcntl qw(:flock);
1322 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1323 mkdir $dir, 0700 unless -d $dir;
1325 foreach my $fuzzy ( @fuzzyfields ) {
1327 my ($field, $table) = reverse split('\.', $fuzzy);
1328 $table ||= 'cust_main';
1330 open(LOCK,">>$dir/$table.$field")
1331 or die "can't open $dir/$table.$field: $!";
1333 or die "can't lock $dir/$table.$field: $!";
1335 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1336 or die "can't open $dir/$table.$field.tmp: $!";
1338 my $sth = dbh->prepare(
1339 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1341 $sth->execute or die $sth->errstr;
1343 while ( my $row = $sth->fetchrow_arrayref ) {
1344 print CACHE $row->[0]. "\n";
1347 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1349 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1355 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1359 sub append_fuzzyfiles {
1360 #my( $first, $last, $company ) = @_;
1362 check_and_rebuild_fuzzyfiles();
1364 #foreach my $fuzzy (@fuzzyfields) {
1365 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1366 'cust_location.address1',
1367 'cust_main.ship_company',
1370 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1377 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1379 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1383 use Fcntl qw(:flock);
1384 sub append_fuzzyfiles_fuzzyfield {
1385 my( $fuzzyfield, $value ) = @_;
1387 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1390 my ($field, $table) = reverse split('\.', $fuzzyfield);
1391 $table ||= 'cust_main';
1393 return unless length($value);
1395 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1396 or die "can't open $dir/$table.$field: $!";
1397 flock(CACHE,LOCK_EX)
1398 or die "can't lock $dir/$table.$field: $!";
1400 print CACHE "$value\n";
1402 flock(CACHE,LOCK_UN)
1403 or die "can't unlock $dir/$table.$field: $!";
1413 my( $self, $fuzzy ) = @_;
1414 my ($field, $table) = reverse split('\.', $fuzzy);
1415 $table ||= 'cust_main';
1417 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1418 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1419 or die "can't open $dir/$table.$field: $!";
1420 my @array = map { chomp; $_; } <CACHE>;
1431 L<FS::cust_main>, L<FS::Record>