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