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