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