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