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