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