spacing, and order like sql, RT#77532
[freeside.git] / FS / FS / cust_main / Search.pm
1 package FS::cust_main::Search;
2
3 use strict;
4 use Carp qw( croak );
5 use base qw( Exporter );
6 use vars qw( @EXPORT_OK $DEBUG $me $conf @fuzzyfields );
7 use String::Approx qw(amatch);
8 use FS::UID qw( dbh );
9 use FS::Record qw( qsearch );
10 use FS::cust_main;
11 use FS::cust_main_invoice;
12 use FS::svc_acct;
13 use FS::payinfo_Mixin;
14
15 @EXPORT_OK = qw( smart_search );
16
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
20 $DEBUG = 0;
21 $me = '[FS::cust_main::Search]';
22
23 @fuzzyfields = (
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',
28 );
29
30 install_callback FS::UID sub { 
31   $conf = new FS::Conf;
32   #yes, need it for stuff below (prolly should be cached)
33 };
34
35 =head1 NAME
36
37 FS::cust_main::Search - Customer searching
38
39 =head1 SYNOPSIS
40
41   use FS::cust_main::Search;
42
43   FS::cust_main::Search::smart_search(%options);
44
45   FS::cust_main::Search::email_search(%options);
46
47   FS::cust_main::Search->search( \%options );
48   
49   FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
50
51 =head1 SUBROUTINES
52
53 =over 4
54
55 =item smart_search OPTION => VALUE ...
56
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
60 number.
61
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
64 smart_search to
65 skip fuzzy matching when an exact match is found.
66
67 Any additional options are treated as an additional qualifier on the search
68 (i.e. I<agentnum>).
69
70 Returns a (possibly empty) array of FS::cust_main objects.
71
72 =cut
73
74 sub smart_search {
75   my %options = @_;
76
77   #here is the agent virtualization
78   my $agentnums_sql = 
79     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
80   my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
81
82   my @cust_main = ();
83
84   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
85   my $search = delete $options{'search'};
86   ( my $alphanum_search = $search ) =~ s/\W//g;
87   
88   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
89
90     #false laziness w/Record::ut_phone
91     my $phonen = "$1-$2-$3";
92     $phonen .= " x$4" if $4;
93
94     my $phonenum = "$1$2$3";
95     #my $extension = $4;
96
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 ' ).
105                      ' ( '.
106                          join(' OR ', map "$_ = '$phonen'",
107                                           qw( daytime night mobile fax )
108                              ).
109                           " OR phonenum = '$phonenum' ".
110                      ' ) '.
111                      " AND $agentnums_sql", #agent virtualization
112     } );
113
114     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
115       #try looking for matches with extensions unless one was specified
116
117       push @cust_main, qsearch( {
118         'table'     => 'cust_main',
119         'hashref'   => { %options },
120         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
121                        ' ( '.
122                            join(' OR ', map "$_ LIKE '$phonen\%'",
123                                             qw( daytime night )
124                                ).
125                        ' ) '.
126                        " AND $agentnums_sql", #agent virtualization
127       } );
128
129     }
130
131   } 
132   
133   
134   if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
135
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 ' ).
144                      ' ( '.
145                          join(' OR ', map "$_ = '$search'",
146                                           qw( dest emailaddress )
147                              ).
148                      ' ) '.
149                      " AND $agentnums_sql", #agent virtualization
150     } );
151
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*$/
157                )
158             or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
159                  && $search =~ /^\s*(\d+-\w)\s*$/
160                )
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*$/
166                )
167             or ( $conf->exists('address1-search' )
168                  && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
169                )
170           )
171   {
172
173     my $num = $1;
174
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",
182       } );
183     }
184
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);
190       next if !$p;
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,
196                           %options,
197                        },
198         } );
199       }
200     }
201
202     push @cust_main, qsearch( {
203         'table'     => 'cust_main',
204         'hashref'   => { 'agent_custid' => $num, %options },
205         'extra_sql' => " AND $agentnums_sql", #agent virtualization
206     } );
207
208     if ( $conf->exists('address1-search') ) {
209       my $len = length($num);
210       $num = lc($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         'table'     => 'cust_main',
215         'addl_from' => ' JOIN cust_location USING (custnum) ',
216         'hashref'   => { %options, },
217         'extra_sql' => 
218           ( keys(%options) ? ' AND ' : ' WHERE ' ).
219           " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
220           " AND $agentnums_sql",
221       } );
222     }
223
224   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
225
226     my($company, $last, $first) = ( $1, $2, $3 );
227
228     # "Company (Last, First)"
229     #this is probably something a browser remembered,
230     #so just do an exact search (but case-insensitive, so USPS standardization
231     #doesn't throw a wrench in the works)
232
233     push @cust_main, qsearch( {
234         'table'     => 'cust_main',
235         'hashref'   => { %options },
236         'extra_sql' => 
237         ( keys(%options) ? ' AND ' : ' WHERE ' ).
238         join(' AND ',
239           " LOWER(first)   = ". dbh->quote(lc($first)),
240           " LOWER(last)    = ". dbh->quote(lc($last)),
241           " LOWER(company) = ". dbh->quote(lc($company)),
242           $agentnums_sql,
243         ),
244       } ),
245
246     #contacts?
247     # probably not necessary for the "something a browser remembered" case
248
249   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
250                                               # try {first,last,company}
251
252     my $value = lc($1);
253
254     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
255     # # full strings the browser remembers won't work
256     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
257
258     use Lingua::EN::NameParse;
259     my $NameParse = new Lingua::EN::NameParse(
260              auto_clean     => 1,
261              allow_reversed => 1,
262     );
263
264     my($last, $first) = ( '', '' );
265     #maybe disable this too and just rely on NameParse?
266     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
267     
268       ($last, $first) = ( $1, $2 );
269     
270     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
271     } elsif ( ! $NameParse->parse($value) ) {
272
273       my %name = $NameParse->components;
274       $first = lc($name{'given_name_1'}) || $name{'initials_1'}; #wtf NameParse, Ed?
275       $last  = lc($name{'surname_1'});
276
277     }
278
279     if ( $first && $last ) {
280
281       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
282
283       #exact
284       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
285       $sql .= "( (LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first)
286                  OR (LOWER(contact.last) = $q_last AND LOWER(contact.first) = $q_first) )";
287
288       #cust_main and contacts
289       push @cust_main, qsearch( {
290         'select'    => 'cust_main.*',
291         'table'     => 'cust_main',
292         'addl_from' => ' left join cust_contact using (custnum) '.
293                        ' left join contact using (contactnum) ',
294         'hashref'   => { %options },
295         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
296       } );
297
298       # or it just be something that was typed in... (try that in a sec)
299
300     }
301
302     my $q_value = dbh->quote($value);
303
304     #exact
305     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
306     $sql .= " (    LOWER(cust_main.first)         = $q_value
307                 OR LOWER(cust_main.last)          = $q_value
308                 OR LOWER(cust_main.company)       = $q_value
309                 OR LOWER(cust_main.ship_company)  = $q_value
310                 OR LOWER(contact.first)           = $q_value
311                 OR LOWER(contact.last)            = $q_value
312             )";
313
314     #address1 (yes, it's a kludge)
315     $sql .= "   OR EXISTS ( 
316                             SELECT 1 FROM cust_location 
317                               WHERE LOWER(cust_location.address1) = $q_value
318                                 AND cust_location.custnum = cust_main.custnum
319                           )"
320       if $conf->exists('address1-search');
321
322     push @cust_main, qsearch( {
323       'select'    => 'cust_main.*',
324       'table'     => 'cust_main',
325       'addl_from' => ' left join cust_contact using (custnum) '.
326                      ' left join contact using (contactnum) ',
327       'hashref'   => { %options },
328       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
329     } );
330
331     #no exact match, trying substring/fuzzy
332     #always do substring & fuzzy (unless they're explicity config'ed off)
333     #getting complaints searches are not returning enough
334     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
335
336       #still some false laziness w/search (was search/cust_main.cgi)
337
338       my $min_len =
339         $FS::CurrentUser::CurrentUser->access_right('List all customers')
340         ? 3 : 4;
341
342       #substring
343
344       my @company_hashrefs = ();
345       if ( length($value) >= $min_len ) {
346         @company_hashrefs = (
347           { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
348           { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
349         );
350       }
351
352       my @hashrefs = ();
353       if ( $first && $last ) {
354
355         @hashrefs = (
356           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
357             'last'         => { op=>'ILIKE', value=>"%$last%" },
358           },
359         );
360
361       } elsif ( length($value) >= $min_len ) {
362
363         @hashrefs = (
364           { 'first'        => { op=>'ILIKE', value=>"%$value%" }, },
365           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
366         );
367
368       }
369
370       foreach my $hashref ( @company_hashrefs, @hashrefs ) {
371
372         push @cust_main, qsearch( {
373           'table'     => 'cust_main',
374           'hashref'   => { %$hashref,
375                            %options,
376                          },
377           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
378         } );
379
380       }
381
382       if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
383
384         push @cust_main, qsearch( {
385           table     => 'cust_main',
386           addl_from => 'JOIN cust_location USING (custnum)',
387           extra_sql => 'WHERE '.
388                         ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
389                         " AND $agentnums_sql", #agent virtualizaiton
390         } );
391
392       }
393
394       #contact substring
395
396       foreach my $hashref ( @hashrefs ) {
397
398         push @cust_main,
399           grep $agentnums_href->{$_->agentnum}, #agent virt
400             grep $_, #skip contacts that don't have cust_main records
401               map $_->cust_main,
402                 qsearch({
403                           'table'     => 'contact',
404                           'hashref'   => { %$hashref,
405                                            #%options,
406                                          },
407                           #'extra_sql' => " AND $agentnums_sql", #agent virt
408                        });
409
410       }
411
412       #fuzzy
413       my %fuzopts = (
414         'hashref'   => \%options,
415         'select'    => '',
416         'extra_sql' => "WHERE $agentnums_sql",    #agent virtualization
417       );
418
419       if ( $first && $last ) {
420         push @cust_main, FS::cust_main::Search->fuzzy_search(
421           { 'last'   => $last,    #fuzzy hashref
422             'first'  => $first }, #
423           %fuzopts
424         );
425         push @cust_main, FS::cust_main::Search->fuzzy_search(
426           { 'contact.last'   => $last,    #fuzzy hashref
427             'contact.first'  => $first }, #
428           %fuzopts
429         );
430       }
431
432       foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
433         push @cust_main, FS::cust_main::Search->fuzzy_search(
434           { $field => $value },
435           %fuzopts
436         );
437       }
438       foreach my $field ( 'first', 'last' ) {
439         push @cust_main, FS::cust_main::Search->fuzzy_search(
440           { "contact.$field" => $value },
441           %fuzopts
442         );
443       }
444       if ( $conf->exists('address1-search') ) {
445         push @cust_main,
446           FS::cust_main::Search->fuzzy_search(
447             { 'cust_location.address1' => $value },
448             %fuzopts
449         );
450       }
451
452     }
453
454   }
455
456   ( my $nospace_search = $search ) =~ s/\s//g;
457   ( my $card_search = $nospace_search ) =~ s/\-//g;
458   $card_search =~ s/[x\*\.\_]/x/gi;
459   
460   if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
461
462     ( my $like_search = $card_search ) =~ s/x/_/g;
463     my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
464
465     push @cust_main, qsearch({
466       'table'     => 'cust_main',
467       'addl_from' => ' JOIN cust_payby USING (custnum)',
468       'hashref'   => {},
469       'extra_sql' => " WHERE (    cust_payby.payinfo LIKE '$like_search'
470                                OR cust_payby.paymask =    '$mask_search'
471                              ) ".
472                      " AND cust_payby.payby IN ('CARD','DCRD') ".
473                      " AND $agentnums_sql", #agent virtulization
474     });
475
476   }
477   
478
479   #eliminate duplicates
480   my %saw = ();
481   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
482
483   @cust_main;
484
485 }
486
487 =item email_search
488
489 Accepts the following options: I<email>, the email address to search for.  The
490 email address will be searched for as an email invoice destination and as an
491 svc_acct account.
492
493 #Any additional options are treated as an additional qualifier on the search
494 #(i.e. I<agentnum>).
495
496 Returns a (possibly empty) array of FS::cust_main objects (but usually just
497 none or one).
498
499 =cut
500
501 sub email_search {
502   my %options = @_;
503
504   my $email = delete $options{'email'};
505
506   #no agent virtualization yet
507   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
508
509   my @cust_main = ();
510
511   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
512
513     my ( $user, $domain ) = ( $1, $2 );
514
515     warn "$me smart_search: searching for $user in domain $domain"
516       if $DEBUG;
517
518     push @cust_main,
519       map { $_->cust_main }
520       map { $_->cust_contact }
521       map { $_->contact }
522           qsearch( {
523                      'table'     => 'contact_email',
524                      'hashref'   => { 'emailaddress' => $email },
525                    }
526                  );
527
528     push @cust_main,
529       map  $_->cust_main,
530       grep $_,
531       map  $_->cust_svc->cust_pkg,
532           qsearch( {
533                      'table'     => 'svc_acct',
534                      'hashref'   => { 'username' => $user, },
535                      'extra_sql' =>
536                        'AND ( SELECT domain FROM svc_domain
537                                 WHERE svc_acct.domsvc = svc_domain.svcnum
538                             ) = '. dbh->quote($domain),
539                    }
540                  );
541   }
542
543   my %saw = ();
544   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
545
546   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
547     if $DEBUG;
548
549   @cust_main;
550
551 }
552
553 =back
554
555 =head1 CLASS METHODS
556
557 =over 4
558
559 =item search HASHREF
560
561 (Class method)
562
563 Returns a qsearch hash expression to search for parameters specified in
564 HASHREF.  Valid parameters are
565
566 =over 4
567
568 =item agentnum
569
570 =item status
571
572 =item address
573
574 =item zip
575
576 =item refnum
577
578 =item cancelled_pkgs
579
580 bool
581
582 =item signupdate
583
584 listref of start date, end date
585
586 =item birthdate
587
588 listref of start date, end date
589
590 =item spouse_birthdate
591
592 listref of start date, end date
593
594 =item anniversary_date
595
596 listref of start date, end date
597
598 =item current_balance
599
600 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
601
602 =item cust_fields
603
604 =item flattened_pkgs
605
606 bool
607
608 =back
609
610 =cut
611
612 sub search {
613   my ($class, $params) = @_;
614
615   my $dbh = dbh;
616
617   my @where = ();
618   my $orderby;
619
620   # initialize these to prevent warnings
621   $params = {
622     'custnum'       => '',
623     'agentnum'      => '',
624     'usernum'       => '',
625     'status'        => '',
626     'address'       => '',
627     'zip'           => '',
628     'invoice_terms' => '',
629     'custbatch'     => '',
630     %$params
631   };
632
633   ##
634   # explicit custnum(s)
635   ##
636
637   if ( $params->{'custnum'} ) {
638     my @custnums = ref($params->{'custnum'}) ? 
639                       @{ $params->{'custnum'} } : 
640                       $params->{'custnum'};
641     push @where, 
642       'cust_main.custnum IN (' . 
643       join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
644       ')' if scalar(@custnums) > 0;
645   }
646
647   ##
648   # parse agent
649   ##
650
651   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
652     push @where,
653       "cust_main.agentnum = $1";
654   }
655
656   ##
657   # parse sales person
658   ##
659
660   if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
661     push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
662                            : 'cust_main.salesnum IS NULL';
663   }
664
665   ##
666   # parse usernum
667   ##
668
669   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
670     push @where,
671       "cust_main.usernum = $1";
672   }
673
674   ##
675   # parse status
676   ##
677
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();
683   }
684
685   my $current = '';
686   unless ( $params->{location_history} ) {
687     $current = '
688       AND (    cust_location.locationnum IN ( cust_main.bill_locationnum,
689                                               cust_main.ship_locationnum
690                                             )
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.'
696                )
697           )';
698   }
699
700   ##
701   # address
702   ##
703   if ( $params->{'address'} ) {
704     # allow this to be an arrayref
705     my @values = ($params->{'address'});
706     @values = @{$values[0]} if ref($values[0]);
707     my @orwhere;
708     foreach (grep /\S/, @values) {
709       my $address = dbh->quote('%'. lc($_). '%');
710       push @orwhere,
711         "LOWER(cust_location.address1) LIKE $address",
712         "LOWER(cust_location.address2) LIKE $address";
713     }
714     if (@orwhere) {
715       push @where, "EXISTS(
716         SELECT 1 FROM cust_location 
717         WHERE cust_location.custnum = cust_main.custnum
718           AND (".join(' OR ',@orwhere).")
719           $current
720         )";
721     }
722   }
723
724   ##
725   # city
726   ##
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
733         $current
734     )";
735   }
736
737   ##
738   # county
739   ##
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
746         $current
747     )";
748   }
749
750   ##
751   # state
752   ##
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
759         $current
760     )";
761   }
762
763   ##
764   # zipcode
765   ##
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
772         $current
773     )";
774   }
775
776   ##
777   # country
778   ##
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'
785         $current
786     )";
787   }
788
789   ###
790   # refnum
791   ###
792   if ( $params->{'refnum'}  ) {
793
794     my @refnum = ref( $params->{'refnum'} )
795                    ? @{ $params->{'refnum'} }
796                    :  ( $params->{'refnum'} );
797
798     @refnum = grep /^(\d*)$/, @refnum;
799
800     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
801       if @refnum;
802
803   }
804
805   ##
806   # parse cancelled package checkbox
807   ##
808
809   my $pkgwhere = "";
810
811   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
812     unless $params->{'cancelled_pkgs'};
813
814   ##
815   # "with email address(es)" checkbox,
816   #    also optionally: with_email_dest and with_contact_type
817   ##
818
819   if ($params->{with_email}) {
820     my @email_dest;
821     my $email_dest_sql;
822     my $contact_type_sql;
823
824     if ($params->{with_email_dest}) {
825       croak unless ref $params->{with_email_dest} eq 'ARRAY';
826
827       @email_dest = @{$params->{with_email_dest}};
828       $email_dest_sql =
829         " AND ( ".
830         join(' OR ',map(" cust_contact.${_}_dest IS NOT NULL ", @email_dest)).
831         " ) ";
832         # Can't use message_dist = 'Y' because single quotes are escaped later
833     }
834     if ($params->{with_contact_type}) {
835       croak unless ref $params->{with_contact_type} eq 'ARRAY';
836
837       my @contact_type = grep {/^\d+$/ && $_ > 0} @{$params->{with_contact_type}};
838       my $has_null_type = 0;
839       $has_null_type = 1 if grep { $_ eq 0 } @{$params->{with_contact_type}};
840       my $hnt_sql;
841       if ($has_null_type) {
842         $hnt_sql  = ' OR ' if @contact_type;
843         $hnt_sql .= ' cust_contact.classnum IS NULL ';
844       }
845
846       $contact_type_sql =
847         " AND ( ".
848         join(' OR ', map(" cust_contact.classnum = $_ ", @contact_type)).
849         $hnt_sql.
850         " ) ";
851     }
852     push @where,
853       "EXISTS ( SELECT 1 FROM contact_email
854                 JOIN cust_contact USING (contactnum)
855                 WHERE cust_contact.custnum = cust_main.custnum
856                 $email_dest_sql
857                 $contact_type_sql
858               ) ";
859   }
860
861   ##
862   # "with postal mail invoices" checkbox
863   ##
864
865   push @where, "cust_main.postal_invoice = 'Y'"
866     if $params->{'POST'};
867
868   ##
869   # "without postal mail invoices" checkbox
870   ##
871
872   push @where, "cust_main.postal_invoice IS NULL"
873     if $params->{'no_POST'};
874
875   ##
876   # "tax exempt" checkbox
877   ##
878   push @where, "cust_main.tax = 'Y'"
879     if $params->{'tax'};
880
881   ##
882   # "not tax exempt" checkbox
883   ##
884   push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
885     if $params->{'no_tax'};
886
887   ##
888   # with referrals
889   ##
890   if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
891
892     my $n = $1;
893   
894     # referral status
895     my $and_status = '';
896     if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
897       my $method = $params->{referral_status}. '_sql';
898       $and_status = ' AND '. FS::cust_main->$method();
899       $and_status =~ s/ cust_main\./ referred_cust_main./g;
900     }
901
902     push @where,
903       " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
904                   WHERE cust_main.custnum = referred_cust_main.referral_custnum
905                     $and_status
906               )";
907
908   }
909
910   ##
911   # dates
912   ##
913
914   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
915
916     next unless exists($params->{$field});
917
918     my($beginning, $ending, $hour) = @{$params->{$field}};
919
920     push @where,
921       "cust_main.$field IS NOT NULL",
922       "cust_main.$field >= $beginning",
923       "cust_main.$field <= $ending";
924
925     if($field eq 'signupdate' && defined $hour) {
926       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
927         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
928       }
929       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
930         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
931       }
932       else {
933         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
934       }
935     }
936
937     $orderby ||= "ORDER BY cust_main.$field";
938
939   }
940
941   ###
942   # classnum
943   ###
944
945   if ( $params->{'classnum'} ) {
946
947     my @classnum = ref( $params->{'classnum'} )
948                      ? @{ $params->{'classnum'} }
949                      :  ( $params->{'classnum'} );
950
951     @classnum = grep /^(\d*)$/, @classnum;
952
953     if ( @classnum ) {
954       push @where, '( '. join(' OR ', map {
955                                             $_ ? "cust_main.classnum = $_"
956                                                : "cust_main.classnum IS NULL"
957                                           }
958                                           @classnum
959                              ).
960                    ' )';
961     }
962
963   }
964
965   ###
966   # invoice terms
967   ###
968
969   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
970     my $terms = $1;
971     if ( $1 eq 'NULL' ) {
972       push @where,
973         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
974     } else {
975       push @where,
976         "cust_main.invoice_terms IS NOT NULL",
977         "cust_main.invoice_terms = '$1'";
978     }
979   }
980
981   ##
982   # amounts
983   ##
984
985   if ( $params->{'current_balance'} ) {
986
987     #my $balance_sql = $class->balance_sql();
988     my $balance_sql = FS::cust_main->balance_sql();
989
990     my @current_balance =
991       ref( $params->{'current_balance'} )
992       ? @{ $params->{'current_balance'} }
993       :  ( $params->{'current_balance'} );
994
995     push @where, map { s/current_balance/$balance_sql/; $_ }
996                      @current_balance;
997
998   }
999
1000   ##
1001   # custbatch
1002   ##
1003
1004   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
1005     push @where,
1006       "cust_main.custbatch = '$1'";
1007   }
1008   
1009   if ( $params->{'tagnum'} ) {
1010     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1011
1012     @tagnums = grep /^(\d+)$/, @tagnums;
1013
1014     if ( @tagnums ) {
1015       if ( $params->{'all_tags'} ) {
1016         foreach ( @tagnums ) {
1017           push @where, 'exists(select 1 from cust_tag where '.
1018                        'cust_tag.custnum = cust_main.custnum and tagnum = '.
1019                        $_ . ')';
1020         }
1021       } else { # matching any tag, not all
1022         my $tags_where = "0 < (select count(1) from cust_tag where " 
1023                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1024                 . join(',', @tagnums) . "))";
1025
1026         push @where, $tags_where;
1027       }
1028     }
1029   }
1030
1031   # pkg_classnum
1032   #   all_pkg_classnums
1033   #   any_pkg_status
1034   if ( $params->{'pkg_classnum'} ) {
1035     my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1036                           @{ $params->{'pkg_classnum'} } :
1037                              $params->{'pkg_classnum'};
1038     @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1039
1040     if ( @pkg_classnums ) {
1041
1042       my @pkg_where;
1043       if ( $params->{'all_pkg_classnums'} ) {
1044         push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1045       } else {
1046         push @pkg_where,
1047           'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1048       }
1049       foreach (@pkg_where) {
1050         my $select_pkg = 
1051           "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1052           "cust_pkg.custnum = cust_main.custnum AND $_ ";
1053         if ( not $params->{'any_pkg_status'} ) {
1054           $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1055         }
1056         push @where, "EXISTS($select_pkg)";
1057       }
1058     }
1059   }
1060
1061   ##
1062   # setup queries, subs, etc. for the search
1063   ##
1064
1065   $orderby ||= 'ORDER BY custnum';
1066
1067   # here is the agent virtualization
1068   push @where,
1069     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1070
1071   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1072
1073   my $addl_from = '';
1074   # always make address fields available in results
1075   for my $pre ('bill_', 'ship_') {
1076     $addl_from .= 
1077       'LEFT JOIN cust_location AS '.$pre.'location '.
1078       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1079   }
1080
1081   # always make referral available in results
1082   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
1083   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1084
1085   my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1086
1087   my @select = (
1088                  'cust_main.custnum',
1089                  'cust_main.salesnum',
1090                  # there's a good chance that we'll need these
1091                  'cust_main.bill_locationnum',
1092                  'cust_main.ship_locationnum',
1093                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1094                );
1095
1096   my @extra_headers     = ();
1097   my @extra_fields      = ();
1098   my @extra_sort_fields = ();
1099
1100   ## search contacts
1101   if ($params->{'contacts'}) {
1102     my $contact_params = $params->{'contacts'};
1103
1104     $addl_from .=
1105       ' LEFT JOIN cust_contact ON ( cust_main.custnum = cust_contact.custnum ) ';
1106
1107     if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
1108       $addl_from .= ' LEFT JOIN contact ON ( cust_contact.contactnum = contact.contactnum ) ';
1109       my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
1110         unless !$contact_params->{'contacts_firstname'};
1111       my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
1112         unless !$contact_params->{'contacts_lastname'};
1113       $extra_sql .= " AND ( '1' $first_query $last_query )";
1114     }
1115
1116     if ($contact_params->{'contacts_email'}) {
1117       $addl_from .= ' LEFT JOIN contact_email ON ( cust_contact.contactnum = contact_email.contactnum ) ';
1118       $extra_sql .= " AND ( contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "' )";
1119     }
1120
1121     if ($contact_params->{'contacts_homephone'} || $contact_params->{'contacts_workphone'} || $contact_params->{'contacts_mobilephone'}) {
1122       $addl_from .= ' LEFT JOIN contact_phone ON ( cust_contact.contactnum = contact_phone.contactnum ) ';
1123       my $contacts_mobilephone;
1124       foreach my $phone (qw( contacts_homephone contacts_workphone contacts_mobilephone )) {
1125         (my $num = $contact_params->{$phone}) =~ s/\W//g;
1126         if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
1127       }
1128       my $home_query = " AND ( contact_phone.phonetypenum = '2' AND contact_phone.phonenum = '" . $contact_params->{'contacts_homephone'} . "' )"
1129         unless !$contact_params->{'contacts_homephone'};
1130       my $work_query = " AND ( contact_phone.phonetypenum = '1' AND contact_phone.phonenum = '" . $contact_params->{'contacts_workphone'} . "' )"
1131         unless !$contact_params->{'contacts_workphone'};
1132       my $mobile_query = " AND ( contact_phone.phonetypenum = '3' AND contact_phone.phonenum = '" . $contact_params->{'contacts_mobilephone'} . "' )"
1133         unless !$contact_params->{'contacts_mobilephone'};
1134       $extra_sql .= " AND ( '1' $home_query $work_query $mobile_query )";
1135     }
1136
1137   }
1138
1139   if ($params->{'flattened_pkgs'}) {
1140
1141     #my $pkg_join = '';
1142     $addl_from .=
1143       ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1144
1145     if ($dbh->{Driver}->{Name} eq 'Pg') {
1146
1147       push @select, "
1148         ARRAY_TO_STRING(
1149           ARRAY(
1150             SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1151               WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1152           ), '|'
1153         ) AS magic
1154       ";
1155
1156     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1157       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1158       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1159       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1160     } else {
1161       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
1162            "omitting package information from report.";
1163     }
1164
1165     my $header_query = "
1166       SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1167         FROM cust_main $addl_from $extra_sql $pkgwhere
1168           GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1169     ";
1170
1171     my $sth = dbh->prepare($header_query) or die dbh->errstr;
1172     $sth->execute() or die $sth->errstr;
1173     my $headerrow = $sth->fetchrow_arrayref;
1174     my $headercount = $headerrow ? $headerrow->[0] : 0;
1175     while($headercount) {
1176       unshift @extra_headers, "Package ". $headercount;
1177       unshift @extra_fields, eval q!sub {my $c = shift;
1178                                          my @a = split '\|', $c->magic;
1179                                          my $p = $a[!.--$headercount. q!];
1180                                          $p;
1181                                         };!;
1182       unshift @extra_sort_fields, '';
1183     }
1184
1185   }
1186
1187   if ( $params->{'with_referrals'} ) {
1188
1189     #XXX next: num for each customer status
1190      
1191     push @select,
1192       '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1193            WHERE cust_main.custnum = referred_cust_main.referral_custnum
1194        ) AS num_referrals';
1195
1196     unshift @extra_headers, 'Referrals';
1197     unshift @extra_fields, 'num_referrals';
1198     unshift @extra_sort_fields, 'num_referrals';
1199
1200   }
1201
1202   my $select = join(', ', @select);
1203
1204   my $sql_query = {
1205     'table'             => 'cust_main',
1206     'select'            => $select,
1207     'addl_from'         => $addl_from,
1208     'hashref'           => {},
1209     'extra_sql'         => $extra_sql,
1210     'order_by'          => $orderby,
1211     'count_query'       => $count_query,
1212     'extra_headers'     => \@extra_headers,
1213     'extra_fields'      => \@extra_fields,
1214     'extra_sort_fields' => \@extra_sort_fields,
1215   };
1216   $sql_query;
1217
1218 }
1219
1220 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1221
1222 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1223 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1224 specified.
1225
1226 Additional options are the same as FS::Record::qsearch
1227
1228 =cut
1229
1230 sub fuzzy_search {
1231   my $self = shift;
1232   my $fuzzy = shift;
1233   # sensible defaults, then merge in any passed options
1234   my %fuzopts = (
1235     'table'     => 'cust_main',
1236     'addl_from' => '',
1237     'extra_sql' => '',
1238     'hashref'   => {},
1239     @_
1240   );
1241
1242   my @cust_main = ();
1243
1244   my @fuzzy_mod = 'i';
1245   my $conf = new FS::Conf;
1246   my $fuzziness = $conf->config('fuzzy-fuzziness');
1247   push @fuzzy_mod, $fuzziness if $fuzziness;
1248
1249   check_and_rebuild_fuzzyfiles();
1250   foreach my $field ( keys %$fuzzy ) {
1251
1252     my $all = $self->all_X($field);
1253     next unless scalar(@$all);
1254
1255     my %match = ();
1256     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1257     next if !keys(%match);
1258
1259     my $in_matches = 'IN (' .
1260                      join(',', map { dbh->quote($_) } keys %match) .
1261                      ')';
1262
1263     my $extra_sql = $fuzopts{extra_sql};
1264     if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1265       $extra_sql .= ' AND ';
1266     } else {
1267       $extra_sql .= 'WHERE ';
1268     }
1269     $extra_sql .= "$field $in_matches";
1270
1271     my $addl_from = $fuzopts{addl_from};
1272     if ( $field =~ /^cust_location\./ ) {
1273       $addl_from .= ' JOIN cust_location USING (custnum)';
1274     } elsif ( $field =~ /^contact\./ ) {
1275       $addl_from .= ' JOIN contact USING (custnum)';
1276     }
1277
1278     push @cust_main, qsearch({
1279       %fuzopts,
1280       'addl_from' => $addl_from,
1281       'extra_sql' => $extra_sql,
1282     });
1283   }
1284
1285   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1286   my %saw = ();
1287   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1288
1289   @cust_main;
1290
1291 }
1292
1293 =back
1294
1295 =head1 UTILITY SUBROUTINES
1296
1297 =over 4
1298
1299 =item check_and_rebuild_fuzzyfiles
1300
1301 =cut
1302
1303 sub check_and_rebuild_fuzzyfiles {
1304   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1305   rebuild_fuzzyfiles()
1306     if grep { ! -e "$dir/$_" }
1307          map {
1308                my ($field, $table) = reverse split('\.', $_);
1309                $table ||= 'cust_main';
1310                "$table.$field"
1311              }
1312            @fuzzyfields;
1313 }
1314
1315 =item rebuild_fuzzyfiles
1316
1317 =cut
1318
1319 sub rebuild_fuzzyfiles {
1320
1321   use Fcntl qw(:flock);
1322
1323   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1324   mkdir $dir, 0700 unless -d $dir;
1325
1326   foreach my $fuzzy ( @fuzzyfields ) {
1327
1328     my ($field, $table) = reverse split('\.', $fuzzy);
1329     $table ||= 'cust_main';
1330
1331     open(LOCK,">>$dir/$table.$field")
1332       or die "can't open $dir/$table.$field: $!";
1333     flock(LOCK,LOCK_EX)
1334       or die "can't lock $dir/$table.$field: $!";
1335
1336     open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1337       or die "can't open $dir/$table.$field.tmp: $!";
1338
1339     my $sth = dbh->prepare(
1340       "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1341     );
1342     $sth->execute or die $sth->errstr;
1343
1344     while ( my $row = $sth->fetchrow_arrayref ) {
1345       print CACHE $row->[0]. "\n";
1346     }
1347
1348     close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1349   
1350     rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1351     close LOCK;
1352   }
1353
1354 }
1355
1356 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1357
1358 =cut
1359
1360 sub append_fuzzyfiles {
1361   #my( $first, $last, $company ) = @_;
1362
1363   check_and_rebuild_fuzzyfiles();
1364
1365   #foreach my $fuzzy (@fuzzyfields) {
1366   foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company', 
1367                       'cust_location.address1',
1368                       'cust_main.ship_company',
1369                     ) {
1370
1371     append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1372
1373   }
1374
1375   1;
1376 }
1377
1378 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1379
1380 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1381
1382 =cut
1383
1384 use Fcntl qw(:flock);
1385 sub append_fuzzyfiles_fuzzyfield {
1386   my( $fuzzyfield, $value ) = @_;
1387
1388   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1389
1390
1391   my ($field, $table) = reverse split('\.', $fuzzyfield);
1392   $table ||= 'cust_main';
1393
1394   return unless defined($value) && length($value);
1395
1396   open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1397     or die "can't open $dir/$table.$field: $!";
1398   flock(CACHE,LOCK_EX)
1399     or die "can't lock $dir/$table.$field: $!";
1400
1401   print CACHE "$value\n";
1402
1403   flock(CACHE,LOCK_UN)
1404     or die "can't unlock $dir/$table.$field: $!";
1405   close CACHE;
1406
1407 }
1408
1409 =item all_X
1410
1411 =cut
1412
1413 sub all_X {
1414   my( $self, $fuzzy ) = @_;
1415   my ($field, $table) = reverse split('\.', $fuzzy);
1416   $table ||= 'cust_main';
1417
1418   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1419   open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1420     or die "can't open $dir/$table.$field: $!";
1421   my @array = map { chomp; $_; } <CACHE>;
1422   close CACHE;
1423   \@array;
1424 }
1425
1426 =head1 BUGS
1427
1428 Bed bugs
1429
1430 =head1 SEE ALSO
1431
1432 L<FS::cust_main>, L<FS::Record>
1433
1434 =cut
1435
1436 1;