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 'table' => 'cust_main',
225 'addl_from' => ' JOIN cust_location USING (custnum) ',
226 'hashref' => { %options, },
228 ( keys(%options) ? ' AND ' : ' WHERE ' ).
229 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
230 " AND $agentnums_sql",
234 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
236 my($company, $last, $first) = ( $1, $2, $3 );
238 # "Company (Last, First)"
239 #this is probably something a browser remembered,
240 #so just do an exact search (but case-insensitive, so USPS standardization
241 #doesn't throw a wrench in the works)
243 push @cust_main, qsearch( {
244 'table' => 'cust_main',
245 'hashref' => { %options },
247 ( keys(%options) ? ' AND ' : ' WHERE ' ).
249 " LOWER(first) = ". dbh->quote(lc($first)),
250 " LOWER(last) = ". dbh->quote(lc($last)),
251 " LOWER(company) = ". dbh->quote(lc($company)),
257 # probably not necessary for the "something a browser remembered" case
259 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
260 # try {first,last,company}
264 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
265 # # full strings the browser remembers won't work
266 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
268 use Lingua::EN::NameParse;
269 my $NameParse = new Lingua::EN::NameParse(
274 my($last, $first) = ( '', '' );
275 #maybe disable this too and just rely on NameParse?
276 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
278 ($last, $first) = ( $1, $2 );
280 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
281 } elsif ( ! $NameParse->parse($value) ) {
283 my %name = $NameParse->components;
284 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
285 $last = $name{'surname_1'};
289 if ( $first && $last ) {
291 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
294 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
295 $sql .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
298 push @cust_main, qsearch( {
299 'table' => 'cust_main',
300 'hashref' => \%options,
301 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
306 grep $agentnums_href->{$_->agentnum}, #agent virt
307 grep $_, #skip contacts that don't have cust_main records
310 'table' => 'contact',
311 'hashref' => { 'first' => $first,
317 # or it just be something that was typed in... (try that in a sec)
321 my $q_value = dbh->quote($value);
324 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
325 $sql .= " ( LOWER(cust_main.first) = $q_value
326 OR LOWER(cust_main.last) = $q_value
327 OR LOWER(cust_main.company) = $q_value
328 OR LOWER(cust_main.ship_company) = $q_value
331 #address1 (yes, it's a kludge)
332 $sql .= " OR EXISTS (
333 SELECT 1 FROM cust_location
334 WHERE LOWER(cust_location.address1) = $q_value
335 AND cust_location.custnum = cust_main.custnum
337 if $conf->exists('address1-search');
339 #contacts (look, another kludge)
340 $sql .= " OR EXISTS ( SELECT 1 FROM contact
341 WHERE ( LOWER(contact.first) = $q_value
342 OR LOWER(contact.last) = $q_value
344 AND contact.custnum IS NOT NULL
345 AND contact.custnum = cust_main.custnum
349 push @cust_main, qsearch( {
350 'table' => 'cust_main',
351 'hashref' => \%options,
352 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
355 #no exact match, trying substring/fuzzy
356 #always do substring & fuzzy (unless they're explicity config'ed off)
357 #getting complaints searches are not returning enough
358 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
360 #still some false laziness w/search (was search/cust_main.cgi)
363 $FS::CurrentUser::CurrentUser->access_right('List all customers')
368 my @company_hashrefs = ();
369 if ( length($value) >= $min_len ) {
370 @company_hashrefs = (
371 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
372 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
377 if ( $first && $last ) {
380 { 'first' => { op=>'ILIKE', value=>"%$first%" },
381 'last' => { op=>'ILIKE', value=>"%$last%" },
385 } elsif ( length($value) >= $min_len ) {
388 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
389 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
394 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
396 push @cust_main, qsearch( {
397 'table' => 'cust_main',
398 'hashref' => { %$hashref,
401 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
406 if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
408 push @cust_main, qsearch( {
409 table => 'cust_main',
410 addl_from => 'JOIN cust_location USING (custnum)',
411 extra_sql => 'WHERE '.
412 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
413 " AND $agentnums_sql", #agent virtualizaiton
420 foreach my $hashref ( @hashrefs ) {
423 grep $agentnums_href->{$_->agentnum}, #agent virt
424 grep $_, #skip contacts that don't have cust_main records
427 'table' => 'contact',
428 'hashref' => { %$hashref,
431 #'extra_sql' => " AND $agentnums_sql", #agent virt
438 'hashref' => \%options,
440 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
443 if ( $first && $last ) {
444 push @cust_main, FS::cust_main::Search->fuzzy_search(
445 { 'last' => $last, #fuzzy hashref
446 'first' => $first }, #
449 push @cust_main, FS::cust_main::Search->fuzzy_search(
450 { 'contact.last' => $last, #fuzzy hashref
451 'contact.first' => $first }, #
456 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
457 push @cust_main, FS::cust_main::Search->fuzzy_search(
458 { $field => $value },
462 foreach my $field ( 'first', 'last' ) {
463 push @cust_main, FS::cust_main::Search->fuzzy_search(
464 { "contact.$field" => $value },
468 if ( $conf->exists('address1-search') ) {
470 FS::cust_main::Search->fuzzy_search(
471 { 'cust_location.address1' => $value },
480 ( my $nospace_search = $search ) =~ s/\s//g;
481 ( my $card_search = $nospace_search ) =~ s/\-//g;
482 $card_search =~ s/[x\*\.\_]/x/gi;
484 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
486 ( my $like_search = $card_search ) =~ s/x/_/g;
487 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
489 push @cust_main, qsearch({
490 'table' => 'cust_main',
491 'addl_from' => ' JOIN cust_payby USING (custnum)',
493 'extra_sql' => " WHERE ( cust_payby.payinfo LIKE '$like_search'
494 OR cust_payby.paymask = '$mask_search'
496 " AND cust_payby.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"
543 map { $_->cust_main }
544 map { $_->cust_contact }
547 'table' => 'contact_email',
548 'hashref' => { 'emailaddress' => $email },
555 map $_->cust_svc->cust_pkg,
557 'table' => 'svc_acct',
558 'hashref' => { 'username' => $user, },
560 'AND ( SELECT domain FROM svc_domain
561 WHERE svc_acct.domsvc = svc_domain.svcnum
562 ) = '. dbh->quote($domain),
568 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
570 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
587 Returns a qsearch hash expression to search for parameters specified in
588 HASHREF. Valid parameters are
608 listref of start date, end date
612 listref of start date, end date
614 =item spouse_birthdate
616 listref of start date, end date
618 =item anniversary_date
620 listref of start date, end date
622 =item current_balance
624 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
637 my ($class, $params) = @_;
644 # initialize these to prevent warnings
652 'invoice_terms' => '',
658 # explicit custnum(s)
661 if ( $params->{'custnum'} ) {
662 my @custnums = ref($params->{'custnum'}) ?
663 @{ $params->{'custnum'} } :
664 $params->{'custnum'};
666 'cust_main.custnum IN (' .
667 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
668 ')' if scalar(@custnums) > 0;
675 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
677 "cust_main.agentnum = $1";
684 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
685 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
686 : 'cust_main.salesnum IS NULL';
693 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
695 "cust_main.usernum = $1";
702 #prospect ordered active inactive suspended cancelled
703 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
704 my $method = $params->{'status'}. '_sql';
705 #push @where, $class->$method();
706 push @where, FS::cust_main->$method();
710 unless ( $params->{location_history} ) {
712 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
713 cust_main.ship_locationnum
715 OR cust_location.locationnum IN (
716 SELECT locationnum FROM cust_pkg
717 WHERE cust_pkg.custnum = cust_main.custnum
718 AND locationnum IS NOT NULL
719 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
727 if ( $params->{'address'} ) {
728 # allow this to be an arrayref
729 my @values = ($params->{'address'});
730 @values = @{$values[0]} if ref($values[0]);
732 foreach (grep /\S/, @values) {
733 my $address = dbh->quote('%'. lc($_). '%');
735 "LOWER(cust_location.address1) LIKE $address",
736 "LOWER(cust_location.address2) LIKE $address";
739 push @where, "EXISTS(
740 SELECT 1 FROM cust_location
741 WHERE cust_location.custnum = cust_main.custnum
742 AND (".join(' OR ',@orwhere).")
751 if ( $params->{'city'} =~ /\S/ ) {
752 my $city = dbh->quote($params->{'city'});
753 push @where, "EXISTS(
754 SELECT 1 FROM cust_location
755 WHERE cust_location.custnum = cust_main.custnum
756 AND cust_location.city = $city
764 if ( $params->{'county'} =~ /\S/ ) {
765 my $county = dbh->quote($params->{'county'});
766 push @where, "EXISTS(
767 SELECT 1 FROM cust_location
768 WHERE cust_location.custnum = cust_main.custnum
769 AND cust_location.county = $county
777 if ( $params->{'state'} =~ /\S/ ) {
778 my $state = dbh->quote($params->{'state'});
779 push @where, "EXISTS(
780 SELECT 1 FROM cust_location
781 WHERE cust_location.custnum = cust_main.custnum
782 AND cust_location.state = $state
790 if ( $params->{'zip'} =~ /\S/ ) {
791 my $zip = dbh->quote($params->{'zip'} . '%');
792 push @where, "EXISTS(
793 SELECT 1 FROM cust_location
794 WHERE cust_location.custnum = cust_main.custnum
795 AND cust_location.zip LIKE $zip
803 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
804 my $country = uc($1);
805 push @where, "EXISTS(
806 SELECT 1 FROM cust_location
807 WHERE cust_location.custnum = cust_main.custnum
808 AND cust_location.country = '$country'
816 if ( $params->{'refnum'} ) {
818 my @refnum = ref( $params->{'refnum'} )
819 ? @{ $params->{'refnum'} }
820 : ( $params->{'refnum'} );
822 @refnum = grep /^(\d*)$/, @refnum;
824 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
830 # parse cancelled package checkbox
835 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
836 unless $params->{'cancelled_pkgs'};
839 # "with email address(es)" checkbox
843 'EXISTS ( SELECT 1 FROM contact_email
844 JOIN cust_contact USING (contactnum)
845 WHERE cust_contact.custnum = cust_main.custnum
847 if $params->{'with_email'};
850 # "with postal mail invoices" checkbox
853 push @where, "cust_main.postal_invoice = 'Y'"
854 if $params->{'POST'};
857 # "without postal mail invoices" checkbox
860 push @where, "cust_main.postal_invoice IS NULL"
861 if $params->{'no_POST'};
864 # "tax exempt" checkbox
866 push @where, "cust_main.tax = 'Y'"
870 # "not tax exempt" checkbox
872 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
873 if $params->{'no_tax'};
878 if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
884 if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
885 my $method = $params->{referral_status}. '_sql';
886 $and_status = ' AND '. FS::cust_main->$method();
887 $and_status =~ s/ cust_main\./ referred_cust_main./g;
891 " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
892 WHERE cust_main.custnum = referred_cust_main.referral_custnum
902 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
904 next unless exists($params->{$field});
906 my($beginning, $ending, $hour) = @{$params->{$field}};
909 "cust_main.$field IS NOT NULL",
910 "cust_main.$field >= $beginning",
911 "cust_main.$field <= $ending";
913 if($field eq 'signupdate' && defined $hour) {
914 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
915 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
917 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
918 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
921 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
925 $orderby ||= "ORDER BY cust_main.$field";
933 if ( $params->{'classnum'} ) {
935 my @classnum = ref( $params->{'classnum'} )
936 ? @{ $params->{'classnum'} }
937 : ( $params->{'classnum'} );
939 @classnum = grep /^(\d*)$/, @classnum;
942 push @where, '( '. join(' OR ', map {
943 $_ ? "cust_main.classnum = $_"
944 : "cust_main.classnum IS NULL"
957 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
959 if ( $1 eq 'NULL' ) {
961 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
964 "cust_main.invoice_terms IS NOT NULL",
965 "cust_main.invoice_terms = '$1'";
973 if ( $params->{'current_balance'} ) {
975 #my $balance_sql = $class->balance_sql();
976 my $balance_sql = FS::cust_main->balance_sql();
978 my @current_balance =
979 ref( $params->{'current_balance'} )
980 ? @{ $params->{'current_balance'} }
981 : ( $params->{'current_balance'} );
983 push @where, map { s/current_balance/$balance_sql/; $_ }
992 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
994 "cust_main.custbatch = '$1'";
997 if ( $params->{'tagnum'} ) {
998 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1000 @tagnums = grep /^(\d+)$/, @tagnums;
1003 if ( $params->{'all_tags'} ) {
1004 foreach ( @tagnums ) {
1005 push @where, 'exists(select 1 from cust_tag where '.
1006 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1009 } else { # matching any tag, not all
1010 my $tags_where = "0 < (select count(1) from cust_tag where "
1011 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1012 . join(',', @tagnums) . "))";
1014 push @where, $tags_where;
1022 if ( $params->{'pkg_classnum'} ) {
1023 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1024 @{ $params->{'pkg_classnum'} } :
1025 $params->{'pkg_classnum'};
1026 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1028 if ( @pkg_classnums ) {
1031 if ( $params->{'all_pkg_classnums'} ) {
1032 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1035 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1037 foreach (@pkg_where) {
1039 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1040 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1041 if ( not $params->{'any_pkg_status'} ) {
1042 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1044 push @where, "EXISTS($select_pkg)";
1050 # setup queries, subs, etc. for the search
1053 $orderby ||= 'ORDER BY custnum';
1055 # here is the agent virtualization
1057 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1059 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1062 # always make address fields available in results
1063 for my $pre ('bill_', 'ship_') {
1065 'LEFT JOIN cust_location AS '.$pre.'location '.
1066 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1069 # always make referral available in results
1070 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1071 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1073 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1076 'cust_main.custnum',
1077 'cust_main.salesnum',
1078 # there's a good chance that we'll need these
1079 'cust_main.bill_locationnum',
1080 'cust_main.ship_locationnum',
1081 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1084 my @extra_headers = ();
1085 my @extra_fields = ();
1086 my @extra_sort_fields = ();
1088 if ($params->{'flattened_pkgs'}) {
1092 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1094 if ($dbh->{Driver}->{Name} eq 'Pg') {
1099 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1100 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1105 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1106 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1107 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1108 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1110 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1111 "omitting package information from report.";
1114 my $header_query = "
1115 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1116 FROM cust_main $addl_from $extra_sql $pkgwhere
1117 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1120 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1121 $sth->execute() or die $sth->errstr;
1122 my $headerrow = $sth->fetchrow_arrayref;
1123 my $headercount = $headerrow ? $headerrow->[0] : 0;
1124 while($headercount) {
1125 unshift @extra_headers, "Package ". $headercount;
1126 unshift @extra_fields, eval q!sub {my $c = shift;
1127 my @a = split '\|', $c->magic;
1128 my $p = $a[!.--$headercount. q!];
1131 unshift @extra_sort_fields, '';
1136 if ( $params->{'with_referrals'} ) {
1138 #XXX next: num for each customer status
1141 '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1142 WHERE cust_main.custnum = referred_cust_main.referral_custnum
1143 ) AS num_referrals';
1145 unshift @extra_headers, 'Referrals';
1146 unshift @extra_fields, 'num_referrals';
1147 unshift @extra_sort_fields, 'num_referrals';
1151 my $select = join(', ', @select);
1154 'table' => 'cust_main',
1155 'select' => $select,
1156 'addl_from' => $addl_from,
1158 'extra_sql' => $extra_sql,
1159 'order_by' => $orderby,
1160 'count_query' => $count_query,
1161 'extra_headers' => \@extra_headers,
1162 'extra_fields' => \@extra_fields,
1163 'extra_sort_fields' => \@extra_sort_fields,
1169 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1171 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1172 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1175 Additional options are the same as FS::Record::qsearch
1182 # sensible defaults, then merge in any passed options
1184 'table' => 'cust_main',
1193 my @fuzzy_mod = 'i';
1194 my $conf = new FS::Conf;
1195 my $fuzziness = $conf->config('fuzzy-fuzziness');
1196 push @fuzzy_mod, $fuzziness if $fuzziness;
1198 check_and_rebuild_fuzzyfiles();
1199 foreach my $field ( keys %$fuzzy ) {
1201 my $all = $self->all_X($field);
1202 next unless scalar(@$all);
1205 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1206 next if !keys(%match);
1208 my $in_matches = 'IN (' .
1209 join(',', map { dbh->quote($_) } keys %match) .
1212 my $extra_sql = $fuzopts{extra_sql};
1213 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1214 $extra_sql .= ' AND ';
1216 $extra_sql .= 'WHERE ';
1218 $extra_sql .= "$field $in_matches";
1220 my $addl_from = $fuzopts{addl_from};
1221 if ( $field =~ /^cust_location\./ ) {
1222 $addl_from .= ' JOIN cust_location USING (custnum)';
1223 } elsif ( $field =~ /^contact\./ ) {
1224 $addl_from .= ' JOIN contact USING (custnum)';
1227 push @cust_main, qsearch({
1229 'addl_from' => $addl_from,
1230 'extra_sql' => $extra_sql,
1234 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1236 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1244 =head1 UTILITY SUBROUTINES
1248 =item check_and_rebuild_fuzzyfiles
1252 sub check_and_rebuild_fuzzyfiles {
1253 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1254 rebuild_fuzzyfiles()
1255 if grep { ! -e "$dir/$_" }
1257 my ($field, $table) = reverse split('\.', $_);
1258 $table ||= 'cust_main';
1264 =item rebuild_fuzzyfiles
1268 sub rebuild_fuzzyfiles {
1270 use Fcntl qw(:flock);
1272 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1273 mkdir $dir, 0700 unless -d $dir;
1275 foreach my $fuzzy ( @fuzzyfields ) {
1277 my ($field, $table) = reverse split('\.', $fuzzy);
1278 $table ||= 'cust_main';
1280 open(LOCK,">>$dir/$table.$field")
1281 or die "can't open $dir/$table.$field: $!";
1283 or die "can't lock $dir/$table.$field: $!";
1285 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1286 or die "can't open $dir/$table.$field.tmp: $!";
1288 my $sth = dbh->prepare(
1289 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1291 $sth->execute or die $sth->errstr;
1293 while ( my $row = $sth->fetchrow_arrayref ) {
1294 print CACHE $row->[0]. "\n";
1297 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1299 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1305 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1309 sub append_fuzzyfiles {
1310 #my( $first, $last, $company ) = @_;
1312 check_and_rebuild_fuzzyfiles();
1314 #foreach my $fuzzy (@fuzzyfields) {
1315 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1316 'cust_location.address1',
1317 'cust_main.ship_company',
1320 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1327 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1329 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1333 use Fcntl qw(:flock);
1334 sub append_fuzzyfiles_fuzzyfield {
1335 my( $fuzzyfield, $value ) = @_;
1337 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1340 my ($field, $table) = reverse split('\.', $fuzzyfield);
1341 $table ||= 'cust_main';
1343 return unless defined($value) && length($value);
1345 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1346 or die "can't open $dir/$table.$field: $!";
1347 flock(CACHE,LOCK_EX)
1348 or die "can't lock $dir/$table.$field: $!";
1350 print CACHE "$value\n";
1352 flock(CACHE,LOCK_UN)
1353 or die "can't unlock $dir/$table.$field: $!";
1363 my( $self, $fuzzy ) = @_;
1364 my ($field, $table) = reverse split('\.', $fuzzy);
1365 $table ||= 'cust_main';
1367 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1368 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1369 or die "can't open $dir/$table.$field: $!";
1370 my @array = map { chomp; $_; } <CACHE>;
1381 L<FS::cust_main>, L<FS::Record>