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