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