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