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 '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 )
105 " OR phonenum = '$phonenum' ".
107 " AND $agentnums_sql", #agent virtualization
108 'addl_from' => ' left join cust_contact using (custnum) left join contact_phone using (contactnum) ',
111 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
112 #try looking for matches with extensions unless one was specified
114 push @cust_main, qsearch( {
115 'table' => 'cust_main',
116 'hashref' => { %options },
117 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
119 join(' OR ', map "$_ LIKE '$phonen\%'",
123 " AND $agentnums_sql", #agent virtualization
131 if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
133 push @cust_main, qsearch( {
134 'table' => 'cust_main',
135 'hashref' => { %options },
136 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
138 join(' OR ', map "$_ = '$search'",
139 qw( dest emailaddress )
142 " AND $agentnums_sql", #agent virtualization
143 'addl_from' => ' left join cust_main_invoice using (custnum) left join cust_contact using (custnum) left join contact_email using (contactnum) ',
146 # custnum search (also try agent_custid), with some tweaking options if your
147 # legacy cust "numbers" have letters
148 } elsif ( $search =~ /^\s*(\d+)\s*$/
149 or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
150 && $search =~ /^\s*(\w\w?\d+)\s*$/
152 or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
153 && $search =~ /^\s*(\d+-\w)\s*$/
155 or ( $conf->config('cust_main-custnum-display_special')
156 # it's not currently possible for special prefixes to contain
157 # digits, so just strip off any alphabetic prefix and match
158 # the rest to custnum
159 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
161 or ( $conf->exists('address1-search' )
162 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
169 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
170 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
171 ? ' AND agent_custid IS NULL ' : '';
172 push @cust_main, qsearch( {
173 'table' => 'cust_main',
174 'hashref' => { 'custnum' => $num, %options },
175 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
179 # for all agents this user can see, if any of them have custnum prefixes
180 # that match the search string, include customers that match the rest
181 # of the custnum and belong to that agent
182 foreach my $agentnum ( keys %$agentnums_href ) {
183 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
185 if ( $p eq substr($num, 0, length($p)) ) {
186 push @cust_main, qsearch( {
187 'table' => 'cust_main',
188 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
189 'agentnum' => $agentnum,
196 push @cust_main, qsearch( {
197 'table' => 'cust_main',
198 'hashref' => { 'agent_custid' => $num, %options },
199 'extra_sql' => " AND $agentnums_sql", #agent virtualization
202 if ( $conf->exists('address1-search') ) {
203 my $len = length($num);
205 # probably the Right Thing: return customers that have any associated
206 # locations matching the string, not just bill/ship location
207 push @cust_main, qsearch( {
208 'select' => 'cust_main.*',
209 'table' => 'cust_main',
210 'addl_from' => ' JOIN cust_location USING (custnum) ',
211 'hashref' => { %options, },
213 ( keys(%options) ? ' AND ' : ' WHERE ' ).
214 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
215 " AND $agentnums_sql",
219 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
221 my($company, $last, $first) = ( $1, $2, $3 );
223 # "Company (Last, First)"
224 #this is probably something a browser remembered,
225 #so just do an exact search (but case-insensitive, so USPS standardization
226 #doesn't throw a wrench in the works)
228 push @cust_main, qsearch( {
229 'table' => 'cust_main',
230 'hashref' => { %options },
232 ( keys(%options) ? ' AND ' : ' WHERE ' ).
234 " LOWER(first) = ". dbh->quote(lc($first)),
235 " LOWER(last) = ". dbh->quote(lc($last)),
236 " LOWER(company) = ". dbh->quote(lc($company)),
242 # probably not necessary for the "something a browser remembered" case
244 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
245 # try {first,last,company}
249 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
250 # # full strings the browser remembers won't work
251 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
253 use Lingua::EN::NameParse;
254 my $NameParse = new Lingua::EN::NameParse(
259 my($last, $first) = ( '', '' );
260 #maybe disable this too and just rely on NameParse?
261 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
263 ($last, $first) = ( $1, $2 );
265 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
266 } elsif ( ! $NameParse->parse($value) ) {
268 my %name = $NameParse->components;
269 $first = lc($name{'given_name_1'}) || $name{'initials_1'}; #wtf NameParse, Ed?
270 $last = lc($name{'surname_1'});
274 if ( $first && $last ) {
276 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
279 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
280 $sql .= "( (LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first)
281 OR (LOWER(contact.last) = $q_last AND LOWER(contact.first) = $q_first) )";
283 #cust_main and contacts
284 push @cust_main, qsearch( {
285 'table' => 'cust_main',
286 'select' => 'cust_main.*, cust_contact.*, contact.contactnum, contact.last as contact_last, contact.first as contact_first, contact.title',
287 'hashref' => { %options },
288 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
289 'addl_from' => ' left join cust_contact on cust_main.custnum = cust_contact.custnum left join contact using (contactnum) ',
292 # or it just be something that was typed in... (try that in a sec)
296 my $q_value = dbh->quote($value);
299 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
300 $sql .= " ( LOWER(cust_main.first) = $q_value
301 OR LOWER(cust_main.last) = $q_value
302 OR LOWER(cust_main.company) = $q_value
303 OR LOWER(cust_main.ship_company) = $q_value
304 OR LOWER(contact.first) = $q_value
305 OR LOWER(contact.last) = $q_value
308 #address1 (yes, it's a kludge)
309 $sql .= " OR EXISTS (
310 SELECT 1 FROM cust_location
311 WHERE LOWER(cust_location.address1) = $q_value
312 AND cust_location.custnum = cust_main.custnum
314 if $conf->exists('address1-search');
316 push @cust_main, qsearch( {
317 'table' => 'cust_main',
318 'select' => 'cust_main.*, cust_contact.*, contact.contactnum, contact.last as contact_last, contact.first as contact_first, contact.title',
319 'hashref' => { %options },
320 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
321 'addl_from' => 'left join cust_contact on cust_main.custnum = cust_contact.custnum left join contact using (contactnum) ',
324 #no exact match, trying substring/fuzzy
325 #always do substring & fuzzy (unless they're explicity config'ed off)
326 #getting complaints searches are not returning enough
327 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
329 #still some false laziness w/search (was search/cust_main.cgi)
332 $FS::CurrentUser::CurrentUser->access_right('List all customers')
337 my @company_hashrefs = ();
338 if ( length($value) >= $min_len ) {
339 @company_hashrefs = (
340 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
341 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
346 if ( $first && $last ) {
349 { 'first' => { op=>'ILIKE', value=>"%$first%" },
350 'last' => { op=>'ILIKE', value=>"%$last%" },
354 } elsif ( length($value) >= $min_len ) {
357 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
358 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
363 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
365 push @cust_main, qsearch( {
366 'table' => 'cust_main',
367 'hashref' => { %$hashref,
370 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
375 if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
377 push @cust_main, qsearch( {
378 select => 'cust_main.*',
379 table => 'cust_main',
380 addl_from => 'JOIN cust_location USING (custnum)',
381 extra_sql => 'WHERE '.
382 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
383 " AND $agentnums_sql", #agent virtualizaiton
390 foreach my $hashref ( @hashrefs ) {
393 grep $agentnums_href->{$_->agentnum}, #agent virt
394 grep $_, #skip contacts that don't have cust_main records
397 'table' => 'contact',
398 'hashref' => { %$hashref,
401 #'extra_sql' => " AND $agentnums_sql", #agent virt
408 'hashref' => \%options,
410 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
413 if ( $first && $last ) {
414 push @cust_main, FS::cust_main::Search->fuzzy_search(
415 { 'last' => $last, #fuzzy hashref
416 'first' => $first }, #
419 push @cust_main, FS::cust_main::Search->fuzzy_search(
420 { 'contact.last' => $last, #fuzzy hashref
421 'contact.first' => $first }, #
426 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
427 push @cust_main, FS::cust_main::Search->fuzzy_search(
428 { $field => $value },
432 foreach my $field ( 'first', 'last' ) {
433 push @cust_main, FS::cust_main::Search->fuzzy_search(
434 { "contact.$field" => $value },
438 if ( $conf->exists('address1-search') ) {
440 FS::cust_main::Search->fuzzy_search(
441 { 'cust_location.address1' => $value },
450 ( my $nospace_search = $search ) =~ s/\s//g;
451 ( my $card_search = $nospace_search ) =~ s/\-//g;
452 $card_search =~ s/[x\*\.\_]/x/gi;
454 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
456 ( my $like_search = $card_search ) =~ s/x/_/g;
457 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
459 push @cust_main, qsearch({
460 'table' => 'cust_main',
462 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
463 OR paymask = '$mask_search'
465 " AND payby IN ('CARD','DCRD') ".
466 " AND $agentnums_sql", #agent virtulization
472 #eliminate duplicates
474 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
482 Accepts the following options: I<email>, the email address to search for. The
483 email address will be searched for as an email invoice destination and as an
486 #Any additional options are treated as an additional qualifier on the search
489 Returns a (possibly empty) array of FS::cust_main objects (but usually just
497 my $email = delete $options{'email'};
499 #no agent virtualization yet
500 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
504 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
506 my ( $user, $domain ) = ( $1, $2 );
508 warn "$me smart_search: searching for $user in domain $domain"
514 'table' => 'cust_main_invoice',
515 'hashref' => { 'dest' => $email },
522 map $_->cust_svc->cust_pkg,
524 'table' => 'svc_acct',
525 'hashref' => { 'username' => $user, },
527 'AND ( SELECT domain FROM svc_domain
528 WHERE svc_acct.domsvc = svc_domain.svcnum
529 ) = '. dbh->quote($domain),
535 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
537 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
554 Returns a qsearch hash expression to search for parameters specified in
555 HASHREF. Valid parameters are
575 listref of start date, end date
579 listref of start date, end date
581 =item spouse_birthdate
583 listref of start date, end date
585 =item anniversary_date
587 listref of start date, end date
597 =item current_balance
599 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
612 my ($class, $params) = @_;
619 # initialize these to prevent warnings
627 'paydate_year' => '',
628 'invoice_terms' => '',
634 # explicit custnum(s)
637 if ( $params->{'custnum'} ) {
638 my @custnums = ref($params->{'custnum'}) ?
639 @{ $params->{'custnum'} } :
640 $params->{'custnum'};
642 'cust_main.custnum IN (' .
643 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
644 ')' if scalar(@custnums) > 0;
651 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
653 "cust_main.agentnum = $1";
660 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
661 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
662 : 'cust_main.salesnum IS NULL';
669 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
671 "cust_main.usernum = $1";
678 #prospect ordered active inactive suspended cancelled
679 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
680 my $method = $params->{'status'}. '_sql';
681 #push @where, $class->$method();
682 push @where, FS::cust_main->$method();
686 unless ( $params->{location_history} ) {
688 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
689 cust_main.ship_locationnum
691 OR cust_location.locationnum IN (
692 SELECT locationnum FROM cust_pkg
693 WHERE cust_pkg.custnum = cust_main.custnum
694 AND locationnum IS NOT NULL
695 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
703 if ( $params->{'address'} ) {
704 # allow this to be an arrayref
705 my @values = ($params->{'address'});
706 @values = @{$values[0]} if ref($values[0]);
708 foreach (grep /\S/, @values) {
709 my $address = dbh->quote('%'. lc($_). '%');
711 "LOWER(cust_location.address1) LIKE $address",
712 "LOWER(cust_location.address2) LIKE $address";
715 push @where, "EXISTS(
716 SELECT 1 FROM cust_location
717 WHERE cust_location.custnum = cust_main.custnum
718 AND (".join(' OR ',@orwhere).")
727 if ( $params->{'city'} =~ /\S/ ) {
728 my $city = dbh->quote($params->{'city'});
729 push @where, "EXISTS(
730 SELECT 1 FROM cust_location
731 WHERE cust_location.custnum = cust_main.custnum
732 AND cust_location.city = $city
740 if ( $params->{'county'} =~ /\S/ ) {
741 my $county = dbh->quote($params->{'county'});
742 push @where, "EXISTS(
743 SELECT 1 FROM cust_location
744 WHERE cust_location.custnum = cust_main.custnum
745 AND cust_location.county = $county
753 if ( $params->{'state'} =~ /\S/ ) {
754 my $state = dbh->quote($params->{'state'});
755 push @where, "EXISTS(
756 SELECT 1 FROM cust_location
757 WHERE cust_location.custnum = cust_main.custnum
758 AND cust_location.state = $state
766 if ( $params->{'zip'} =~ /\S/ ) {
767 my $zip = dbh->quote($params->{'zip'} . '%');
768 push @where, "EXISTS(
769 SELECT 1 FROM cust_location
770 WHERE cust_location.custnum = cust_main.custnum
771 AND cust_location.zip LIKE $zip
779 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
780 my $country = uc($1);
781 push @where, "EXISTS(
782 SELECT 1 FROM cust_location
783 WHERE cust_location.custnum = cust_main.custnum
784 AND cust_location.country = '$country'
792 if ( $params->{'refnum'} ) {
794 my @refnum = ref( $params->{'refnum'} )
795 ? @{ $params->{'refnum'} }
796 : ( $params->{'refnum'} );
798 @refnum = grep /^(\d*)$/, @refnum;
800 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
806 # parse cancelled package checkbox
811 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
812 unless $params->{'cancelled_pkgs'};
815 # "with email address(es)" checkbox
819 'EXISTS ( SELECT 1 FROM cust_main_invoice
820 WHERE cust_main_invoice.custnum = cust_main.custnum
822 )' # AND dest LIKE '%@%'
823 if $params->{'with_email'};
826 # "with postal mail invoices" checkbox
830 "EXISTS ( SELECT 1 FROM cust_main_invoice
831 WHERE cust_main_invoice.custnum = cust_main.custnum
833 if $params->{'POST'};
836 # "without postal mail invoices" checkbox
840 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
841 WHERE cust_main_invoice.custnum = cust_main.custnum
843 if $params->{'no_POST'};
846 # "tax exempt" checkbox
848 push @where, "cust_main.tax = 'Y'"
852 # "not tax exempt" checkbox
854 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
855 if $params->{'no_tax'};
860 if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
866 if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
867 my $method = $params->{referral_status}. '_sql';
868 $and_status = ' AND '. FS::cust_main->$method();
869 $and_status =~ s/ cust_main\./ referred_cust_main./g;
873 " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
874 WHERE cust_main.custnum = referred_cust_main.referral_custnum
884 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
886 next unless exists($params->{$field});
888 my($beginning, $ending, $hour) = @{$params->{$field}};
891 "cust_main.$field IS NOT NULL",
892 "cust_main.$field >= $beginning",
893 "cust_main.$field <= $ending";
895 if($field eq 'signupdate' && defined $hour) {
896 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
897 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
899 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
900 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
903 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
907 $orderby ||= "ORDER BY cust_main.$field";
915 if ( $params->{'classnum'} ) {
917 my @classnum = ref( $params->{'classnum'} )
918 ? @{ $params->{'classnum'} }
919 : ( $params->{'classnum'} );
921 @classnum = grep /^(\d*)$/, @classnum;
924 push @where, '( '. join(' OR ', map {
925 $_ ? "cust_main.classnum = $_"
926 : "cust_main.classnum IS NULL"
939 if ( $params->{'payby'} ) {
941 my @payby = ref( $params->{'payby'} )
942 ? @{ $params->{'payby'} }
943 : ( $params->{'payby'} );
945 @payby = grep /^([A-Z]{4})$/, @payby;
947 push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
953 # paydate_year / paydate_month
956 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
958 $params->{'paydate_month'} =~ /^(\d\d?)$/
959 or die "paydate_year without paydate_month?";
963 'paydate IS NOT NULL',
965 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
973 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
975 if ( $1 eq 'NULL' ) {
977 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
980 "cust_main.invoice_terms IS NOT NULL",
981 "cust_main.invoice_terms = '$1'";
989 if ( $params->{'current_balance'} ) {
991 #my $balance_sql = $class->balance_sql();
992 my $balance_sql = FS::cust_main->balance_sql();
994 my @current_balance =
995 ref( $params->{'current_balance'} )
996 ? @{ $params->{'current_balance'} }
997 : ( $params->{'current_balance'} );
999 push @where, map { s/current_balance/$balance_sql/; $_ }
1008 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
1010 "cust_main.custbatch = '$1'";
1013 if ( $params->{'tagnum'} ) {
1014 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1016 @tagnums = grep /^(\d+)$/, @tagnums;
1019 if ( $params->{'all_tags'} ) {
1020 my $exists = $params->{'all_tags'} eq 'all' ? 'exists' : 'not exists';
1021 foreach ( @tagnums ) {
1022 push @where, $exists.'(select 1 from cust_tag where '.
1023 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1026 } else { # matching any tag, not all
1027 my $tags_where = "0 < (select count(1) from cust_tag where "
1028 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1029 . join(',', @tagnums) . "))";
1031 push @where, $tags_where;
1039 if ( $params->{'pkg_classnum'} ) {
1040 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1041 @{ $params->{'pkg_classnum'} } :
1042 $params->{'pkg_classnum'};
1043 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1045 if ( @pkg_classnums ) {
1048 if ( $params->{'all_pkg_classnums'} ) {
1049 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1052 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1054 foreach (@pkg_where) {
1056 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1057 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1058 if ( not $params->{'any_pkg_status'} ) {
1059 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1061 push @where, "EXISTS($select_pkg)";
1067 # setup queries, subs, etc. for the search
1070 $orderby ||= 'ORDER BY custnum';
1072 # here is the agent virtualization
1074 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1076 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1079 # always make address fields available in results
1080 for my $pre ('bill_', 'ship_') {
1082 'LEFT JOIN cust_location AS '.$pre.'location '.
1083 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1086 # always make referral available in results
1087 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1088 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1090 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1093 'cust_main.custnum',
1094 'cust_main.salesnum',
1095 # there's a good chance that we'll need these
1096 'cust_main.bill_locationnum',
1097 'cust_main.ship_locationnum',
1098 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1101 my @extra_headers = ();
1102 my @extra_fields = ();
1103 my @extra_sort_fields = ();
1105 if ($params->{'flattened_pkgs'}) {
1109 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1111 if ($dbh->{Driver}->{Name} eq 'Pg') {
1116 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1117 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1122 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1123 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1124 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1125 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1127 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1128 "omitting package information from report.";
1131 my $header_query = "
1132 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1133 FROM cust_main $addl_from $extra_sql $pkgwhere
1134 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1137 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1138 $sth->execute() or die $sth->errstr;
1139 my $headerrow = $sth->fetchrow_arrayref;
1140 my $headercount = $headerrow ? $headerrow->[0] : 0;
1141 while($headercount) {
1142 unshift @extra_headers, "Package ". $headercount;
1143 unshift @extra_fields, eval q!sub {my $c = shift;
1144 my @a = split '\|', $c->magic;
1145 my $p = $a[!.--$headercount. q!];
1148 unshift @extra_sort_fields, '';
1153 if ( $params->{'with_referrals'} ) {
1155 #XXX next: num for each customer status
1158 '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1159 WHERE cust_main.custnum = referred_cust_main.referral_custnum
1160 ) AS num_referrals';
1162 unshift @extra_headers, 'Referrals';
1163 unshift @extra_fields, 'num_referrals';
1164 unshift @extra_sort_fields, 'num_referrals';
1168 my $select = join(', ', @select);
1171 'table' => 'cust_main',
1172 'select' => $select,
1173 'addl_from' => $addl_from,
1175 'extra_sql' => $extra_sql,
1176 'order_by' => $orderby,
1177 'count_query' => $count_query,
1178 'extra_headers' => \@extra_headers,
1179 'extra_fields' => \@extra_fields,
1180 'extra_sort_fields' => \@extra_sort_fields,
1182 #warn Data::Dumper::Dumper($sql_query);
1187 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1189 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1190 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1193 Additional options are the same as FS::Record::qsearch
1200 # sensible defaults, then merge in any passed options
1202 'table' => 'cust_main',
1211 my @fuzzy_mod = 'i';
1212 my $conf = new FS::Conf;
1213 my $fuzziness = $conf->config('fuzzy-fuzziness');
1214 push @fuzzy_mod, $fuzziness if $fuzziness;
1216 check_and_rebuild_fuzzyfiles();
1217 foreach my $field ( keys %$fuzzy ) {
1219 my $all = $self->all_X($field);
1220 next unless scalar(@$all);
1223 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1224 next if !keys(%match);
1226 my $in_matches = 'IN (' .
1227 join(',', map { dbh->quote($_) } keys %match) .
1230 my $extra_sql = $fuzopts{extra_sql};
1231 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1232 $extra_sql .= ' AND ';
1234 $extra_sql .= 'WHERE ';
1236 $extra_sql .= "$field $in_matches";
1238 my $addl_from = $fuzopts{addl_from};
1239 if ( $field =~ /^cust_location\./ ) {
1240 $addl_from .= ' JOIN cust_location USING (custnum)';
1241 } elsif ( $field =~ /^contact\./ ) {
1242 $addl_from .= ' JOIN contact USING (custnum)';
1245 push @cust_main, qsearch({
1247 'addl_from' => $addl_from,
1248 'extra_sql' => $extra_sql,
1252 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1254 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1262 =head1 UTILITY SUBROUTINES
1266 =item check_and_rebuild_fuzzyfiles
1270 sub check_and_rebuild_fuzzyfiles {
1271 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1272 rebuild_fuzzyfiles()
1273 if grep { ! -e "$dir/$_" }
1275 my ($field, $table) = reverse split('\.', $_);
1276 $table ||= 'cust_main';
1282 =item rebuild_fuzzyfiles
1286 sub rebuild_fuzzyfiles {
1288 use Fcntl qw(:flock);
1290 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1291 mkdir $dir, 0700 unless -d $dir;
1293 foreach my $fuzzy ( @fuzzyfields ) {
1295 my ($field, $table) = reverse split('\.', $fuzzy);
1296 $table ||= 'cust_main';
1298 open(LOCK,">>$dir/$table.$field")
1299 or die "can't open $dir/$table.$field: $!";
1301 or die "can't lock $dir/$table.$field: $!";
1303 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1304 or die "can't open $dir/$table.$field.tmp: $!";
1306 my $sth = dbh->prepare(
1307 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1309 $sth->execute or die $sth->errstr;
1311 while ( my $row = $sth->fetchrow_arrayref ) {
1312 print CACHE $row->[0]. "\n";
1315 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1317 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1323 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1327 sub append_fuzzyfiles {
1328 #my( $first, $last, $company ) = @_;
1330 check_and_rebuild_fuzzyfiles();
1332 #foreach my $fuzzy (@fuzzyfields) {
1333 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1334 'cust_location.address1',
1335 'cust_main.ship_company',
1338 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1345 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1347 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1351 use Fcntl qw(:flock);
1352 sub append_fuzzyfiles_fuzzyfield {
1353 my( $fuzzyfield, $value ) = @_;
1355 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1358 my ($field, $table) = reverse split('\.', $fuzzyfield);
1359 $table ||= 'cust_main';
1361 return unless length($value);
1363 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1364 or die "can't open $dir/$table.$field: $!";
1365 flock(CACHE,LOCK_EX)
1366 or die "can't lock $dir/$table.$field: $!";
1368 print CACHE "$value\n";
1370 flock(CACHE,LOCK_UN)
1371 or die "can't unlock $dir/$table.$field: $!";
1381 my( $self, $fuzzy ) = @_;
1382 my ($field, $table) = reverse split('\.', $fuzzy);
1383 $table ||= 'cust_main';
1385 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1386 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1387 or die "can't open $dir/$table.$field: $!";
1388 my @array = map { chomp; $_; } <CACHE>;
1399 L<FS::cust_main>, L<FS::Record>