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