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 { 'company' => { op=>'ILIKE', value=>"%$value%" }, },
363 { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
368 if ( $first && $last ) {
371 { 'first' => { op=>'ILIKE', value=>"%$first%" },
372 'last' => { op=>'ILIKE', value=>"%$last%" },
379 { 'first' => { op=>'ILIKE', value=>"%$value%" }, },
380 { 'last' => { op=>'ILIKE', value=>"%$value%" }, },
384 foreach my $hashref ( @company_hashrefs, @hashrefs ) {
386 push @cust_main, qsearch( {
387 'table' => 'cust_main',
388 'hashref' => { %$hashref,
391 'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
396 if ( $conf->exists('address1-search') ) {
398 push @cust_main, qsearch( {
399 table => 'cust_main',
400 addl_from => 'JOIN cust_location USING (custnum)',
401 extra_sql => 'WHERE '.
402 ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
403 " AND $agentnums_sql", #agent virtualizaiton
410 foreach my $hashref ( @hashrefs ) {
413 grep $agentnums_href->{$_->agentnum}, #agent virt
414 grep $_, #skip contacts that don't have cust_main records
417 'table' => 'contact',
418 'hashref' => { %$hashref,
421 #'extra_sql' => " AND $agentnums_sql", #agent virt
428 'hashref' => \%options,
430 'extra_sql' => "WHERE $agentnums_sql", #agent virtualization
433 if ( $first && $last ) {
434 push @cust_main, FS::cust_main::Search->fuzzy_search(
435 { 'last' => $last, #fuzzy hashref
436 'first' => $first }, #
439 push @cust_main, FS::cust_main::Search->fuzzy_search(
440 { 'contact.last' => $last, #fuzzy hashref
441 'contact.first' => $first }, #
445 foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
446 push @cust_main, FS::cust_main::Search->fuzzy_search(
447 { $field => $value },
451 foreach my $field ( 'first', 'last' ) {
452 push @cust_main, FS::cust_main::Search->fuzzy_search(
453 { "contact.$field" => $value },
457 if ( $conf->exists('address1-search') ) {
459 FS::cust_main::Search->fuzzy_search(
460 { 'cust_location.address1' => $value },
469 ( my $nospace_search = $search ) =~ s/\s//g;
470 ( my $card_search = $nospace_search ) =~ s/\-//g;
471 $card_search =~ s/[x\*\.\_]/x/gi;
473 if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
475 ( my $like_search = $card_search ) =~ s/x/_/g;
476 my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
478 push @cust_main, qsearch({
479 'table' => 'cust_main',
480 'addl_from' => ' JOIN cust_payby USING (custnum)',
482 'extra_sql' => " WHERE ( cust_payby.payinfo LIKE '$like_search'
483 OR cust_payby.paymask = '$mask_search'
485 " AND cust_payby.payby IN ('CARD','DCRD') ".
486 " AND $agentnums_sql", #agent virtulization
492 #eliminate duplicates
494 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
502 Accepts the following options: I<email>, the email address to search for. The
503 email address will be searched for as an email invoice destination and as an
506 #Any additional options are treated as an additional qualifier on the search
509 Returns a (possibly empty) array of FS::cust_main objects (but usually just
519 my $email = delete $options{'email'};
521 #we're only being used by RT at the moment... no agent virtualization yet
522 #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
526 if ( $email =~ /([^@]+)\@([^@]+)/ ) {
528 my ( $user, $domain ) = ( $1, $2 );
530 warn "$me smart_search: searching for $user in domain $domain"
536 'table' => 'cust_main_invoice',
537 'hashref' => { 'dest' => $email },
544 map $_->cust_svc->cust_pkg,
546 'table' => 'svc_acct',
547 'hashref' => { 'username' => $user, },
549 'AND ( SELECT domain FROM svc_domain
550 WHERE svc_acct.domsvc = svc_domain.svcnum
551 ) = '. dbh->quote($domain),
557 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
559 warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
576 Returns a qsearch hash expression to search for parameters specified in
577 HASHREF. Valid parameters are
597 listref of start date, end date
601 listref of start date, end date
603 =item spouse_birthdate
605 listref of start date, end date
607 =item anniversary_date
609 listref of start date, end date
619 =item current_balance
621 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
634 my ($class, $params) = @_;
641 # initialize these to prevent warnings
649 'paydate_year' => '',
650 'invoice_terms' => '',
656 # explicit custnum(s)
659 if ( $params->{'custnum'} ) {
660 my @custnums = ref($params->{'custnum'}) ?
661 @{ $params->{'custnum'} } :
662 $params->{'custnum'};
664 'cust_main.custnum IN (' .
665 join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
666 ')' if scalar(@custnums) > 0;
673 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
675 "cust_main.agentnum = $1";
682 if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
683 push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
684 : 'cust_main.salesnum IS NULL';
691 if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
693 "cust_main.usernum = $1";
700 #prospect ordered active inactive suspended cancelled
701 if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
702 my $method = $params->{'status'}. '_sql';
703 #push @where, $class->$method();
704 push @where, FS::cust_main->$method();
710 if ( $params->{'address'} ) {
711 # allow this to be an arrayref
712 my @values = ($params->{'address'});
713 @values = @{$values[0]} if ref($values[0]);
715 foreach (grep /\S/, @values) {
716 my $address = dbh->quote('%'. lc($_). '%');
718 "LOWER(cust_location.address1) LIKE $address",
719 "LOWER(cust_location.address2) LIKE $address";
722 push @where, "EXISTS(
723 SELECT 1 FROM cust_location
724 WHERE cust_location.custnum = cust_main.custnum
725 AND (".join(' OR ',@orwhere).")
733 if ( $params->{'county'} =~ /\S/ ) {
734 my $county = dbh->quote($params->{'county'});
735 push @where, "EXISTS(
736 SELECT 1 FROM cust_location
737 WHERE cust_location.custnum = cust_main.custnum
738 AND cust_location.county = $county
745 if ( $params->{'state'} =~ /\S/ ) {
746 my $state = dbh->quote($params->{'state'});
747 push @where, "EXISTS(
748 SELECT 1 FROM cust_location
749 WHERE cust_location.custnum = cust_main.custnum
750 AND cust_location.state = $state
757 if ( $params->{'zip'} =~ /\S/ ) {
758 my $zip = dbh->quote($params->{'zip'} . '%');
759 push @where, "EXISTS(
760 SELECT 1 FROM cust_location
761 WHERE cust_location.custnum = cust_main.custnum
762 AND cust_location.zip LIKE $zip
769 if ( $params->{'country'} =~ /^(\w\w)$/ ) {
770 my $country = uc($1);
771 push @where, "EXISTS(
772 SELECT 1 FROM cust_location
773 WHERE cust_location.custnum = cust_main.custnum
774 AND cust_location.country = '$country'
781 if ( $params->{'refnum'} ) {
783 my @refnum = ref( $params->{'refnum'} )
784 ? @{ $params->{'refnum'} }
785 : ( $params->{'refnum'} );
787 @refnum = grep /^(\d*)$/, @refnum;
789 push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
795 # parse cancelled package checkbox
800 $pkgwhere .= "AND (cancel = 0 or cancel is null)"
801 unless $params->{'cancelled_pkgs'};
804 # "with email address(es)" checkbox
808 'EXISTS ( SELECT 1 FROM cust_main_invoice
809 WHERE cust_main_invoice.custnum = cust_main.custnum
811 )' # AND dest LIKE '%@%'
812 if $params->{'with_email'};
815 # "with postal mail invoices" checkbox
819 "EXISTS ( SELECT 1 FROM cust_main_invoice
820 WHERE cust_main_invoice.custnum = cust_main.custnum
822 if $params->{'POST'};
825 # "without postal mail invoices" checkbox
829 "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
830 WHERE cust_main_invoice.custnum = cust_main.custnum
832 if $params->{'no_POST'};
835 # "tax exempt" checkbox
837 push @where, "cust_main.tax = 'Y'"
841 # "not tax exempt" checkbox
843 push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
844 if $params->{'no_tax'};
850 foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
852 next unless exists($params->{$field});
854 my($beginning, $ending, $hour) = @{$params->{$field}};
857 "cust_main.$field IS NOT NULL",
858 "cust_main.$field >= $beginning",
859 "cust_main.$field <= $ending";
861 if($field eq 'signupdate' && defined $hour) {
862 if ($dbh->{Driver}->{Name} =~ /Pg/i) {
863 push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
865 elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
866 push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
869 warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
873 $orderby ||= "ORDER BY cust_main.$field";
881 if ( $params->{'classnum'} ) {
883 my @classnum = ref( $params->{'classnum'} )
884 ? @{ $params->{'classnum'} }
885 : ( $params->{'classnum'} );
887 @classnum = grep /^(\d*)$/, @classnum;
890 push @where, '( '. join(' OR ', map {
891 $_ ? "cust_main.classnum = $_"
892 : "cust_main.classnum IS NULL"
905 if ( $params->{'payby'} ) {
907 my @payby = ref( $params->{'payby'} )
908 ? @{ $params->{'payby'} }
909 : ( $params->{'payby'} );
911 @payby = grep /^([A-Z]{4})$/, @payby;
912 my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
913 push @where, "EXISTS( SELECT 1 FROM cust_payby WHERE payby $in_payby ".
914 "AND cust_payby.custnum = cust_main.custnum)"
919 # paydate_year / paydate_month
922 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
924 $params->{'paydate_month'} =~ /^(\d\d?)$/
925 or die "paydate_year without paydate_month?";
929 'paydate IS NOT NULL',
931 "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
939 if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
941 if ( $1 eq 'NULL' ) {
943 "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
946 "cust_main.invoice_terms IS NOT NULL",
947 "cust_main.invoice_terms = '$1'";
955 if ( $params->{'current_balance'} ) {
957 #my $balance_sql = $class->balance_sql();
958 my $balance_sql = FS::cust_main->balance_sql();
960 my @current_balance =
961 ref( $params->{'current_balance'} )
962 ? @{ $params->{'current_balance'} }
963 : ( $params->{'current_balance'} );
965 push @where, map { s/current_balance/$balance_sql/; $_ }
974 if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
976 "cust_main.custbatch = '$1'";
979 if ( $params->{'tagnum'} ) {
980 my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
982 @tagnums = grep /^(\d+)$/, @tagnums;
985 if ( $params->{'all_tags'} ) {
986 foreach ( @tagnums ) {
987 push @where, 'exists(select 1 from cust_tag where '.
988 'cust_tag.custnum = cust_main.custnum and tagnum = '.
991 } else { # matching any tag, not all
992 my $tags_where = "0 < (select count(1) from cust_tag where "
993 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
994 . join(',', @tagnums) . "))";
996 push @where, $tags_where;
1004 if ( $params->{'pkg_classnum'} ) {
1005 my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1006 @{ $params->{'pkg_classnum'} } :
1007 $params->{'pkg_classnum'};
1008 @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1010 if ( @pkg_classnums ) {
1013 if ( $params->{'all_pkg_classnums'} ) {
1014 push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1017 'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1019 foreach (@pkg_where) {
1021 "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1022 "cust_pkg.custnum = cust_main.custnum AND $_ ";
1023 if ( not $params->{'any_pkg_status'} ) {
1024 $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1026 push @where, "EXISTS($select_pkg)";
1032 # setup queries, subs, etc. for the search
1035 $orderby ||= 'ORDER BY custnum';
1037 # here is the agent virtualization
1039 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1041 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1044 # always make address fields available in results
1045 for my $pre ('bill_', 'ship_') {
1047 'LEFT JOIN cust_location AS '.$pre.'location '.
1048 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1051 my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1054 'cust_main.custnum',
1055 'cust_main.salesnum',
1056 # there's a good chance that we'll need these
1057 'cust_main.bill_locationnum',
1058 'cust_main.ship_locationnum',
1059 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1062 my(@extra_headers) = ();
1063 my(@extra_fields) = ();
1065 if ($params->{'flattened_pkgs'}) {
1069 ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1071 if ($dbh->{Driver}->{Name} eq 'Pg') {
1076 SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1077 WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1082 } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1083 push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1084 $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1085 #$pkg_join .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1087 warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
1088 "omitting package information from report.";
1091 my $header_query = "
1092 SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1093 FROM cust_main $addl_from $extra_sql $pkgwhere
1094 GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1097 my $sth = dbh->prepare($header_query) or die dbh->errstr;
1098 $sth->execute() or die $sth->errstr;
1099 my $headerrow = $sth->fetchrow_arrayref;
1100 my $headercount = $headerrow ? $headerrow->[0] : 0;
1101 while($headercount) {
1102 unshift @extra_headers, "Package ". $headercount;
1103 unshift @extra_fields, eval q!sub {my $c = shift;
1104 my @a = split '\|', $c->magic;
1105 my $p = $a[!.--$headercount. q!];
1112 my $select = join(', ', @select);
1115 'table' => 'cust_main',
1116 'select' => $select,
1117 'addl_from' => $addl_from,
1119 'extra_sql' => $extra_sql,
1120 'order_by' => $orderby,
1121 'count_query' => $count_query,
1122 'extra_headers' => \@extra_headers,
1123 'extra_fields' => \@extra_fields,
1125 #warn Data::Dumper::Dumper($sql_query);
1130 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1132 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1133 records. Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1136 Additional options are the same as FS::Record::qsearch
1143 # sensible defaults, then merge in any passed options
1145 'table' => 'cust_main',
1154 my @fuzzy_mod = 'i';
1155 my $conf = new FS::Conf;
1156 my $fuzziness = $conf->config('fuzzy-fuzziness');
1157 push @fuzzy_mod, $fuzziness if $fuzziness;
1159 check_and_rebuild_fuzzyfiles();
1160 foreach my $field ( keys %$fuzzy ) {
1162 my $all = $self->all_X($field);
1163 next unless scalar(@$all);
1166 $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1167 next if !keys(%match);
1169 my $in_matches = 'IN (' .
1170 join(',', map { dbh->quote($_) } keys %match) .
1173 my $extra_sql = $fuzopts{extra_sql};
1174 if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1175 $extra_sql .= ' AND ';
1177 $extra_sql .= 'WHERE ';
1179 $extra_sql .= "$field $in_matches";
1181 my $addl_from = $fuzopts{addl_from};
1182 if ( $field =~ /^cust_location\./ ) {
1183 $addl_from .= ' JOIN cust_location USING (custnum)';
1184 } elsif ( $field =~ /^contact\./ ) {
1185 $addl_from .= ' JOIN contact USING (custnum)';
1188 push @cust_main, qsearch({
1190 'addl_from' => $addl_from,
1191 'extra_sql' => $extra_sql,
1195 # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1197 @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1205 =head1 UTILITY SUBROUTINES
1209 =item check_and_rebuild_fuzzyfiles
1213 sub check_and_rebuild_fuzzyfiles {
1214 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1215 rebuild_fuzzyfiles()
1216 if grep { ! -e "$dir/$_" }
1218 my ($field, $table) = reverse split('\.', $_);
1219 $table ||= 'cust_main';
1225 =item rebuild_fuzzyfiles
1229 sub rebuild_fuzzyfiles {
1231 use Fcntl qw(:flock);
1233 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1234 mkdir $dir, 0700 unless -d $dir;
1236 foreach my $fuzzy ( @fuzzyfields ) {
1238 my ($field, $table) = reverse split('\.', $fuzzy);
1239 $table ||= 'cust_main';
1241 open(LOCK,">>$dir/$table.$field")
1242 or die "can't open $dir/$table.$field: $!";
1244 or die "can't lock $dir/$table.$field: $!";
1246 open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1247 or die "can't open $dir/$table.$field.tmp: $!";
1249 my $sth = dbh->prepare(
1250 "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1252 $sth->execute or die $sth->errstr;
1254 while ( my $row = $sth->fetchrow_arrayref ) {
1255 print CACHE $row->[0]. "\n";
1258 close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1260 rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1266 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1270 sub append_fuzzyfiles {
1271 #my( $first, $last, $company ) = @_;
1273 check_and_rebuild_fuzzyfiles();
1275 #foreach my $fuzzy (@fuzzyfields) {
1276 foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company',
1277 'cust_location.address1',
1278 'cust_main.ship_company',
1281 append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1288 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1290 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1294 use Fcntl qw(:flock);
1295 sub append_fuzzyfiles_fuzzyfield {
1296 my( $fuzzyfield, $value ) = @_;
1298 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1301 my ($field, $table) = reverse split('\.', $fuzzyfield);
1302 $table ||= 'cust_main';
1304 return unless defined($value) && length($value);
1306 open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1307 or die "can't open $dir/$table.$field: $!";
1308 flock(CACHE,LOCK_EX)
1309 or die "can't lock $dir/$table.$field: $!";
1311 print CACHE "$value\n";
1313 flock(CACHE,LOCK_UN)
1314 or die "can't unlock $dir/$table.$field: $!";
1324 my( $self, $fuzzy ) = @_;
1325 my ($field, $table) = reverse split('\.', $fuzzy);
1326 $table ||= 'cust_main';
1328 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1329 open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1330 or die "can't open $dir/$table.$field: $!";
1331 my @array = map { chomp; $_; } <CACHE>;
1342 L<FS::cust_main>, L<FS::Record>