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