1 package FS::cust_main::Search;
5 use base qw( Exporter );
6 use vars qw( @EXPORT_OK $DEBUG $me $conf @fuzzyfields );
7 use String::Approx qw(amatch);
9 use FS::Record qw( qsearch );
11 use FS::cust_main_invoice;
13 use FS::payinfo_Mixin;
15 @EXPORT_OK = qw( smart_search );
17 # 1 is mostly method/subroutine entry and options
18 # 2 traces progress of some operations
19 # 3 is even more information including possibly sensitive data
21 $me = '[FS::cust_main::Search]';
24 'cust_main.first', 'cust_main.last', 'cust_main.company',
25 'cust_main.ship_company', # if you're using it
26 'cust_location.address1',
27 'contact.first', 'contact.last',
30 install_callback FS::UID sub {
32 #yes, need it for stuff below (prolly should be cached)
37 FS::cust_main::Search - Customer searching
41 use FS::cust_main::Search;
43 FS::cust_main::Search::smart_search(%options);
45 FS::cust_main::Search::email_search(%options);
47 FS::cust_main::Search->search( \%options );
49 FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
55 =item smart_search OPTION => VALUE ...
57 Accepts the following options: I<search>, the string to search for. The string
58 will be searched for as a customer number, phone number, name or company name,
59 address (if address1-search is on), invoicing email address, or credit card
62 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
63 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
65 skip fuzzy matching when an exact match is found.
67 Any additional options are treated as an additional qualifier on the search
70 Returns a (possibly empty) array of FS::cust_main objects.
77 #here is the agent virtualization
79 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
80 my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
84 my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
85 my $search = delete $options{'search'};
86 ( my $alphanum_search = $search ) =~ s/\W//g;
88 if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
90 #false laziness w/Record::ut_phone
91 my $phonen = "$1-$2-$3";
92 $phonen .= " x$4" if $4;
94 my $phonenum = "$1$2$3";
97 #cust_main phone numbers and contact phone number
98 push @cust_main, qsearch( {
99 'select' => 'cust_main.*',
100 'table' => 'cust_main',
101 'addl_from' => ' left join cust_contact using (custnum) '.
102 ' left join contact_phone using (contactnum) ',
103 'hashref' => { %options },
104 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
106 join(' OR ', map "$_ = '$phonen'",
107 qw( daytime night mobile fax )
109 " OR phonenum = '$phonenum' ".
111 " AND $agentnums_sql", #agent virtualization
114 unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
115 #try looking for matches with extensions unless one was specified
117 push @cust_main, qsearch( {
118 'table' => 'cust_main',
119 'hashref' => { %options },
120 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
122 join(' OR ', map "$_ LIKE '$phonen\%'",
126 " AND $agentnums_sql", #agent virtualization
134 if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
136 push @cust_main, qsearch( {
137 'select' => 'cust_main.*',
138 'table' => 'cust_main',
139 'addl_from' => ' left join cust_main_invoice using (custnum) '.
140 ' left join cust_contact using (custnum) '.
141 ' left join contact_email using (contactnum) ',
142 'hashref' => { %options },
143 'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
145 join(' OR ', map "$_ = '$search'",
146 qw( dest emailaddress )
149 " AND $agentnums_sql", #agent virtualization
152 # custnum search (also try agent_custid), with some tweaking options if your
153 # legacy cust "numbers" have letters
154 } elsif ( $search =~ /^\s*(\d+)\s*$/
155 or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
156 && $search =~ /^\s*(\w\w?\d+)\s*$/
158 or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
159 && $search =~ /^\s*(\d+-\w)\s*$/
161 or ( $conf->config('cust_main-custnum-display_special')
162 # it's not currently possible for special prefixes to contain
163 # digits, so just strip off any alphabetic prefix and match
164 # the rest to custnum
165 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
167 or ( $conf->exists('address1-search' )
168 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
175 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
176 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
177 ? ' AND agent_custid IS NULL ' : '';
178 push @cust_main, qsearch( {
179 'table' => 'cust_main',
180 'hashref' => { 'custnum' => $num, %options },
181 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
185 # for all agents this user can see, if any of them have custnum prefixes
186 # that match the search string, include customers that match the rest
187 # of the custnum and belong to that agent
188 foreach my $agentnum ( keys %$agentnums_href ) {
189 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
191 if ( $p eq substr($num, 0, length($p)) ) {
192 push @cust_main, qsearch( {
193 'table' => 'cust_main',
194 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
195 'agentnum' => $agentnum,
202 push @cust_main, qsearch( {
203 'table' => 'cust_main',
204 'hashref' => { 'agent_custid' => $num, %options },
205 'extra_sql' => " AND $agentnums_sql", #agent virtualization
208 if ( $conf->exists('address1-search') ) {
209 my $len = length($num);
211 # probably the Right Thing: return customers that have any associated
212 # locations matching the string, not just bill/ship location
213 push @cust_main, qsearch( {
214 'select' => 'cust_main.*',
215 'table' => 'cust_main',
216 'addl_from' => ' JOIN cust_location USING (custnum) ',
217 'hashref' => { %options, },
219 ( keys(%options) ? ' AND ' : ' WHERE ' ).
220 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
221 " AND $agentnums_sql",
225 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
227 my($company, $last, $first) = ( $1, $2, $3 );
229 # "Company (Last, First)"
230 #this is probably something a browser remembered,
231 #so just do an exact search (but case-insensitive, so USPS standardization
232 #doesn't throw a wrench in the works)
234 push @cust_main, qsearch( {
235 'table' => 'cust_main',
236 'hashref' => { %options },
238 ( keys(%options) ? ' AND ' : ' WHERE ' ).
240 " LOWER(first) = ". dbh->quote(lc($first)),
241 " LOWER(last) = ". dbh->quote(lc($last)),
242 " LOWER(company) = ". dbh->quote(lc($company)),
248 # probably not necessary for the "something a browser remembered" case
250 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
251 # try {first,last,company}
255 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
256 # # full strings the browser remembers won't work
257 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
259 use Lingua::EN::NameParse;
260 my $NameParse = new Lingua::EN::NameParse(
265 my($last, $first) = ( '', '' );
266 #maybe disable this too and just rely on NameParse?
267 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
269 ($last, $first) = ( $1, $2 );
271 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
272 } elsif ( ! $NameParse->parse($value) ) {
274 my %name = $NameParse->components;
275 $first = lc($name{'given_name_1'}) || $name{'initials_1'}; #wtf NameParse, Ed?
276 $last = lc($name{'surname_1'});
280 if ( $first && $last ) {
282 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
285 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
286 $sql .= "( (LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first)
287 OR (LOWER(contact.last) = $q_last AND LOWER(contact.first) = $q_first) )";
289 #cust_main and contacts
290 push @cust_main, qsearch( {
291 'select' => 'cust_main.*',
292 'table' => 'cust_main',
293 'addl_from' => ' left join cust_contact using (custnum) '.
294 ' left join contact using (contactnum) ',
295 'hashref' => { %options },
296 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
299 # or it just be something that was typed in... (try that in a sec)
303 my $q_value = dbh->quote($value);
306 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
307 $sql .= " ( LOWER(cust_main.first) = $q_value
308 OR LOWER(cust_main.last) = $q_value
309 OR LOWER(cust_main.company) = $q_value
310 OR LOWER(cust_main.ship_company) = $q_value
311 OR LOWER(contact.first) = $q_value
312 OR LOWER(contact.last) = $q_value
315 #address1 (yes, it's a kludge)
316 $sql .= " OR EXISTS (
317 SELECT 1 FROM cust_location
318 WHERE LOWER(cust_location.address1) = $q_value
319 AND cust_location.custnum = cust_main.custnum
321 if $conf->exists('address1-search');
323 push @cust_main, qsearch( {
324 'select' => 'cust_main.*',
325 'table' => 'cust_main',
326 'addl_from' => ' left join cust_contact using (custnum) '.
327 ' left join contact using (contactnum) ',
328 'hashref' => { %options },
329 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
332 #no exact match, trying substring/fuzzy
333 #always do substring & fuzzy (unless they're explicity config'ed off)
334 #getting complaints searches are not returning enough
335 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
337 #still some false laziness w/search (was search/cust_main.cgi)
340 $FS::CurrentUser::CurrentUser->access_right('List all customers')
345 my @company_hashrefs = ();
346 if ( length($value) >= $min_len ) {
347 @company_hashrefs = (
348 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
349 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
354 if ( $first && $last ) {
357 { 'first' => { op=>'ILIKE', value=>"%$first%" },
358 'last' => { op=>'ILIKE', value=>"%$last%" },
362 } elsif ( length($value) >= $min_len ) {
365 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
366 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
371 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
373 push @cust_main, qsearch( {
374 'table' => 'cust_main',
375 'hashref' => { %$hashref,
378 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
383 if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
385 push @cust_main, qsearch( {
386 select => 'cust_main.*',
387 table => 'cust_main',
388 addl_from => 'JOIN cust_location USING (custnum)',
389 extra_sql => 'WHERE '.
390 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
391 " AND $agentnums_sql", #agent virtualizaiton
398 foreach my $hashref ( @hashrefs ) {
401 grep $agentnums_href->{$_->agentnum}, #agent virt
402 grep $_, #skip contacts that don't have cust_main records
405 'table' => 'contact',
406 'hashref' => { %$hashref,
409 #'extra_sql' => " AND $agentnums_sql", #agent virt
416 'hashref' => \%options,
418 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
421 if ( $first && $last ) {
422 push @cust_main, FS::cust_main::Search->fuzzy_search(
423 { 'last' => $last, #fuzzy hashref
424 'first' => $first }, #
427 push @cust_main, FS::cust_main::Search->fuzzy_search(
428 { 'contact.last' => $last, #fuzzy hashref
429 'contact.first' => $first }, #
434 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
435 push @cust_main, FS::cust_main::Search->fuzzy_search(
436 { $field => $value },
440 foreach my $field ( 'first', 'last' ) {
441 push @cust_main, FS::cust_main::Search->fuzzy_search(
442 { "contact.$field" => $value },
446 if ( $conf->exists('address1-search') ) {
448 FS::cust_main::Search->fuzzy_search(
449 { 'cust_location.address1' => $value },
458 ( my $nospace_search = $search ) =~ s/\s//g;
459 ( my $card_search = $nospace_search ) =~ s/\-//g;
460 $card_search =~ s/[x\*\.\_]/x/gi;
462 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
464 ( my $like_search = $card_search ) =~ s/x/_/g;
465 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
467 push @cust_main, qsearch({
468 'select' => 'cust_main.*',
469 'table' => 'cust_main',
470 'addl_from' => ' JOIN cust_payby USING (custnum)',
472 'extra_sql' => " WHERE ( cust_payby.payinfo LIKE '$like_search'
473 OR cust_payby.paymask = '$mask_search'
475 " AND cust_payby.payby IN ('CARD','DCRD') ".
476 " AND $agentnums_sql", #agent virtulization
482 #eliminate duplicates
484 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
492 Accepts the following options: I<email>, the email address to search for. The
493 email address will be searched for as an email invoice destination and as an
496 #Any additional options are treated as an additional qualifier on the search
499 Returns a (possibly empty) array of FS::cust_main objects (but usually just
507 my $email = delete $options{'email'};
509 #no agent virtualization yet
510 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
514 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
516 my ( $user, $domain ) = ( $1, $2 );
518 warn "$me smart_search: searching for $user in domain $domain"
522 map { $_->cust_main }
523 map { $_->cust_contact }
526 'table' => 'contact_email',
527 'hashref' => { 'emailaddress' => $email },
534 map $_->cust_svc->cust_pkg,
536 'table' => 'svc_acct',
537 'hashref' => { 'username' => $user, },
539 'AND ( SELECT domain FROM svc_domain
540 WHERE svc_acct.domsvc = svc_domain.svcnum
541 ) = '. dbh->quote($domain),
547 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
549 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
566 Returns a qsearch hash expression to search for parameters specified in
567 HASHREF. Valid parameters are
587 listref of start date, end date
591 listref of start date, end date
593 =item spouse_birthdate
595 listref of start date, end date
597 =item anniversary_date
599 listref of start date, end date
601 =item current_balance
603 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
616 my ($class, $params) = @_;
623 # initialize these to prevent warnings
631 'invoice_terms' => '',
637 # explicit custnum(s)
640 if ( $params->{'custnum'} ) {
641 my @custnums = ref($params->{'custnum'}) ?
642 @{ $params->{'custnum'} } :
643 $params->{'custnum'};
645 'cust_main.custnum IN (' .
646 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
647 ')' if scalar(@custnums) > 0;
654 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
656 "cust_main.agentnum = $1";
663 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
664 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
665 : 'cust_main.salesnum IS NULL';
672 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
674 "cust_main.usernum = $1";
681 #prospect ordered active inactive suspended cancelled
682 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
683 my $method = $params->{'status'}. '_sql';
684 #push @where, $class->$method();
685 push @where, FS::cust_main->$method();
689 unless ( $params->{location_history} ) {
691 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
692 cust_main.ship_locationnum
694 OR cust_location.locationnum IN (
695 SELECT locationnum FROM cust_pkg
696 WHERE cust_pkg.custnum = cust_main.custnum
697 AND locationnum IS NOT NULL
698 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
706 if ( $params->{'address'} ) {
707 # allow this to be an arrayref
708 my @values = ($params->{'address'});
709 @values = @{$values[0]} if ref($values[0]);
711 foreach (grep /\S/, @values) {
712 my $address = dbh->quote('%'. lc($_). '%');
714 "LOWER(cust_location.address1) LIKE $address",
715 "LOWER(cust_location.address2) LIKE $address";
718 push @where, "EXISTS(
719 SELECT 1 FROM cust_location
720 WHERE cust_location.custnum = cust_main.custnum
721 AND (".join(' OR ',@orwhere).")
730 if ( $params->{'city'} =~ /\S/ ) {
731 my $city = dbh->quote($params->{'city'});
732 push @where, "EXISTS(
733 SELECT 1 FROM cust_location
734 WHERE cust_location.custnum = cust_main.custnum
735 AND cust_location.city = $city
743 if ( $params->{'county'} =~ /\S/ ) {
744 my $county = dbh->quote($params->{'county'});
745 push @where, "EXISTS(
746 SELECT 1 FROM cust_location
747 WHERE cust_location.custnum = cust_main.custnum
748 AND cust_location.county = $county
756 if ( $params->{'state'} =~ /\S/ ) {
757 my $state = dbh->quote($params->{'state'});
758 push @where, "EXISTS(
759 SELECT 1 FROM cust_location
760 WHERE cust_location.custnum = cust_main.custnum
761 AND cust_location.state = $state
769 if ( $params->{'zip'} =~ /\S/ ) {
770 my $zip = dbh->quote($params->{'zip'} . '%');
771 push @where, "EXISTS(
772 SELECT 1 FROM cust_location
773 WHERE cust_location.custnum = cust_main.custnum
774 AND cust_location.zip LIKE $zip
782 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
783 my $country = uc($1);
784 push @where, "EXISTS(
785 SELECT 1 FROM cust_location
786 WHERE cust_location.custnum = cust_main.custnum
787 AND cust_location.country = '$country'
796 foreach my $phonet (qw(daytime night mobile fax)) {
797 if ($params->{$phonet}) {
798 $params->{$phonet} =~ s/\D//g;
799 $params->{$phonet} =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
801 my $phonen = "$1-$2-$3";
802 if ($4) { push @where, "cust_main.".$phonet." = '".$phonen." x$4'"; }
803 else { push @where, "cust_main.".$phonet." like '".$phonen."%'"; }
810 if ( $params->{'refnum'} ) {
812 my @refnum = ref( $params->{'refnum'} )
813 ? @{ $params->{'refnum'} }
814 : ( $params->{'refnum'} );
816 @refnum = grep /^(\d*)$/, @refnum;
818 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
824 # parse cancelled package checkbox
829 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
830 unless $params->{'cancelled_pkgs'};
833 # "with email address(es)" checkbox,
834 # also optionally: with_email_dest and with_contact_type
837 if ($params->{with_email}) {
840 my $contact_type_sql;
842 if ($params->{with_email_dest}) {
843 croak unless ref $params->{with_email_dest} eq 'ARRAY';
845 @email_dest = @{$params->{with_email_dest}};
848 join(' OR ',map(" cust_contact.${_}_dest IS NOT NULL ", @email_dest)).
850 # Can't use message_dist = 'Y' because single quotes are escaped later
852 if ($params->{with_contact_type}) {
853 croak unless ref $params->{with_contact_type} eq 'ARRAY';
855 my @contact_type = grep {/^\d+$/ && $_ > 0} @{$params->{with_contact_type}};
856 my $has_null_type = 0;
857 $has_null_type = 1 if grep { $_ eq 0 } @{$params->{with_contact_type}};
859 if ($has_null_type) {
860 $hnt_sql = ' OR ' if @contact_type;
861 $hnt_sql .= ' cust_contact.classnum IS NULL ';
866 join(' OR ', map(" cust_contact.classnum = $_ ", @contact_type)).
871 "EXISTS ( SELECT 1 FROM contact_email
872 JOIN cust_contact USING (contactnum)
873 WHERE cust_contact.custnum = cust_main.custnum
880 # "with postal mail invoices" checkbox
883 push @where, "cust_main.postal_invoice = 'Y'"
884 if $params->{'POST'};
887 # "without postal mail invoices" checkbox
890 push @where, "cust_main.postal_invoice IS NULL"
891 if $params->{'no_POST'};
894 # "tax exempt" checkbox
896 push @where, "cust_main.tax = 'Y'"
900 # "not tax exempt" checkbox
902 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
903 if $params->{'no_tax'};
908 if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
914 if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
915 my $method = $params->{referral_status}. '_sql';
916 $and_status = ' AND '. FS::cust_main->$method();
917 $and_status =~ s/ cust_main\./ referred_cust_main./g;
921 " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
922 WHERE cust_main.custnum = referred_cust_main.referral_custnum
932 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
934 next unless exists($params->{$field});
936 my($beginning, $ending, $hour) = @{$params->{$field}};
939 "cust_main.$field IS NOT NULL",
940 "cust_main.$field >= $beginning",
941 "cust_main.$field <= $ending";
943 if($field eq 'signupdate' && defined $hour) {
944 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
945 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
947 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
948 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
951 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
955 $orderby ||= "ORDER BY cust_main.$field";
963 if ( $params->{'classnum'} ) {
965 my @classnum = ref( $params->{'classnum'} )
966 ? @{ $params->{'classnum'} }
967 : ( $params->{'classnum'} );
969 @classnum = grep /^(\d*)$/, @classnum;
972 push @where, '( '. join(' OR ', map {
973 $_ ? "cust_main.classnum = $_"
974 : "cust_main.classnum IS NULL"
987 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
989 if ( $1 eq 'NULL' ) {
991 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
994 "cust_main.invoice_terms IS NOT NULL",
995 "cust_main.invoice_terms = '$1'";
1003 if ( $params->{'current_balance'} ) {
1005 #my $balance_sql = $class->balance_sql();
1006 my $balance_sql = FS::cust_main->balance_sql();
1008 my @current_balance =
1009 ref( $params->{'current_balance'} )
1010 ? @{ $params->{'current_balance'} }
1011 : ( $params->{'current_balance'} );
1013 push @where, map { s/current_balance/$balance_sql/; $_ }
1022 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
1024 "cust_main.custbatch = '$1'";
1027 if ( $params->{'tagnum'} ) {
1028 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1030 @tagnums = grep /^(\d+)$/, @tagnums;
1033 if ( $params->{'all_tags'} ) {
1034 my $exists = $params->{'all_tags'} eq 'all' ? 'exists' : 'not exists';
1035 foreach ( @tagnums ) {
1036 push @where, $exists.'(select 1 from cust_tag where '.
1037 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1040 } else { # matching any tag, not all
1041 my $tags_where = "0 < (select count(1) from cust_tag where "
1042 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1043 . join(',', @tagnums) . "))";
1045 push @where, $tags_where;
1053 if ( $params->{'pkg_classnum'} ) {
1054 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1055 @{ $params->{'pkg_classnum'} } :
1056 $params->{'pkg_classnum'};
1057 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1059 if ( @pkg_classnums ) {
1062 if ( $params->{'all_pkg_classnums'} ) {
1063 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1066 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1068 foreach (@pkg_where) {
1070 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1071 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1072 if ( not $params->{'any_pkg_status'} ) {
1073 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1075 push @where, "EXISTS($select_pkg)";
1083 if (keys %{ $params->{'contacts'} }) {
1084 my $contact_params = $params->{'contacts'};
1086 if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
1087 my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
1088 unless !$contact_params->{'contacts_firstname'};
1089 my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
1090 unless !$contact_params->{'contacts_lastname'};
1092 "EXISTS ( SELECT 1 FROM contact
1093 JOIN cust_contact USING (contactnum)
1094 WHERE cust_contact.custnum = cust_main.custnum
1095 $first_query $last_query
1099 if ($contact_params->{'contacts_email'}) {
1101 "EXISTS ( SELECT 1 FROM contact_email
1102 JOIN cust_contact USING (contactnum)
1103 WHERE cust_contact.custnum = cust_main.custnum
1104 AND contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "'
1108 if ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
1110 foreach my $phone ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
1111 $phone =~ /^contacts_phonetypenum(\d+)$/ or die "No phone type num $1 from $phone";
1112 my $phonetypenum = $1;
1113 (my $num = $contact_params->{$phone}) =~ s/\W//g;
1114 if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
1115 $phone_query .= " AND ( contact_phone.phonetypenum = '".$phonetypenum."' AND contact_phone.phonenum = '" . $contact_params->{$phone} . "' )"
1116 unless !$contact_params->{$phone};
1119 "EXISTS ( SELECT 1 FROM contact_phone
1120 JOIN cust_contact USING (contactnum)
1121 WHERE cust_contact.custnum = cust_main.custnum
1129 # setup queries, subs, etc. for the search
1132 $orderby ||= 'ORDER BY cust_main.custnum';
1134 # here is the agent virtualization
1136 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1138 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1141 # always make address fields available in results
1142 for my $pre ('bill_', 'ship_') {
1144 'LEFT JOIN cust_location AS '.$pre.'location '.
1145 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1148 # always make referral available in results
1149 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1150 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1153 'cust_main.custnum',
1154 'cust_main.salesnum',
1155 # there's a good chance that we'll need these
1156 'cust_main.bill_locationnum',
1157 'cust_main.ship_locationnum',
1158 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1161 my @extra_headers = ();
1162 my @extra_fields = ();
1163 my @extra_sort_fields = ();
1165 my $count_query = "SELECT COUNT(DISTINCT cust_main.custnum) FROM cust_main $addl_from $extra_sql";
1167 if ($params->{'flattened_pkgs'}) {
1171 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1173 if ($dbh->{Driver}->{Name} eq 'Pg') {
1178 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1179 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1184 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1185 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1186 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1187 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1189 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1190 "omitting package information from report.";
1193 my $header_query = "
1194 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1195 FROM cust_main $addl_from $extra_sql $pkgwhere
1196 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1199 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1200 $sth->execute() or die $sth->errstr;
1201 my $headerrow = $sth->fetchrow_arrayref;
1202 my $headercount = $headerrow ? $headerrow->[0] : 0;
1203 while($headercount) {
1204 unshift @extra_headers, "Package ". $headercount;
1205 unshift @extra_fields, eval q!sub {my $c = shift;
1206 my @a = split '\|', $c->magic;
1207 my $p = $a[!.--$headercount. q!];
1210 unshift @extra_sort_fields, '';
1215 if ( $params->{'with_referrals'} ) {
1217 #XXX next: num for each customer status
1220 '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1221 WHERE cust_main.custnum = referred_cust_main.referral_custnum
1222 ) AS num_referrals';
1224 unshift @extra_headers, 'Referrals';
1225 unshift @extra_fields, 'num_referrals';
1226 unshift @extra_sort_fields, 'num_referrals';
1230 my $select = join(', ', @select);
1233 'table' => 'cust_main',
1234 'select' => $select,
1235 'addl_from' => $addl_from,
1237 'extra_sql' => $extra_sql,
1238 'order_by' => $orderby,
1239 'count_query' => $count_query,
1240 'extra_headers' => \@extra_headers,
1241 'extra_fields' => \@extra_fields,
1242 'extra_sort_fields' => \@extra_sort_fields,
1248 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1250 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1251 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1254 Additional options are the same as FS::Record::qsearch
1261 # sensible defaults, then merge in any passed options
1263 'table' => 'cust_main',
1272 my @fuzzy_mod = 'i';
1273 my $conf = new FS::Conf;
1274 my $fuzziness = $conf->config('fuzzy-fuzziness');
1275 push @fuzzy_mod, $fuzziness if $fuzziness;
1277 check_and_rebuild_fuzzyfiles();
1278 foreach my $field ( keys %$fuzzy ) {
1280 my $all = $self->all_X($field);
1281 next unless scalar(@$all);
1284 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1285 next if !keys(%match);
1287 my $in_matches = 'IN (' .
1288 join(',', map { dbh->quote($_) } keys %match) .
1291 my $extra_sql = $fuzopts{extra_sql};
1292 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1293 $extra_sql .= ' AND ';
1295 $extra_sql .= 'WHERE ';
1297 $extra_sql .= "$field $in_matches";
1299 my $addl_from = $fuzopts{addl_from};
1300 if ( $field =~ /^cust_location\./ ) {
1301 $addl_from .= ' JOIN cust_location USING (custnum)';
1302 } elsif ( $field =~ /^contact\./ ) {
1303 $addl_from .= ' JOIN contact USING (custnum)';
1306 push @cust_main, qsearch({
1308 'addl_from' => $addl_from,
1309 'extra_sql' => $extra_sql,
1313 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1315 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1323 =head1 UTILITY SUBROUTINES
1327 =item check_and_rebuild_fuzzyfiles
1331 sub check_and_rebuild_fuzzyfiles {
1332 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1333 rebuild_fuzzyfiles()
1334 if grep { ! -e "$dir/$_" }
1336 my ($field, $table) = reverse split('\.', $_);
1337 $table ||= 'cust_main';
1343 =item rebuild_fuzzyfiles
1347 sub rebuild_fuzzyfiles {
1349 use Fcntl qw(:flock);
1351 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1352 mkdir $dir, 0700 unless -d $dir;
1354 foreach my $fuzzy ( @fuzzyfields ) {
1356 my ($field, $table) = reverse split('\.', $fuzzy);
1357 $table ||= 'cust_main';
1359 open(LOCK,">>$dir/$table.$field")
1360 or die "can't open $dir/$table.$field: $!";
1362 or die "can't lock $dir/$table.$field: $!";
1364 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1365 or die "can't open $dir/$table.$field.tmp: $!";
1367 my $sth = dbh->prepare(
1368 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1370 $sth->execute or die $sth->errstr;
1372 while ( my $row = $sth->fetchrow_arrayref ) {
1373 print CACHE $row->[0]. "\n";
1376 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1378 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1384 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1388 sub append_fuzzyfiles {
1389 #my( $first, $last, $company ) = @_;
1391 check_and_rebuild_fuzzyfiles();
1393 #foreach my $fuzzy (@fuzzyfields) {
1394 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1395 'cust_location.address1',
1396 'cust_main.ship_company',
1399 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1406 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1408 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1412 use Fcntl qw(:flock);
1413 sub append_fuzzyfiles_fuzzyfield {
1414 my( $fuzzyfield, $value ) = @_;
1416 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1419 my ($field, $table) = reverse split('\.', $fuzzyfield);
1420 $table ||= 'cust_main';
1422 return unless defined($value) && length($value);
1424 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1425 or die "can't open $dir/$table.$field: $!";
1426 flock(CACHE,LOCK_EX)
1427 or die "can't lock $dir/$table.$field: $!";
1429 print CACHE "$value\n";
1431 flock(CACHE,LOCK_UN)
1432 or die "can't unlock $dir/$table.$field: $!";
1442 my( $self, $fuzzy ) = @_;
1443 my ($field, $table) = reverse split('\.', $fuzzy);
1444 $table ||= 'cust_main';
1446 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1447 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1448 or die "can't open $dir/$table.$field: $!";
1449 my @array = map { chomp; $_; } <CACHE>;
1460 L<FS::cust_main>, L<FS::Record>