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