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