RT# 73422 Changes to report Customer Contacts
[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       'table'   => 'cust_main',
100       'hashref' => { %options },
101       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
102                      ' ( '.
103                          join(' OR ', map "$_ = '$phonen'",
104                                           qw( daytime night mobile fax )
105                              ).
106                           " OR phonenum = '$phonenum' ".
107                      ' ) '.
108                      " AND $agentnums_sql", #agent virtualization
109       'addl_from' => ' left join cust_contact using (custnum) left join contact_phone using (contactnum) ',
110     } );
111
112     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
113       #try looking for matches with extensions unless one was specified
114
115       push @cust_main, qsearch( {
116         'table'   => 'cust_main',
117         'hashref' => { %options },
118         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
119                        ' ( '.
120                            join(' OR ', map "$_ LIKE '$phonen\%'",
121                                             qw( daytime night )
122                                ).
123                        ' ) '.
124                        " AND $agentnums_sql", #agent virtualization
125       } );
126
127     }
128
129   } 
130   
131   
132   if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
133
134     push @cust_main, qsearch( {
135       'table'   => 'cust_main',
136       'hashref' => { %options },
137       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
138                      ' ( '.
139                          join(' OR ', map "$_ = '$search'",
140                                           qw( dest emailaddress )
141                              ).
142                      ' ) '.
143                      " AND $agentnums_sql", #agent virtualization
144       'addl_from' => ' left join cust_main_invoice using (custnum) left join cust_contact using (custnum) left join contact_email using (contactnum) ',
145     } );
146
147   # custnum search (also try agent_custid), with some tweaking options if your
148   # legacy cust "numbers" have letters
149   } elsif (    $search =~ /^\s*(\d+)\s*$/
150             or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
151                  && $search =~ /^\s*(\w\w?\d+)\s*$/
152                )
153             or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
154                  && $search =~ /^\s*(\d+-\w)\s*$/
155                )
156             or ( $conf->config('cust_main-custnum-display_special')
157                  # it's not currently possible for special prefixes to contain
158                  # digits, so just strip off any alphabetic prefix and match 
159                  # the rest to custnum
160                  && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
161                )
162             or ( $conf->exists('address1-search' )
163                  && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
164                )
165           )
166   {
167
168     my $num = $1;
169
170     if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
171       my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
172                                 ? ' AND agent_custid IS NULL ' : '';
173       push @cust_main, qsearch( {
174         'table'     => 'cust_main',
175         'hashref'   => { 'custnum' => $num, %options },
176         'extra_sql' => " AND $agentnums_sql $agent_custid_null",
177       } );
178     }
179
180     # for all agents this user can see, if any of them have custnum prefixes 
181     # that match the search string, include customers that match the rest 
182     # of the custnum and belong to that agent
183     foreach my $agentnum ( keys %$agentnums_href ) {
184       my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
185       next if !$p;
186       if ( $p eq substr($num, 0, length($p)) ) {
187         push @cust_main, qsearch( {
188           'table'   => 'cust_main',
189           'hashref' => { 'custnum' => 0 + substr($num, length($p)),
190                          'agentnum' => $agentnum,
191                           %options,
192                        },
193         } );
194       }
195     }
196
197     push @cust_main, qsearch( {
198         'table'     => 'cust_main',
199         'hashref'   => { 'agent_custid' => $num, %options },
200         'extra_sql' => " AND $agentnums_sql", #agent virtualization
201     } );
202
203     if ( $conf->exists('address1-search') ) {
204       my $len = length($num);
205       $num = lc($num);
206       # probably the Right Thing: return customers that have any associated
207       # locations matching the string, not just bill/ship location
208       push @cust_main, qsearch( {
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           table     => 'cust_main',
379           addl_from => 'JOIN cust_location USING (custnum)',
380           extra_sql => 'WHERE '.
381                         ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
382                         " AND $agentnums_sql", #agent virtualizaiton
383         } );
384
385       }
386
387       #contact substring
388
389       foreach my $hashref ( @hashrefs ) {
390
391         push @cust_main,
392           grep $agentnums_href->{$_->agentnum}, #agent virt
393             grep $_, #skip contacts that don't have cust_main records
394               map $_->cust_main,
395                 qsearch({
396                           'table'     => 'contact',
397                           'hashref'   => { %$hashref,
398                                            #%options,
399                                          },
400                           #'extra_sql' => " AND $agentnums_sql", #agent virt
401                        });
402
403       }
404
405       #fuzzy
406       my %fuzopts = (
407         'hashref'   => \%options,
408         'select'    => '',
409         'extra_sql' => "WHERE $agentnums_sql",    #agent virtualization
410       );
411
412       if ( $first && $last ) {
413         push @cust_main, FS::cust_main::Search->fuzzy_search(
414           { 'last'   => $last,    #fuzzy hashref
415             'first'  => $first }, #
416           %fuzopts
417         );
418         push @cust_main, FS::cust_main::Search->fuzzy_search(
419           { 'contact.last'   => $last,    #fuzzy hashref
420             'contact.first'  => $first }, #
421           %fuzopts
422         );
423       }
424
425       foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
426         push @cust_main, FS::cust_main::Search->fuzzy_search(
427           { $field => $value },
428           %fuzopts
429         );
430       }
431       foreach my $field ( 'first', 'last' ) {
432         push @cust_main, FS::cust_main::Search->fuzzy_search(
433           { "contact.$field" => $value },
434           %fuzopts
435         );
436       }
437       if ( $conf->exists('address1-search') ) {
438         push @cust_main,
439           FS::cust_main::Search->fuzzy_search(
440             { 'cust_location.address1' => $value },
441             %fuzopts
442         );
443       }
444
445     }
446
447   }
448
449   ( my $nospace_search = $search ) =~ s/\s//g;
450   ( my $card_search = $nospace_search ) =~ s/\-//g;
451   $card_search =~ s/[x\*\.\_]/x/gi;
452   
453   if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
454
455     ( my $like_search = $card_search ) =~ s/x/_/g;
456     my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
457
458     push @cust_main, qsearch({
459       'table'     => 'cust_main',
460       'addl_from' => ' JOIN cust_payby USING (custnum)',
461       'hashref'   => {},
462       'extra_sql' => " WHERE (    cust_payby.payinfo LIKE '$like_search'
463                                OR cust_payby.paymask =    '$mask_search'
464                              ) ".
465                      " AND cust_payby.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       map { $_->cust_contact }
514       map { $_->contact }
515           qsearch( {
516                      'table'     => 'contact_email',
517                      'hashref'   => { 'emailaddress' => $email },
518                    }
519                  );
520
521     push @cust_main,
522       map  $_->cust_main,
523       grep $_,
524       map  $_->cust_svc->cust_pkg,
525           qsearch( {
526                      'table'     => 'svc_acct',
527                      'hashref'   => { 'username' => $user, },
528                      'extra_sql' =>
529                        'AND ( SELECT domain FROM svc_domain
530                                 WHERE svc_acct.domsvc = svc_domain.svcnum
531                             ) = '. dbh->quote($domain),
532                    }
533                  );
534   }
535
536   my %saw = ();
537   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
538
539   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
540     if $DEBUG;
541
542   @cust_main;
543
544 }
545
546 =back
547
548 =head1 CLASS METHODS
549
550 =over 4
551
552 =item search HASHREF
553
554 (Class method)
555
556 Returns a qsearch hash expression to search for parameters specified in
557 HASHREF.  Valid parameters are
558
559 =over 4
560
561 =item agentnum
562
563 =item status
564
565 =item address
566
567 =item zip
568
569 =item refnum
570
571 =item cancelled_pkgs
572
573 bool
574
575 =item signupdate
576
577 listref of start date, end date
578
579 =item birthdate
580
581 listref of start date, end date
582
583 =item spouse_birthdate
584
585 listref of start date, end date
586
587 =item anniversary_date
588
589 listref of start date, end date
590
591 =item current_balance
592
593 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
594
595 =item cust_fields
596
597 =item flattened_pkgs
598
599 bool
600
601 =back
602
603 =cut
604
605 sub search {
606   my ($class, $params) = @_;
607
608   my $dbh = dbh;
609
610   my @where = ();
611   my $orderby;
612
613   # initialize these to prevent warnings
614   $params = {
615     'custnum'       => '',
616     'agentnum'      => '',
617     'usernum'       => '',
618     'status'        => '',
619     'address'       => '',
620     'zip'           => '',
621     'invoice_terms' => '',
622     'custbatch'     => '',
623     %$params
624   };
625
626   ##
627   # explicit custnum(s)
628   ##
629
630   if ( $params->{'custnum'} ) {
631     my @custnums = ref($params->{'custnum'}) ? 
632                       @{ $params->{'custnum'} } : 
633                       $params->{'custnum'};
634     push @where, 
635       'cust_main.custnum IN (' . 
636       join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
637       ')' if scalar(@custnums) > 0;
638   }
639
640   ##
641   # parse agent
642   ##
643
644   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
645     push @where,
646       "cust_main.agentnum = $1";
647   }
648
649   ##
650   # parse sales person
651   ##
652
653   if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
654     push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
655                            : 'cust_main.salesnum IS NULL';
656   }
657
658   ##
659   # parse usernum
660   ##
661
662   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
663     push @where,
664       "cust_main.usernum = $1";
665   }
666
667   ##
668   # parse status
669   ##
670
671   #prospect ordered active inactive suspended cancelled
672   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
673     my $method = $params->{'status'}. '_sql';
674     #push @where, $class->$method();
675     push @where, FS::cust_main->$method();
676   }
677
678   my $current = '';
679   unless ( $params->{location_history} ) {
680     $current = '
681       AND (    cust_location.locationnum IN ( cust_main.bill_locationnum,
682                                               cust_main.ship_locationnum
683                                             )
684             OR cust_location.locationnum IN (
685                  SELECT locationnum FROM cust_pkg
686                   WHERE cust_pkg.custnum = cust_main.custnum
687                     AND locationnum IS NOT NULL
688                     AND '. FS::cust_pkg->ncancelled_recurring_sql.'
689                )
690           )';
691   }
692
693   ##
694   # address
695   ##
696   if ( $params->{'address'} ) {
697     # allow this to be an arrayref
698     my @values = ($params->{'address'});
699     @values = @{$values[0]} if ref($values[0]);
700     my @orwhere;
701     foreach (grep /\S/, @values) {
702       my $address = dbh->quote('%'. lc($_). '%');
703       push @orwhere,
704         "LOWER(cust_location.address1) LIKE $address",
705         "LOWER(cust_location.address2) LIKE $address";
706     }
707     if (@orwhere) {
708       push @where, "EXISTS(
709         SELECT 1 FROM cust_location 
710         WHERE cust_location.custnum = cust_main.custnum
711           AND (".join(' OR ',@orwhere).")
712           $current
713         )";
714     }
715   }
716
717   ##
718   # city
719   ##
720   if ( $params->{'city'} =~ /\S/ ) {
721     my $city = dbh->quote($params->{'city'});
722     push @where, "EXISTS(
723       SELECT 1 FROM cust_location
724       WHERE cust_location.custnum = cust_main.custnum
725         AND cust_location.city = $city
726         $current
727     )";
728   }
729
730   ##
731   # county
732   ##
733   if ( $params->{'county'} =~ /\S/ ) {
734     my $county = dbh->quote($params->{'county'});
735     push @where, "EXISTS(
736       SELECT 1 FROM cust_location
737       WHERE cust_location.custnum = cust_main.custnum
738         AND cust_location.county = $county
739         $current
740     )";
741   }
742
743   ##
744   # state
745   ##
746   if ( $params->{'state'} =~ /\S/ ) {
747     my $state = dbh->quote($params->{'state'});
748     push @where, "EXISTS(
749       SELECT 1 FROM cust_location
750       WHERE cust_location.custnum = cust_main.custnum
751         AND cust_location.state = $state
752         $current
753     )";
754   }
755
756   ##
757   # zipcode
758   ##
759   if ( $params->{'zip'} =~ /\S/ ) {
760     my $zip = dbh->quote($params->{'zip'} . '%');
761     push @where, "EXISTS(
762       SELECT 1 FROM cust_location
763       WHERE cust_location.custnum = cust_main.custnum
764         AND cust_location.zip LIKE $zip
765         $current
766     )";
767   }
768
769   ##
770   # country
771   ##
772   if ( $params->{'country'} =~ /^(\w\w)$/ ) {
773     my $country = uc($1);
774     push @where, "EXISTS(
775       SELECT 1 FROM cust_location
776       WHERE cust_location.custnum = cust_main.custnum
777         AND cust_location.country = '$country'
778         $current
779     )";
780   }
781
782   ###
783   # refnum
784   ###
785   if ( $params->{'refnum'}  ) {
786
787     my @refnum = ref( $params->{'refnum'} )
788                    ? @{ $params->{'refnum'} }
789                    :  ( $params->{'refnum'} );
790
791     @refnum = grep /^(\d*)$/, @refnum;
792
793     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
794       if @refnum;
795
796   }
797
798   ##
799   # parse cancelled package checkbox
800   ##
801
802   my $pkgwhere = "";
803
804   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
805     unless $params->{'cancelled_pkgs'};
806
807   ##
808   # "with email address(es)" checkbox,
809   #    also optionally: with_email_dest and with_contact_type
810   ##
811
812   if ($params->{with_email}) {
813     my @email_dest;
814     my $email_dest_sql;
815     my $contact_type_sql;
816
817     if ($params->{with_email_dest}) {
818       croak unless ref $params->{with_email_dest} eq 'ARRAY';
819
820       @email_dest = @{$params->{with_email_dest}};
821       $email_dest_sql =
822         " AND ( ".
823         join(' OR ',map(" cust_contact.${_}_dest IS NOT NULL ", @email_dest)).
824         " ) ";
825         # Can't use message_dist = 'Y' because single quotes are escaped later
826     }
827     if ($params->{with_contact_type}) {
828       croak unless ref $params->{with_contact_type} eq 'ARRAY';
829
830       my @contact_type = grep {/^\d+$/ && $_ > 0} @{$params->{with_contact_type}};
831       my $has_null_type = 0;
832       $has_null_type = 1 if grep { $_ eq 0 } @{$params->{with_contact_type}};
833       my $hnt_sql;
834       if ($has_null_type) {
835         $hnt_sql  = ' OR ' if @contact_type;
836         $hnt_sql .= ' cust_contact.classnum IS NULL ';
837       }
838
839       $contact_type_sql =
840         " AND ( ".
841         join(' OR ', map(" cust_contact.classnum = $_ ", @contact_type)).
842         $hnt_sql.
843         " ) ";
844     }
845     push @where,
846       "EXISTS ( SELECT 1 FROM contact_email
847                 JOIN cust_contact USING (contactnum)
848                 WHERE cust_contact.custnum = cust_main.custnum
849                 $email_dest_sql
850                 $contact_type_sql
851               ) ";
852   }
853
854   ##
855   # "with postal mail invoices" checkbox
856   ##
857
858   push @where, "cust_main.postal_invoice = 'Y'"
859     if $params->{'POST'};
860
861   ##
862   # "without postal mail invoices" checkbox
863   ##
864
865   push @where, "cust_main.postal_invoice IS NULL"
866     if $params->{'no_POST'};
867
868   ##
869   # "tax exempt" checkbox
870   ##
871   push @where, "cust_main.tax = 'Y'"
872     if $params->{'tax'};
873
874   ##
875   # "not tax exempt" checkbox
876   ##
877   push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
878     if $params->{'no_tax'};
879
880   ##
881   # with referrals
882   ##
883   if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
884
885     my $n = $1;
886   
887     # referral status
888     my $and_status = '';
889     if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
890       my $method = $params->{referral_status}. '_sql';
891       $and_status = ' AND '. FS::cust_main->$method();
892       $and_status =~ s/ cust_main\./ referred_cust_main./g;
893     }
894
895     push @where,
896       " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
897                   WHERE cust_main.custnum = referred_cust_main.referral_custnum
898                     $and_status
899               )";
900
901   }
902
903   ##
904   # dates
905   ##
906
907   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
908
909     next unless exists($params->{$field});
910
911     my($beginning, $ending, $hour) = @{$params->{$field}};
912
913     push @where,
914       "cust_main.$field IS NOT NULL",
915       "cust_main.$field >= $beginning",
916       "cust_main.$field <= $ending";
917
918     if($field eq 'signupdate' && defined $hour) {
919       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
920         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
921       }
922       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
923         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
924       }
925       else {
926         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
927       }
928     }
929
930     $orderby ||= "ORDER BY cust_main.$field";
931
932   }
933
934   ###
935   # classnum
936   ###
937
938   if ( $params->{'classnum'} ) {
939
940     my @classnum = ref( $params->{'classnum'} )
941                      ? @{ $params->{'classnum'} }
942                      :  ( $params->{'classnum'} );
943
944     @classnum = grep /^(\d*)$/, @classnum;
945
946     if ( @classnum ) {
947       push @where, '( '. join(' OR ', map {
948                                             $_ ? "cust_main.classnum = $_"
949                                                : "cust_main.classnum IS NULL"
950                                           }
951                                           @classnum
952                              ).
953                    ' )';
954     }
955
956   }
957
958   ###
959   # invoice terms
960   ###
961
962   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
963     my $terms = $1;
964     if ( $1 eq 'NULL' ) {
965       push @where,
966         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
967     } else {
968       push @where,
969         "cust_main.invoice_terms IS NOT NULL",
970         "cust_main.invoice_terms = '$1'";
971     }
972   }
973
974   ##
975   # amounts
976   ##
977
978   if ( $params->{'current_balance'} ) {
979
980     #my $balance_sql = $class->balance_sql();
981     my $balance_sql = FS::cust_main->balance_sql();
982
983     my @current_balance =
984       ref( $params->{'current_balance'} )
985       ? @{ $params->{'current_balance'} }
986       :  ( $params->{'current_balance'} );
987
988     push @where, map { s/current_balance/$balance_sql/; $_ }
989                      @current_balance;
990
991   }
992
993   ##
994   # custbatch
995   ##
996
997   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
998     push @where,
999       "cust_main.custbatch = '$1'";
1000   }
1001   
1002   if ( $params->{'tagnum'} ) {
1003     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1004
1005     @tagnums = grep /^(\d+)$/, @tagnums;
1006
1007     if ( @tagnums ) {
1008       if ( $params->{'all_tags'} ) {
1009         foreach ( @tagnums ) {
1010           push @where, 'exists(select 1 from cust_tag where '.
1011                        'cust_tag.custnum = cust_main.custnum and tagnum = '.
1012                        $_ . ')';
1013         }
1014       } else { # matching any tag, not all
1015         my $tags_where = "0 < (select count(1) from cust_tag where " 
1016                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1017                 . join(',', @tagnums) . "))";
1018
1019         push @where, $tags_where;
1020       }
1021     }
1022   }
1023
1024   # pkg_classnum
1025   #   all_pkg_classnums
1026   #   any_pkg_status
1027   if ( $params->{'pkg_classnum'} ) {
1028     my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1029                           @{ $params->{'pkg_classnum'} } :
1030                              $params->{'pkg_classnum'};
1031     @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1032
1033     if ( @pkg_classnums ) {
1034
1035       my @pkg_where;
1036       if ( $params->{'all_pkg_classnums'} ) {
1037         push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1038       } else {
1039         push @pkg_where,
1040           'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1041       }
1042       foreach (@pkg_where) {
1043         my $select_pkg = 
1044           "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1045           "cust_pkg.custnum = cust_main.custnum AND $_ ";
1046         if ( not $params->{'any_pkg_status'} ) {
1047           $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1048         }
1049         push @where, "EXISTS($select_pkg)";
1050       }
1051     }
1052   }
1053
1054   ##
1055   # setup queries, subs, etc. for the search
1056   ##
1057
1058   $orderby ||= 'ORDER BY custnum';
1059
1060   # here is the agent virtualization
1061   push @where,
1062     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1063
1064   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1065
1066   my $addl_from = '';
1067   # always make address fields available in results
1068   for my $pre ('bill_', 'ship_') {
1069     $addl_from .= 
1070       'LEFT JOIN cust_location AS '.$pre.'location '.
1071       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1072   }
1073
1074   # always make referral available in results
1075   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
1076   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1077
1078   my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
1079
1080   my @select = (
1081                  'cust_main.custnum',
1082                  'cust_main.salesnum',
1083                  # there's a good chance that we'll need these
1084                  'cust_main.bill_locationnum',
1085                  'cust_main.ship_locationnum',
1086                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1087                );
1088
1089   my @extra_headers     = ();
1090   my @extra_fields      = ();
1091   my @extra_sort_fields = ();
1092
1093   ## search contacts
1094   if ($params->{'contacts'}) {
1095     my $contact_params = $params->{'contacts'};
1096
1097     $addl_from .=
1098       ' LEFT JOIN cust_contact ON ( cust_main.custnum = cust_contact.custnum ) ';
1099
1100     if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
1101       $addl_from .= ' LEFT JOIN contact ON ( cust_contact.contactnum = contact.contactnum ) ';
1102       my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
1103         unless !$contact_params->{'contacts_firstname'};
1104       my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
1105         unless !$contact_params->{'contacts_lastname'};
1106       $extra_sql .= " AND ( '1' $first_query $last_query )";
1107     }
1108
1109     if ($contact_params->{'contacts_email'}) {
1110       $addl_from .= ' LEFT JOIN contact_email ON ( cust_contact.contactnum = contact_email.contactnum ) ';
1111       $extra_sql .= " AND ( contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "' )";
1112     }
1113
1114     if ($contact_params->{'contacts_homephone'} || $contact_params->{'contacts_workphone'} || $contact_params->{'contacts_mobilephone'}) {
1115       $addl_from .= ' LEFT JOIN contact_phone ON ( cust_contact.contactnum = contact_phone.contactnum ) ';
1116       my $contacts_mobilephone;
1117       foreach my $phone (qw( contacts_homephone contacts_workphone contacts_mobilephone )) {
1118         (my $num = $contact_params->{$phone}) =~ s/\W//g;
1119         if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
1120       }
1121       my $home_query = " AND ( contact_phone.phonetypenum = '2' AND contact_phone.phonenum = '" . $contact_params->{'contacts_homephone'} . "' )"
1122         unless !$contact_params->{'contacts_homephone'};
1123       my $work_query = " AND ( contact_phone.phonetypenum = '1' AND contact_phone.phonenum = '" . $contact_params->{'contacts_workphone'} . "' )"
1124         unless !$contact_params->{'contacts_workphone'};
1125       my $mobile_query = " AND ( contact_phone.phonetypenum = '3' AND contact_phone.phonenum = '" . $contact_params->{'contacts_mobilephone'} . "' )"
1126         unless !$contact_params->{'contacts_mobilephone'};
1127       $extra_sql .= " AND ( '1' $home_query $work_query $mobile_query )";
1128     }
1129
1130   }
1131
1132   if ($params->{'flattened_pkgs'}) {
1133
1134     #my $pkg_join = '';
1135     $addl_from .=
1136       ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1137
1138     if ($dbh->{Driver}->{Name} eq 'Pg') {
1139
1140       push @select, "
1141         ARRAY_TO_STRING(
1142           ARRAY(
1143             SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1144               WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1145           ), '|'
1146         ) AS magic
1147       ";
1148
1149     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1150       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1151       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1152       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1153     } else {
1154       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
1155            "omitting package information from report.";
1156     }
1157
1158     my $header_query = "
1159       SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1160         FROM cust_main $addl_from $extra_sql $pkgwhere
1161           GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1162     ";
1163
1164     my $sth = dbh->prepare($header_query) or die dbh->errstr;
1165     $sth->execute() or die $sth->errstr;
1166     my $headerrow = $sth->fetchrow_arrayref;
1167     my $headercount = $headerrow ? $headerrow->[0] : 0;
1168     while($headercount) {
1169       unshift @extra_headers, "Package ". $headercount;
1170       unshift @extra_fields, eval q!sub {my $c = shift;
1171                                          my @a = split '\|', $c->magic;
1172                                          my $p = $a[!.--$headercount. q!];
1173                                          $p;
1174                                         };!;
1175       unshift @extra_sort_fields, '';
1176     }
1177
1178   }
1179
1180   if ( $params->{'with_referrals'} ) {
1181
1182     #XXX next: num for each customer status
1183      
1184     push @select,
1185       '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1186            WHERE cust_main.custnum = referred_cust_main.referral_custnum
1187        ) AS num_referrals';
1188
1189     unshift @extra_headers, 'Referrals';
1190     unshift @extra_fields, 'num_referrals';
1191     unshift @extra_sort_fields, 'num_referrals';
1192
1193   }
1194
1195   my $select = join(', ', @select);
1196
1197   my $sql_query = {
1198     'table'             => 'cust_main',
1199     'select'            => $select,
1200     'addl_from'         => $addl_from,
1201     'hashref'           => {},
1202     'extra_sql'         => $extra_sql,
1203     'order_by'          => $orderby,
1204     'count_query'       => $count_query,
1205     'extra_headers'     => \@extra_headers,
1206     'extra_fields'      => \@extra_fields,
1207     'extra_sort_fields' => \@extra_sort_fields,
1208   };
1209   $sql_query;
1210
1211 }
1212
1213 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1214
1215 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1216 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1217 specified.
1218
1219 Additional options are the same as FS::Record::qsearch
1220
1221 =cut
1222
1223 sub fuzzy_search {
1224   my $self = shift;
1225   my $fuzzy = shift;
1226   # sensible defaults, then merge in any passed options
1227   my %fuzopts = (
1228     'table'     => 'cust_main',
1229     'addl_from' => '',
1230     'extra_sql' => '',
1231     'hashref'   => {},
1232     @_
1233   );
1234
1235   my @cust_main = ();
1236
1237   my @fuzzy_mod = 'i';
1238   my $conf = new FS::Conf;
1239   my $fuzziness = $conf->config('fuzzy-fuzziness');
1240   push @fuzzy_mod, $fuzziness if $fuzziness;
1241
1242   check_and_rebuild_fuzzyfiles();
1243   foreach my $field ( keys %$fuzzy ) {
1244
1245     my $all = $self->all_X($field);
1246     next unless scalar(@$all);
1247
1248     my %match = ();
1249     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1250     next if !keys(%match);
1251
1252     my $in_matches = 'IN (' .
1253                      join(',', map { dbh->quote($_) } keys %match) .
1254                      ')';
1255
1256     my $extra_sql = $fuzopts{extra_sql};
1257     if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1258       $extra_sql .= ' AND ';
1259     } else {
1260       $extra_sql .= 'WHERE ';
1261     }
1262     $extra_sql .= "$field $in_matches";
1263
1264     my $addl_from = $fuzopts{addl_from};
1265     if ( $field =~ /^cust_location\./ ) {
1266       $addl_from .= ' JOIN cust_location USING (custnum)';
1267     } elsif ( $field =~ /^contact\./ ) {
1268       $addl_from .= ' JOIN contact USING (custnum)';
1269     }
1270
1271     push @cust_main, qsearch({
1272       %fuzopts,
1273       'addl_from' => $addl_from,
1274       'extra_sql' => $extra_sql,
1275     });
1276   }
1277
1278   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1279   my %saw = ();
1280   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1281
1282   @cust_main;
1283
1284 }
1285
1286 =back
1287
1288 =head1 UTILITY SUBROUTINES
1289
1290 =over 4
1291
1292 =item check_and_rebuild_fuzzyfiles
1293
1294 =cut
1295
1296 sub check_and_rebuild_fuzzyfiles {
1297   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1298   rebuild_fuzzyfiles()
1299     if grep { ! -e "$dir/$_" }
1300          map {
1301                my ($field, $table) = reverse split('\.', $_);
1302                $table ||= 'cust_main';
1303                "$table.$field"
1304              }
1305            @fuzzyfields;
1306 }
1307
1308 =item rebuild_fuzzyfiles
1309
1310 =cut
1311
1312 sub rebuild_fuzzyfiles {
1313
1314   use Fcntl qw(:flock);
1315
1316   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1317   mkdir $dir, 0700 unless -d $dir;
1318
1319   foreach my $fuzzy ( @fuzzyfields ) {
1320
1321     my ($field, $table) = reverse split('\.', $fuzzy);
1322     $table ||= 'cust_main';
1323
1324     open(LOCK,">>$dir/$table.$field")
1325       or die "can't open $dir/$table.$field: $!";
1326     flock(LOCK,LOCK_EX)
1327       or die "can't lock $dir/$table.$field: $!";
1328
1329     open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1330       or die "can't open $dir/$table.$field.tmp: $!";
1331
1332     my $sth = dbh->prepare(
1333       "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1334     );
1335     $sth->execute or die $sth->errstr;
1336
1337     while ( my $row = $sth->fetchrow_arrayref ) {
1338       print CACHE $row->[0]. "\n";
1339     }
1340
1341     close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1342   
1343     rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1344     close LOCK;
1345   }
1346
1347 }
1348
1349 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1350
1351 =cut
1352
1353 sub append_fuzzyfiles {
1354   #my( $first, $last, $company ) = @_;
1355
1356   check_and_rebuild_fuzzyfiles();
1357
1358   #foreach my $fuzzy (@fuzzyfields) {
1359   foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company', 
1360                       'cust_location.address1',
1361                       'cust_main.ship_company',
1362                     ) {
1363
1364     append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1365
1366   }
1367
1368   1;
1369 }
1370
1371 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1372
1373 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1374
1375 =cut
1376
1377 use Fcntl qw(:flock);
1378 sub append_fuzzyfiles_fuzzyfield {
1379   my( $fuzzyfield, $value ) = @_;
1380
1381   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1382
1383
1384   my ($field, $table) = reverse split('\.', $fuzzyfield);
1385   $table ||= 'cust_main';
1386
1387   return unless defined($value) && length($value);
1388
1389   open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1390     or die "can't open $dir/$table.$field: $!";
1391   flock(CACHE,LOCK_EX)
1392     or die "can't lock $dir/$table.$field: $!";
1393
1394   print CACHE "$value\n";
1395
1396   flock(CACHE,LOCK_UN)
1397     or die "can't unlock $dir/$table.$field: $!";
1398   close CACHE;
1399
1400 }
1401
1402 =item all_X
1403
1404 =cut
1405
1406 sub all_X {
1407   my( $self, $fuzzy ) = @_;
1408   my ($field, $table) = reverse split('\.', $fuzzy);
1409   $table ||= 'cust_main';
1410
1411   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1412   open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1413     or die "can't open $dir/$table.$field: $!";
1414   my @array = map { chomp; $_; } <CACHE>;
1415   close CACHE;
1416   \@array;
1417 }
1418
1419 =head1 BUGS
1420
1421 Bed bugs
1422
1423 =head1 SEE ALSO
1424
1425 L<FS::cust_main>, L<FS::Record>
1426
1427 =cut
1428
1429 1;