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