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 || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
166 && $search =~ /^\s*(\w\w?\d+)\s*$/
168 || ( $conf->config('cust_main-custnum-display_special')
169 # it's not currently possible for special prefixes to contain
170 # digits, so just strip off any alphabetic prefix and match
171 # the rest to custnum
172 && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
174 || ( $conf->exists('address1-search' )
175 && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
182 if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
183 my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
184 ? ' AND agent_custid IS NULL ' : '';
185 push @cust_main, qsearch( {
186 'table' => 'cust_main',
187 'hashref' => { 'custnum' => $num, %options },
188 'extra_sql' => " AND $agentnums_sql $agent_custid_null",
192 # for all agents this user can see, if any of them have custnum prefixes
193 # that match the search string, include customers that match the rest
194 # of the custnum and belong to that agent
195 foreach my $agentnum ( keys %$agentnums_href ) {
196 my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
198 if ( $p eq substr($num, 0, length($p)) ) {
199 push @cust_main, qsearch( {
200 'table' => 'cust_main',
201 'hashref' => { 'custnum' => 0 + substr($num, length($p)),
202 'agentnum' => $agentnum,
209 push @cust_main, qsearch( {
210 'table' => 'cust_main',
211 'hashref' => { 'agent_custid' => $num, %options },
212 'extra_sql' => " AND $agentnums_sql", #agent virtualization
215 if ( $conf->exists('address1-search') ) {
216 my $len = length($num);
218 # probably the Right Thing: return customers that have any associated
219 # locations matching the string, not just bill/ship location
220 push @cust_main, qsearch( {
221 'table' => 'cust_main',
222 'addl_from' => ' JOIN cust_location USING (custnum) ',
223 'hashref' => { %options, },
225 ( keys(%options) ? ' AND ' : ' WHERE ' ).
226 " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
227 " AND $agentnums_sql",
231 } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
233 my($company, $last, $first) = ( $1, $2, $3 );
235 # "Company (Last, First)"
236 #this is probably something a browser remembered,
237 #so just do an exact search (but case-insensitive, so USPS standardization
238 #doesn't throw a wrench in the works)
240 push @cust_main, qsearch( {
241 'table' => 'cust_main',
242 'hashref' => { %options },
244 ( keys(%options) ? ' AND ' : ' WHERE ' ).
246 " LOWER(first) = ". dbh->quote(lc($first)),
247 " LOWER(last) = ". dbh->quote(lc($last)),
248 " LOWER(company) = ". dbh->quote(lc($company)),
254 # probably not necessary for the "something a browser remembered" case
256 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
257 # try {first,last,company}
261 # # remove "(Last, First)" in "Company (Last, First)", otherwise the
262 # # full strings the browser remembers won't work
263 # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
265 use Lingua::EN::NameParse;
266 my $NameParse = new Lingua::EN::NameParse(
271 my($last, $first) = ( '', '' );
272 #maybe disable this too and just rely on NameParse?
273 if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
275 ($last, $first) = ( $1, $2 );
277 #} elsif ( $value =~ /^(.+)\s+(.+)$/ ) {
278 } elsif ( ! $NameParse->parse($value) ) {
280 my %name = $NameParse->components;
281 $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
282 $last = $name{'surname_1'};
286 if ( $first && $last ) {
288 my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
291 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
292 $sql .= "( LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first )";
295 push @cust_main, qsearch( {
296 'table' => 'cust_main',
297 'hashref' => \%options,
298 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
303 grep $agentnums_href->{$_->agentnum}, #agent virt
304 grep $_, #skip contacts that don't have cust_main records
307 'table' => 'contact',
308 'hashref' => { 'first' => $first,
314 # or it just be something that was typed in... (try that in a sec)
318 my $q_value = dbh->quote($value);
321 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
322 $sql .= " ( LOWER(cust_main.first) = $q_value
323 OR LOWER(cust_main.last) = $q_value
324 OR LOWER(cust_main.company) = $q_value
325 OR LOWER(cust_main.ship_company) = $q_value
328 #address1 (yes, it's a kludge)
329 $sql .= " OR EXISTS (
330 SELECT 1 FROM cust_location
331 WHERE LOWER(cust_location.address1) = $q_value
332 AND cust_location.custnum = cust_main.custnum
334 if $conf->exists('address1-search');
336 #contacts (look, another kludge)
337 $sql .= " OR EXISTS ( SELECT 1 FROM contact
338 WHERE ( LOWER(contact.first) = $q_value
339 OR LOWER(contact.last) = $q_value
341 AND contact.custnum IS NOT NULL
342 AND contact.custnum = cust_main.custnum
346 push @cust_main, qsearch( {
347 'table' => 'cust_main',
348 'hashref' => \%options,
349 'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
352 #no exact match, trying substring/fuzzy
353 #always do substring & fuzzy (unless they're explicity config'ed off)
354 #getting complaints searches are not returning enough
355 unless ( @cust_main && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
357 #still some false laziness w/search (was search/cust_main.cgi)
361 my @company_hashrefs = ();
362 if ( length($value) >= 4 ) {
363 @company_hashrefs = (
364 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
365 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
370 if ( $first && $last ) {
373 { 'first' => { op=>'ILIKE', value=>"%$first%" },
374 'last' => { op=>'ILIKE', value=>"%$last%" },
378 } elsif ( length($value) >= 4 ) {
381 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
382 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
387 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
389 push @cust_main, qsearch( {
390 'table' => 'cust_main',
391 'hashref' => { %$hashref,
394 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
399 if ( $conf->exists('address1-search') && length($value) >= 4 ) {
401 push @cust_main, qsearch( {
402 table => 'cust_main',
403 addl_from => 'JOIN cust_location USING (custnum)',
404 extra_sql => 'WHERE '.
405 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
406 " AND $agentnums_sql", #agent virtualizaiton
413 foreach my $hashref ( @hashrefs ) {
416 grep $agentnums_href->{$_->agentnum}, #agent virt
417 grep $_, #skip contacts that don't have cust_main records
420 'table' => 'contact',
421 'hashref' => { %$hashref,
424 #'extra_sql' => " AND $agentnums_sql", #agent virt
431 'hashref' => \%options,
433 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
436 if ( $first && $last ) {
437 push @cust_main, FS::cust_main::Search->fuzzy_search(
438 { 'last' => $last, #fuzzy hashref
439 'first' => $first }, #
442 push @cust_main, FS::cust_main::Search->fuzzy_search(
443 { 'contact.last' => $last, #fuzzy hashref
444 'contact.first' => $first }, #
449 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
450 push @cust_main, FS::cust_main::Search->fuzzy_search(
451 { $field => $value },
455 foreach my $field ( 'first', 'last' ) {
456 push @cust_main, FS::cust_main::Search->fuzzy_search(
457 { "contact.$field" => $value },
461 if ( $conf->exists('address1-search') ) {
463 FS::cust_main::Search->fuzzy_search(
464 { 'cust_location.address1' => $value },
473 ( my $nospace_search = $search ) =~ s/\s//g;
474 ( my $card_search = $nospace_search ) =~ s/\-//g;
475 $card_search =~ s/[x\*\.\_]/x/gi;
477 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
479 ( my $like_search = $card_search ) =~ s/x/_/g;
480 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
482 push @cust_main, qsearch({
483 'table' => 'cust_main',
485 'extra_sql' => " WHERE ( payinfo LIKE '$like_search'
486 OR paymask = '$mask_search'
488 " AND payby IN ('CARD','DCRD') ".
489 " AND $agentnums_sql", #agent virtulization
495 #eliminate duplicates
497 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
505 Accepts the following options: I<email>, the email address to search for. The
506 email address will be searched for as an email invoice destination and as an
509 #Any additional options are treated as an additional qualifier on the search
512 Returns a (possibly empty) array of FS::cust_main objects (but usually just
520 my $email = delete $options{'email'};
522 #no agent virtualization yet
523 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
527 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
529 my ( $user, $domain ) = ( $1, $2 );
531 warn "$me smart_search: searching for $user in domain $domain"
537 'table' => 'cust_main_invoice',
538 'hashref' => { 'dest' => $email },
545 map $_->cust_svc->cust_pkg,
547 'table' => 'svc_acct',
548 'hashref' => { 'username' => $user, },
550 'AND ( SELECT domain FROM svc_domain
551 WHERE svc_acct.domsvc = svc_domain.svcnum
552 ) = '. dbh->quote($domain),
558 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
560 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
577 Returns a qsearch hash expression to search for parameters specified in
578 HASHREF. Valid parameters are
598 listref of start date, end date
602 listref of start date, end date
604 =item spouse_birthdate
606 listref of start date, end date
608 =item anniversary_date
610 listref of start date, end date
620 =item current_balance
622 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
635 my ($class, $params) = @_;
642 # initialize these to prevent warnings
650 'paydate_year' => '',
651 'invoice_terms' => '',
657 # explicit custnum(s)
660 if ( $params->{'custnum'} ) {
661 my @custnums = ref($params->{'custnum'}) ?
662 @{ $params->{'custnum'} } :
663 $params->{'custnum'};
665 'cust_main.custnum IN (' .
666 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
667 ')' if scalar(@custnums) > 0;
674 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
676 "cust_main.agentnum = $1";
683 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
684 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
685 : 'cust_main.salesnum IS NULL';
692 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
694 "cust_main.usernum = $1";
701 #prospect ordered active inactive suspended cancelled
702 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
703 my $method = $params->{'status'}. '_sql';
704 #push @where, $class->$method();
705 push @where, FS::cust_main->$method();
709 unless ( $params->{location_history} ) {
711 AND ( cust_location.locationnum IN ( cust_main.bill_locationnum,
712 cust_main.ship_locationnum
714 OR cust_location.locationnum IN (
715 SELECT locationnum FROM cust_pkg
716 WHERE cust_pkg.custnum = cust_main.custnum
717 AND locationnum IS NOT NULL
718 AND '. FS::cust_pkg->ncancelled_recurring_sql.'
726 if ( $params->{'address'} ) {
727 # allow this to be an arrayref
728 my @values = ($params->{'address'});
729 @values = @{$values[0]} if ref($values[0]);
731 foreach (grep /\S/, @values) {
732 my $address = dbh->quote('%'. lc($_). '%');
734 "LOWER(cust_location.address1) LIKE $address",
735 "LOWER(cust_location.address2) LIKE $address";
738 push @where, "EXISTS(
739 SELECT 1 FROM cust_location
740 WHERE cust_location.custnum = cust_main.custnum
741 AND (".join(' OR ',@orwhere).")
750 if ( $params->{'city'} =~ /\S/ ) {
751 my $city = dbh->quote($params->{'city'});
752 push @where, "EXISTS(
753 SELECT 1 FROM cust_location
754 WHERE cust_location.custnum = cust_main.custnum
755 AND cust_location.city = $city
763 if ( $params->{'county'} =~ /\S/ ) {
764 my $county = dbh->quote($params->{'county'});
765 push @where, "EXISTS(
766 SELECT 1 FROM cust_location
767 WHERE cust_location.custnum = cust_main.custnum
768 AND cust_location.county = $county
776 if ( $params->{'state'} =~ /\S/ ) {
777 my $state = dbh->quote($params->{'state'});
778 push @where, "EXISTS(
779 SELECT 1 FROM cust_location
780 WHERE cust_location.custnum = cust_main.custnum
781 AND cust_location.state = $state
789 if ( $params->{'zip'} =~ /\S/ ) {
790 my $zip = dbh->quote($params->{'zip'} . '%');
791 push @where, "EXISTS(
792 SELECT 1 FROM cust_location
793 WHERE cust_location.custnum = cust_main.custnum
794 AND cust_location.zip LIKE $zip
802 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
803 my $country = uc($1);
804 push @where, "EXISTS(
805 SELECT 1 FROM cust_location
806 WHERE cust_location.custnum = cust_main.custnum
807 AND cust_location.country = '$country'
815 if ( $params->{'refnum'} ) {
817 my @refnum = ref( $params->{'refnum'} )
818 ? @{ $params->{'refnum'} }
819 : ( $params->{'refnum'} );
821 @refnum = grep /^(\d*)$/, @refnum;
823 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
829 # parse cancelled package checkbox
834 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
835 unless $params->{'cancelled_pkgs'};
838 # "with email address(es)" checkbox
842 'EXISTS ( SELECT 1 FROM cust_main_invoice
843 WHERE cust_main_invoice.custnum = cust_main.custnum
845 )' # AND dest LIKE '%@%'
846 if $params->{'with_email'};
849 # "with postal mail invoices" checkbox
853 "EXISTS ( SELECT 1 FROM cust_main_invoice
854 WHERE cust_main_invoice.custnum = cust_main.custnum
856 if $params->{'POST'};
859 # "without postal mail invoices" checkbox
863 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
864 WHERE cust_main_invoice.custnum = cust_main.custnum
866 if $params->{'no_POST'};
869 # "tax exempt" checkbox
871 push @where, "cust_main.tax = 'Y'"
875 # "not tax exempt" checkbox
877 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
878 if $params->{'no_tax'};
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 foreach ( @tagnums ) {
1021 push @where, 'exists(select 1 from cust_tag where '.
1022 'cust_tag.custnum = cust_main.custnum and tagnum = '.
1025 } else { # matching any tag, not all
1026 my $tags_where = "0 < (select count(1) from cust_tag where "
1027 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1028 . join(',', @tagnums) . "))";
1030 push @where, $tags_where;
1038 if ( $params->{'pkg_classnum'} ) {
1039 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1040 @{ $params->{'pkg_classnum'} } :
1041 $params->{'pkg_classnum'};
1042 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1044 if ( @pkg_classnums ) {
1047 if ( $params->{'all_pkg_classnums'} ) {
1048 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1051 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1053 foreach (@pkg_where) {
1055 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1056 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1057 if ( not $params->{'any_pkg_status'} ) {
1058 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1060 push @where, "EXISTS($select_pkg)";
1066 # setup queries, subs, etc. for the search
1069 $orderby ||= 'ORDER BY custnum';
1071 # here is the agent virtualization
1073 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1075 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1078 # always make address fields available in results
1079 for my $pre ('bill_', 'ship_') {
1081 'LEFT JOIN cust_location AS '.$pre.'location '.
1082 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1085 # always make referral available in results
1086 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
1087 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1089 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1092 'cust_main.custnum',
1093 'cust_main.salesnum',
1094 # there's a good chance that we'll need these
1095 'cust_main.bill_locationnum',
1096 'cust_main.ship_locationnum',
1097 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1100 my(@extra_headers) = ();
1101 my(@extra_fields) = ();
1103 if ($params->{'flattened_pkgs'}) {
1107 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1109 if ($dbh->{Driver}->{Name} eq 'Pg') {
1114 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1115 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1120 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1121 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1122 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1123 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1125 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1126 "omitting package information from report.";
1129 my $header_query = "
1130 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1131 FROM cust_main $addl_from $extra_sql $pkgwhere
1132 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1135 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1136 $sth->execute() or die $sth->errstr;
1137 my $headerrow = $sth->fetchrow_arrayref;
1138 my $headercount = $headerrow ? $headerrow->[0] : 0;
1139 while($headercount) {
1140 unshift @extra_headers, "Package ". $headercount;
1141 unshift @extra_fields, eval q!sub {my $c = shift;
1142 my @a = split '\|', $c->magic;
1143 my $p = $a[!.--$headercount. q!];
1150 my $select = join(', ', @select);
1153 'table' => 'cust_main',
1154 'select' => $select,
1155 'addl_from' => $addl_from,
1157 'extra_sql' => $extra_sql,
1158 'order_by' => $orderby,
1159 'count_query' => $count_query,
1160 'extra_headers' => \@extra_headers,
1161 'extra_fields' => \@extra_fields,
1163 #warn Data::Dumper::Dumper($sql_query);
1168 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1170 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1171 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1174 Additional options are the same as FS::Record::qsearch
1181 # sensible defaults, then merge in any passed options
1183 'table' => 'cust_main',
1192 my @fuzzy_mod = 'i';
1193 my $conf = new FS::Conf;
1194 my $fuzziness = $conf->config('fuzzy-fuzziness');
1195 push @fuzzy_mod, $fuzziness if $fuzziness;
1197 check_and_rebuild_fuzzyfiles();
1198 foreach my $field ( keys %$fuzzy ) {
1200 my $all = $self->all_X($field);
1201 next unless scalar(@$all);
1204 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1205 next if !keys(%match);
1207 my $in_matches = 'IN (' .
1208 join(',', map { dbh->quote($_) } keys %match) .
1211 my $extra_sql = $fuzopts{extra_sql};
1212 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1213 $extra_sql .= ' AND ';
1215 $extra_sql .= 'WHERE ';
1217 $extra_sql .= "$field $in_matches";
1219 my $addl_from = $fuzopts{addl_from};
1220 if ( $field =~ /^cust_location\./ ) {
1221 $addl_from .= ' JOIN cust_location USING (custnum)';
1222 } elsif ( $field =~ /^contact\./ ) {
1223 $addl_from .= ' JOIN contact USING (custnum)';
1226 push @cust_main, qsearch({
1228 'addl_from' => $addl_from,
1229 'extra_sql' => $extra_sql,
1233 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1235 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1243 =head1 UTILITY SUBROUTINES
1247 =item check_and_rebuild_fuzzyfiles
1251 sub check_and_rebuild_fuzzyfiles {
1252 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1253 rebuild_fuzzyfiles()
1254 if grep { ! -e "$dir/$_" }
1256 my ($field, $table) = reverse split('\.', $_);
1257 $table ||= 'cust_main';
1263 =item rebuild_fuzzyfiles
1267 sub rebuild_fuzzyfiles {
1269 use Fcntl qw(:flock);
1271 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1272 mkdir $dir, 0700 unless -d $dir;
1274 foreach my $fuzzy ( @fuzzyfields ) {
1276 my ($field, $table) = reverse split('\.', $fuzzy);
1277 $table ||= 'cust_main';
1279 open(LOCK,">>$dir/$table.$field")
1280 or die "can't open $dir/$table.$field: $!";
1282 or die "can't lock $dir/$table.$field: $!";
1284 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1285 or die "can't open $dir/$table.$field.tmp: $!";
1287 my $sth = dbh->prepare(
1288 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1290 $sth->execute or die $sth->errstr;
1292 while ( my $row = $sth->fetchrow_arrayref ) {
1293 print CACHE $row->[0]. "\n";
1296 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1298 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1304 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1308 sub append_fuzzyfiles {
1309 #my( $first, $last, $company ) = @_;
1311 check_and_rebuild_fuzzyfiles();
1313 #foreach my $fuzzy (@fuzzyfields) {
1314 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1315 'cust_location.address1',
1316 'cust_main.ship_company',
1319 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1326 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1328 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1332 use Fcntl qw(:flock);
1333 sub append_fuzzyfiles_fuzzyfield {
1334 my( $fuzzyfield, $value ) = @_;
1336 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1339 my ($field, $table) = reverse split('\.', $fuzzyfield);
1340 $table ||= 'cust_main';
1342 return unless length($value);
1344 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1345 or die "can't open $dir/$table.$field: $!";
1346 flock(CACHE,LOCK_EX)
1347 or die "can't lock $dir/$table.$field: $!";
1349 print CACHE "$value\n";
1351 flock(CACHE,LOCK_UN)
1352 or die "can't unlock $dir/$table.$field: $!";
1362 my( $self, $fuzzy ) = @_;
1363 my ($field, $table) = reverse split('\.', $fuzzy);
1364 $table ||= 'cust_main';
1366 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1367 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1368 or die "can't open $dir/$table.$field: $!";
1369 my @array = map { chomp; $_; } <CACHE>;
1380 L<FS::cust_main>, L<FS::Record>