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